httplib.h 63 KB

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