httplib.h 38 KB

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