httplib.h 60 KB

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