httplib.h 57 KB

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