httplib.h 23 KB

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