httplib.h 41 KB

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