httplib.h 57 KB

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