httplib.h 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2017 Yuji Hirose. All rights reserved.
  5. // The Boost Software License 1.0
  6. //
  7. #ifndef _CPPHTTPLIB_HTTPLIB_H_
  8. #define _CPPHTTPLIB_HTTPLIB_H_
  9. #ifdef _WIN32
  10. #ifndef _CRT_SECURE_NO_WARNINGS
  11. #define _CRT_SECURE_NO_WARNINGS
  12. #endif
  13. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  14. #define _CRT_NONSTDC_NO_DEPRECATE
  15. #endif
  16. #if defined(_MSC_VER) && _MSC_VER < 1900
  17. #define snprintf _snprintf_s
  18. #endif
  19. #ifndef S_ISREG
  20. #define S_ISREG(m) (((m)&S_IFREG)==S_IFREG)
  21. #endif
  22. #ifndef S_ISDIR
  23. #define S_ISDIR(m) (((m)&S_IFDIR)==S_IFDIR)
  24. #endif
  25. #include <fcntl.h>
  26. #include <io.h>
  27. #include <winsock2.h>
  28. #include <ws2tcpip.h>
  29. #undef min
  30. #undef max
  31. typedef SOCKET socket_t;
  32. #else
  33. #include <pthread.h>
  34. #include <unistd.h>
  35. #include <netdb.h>
  36. #include <cstring>
  37. #include <netinet/in.h>
  38. #include <arpa/inet.h>
  39. #include <signal.h>
  40. #include <sys/socket.h>
  41. typedef int socket_t;
  42. #endif
  43. #include <fstream>
  44. #include <functional>
  45. #include <map>
  46. #include <memory>
  47. #include <regex>
  48. #include <string>
  49. #include <sys/stat.h>
  50. #include <assert.h>
  51. #ifdef __has_include
  52. #if __has_include(<openssl/ssl.h>)
  53. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  54. #define CPPHTTPLIB_OPENSSL_SUPPORT
  55. #endif
  56. #endif
  57. #endif
  58. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  59. #include <openssl/ssl.h>
  60. #endif
  61. namespace httplib
  62. {
  63. namespace detail {
  64. struct ci {
  65. bool operator() (const std::string & s1, const std::string & s2) const {
  66. return std::lexicographical_compare(
  67. s1.begin(), s1.end(),
  68. s2.begin(), s2.end(),
  69. [](char c1, char c2) {
  70. return std::tolower(c1) < std::tolower(c2);
  71. });
  72. }
  73. };
  74. } // namespace detail
  75. enum class HttpVersion { v1_0 = 0, v1_1 };
  76. typedef std::multimap<std::string, std::string, detail::ci> Headers;
  77. template<typename uint64_t, typename... Args>
  78. std::pair<std::string, std::string> make_range_header(uint64_t value, Args... args);
  79. typedef std::multimap<std::string, std::string> Params;
  80. typedef std::smatch Match;
  81. typedef std::function<void (uint64_t current, uint64_t total)> Progress;
  82. struct MultipartFile {
  83. std::string filename;
  84. std::string content_type;
  85. size_t offset = 0;
  86. size_t length = 0;
  87. };
  88. typedef std::multimap<std::string, MultipartFile> MultipartFiles;
  89. struct Request {
  90. std::string method;
  91. std::string path;
  92. Headers headers;
  93. std::string body;
  94. Params params;
  95. MultipartFiles files;
  96. Match matches;
  97. Progress progress;
  98. bool has_header(const char* key) const;
  99. std::string get_header_value(const char* key) const;
  100. bool has_param(const char* key) const;
  101. std::string get_param_value(const char* key) const;
  102. bool has_file(const char* key) const;
  103. MultipartFile get_file_value(const char* key) const;
  104. };
  105. struct Response {
  106. int status;
  107. Headers headers;
  108. std::string body;
  109. bool has_header(const char* key) const;
  110. std::string get_header_value(const char* key) const;
  111. void set_header(const char* key, const char* val);
  112. void set_redirect(const char* url);
  113. void set_content(const char* s, size_t n, const char* content_type);
  114. void set_content(const std::string& s, const char* content_type);
  115. Response() : status(-1) {}
  116. };
  117. class Stream {
  118. public:
  119. virtual ~Stream() {}
  120. virtual int read(char* ptr, size_t size) = 0;
  121. virtual int write(const char* ptr, size_t size1) = 0;
  122. virtual int write(const char* ptr) = 0;
  123. template <typename ...Args>
  124. void write_format(const char* fmt, const Args& ...args);
  125. };
  126. class SocketStream : public Stream {
  127. public:
  128. SocketStream(socket_t sock);
  129. virtual ~SocketStream();
  130. virtual int read(char* ptr, size_t size);
  131. virtual int write(const char* ptr, size_t size);
  132. virtual int write(const char* ptr);
  133. private:
  134. socket_t sock_;
  135. };
  136. class Server {
  137. public:
  138. typedef std::function<void (const Request&, Response&)> Handler;
  139. typedef std::function<void (const Request&, const Response&)> Logger;
  140. Server();
  141. virtual ~Server();
  142. Server& get(const char* pattern, Handler handler);
  143. Server& post(const char* pattern, Handler handler);
  144. bool set_base_dir(const char* path);
  145. void set_error_handler(Handler handler);
  146. void set_logger(Logger logger);
  147. bool listen(const char* host, int port, int socket_flags = 0);
  148. void stop();
  149. protected:
  150. void process_request(Stream& strm);
  151. private:
  152. typedef std::vector<std::pair<std::regex, Handler>> Handlers;
  153. bool routing(Request& req, Response& res);
  154. bool handle_file_request(Request& req, Response& res);
  155. bool dispatch_request(Request& req, Response& res, Handlers& handlers);
  156. bool read_request_line(Stream& strm, Request& req);
  157. void write_response(Stream& strm, const Request& req, Response& res);
  158. virtual bool read_and_close_socket(socket_t sock);
  159. socket_t svr_sock_;
  160. std::string base_dir_;
  161. Handlers get_handlers_;
  162. Handlers post_handlers_;
  163. Handler error_handler_;
  164. Logger logger_;
  165. };
  166. class Client {
  167. public:
  168. Client(const char* host, int port, HttpVersion http_version = HttpVersion::v1_0);
  169. virtual ~Client();
  170. std::shared_ptr<Response> get(const char* path, Progress progress = nullptr);
  171. std::shared_ptr<Response> get(const char* path, const Headers& headers, Progress progress = nullptr);
  172. std::shared_ptr<Response> head(const char* path);
  173. std::shared_ptr<Response> head(const char* path, const Headers& headers);
  174. std::shared_ptr<Response> post(const char* path, const std::string& body, const char* content_type);
  175. std::shared_ptr<Response> post(const char* path, const Headers& headers, const std::string& body, const char* content_type);
  176. std::shared_ptr<Response> post(const char* path, const Params& params);
  177. std::shared_ptr<Response> post(const char* path, const Headers& headers, const Params& params);
  178. bool send(const Request& req, Response& res);
  179. protected:
  180. bool process_request(Stream& strm, const Request& req, Response& res);
  181. const std::string host_;
  182. const int port_;
  183. const HttpVersion http_version_;
  184. const std::string host_and_port_;
  185. private:
  186. bool read_response_line(Stream& strm, Response& res);
  187. void write_request(Stream& strm, const Request& req, const char* ver);
  188. virtual bool read_and_close_socket(socket_t sock, const Request& req, Response& res);
  189. };
  190. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  191. class SSLSocketStream : public Stream {
  192. public:
  193. SSLSocketStream(SSL* ssl);
  194. virtual ~SSLSocketStream();
  195. virtual int read(char* ptr, size_t size);
  196. virtual int write(const char* ptr, size_t size);
  197. virtual int write(const char* ptr);
  198. private:
  199. SSL* ssl_;
  200. };
  201. class SSLServer : public Server {
  202. public:
  203. SSLServer(const char* cert_path, const char* private_key_path);
  204. virtual ~SSLServer();
  205. private:
  206. virtual bool read_and_close_socket(socket_t sock);
  207. SSL_CTX* ctx_;
  208. };
  209. class SSLClient : public Client {
  210. public:
  211. SSLClient(const char* host, int port, HttpVersion http_version = HttpVersion::v1_0);
  212. virtual ~SSLClient();
  213. private:
  214. virtual bool read_and_close_socket(socket_t sock, const Request& req, Response& res);
  215. SSL_CTX* ctx_;
  216. };
  217. #endif
  218. /*
  219. * Implementation
  220. */
  221. namespace detail {
  222. static std::vector<const char*> http_version_strings = { "HTTP/1.0", "HTTP/1.1" };
  223. template <class Fn>
  224. void split(const char* b, const char* e, char d, Fn fn)
  225. {
  226. int i = 0;
  227. int beg = 0;
  228. while (e ? (b + i != e) : (b[i] != '\0')) {
  229. if (b[i] == d) {
  230. fn(&b[beg], &b[i]);
  231. beg = i + 1;
  232. }
  233. i++;
  234. }
  235. if (i) {
  236. fn(&b[beg], &b[i]);
  237. }
  238. }
  239. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  240. // to store data. The call can set memory on stack for performance.
  241. class stream_line_reader {
  242. public:
  243. stream_line_reader(Stream& strm, char* fixed_buffer, size_t fixed_buffer_size)
  244. : strm_(strm)
  245. , fixed_buffer_(fixed_buffer)
  246. , fixed_buffer_size_(fixed_buffer_size) {
  247. }
  248. const char* ptr() const {
  249. if (glowable_buffer_.empty()) {
  250. return fixed_buffer_;
  251. } else {
  252. return glowable_buffer_.data();
  253. }
  254. }
  255. bool getline() {
  256. fixed_buffer_used_size_ = 0;
  257. glowable_buffer_.clear();
  258. size_t i = 0;
  259. for (;;) {
  260. char byte;
  261. auto n = strm_.read(&byte, 1);
  262. if (n < 1) {
  263. if (i == 0) {
  264. return false;
  265. } else {
  266. break;
  267. }
  268. }
  269. append(byte);
  270. if (byte == '\n') {
  271. break;
  272. }
  273. }
  274. append('\0');
  275. return true;
  276. }
  277. private:
  278. void append(char c) {
  279. if (fixed_buffer_used_size_ < fixed_buffer_size_) {
  280. fixed_buffer_[fixed_buffer_used_size_++] = c;
  281. } else {
  282. if (glowable_buffer_.empty()) {
  283. glowable_buffer_.assign(fixed_buffer_, fixed_buffer_size_);
  284. }
  285. glowable_buffer_ += c;
  286. }
  287. }
  288. Stream& strm_;
  289. char* fixed_buffer_;
  290. const size_t fixed_buffer_size_;
  291. size_t fixed_buffer_used_size_;
  292. std::string glowable_buffer_;
  293. };
  294. inline int close_socket(socket_t sock)
  295. {
  296. #ifdef _WIN32
  297. return closesocket(sock);
  298. #else
  299. return close(sock);
  300. #endif
  301. }
  302. template <typename T>
  303. inline bool read_and_close_socket(socket_t sock, T callback)
  304. {
  305. SocketStream strm(sock);
  306. auto ret = callback(strm);
  307. close_socket(sock);
  308. return ret;
  309. }
  310. inline int shutdown_socket(socket_t sock)
  311. {
  312. #ifdef _WIN32
  313. return shutdown(sock, SD_BOTH);
  314. #else
  315. return shutdown(sock, SHUT_RDWR);
  316. #endif
  317. }
  318. template <typename Fn>
  319. socket_t create_socket(const char* host, int port, Fn fn, int socket_flags = 0)
  320. {
  321. #ifdef _WIN32
  322. #define SO_SYNCHRONOUS_NONALERT 0x20
  323. #define SO_OPENTYPE 0x7008
  324. int opt = SO_SYNCHRONOUS_NONALERT;
  325. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
  326. #endif
  327. // Get address info
  328. struct addrinfo hints;
  329. struct addrinfo *result;
  330. memset(&hints, 0, sizeof(struct addrinfo));
  331. hints.ai_family = AF_UNSPEC;
  332. hints.ai_socktype = SOCK_STREAM;
  333. hints.ai_flags = socket_flags;
  334. hints.ai_protocol = 0;
  335. auto service = std::to_string(port);
  336. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  337. return -1;
  338. }
  339. for (auto rp = result; rp; rp = rp->ai_next) {
  340. // Create a socket
  341. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  342. if (sock == -1) {
  343. continue;
  344. }
  345. // Make 'reuse address' option available
  346. int yes = 1;
  347. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
  348. // bind or connect
  349. if (fn(sock, *rp)) {
  350. freeaddrinfo(result);
  351. return sock;
  352. }
  353. close_socket(sock);
  354. }
  355. freeaddrinfo(result);
  356. return -1;
  357. }
  358. inline socket_t create_server_socket(const char* host, int port, int socket_flags)
  359. {
  360. return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
  361. if (::bind(sock, ai.ai_addr, ai.ai_addrlen)) {
  362. return false;
  363. }
  364. if (listen(sock, 5)) { // Listen through 5 channels
  365. return false;
  366. }
  367. return true;
  368. }, socket_flags);
  369. }
  370. inline socket_t create_client_socket(const char* host, int port)
  371. {
  372. return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
  373. if (connect(sock, ai.ai_addr, ai.ai_addrlen)) {
  374. return false;
  375. }
  376. return true;
  377. });
  378. }
  379. inline bool is_file(const std::string& path)
  380. {
  381. struct stat st;
  382. return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  383. }
  384. inline bool is_dir(const std::string& path)
  385. {
  386. struct stat st;
  387. return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  388. }
  389. inline bool is_valid_path(const std::string& path) {
  390. size_t level = 0;
  391. size_t i = 0;
  392. // Skip slash
  393. while (i < path.size() && path[i] == '/') {
  394. i++;
  395. }
  396. while (i < path.size()) {
  397. // Read component
  398. auto beg = i;
  399. while (i < path.size() && path[i] != '/') {
  400. i++;
  401. }
  402. auto len = i - beg;
  403. assert(len > 0);
  404. if (!path.compare(beg, len, ".")) {
  405. ;
  406. } else if (!path.compare(beg, len, "..")) {
  407. if (level == 0) {
  408. return false;
  409. }
  410. level--;
  411. } else {
  412. level++;
  413. }
  414. // Skip slash
  415. while (i < path.size() && path[i] == '/') {
  416. i++;
  417. }
  418. }
  419. return true;
  420. }
  421. inline void read_file(const std::string& path, std::string& out)
  422. {
  423. std::ifstream fs(path, std::ios_base::binary);
  424. fs.seekg(0, std::ios_base::end);
  425. auto size = fs.tellg();
  426. fs.seekg(0);
  427. out.resize(static_cast<size_t>(size));
  428. fs.read(&out[0], size);
  429. }
  430. inline std::string file_extension(const std::string& path)
  431. {
  432. std::smatch m;
  433. auto pat = std::regex("\\.([a-zA-Z0-9]+)$");
  434. if (std::regex_search(path, m, pat)) {
  435. return m[1].str();
  436. }
  437. return std::string();
  438. }
  439. inline const char* content_type(const std::string& path)
  440. {
  441. auto ext = file_extension(path);
  442. if (ext == "txt") {
  443. return "text/plain";
  444. } else if (ext == "html") {
  445. return "text/html";
  446. } else if (ext == "js") {
  447. return "text/javascript";
  448. } else if (ext == "css") {
  449. return "text/css";
  450. } else if (ext == "xml") {
  451. return "text/xml";
  452. } else if (ext == "jpeg" || ext == "jpg") {
  453. return "image/jpg";
  454. } else if (ext == "png") {
  455. return "image/png";
  456. } else if (ext == "gif") {
  457. return "image/gif";
  458. } else if (ext == "svg") {
  459. return "image/svg+xml";
  460. } else if (ext == "ico") {
  461. return "image/x-icon";
  462. } else if (ext == "json") {
  463. return "application/json";
  464. } else if (ext == "pdf") {
  465. return "application/pdf";
  466. } else if (ext == "xhtml") {
  467. return "application/xhtml+xml";
  468. }
  469. return nullptr;
  470. }
  471. inline const char* status_message(int status)
  472. {
  473. switch (status) {
  474. case 200: return "OK";
  475. case 400: return "Bad Request";
  476. case 404: return "Not Found";
  477. default:
  478. case 500: return "Internal Server Error";
  479. }
  480. }
  481. inline const char* get_header_value(const Headers& headers, const char* key, const char* def)
  482. {
  483. auto it = headers.find(key);
  484. if (it != headers.end()) {
  485. return it->second.c_str();
  486. }
  487. return def;
  488. }
  489. inline int get_header_value_int(const Headers& headers, const char* key, int def)
  490. {
  491. auto it = headers.find(key);
  492. if (it != headers.end()) {
  493. return std::stoi(it->second);
  494. }
  495. return def;
  496. }
  497. inline bool read_headers(Stream& strm, Headers& headers)
  498. {
  499. static std::regex re(R"((.+?):\s*(.+?)\s*\r\n)");
  500. const auto bufsiz = 2048;
  501. char buf[bufsiz];
  502. stream_line_reader reader(strm, buf, bufsiz);
  503. for (;;) {
  504. if (!reader.getline()) {
  505. return false;
  506. }
  507. if (!strcmp(reader.ptr(), "\r\n")) {
  508. break;
  509. }
  510. std::cmatch m;
  511. if (std::regex_match(reader.ptr(), m, re)) {
  512. auto key = std::string(m[1]);
  513. auto val = std::string(m[2]);
  514. headers.emplace(key, val);
  515. }
  516. }
  517. return true;
  518. }
  519. template <typename T>
  520. bool read_content_with_length(Stream& strm, T& x, size_t len, Progress progress)
  521. {
  522. x.body.assign(len, 0);
  523. size_t r = 0;
  524. while (r < len){
  525. auto r_incr = strm.read(&x.body[r], len - r);
  526. if (r_incr <= 0) {
  527. return false;
  528. }
  529. r += r_incr;
  530. if (progress) {
  531. progress(r, len);
  532. }
  533. }
  534. return true;
  535. }
  536. template <typename T>
  537. bool read_content_without_length(Stream& strm, T& x)
  538. {
  539. for (;;) {
  540. char byte;
  541. auto n = strm.read(&byte, 1);
  542. if (n < 0) {
  543. return false;
  544. } else if (n == 0) {
  545. break;
  546. }
  547. x.body += byte;
  548. }
  549. return true;
  550. }
  551. template <typename T>
  552. bool read_content_chunked(Stream& strm, T& x)
  553. {
  554. const auto bufsiz = 16;
  555. char buf[bufsiz];
  556. stream_line_reader reader(strm, buf, bufsiz);
  557. if (!reader.getline()) {
  558. return false;
  559. }
  560. auto chunk_len = std::stoi(reader.ptr(), 0, 16);
  561. while (chunk_len > 0){
  562. std::string chunk(chunk_len, 0);
  563. auto n = strm.read(&chunk[0], chunk_len);
  564. if (n <= 0) {
  565. return false;
  566. }
  567. if (!reader.getline()) {
  568. return false;
  569. }
  570. if (strcmp(reader.ptr(), "\r\n")) {
  571. break;
  572. }
  573. x.body += chunk;
  574. if (!reader.getline()) {
  575. return false;
  576. }
  577. chunk_len = std::stoi(reader.ptr(), 0, 16);
  578. }
  579. return true;
  580. }
  581. template <typename T>
  582. bool read_content(Stream& strm, T& x, Progress progress = Progress())
  583. {
  584. auto len = get_header_value_int(x.headers, "Content-Length", 0);
  585. if (len) {
  586. return read_content_with_length(strm, x, len, progress);
  587. } else {
  588. auto encoding = get_header_value(x.headers, "Transfer-Encoding", "");
  589. if (!strcmp(encoding, "chunked")) {
  590. return read_content_chunked(strm, x);
  591. } else {
  592. return read_content_without_length(strm, x);
  593. }
  594. }
  595. return true;
  596. }
  597. template <typename T>
  598. inline void write_headers(Stream& strm, const T& info)
  599. {
  600. strm.write("Connection: close\r\n");
  601. for (const auto& x: info.headers) {
  602. if (x.first != "Content-Type" && x.first != "Content-Length") {
  603. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  604. }
  605. }
  606. auto t = get_header_value(info.headers, "Content-Type", "text/plain");
  607. strm.write_format("Content-Type: %s\r\n", t);
  608. strm.write_format("Content-Length: %ld\r\n", info.body.size());
  609. }
  610. inline std::string encode_url(const std::string& s)
  611. {
  612. std::string result;
  613. for (auto i = 0; s[i]; i++) {
  614. switch (s[i]) {
  615. case ' ': result += "+"; break;
  616. case '\'': result += "%27"; break;
  617. case ',': result += "%2C"; break;
  618. case ':': result += "%3A"; break;
  619. case ';': result += "%3B"; break;
  620. default:
  621. if (s[i] < 0) {
  622. result += '%';
  623. char hex[4];
  624. size_t len = snprintf(hex, sizeof(hex) - 1, "%02X", (unsigned char)s[i]);
  625. assert(len == 2);
  626. result.append(hex, len);
  627. } else {
  628. result += s[i];
  629. }
  630. break;
  631. }
  632. }
  633. return result;
  634. }
  635. inline bool is_hex(char c, int& v)
  636. {
  637. if (0x20 <= c && isdigit(c)) {
  638. v = c - '0';
  639. return true;
  640. } else if ('A' <= c && c <= 'F') {
  641. v = c - 'A' + 10;
  642. return true;
  643. } else if ('a' <= c && c <= 'f') {
  644. v = c - 'a' + 10;
  645. return true;
  646. }
  647. return false;
  648. }
  649. inline bool from_hex_to_i(const std::string& s, int i, int cnt, int& val)
  650. {
  651. val = 0;
  652. for (; cnt; i++, cnt--) {
  653. if (!s[i]) {
  654. return false;
  655. }
  656. int v = 0;
  657. if (is_hex(s[i], v)) {
  658. val = val * 16 + v;
  659. } else {
  660. return false;
  661. }
  662. }
  663. return true;
  664. }
  665. inline size_t to_utf8(int code, char* buff)
  666. {
  667. if (code < 0x0080) {
  668. buff[0] = (code & 0x7F);
  669. return 1;
  670. } else if (code < 0x0800) {
  671. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  672. buff[1] = (0x80 | (code & 0x3F));
  673. return 2;
  674. } else if (code < 0xD800) {
  675. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  676. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  677. buff[2] = (0x80 | (code & 0x3F));
  678. return 3;
  679. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  680. return 0;
  681. } else if (code < 0x10000) {
  682. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  683. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  684. buff[2] = (0x80 | (code & 0x3F));
  685. return 3;
  686. } else if (code < 0x110000) {
  687. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  688. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  689. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  690. buff[3] = (0x80 | (code & 0x3F));
  691. return 4;
  692. }
  693. // NOTREACHED
  694. return 0;
  695. }
  696. inline std::string decode_url(const std::string& s)
  697. {
  698. std::string result;
  699. for (int i = 0; s[i]; i++) {
  700. if (s[i] == '%') {
  701. if (s[i + 1] && s[i + 1] == 'u') {
  702. int val = 0;
  703. if (from_hex_to_i(s, i + 2, 4, val)) {
  704. // 4 digits Unicode codes
  705. char buff[4];
  706. size_t len = to_utf8(val, buff);
  707. if (len > 0) {
  708. result.append(buff, len);
  709. }
  710. i += 5; // 'u0000'
  711. } else {
  712. result += s[i];
  713. }
  714. } else {
  715. int val = 0;
  716. if (from_hex_to_i(s, i + 1, 2, val)) {
  717. // 2 digits hex codes
  718. result += val;
  719. i += 2; // '00'
  720. } else {
  721. result += s[i];
  722. }
  723. }
  724. } else if (s[i] == '+') {
  725. result += ' ';
  726. } else {
  727. result += s[i];
  728. }
  729. }
  730. return result;
  731. }
  732. inline void parse_query_text(const std::string& s, Params& params)
  733. {
  734. split(&s[0], &s[s.size()], '&', [&](const char* b, const char* e) {
  735. std::string key;
  736. std::string val;
  737. split(b, e, '=', [&](const char* b, const char* e) {
  738. if (key.empty()) {
  739. key.assign(b, e);
  740. } else {
  741. val.assign(b, e);
  742. }
  743. });
  744. params.emplace(key, decode_url(val));
  745. });
  746. }
  747. inline bool parse_multipart_boundary(const std::string& content_type, std::string& boundary)
  748. {
  749. auto pos = content_type.find("boundary=");
  750. if (pos == std::string::npos) {
  751. return false;
  752. }
  753. boundary = content_type.substr(pos + 9);
  754. return true;
  755. }
  756. inline bool parse_multipart_formdata(
  757. const std::string& boundary, const std::string& body, MultipartFiles& files)
  758. {
  759. static std::string dash = "--";
  760. static std::string crlf = "\r\n";
  761. static std::regex re_content_type(
  762. "Content-Type: (.*?)");
  763. static std::regex re_content_disposition(
  764. "Content-Disposition: form-data; name=\"(.*?)\"(?:; filename=\"(.*?)\")?");
  765. auto dash_boundary = dash + boundary;
  766. auto pos = body.find(dash_boundary);
  767. if (pos != 0) {
  768. return false;
  769. }
  770. pos += dash_boundary.size();
  771. auto next_pos = body.find(crlf, pos);
  772. if (next_pos == std::string::npos) {
  773. return false;
  774. }
  775. pos = next_pos + crlf.size();
  776. while (pos < body.size()) {
  777. next_pos = body.find(crlf, pos);
  778. if (next_pos == std::string::npos) {
  779. return false;
  780. }
  781. std::string name;
  782. MultipartFile file;
  783. auto header = body.substr(pos, (next_pos - pos));
  784. while (pos != next_pos) {
  785. std::smatch m;
  786. if (std::regex_match(header, m, re_content_type)) {
  787. file.content_type = m[1];
  788. } else if (std::regex_match(header, m, re_content_disposition)) {
  789. name = m[1];
  790. file.filename = m[2];
  791. }
  792. pos = next_pos + crlf.size();
  793. next_pos = body.find(crlf, pos);
  794. if (next_pos == std::string::npos) {
  795. return false;
  796. }
  797. header = body.substr(pos, (next_pos - pos));
  798. }
  799. pos = next_pos + crlf.size();
  800. next_pos = body.find(crlf + dash_boundary, pos);
  801. if (next_pos == std::string::npos) {
  802. return false;
  803. }
  804. file.offset = pos;
  805. file.length = next_pos - pos;
  806. pos = next_pos + crlf.size() + dash_boundary.size();
  807. next_pos = body.find(crlf, pos);
  808. if (next_pos == std::string::npos) {
  809. return false;
  810. }
  811. files.emplace(name, file);
  812. pos = next_pos + crlf.size();
  813. }
  814. return true;
  815. }
  816. inline std::string to_lower(const char* beg, const char* end)
  817. {
  818. std::string out;
  819. auto it = beg;
  820. while (it != end) {
  821. out += ::tolower(*it);
  822. it++;
  823. }
  824. return out;
  825. }
  826. inline void make_range_header_core(std::string&) {}
  827. template<typename uint64_t>
  828. inline void make_range_header_core(std::string& field, uint64_t value)
  829. {
  830. if (!field.empty()) {
  831. field += ", ";
  832. }
  833. field += std::to_string(value) + "-";
  834. }
  835. template<typename uint64_t, typename... Args>
  836. inline void make_range_header_core(std::string& field, uint64_t value1, uint64_t value2, Args... args)
  837. {
  838. if (!field.empty()) {
  839. field += ", ";
  840. }
  841. field += std::to_string(value1) + "-" + std::to_string(value2);
  842. make_range_header_core(field, args...);
  843. }
  844. #ifdef _WIN32
  845. class WSInit {
  846. public:
  847. WSInit() {
  848. WSADATA wsaData;
  849. WSAStartup(0x0002, &wsaData);
  850. }
  851. ~WSInit() {
  852. WSACleanup();
  853. }
  854. };
  855. static WSInit wsinit_;
  856. #endif
  857. } // namespace detail
  858. // Header utilities
  859. template<typename uint64_t, typename... Args>
  860. inline std::pair<std::string, std::string> make_range_header(uint64_t value, Args... args)
  861. {
  862. std::string field;
  863. detail::make_range_header_core(field, value, args...);
  864. field.insert(0, "bytes=");
  865. return std::make_pair("Range", field);
  866. }
  867. // Request implementation
  868. inline bool Request::has_header(const char* key) const
  869. {
  870. return headers.find(key) != headers.end();
  871. }
  872. inline std::string Request::get_header_value(const char* key) const
  873. {
  874. return detail::get_header_value(headers, key, "");
  875. }
  876. inline bool Request::has_param(const char* key) const
  877. {
  878. return params.find(key) != params.end();
  879. }
  880. inline std::string Request::get_param_value(const char* key) const
  881. {
  882. auto it = params.find(key);
  883. if (it != params.end()) {
  884. return it->second;
  885. }
  886. return std::string();
  887. }
  888. inline bool Request::has_file(const char* key) const
  889. {
  890. return files.find(key) != files.end();
  891. }
  892. inline MultipartFile Request::get_file_value(const char* key) const
  893. {
  894. auto it = files.find(key);
  895. if (it != files.end()) {
  896. return it->second;
  897. }
  898. return MultipartFile();
  899. }
  900. // Response implementation
  901. inline bool Response::has_header(const char* key) const
  902. {
  903. return headers.find(key) != headers.end();
  904. }
  905. inline std::string Response::get_header_value(const char* key) const
  906. {
  907. return detail::get_header_value(headers, key, "");
  908. }
  909. inline void Response::set_header(const char* key, const char* val)
  910. {
  911. headers.emplace(key, val);
  912. }
  913. inline void Response::set_redirect(const char* url)
  914. {
  915. set_header("Location", url);
  916. status = 302;
  917. }
  918. inline void Response::set_content(const char* s, size_t n, const char* content_type)
  919. {
  920. body.assign(s, n);
  921. set_header("Content-Type", content_type);
  922. }
  923. inline void Response::set_content(const std::string& s, const char* content_type)
  924. {
  925. body = s;
  926. set_header("Content-Type", content_type);
  927. }
  928. // Rstream implementation
  929. template <typename ...Args>
  930. inline void Stream::write_format(const char* fmt, const Args& ...args)
  931. {
  932. const auto bufsiz = 2048;
  933. char buf[bufsiz];
  934. auto n = snprintf(buf, bufsiz - 1, fmt, args...);
  935. if (n > 0) {
  936. if (n >= bufsiz - 1) {
  937. std::vector<char> glowable_buf(bufsiz);
  938. while (n >= static_cast<int>(glowable_buf.size() - 1)) {
  939. glowable_buf.resize(glowable_buf.size() * 2);
  940. #if defined(_MSC_VER) && _MSC_VER < 1900
  941. n = _snprintf_s(&glowable_buf[0], glowable_buf.size(), glowable_buf.size() - 1, fmt, args...);
  942. #else
  943. n = snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...);
  944. #endif
  945. }
  946. write(&glowable_buf[0], n);
  947. } else {
  948. write(buf, n);
  949. }
  950. }
  951. }
  952. // Socket stream implementation
  953. inline SocketStream::SocketStream(socket_t sock): sock_(sock)
  954. {
  955. }
  956. inline SocketStream::~SocketStream()
  957. {
  958. }
  959. inline int SocketStream::read(char* ptr, size_t size)
  960. {
  961. return recv(sock_, ptr, size, 0);
  962. }
  963. inline int SocketStream::write(const char* ptr, size_t size)
  964. {
  965. return send(sock_, ptr, size, 0);
  966. }
  967. inline int SocketStream::write(const char* ptr)
  968. {
  969. return write(ptr, strlen(ptr));
  970. }
  971. // HTTP server implementation
  972. inline Server::Server()
  973. : svr_sock_(-1)
  974. {
  975. #ifndef _WIN32
  976. signal(SIGPIPE, SIG_IGN);
  977. #endif
  978. }
  979. inline Server::~Server()
  980. {
  981. }
  982. inline Server& Server::get(const char* pattern, Handler handler)
  983. {
  984. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  985. return *this;
  986. }
  987. inline Server& Server::post(const char* pattern, Handler handler)
  988. {
  989. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  990. return *this;
  991. }
  992. inline bool Server::set_base_dir(const char* path)
  993. {
  994. if (detail::is_dir(path)) {
  995. base_dir_ = path;
  996. return true;
  997. }
  998. return false;
  999. }
  1000. inline void Server::set_error_handler(Handler handler)
  1001. {
  1002. error_handler_ = handler;
  1003. }
  1004. inline void Server::set_logger(Logger logger)
  1005. {
  1006. logger_ = logger;
  1007. }
  1008. inline bool Server::listen(const char* host, int port, int socket_flags)
  1009. {
  1010. svr_sock_ = detail::create_server_socket(host, port, socket_flags);
  1011. if (svr_sock_ == -1) {
  1012. return false;
  1013. }
  1014. auto ret = true;
  1015. for (;;) {
  1016. socket_t sock = accept(svr_sock_, NULL, NULL);
  1017. if (sock == -1) {
  1018. if (svr_sock_ != -1) {
  1019. detail::close_socket(svr_sock_);
  1020. ret = false;
  1021. } else {
  1022. ; // The server socket was closed by user.
  1023. }
  1024. break;
  1025. }
  1026. // TODO: should be async
  1027. read_and_close_socket(sock);
  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