httplib.h 61 KB

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