httplib.h 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2017 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef _CPPHTTPLIB_HTTPLIB_H_
  8. #define _CPPHTTPLIB_HTTPLIB_H_
  9. #ifdef _WIN32
  10. #ifndef _CRT_SECURE_NO_WARNINGS
  11. #define _CRT_SECURE_NO_WARNINGS
  12. #endif
  13. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  14. #define _CRT_NONSTDC_NO_DEPRECATE
  15. #endif
  16. #if defined(_MSC_VER) && _MSC_VER < 1900
  17. #define snprintf _snprintf_s
  18. #endif
  19. #ifndef S_ISREG
  20. #define S_ISREG(m) (((m)&S_IFREG)==S_IFREG)
  21. #endif
  22. #ifndef S_ISDIR
  23. #define S_ISDIR(m) (((m)&S_IFDIR)==S_IFDIR)
  24. #endif
  25. #include <io.h>
  26. #include <winsock2.h>
  27. #include <ws2tcpip.h>
  28. #undef min
  29. #undef max
  30. #ifndef strcasecmp
  31. #define strcasecmp _stricmp
  32. #endif
  33. typedef SOCKET socket_t;
  34. #else
  35. #include <pthread.h>
  36. #include <unistd.h>
  37. #include <netdb.h>
  38. #include <cstring>
  39. #include <netinet/in.h>
  40. #include <arpa/inet.h>
  41. #include <signal.h>
  42. #include <sys/socket.h>
  43. #include <sys/select.h>
  44. typedef int socket_t;
  45. #define INVALID_SOCKET (-1)
  46. #endif
  47. #include <fstream>
  48. #include <functional>
  49. #include <map>
  50. #include <memory>
  51. #include <mutex>
  52. #include <regex>
  53. #include <string>
  54. #include <thread>
  55. #include <sys/stat.h>
  56. #include <fcntl.h>
  57. #include <assert.h>
  58. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  59. #include <openssl/ssl.h>
  60. #endif
  61. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  62. #include <zlib.h>
  63. #endif
  64. /*
  65. * Configuration
  66. */
  67. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  68. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND 0
  69. namespace httplib
  70. {
  71. namespace detail {
  72. struct ci {
  73. bool operator() (const std::string & s1, const std::string & s2) const {
  74. return std::lexicographical_compare(
  75. s1.begin(), s1.end(),
  76. s2.begin(), s2.end(),
  77. [](char c1, char c2) {
  78. return ::tolower(c1) < ::tolower(c2);
  79. });
  80. }
  81. };
  82. } // namespace detail
  83. enum class HttpVersion { v1_0 = 0, v1_1 };
  84. typedef std::multimap<std::string, std::string, detail::ci> Headers;
  85. template<typename uint64_t, typename... Args>
  86. std::pair<std::string, std::string> make_range_header(uint64_t value, Args... args);
  87. typedef std::multimap<std::string, std::string> Params;
  88. typedef std::smatch Match;
  89. typedef std::function<void (uint64_t current, uint64_t total)> Progress;
  90. struct MultipartFile {
  91. std::string filename;
  92. std::string content_type;
  93. size_t offset = 0;
  94. size_t length = 0;
  95. };
  96. typedef std::multimap<std::string, MultipartFile> MultipartFiles;
  97. struct Request {
  98. std::string version;
  99. std::string method;
  100. std::string target;
  101. std::string path;
  102. Headers headers;
  103. std::string body;
  104. Params params;
  105. MultipartFiles files;
  106. Match matches;
  107. Progress progress;
  108. bool has_header(const char* key) const;
  109. std::string get_header_value(const char* key) const;
  110. void set_header(const char* key, const char* val);
  111. bool has_param(const char* key) const;
  112. std::string get_param_value(const char* key) const;
  113. bool has_file(const char* key) const;
  114. MultipartFile get_file_value(const char* key) const;
  115. };
  116. struct Response {
  117. std::string version;
  118. int status;
  119. Headers headers;
  120. std::string body;
  121. std::function<std::string (uint64_t offset)> streamcb;
  122. bool has_header(const char* key) const;
  123. std::string get_header_value(const char* key) const;
  124. void set_header(const char* key, const char* val);
  125. void set_redirect(const char* uri);
  126. void set_content(const char* s, size_t n, const char* content_type);
  127. void set_content(const std::string& s, const char* content_type);
  128. Response() : status(-1) {}
  129. };
  130. class Stream {
  131. public:
  132. virtual ~Stream() {}
  133. virtual int read(char* ptr, size_t size) = 0;
  134. virtual int write(const char* ptr, size_t size1) = 0;
  135. virtual int write(const char* ptr) = 0;
  136. virtual std::string get_remote_addr() = 0;
  137. template <typename ...Args>
  138. void write_format(const char* fmt, const Args& ...args);
  139. };
  140. class SocketStream : public Stream {
  141. public:
  142. SocketStream(socket_t sock);
  143. virtual ~SocketStream();
  144. virtual int read(char* ptr, size_t size);
  145. virtual int write(const char* ptr, size_t size);
  146. virtual int write(const char* ptr);
  147. virtual std::string get_remote_addr();
  148. private:
  149. socket_t sock_;
  150. };
  151. class Server {
  152. public:
  153. typedef std::function<void (const Request&, Response&)> Handler;
  154. typedef std::function<void (const Request&, const Response&)> Logger;
  155. Server();
  156. virtual ~Server();
  157. virtual bool is_valid() const;
  158. Server& Get(const char* pattern, Handler handler);
  159. Server& Post(const char* pattern, Handler handler);
  160. Server& Put(const char* pattern, Handler handler);
  161. Server& Delete(const char* pattern, Handler handler);
  162. Server& Options(const char* pattern, Handler handler);
  163. bool set_base_dir(const char* path);
  164. void set_error_handler(Handler handler);
  165. void set_logger(Logger logger);
  166. void set_keep_alive_max_count(size_t count);
  167. int bind_to_any_port(const char* host, int socket_flags = 0);
  168. bool listen_after_bind();
  169. bool listen(const char* host, int port, int socket_flags = 0);
  170. bool is_running() const;
  171. void stop();
  172. protected:
  173. bool process_request(Stream& strm, bool last_connection, bool& connection_close);
  174. size_t keep_alive_max_count_;
  175. private:
  176. typedef std::vector<std::pair<std::regex, Handler>> Handlers;
  177. socket_t create_server_socket(const char* host, int port, int socket_flags) const;
  178. int bind_internal(const char* host, int port, int socket_flags);
  179. bool listen_internal();
  180. bool routing(Request& req, Response& res);
  181. bool handle_file_request(Request& req, Response& res);
  182. bool dispatch_request(Request& req, Response& res, Handlers& handlers);
  183. bool parse_request_line(const char* s, Request& req);
  184. void write_response(Stream& strm, bool last_connection, const Request& req, Response& res);
  185. virtual bool read_and_close_socket(socket_t sock);
  186. bool is_running_;
  187. socket_t svr_sock_;
  188. std::string base_dir_;
  189. Handlers get_handlers_;
  190. Handlers post_handlers_;
  191. Handlers put_handlers_;
  192. Handlers delete_handlers_;
  193. Handlers options_handlers_;
  194. Handler error_handler_;
  195. Logger logger_;
  196. // TODO: Use thread pool...
  197. std::mutex running_threads_mutex_;
  198. int running_threads_;
  199. };
  200. class Client {
  201. public:
  202. Client(
  203. const char* host,
  204. int port = 80,
  205. size_t timeout_sec = 300);
  206. virtual ~Client();
  207. virtual bool is_valid() const;
  208. std::shared_ptr<Response> Get(const char* path, Progress progress = nullptr);
  209. std::shared_ptr<Response> Get(const char* path, const Headers& headers, Progress progress = nullptr);
  210. std::shared_ptr<Response> Head(const char* path);
  211. std::shared_ptr<Response> Head(const char* path, const Headers& headers);
  212. std::shared_ptr<Response> Post(const char* path, const std::string& body, const char* content_type);
  213. std::shared_ptr<Response> Post(const char* path, const Headers& headers, const std::string& body, const char* content_type);
  214. std::shared_ptr<Response> Post(const char* path, const Params& params);
  215. std::shared_ptr<Response> Post(const char* path, const Headers& headers, const Params& params);
  216. std::shared_ptr<Response> Put(const char* path, const std::string& body, const char* content_type);
  217. std::shared_ptr<Response> Put(const char* path, const Headers& headers, const std::string& body, const char* content_type);
  218. std::shared_ptr<Response> Delete(const char* path);
  219. std::shared_ptr<Response> Delete(const char* path, const Headers& headers);
  220. std::shared_ptr<Response> Options(const char* path);
  221. std::shared_ptr<Response> Options(const char* path, const Headers& headers);
  222. bool send(Request& req, Response& res);
  223. protected:
  224. bool process_request(Stream& strm, Request& req, Response& res, bool& connection_close);
  225. const std::string host_;
  226. const int port_;
  227. size_t timeout_sec_;
  228. const std::string host_and_port_;
  229. private:
  230. socket_t create_client_socket() const;
  231. bool read_response_line(Stream& strm, Response& res);
  232. void write_request(Stream& strm, Request& req);
  233. virtual bool read_and_close_socket(socket_t sock, Request& req, Response& res);
  234. };
  235. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  236. class SSLSocketStream : public Stream {
  237. public:
  238. SSLSocketStream(socket_t sock, SSL* ssl);
  239. virtual ~SSLSocketStream();
  240. virtual int read(char* ptr, size_t size);
  241. virtual int write(const char* ptr, size_t size);
  242. virtual int write(const char* ptr);
  243. virtual std::string get_remote_addr();
  244. private:
  245. socket_t sock_;
  246. SSL* ssl_;
  247. };
  248. class SSLServer : public Server {
  249. public:
  250. SSLServer(
  251. const char* cert_path, const char* private_key_path);
  252. virtual ~SSLServer();
  253. virtual bool is_valid() const;
  254. private:
  255. virtual bool read_and_close_socket(socket_t sock);
  256. SSL_CTX* ctx_;
  257. std::mutex ctx_mutex_;
  258. };
  259. class SSLClient : public Client {
  260. public:
  261. SSLClient(
  262. const char* host,
  263. int port = 80,
  264. size_t timeout_sec = 300);
  265. virtual ~SSLClient();
  266. virtual bool is_valid() const;
  267. private:
  268. virtual bool read_and_close_socket(socket_t sock, Request& req, Response& res);
  269. SSL_CTX* ctx_;
  270. std::mutex ctx_mutex_;
  271. };
  272. #endif
  273. /*
  274. * Implementation
  275. */
  276. namespace detail {
  277. template <class Fn>
  278. void split(const char* b, const char* e, char d, Fn fn)
  279. {
  280. int i = 0;
  281. int beg = 0;
  282. while (e ? (b + i != e) : (b[i] != '\0')) {
  283. if (b[i] == d) {
  284. fn(&b[beg], &b[i]);
  285. beg = i + 1;
  286. }
  287. i++;
  288. }
  289. if (i) {
  290. fn(&b[beg], &b[i]);
  291. }
  292. }
  293. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  294. // to store data. The call can set memory on stack for performance.
  295. class stream_line_reader {
  296. public:
  297. stream_line_reader(Stream& strm, char* fixed_buffer, size_t fixed_buffer_size)
  298. : strm_(strm)
  299. , fixed_buffer_(fixed_buffer)
  300. , fixed_buffer_size_(fixed_buffer_size) {
  301. }
  302. const char* ptr() const {
  303. if (glowable_buffer_.empty()) {
  304. return fixed_buffer_;
  305. } else {
  306. return glowable_buffer_.data();
  307. }
  308. }
  309. bool getline() {
  310. fixed_buffer_used_size_ = 0;
  311. glowable_buffer_.clear();
  312. for (size_t i = 0; ; i++) {
  313. char byte;
  314. auto n = strm_.read(&byte, 1);
  315. if (n < 0) {
  316. return false;
  317. } else if (n == 0) {
  318. if (i == 0) {
  319. return false;
  320. } else {
  321. break;
  322. }
  323. }
  324. append(byte);
  325. if (byte == '\n') {
  326. break;
  327. }
  328. }
  329. return true;
  330. }
  331. private:
  332. void append(char c) {
  333. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  334. fixed_buffer_[fixed_buffer_used_size_++] = c;
  335. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  336. } else {
  337. if (glowable_buffer_.empty()) {
  338. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  339. glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  340. }
  341. glowable_buffer_ += c;
  342. }
  343. }
  344. Stream& strm_;
  345. char* fixed_buffer_;
  346. const size_t fixed_buffer_size_;
  347. size_t fixed_buffer_used_size_;
  348. std::string glowable_buffer_;
  349. };
  350. inline int close_socket(socket_t sock)
  351. {
  352. #ifdef _WIN32
  353. return closesocket(sock);
  354. #else
  355. return close(sock);
  356. #endif
  357. }
  358. inline int select_read(socket_t sock, size_t sec, size_t usec)
  359. {
  360. fd_set fds;
  361. FD_ZERO(&fds);
  362. FD_SET(sock, &fds);
  363. timeval tv;
  364. tv.tv_sec = sec;
  365. tv.tv_usec = usec;
  366. return select(sock + 1, &fds, NULL, NULL, &tv);
  367. }
  368. inline bool wait_until_socket_is_ready(socket_t sock, size_t sec, size_t usec)
  369. {
  370. fd_set fdsr;
  371. FD_ZERO(&fdsr);
  372. FD_SET(sock, &fdsr);
  373. auto fdsw = fdsr;
  374. auto fdse = fdsr;
  375. timeval tv;
  376. tv.tv_sec = sec;
  377. tv.tv_usec = usec;
  378. if (select(sock + 1, &fdsr, &fdsw, &fdse, &tv) < 0) {
  379. return false;
  380. } else if (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw)) {
  381. int error = 0;
  382. socklen_t len = sizeof(error);
  383. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (char*)&error, &len) < 0 || error) {
  384. return false;
  385. }
  386. } else {
  387. return false;
  388. }
  389. return true;
  390. }
  391. template <typename T>
  392. inline bool read_and_close_socket(socket_t sock, size_t keep_alive_max_count, T callback)
  393. {
  394. bool ret = false;
  395. if (keep_alive_max_count > 0) {
  396. auto count = keep_alive_max_count;
  397. while (count > 0 &&
  398. detail::select_read(sock,
  399. CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  400. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0) {
  401. SocketStream strm(sock);
  402. auto last_connection = count == 1;
  403. auto connection_close = false;
  404. ret = callback(strm, last_connection, connection_close);
  405. if (!ret || connection_close) {
  406. break;
  407. }
  408. count--;
  409. }
  410. } else {
  411. SocketStream strm(sock);
  412. auto dummy_connection_close = false;
  413. ret = callback(strm, true, dummy_connection_close);
  414. }
  415. close_socket(sock);
  416. return ret;
  417. }
  418. inline int shutdown_socket(socket_t sock)
  419. {
  420. #ifdef _WIN32
  421. return shutdown(sock, SD_BOTH);
  422. #else
  423. return shutdown(sock, SHUT_RDWR);
  424. #endif
  425. }
  426. template <typename Fn>
  427. socket_t create_socket(const char* host, int port, Fn fn, int socket_flags = 0)
  428. {
  429. #ifdef _WIN32
  430. #define SO_SYNCHRONOUS_NONALERT 0x20
  431. #define SO_OPENTYPE 0x7008
  432. int opt = SO_SYNCHRONOUS_NONALERT;
  433. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
  434. #endif
  435. // Get address info
  436. struct addrinfo hints;
  437. struct addrinfo *result;
  438. memset(&hints, 0, sizeof(struct addrinfo));
  439. hints.ai_family = AF_UNSPEC;
  440. hints.ai_socktype = SOCK_STREAM;
  441. hints.ai_flags = socket_flags;
  442. hints.ai_protocol = 0;
  443. auto service = std::to_string(port);
  444. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  445. return INVALID_SOCKET;
  446. }
  447. for (auto rp = result; rp; rp = rp->ai_next) {
  448. // Create a socket
  449. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  450. if (sock == INVALID_SOCKET) {
  451. continue;
  452. }
  453. // Make 'reuse address' option available
  454. int yes = 1;
  455. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
  456. // bind or connect
  457. if (fn(sock, *rp)) {
  458. freeaddrinfo(result);
  459. return sock;
  460. }
  461. close_socket(sock);
  462. }
  463. freeaddrinfo(result);
  464. return INVALID_SOCKET;
  465. }
  466. inline void set_nonblocking(socket_t sock, bool nonblocking)
  467. {
  468. #ifdef _WIN32
  469. auto flags = nonblocking ? 1UL : 0UL;
  470. ioctlsocket(sock, FIONBIO, &flags);
  471. #else
  472. auto flags = fcntl(sock, F_GETFL, 0);
  473. fcntl(sock, F_SETFL, nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  474. #endif
  475. }
  476. inline bool is_connection_error()
  477. {
  478. #ifdef _WIN32
  479. return WSAGetLastError() != WSAEWOULDBLOCK;
  480. #else
  481. return errno != EINPROGRESS;
  482. #endif
  483. }
  484. inline std::string get_remote_addr(socket_t sock) {
  485. struct sockaddr_storage addr;
  486. socklen_t len = sizeof(addr);
  487. if (!getpeername(sock, (struct sockaddr*)&addr, &len)) {
  488. char ipstr[NI_MAXHOST];
  489. if (!getnameinfo((struct sockaddr*)&addr, len,
  490. ipstr, sizeof(ipstr), nullptr, 0, NI_NUMERICHOST)) {
  491. return ipstr;
  492. }
  493. }
  494. return std::string();
  495. }
  496. inline bool is_file(const std::string& path)
  497. {
  498. struct stat st;
  499. return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  500. }
  501. inline bool is_dir(const std::string& path)
  502. {
  503. struct stat st;
  504. return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  505. }
  506. inline bool is_valid_path(const std::string& path) {
  507. size_t level = 0;
  508. size_t i = 0;
  509. // Skip slash
  510. while (i < path.size() && path[i] == '/') {
  511. i++;
  512. }
  513. while (i < path.size()) {
  514. // Read component
  515. auto beg = i;
  516. while (i < path.size() && path[i] != '/') {
  517. i++;
  518. }
  519. auto len = i - beg;
  520. assert(len > 0);
  521. if (!path.compare(beg, len, ".")) {
  522. ;
  523. } else if (!path.compare(beg, len, "..")) {
  524. if (level == 0) {
  525. return false;
  526. }
  527. level--;
  528. } else {
  529. level++;
  530. }
  531. // Skip slash
  532. while (i < path.size() && path[i] == '/') {
  533. i++;
  534. }
  535. }
  536. return true;
  537. }
  538. inline void read_file(const std::string& path, std::string& out)
  539. {
  540. std::ifstream fs(path, std::ios_base::binary);
  541. fs.seekg(0, std::ios_base::end);
  542. auto size = fs.tellg();
  543. fs.seekg(0);
  544. out.resize(static_cast<size_t>(size));
  545. fs.read(&out[0], size);
  546. }
  547. inline std::string file_extension(const std::string& path)
  548. {
  549. std::smatch m;
  550. auto pat = std::regex("\\.([a-zA-Z0-9]+)$");
  551. if (std::regex_search(path, m, pat)) {
  552. return m[1].str();
  553. }
  554. return std::string();
  555. }
  556. inline const char* find_content_type(const std::string& path)
  557. {
  558. auto ext = file_extension(path);
  559. if (ext == "txt") {
  560. return "text/plain";
  561. } else if (ext == "html") {
  562. return "text/html";
  563. } else if (ext == "css") {
  564. return "text/css";
  565. } else if (ext == "jpeg" || ext == "jpg") {
  566. return "image/jpg";
  567. } else if (ext == "png") {
  568. return "image/png";
  569. } else if (ext == "gif") {
  570. return "image/gif";
  571. } else if (ext == "svg") {
  572. return "image/svg+xml";
  573. } else if (ext == "ico") {
  574. return "image/x-icon";
  575. } else if (ext == "json") {
  576. return "application/json";
  577. } else if (ext == "pdf") {
  578. return "application/pdf";
  579. } else if (ext == "js") {
  580. return "application/javascript";
  581. } else if (ext == "xml") {
  582. return "application/xml";
  583. } else if (ext == "xhtml") {
  584. return "application/xhtml+xml";
  585. }
  586. return nullptr;
  587. }
  588. inline const char* status_message(int status)
  589. {
  590. switch (status) {
  591. case 200: return "OK";
  592. case 301: return "Moved Permanently";
  593. case 302: return "Found";
  594. case 303: return "See Other";
  595. case 304: return "Not Modified";
  596. case 400: return "Bad Request";
  597. case 403: return "Forbidden";
  598. case 404: return "Not Found";
  599. case 415: return "Unsupported Media Type";
  600. default:
  601. case 500: return "Internal Server Error";
  602. }
  603. }
  604. inline const char* get_header_value(const Headers& headers, const char* key, const char* def)
  605. {
  606. auto it = headers.find(key);
  607. if (it != headers.end()) {
  608. return it->second.c_str();
  609. }
  610. return def;
  611. }
  612. inline int get_header_value_int(const Headers& headers, const char* key, int def)
  613. {
  614. auto it = headers.find(key);
  615. if (it != headers.end()) {
  616. return std::stoi(it->second);
  617. }
  618. return def;
  619. }
  620. inline bool read_headers(Stream& strm, Headers& headers)
  621. {
  622. static std::regex re(R"((.+?):\s*(.+?)\s*\r\n)");
  623. const auto bufsiz = 2048;
  624. char buf[bufsiz];
  625. stream_line_reader reader(strm, buf, bufsiz);
  626. for (;;) {
  627. if (!reader.getline()) {
  628. return false;
  629. }
  630. if (!strcmp(reader.ptr(), "\r\n")) {
  631. break;
  632. }
  633. std::cmatch m;
  634. if (std::regex_match(reader.ptr(), m, re)) {
  635. auto key = std::string(m[1]);
  636. auto val = std::string(m[2]);
  637. headers.emplace(key, val);
  638. }
  639. }
  640. return true;
  641. }
  642. inline bool read_content_with_length(Stream& strm, std::string& out, size_t len, Progress progress)
  643. {
  644. out.assign(len, 0);
  645. size_t r = 0;
  646. while (r < len){
  647. auto n = strm.read(&out[r], len - r);
  648. if (n <= 0) {
  649. return false;
  650. }
  651. r += n;
  652. if (progress) {
  653. progress(r, len);
  654. }
  655. }
  656. return true;
  657. }
  658. inline bool read_content_without_length(Stream& strm, std::string& out)
  659. {
  660. for (;;) {
  661. char byte;
  662. auto n = strm.read(&byte, 1);
  663. if (n < 0) {
  664. return false;
  665. } else if (n == 0) {
  666. return true;
  667. }
  668. out += byte;
  669. }
  670. return true;
  671. }
  672. inline bool read_content_chunked(Stream& strm, std::string& out)
  673. {
  674. const auto bufsiz = 16;
  675. char buf[bufsiz];
  676. stream_line_reader reader(strm, buf, bufsiz);
  677. if (!reader.getline()) {
  678. return false;
  679. }
  680. auto chunk_len = std::stoi(reader.ptr(), 0, 16);
  681. while (chunk_len > 0){
  682. std::string chunk;
  683. if (!read_content_with_length(strm, chunk, chunk_len, nullptr)) {
  684. return false;
  685. }
  686. if (!reader.getline()) {
  687. return false;
  688. }
  689. if (strcmp(reader.ptr(), "\r\n")) {
  690. break;
  691. }
  692. out += chunk;
  693. if (!reader.getline()) {
  694. return false;
  695. }
  696. chunk_len = std::stoi(reader.ptr(), 0, 16);
  697. }
  698. if (chunk_len == 0) {
  699. // Reader terminator after chunks
  700. if (!reader.getline() || strcmp(reader.ptr(), "\r\n"))
  701. return false;
  702. }
  703. return true;
  704. }
  705. template <typename T>
  706. bool read_content(Stream& strm, T& x, Progress progress = Progress())
  707. {
  708. auto len = get_header_value_int(x.headers, "Content-Length", 0);
  709. if (len) {
  710. return read_content_with_length(strm, x.body, len, progress);
  711. } else {
  712. const auto& encoding = get_header_value(x.headers, "Transfer-Encoding", "");
  713. if (!strcasecmp(encoding, "chunked")) {
  714. return read_content_chunked(strm, x.body);
  715. } else {
  716. return read_content_without_length(strm, x.body);
  717. }
  718. }
  719. return true;
  720. }
  721. template <typename T>
  722. inline void write_headers(Stream& strm, const T& info)
  723. {
  724. for (const auto& x: info.headers) {
  725. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  726. }
  727. strm.write("\r\n");
  728. }
  729. inline std::string encode_url(const std::string& s)
  730. {
  731. std::string result;
  732. for (auto i = 0; s[i]; i++) {
  733. switch (s[i]) {
  734. case ' ': result += "+"; break;
  735. case '\'': result += "%27"; break;
  736. case ',': result += "%2C"; break;
  737. case ':': result += "%3A"; break;
  738. case ';': result += "%3B"; break;
  739. default:
  740. if (s[i] < 0) {
  741. result += '%';
  742. char hex[4];
  743. size_t len = snprintf(hex, sizeof(hex) - 1, "%02X", (unsigned char)s[i]);
  744. assert(len == 2);
  745. result.append(hex, len);
  746. } else {
  747. result += s[i];
  748. }
  749. break;
  750. }
  751. }
  752. return result;
  753. }
  754. inline bool is_hex(char c, int& v)
  755. {
  756. if (0x20 <= c && isdigit(c)) {
  757. v = c - '0';
  758. return true;
  759. } else if ('A' <= c && c <= 'F') {
  760. v = c - 'A' + 10;
  761. return true;
  762. } else if ('a' <= c && c <= 'f') {
  763. v = c - 'a' + 10;
  764. return true;
  765. }
  766. return false;
  767. }
  768. inline bool from_hex_to_i(const std::string& s, size_t i, size_t cnt, int& val)
  769. {
  770. if (i >= s.size()) {
  771. return false;
  772. }
  773. val = 0;
  774. for (; cnt; i++, cnt--) {
  775. if (!s[i]) {
  776. return false;
  777. }
  778. int v = 0;
  779. if (is_hex(s[i], v)) {
  780. val = val * 16 + v;
  781. } else {
  782. return false;
  783. }
  784. }
  785. return true;
  786. }
  787. inline std::string from_i_to_hex(uint64_t n)
  788. {
  789. const char *charset = "0123456789abcdef";
  790. std::string ret;
  791. do {
  792. ret = charset[n & 15] + ret;
  793. n >>= 4;
  794. } while (n > 0);
  795. return ret;
  796. }
  797. inline size_t to_utf8(int code, char* buff)
  798. {
  799. if (code < 0x0080) {
  800. buff[0] = (code & 0x7F);
  801. return 1;
  802. } else if (code < 0x0800) {
  803. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  804. buff[1] = (0x80 | (code & 0x3F));
  805. return 2;
  806. } else if (code < 0xD800) {
  807. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  808. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  809. buff[2] = (0x80 | (code & 0x3F));
  810. return 3;
  811. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  812. return 0;
  813. } else if (code < 0x10000) {
  814. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  815. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  816. buff[2] = (0x80 | (code & 0x3F));
  817. return 3;
  818. } else if (code < 0x110000) {
  819. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  820. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  821. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  822. buff[3] = (0x80 | (code & 0x3F));
  823. return 4;
  824. }
  825. // NOTREACHED
  826. return 0;
  827. }
  828. inline std::string decode_url(const std::string& s)
  829. {
  830. std::string result;
  831. for (size_t i = 0; i < s.size(); i++) {
  832. if (s[i] == '%' && i + 1 < s.size()) {
  833. if (s[i + 1] == 'u') {
  834. int val = 0;
  835. if (from_hex_to_i(s, i + 2, 4, val)) {
  836. // 4 digits Unicode codes
  837. char buff[4];
  838. size_t len = to_utf8(val, buff);
  839. if (len > 0) {
  840. result.append(buff, len);
  841. }
  842. i += 5; // 'u0000'
  843. } else {
  844. result += s[i];
  845. }
  846. } else {
  847. int val = 0;
  848. if (from_hex_to_i(s, i + 1, 2, val)) {
  849. // 2 digits hex codes
  850. result += val;
  851. i += 2; // '00'
  852. } else {
  853. result += s[i];
  854. }
  855. }
  856. } else if (s[i] == '+') {
  857. result += ' ';
  858. } else {
  859. result += s[i];
  860. }
  861. }
  862. return result;
  863. }
  864. inline void parse_query_text(const std::string& s, Params& params)
  865. {
  866. split(&s[0], &s[s.size()], '&', [&](const char* b, const char* e) {
  867. std::string key;
  868. std::string val;
  869. split(b, e, '=', [&](const char* b, const char* e) {
  870. if (key.empty()) {
  871. key.assign(b, e);
  872. } else {
  873. val.assign(b, e);
  874. }
  875. });
  876. params.emplace(key, decode_url(val));
  877. });
  878. }
  879. inline bool parse_multipart_boundary(const std::string& content_type, std::string& boundary)
  880. {
  881. auto pos = content_type.find("boundary=");
  882. if (pos == std::string::npos) {
  883. return false;
  884. }
  885. boundary = content_type.substr(pos + 9);
  886. return true;
  887. }
  888. inline bool parse_multipart_formdata(
  889. const std::string& boundary, const std::string& body, MultipartFiles& files)
  890. {
  891. static std::string dash = "--";
  892. static std::string crlf = "\r\n";
  893. static std::regex re_content_type(
  894. "Content-Type: (.*?)", std::regex_constants::icase);
  895. static std::regex re_content_disposition(
  896. "Content-Disposition: form-data; name=\"(.*?)\"(?:; filename=\"(.*?)\")?",
  897. std::regex_constants::icase);
  898. auto dash_boundary = dash + boundary;
  899. auto pos = body.find(dash_boundary);
  900. if (pos != 0) {
  901. return false;
  902. }
  903. pos += dash_boundary.size();
  904. auto next_pos = body.find(crlf, pos);
  905. if (next_pos == std::string::npos) {
  906. return false;
  907. }
  908. pos = next_pos + crlf.size();
  909. while (pos < body.size()) {
  910. next_pos = body.find(crlf, pos);
  911. if (next_pos == std::string::npos) {
  912. return false;
  913. }
  914. std::string name;
  915. MultipartFile file;
  916. auto header = body.substr(pos, (next_pos - pos));
  917. while (pos != next_pos) {
  918. std::smatch m;
  919. if (std::regex_match(header, m, re_content_type)) {
  920. file.content_type = m[1];
  921. } else if (std::regex_match(header, m, re_content_disposition)) {
  922. name = m[1];
  923. file.filename = m[2];
  924. }
  925. pos = next_pos + crlf.size();
  926. next_pos = body.find(crlf, pos);
  927. if (next_pos == std::string::npos) {
  928. return false;
  929. }
  930. header = body.substr(pos, (next_pos - pos));
  931. }
  932. pos = next_pos + crlf.size();
  933. next_pos = body.find(crlf + dash_boundary, pos);
  934. if (next_pos == std::string::npos) {
  935. return false;
  936. }
  937. file.offset = pos;
  938. file.length = next_pos - pos;
  939. pos = next_pos + crlf.size() + dash_boundary.size();
  940. next_pos = body.find(crlf, pos);
  941. if (next_pos == std::string::npos) {
  942. return false;
  943. }
  944. files.emplace(name, file);
  945. pos = next_pos + crlf.size();
  946. }
  947. return true;
  948. }
  949. inline std::string to_lower(const char* beg, const char* end)
  950. {
  951. std::string out;
  952. auto it = beg;
  953. while (it != end) {
  954. out += ::tolower(*it);
  955. it++;
  956. }
  957. return out;
  958. }
  959. inline void make_range_header_core(std::string&) {}
  960. template<typename uint64_t>
  961. inline void make_range_header_core(std::string& field, uint64_t value)
  962. {
  963. if (!field.empty()) {
  964. field += ", ";
  965. }
  966. field += std::to_string(value) + "-";
  967. }
  968. template<typename uint64_t, typename... Args>
  969. inline void make_range_header_core(std::string& field, uint64_t value1, uint64_t value2, Args... args)
  970. {
  971. if (!field.empty()) {
  972. field += ", ";
  973. }
  974. field += std::to_string(value1) + "-" + std::to_string(value2);
  975. make_range_header_core(field, args...);
  976. }
  977. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  978. inline bool can_compress(const std::string& content_type) {
  979. return !content_type.find("text/") ||
  980. content_type == "image/svg+xml" ||
  981. content_type == "application/javascript" ||
  982. content_type == "application/json" ||
  983. content_type == "application/xml" ||
  984. content_type == "application/xhtml+xml";
  985. }
  986. inline void compress(std::string& content)
  987. {
  988. z_stream strm;
  989. strm.zalloc = Z_NULL;
  990. strm.zfree = Z_NULL;
  991. strm.opaque = Z_NULL;
  992. auto ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY);
  993. if (ret != Z_OK) {
  994. return;
  995. }
  996. strm.avail_in = content.size();
  997. strm.next_in = (Bytef *)content.data();
  998. std::string compressed;
  999. const auto bufsiz = 16384;
  1000. char buff[bufsiz];
  1001. do {
  1002. strm.avail_out = bufsiz;
  1003. strm.next_out = (Bytef *)buff;
  1004. deflate(&strm, Z_FINISH);
  1005. compressed.append(buff, bufsiz - strm.avail_out);
  1006. } while (strm.avail_out == 0);
  1007. content.swap(compressed);
  1008. deflateEnd(&strm);
  1009. }
  1010. inline void decompress(std::string& content)
  1011. {
  1012. z_stream strm;
  1013. strm.zalloc = Z_NULL;
  1014. strm.zfree = Z_NULL;
  1015. strm.opaque = Z_NULL;
  1016. // 15 is the value of wbits, which should be at the maximum possible value to ensure
  1017. // that any gzip stream can be decoded. The offset of 16 specifies that the stream
  1018. // to decompress will be formatted with a gzip wrapper.
  1019. auto ret = inflateInit2(&strm, 16 + 15);
  1020. if (ret != Z_OK) {
  1021. return;
  1022. }
  1023. strm.avail_in = content.size();
  1024. strm.next_in = (Bytef *)content.data();
  1025. std::string decompressed;
  1026. const auto bufsiz = 16384;
  1027. char buff[bufsiz];
  1028. do {
  1029. strm.avail_out = bufsiz;
  1030. strm.next_out = (Bytef *)buff;
  1031. inflate(&strm, Z_NO_FLUSH);
  1032. decompressed.append(buff, bufsiz - strm.avail_out);
  1033. } while (strm.avail_out == 0);
  1034. content.swap(decompressed);
  1035. inflateEnd(&strm);
  1036. }
  1037. #endif
  1038. #ifdef _WIN32
  1039. class WSInit {
  1040. public:
  1041. WSInit() {
  1042. WSADATA wsaData;
  1043. WSAStartup(0x0002, &wsaData);
  1044. }
  1045. ~WSInit() {
  1046. WSACleanup();
  1047. }
  1048. };
  1049. static WSInit wsinit_;
  1050. #endif
  1051. } // namespace detail
  1052. // Header utilities
  1053. template<typename uint64_t, typename... Args>
  1054. inline std::pair<std::string, std::string> make_range_header(uint64_t value, Args... args)
  1055. {
  1056. std::string field;
  1057. detail::make_range_header_core(field, value, args...);
  1058. field.insert(0, "bytes=");
  1059. return std::make_pair("Range", field);
  1060. }
  1061. // Request implementation
  1062. inline bool Request::has_header(const char* key) const
  1063. {
  1064. return headers.find(key) != headers.end();
  1065. }
  1066. inline std::string Request::get_header_value(const char* key) const
  1067. {
  1068. return detail::get_header_value(headers, key, "");
  1069. }
  1070. inline void Request::set_header(const char* key, const char* val)
  1071. {
  1072. headers.emplace(key, val);
  1073. }
  1074. inline bool Request::has_param(const char* key) const
  1075. {
  1076. return params.find(key) != params.end();
  1077. }
  1078. inline std::string Request::get_param_value(const char* key) const
  1079. {
  1080. auto it = params.find(key);
  1081. if (it != params.end()) {
  1082. return it->second;
  1083. }
  1084. return std::string();
  1085. }
  1086. inline bool Request::has_file(const char* key) const
  1087. {
  1088. return files.find(key) != files.end();
  1089. }
  1090. inline MultipartFile Request::get_file_value(const char* key) const
  1091. {
  1092. auto it = files.find(key);
  1093. if (it != files.end()) {
  1094. return it->second;
  1095. }
  1096. return MultipartFile();
  1097. }
  1098. // Response implementation
  1099. inline bool Response::has_header(const char* key) const
  1100. {
  1101. return headers.find(key) != headers.end();
  1102. }
  1103. inline std::string Response::get_header_value(const char* key) const
  1104. {
  1105. return detail::get_header_value(headers, key, "");
  1106. }
  1107. inline void Response::set_header(const char* key, const char* val)
  1108. {
  1109. headers.emplace(key, val);
  1110. }
  1111. inline void Response::set_redirect(const char* url)
  1112. {
  1113. set_header("Location", url);
  1114. status = 302;
  1115. }
  1116. inline void Response::set_content(const char* s, size_t n, const char* content_type)
  1117. {
  1118. body.assign(s, n);
  1119. set_header("Content-Type", content_type);
  1120. }
  1121. inline void Response::set_content(const std::string& s, const char* content_type)
  1122. {
  1123. body = s;
  1124. set_header("Content-Type", content_type);
  1125. }
  1126. // Rstream implementation
  1127. template <typename ...Args>
  1128. inline void Stream::write_format(const char* fmt, const Args& ...args)
  1129. {
  1130. const auto bufsiz = 2048;
  1131. char buf[bufsiz];
  1132. #if defined(_MSC_VER) && _MSC_VER < 1900
  1133. auto n = _snprintf_s(buf, bufsiz, bufsiz - 1, fmt, args...);
  1134. #else
  1135. auto n = snprintf(buf, bufsiz - 1, fmt, args...);
  1136. #endif
  1137. if (n > 0) {
  1138. if (n >= bufsiz - 1) {
  1139. std::vector<char> glowable_buf(bufsiz);
  1140. while (n >= static_cast<int>(glowable_buf.size() - 1)) {
  1141. glowable_buf.resize(glowable_buf.size() * 2);
  1142. #if defined(_MSC_VER) && _MSC_VER < 1900
  1143. n = _snprintf_s(&glowable_buf[0], glowable_buf.size(), glowable_buf.size() - 1, fmt, args...);
  1144. #else
  1145. n = snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...);
  1146. #endif
  1147. }
  1148. write(&glowable_buf[0], n);
  1149. } else {
  1150. write(buf, n);
  1151. }
  1152. }
  1153. }
  1154. // Socket stream implementation
  1155. inline SocketStream::SocketStream(socket_t sock): sock_(sock)
  1156. {
  1157. }
  1158. inline SocketStream::~SocketStream()
  1159. {
  1160. }
  1161. inline int SocketStream::read(char* ptr, size_t size)
  1162. {
  1163. return recv(sock_, ptr, size, 0);
  1164. }
  1165. inline int SocketStream::write(const char* ptr, size_t size)
  1166. {
  1167. return send(sock_, ptr, size, 0);
  1168. }
  1169. inline int SocketStream::write(const char* ptr)
  1170. {
  1171. return write(ptr, strlen(ptr));
  1172. }
  1173. inline std::string SocketStream::get_remote_addr() {
  1174. return detail::get_remote_addr(sock_);
  1175. }
  1176. // HTTP server implementation
  1177. inline Server::Server()
  1178. : keep_alive_max_count_(5)
  1179. , is_running_(false)
  1180. , svr_sock_(INVALID_SOCKET)
  1181. , running_threads_(0)
  1182. {
  1183. #ifndef _WIN32
  1184. signal(SIGPIPE, SIG_IGN);
  1185. #endif
  1186. }
  1187. inline Server::~Server()
  1188. {
  1189. }
  1190. inline Server& Server::Get(const char* pattern, Handler handler)
  1191. {
  1192. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1193. return *this;
  1194. }
  1195. inline Server& Server::Post(const char* pattern, Handler handler)
  1196. {
  1197. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1198. return *this;
  1199. }
  1200. inline Server& Server::Put(const char* pattern, Handler handler)
  1201. {
  1202. put_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1203. return *this;
  1204. }
  1205. inline Server& Server::Delete(const char* pattern, Handler handler)
  1206. {
  1207. delete_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1208. return *this;
  1209. }
  1210. inline Server& Server::Options(const char* pattern, Handler handler)
  1211. {
  1212. options_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1213. return *this;
  1214. }
  1215. inline bool Server::set_base_dir(const char* path)
  1216. {
  1217. if (detail::is_dir(path)) {
  1218. base_dir_ = path;
  1219. return true;
  1220. }
  1221. return false;
  1222. }
  1223. inline void Server::set_error_handler(Handler handler)
  1224. {
  1225. error_handler_ = handler;
  1226. }
  1227. inline void Server::set_logger(Logger logger)
  1228. {
  1229. logger_ = logger;
  1230. }
  1231. inline void Server::set_keep_alive_max_count(size_t count)
  1232. {
  1233. keep_alive_max_count_ = count;
  1234. }
  1235. inline int Server::bind_to_any_port(const char* host, int socket_flags)
  1236. {
  1237. return bind_internal(host, 0, socket_flags);
  1238. }
  1239. inline bool Server::listen_after_bind() {
  1240. return listen_internal();
  1241. }
  1242. inline bool Server::listen(const char* host, int port, int socket_flags)
  1243. {
  1244. if (bind_internal(host, port, socket_flags) < 0)
  1245. return false;
  1246. return listen_internal();
  1247. }
  1248. inline bool Server::is_running() const
  1249. {
  1250. return is_running_;
  1251. }
  1252. inline void Server::stop()
  1253. {
  1254. if (is_running_) {
  1255. assert(svr_sock_ != INVALID_SOCKET);
  1256. detail::shutdown_socket(svr_sock_);
  1257. detail::close_socket(svr_sock_);
  1258. svr_sock_ = INVALID_SOCKET;
  1259. }
  1260. }
  1261. inline bool Server::parse_request_line(const char* s, Request& req)
  1262. {
  1263. static std::regex re("(GET|HEAD|POST|PUT|DELETE|OPTIONS) (([^?]+)(?:\\?(.+?))?) (HTTP/1\\.[01])\r\n");
  1264. std::cmatch m;
  1265. if (std::regex_match(s, m, re)) {
  1266. req.version = std::string(m[5]);
  1267. req.method = std::string(m[1]);
  1268. req.target = std::string(m[2]);
  1269. req.path = detail::decode_url(m[3]);
  1270. // Parse query text
  1271. auto len = std::distance(m[4].first, m[4].second);
  1272. if (len > 0) {
  1273. detail::parse_query_text(m[4], req.params);
  1274. }
  1275. return true;
  1276. }
  1277. return false;
  1278. }
  1279. inline void Server::write_response(Stream& strm, bool last_connection, const Request& req, Response& res)
  1280. {
  1281. assert(res.status != -1);
  1282. if (400 <= res.status && error_handler_) {
  1283. error_handler_(req, res);
  1284. }
  1285. // Response line
  1286. strm.write_format("HTTP/1.1 %d %s\r\n",
  1287. res.status,
  1288. detail::status_message(res.status));
  1289. // Headers
  1290. if (last_connection ||
  1291. req.get_header_value("Connection") == "close") {
  1292. res.set_header("Connection", "close");
  1293. }
  1294. if (!last_connection &&
  1295. req.get_header_value("Connection") == "Keep-Alive") {
  1296. res.set_header("Connection", "Keep-Alive");
  1297. }
  1298. if (!res.body.empty()) {
  1299. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1300. // TODO: 'Accpet-Encoding' has gzip, not gzip;q=0
  1301. const auto& encodings = req.get_header_value("Accept-Encoding");
  1302. if (encodings.find("gzip") != std::string::npos &&
  1303. detail::can_compress(res.get_header_value("Content-Type"))) {
  1304. detail::compress(res.body);
  1305. res.set_header("Content-Encoding", "gzip");
  1306. }
  1307. #endif
  1308. if (!res.has_header("Content-Type")) {
  1309. res.set_header("Content-Type", "text/plain");
  1310. }
  1311. auto length = std::to_string(res.body.size());
  1312. res.set_header("Content-Length", length.c_str());
  1313. } else if (res.streamcb) {
  1314. // Streamed response
  1315. bool chunked_response = !res.has_header("Content-Length");
  1316. if (chunked_response)
  1317. res.set_header("Transfer-Encoding", "chunked");
  1318. }
  1319. detail::write_headers(strm, res);
  1320. // Body
  1321. if (req.method != "HEAD") {
  1322. if (!res.body.empty()) {
  1323. strm.write(res.body.c_str(), res.body.size());
  1324. } else if (res.streamcb) {
  1325. bool chunked_response = !res.has_header("Content-Length");
  1326. uint64_t offset = 0;
  1327. bool data_available = true;
  1328. while (data_available) {
  1329. std::string chunk = res.streamcb(offset);
  1330. offset += chunk.size();
  1331. data_available = !chunk.empty();
  1332. // Emit chunked response header and footer for each chunk
  1333. if (chunked_response)
  1334. chunk = detail::from_i_to_hex(chunk.size()) + "\r\n" + chunk + "\r\n";
  1335. if (strm.write(chunk.c_str(), chunk.size()) < 0)
  1336. break; // Stop on error
  1337. }
  1338. }
  1339. }
  1340. // Log
  1341. if (logger_) {
  1342. logger_(req, res);
  1343. }
  1344. }
  1345. inline bool Server::handle_file_request(Request& req, Response& res)
  1346. {
  1347. if (!base_dir_.empty() && detail::is_valid_path(req.path)) {
  1348. std::string path = base_dir_ + req.path;
  1349. if (!path.empty() && path.back() == '/') {
  1350. path += "index.html";
  1351. }
  1352. if (detail::is_file(path)) {
  1353. detail::read_file(path, res.body);
  1354. auto type = detail::find_content_type(path);
  1355. if (type) {
  1356. res.set_header("Content-Type", type);
  1357. }
  1358. res.status = 200;
  1359. return true;
  1360. }
  1361. }
  1362. return false;
  1363. }
  1364. inline socket_t Server::create_server_socket(const char* host, int port, int socket_flags) const
  1365. {
  1366. return detail::create_socket(host, port,
  1367. [](socket_t sock, struct addrinfo& ai) -> bool {
  1368. if (::bind(sock, ai.ai_addr, ai.ai_addrlen)) {
  1369. return false;
  1370. }
  1371. if (::listen(sock, 5)) { // Listen through 5 channels
  1372. return false;
  1373. }
  1374. return true;
  1375. }, socket_flags);
  1376. }
  1377. inline int Server::bind_internal(const char* host, int port, int socket_flags)
  1378. {
  1379. if (!is_valid()) {
  1380. return -1;
  1381. }
  1382. svr_sock_ = create_server_socket(host, port, socket_flags);
  1383. if (svr_sock_ == INVALID_SOCKET) {
  1384. return -1;
  1385. }
  1386. if (port == 0) {
  1387. struct sockaddr_storage address;
  1388. socklen_t len = sizeof(address);
  1389. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&address), &len) == -1) {
  1390. return -1;
  1391. }
  1392. if (address.ss_family == AF_INET) {
  1393. return ntohs(reinterpret_cast<struct sockaddr_in*>(&address)->sin_port);
  1394. } else if (address.ss_family == AF_INET6) {
  1395. return ntohs(reinterpret_cast<struct sockaddr_in6*>(&address)->sin6_port);
  1396. } else {
  1397. return -1;
  1398. }
  1399. } else {
  1400. return port;
  1401. }
  1402. }
  1403. inline bool Server::listen_internal()
  1404. {
  1405. auto ret = true;
  1406. is_running_ = true;
  1407. for (;;) {
  1408. auto val = detail::select_read(svr_sock_, 0, 100000);
  1409. if (val == 0) { // Timeout
  1410. if (svr_sock_ == INVALID_SOCKET) {
  1411. // The server socket was closed by 'stop' method.
  1412. break;
  1413. }
  1414. continue;
  1415. }
  1416. socket_t sock = accept(svr_sock_, NULL, NULL);
  1417. if (sock == INVALID_SOCKET) {
  1418. if (svr_sock_ != INVALID_SOCKET) {
  1419. detail::close_socket(svr_sock_);
  1420. ret = false;
  1421. } else {
  1422. ; // The server socket was closed by user.
  1423. }
  1424. break;
  1425. }
  1426. // TODO: Use thread pool...
  1427. std::thread([=]() {
  1428. {
  1429. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  1430. running_threads_++;
  1431. }
  1432. read_and_close_socket(sock);
  1433. {
  1434. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  1435. running_threads_--;
  1436. }
  1437. }).detach();
  1438. }
  1439. // TODO: Use thread pool...
  1440. for (;;) {
  1441. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1442. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  1443. if (!running_threads_) {
  1444. break;
  1445. }
  1446. }
  1447. is_running_ = false;
  1448. return ret;
  1449. }
  1450. inline bool Server::routing(Request& req, Response& res)
  1451. {
  1452. if (req.method == "GET" && handle_file_request(req, res)) {
  1453. return true;
  1454. }
  1455. if (req.method == "GET" || req.method == "HEAD") {
  1456. return dispatch_request(req, res, get_handlers_);
  1457. } else if (req.method == "POST") {
  1458. return dispatch_request(req, res, post_handlers_);
  1459. } else if (req.method == "PUT") {
  1460. return dispatch_request(req, res, put_handlers_);
  1461. } else if (req.method == "DELETE") {
  1462. return dispatch_request(req, res, delete_handlers_);
  1463. } else if (req.method == "OPTIONS") {
  1464. return dispatch_request(req, res, options_handlers_);
  1465. }
  1466. return false;
  1467. }
  1468. inline bool Server::dispatch_request(Request& req, Response& res, Handlers& handlers)
  1469. {
  1470. for (const auto& x: handlers) {
  1471. const auto& pattern = x.first;
  1472. const auto& handler = x.second;
  1473. if (std::regex_match(req.path, req.matches, pattern)) {
  1474. handler(req, res);
  1475. return true;
  1476. }
  1477. }
  1478. return false;
  1479. }
  1480. inline bool Server::process_request(Stream& strm, bool last_connection, bool& connection_close)
  1481. {
  1482. const auto bufsiz = 2048;
  1483. char buf[bufsiz];
  1484. detail::stream_line_reader reader(strm, buf, bufsiz);
  1485. // Connection has been closed on client
  1486. if (!reader.getline()) {
  1487. return false;
  1488. }
  1489. Request req;
  1490. Response res;
  1491. res.version = "HTTP/1.1";
  1492. // Request line and headers
  1493. if (!parse_request_line(reader.ptr(), req) || !detail::read_headers(strm, req.headers)) {
  1494. res.status = 400;
  1495. write_response(strm, last_connection, req, res);
  1496. return true;
  1497. }
  1498. auto ret = true;
  1499. if (req.get_header_value("Connection") == "close") {
  1500. // ret = false;
  1501. connection_close = true;
  1502. }
  1503. req.set_header("REMOTE_ADDR", strm.get_remote_addr().c_str());
  1504. // Body
  1505. if (req.method == "POST" || req.method == "PUT") {
  1506. if (!detail::read_content(strm, req)) {
  1507. res.status = 400;
  1508. write_response(strm, last_connection, req, res);
  1509. return ret;
  1510. }
  1511. const auto& content_type = req.get_header_value("Content-Type");
  1512. if (req.get_header_value("Content-Encoding") == "gzip") {
  1513. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1514. detail::decompress(req.body);
  1515. #else
  1516. res.status = 415;
  1517. write_response(strm, last_connection, req, res);
  1518. return ret;
  1519. #endif
  1520. }
  1521. if (!content_type.find("application/x-www-form-urlencoded")) {
  1522. detail::parse_query_text(req.body, req.params);
  1523. } else if(!content_type.find("multipart/form-data")) {
  1524. std::string boundary;
  1525. if (!detail::parse_multipart_boundary(content_type, boundary) ||
  1526. !detail::parse_multipart_formdata(boundary, req.body, req.files)) {
  1527. res.status = 400;
  1528. write_response(strm, last_connection, req, res);
  1529. return ret;
  1530. }
  1531. }
  1532. }
  1533. if (routing(req, res)) {
  1534. if (res.status == -1) {
  1535. res.status = 200;
  1536. }
  1537. } else {
  1538. res.status = 404;
  1539. }
  1540. write_response(strm, last_connection, req, res);
  1541. return ret;
  1542. }
  1543. inline bool Server::is_valid() const
  1544. {
  1545. return true;
  1546. }
  1547. inline bool Server::read_and_close_socket(socket_t sock)
  1548. {
  1549. return detail::read_and_close_socket(
  1550. sock,
  1551. keep_alive_max_count_,
  1552. [this](Stream& strm, bool last_connection, bool& connection_close) {
  1553. return process_request(strm, last_connection, connection_close);
  1554. });
  1555. }
  1556. // HTTP client implementation
  1557. inline Client::Client(
  1558. const char* host, int port, size_t timeout_sec)
  1559. : host_(host)
  1560. , port_(port)
  1561. , timeout_sec_(timeout_sec)
  1562. , host_and_port_(host_ + ":" + std::to_string(port_))
  1563. {
  1564. }
  1565. inline Client::~Client()
  1566. {
  1567. }
  1568. inline bool Client::is_valid() const
  1569. {
  1570. return true;
  1571. }
  1572. inline socket_t Client::create_client_socket() const
  1573. {
  1574. return detail::create_socket(host_.c_str(), port_,
  1575. [=](socket_t sock, struct addrinfo& ai) -> bool {
  1576. detail::set_nonblocking(sock, true);
  1577. auto ret = connect(sock, ai.ai_addr, ai.ai_addrlen);
  1578. if (ret < 0) {
  1579. if (detail::is_connection_error() ||
  1580. !detail::wait_until_socket_is_ready(sock, timeout_sec_, 0)) {
  1581. detail::close_socket(sock);
  1582. return false;
  1583. }
  1584. }
  1585. detail::set_nonblocking(sock, false);
  1586. return true;
  1587. });
  1588. }
  1589. inline bool Client::read_response_line(Stream& strm, Response& res)
  1590. {
  1591. const auto bufsiz = 2048;
  1592. char buf[bufsiz];
  1593. detail::stream_line_reader reader(strm, buf, bufsiz);
  1594. if (!reader.getline()) {
  1595. return false;
  1596. }
  1597. const static std::regex re("(HTTP/1\\.[01]) (\\d+?) .+\r\n");
  1598. std::cmatch m;
  1599. if (std::regex_match(reader.ptr(), m, re)) {
  1600. res.version = std::string(m[1]);
  1601. res.status = std::stoi(std::string(m[2]));
  1602. }
  1603. return true;
  1604. }
  1605. inline bool Client::send(Request& req, Response& res)
  1606. {
  1607. if (req.path.empty()) {
  1608. return false;
  1609. }
  1610. auto sock = create_client_socket();
  1611. if (sock == INVALID_SOCKET) {
  1612. return false;
  1613. }
  1614. return read_and_close_socket(sock, req, res);
  1615. }
  1616. inline void Client::write_request(Stream& strm, Request& req)
  1617. {
  1618. auto path = detail::encode_url(req.path);
  1619. // Request line
  1620. strm.write_format("%s %s HTTP/1.1\r\n",
  1621. req.method.c_str(),
  1622. path.c_str());
  1623. // Headers
  1624. req.set_header("Host", host_and_port_.c_str());
  1625. if (!req.has_header("Accept")) {
  1626. req.set_header("Accept", "*/*");
  1627. }
  1628. if (!req.has_header("User-Agent")) {
  1629. req.set_header("User-Agent", "cpp-httplib/0.2");
  1630. }
  1631. // TODO: Support KeepAlive connection
  1632. // if (!req.has_header("Connection")) {
  1633. req.set_header("Connection", "close");
  1634. // }
  1635. if (!req.body.empty()) {
  1636. if (!req.has_header("Content-Type")) {
  1637. req.set_header("Content-Type", "text/plain");
  1638. }
  1639. auto length = std::to_string(req.body.size());
  1640. req.set_header("Content-Length", length.c_str());
  1641. }
  1642. detail::write_headers(strm, req);
  1643. // Body
  1644. if (!req.body.empty()) {
  1645. if (req.get_header_value("Content-Type") == "application/x-www-form-urlencoded") {
  1646. auto str = detail::encode_url(req.body);
  1647. strm.write(str.c_str(), str.size());
  1648. } else {
  1649. strm.write(req.body.c_str(), req.body.size());
  1650. }
  1651. }
  1652. }
  1653. inline bool Client::process_request(Stream& strm, Request& req, Response& res, bool& connection_close)
  1654. {
  1655. // Send request
  1656. write_request(strm, req);
  1657. // Receive response and headers
  1658. if (!read_response_line(strm, res) || !detail::read_headers(strm, res.headers)) {
  1659. return false;
  1660. }
  1661. if (res.get_header_value("Connection") == "close" || res.version == "HTTP/1.0") {
  1662. connection_close = true;
  1663. }
  1664. // Body
  1665. if (req.method != "HEAD") {
  1666. if (!detail::read_content(strm, res, req.progress)) {
  1667. return false;
  1668. }
  1669. if (res.get_header_value("Content-Encoding") == "gzip") {
  1670. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1671. detail::decompress(res.body);
  1672. #else
  1673. return false;
  1674. #endif
  1675. }
  1676. }
  1677. return true;
  1678. }
  1679. inline bool Client::read_and_close_socket(socket_t sock, Request& req, Response& res)
  1680. {
  1681. return detail::read_and_close_socket(
  1682. sock,
  1683. 0,
  1684. [&](Stream& strm, bool /*last_connection*/, bool& connection_close) {
  1685. return process_request(strm, req, res, connection_close);
  1686. });
  1687. }
  1688. inline std::shared_ptr<Response> Client::Get(const char* path, Progress progress)
  1689. {
  1690. return Get(path, Headers(), progress);
  1691. }
  1692. inline std::shared_ptr<Response> Client::Get(const char* path, const Headers& headers, Progress progress)
  1693. {
  1694. Request req;
  1695. req.method = "GET";
  1696. req.path = path;
  1697. req.headers = headers;
  1698. req.progress = progress;
  1699. auto res = std::make_shared<Response>();
  1700. return send(req, *res) ? res : nullptr;
  1701. }
  1702. inline std::shared_ptr<Response> Client::Head(const char* path)
  1703. {
  1704. return Head(path, Headers());
  1705. }
  1706. inline std::shared_ptr<Response> Client::Head(const char* path, const Headers& headers)
  1707. {
  1708. Request req;
  1709. req.method = "HEAD";
  1710. req.headers = headers;
  1711. req.path = path;
  1712. auto res = std::make_shared<Response>();
  1713. return send(req, *res) ? res : nullptr;
  1714. }
  1715. inline std::shared_ptr<Response> Client::Post(
  1716. const char* path, const std::string& body, const char* content_type)
  1717. {
  1718. return Post(path, Headers(), body, content_type);
  1719. }
  1720. inline std::shared_ptr<Response> Client::Post(
  1721. const char* path, const Headers& headers, const std::string& body, const char* content_type)
  1722. {
  1723. Request req;
  1724. req.method = "POST";
  1725. req.headers = headers;
  1726. req.path = path;
  1727. req.headers.emplace("Content-Type", content_type);
  1728. req.body = body;
  1729. auto res = std::make_shared<Response>();
  1730. return send(req, *res) ? res : nullptr;
  1731. }
  1732. inline std::shared_ptr<Response> Client::Post(const char* path, const Params& params)
  1733. {
  1734. return Post(path, Headers(), params);
  1735. }
  1736. inline std::shared_ptr<Response> Client::Post(const char* path, const Headers& headers, const Params& params)
  1737. {
  1738. std::string query;
  1739. for (auto it = params.begin(); it != params.end(); ++it) {
  1740. if (it != params.begin()) {
  1741. query += "&";
  1742. }
  1743. query += it->first;
  1744. query += "=";
  1745. query += it->second;
  1746. }
  1747. return Post(path, headers, query, "application/x-www-form-urlencoded");
  1748. }
  1749. inline std::shared_ptr<Response> Client::Put(
  1750. const char* path, const std::string& body, const char* content_type)
  1751. {
  1752. return Put(path, Headers(), body, content_type);
  1753. }
  1754. inline std::shared_ptr<Response> Client::Put(
  1755. const char* path, const Headers& headers, const std::string& body, const char* content_type)
  1756. {
  1757. Request req;
  1758. req.method = "PUT";
  1759. req.headers = headers;
  1760. req.path = path;
  1761. req.headers.emplace("Content-Type", content_type);
  1762. req.body = body;
  1763. auto res = std::make_shared<Response>();
  1764. return send(req, *res) ? res : nullptr;
  1765. }
  1766. inline std::shared_ptr<Response> Client::Delete(const char* path)
  1767. {
  1768. return Delete(path, Headers());
  1769. }
  1770. inline std::shared_ptr<Response> Client::Delete(const char* path, const Headers& headers)
  1771. {
  1772. Request req;
  1773. req.method = "DELETE";
  1774. req.path = path;
  1775. req.headers = headers;
  1776. auto res = std::make_shared<Response>();
  1777. return send(req, *res) ? res : nullptr;
  1778. }
  1779. inline std::shared_ptr<Response> Client::Options(const char* path)
  1780. {
  1781. return Options(path, Headers());
  1782. }
  1783. inline std::shared_ptr<Response> Client::Options(const char* path, const Headers& headers)
  1784. {
  1785. Request req;
  1786. req.method = "OPTIONS";
  1787. req.path = path;
  1788. req.headers = headers;
  1789. auto res = std::make_shared<Response>();
  1790. return send(req, *res) ? res : nullptr;
  1791. }
  1792. /*
  1793. * SSL Implementation
  1794. */
  1795. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1796. namespace detail {
  1797. template <typename U, typename V, typename T>
  1798. inline bool read_and_close_socket_ssl(
  1799. socket_t sock, size_t keep_alive_max_count,
  1800. // TODO: OpenSSL 1.0.2 occasionally crashes...
  1801. // The upcoming 1.1.0 is going to be thread safe.
  1802. SSL_CTX* ctx, std::mutex& ctx_mutex,
  1803. U SSL_connect_or_accept, V setup,
  1804. T callback)
  1805. {
  1806. SSL* ssl = nullptr;
  1807. {
  1808. std::lock_guard<std::mutex> guard(ctx_mutex);
  1809. ssl = SSL_new(ctx);
  1810. if (!ssl) {
  1811. return false;
  1812. }
  1813. }
  1814. auto bio = BIO_new_socket(sock, BIO_NOCLOSE);
  1815. SSL_set_bio(ssl, bio, bio);
  1816. setup(ssl);
  1817. SSL_connect_or_accept(ssl);
  1818. bool ret = false;
  1819. if (keep_alive_max_count > 0) {
  1820. auto count = keep_alive_max_count;
  1821. while (count > 0 &&
  1822. detail::select_read(sock,
  1823. CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  1824. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0) {
  1825. SSLSocketStream strm(sock, ssl);
  1826. auto last_connection = count == 1;
  1827. auto connection_close = false;
  1828. ret = callback(strm, last_connection, connection_close);
  1829. if (!ret || connection_close) {
  1830. break;
  1831. }
  1832. count--;
  1833. }
  1834. } else {
  1835. SSLSocketStream strm(sock, ssl);
  1836. auto dummy_connection_close = false;
  1837. ret = callback(strm, true, dummy_connection_close);
  1838. }
  1839. SSL_shutdown(ssl);
  1840. {
  1841. std::lock_guard<std::mutex> guard(ctx_mutex);
  1842. SSL_free(ssl);
  1843. }
  1844. close_socket(sock);
  1845. return ret;
  1846. }
  1847. class SSLInit {
  1848. public:
  1849. SSLInit() {
  1850. SSL_load_error_strings();
  1851. SSL_library_init();
  1852. }
  1853. };
  1854. static SSLInit sslinit_;
  1855. } // namespace detail
  1856. // SSL socket stream implementation
  1857. inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL* ssl)
  1858. : sock_(sock), ssl_(ssl)
  1859. {
  1860. }
  1861. inline SSLSocketStream::~SSLSocketStream()
  1862. {
  1863. }
  1864. inline int SSLSocketStream::read(char* ptr, size_t size)
  1865. {
  1866. return SSL_read(ssl_, ptr, size);
  1867. }
  1868. inline int SSLSocketStream::write(const char* ptr, size_t size)
  1869. {
  1870. return SSL_write(ssl_, ptr, size);
  1871. }
  1872. inline int SSLSocketStream::write(const char* ptr)
  1873. {
  1874. return write(ptr, strlen(ptr));
  1875. }
  1876. inline std::string SSLSocketStream::get_remote_addr() {
  1877. return detail::get_remote_addr(sock_);
  1878. }
  1879. // SSL HTTP server implementation
  1880. inline SSLServer::SSLServer(const char* cert_path, const char* private_key_path)
  1881. {
  1882. ctx_ = SSL_CTX_new(SSLv23_server_method());
  1883. if (ctx_) {
  1884. SSL_CTX_set_options(ctx_,
  1885. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  1886. SSL_OP_NO_COMPRESSION |
  1887. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  1888. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  1889. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  1890. // EC_KEY_free(ecdh);
  1891. if (SSL_CTX_use_certificate_file(ctx_, cert_path, SSL_FILETYPE_PEM) != 1 ||
  1892. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != 1) {
  1893. SSL_CTX_free(ctx_);
  1894. ctx_ = nullptr;
  1895. }
  1896. }
  1897. }
  1898. inline SSLServer::~SSLServer()
  1899. {
  1900. if (ctx_) {
  1901. SSL_CTX_free(ctx_);
  1902. }
  1903. }
  1904. inline bool SSLServer::is_valid() const
  1905. {
  1906. return ctx_;
  1907. }
  1908. inline bool SSLServer::read_and_close_socket(socket_t sock)
  1909. {
  1910. return detail::read_and_close_socket_ssl(
  1911. sock,
  1912. keep_alive_max_count_,
  1913. ctx_, ctx_mutex_,
  1914. SSL_accept,
  1915. [](SSL* /*ssl*/) {},
  1916. [this](Stream& strm, bool last_connection, bool& connection_close) {
  1917. return process_request(strm, last_connection, connection_close);
  1918. });
  1919. }
  1920. // SSL HTTP client implementation
  1921. inline SSLClient::SSLClient(const char* host, int port, size_t timeout_sec)
  1922. : Client(host, port, timeout_sec)
  1923. {
  1924. ctx_ = SSL_CTX_new(SSLv23_client_method());
  1925. }
  1926. inline SSLClient::~SSLClient()
  1927. {
  1928. if (ctx_) {
  1929. SSL_CTX_free(ctx_);
  1930. }
  1931. }
  1932. inline bool SSLClient::is_valid() const
  1933. {
  1934. return ctx_;
  1935. }
  1936. inline bool SSLClient::read_and_close_socket(socket_t sock, Request& req, Response& res)
  1937. {
  1938. return is_valid() && detail::read_and_close_socket_ssl(
  1939. sock, 0,
  1940. ctx_, ctx_mutex_,
  1941. SSL_connect,
  1942. [&](SSL* ssl) {
  1943. SSL_set_tlsext_host_name(ssl, host_.c_str());
  1944. },
  1945. [&](Stream& strm, bool /*last_connection*/, bool& connection_close) {
  1946. return process_request(strm, req, res, connection_close);
  1947. });
  1948. }
  1949. #endif
  1950. } // namespace httplib
  1951. #endif
  1952. // vim: et ts=4 sw=4 cin cino={1s ff=unix