httplib.h 62 KB

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