httplib.h 30 KB

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