httplib.h 22 KB

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