httplib.h 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635
  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. #ifndef SO_SYNCHRONOUS_NONALERT
  17. #define SO_SYNCHRONOUS_NONALERT 0x20
  18. #endif
  19. #ifndef SO_OPENTYPE
  20. #define SO_OPENTYPE 0x7008
  21. #endif
  22. #if (_MSC_VER < 1900)
  23. #define snprintf _snprintf_s
  24. #endif
  25. #define S_ISREG(m) (((m)&S_IFREG)==S_IFREG)
  26. #define S_ISDIR(m) (((m)&S_IFDIR)==S_IFDIR)
  27. #include <fcntl.h>
  28. #include <io.h>
  29. #include <winsock2.h>
  30. #include <ws2tcpip.h>
  31. #undef min
  32. #undef max
  33. typedef SOCKET socket_t;
  34. #else
  35. #include <pthread.h>
  36. #include <unistd.h>
  37. #include <netdb.h>
  38. #include <cstring>
  39. #include <netinet/in.h>
  40. #include <arpa/inet.h>
  41. #include <signal.h>
  42. #include <sys/socket.h>
  43. typedef int socket_t;
  44. #endif
  45. #include <fstream>
  46. #include <functional>
  47. #include <map>
  48. #include <memory>
  49. #include <regex>
  50. #include <string>
  51. #include <sys/stat.h>
  52. #include <assert.h>
  53. #ifdef __has_include
  54. #if __has_include(<openssl/ssl.h>)
  55. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  56. #define CPPHTTPLIB_OPENSSL_SUPPORT
  57. #endif
  58. #endif
  59. #endif
  60. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  61. #include <openssl/ssl.h>
  62. #endif
  63. namespace httplib
  64. {
  65. enum class HttpVersion { v1_0 = 0, v1_1 };
  66. typedef std::multimap<std::string, std::string> MultiMap;
  67. typedef std::smatch Match;
  68. typedef std::function<void (int64_t current, int64_t total)> Progress;
  69. struct MultipartFile {
  70. std::string filename;
  71. std::string content_type;
  72. size_t offset = 0;
  73. size_t length = 0;
  74. };
  75. typedef std::multimap<std::string, MultipartFile> MultipartFiles;
  76. struct Request {
  77. std::string method;
  78. std::string path;
  79. MultiMap headers;
  80. std::string body;
  81. MultiMap params;
  82. MultipartFiles files;
  83. Match matches;
  84. Progress progress;
  85. bool has_header(const char* key) const;
  86. std::string get_header_value(const char* key) const;
  87. void set_header(const char* key, const char* val);
  88. bool has_param(const char* key) const;
  89. std::string get_param_value(const char* key) const;
  90. bool has_file(const char* key) const;
  91. MultipartFile get_file_value(const char* key) const;
  92. };
  93. struct Response {
  94. int status;
  95. MultiMap headers;
  96. std::string body;
  97. bool has_header(const char* key) const;
  98. std::string get_header_value(const char* key) const;
  99. void set_header(const char* key, const char* val);
  100. void set_redirect(const char* url);
  101. void set_content(const char* s, size_t n, const char* content_type);
  102. void set_content(const std::string& s, const char* content_type);
  103. Response() : status(-1) {}
  104. };
  105. class Stream {
  106. public:
  107. virtual ~Stream() {}
  108. virtual int read(char* ptr, size_t size) = 0;
  109. virtual int write(const char* ptr, size_t size1) = 0;
  110. virtual int write(const char* ptr) = 0;
  111. };
  112. class SocketStream : public Stream {
  113. public:
  114. SocketStream(socket_t sock);
  115. virtual ~SocketStream();
  116. virtual int read(char* ptr, size_t size);
  117. virtual int write(const char* ptr, size_t size);
  118. virtual int write(const char* ptr);
  119. private:
  120. socket_t sock_;
  121. };
  122. class Server {
  123. public:
  124. typedef std::function<void (const Request&, Response&)> Handler;
  125. typedef std::function<void (const Request&, const Response&)> Logger;
  126. Server();
  127. virtual ~Server();
  128. Server& get(const char* pattern, Handler handler);
  129. Server& post(const char* pattern, Handler handler);
  130. bool set_base_dir(const char* path);
  131. void set_error_handler(Handler handler);
  132. void set_logger(Logger logger);
  133. bool listen(const char* host, int port, int socket_flags = 0);
  134. void stop();
  135. protected:
  136. void process_request(Stream& strm);
  137. private:
  138. typedef std::vector<std::pair<std::regex, Handler>> Handlers;
  139. bool routing(Request& req, Response& res);
  140. bool handle_file_request(Request& req, Response& res);
  141. bool dispatch_request(Request& req, Response& res, Handlers& handlers);
  142. bool read_request_line(Stream& strm, Request& req);
  143. void write_response(Stream& strm, const Request& req, Response& res);
  144. virtual bool read_and_close_socket(socket_t sock);
  145. socket_t svr_sock_;
  146. std::string base_dir_;
  147. Handlers get_handlers_;
  148. Handlers post_handlers_;
  149. Handler error_handler_;
  150. Logger logger_;
  151. };
  152. class Client {
  153. public:
  154. Client(const char* host, int port, HttpVersion http_version = HttpVersion::v1_0);
  155. virtual ~Client();
  156. std::shared_ptr<Response> get(const char* path, Progress callback = [](int64_t,int64_t){});
  157. std::shared_ptr<Response> head(const char* path);
  158. std::shared_ptr<Response> post(const char* path, const std::string& body, const char* content_type);
  159. std::shared_ptr<Response> post(const char* path, const MultiMap& params);
  160. bool send(const Request& req, Response& res);
  161. protected:
  162. bool process_request(Stream& strm, const Request& req, Response& res);
  163. const std::string host_;
  164. const int port_;
  165. const HttpVersion http_version_;
  166. const std::string host_and_port_;
  167. private:
  168. bool read_response_line(Stream& strm, Response& res);
  169. void add_default_headers(Request& req);
  170. virtual bool read_and_close_socket(socket_t sock, const Request& req, Response& res);
  171. };
  172. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  173. class SSLSocketStream : public Stream {
  174. public:
  175. SSLSocketStream(SSL* ssl);
  176. virtual ~SSLSocketStream();
  177. virtual int read(char* ptr, size_t size);
  178. virtual int write(const char* ptr, size_t size);
  179. virtual int write(const char* ptr);
  180. private:
  181. SSL* ssl_;
  182. };
  183. class SSLServer : public Server {
  184. public:
  185. SSLServer(const char* cert_path, const char* private_key_path);
  186. virtual ~SSLServer();
  187. private:
  188. virtual bool read_and_close_socket(socket_t sock);
  189. SSL_CTX* ctx_;
  190. };
  191. class SSLClient : public Client {
  192. public:
  193. SSLClient(const char* host, int port, HttpVersion http_version = HttpVersion::v1_0);
  194. virtual ~SSLClient();
  195. private:
  196. virtual bool read_and_close_socket(socket_t sock, const Request& req, Response& res);
  197. SSL_CTX* ctx_;
  198. };
  199. #endif
  200. /*
  201. * Implementation
  202. */
  203. namespace detail {
  204. static std::vector<const char*> http_version_strings = { "HTTP/1.0", "HTTP/1.1" };
  205. template <class Fn>
  206. void split(const char* b, const char* e, char d, Fn fn)
  207. {
  208. int i = 0;
  209. int beg = 0;
  210. while (e ? (b + i != e) : (b[i] != '\0')) {
  211. if (b[i] == d) {
  212. fn(&b[beg], &b[i]);
  213. beg = i + 1;
  214. }
  215. i++;
  216. }
  217. if (i) {
  218. fn(&b[beg], &b[i]);
  219. }
  220. }
  221. class socket_reader {
  222. public:
  223. socket_reader(Stream& strm, char* fixed_buffer, size_t fixed_buffer_size)
  224. : strm_(strm)
  225. , fixed_buffer_(fixed_buffer)
  226. , fixed_buffer_size_(fixed_buffer_size) {
  227. }
  228. const char* ptr() const {
  229. if (glowable_buffer_.empty()) {
  230. return fixed_buffer_;
  231. } else {
  232. return glowable_buffer_.data();
  233. }
  234. }
  235. bool getline() {
  236. fixed_buffer_used_size_ = 0;
  237. glowable_buffer_.clear();
  238. size_t i = 0;
  239. for (;;) {
  240. char byte;
  241. auto n = strm_.read(&byte, 1);
  242. if (n < 1) {
  243. if (i == 0) {
  244. return false;
  245. } else {
  246. break;
  247. }
  248. }
  249. append(byte);
  250. if (byte == '\n') {
  251. break;
  252. }
  253. }
  254. append('\0');
  255. return true;
  256. }
  257. private:
  258. void append(char c) {
  259. if (fixed_buffer_used_size_ < fixed_buffer_size_) {
  260. fixed_buffer_[fixed_buffer_used_size_++] = c;
  261. } else {
  262. if (glowable_buffer_.empty()) {
  263. glowable_buffer_.assign(fixed_buffer_, fixed_buffer_size_);
  264. }
  265. glowable_buffer_ += c;
  266. }
  267. }
  268. Stream& strm_;
  269. char* fixed_buffer_;
  270. const size_t fixed_buffer_size_;
  271. size_t fixed_buffer_used_size_;
  272. std::string glowable_buffer_;
  273. };
  274. template <typename ...Args>
  275. inline void socket_printf(Stream& strm, const char* fmt, const Args& ...args)
  276. {
  277. char buf[BUFSIZ];
  278. auto n = snprintf(buf, BUFSIZ, fmt, args...);
  279. if (n > 0) {
  280. if (n >= BUFSIZ) {
  281. std::vector<char> glowable_buf(BUFSIZ);
  282. while (n >= static_cast<int>(glowable_buf.size())) {
  283. glowable_buf.resize(glowable_buf.size() * 2);
  284. n = snprintf(&glowable_buf[0], glowable_buf.size(), fmt, args...);
  285. }
  286. strm.write(&glowable_buf[0], n);
  287. } else {
  288. strm.write(buf, n);
  289. }
  290. }
  291. }
  292. inline int close_socket(socket_t sock)
  293. {
  294. #ifdef _WIN32
  295. return closesocket(sock);
  296. #else
  297. return close(sock);
  298. #endif
  299. }
  300. template <typename T>
  301. inline bool read_and_close_socket(socket_t sock, T callback)
  302. {
  303. SocketStream strm(sock);
  304. auto ret = callback(strm);
  305. close_socket(sock);
  306. return ret;
  307. }
  308. inline int shutdown_socket(socket_t sock)
  309. {
  310. #ifdef _WIN32
  311. return shutdown(sock, SD_BOTH);
  312. #else
  313. return shutdown(sock, SHUT_RDWR);
  314. #endif
  315. }
  316. template <typename Fn>
  317. socket_t create_socket(const char* host, int port, Fn fn, int socket_flags = 0)
  318. {
  319. #ifdef _WIN32
  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