httplib.h 38 KB

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