httplib.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2012 Yuji Hirose. All rights reserved.
  5. // The Boost Software License 1.0
  6. //
  7. #ifndef _CPPHTTPLIB_HTTPSLIB_H_
  8. #define _CPPHTTPLIB_HTTPSLIB_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 <sys/socket.h>
  38. typedef int socket_t;
  39. #endif
  40. #include <fstream>
  41. #include <functional>
  42. #include <map>
  43. #include <memory>
  44. #include <regex>
  45. #include <string>
  46. #include <sys/stat.h>
  47. #include <assert.h>
  48. namespace httplib
  49. {
  50. typedef std::map<std::string, std::string> Map;
  51. typedef std::multimap<std::string, std::string> MultiMap;
  52. typedef std::smatch Match;
  53. struct Request {
  54. std::string method;
  55. std::string url;
  56. MultiMap headers;
  57. std::string body;
  58. Map params;
  59. Match matches;
  60. bool has_header(const char* key) const;
  61. std::string get_header_value(const char* key) const;
  62. void set_header(const char* key, const char* val);
  63. bool has_param(const char* key) const;
  64. };
  65. struct Response {
  66. int status;
  67. MultiMap headers;
  68. std::string body;
  69. bool has_header(const char* key) const;
  70. std::string get_header_value(const char* key) const;
  71. void set_header(const char* key, const char* val);
  72. void set_redirect(const char* url);
  73. void set_content(const char* s, size_t n, const char* content_type);
  74. void set_content(const std::string& s, const char* content_type);
  75. Response() : status(-1) {}
  76. };
  77. class Server {
  78. public:
  79. typedef std::function<void (const Request&, Response&)> Handler;
  80. typedef std::function<void (const Request&, const Response&)> Logger;
  81. Server();
  82. void get(const char* pattern, Handler handler);
  83. void post(const char* pattern, Handler handler);
  84. bool set_base_dir(const char* path);
  85. void set_error_handler(Handler handler);
  86. void set_logger(Logger logger);
  87. bool listen(const char* host, int port);
  88. void stop();
  89. private:
  90. typedef std::vector<std::pair<std::regex, Handler>> Handlers;
  91. void process_request(socket_t sock);
  92. bool read_request_line(socket_t sock, Request& req);
  93. bool routing(Request& req, Response& res);
  94. bool handle_file_request(Request& req, Response& res);
  95. bool dispatch_request(Request& req, Response& res, Handlers& handlers);
  96. socket_t svr_sock_;
  97. std::string base_dir_;
  98. Handlers get_handlers_;
  99. Handlers post_handlers_;
  100. Handler error_handler_;
  101. Logger logger_;
  102. };
  103. class Client {
  104. public:
  105. Client(const char* host, int port);
  106. std::shared_ptr<Response> get(const char* url);
  107. std::shared_ptr<Response> head(const char* url);
  108. std::shared_ptr<Response> post(const char* url, const std::string& body, const char* content_type);
  109. std::shared_ptr<Response> post(const char* url, const Map& params);
  110. bool send(const Request& req, Response& res);
  111. private:
  112. bool read_response_line(socket_t sock, Response& res);
  113. const std::string host_;
  114. const int port_;
  115. };
  116. // Implementation
  117. namespace detail {
  118. template <class Fn>
  119. void split(const char* b, const char* e, char d, Fn fn)
  120. {
  121. int i = 0;
  122. int beg = 0;
  123. while (e ? (b + i != e) : (b[i] != '\0')) {
  124. if (b[i] == d) {
  125. fn(&b[beg], &b[i]);
  126. beg = i + 1;
  127. }
  128. i++;
  129. }
  130. if (i) {
  131. fn(&b[beg], &b[i]);
  132. }
  133. }
  134. inline int socket_read(socket_t sock, char* ptr, size_t size)
  135. {
  136. return recv(sock, ptr, size, 0);
  137. }
  138. inline int socket_write(socket_t sock, const char* ptr, size_t size = -1)
  139. {
  140. if (size == -1) {
  141. size = strlen(ptr);
  142. }
  143. return send(sock, ptr, size, 0);
  144. }
  145. inline bool socket_gets(socket_t sock, char* buf, int bufsiz)
  146. {
  147. // TODO: buffering for better performance
  148. size_t i = 0;
  149. for (;;) {
  150. char byte;
  151. auto n = socket_read(sock, &byte, 1);
  152. if (n < 1) {
  153. if (i == 0) {
  154. return false;
  155. } else {
  156. break;
  157. }
  158. }
  159. buf[i++] = byte;
  160. if (byte == '\n') {
  161. break;
  162. }
  163. }
  164. buf[i] = '\0';
  165. return true;
  166. }
  167. template <typename ...Args>
  168. inline void socket_printf(socket_t sock, const char* fmt, const Args& ...args)
  169. {
  170. char buf[BUFSIZ];
  171. auto n = snprintf(buf, BUFSIZ, fmt, args...);
  172. if (n > 0) {
  173. if (n >= BUFSIZ) {
  174. // TODO: buffer size is not large enough...
  175. } else {
  176. socket_write(sock, buf, n);
  177. }
  178. }
  179. }
  180. inline int close_socket(socket_t sock)
  181. {
  182. #ifdef _MSC_VER
  183. return closesocket(sock);
  184. #else
  185. return close(sock);
  186. #endif
  187. }
  188. template <typename T>
  189. inline bool read_and_close_socket(socket_t sock, T callback)
  190. {
  191. auto ret = callback(sock);
  192. close_socket(sock);
  193. return ret;
  194. }
  195. inline int shutdown_socket(socket_t sock)
  196. {
  197. #ifdef _MSC_VER
  198. return shutdown(sock, SD_BOTH);
  199. #else
  200. return shutdown(sock, SHUT_RDWR);
  201. #endif
  202. }
  203. template <typename Fn>
  204. socket_t create_socket(const char* host, int port, Fn fn)
  205. {
  206. #ifdef _MSC_VER
  207. int opt = SO_SYNCHRONOUS_NONALERT;
  208. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
  209. #endif
  210. // Get address info
  211. struct addrinfo hints;
  212. struct addrinfo *result;
  213. memset(&hints, 0, sizeof(struct addrinfo));
  214. hints.ai_family = AF_UNSPEC;
  215. hints.ai_socktype = SOCK_STREAM;
  216. hints.ai_flags = 0;
  217. hints.ai_protocol = 0;
  218. auto service = std::to_string(port);
  219. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  220. return -1;
  221. }
  222. for (auto rp = result; rp; rp = rp->ai_next) {
  223. // Create a socket
  224. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  225. if (sock == -1) {
  226. continue;
  227. }
  228. // Make 'reuse address' option available
  229. int yes = 1;
  230. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
  231. // bind or connect
  232. if (fn(sock, *rp)) {
  233. freeaddrinfo(result);
  234. return sock;
  235. }
  236. close_socket(sock);
  237. }
  238. freeaddrinfo(result);
  239. return -1;
  240. }
  241. inline socket_t create_server_socket(const char* host, int port)
  242. {
  243. return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
  244. if (::bind(sock, ai.ai_addr, ai.ai_addrlen)) {
  245. return false;
  246. }
  247. if (listen(sock, 5)) { // Listen through 5 channels
  248. return false;
  249. }
  250. return true;
  251. });
  252. }
  253. inline socket_t create_client_socket(const char* host, int port)
  254. {
  255. return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
  256. if (connect(sock, ai.ai_addr, ai.ai_addrlen)) {
  257. return false;
  258. }
  259. return true;
  260. });
  261. }
  262. inline bool is_file(const std::string& s)
  263. {
  264. struct stat st;
  265. return stat(s.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  266. }
  267. inline bool is_dir(const std::string& s)
  268. {
  269. struct stat st;
  270. return stat(s.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  271. }
  272. inline void read_file(const std::string& path, std::string& out)
  273. {
  274. std::ifstream fs(path, std::ios_base::binary);
  275. fs.seekg(0, std::ios_base::end);
  276. auto size = fs.tellg();
  277. fs.seekg(0);
  278. out.resize(static_cast<size_t>(size));
  279. fs.read(&out[0], size);
  280. }
  281. inline std::string get_file_extention(const std::string& path)
  282. {
  283. std::smatch m;
  284. auto pat = std::regex("\\.([a-zA-Z0-9]+)$");
  285. auto ret = std::regex_search(path, m, pat);
  286. std::string content_type;
  287. if (ret) {
  288. return m[1].str();
  289. }
  290. return std::string();
  291. }
  292. inline const char* get_content_type_from_file_extention(const std::string& ext)
  293. {
  294. if (ext == "html") {
  295. return "text/html";
  296. }
  297. return "text/plain";
  298. }
  299. inline const char* status_message(int status)
  300. {
  301. switch (status) {
  302. case 200: return "OK";
  303. case 400: return "Bad Request";
  304. case 404: return "Not Found";
  305. default:
  306. case 500: return "Internal Server Error";
  307. }
  308. }
  309. inline const char* get_header_value(const MultiMap& map, const char* key, const char* def)
  310. {
  311. auto it = map.find(key);
  312. if (it != map.end()) {
  313. return it->second.c_str();
  314. }
  315. return def;
  316. }
  317. inline int get_header_value_int(const MultiMap& map, const char* key, int def)
  318. {
  319. auto it = map.find(key);
  320. if (it != map.end()) {
  321. return std::stoi(it->second);
  322. }
  323. return def;
  324. }
  325. inline bool read_headers(socket_t sock, MultiMap& headers)
  326. {
  327. static std::regex re("(.+?): (.+?)\r\n");
  328. const auto BUFSIZ_HEADER = 2048;
  329. char buf[BUFSIZ_HEADER];
  330. for (;;) {
  331. if (!socket_gets(sock, buf, BUFSIZ_HEADER)) {
  332. return false;
  333. }
  334. if (!strcmp(buf, "\r\n")) {
  335. break;
  336. }
  337. std::cmatch m;
  338. if (std::regex_match(buf, m, re)) {
  339. auto key = std::string(m[1]);
  340. auto val = std::string(m[2]);
  341. headers.insert(std::make_pair(key, val));
  342. }
  343. }
  344. return true;
  345. }
  346. template <typename T>
  347. bool read_content(socket_t sock, T& x)
  348. {
  349. auto len = get_header_value_int(x.headers, "Content-Length", 0);
  350. if (len) {
  351. x.body.assign(len, 0);
  352. if (!socket_read(sock, &x.body[0], x.body.size())) {
  353. return false;
  354. }
  355. }
  356. return true;
  357. }
  358. template <typename T>
  359. inline void write_headers(socket_t sock, const T& res)
  360. {
  361. socket_write(sock, "Connection: close\r\n");
  362. for (const auto& x: res.headers) {
  363. if (x.first != "Content-Type" && x.first != "Content-Length") {
  364. socket_printf(sock, "%s: %s\r\n", x.first.c_str(), x.second.c_str());
  365. }
  366. }
  367. auto t = get_header_value(res.headers, "Content-Type", "text/plain");
  368. socket_printf(sock, "Content-Type: %s\r\n", t);
  369. socket_printf(sock, "Content-Length: %ld\r\n", res.body.size());
  370. socket_write(sock, "\r\n");
  371. }
  372. inline void write_response(socket_t sock, const Request& req, const Response& res)
  373. {
  374. socket_printf(sock, "HTTP/1.0 %d %s\r\n", res.status, status_message(res.status));
  375. write_headers(sock, res);
  376. if (!res.body.empty() && req.method != "HEAD") {
  377. socket_write(sock, res.body.c_str(), res.body.size());
  378. }
  379. }
  380. inline std::string encode_url(const std::string& s)
  381. {
  382. std::string result;
  383. for (auto i = 0; s[i]; i++) {
  384. switch (s[i]) {
  385. case ' ': result += "+"; break;
  386. case '\'': result += "%27"; break;
  387. case ',': result += "%2C"; break;
  388. case ':': result += "%3A"; break;
  389. case ';': result += "%3B"; break;
  390. default:
  391. if (s[i] < 0) {
  392. result += '%';
  393. char hex[4];
  394. size_t len = snprintf(hex, sizeof(hex), "%02X", (unsigned char)s[i]);
  395. assert(len == 2);
  396. result.append(hex, len);
  397. } else {
  398. result += s[i];
  399. }
  400. break;
  401. }
  402. }
  403. return result;
  404. }
  405. inline bool is_hex(char c, int& v)
  406. {
  407. if (0x20 <= c && isdigit(c)) {
  408. v = c - '0';
  409. return true;
  410. } else if ('A' <= c && c <= 'F') {
  411. v = c - 'A' + 10;
  412. return true;
  413. } else if ('a' <= c && c <= 'f') {
  414. v = c - 'a' + 10;
  415. return true;
  416. }
  417. return false;
  418. }
  419. inline int from_hex_to_i(const std::string& s, int i, int cnt, int& val)
  420. {
  421. val = 0;
  422. for (; s[i] && cnt; i++, cnt--) {
  423. int v = 0;
  424. if (is_hex(s[i], v)) {
  425. val = val * 16 + v;
  426. } else {
  427. break;
  428. }
  429. }
  430. return --i;
  431. }
  432. inline size_t to_utf8(int code, char* buff)
  433. {
  434. if (code < 0x0080) {
  435. buff[0] = (code & 0x7F);
  436. return 1;
  437. } else if (code < 0x0800) {
  438. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  439. buff[1] = (0x80 | (code & 0x3F));
  440. return 2;
  441. } else if (code < 0xD800) {
  442. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  443. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  444. buff[2] = (0x80 | (code & 0x3F));
  445. return 3;
  446. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  447. return 0;
  448. } else if (code < 0x10000) {
  449. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  450. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  451. buff[2] = (0x80 | (code & 0x3F));
  452. return 3;
  453. } else if (code < 0x110000) {
  454. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  455. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  456. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  457. buff[3] = (0x80 | (code & 0x3F));
  458. return 4;
  459. }
  460. // NOTREACHED
  461. return 0;
  462. }
  463. inline std::string decode_url(const std::string& s)
  464. {
  465. std::string result;
  466. for (int i = 0; s[i]; i++) {
  467. if (s[i] == '%') {
  468. i++;
  469. assert(s[i]);
  470. if (s[i] == '%') {
  471. result += s[i];
  472. } else if (s[i] == 'u') {
  473. // Unicode
  474. i++;
  475. assert(s[i]);
  476. int val = 0;
  477. i = from_hex_to_i(s, i, 4, val);
  478. char buff[4];
  479. size_t len = to_utf8(val, buff);
  480. if (len > 0) {
  481. result.append(buff, len);
  482. }
  483. } else {
  484. // HEX
  485. int val = 0;
  486. i = from_hex_to_i(s, i, 2, val);
  487. result += val;
  488. }
  489. } else if (s[i] == '+') {
  490. result += ' ';
  491. } else {
  492. result += s[i];
  493. }
  494. }
  495. return result;
  496. }
  497. inline void write_request(socket_t sock, const Request& req)
  498. {
  499. auto url = encode_url(req.url);
  500. socket_printf(sock, "%s %s HTTP/1.0\r\n", req.method.c_str(), url.c_str());
  501. write_headers(sock, req);
  502. if (!req.body.empty()) {
  503. if (req.has_header("application/x-www-form-urlencoded")) {
  504. auto str = encode_url(req.body);
  505. socket_write(sock, str.c_str(), str.size());
  506. } else {
  507. socket_write(sock, req.body.c_str(), req.body.size());
  508. }
  509. }
  510. }
  511. inline void parse_query_text(const std::string& s, Map& params)
  512. {
  513. split(&s[0], &s[s.size()], '&', [&](const char* b, const char* e) {
  514. std::string key;
  515. std::string val;
  516. split(b, e, '=', [&](const char* b, const char* e) {
  517. if (key.empty()) {
  518. key.assign(b, e);
  519. } else {
  520. val.assign(b, e);
  521. }
  522. });
  523. params[key] = detail::decode_url(val);
  524. });
  525. }
  526. #ifdef _MSC_VER
  527. class WSInit {
  528. public:
  529. WSInit() {
  530. WSADATA wsaData;
  531. WSAStartup(0x0002, &wsaData);
  532. }
  533. ~WSInit() {
  534. WSACleanup();
  535. }
  536. };
  537. static WSInit wsinit_;
  538. #endif
  539. } // namespace detail
  540. // Request implementation
  541. inline bool Request::has_header(const char* key) const
  542. {
  543. return headers.find(key) != headers.end();
  544. }
  545. inline std::string Request::get_header_value(const char* key) const
  546. {
  547. return detail::get_header_value(headers, key, "");
  548. }
  549. inline void Request::set_header(const char* key, const char* val)
  550. {
  551. headers.insert(std::make_pair(key, val));
  552. }
  553. inline bool Request::has_param(const char* key) const
  554. {
  555. return params.find(key) != params.end();
  556. }
  557. // Response implementation
  558. inline bool Response::has_header(const char* key) const
  559. {
  560. return headers.find(key) != headers.end();
  561. }
  562. inline std::string Response::get_header_value(const char* key) const
  563. {
  564. return detail::get_header_value(headers, key, "");
  565. }
  566. inline void Response::set_header(const char* key, const char* val)
  567. {
  568. headers.insert(std::make_pair(key, val));
  569. }
  570. inline void Response::set_redirect(const char* url)
  571. {
  572. set_header("Location", url);
  573. status = 302;
  574. }
  575. inline void Response::set_content(const char* s, size_t n, const char* content_type)
  576. {
  577. body.assign(s, n);
  578. set_header("Content-Type", content_type);
  579. }
  580. inline void Response::set_content(const std::string& s, const char* content_type)
  581. {
  582. body = s;
  583. set_header("Content-Type", content_type);
  584. }
  585. // HTTP server implementation
  586. inline Server::Server()
  587. : svr_sock_(-1)
  588. {
  589. }
  590. inline void Server::get(const char* pattern, Handler handler)
  591. {
  592. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  593. }
  594. inline void Server::post(const char* pattern, Handler handler)
  595. {
  596. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  597. }
  598. inline bool Server::set_base_dir(const char* path)
  599. {
  600. if (detail::is_dir(path)) {
  601. base_dir_ = path;
  602. return true;
  603. }
  604. return false;
  605. }
  606. inline void Server::set_error_handler(Handler handler)
  607. {
  608. error_handler_ = handler;
  609. }
  610. inline void Server::set_logger(Logger logger)
  611. {
  612. logger_ = logger;
  613. }
  614. inline bool Server::listen(const char* host, int port)
  615. {
  616. svr_sock_ = detail::create_server_socket(host, port);
  617. if (svr_sock_ == -1) {
  618. return false;
  619. }
  620. auto ret = true;
  621. for (;;) {
  622. socket_t sock = accept(svr_sock_, NULL, NULL);
  623. if (sock == -1) {
  624. if (svr_sock_ != -1) {
  625. detail::close_socket(svr_sock_);
  626. ret = false;
  627. } else {
  628. ; // The server socket was closed by user.
  629. }
  630. break;
  631. }
  632. // TODO: should be async
  633. detail::read_and_close_socket(sock, [this](socket_t sock) {
  634. process_request(sock);
  635. return true;
  636. });
  637. }
  638. return ret;
  639. }
  640. inline void Server::stop()
  641. {
  642. detail::shutdown_socket(svr_sock_);
  643. detail::close_socket(svr_sock_);
  644. svr_sock_ = -1;
  645. }
  646. inline bool Server::read_request_line(socket_t sock, Request& req)
  647. {
  648. const auto BUFSIZ_REQUESTLINE = 2048;
  649. char buf[BUFSIZ_REQUESTLINE];
  650. if (!detail::socket_gets(sock, buf, BUFSIZ_REQUESTLINE)) {
  651. return false;
  652. }
  653. static std::regex re("(GET|HEAD|POST) ([^?]+)(?:\\?(.+?))? HTTP/1\\.[01]\r\n");
  654. std::cmatch m;
  655. if (std::regex_match(buf, m, re)) {
  656. req.method = std::string(m[1]);
  657. req.url = detail::decode_url(m[2]);
  658. // Parse query text
  659. auto len = std::distance(m[3].first, m[3].second);
  660. if (len > 0) {
  661. detail::parse_query_text(m[3], req.params);
  662. }
  663. return true;
  664. }
  665. return false;
  666. }
  667. inline bool Server::handle_file_request(Request& req, Response& res)
  668. {
  669. if (!base_dir_.empty()) {
  670. std::string path = base_dir_ + req.url;
  671. if (!path.empty() && path.back() == '/') {
  672. path += "index.html";
  673. }
  674. if (detail::is_file(path)) {
  675. detail::read_file(path, res.body);
  676. res.set_header("Content-Type",
  677. detail::get_content_type_from_file_extention(
  678. detail::get_file_extention(path)));
  679. res.status = 200;
  680. return true;
  681. }
  682. }
  683. return false;
  684. }
  685. inline bool Server::routing(Request& req, Response& res)
  686. {
  687. if (req.method == "GET" && handle_file_request(req, res)) {
  688. return true;
  689. }
  690. if (req.method == "GET" || req.method == "HEAD") {
  691. return dispatch_request(req, res, get_handlers_);
  692. } else if (req.method == "POST") {
  693. return dispatch_request(req, res, post_handlers_);
  694. }
  695. return false;
  696. }
  697. inline bool Server::dispatch_request(Request& req, Response& res, Handlers& handlers)
  698. {
  699. for (const auto& x: handlers) {
  700. const auto& pattern = x.first;
  701. const auto& handler = x.second;
  702. if (std::regex_match(req.url, req.matches, pattern)) {
  703. handler(req, res);
  704. return true;
  705. }
  706. }
  707. return false;
  708. }
  709. inline void Server::process_request(socket_t sock)
  710. {
  711. Request req;
  712. Response res;
  713. if (!read_request_line(sock, req) ||
  714. !detail::read_headers(sock, req.headers)) {
  715. return;
  716. }
  717. if (req.method == "POST") {
  718. if (!detail::read_content(sock, req)) {
  719. return;
  720. }
  721. static std::string type = "application/x-www-form-urlencoded";
  722. if (!req.get_header_value("Content-Type").compare(0, type.size(), type)) {
  723. detail::parse_query_text(req.body, req.params);
  724. }
  725. }
  726. if (routing(req, res)) {
  727. if (res.status == -1) {
  728. res.status = 200;
  729. }
  730. } else {
  731. res.status = 404;
  732. }
  733. assert(res.status != -1);
  734. if (400 <= res.status && error_handler_) {
  735. error_handler_(req, res);
  736. }
  737. detail::write_response(sock, req, res);
  738. if (logger_) {
  739. logger_(req, res);
  740. }
  741. }
  742. // HTTP client implementation
  743. inline Client::Client(const char* host, int port)
  744. : host_(host)
  745. , port_(port)
  746. {
  747. }
  748. inline bool Client::read_response_line(socket_t sock, Response& res)
  749. {
  750. const auto BUFSIZ_RESPONSELINE = 2048;
  751. char buf[BUFSIZ_RESPONSELINE];
  752. if (!detail::socket_gets(sock, buf, BUFSIZ_RESPONSELINE)) {
  753. return false;
  754. }
  755. const static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
  756. std::cmatch m;
  757. if (std::regex_match(buf, m, re)) {
  758. res.status = std::stoi(std::string(m[1]));
  759. }
  760. return true;
  761. }
  762. inline bool Client::send(const Request& req, Response& res)
  763. {
  764. auto sock = detail::create_client_socket(host_.c_str(), port_);
  765. if (sock == -1) {
  766. return false;
  767. }
  768. return detail::read_and_close_socket(sock, [&](socket_t sock) {
  769. // Send request
  770. detail::write_request(sock, req);
  771. // Receive response
  772. if (!read_response_line(sock, res) ||
  773. !detail::read_headers(sock, res.headers)) {
  774. return false;
  775. }
  776. if (req.method != "HEAD") {
  777. if (!detail::read_content(sock, res)) {
  778. return false;
  779. }
  780. }
  781. return true;
  782. });
  783. }
  784. inline std::shared_ptr<Response> Client::get(const char* url)
  785. {
  786. Request req;
  787. req.method = "GET";
  788. req.url = url;
  789. auto res = std::make_shared<Response>();
  790. return send(req, *res) ? res : nullptr;
  791. }
  792. inline std::shared_ptr<Response> Client::head(const char* url)
  793. {
  794. Request req;
  795. req.method = "HEAD";
  796. req.url = url;
  797. auto res = std::make_shared<Response>();
  798. return send(req, *res) ? res : nullptr;
  799. }
  800. inline std::shared_ptr<Response> Client::post(
  801. const char* url, const std::string& body, const char* content_type)
  802. {
  803. Request req;
  804. req.method = "POST";
  805. req.url = url;
  806. req.set_header("Content-Type", content_type);
  807. req.body = body;
  808. auto res = std::make_shared<Response>();
  809. return send(req, *res) ? res : nullptr;
  810. }
  811. inline std::shared_ptr<Response> Client::post(
  812. const char* url, const Map& params)
  813. {
  814. std::string query;
  815. for (auto it = params.begin(); it != params.end(); ++it) {
  816. if (it != params.begin()) {
  817. query += "&";
  818. }
  819. query += it->first;
  820. query += "=";
  821. query += it->second;
  822. }
  823. return post(url, query, "application/x-www-form-urlencoded");
  824. }
  825. } // namespace httplib
  826. #endif
  827. // vim: et ts=4 sw=4 cin cino={1s ff=unix