httplib.h 63 KB

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