httplib.h 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2017 Yuji Hirose. All rights reserved.
  5. // The Boost Software License 1.0
  6. //
  7. #ifndef _CPPHTTPLIB_HTTPLIB_H_
  8. #define _CPPHTTPLIB_HTTPLIB_H_
  9. #ifdef _MSC_VER
  10. #ifndef _CRT_SECURE_NO_WARNINGS
  11. #define _CRT_SECURE_NO_WARNINGS
  12. #endif //_CRT_SECURE_NO_WARNINGS
  13. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  14. #define _CRT_NONSTDC_NO_DEPRECATE
  15. #endif //_CRT_NONSTDC_NO_DEPRECATE
  16. #ifndef SO_SYNCHRONOUS_NONALERT
  17. #define SO_SYNCHRONOUS_NONALERT 0x20
  18. #endif
  19. #ifndef SO_OPENTYPE
  20. #define SO_OPENTYPE 0x7008
  21. #endif
  22. #if (_MSC_VER < 1900)
  23. #define snprintf _snprintf_s
  24. #endif
  25. #define S_ISREG(m) (((m)&S_IFREG)==S_IFREG)
  26. #define S_ISDIR(m) (((m)&S_IFDIR)==S_IFDIR)
  27. #include <fcntl.h>
  28. #include <io.h>
  29. #include <winsock2.h>
  30. #include <ws2tcpip.h>
  31. #undef min
  32. #undef max
  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. typedef int socket_t;
  44. #endif
  45. #include <fstream>
  46. #include <functional>
  47. #include <map>
  48. #include <memory>
  49. #include <regex>
  50. #include <string>
  51. #include <sys/stat.h>
  52. #include <assert.h>
  53. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  54. #include <openssl/ssl.h>
  55. #endif
  56. namespace httplib
  57. {
  58. enum class HttpVersion { v1_0 = 0, v1_1 };
  59. typedef std::multimap<std::string, std::string> MultiMap;
  60. typedef std::smatch Match;
  61. typedef std::function<void (int64_t current, int64_t total)> Progress;
  62. struct MultipartFile {
  63. std::string filename;
  64. std::string content_type;
  65. size_t offset = 0;
  66. size_t length = 0;
  67. };
  68. typedef std::multimap<std::string, MultipartFile> MultipartFiles;
  69. struct Request {
  70. std::string method;
  71. std::string path;
  72. MultiMap headers;
  73. std::string body;
  74. MultiMap params;
  75. MultipartFiles files;
  76. Match matches;
  77. Progress progress;
  78. bool has_header(const char* key) const;
  79. std::string get_header_value(const char* key) const;
  80. void set_header(const char* key, const char* val);
  81. bool has_param(const char* key) const;
  82. std::string get_param_value(const char* key) const;
  83. bool has_file(const char* key) const;
  84. MultipartFile get_file_value(const char* key) const;
  85. };
  86. struct Response {
  87. int status;
  88. MultiMap headers;
  89. std::string body;
  90. bool has_header(const char* key) const;
  91. std::string get_header_value(const char* key) const;
  92. void set_header(const char* key, const char* val);
  93. void set_redirect(const char* url);
  94. void set_content(const char* s, size_t n, const char* content_type);
  95. void set_content(const std::string& s, const char* content_type);
  96. Response() : status(-1) {}
  97. };
  98. class Stream {
  99. public:
  100. virtual ~Stream() {}
  101. virtual int read(char* ptr, size_t size) = 0;
  102. virtual int write(const char* ptr, size_t size1) = 0;
  103. virtual int write(const char* ptr) = 0;
  104. };
  105. class SocketStream : public Stream {
  106. public:
  107. SocketStream(socket_t sock);
  108. virtual ~SocketStream();
  109. virtual int read(char* ptr, size_t size);
  110. virtual int write(const char* ptr, size_t size);
  111. virtual int write(const char* ptr);
  112. private:
  113. socket_t sock_;
  114. };
  115. class Server {
  116. public:
  117. typedef std::function<void (const Request&, Response&)> Handler;
  118. typedef std::function<void (const Request&, const Response&)> Logger;
  119. Server();
  120. virtual ~Server();
  121. Server& get(const char* pattern, Handler handler);
  122. Server& post(const char* pattern, Handler handler);
  123. bool set_base_dir(const char* path);
  124. void set_error_handler(Handler handler);
  125. void set_logger(Logger logger);
  126. bool listen(const char* host, int port, int socket_flags = 0);
  127. void stop();
  128. protected:
  129. void process_request(Stream& strm);
  130. private:
  131. typedef std::vector<std::pair<std::regex, Handler>> Handlers;
  132. bool routing(Request& req, Response& res);
  133. bool handle_file_request(Request& req, Response& res);
  134. bool dispatch_request(Request& req, Response& res, Handlers& handlers);
  135. bool read_request_line(Stream& strm, Request& req);
  136. void write_response(Stream& strm, const Request& req, Response& res);
  137. virtual bool read_and_close_socket(socket_t sock);
  138. socket_t svr_sock_;
  139. std::string base_dir_;
  140. Handlers get_handlers_;
  141. Handlers post_handlers_;
  142. Handler error_handler_;
  143. Logger logger_;
  144. };
  145. class Client {
  146. public:
  147. Client(const char* host, int port, HttpVersion http_version = HttpVersion::v1_0);
  148. virtual ~Client();
  149. std::shared_ptr<Response> get(const char* path, Progress callback = [](int64_t,int64_t){});
  150. std::shared_ptr<Response> head(const char* path);
  151. std::shared_ptr<Response> post(const char* path, const std::string& body, const char* content_type);
  152. std::shared_ptr<Response> post(const char* path, const MultiMap& params);
  153. bool send(const Request& req, Response& res);
  154. protected:
  155. bool process_request(Stream& strm, const Request& req, Response& res);
  156. const std::string host_;
  157. const int port_;
  158. const HttpVersion http_version_;
  159. const std::string host_and_port_;
  160. private:
  161. bool read_response_line(Stream& strm, Response& res);
  162. void add_default_headers(Request& req);
  163. virtual bool read_and_close_socket(socket_t sock, const Request& req, Response& res);
  164. };
  165. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  166. class SSLSocketStream : public Stream {
  167. public:
  168. SSLSocketStream(SSL* ssl);
  169. virtual ~SSLSocketStream();
  170. virtual int read(char* ptr, size_t size);
  171. virtual int write(const char* ptr, size_t size);
  172. virtual int write(const char* ptr);
  173. private:
  174. SSL* ssl_;
  175. };
  176. class SSLServer : public Server {
  177. public:
  178. SSLServer(const char* cert_path, const char* private_key_path);
  179. virtual ~SSLServer();
  180. private:
  181. virtual bool read_and_close_socket(socket_t sock);
  182. SSL_CTX* ctx_;
  183. };
  184. class SSLClient : public Client {
  185. public:
  186. SSLClient(const char* host, int port, HttpVersion http_version = HttpVersion::v1_0);
  187. virtual ~SSLClient();
  188. private:
  189. virtual bool read_and_close_socket(socket_t sock, const Request& req, Response& res);
  190. SSL_CTX* ctx_;
  191. };
  192. #endif
  193. /*
  194. * Implementation
  195. */
  196. namespace detail {
  197. static std::vector<const char*> http_version_strings = { "HTTP/1.0", "HTTP/1.1" };
  198. template <class Fn>
  199. void split(const char* b, const char* e, char d, Fn fn)
  200. {
  201. int i = 0;
  202. int beg = 0;
  203. while (e ? (b + i != e) : (b[i] != '\0')) {
  204. if (b[i] == d) {
  205. fn(&b[beg], &b[i]);
  206. beg = i + 1;
  207. }
  208. i++;
  209. }
  210. if (i) {
  211. fn(&b[beg], &b[i]);
  212. }
  213. }
  214. inline bool socket_gets(Stream& strm, char* buf, size_t bufsiz)
  215. {
  216. // TODO: buffering for better performance
  217. size_t i = 0;
  218. for (;;) {
  219. char byte;
  220. auto n = strm.read(&byte, 1);
  221. if (n < 1) {
  222. if (i == 0) {
  223. return false;
  224. } else {
  225. break;
  226. }
  227. }
  228. if (i == bufsiz) {
  229. return false;
  230. }
  231. buf[i++] = byte;
  232. if (byte == '\n') {
  233. break;
  234. }
  235. }
  236. if (i == bufsiz) {
  237. return false;
  238. }
  239. buf[i] = '\0';
  240. return true;
  241. }
  242. template <typename ...Args>
  243. inline void socket_printf(Stream& strm, const char* fmt, const Args& ...args)
  244. {
  245. char buf[BUFSIZ];
  246. auto n = snprintf(buf, BUFSIZ, fmt, args...);
  247. if (n > 0) {
  248. if (n >= BUFSIZ) {
  249. std::vector<char> glowable_buf(BUFSIZ);
  250. while (n >= static_cast<int>(glowable_buf.size())) {
  251. glowable_buf.resize(glowable_buf.size() * 2);
  252. n = snprintf(&glowable_buf[0], glowable_buf.size(), fmt, args...);
  253. }
  254. strm.write(&glowable_buf[0], n);
  255. } else {
  256. strm.write(buf, n);
  257. }
  258. }
  259. }
  260. inline int close_socket(socket_t sock)
  261. {
  262. #ifdef _MSC_VER
  263. return closesocket(sock);
  264. #else
  265. return close(sock);
  266. #endif
  267. }
  268. template <typename T>
  269. inline bool read_and_close_socket(socket_t sock, T callback)
  270. {
  271. SocketStream strm(sock);
  272. auto ret = callback(strm);
  273. close_socket(sock);
  274. return ret;
  275. }
  276. inline int shutdown_socket(socket_t sock)
  277. {
  278. #ifdef _MSC_VER
  279. return shutdown(sock, SD_BOTH);
  280. #else
  281. return shutdown(sock, SHUT_RDWR);
  282. #endif
  283. }
  284. template <typename Fn>
  285. socket_t create_socket(const char* host, int port, Fn fn, int socket_flags = 0)
  286. {
  287. #ifdef _MSC_VER
  288. int opt = SO_SYNCHRONOUS_NONALERT;
  289. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
  290. #endif
  291. // Get address info
  292. struct addrinfo hints;
  293. struct addrinfo *result;
  294. memset(&hints, 0, sizeof(struct addrinfo));
  295. hints.ai_family = AF_UNSPEC;
  296. hints.ai_socktype = SOCK_STREAM;
  297. hints.ai_flags = socket_flags;
  298. hints.ai_protocol = 0;
  299. auto service = std::to_string(port);
  300. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  301. return -1;
  302. }
  303. for (auto rp = result; rp; rp = rp->ai_next) {
  304. // Create a socket
  305. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  306. if (sock == -1) {
  307. continue;
  308. }
  309. // Make 'reuse address' option available
  310. int yes = 1;
  311. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
  312. // bind or connect
  313. if (fn(sock, *rp)) {
  314. freeaddrinfo(result);
  315. return sock;
  316. }
  317. close_socket(sock);
  318. }
  319. freeaddrinfo(result);
  320. return -1;
  321. }
  322. inline socket_t create_server_socket(const char* host, int port, int socket_flags)
  323. {
  324. return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
  325. if (::bind(sock, ai.ai_addr, ai.ai_addrlen)) {
  326. return false;
  327. }
  328. if (listen(sock, 5)) { // Listen through 5 channels
  329. return false;
  330. }
  331. return true;
  332. }, socket_flags);
  333. }
  334. inline socket_t create_client_socket(const char* host, int port)
  335. {
  336. return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
  337. if (connect(sock, ai.ai_addr, ai.ai_addrlen)) {
  338. return false;
  339. }
  340. return true;
  341. });
  342. }
  343. inline bool is_file(const std::string& path)
  344. {
  345. struct stat st;
  346. return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  347. }
  348. inline bool is_dir(const std::string& path)
  349. {
  350. struct stat st;
  351. return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  352. }
  353. inline bool is_valid_path(const std::string& path) {
  354. size_t level = 0;
  355. size_t i = 0;
  356. // Skip slash
  357. while (i < path.size() && path[i] == '/') {
  358. i++;
  359. }
  360. while (i < path.size()) {
  361. // Read component
  362. auto beg = i;
  363. while (i < path.size() && path[i] != '/') {
  364. i++;
  365. }
  366. auto len = i - beg;
  367. assert(len > 0);
  368. if (!path.compare(beg, len, ".")) {
  369. ;
  370. } else if (!path.compare(beg, len, "..")) {
  371. if (level == 0) {
  372. return false;
  373. }
  374. level--;
  375. } else {
  376. level++;
  377. }
  378. // Skip slash
  379. while (i < path.size() && path[i] == '/') {
  380. i++;
  381. }
  382. }
  383. return true;
  384. }
  385. inline void read_file(const std::string& path, std::string& out)
  386. {
  387. std::ifstream fs(path, std::ios_base::binary);
  388. fs.seekg(0, std::ios_base::end);
  389. auto size = fs.tellg();
  390. fs.seekg(0);
  391. out.resize(static_cast<size_t>(size));
  392. fs.read(&out[0], size);
  393. }
  394. inline std::string file_extension(const std::string& path)
  395. {
  396. std::smatch m;
  397. auto pat = std::regex("\\.([a-zA-Z0-9]+)$");
  398. if (std::regex_search(path, m, pat)) {
  399. return m[1].str();
  400. }
  401. return std::string();
  402. }
  403. inline const char* content_type(const std::string& path)
  404. {
  405. auto ext = detail::file_extension(path);
  406. if (ext == "txt") {
  407. return "text/plain";
  408. } else if (ext == "html") {
  409. return "text/html";
  410. } else if (ext == "js") {
  411. return "text/javascript";
  412. } else if (ext == "css") {
  413. return "text/css";
  414. } else if (ext == "xml") {
  415. return "text/xml";
  416. } else if (ext == "jpeg" || ext == "jpg") {
  417. return "image/jpg";
  418. } else if (ext == "png") {
  419. return "image/png";
  420. } else if (ext == "gif") {
  421. return "image/gif";
  422. } else if (ext == "svg") {
  423. return "image/svg+xml";
  424. } else if (ext == "ico") {
  425. return "image/x-icon";
  426. } else if (ext == "json") {
  427. return "application/json";
  428. } else if (ext == "pdf") {
  429. return "application/pdf";
  430. } else if (ext == "xhtml") {
  431. return "application/xhtml+xml";
  432. }
  433. return nullptr;
  434. }
  435. inline const char* status_message(int status)
  436. {
  437. switch (status) {
  438. case 200: return "OK";
  439. case 400: return "Bad Request";
  440. case 404: return "Not Found";
  441. default:
  442. case 500: return "Internal Server Error";
  443. }
  444. }
  445. inline const char* get_header_value(const MultiMap& headers, const char* key, const char* def)
  446. {
  447. auto it = headers.find(key);
  448. if (it != headers.end()) {
  449. return it->second.c_str();
  450. }
  451. return def;
  452. }
  453. inline int get_header_value_int(const MultiMap& headers, const char* key, int def)
  454. {
  455. auto it = headers.find(key);
  456. if (it != headers.end()) {
  457. return std::stoi(it->second);
  458. }
  459. return def;
  460. }
  461. inline bool read_headers(Stream& strm, MultiMap& headers)
  462. {
  463. static std::regex re("(.+?): (.+?)\r\n");
  464. const auto BUFSIZ_HEADER = 2048;
  465. char buf[BUFSIZ_HEADER];
  466. for (;;) {
  467. if (!socket_gets(strm, buf, BUFSIZ_HEADER)) {
  468. return false;
  469. }
  470. if (!strcmp(buf, "\r\n")) {
  471. break;
  472. }
  473. std::cmatch m;
  474. if (std::regex_match(buf, m, re)) {
  475. auto key = std::string(m[1]);
  476. auto val = std::string(m[2]);
  477. headers.emplace(key, val);
  478. }
  479. }
  480. return true;
  481. }
  482. template <typename T>
  483. bool read_content_with_length(Stream& strm, T& x, size_t len, Progress progress)
  484. {
  485. x.body.assign(len, 0);
  486. size_t r = 0;
  487. while (r < len){
  488. auto r_incr = strm.read(&x.body[r], len - r);
  489. if (r_incr <= 0) {
  490. return false;
  491. }
  492. r += r_incr;
  493. if (progress) {
  494. progress(r, len);
  495. }
  496. }
  497. return true;
  498. }
  499. template <typename T>
  500. bool read_content_without_length(Stream& strm, T& x)
  501. {
  502. for (;;) {
  503. char byte;
  504. auto n = strm.read(&byte, 1);
  505. if (n < 0) {
  506. return false;
  507. } else if (n == 0) {
  508. break;
  509. }
  510. x.body += byte;
  511. }
  512. return true;
  513. }
  514. template <typename T>
  515. bool read_content_chunked(Stream& strm, T& x)
  516. {
  517. const auto BUFSIZ_CHUNK_LEN = 16;
  518. char buf[BUFSIZ_CHUNK_LEN];
  519. if (!socket_gets(strm, buf, BUFSIZ_CHUNK_LEN)) {
  520. return false;
  521. }
  522. auto chunk_len = std::stoi(buf, 0, 16);
  523. while (chunk_len > 0){
  524. std::string chunk(chunk_len, 0);
  525. auto n = strm.read(&chunk[0], chunk_len);
  526. if (n <= 0) {
  527. return false;
  528. }
  529. if (!socket_gets(strm, buf, BUFSIZ_CHUNK_LEN)) {
  530. return false;
  531. }
  532. if (strcmp(buf, "\r\n")) {
  533. break;
  534. }
  535. x.body += chunk;
  536. if (!socket_gets(strm, buf, BUFSIZ_CHUNK_LEN)) {
  537. return false;
  538. }
  539. chunk_len = std::stoi(buf, 0, 16);
  540. }
  541. return true;
  542. }
  543. template <typename T>
  544. bool read_content(Stream& strm, T& x, Progress progress = [](int64_t,int64_t){})
  545. {
  546. auto len = get_header_value_int(x.headers, "Content-Length", 0);
  547. if (len) {
  548. return read_content_with_length(strm, x, len, progress);
  549. } else {
  550. auto encoding = get_header_value(x.headers, "Transfer-Encoding", "");
  551. if (!strcmp(encoding, "chunked")) {
  552. return read_content_chunked(strm, x);
  553. } else {
  554. return read_content_without_length(strm, x);
  555. }
  556. }
  557. return true;
  558. }
  559. template <typename T>
  560. inline void write_headers(Stream& strm, const T& res)
  561. {
  562. strm.write("Connection: close\r\n");
  563. for (const auto& x: res.headers) {
  564. if (x.first != "Content-Type" && x.first != "Content-Length") {
  565. socket_printf(strm, "%s: %s\r\n", x.first.c_str(), x.second.c_str());
  566. }
  567. }
  568. auto t = get_header_value(res.headers, "Content-Type", "text/plain");
  569. socket_printf(strm, "Content-Type: %s\r\n", t);
  570. socket_printf(strm, "Content-Length: %ld\r\n", res.body.size());
  571. strm.write("\r\n");
  572. }
  573. inline void write_response(Stream& strm, const Request& req, const Response& res)
  574. {
  575. socket_printf(strm, "HTTP/1.0 %d %s\r\n", res.status, status_message(res.status));
  576. write_headers(strm, res);
  577. if (!res.body.empty() && req.method != "HEAD") {
  578. strm.write(res.body.c_str(), res.body.size());
  579. }
  580. }
  581. inline std::string encode_url(const std::string& s)
  582. {
  583. std::string result;
  584. for (auto i = 0; s[i]; i++) {
  585. switch (s[i]) {
  586. case ' ': result += "+"; break;
  587. case '\'': result += "%27"; break;
  588. case ',': result += "%2C"; break;
  589. case ':': result += "%3A"; break;
  590. case ';': result += "%3B"; break;
  591. default:
  592. if (s[i] < 0) {
  593. result += '%';
  594. char hex[4];
  595. size_t len = snprintf(hex, sizeof(hex), "%02X", (unsigned char)s[i]);
  596. assert(len == 2);
  597. result.append(hex, len);
  598. } else {
  599. result += s[i];
  600. }
  601. break;
  602. }
  603. }
  604. return result;
  605. }
  606. inline bool is_hex(char c, int& v)
  607. {
  608. if (0x20 <= c && isdigit(c)) {
  609. v = c - '0';
  610. return true;
  611. } else if ('A' <= c && c <= 'F') {
  612. v = c - 'A' + 10;
  613. return true;
  614. } else if ('a' <= c && c <= 'f') {
  615. v = c - 'a' + 10;
  616. return true;
  617. }
  618. return false;
  619. }
  620. inline bool from_hex_to_i(const std::string& s, int i, int cnt, int& val)
  621. {
  622. val = 0;
  623. for (; cnt; i++, cnt--) {
  624. if (!s[i]) {
  625. return false;
  626. }
  627. int v = 0;
  628. if (is_hex(s[i], v)) {
  629. val = val * 16 + v;
  630. } else {
  631. return false;
  632. }
  633. }
  634. return true;
  635. }
  636. inline size_t to_utf8(int code, char* buff)
  637. {
  638. if (code < 0x0080) {
  639. buff[0] = (code & 0x7F);
  640. return 1;
  641. } else if (code < 0x0800) {
  642. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  643. buff[1] = (0x80 | (code & 0x3F));
  644. return 2;
  645. } else if (code < 0xD800) {
  646. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  647. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  648. buff[2] = (0x80 | (code & 0x3F));
  649. return 3;
  650. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  651. return 0;
  652. } else if (code < 0x10000) {
  653. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  654. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  655. buff[2] = (0x80 | (code & 0x3F));
  656. return 3;
  657. } else if (code < 0x110000) {
  658. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  659. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  660. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  661. buff[3] = (0x80 | (code & 0x3F));
  662. return 4;
  663. }
  664. // NOTREACHED
  665. return 0;
  666. }
  667. inline std::string decode_url(const std::string& s)
  668. {
  669. std::string result;
  670. for (int i = 0; s[i]; i++) {
  671. if (s[i] == '%') {
  672. if (s[i + 1] && s[i + 1] == 'u') {
  673. int val = 0;
  674. if (from_hex_to_i(s, i + 2, 4, val)) {
  675. // 4 digits Unicode codes
  676. char buff[4];
  677. size_t len = to_utf8(val, buff);
  678. if (len > 0) {
  679. result.append(buff, len);
  680. }
  681. i += 5; // 'u0000'
  682. } else {
  683. result += s[i];
  684. }
  685. } else {
  686. int val = 0;
  687. if (from_hex_to_i(s, i + 1, 2, val)) {
  688. // 2 digits hex codes
  689. result += val;
  690. i += 2; // '00'
  691. } else {
  692. result += s[i];
  693. }
  694. }
  695. } else if (s[i] == '+') {
  696. result += ' ';
  697. } else {
  698. result += s[i];
  699. }
  700. }
  701. return result;
  702. }
  703. inline void write_request(Stream& strm, const Request& req, const char* ver)
  704. {
  705. auto path = encode_url(req.path);
  706. socket_printf(strm, "%s %s %s\r\n", req.method.c_str(), path.c_str(), ver);
  707. write_headers(strm, req);
  708. if (!req.body.empty()) {
  709. if (req.has_header("application/x-www-form-urlencoded")) {
  710. auto str = encode_url(req.body);
  711. strm.write(str.c_str(), str.size());
  712. } else {
  713. strm.write(req.body.c_str(), req.body.size());
  714. }
  715. }
  716. }
  717. inline void parse_query_text(const std::string& s, MultiMap& params)
  718. {
  719. split(&s[0], &s[s.size()], '&', [&](const char* b, const char* e) {
  720. std::string key;
  721. std::string val;
  722. split(b, e, '=', [&](const char* b, const char* e) {
  723. if (key.empty()) {
  724. key.assign(b, e);
  725. } else {
  726. val.assign(b, e);
  727. }
  728. });
  729. params.emplace(key, detail::decode_url(val));
  730. });
  731. }
  732. inline bool parse_multipart_boundary(const std::string& content_type, std::string& boundary)
  733. {
  734. auto pos = content_type.find("boundary=");
  735. if (pos == std::string::npos) {
  736. return false;
  737. }
  738. boundary = content_type.substr(pos + 9);
  739. return true;
  740. }
  741. inline bool parse_multipart_formdata(
  742. const std::string& boundary, const std::string& body, MultipartFiles& files)
  743. {
  744. static std::string dash = "--";
  745. static std::string crlf = "\r\n";
  746. static std::regex re_content_type(
  747. "Content-Type: (.*?)");
  748. static std::regex re_content_disposition(
  749. "Content-Disposition: form-data; name=\"(.*?)\"(?:; filename=\"(.*?)\")?");
  750. auto dash_boundary = dash + boundary;
  751. auto pos = body.find(dash_boundary);
  752. if (pos != 0) {
  753. return false;
  754. }
  755. pos += dash_boundary.size();
  756. auto next_pos = body.find(crlf, pos);
  757. if (next_pos == std::string::npos) {
  758. return false;
  759. }
  760. pos = next_pos + crlf.size();
  761. while (pos < body.size()) {
  762. next_pos = body.find(crlf, pos);
  763. if (next_pos == std::string::npos) {
  764. return false;
  765. }
  766. std::string name;
  767. MultipartFile file;
  768. auto header = body.substr(pos, (next_pos - pos));
  769. while (pos != next_pos) {
  770. std::smatch m;
  771. if (std::regex_match(header, m, re_content_type)) {
  772. file.content_type = m[1];
  773. } else if (std::regex_match(header, m, re_content_disposition)) {
  774. name = m[1];
  775. file.filename = m[2];
  776. }
  777. pos = next_pos + crlf.size();
  778. next_pos = body.find(crlf, pos);
  779. if (next_pos == std::string::npos) {
  780. return false;
  781. }
  782. header = body.substr(pos, (next_pos - pos));
  783. }
  784. pos = next_pos + crlf.size();
  785. next_pos = body.find(crlf + dash_boundary, pos);
  786. if (next_pos == std::string::npos) {
  787. return false;
  788. }
  789. file.offset = pos;
  790. file.length = next_pos - pos;
  791. pos = next_pos + crlf.size() + dash_boundary.size();
  792. next_pos = body.find(crlf, pos);
  793. if (next_pos == std::string::npos) {
  794. return false;
  795. }
  796. files.emplace(name, file);
  797. pos = next_pos + crlf.size();
  798. }
  799. return true;
  800. }
  801. #ifdef _MSC_VER
  802. class WSInit {
  803. public:
  804. WSInit() {
  805. WSADATA wsaData;
  806. WSAStartup(0x0002, &wsaData);
  807. }
  808. ~WSInit() {
  809. WSACleanup();
  810. }
  811. };
  812. static WSInit wsinit_;
  813. #endif
  814. } // namespace detail
  815. // Request implementation
  816. inline bool Request::has_header(const char* key) const
  817. {
  818. return headers.find(key) != headers.end();
  819. }
  820. inline std::string Request::get_header_value(const char* key) const
  821. {
  822. return detail::get_header_value(headers, key, "");
  823. }
  824. inline void Request::set_header(const char* key, const char* val)
  825. {
  826. headers.emplace(key, val);
  827. }
  828. inline bool Request::has_param(const char* key) const
  829. {
  830. return params.find(key) != params.end();
  831. }
  832. inline std::string Request::get_param_value(const char* key) const
  833. {
  834. auto it = params.find(key);
  835. if (it != params.end()) {
  836. return it->second;
  837. }
  838. return std::string();
  839. }
  840. inline bool Request::has_file(const char* key) const
  841. {
  842. return files.find(key) != files.end();
  843. }
  844. inline MultipartFile Request::get_file_value(const char* key) const
  845. {
  846. auto it = files.find(key);
  847. if (it != files.end()) {
  848. return it->second;
  849. }
  850. return MultipartFile();
  851. }
  852. // Response implementation
  853. inline bool Response::has_header(const char* key) const
  854. {
  855. return headers.find(key) != headers.end();
  856. }
  857. inline std::string Response::get_header_value(const char* key) const
  858. {
  859. return detail::get_header_value(headers, key, "");
  860. }
  861. inline void Response::set_header(const char* key, const char* val)
  862. {
  863. headers.emplace(key, val);
  864. }
  865. inline void Response::set_redirect(const char* url)
  866. {
  867. set_header("Location", url);
  868. status = 302;
  869. }
  870. inline void Response::set_content(const char* s, size_t n, const char* content_type)
  871. {
  872. body.assign(s, n);
  873. set_header("Content-Type", content_type);
  874. }
  875. inline void Response::set_content(const std::string& s, const char* content_type)
  876. {
  877. body = s;
  878. set_header("Content-Type", content_type);
  879. }
  880. // Socket stream implementation
  881. inline SocketStream::SocketStream(socket_t sock): sock_(sock)
  882. {
  883. }
  884. inline SocketStream::~SocketStream()
  885. {
  886. }
  887. inline int SocketStream::read(char* ptr, size_t size)
  888. {
  889. return recv(sock_, ptr, size, 0);
  890. }
  891. inline int SocketStream::write(const char* ptr, size_t size)
  892. {
  893. return send(sock_, ptr, size, 0);
  894. }
  895. inline int SocketStream::write(const char* ptr)
  896. {
  897. return write(ptr, strlen(ptr));
  898. }
  899. // HTTP server implementation
  900. inline Server::Server()
  901. : svr_sock_(-1)
  902. {
  903. #ifndef _MSC_VER
  904. signal(SIGPIPE, SIG_IGN);
  905. #endif
  906. }
  907. inline Server::~Server()
  908. {
  909. }
  910. inline Server& Server::get(const char* pattern, Handler handler)
  911. {
  912. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  913. return *this;
  914. }
  915. inline Server& Server::post(const char* pattern, Handler handler)
  916. {
  917. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  918. return *this;
  919. }
  920. inline bool Server::set_base_dir(const char* path)
  921. {
  922. if (detail::is_dir(path)) {
  923. base_dir_ = path;
  924. return true;
  925. }
  926. return false;
  927. }
  928. inline void Server::set_error_handler(Handler handler)
  929. {
  930. error_handler_ = handler;
  931. }
  932. inline void Server::set_logger(Logger logger)
  933. {
  934. logger_ = logger;
  935. }
  936. inline bool Server::listen(const char* host, int port, int socket_flags)
  937. {
  938. svr_sock_ = detail::create_server_socket(host, port, socket_flags);
  939. if (svr_sock_ == -1) {
  940. return false;
  941. }
  942. auto ret = true;
  943. for (;;) {
  944. socket_t sock = accept(svr_sock_, NULL, NULL);
  945. if (sock == -1) {
  946. if (svr_sock_ != -1) {
  947. detail::close_socket(svr_sock_);
  948. ret = false;
  949. } else {
  950. ; // The server socket was closed by user.
  951. }
  952. break;
  953. }
  954. // TODO: should be async
  955. read_and_close_socket(sock);
  956. }
  957. return ret;
  958. }
  959. inline void Server::stop()
  960. {
  961. detail::shutdown_socket(svr_sock_);
  962. detail::close_socket(svr_sock_);
  963. svr_sock_ = -1;
  964. }
  965. inline bool Server::read_request_line(Stream& strm, Request& req)
  966. {
  967. const auto BUFSIZ_REQUESTLINE = 2048;
  968. char buf[BUFSIZ_REQUESTLINE];
  969. if (!detail::socket_gets(strm, buf, BUFSIZ_REQUESTLINE)) {
  970. return false;
  971. }
  972. static std::regex re("(GET|HEAD|POST) ([^?]+)(?:\\?(.+?))? HTTP/1\\.[01]\r\n");
  973. std::cmatch m;
  974. if (std::regex_match(buf, m, re)) {
  975. req.method = std::string(m[1]);
  976. req.path = detail::decode_url(m[2]);
  977. // Parse query text
  978. auto len = std::distance(m[3].first, m[3].second);
  979. if (len > 0) {
  980. detail::parse_query_text(m[3], req.params);
  981. }
  982. return true;
  983. }
  984. return false;
  985. }
  986. inline void Server::write_response(Stream& strm, const Request& req, Response& res)
  987. {
  988. assert(res.status != -1);
  989. if (400 <= res.status && error_handler_) {
  990. error_handler_(req, res);
  991. }
  992. detail::write_response(strm, req, res);
  993. if (logger_) {
  994. logger_(req, res);
  995. }
  996. }
  997. inline bool Server::handle_file_request(Request& req, Response& res)
  998. {
  999. if (!base_dir_.empty() && detail::is_valid_path(req.path)) {
  1000. std::string path = base_dir_ + req.path;
  1001. if (!path.empty() && path.back() == '/') {
  1002. path += "index.html";
  1003. }
  1004. if (detail::is_file(path)) {
  1005. detail::read_file(path, res.body);
  1006. auto type = detail::content_type(path);
  1007. if (type) {
  1008. res.set_header("Content-Type", type);
  1009. }
  1010. res.status = 200;
  1011. return true;
  1012. }
  1013. }
  1014. return false;
  1015. }
  1016. inline bool Server::routing(Request& req, Response& res)
  1017. {
  1018. if (req.method == "GET" && handle_file_request(req, res)) {
  1019. return true;
  1020. }
  1021. if (req.method == "GET" || req.method == "HEAD") {
  1022. return dispatch_request(req, res, get_handlers_);
  1023. } else if (req.method == "POST") {
  1024. return dispatch_request(req, res, post_handlers_);
  1025. }
  1026. return false;
  1027. }
  1028. inline bool Server::dispatch_request(Request& req, Response& res, Handlers& handlers)
  1029. {
  1030. for (const auto& x: handlers) {
  1031. const auto& pattern = x.first;
  1032. const auto& handler = x.second;
  1033. if (std::regex_match(req.path, req.matches, pattern)) {
  1034. handler(req, res);
  1035. return true;
  1036. }
  1037. }
  1038. return false;
  1039. }
  1040. inline void Server::process_request(Stream& strm)
  1041. {
  1042. Request req;
  1043. Response res;
  1044. if (!read_request_line(strm, req) || !detail::read_headers(strm, req.headers)) {
  1045. res.status = 400;
  1046. write_response(strm, req, res);
  1047. return;
  1048. }
  1049. if (req.method == "POST") {
  1050. if (!detail::read_content(strm, req)) {
  1051. res.status = 400;
  1052. write_response(strm, req, res);
  1053. return;
  1054. }
  1055. const auto& content_type = req.get_header_value("Content-Type");
  1056. if (!content_type.find("application/x-www-form-urlencoded")) {
  1057. detail::parse_query_text(req.body, req.params);
  1058. } else if(!content_type.find("multipart/form-data")) {
  1059. std::string boundary;
  1060. if (!detail::parse_multipart_boundary(content_type, boundary) ||
  1061. !detail::parse_multipart_formdata(boundary, req.body, req.files)) {
  1062. res.status = 400;
  1063. write_response(strm, req, res);
  1064. return;
  1065. }
  1066. }
  1067. }
  1068. if (routing(req, res)) {
  1069. if (res.status == -1) {
  1070. res.status = 200;
  1071. }
  1072. } else {
  1073. res.status = 404;
  1074. }
  1075. write_response(strm, req, res);
  1076. }
  1077. inline bool Server::read_and_close_socket(socket_t sock)
  1078. {
  1079. return detail::read_and_close_socket(sock, [this](Stream& strm) {
  1080. process_request(strm);
  1081. return true;
  1082. });
  1083. }
  1084. // HTTP client implementation
  1085. inline Client::Client(const char* host, int port, HttpVersion http_version)
  1086. : host_(host)
  1087. , port_(port)
  1088. , http_version_(http_version)
  1089. , host_and_port_(host_ + ":" + std::to_string(port_))
  1090. {
  1091. }
  1092. inline Client::~Client()
  1093. {
  1094. }
  1095. inline bool Client::read_response_line(Stream& strm, Response& res)
  1096. {
  1097. const auto BUFSIZ_RESPONSELINE = 2048;
  1098. char buf[BUFSIZ_RESPONSELINE];
  1099. if (!detail::socket_gets(strm, buf, BUFSIZ_RESPONSELINE)) {
  1100. return false;
  1101. }
  1102. const static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
  1103. std::cmatch m;
  1104. if (std::regex_match(buf, m, re)) {
  1105. res.status = std::stoi(std::string(m[1]));
  1106. }
  1107. return true;
  1108. }
  1109. inline bool Client::send(const Request& req, Response& res)
  1110. {
  1111. auto sock = detail::create_client_socket(host_.c_str(), port_);
  1112. if (sock == -1) {
  1113. return false;
  1114. }
  1115. return read_and_close_socket(sock, req, res);
  1116. }
  1117. inline bool Client::process_request(Stream& strm, const Request& req, Response& res)
  1118. {
  1119. // Send request
  1120. auto ver = detail::http_version_strings[static_cast<size_t>(http_version_)];
  1121. detail::write_request(strm, req, ver);
  1122. // Receive response
  1123. if (!read_response_line(strm, res) ||
  1124. !detail::read_headers(strm, res.headers)) {
  1125. return false;
  1126. }
  1127. if (req.method != "HEAD") {
  1128. if (!detail::read_content(strm, res, req.progress)) {
  1129. return false;
  1130. }
  1131. }
  1132. return true;
  1133. }
  1134. inline bool Client::read_and_close_socket(socket_t sock, const Request& req, Response& res)
  1135. {
  1136. return detail::read_and_close_socket(sock, [&](Stream& strm) {
  1137. return process_request(strm, req, res);
  1138. });
  1139. }
  1140. inline void Client::add_default_headers(Request& req)
  1141. {
  1142. req.set_header("Host", host_and_port_.c_str());
  1143. req.set_header("Accept", "*/*");
  1144. req.set_header("User-Agent", "cpp-httplib/0.1");
  1145. }
  1146. inline std::shared_ptr<Response> Client::get(const char* path, Progress callback)
  1147. {
  1148. Request req;
  1149. req.method = "GET";
  1150. req.path = path;
  1151. req.progress = callback;
  1152. add_default_headers(req);
  1153. auto res = std::make_shared<Response>();
  1154. return send(req, *res) ? res : nullptr;
  1155. }
  1156. inline std::shared_ptr<Response> Client::head(const char* path)
  1157. {
  1158. Request req;
  1159. req.method = "HEAD";
  1160. req.path = path;
  1161. add_default_headers(req);
  1162. auto res = std::make_shared<Response>();
  1163. return send(req, *res) ? res : nullptr;
  1164. }
  1165. inline std::shared_ptr<Response> Client::post(
  1166. const char* path, const std::string& body, const char* content_type)
  1167. {
  1168. Request req;
  1169. req.method = "POST";
  1170. req.path = path;
  1171. add_default_headers(req);
  1172. req.set_header("Content-Type", content_type);
  1173. req.body = body;
  1174. auto res = std::make_shared<Response>();
  1175. return send(req, *res) ? res : nullptr;
  1176. }
  1177. inline std::shared_ptr<Response> Client::post(
  1178. const char* path, const MultiMap& params)
  1179. {
  1180. std::string query;
  1181. for (auto it = params.begin(); it != params.end(); ++it) {
  1182. if (it != params.begin()) {
  1183. query += "&";
  1184. }
  1185. query += it->first;
  1186. query += "=";
  1187. query += it->second;
  1188. }
  1189. return post(path, query, "application/x-www-form-urlencoded");
  1190. }
  1191. /*
  1192. * SSL Implementation
  1193. */
  1194. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1195. namespace detail {
  1196. template <typename U, typename V, typename T>
  1197. inline bool read_and_close_socket_ssl(socket_t sock, SSL_CTX* ctx, U SSL_connect_or_accept, V setup, T callback)
  1198. {
  1199. auto ssl = SSL_new(ctx);
  1200. auto bio = BIO_new_socket(sock, BIO_NOCLOSE);
  1201. SSL_set_bio(ssl, bio, bio);
  1202. setup(ssl);
  1203. SSL_connect_or_accept(ssl);
  1204. SSLSocketStream strm(ssl);
  1205. auto ret = callback(strm);
  1206. SSL_shutdown(ssl);
  1207. SSL_free(ssl);
  1208. close_socket(sock);
  1209. return ret;
  1210. }
  1211. class SSLInit {
  1212. public:
  1213. SSLInit() {
  1214. SSL_load_error_strings();
  1215. SSL_library_init();
  1216. }
  1217. };
  1218. static SSLInit sslinit_;
  1219. } // namespace detail
  1220. // SSL socket stream implementation
  1221. inline SSLSocketStream::SSLSocketStream(SSL* ssl): ssl_(ssl)
  1222. {
  1223. }
  1224. inline SSLSocketStream::~SSLSocketStream()
  1225. {
  1226. }
  1227. inline int SSLSocketStream::read(char* ptr, size_t size)
  1228. {
  1229. return SSL_read(ssl_, ptr, size);
  1230. }
  1231. inline int SSLSocketStream::write(const char* ptr, size_t size)
  1232. {
  1233. return SSL_write(ssl_, ptr, size);
  1234. }
  1235. inline int SSLSocketStream::write(const char* ptr)
  1236. {
  1237. return write(ptr, strlen(ptr));
  1238. }
  1239. // SSL HTTP server implementation
  1240. inline SSLServer::SSLServer(const char* cert_path, const char* private_key_path)
  1241. {
  1242. ctx_ = SSL_CTX_new(SSLv23_server_method());
  1243. if (ctx_) {
  1244. SSL_CTX_set_options(ctx_,
  1245. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  1246. SSL_OP_NO_COMPRESSION |
  1247. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  1248. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  1249. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  1250. // EC_KEY_free(ecdh);
  1251. if (SSL_CTX_use_certificate_file(ctx_, cert_path, SSL_FILETYPE_PEM) != 1 ||
  1252. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != 1) {
  1253. SSL_CTX_free(ctx_);
  1254. ctx_ = nullptr;
  1255. }
  1256. }
  1257. }
  1258. inline SSLServer::~SSLServer()
  1259. {
  1260. if (ctx_) {
  1261. SSL_CTX_free(ctx_);
  1262. }
  1263. }
  1264. inline bool SSLServer::read_and_close_socket(socket_t sock)
  1265. {
  1266. return detail::read_and_close_socket_ssl(
  1267. sock, ctx_,
  1268. SSL_accept,
  1269. [](SSL* /*ssl*/) {},
  1270. [this](Stream& strm) {
  1271. process_request(strm);
  1272. return true;
  1273. });
  1274. }
  1275. // SSL HTTP client implementation
  1276. inline SSLClient::SSLClient(const char* host, int port, HttpVersion http_version)
  1277. : Client(host, port, http_version)
  1278. {
  1279. ctx_ = SSL_CTX_new(SSLv23_client_method());
  1280. }
  1281. inline SSLClient::~SSLClient()
  1282. {
  1283. if (ctx_) {
  1284. SSL_CTX_free(ctx_);
  1285. }
  1286. }
  1287. inline bool SSLClient::read_and_close_socket(socket_t sock, const Request& req, Response& res)
  1288. {
  1289. return detail::read_and_close_socket_ssl(
  1290. sock, ctx_,
  1291. SSL_connect,
  1292. [&](SSL* ssl) {
  1293. SSL_set_tlsext_host_name(ssl, host_.c_str());
  1294. },
  1295. [&](Stream& strm) {
  1296. return process_request(strm, req, res);
  1297. });
  1298. }
  1299. #endif
  1300. } // namespace httplib
  1301. #endif
  1302. // vim: et ts=4 sw=4 cin cino={1s ff=unix