httplib.h 61 KB

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