httplib.h 38 KB

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