httplib.h 59 KB

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