httplib.h 62 KB

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