2
0

httplib.h 57 KB

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