httplib.h 22 KB

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