httplib.h 63 KB

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