httplib.h 38 KB

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