httplib.h 57 KB

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