httplib.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2012 Yuji Hirose. All rights reserved.
  5. // The Boost Software License 1.0
  6. //
  7. #ifndef HTTPSVRKIT_H
  8. #define HTTPSVRKIT_H
  9. #ifdef _WIN32
  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. #include <fcntl.h>
  19. #include <io.h>
  20. #include <winsock2.h>
  21. typedef SOCKET socket_t;
  22. #else
  23. #include <pthread.h>
  24. #include <unistd.h>
  25. #include <netdb.h>
  26. #include <netinet/in.h>
  27. #include <arpa/inet.h>
  28. #include <sys/socket.h>
  29. typedef int socket_t;
  30. #endif
  31. #include <functional>
  32. #include <map>
  33. #include <regex>
  34. #include <string>
  35. #include <assert.h>
  36. namespace httplib
  37. {
  38. typedef std::map<std::string, std::string> Map;
  39. typedef std::multimap<std::string, std::string> MultiMap;
  40. typedef std::smatch Match;
  41. struct Request {
  42. std::string method;
  43. std::string url;
  44. MultiMap headers;
  45. std::string body;
  46. Map params;
  47. Match matches;
  48. bool has_header(const char* key) const;
  49. std::string get_header_value(const char* key) const;
  50. void set_header(const char* key, const char* val);
  51. bool has_param(const char* key) const;
  52. };
  53. struct Response {
  54. int status;
  55. MultiMap headers;
  56. std::string body;
  57. bool has_header(const char* key) const;
  58. std::string get_header_value(const char* key) const;
  59. void set_header(const char* key, const char* val);
  60. void set_redirect(const char* url);
  61. void set_content(const std::string& s, const char* content_type);
  62. Response() : status(-1) {}
  63. };
  64. struct Connection {
  65. Request request;
  66. Response response;
  67. };
  68. class Server {
  69. public:
  70. typedef std::function<void (Connection& c)> Handler;
  71. Server(const char* host, int port);
  72. ~Server();
  73. void get(const char* pattern, Handler handler);
  74. void post(const char* pattern, Handler handler);
  75. void set_error_handler(Handler handler);
  76. void set_logger(Handler logger);
  77. bool run();
  78. void stop();
  79. private:
  80. typedef std::vector<std::pair<std::regex, Handler>> Handlers;
  81. void process_request(socket_t sock);
  82. bool read_request_line(FILE* fp, Request& req);
  83. bool routing(Connection& c);
  84. bool dispatch_request(Connection& c, Handlers& handlers);
  85. const std::string host_;
  86. const int port_;
  87. socket_t svr_sock_;
  88. Handlers get_handlers_;
  89. Handlers post_handlers_;
  90. Handler error_handler_;
  91. Handler logger_;
  92. };
  93. class Client {
  94. public:
  95. Client(const char* host, int port);
  96. ~Client();
  97. std::shared_ptr<Response> get(const char* url);
  98. std::shared_ptr<Response> post(
  99. const char* url, const std::string& body, const char* content_type);
  100. bool send(const Request& req, Response& res);
  101. private:
  102. bool read_response_line(FILE* fp, Response& res);
  103. const std::string host_;
  104. const int port_;
  105. };
  106. // Implementation
  107. namespace detail {
  108. template <class Fn>
  109. void split(const char* b, const char* e, char d, Fn fn)
  110. {
  111. int i = 0;
  112. int beg = 0;
  113. while (e ? (b + i != e) : (b[i] != '\0')) {
  114. if (b[i] == d) {
  115. fn(&b[beg], &b[i]);
  116. beg = i + 1;
  117. }
  118. i++;
  119. }
  120. if (i) {
  121. fn(&b[beg], &b[i]);
  122. }
  123. }
  124. inline void get_flie_pointers(int fd, FILE*& fp_read, FILE*& fp_write)
  125. {
  126. #ifdef _WIN32
  127. int osfhandle = _open_osfhandle(fd, _O_RDONLY);
  128. fp_read = fdopen(osfhandle, "rb");
  129. fp_write = fdopen(osfhandle, "wb");
  130. #else
  131. fp_read = fdopen(fd, "rb");
  132. fp_write = fdopen(fd, "wb");
  133. #endif
  134. }
  135. template <typename Fn>
  136. socket_t create_socket(const char* host, int port, Fn fn)
  137. {
  138. #ifdef _WIN32
  139. int opt = SO_SYNCHRONOUS_NONALERT;
  140. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
  141. #endif
  142. // Create a socket
  143. socket_t sock = socket(AF_INET, SOCK_STREAM, 0);
  144. if (sock == -1) {
  145. return -1;
  146. }
  147. // Make 'reuse address' option available
  148. int yes = 1;
  149. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
  150. // Get a host entry info
  151. struct hostent* hp;
  152. if (!(hp = gethostbyname(host))) {
  153. return -1;
  154. }
  155. // Bind the socket to the given address
  156. struct sockaddr_in addr;
  157. memset(&addr, 0, sizeof(addr));
  158. memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
  159. addr.sin_family = AF_INET;
  160. addr.sin_port = htons(port);
  161. return fn(sock, addr);
  162. }
  163. inline socket_t create_server_socket(const char* host, int port)
  164. {
  165. return create_socket(host, port, [](socket_t sock, struct sockaddr_in& addr) -> socket_t {
  166. if (::bind(sock, (struct sockaddr*)&addr, sizeof(addr))) {
  167. return -1;
  168. }
  169. if (listen(sock, 5)) { // Listen through 5 channels
  170. return -1;
  171. }
  172. return sock;
  173. });
  174. }
  175. inline int shutdown_and_close_socket(socket_t sock)
  176. {
  177. #ifdef _WIN32
  178. shutdown(sock, SD_BOTH);
  179. return closesocket(sock);
  180. #else
  181. shutdown(sock, SHUT_RDWR);
  182. return close(sock);
  183. #endif
  184. }
  185. inline socket_t create_client_socket(const char* host, int port)
  186. {
  187. return create_socket(host, port, [](socket_t sock, struct sockaddr_in& addr) -> socket_t {
  188. if (connect(sock, (struct sockaddr*)&addr, sizeof(struct sockaddr_in))) {
  189. return -1;
  190. }
  191. return sock;
  192. });
  193. }
  194. inline const char* status_message(int status)
  195. {
  196. switch (status) {
  197. case 400: return "Bad Request";
  198. case 404: return "Not Found";
  199. default:
  200. status = 500;
  201. return "Internal Server Error";
  202. }
  203. }
  204. inline const char* get_header_value_text(const MultiMap& map, const char* key, const char* def)
  205. {
  206. auto it = map.find(key);
  207. if (it != map.end()) {
  208. return it->second.c_str();
  209. }
  210. return def;
  211. }
  212. inline int get_header_value_int(const MultiMap& map, const char* key, int def)
  213. {
  214. auto it = map.find(key);
  215. if (it != map.end()) {
  216. return std::atoi(it->second.c_str());
  217. }
  218. return def;
  219. }
  220. inline bool read_headers(FILE* fp, MultiMap& headers)
  221. {
  222. static std::regex re("(.+?): (.+?)\r\n");
  223. const size_t BUFSIZ_HEADER = 2048;
  224. char buf[BUFSIZ_HEADER];
  225. for (;;) {
  226. if (!fgets(buf, BUFSIZ_HEADER, fp)) {
  227. return false;
  228. }
  229. if (!strcmp(buf, "\r\n")) {
  230. break;
  231. }
  232. std::cmatch m;
  233. if (std::regex_match(buf, m, re)) {
  234. auto key = std::string(m[1]);
  235. auto val = std::string(m[2]);
  236. headers.insert(std::make_pair(key, val));
  237. }
  238. }
  239. return true;
  240. }
  241. template <typename T>
  242. bool read_content(T& x, FILE* fp)
  243. {
  244. auto len = get_header_value_int(x.headers, "Content-Length", 0);
  245. if (len) {
  246. x.body.assign(len, 0);
  247. if (!fgets(&x.body[0], x.body.size() + 1, fp)) {
  248. return false;
  249. }
  250. }
  251. return true;
  252. }
  253. template <typename T>
  254. inline void write_headers(FILE* fp, const T& x)
  255. {
  256. fprintf(fp, "Connection: close\r\n");
  257. for (auto it = x.headers.begin(); it != x.headers.end(); ++it) {
  258. if (it->first != "Content-Type" && it->first != "Content-Length") {
  259. fprintf(fp, "%s: %s\r\n", it->first.c_str(), it->second.c_str());
  260. }
  261. }
  262. if (!x.body.empty()) {
  263. auto content_type = get_header_value_text(x.headers, "Content-Type", "text/plain");
  264. fprintf(fp, "Content-Type: %s\r\n", content_type);
  265. fprintf(fp, "Content-Length: %ld\r\n", x.body.size());
  266. }
  267. fprintf(fp, "\r\n");
  268. }
  269. inline void write_response(FILE* fp, const Response& res)
  270. {
  271. fprintf(fp, "HTTP/1.0 %d %s\r\n", res.status, status_message(res.status));
  272. write_headers(fp, res);
  273. if (!res.body.empty()) {
  274. fprintf(fp, "%s", res.body.c_str());
  275. }
  276. }
  277. inline void write_request(FILE* fp, const Request& req)
  278. {
  279. fprintf(fp, "%s %s HTTP/1.0\r\n", req.method.c_str(), req.url.c_str());
  280. write_headers(fp, req);
  281. if (!req.body.empty()) {
  282. fprintf(fp, "%s", req.body.c_str());
  283. }
  284. }
  285. inline void parse_query_text(const char* b, const char* e, Map& params)
  286. {
  287. split(b, e, '&', [&](const char* b, const char* e) {
  288. std::string key;
  289. std::string val;
  290. split(b, e, '=', [&](const char* b, const char* e) {
  291. if (key.empty()) {
  292. key.assign(b, e);
  293. } else {
  294. val.assign(b, e);
  295. }
  296. });
  297. params[key] = val;
  298. });
  299. }
  300. inline void parse_query_text(const std::string& s, Map& params)
  301. {
  302. parse_query_text(&s[0], &s[s.size()], params);
  303. }
  304. } // namespace detail
  305. // Request implementation
  306. inline bool Request::has_header(const char* key) const
  307. {
  308. return headers.find(key) != headers.end();
  309. }
  310. inline std::string Request::get_header_value(const char* key) const
  311. {
  312. return detail::get_header_value_text(headers, key, "");
  313. }
  314. inline void Request::set_header(const char* key, const char* val)
  315. {
  316. headers.insert(std::make_pair(key, val));
  317. }
  318. inline bool Request::has_param(const char* key) const
  319. {
  320. return params.find(key) != params.end();
  321. }
  322. // Response implementation
  323. inline bool Response::has_header(const char* key) const
  324. {
  325. return headers.find(key) != headers.end();
  326. }
  327. inline std::string Response::get_header_value(const char* key) const
  328. {
  329. return detail::get_header_value_text(headers, key, "");
  330. }
  331. inline void Response::set_header(const char* key, const char* val)
  332. {
  333. headers.insert(std::make_pair(key, val));
  334. }
  335. inline void Response::set_redirect(const char* url)
  336. {
  337. set_header("Location", url);
  338. status = 302;
  339. }
  340. inline void Response::set_content(const std::string& s, const char* content_type)
  341. {
  342. body = s;
  343. set_header("Content-Type", content_type);
  344. }
  345. // HTTP server implementation
  346. inline Server::Server(const char* host, int port)
  347. : host_(host)
  348. , port_(port)
  349. , svr_sock_(-1)
  350. {
  351. #ifdef _WIN32
  352. WSADATA wsaData;
  353. WSAStartup(0x0002, &wsaData);
  354. #endif
  355. }
  356. inline Server::~Server()
  357. {
  358. #ifdef _WIN32
  359. WSACleanup();
  360. #endif
  361. }
  362. inline void Server::get(const char* pattern, Handler handler)
  363. {
  364. get_handlers_.push_back(std::make_pair(pattern, handler));
  365. }
  366. inline void Server::post(const char* pattern, Handler handler)
  367. {
  368. post_handlers_.push_back(std::make_pair(pattern, handler));
  369. }
  370. inline void Server::set_error_handler(Handler handler)
  371. {
  372. error_handler_ = handler;
  373. }
  374. inline void Server::set_logger(Handler logger)
  375. {
  376. logger_ = logger;
  377. }
  378. inline bool Server::run()
  379. {
  380. svr_sock_ = detail::create_server_socket(host_.c_str(), port_);
  381. if (svr_sock_ == -1) {
  382. return false;
  383. }
  384. for (;;) {
  385. socket_t sock = accept(svr_sock_, NULL, NULL);
  386. if (sock == -1) {
  387. if (svr_sock_ == -1) {
  388. // The server socket was closed by user.
  389. return true;
  390. } else {
  391. detail::shutdown_and_close_socket(svr_sock_);
  392. return false;
  393. }
  394. }
  395. // TODO: should be async
  396. process_request(sock);
  397. detail::shutdown_and_close_socket(sock);
  398. }
  399. // NOTREACHED
  400. }
  401. inline void Server::stop()
  402. {
  403. detail::shutdown_and_close_socket(svr_sock_);
  404. svr_sock_ = -1;
  405. }
  406. inline bool Server::read_request_line(FILE* fp, Request& req)
  407. {
  408. const size_t BUFSIZ_REQUESTLINE = 2048;
  409. char buf[BUFSIZ_REQUESTLINE];
  410. if (!fgets(buf, BUFSIZ_REQUESTLINE, fp)) {
  411. return false;
  412. }
  413. static std::regex re("(GET|POST) ([^?]+)(?:\\?(.+?))? HTTP/1\\.[01]\r\n");
  414. std::cmatch m;
  415. if (std::regex_match(buf, m, re)) {
  416. req.method = std::string(m[1]);
  417. req.url = std::string(m[2]);
  418. // Parse query text
  419. auto len = std::distance(m[3].first, m[3].second);
  420. if (len > 0) {
  421. const auto& pos = m[3];
  422. detail::parse_query_text(pos.first, pos.second, req.params);
  423. }
  424. return true;
  425. }
  426. return false;
  427. }
  428. inline bool Server::routing(Connection& c)
  429. {
  430. if (c.request.method == "GET") {
  431. return dispatch_request(c, get_handlers_);
  432. } else if (c.request.method == "POST") {
  433. return dispatch_request(c, post_handlers_);
  434. }
  435. return false;
  436. }
  437. inline bool Server::dispatch_request(Connection& c, Handlers& handlers)
  438. {
  439. for (auto it = handlers.begin(); it != handlers.end(); ++it) {
  440. const auto& pattern = it->first;
  441. const auto& handler = it->second;
  442. if (std::regex_match(c.request.url, c.request.matches, pattern)) {
  443. handler(c);
  444. return true;
  445. }
  446. }
  447. return false;
  448. }
  449. inline void Server::process_request(socket_t sock)
  450. {
  451. FILE* fp_read;
  452. FILE* fp_write;
  453. detail::get_flie_pointers(sock, fp_read, fp_write);
  454. Connection c;
  455. if (!read_request_line(fp_read, c.request) ||
  456. !detail::read_headers(fp_read, c.request.headers)) {
  457. return;
  458. }
  459. if (c.request.method == "POST") {
  460. if (!detail::read_content(c.request, fp_read)) {
  461. return;
  462. }
  463. if (c.request.get_header_value("Content-Type") == "application/x-www-form-urlencoded") {
  464. detail::parse_query_text(c.request.body, c.request.params);
  465. }
  466. }
  467. if (routing(c)) {
  468. if (c.response.status == -1) {
  469. c.response.status = 200;
  470. }
  471. } else {
  472. c.response.status = 404;
  473. }
  474. assert(c.response.status != -1);
  475. if (400 <= c.response.status && error_handler_) {
  476. error_handler_(c);
  477. }
  478. detail::write_response(fp_write, c.response);
  479. fflush(fp_write);
  480. if (logger_) {
  481. logger_(c);
  482. }
  483. }
  484. // HTTP client implementation
  485. inline Client::Client(const char* host, int port)
  486. : host_(host)
  487. , port_(port)
  488. {
  489. #ifdef _WIN32
  490. WSADATA wsaData;
  491. WSAStartup(0x0002, &wsaData);
  492. #endif
  493. }
  494. inline Client::~Client()
  495. {
  496. #ifdef _WIN32
  497. WSACleanup();
  498. #endif
  499. }
  500. inline bool Client::read_response_line(FILE* fp, Response& res)
  501. {
  502. const size_t BUFSIZ_RESPONSELINE = 2048;
  503. char buf[BUFSIZ_RESPONSELINE];
  504. if (!fgets(buf, BUFSIZ_RESPONSELINE, fp)) {
  505. return false;
  506. }
  507. static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
  508. std::cmatch m;
  509. if (std::regex_match(buf, m, re)) {
  510. res.status = std::atoi(std::string(m[1]).c_str());
  511. }
  512. return true;
  513. }
  514. inline bool Client::send(const Request& req, Response& res)
  515. {
  516. socket_t sock = detail::create_client_socket(host_.c_str(), port_);
  517. if (sock == -1) {
  518. return false;
  519. }
  520. FILE* fp_read;
  521. FILE* fp_write;
  522. detail::get_flie_pointers(sock, fp_read, fp_write);
  523. // Send request
  524. detail::write_request(fp_write, req);
  525. fflush(fp_write);
  526. if (!read_response_line(fp_read, res) ||
  527. !detail::read_headers(fp_read, res.headers) ||
  528. !detail::read_content(res, fp_read)) {
  529. return false;
  530. }
  531. detail::shutdown_and_close_socket(sock);
  532. return true;
  533. }
  534. inline std::shared_ptr<Response> Client::get(const char* url)
  535. {
  536. Request req;
  537. req.method = "GET";
  538. req.url = url;
  539. auto res = std::make_shared<Response>();
  540. return send(req, *res) ? res : nullptr;
  541. }
  542. inline std::shared_ptr<Response> Client::post(
  543. const char* url, const std::string& body, const char* content_type)
  544. {
  545. Request req;
  546. req.method = "POST";
  547. req.url = url;
  548. req.set_header("Content-Type", content_type);
  549. req.body = body;
  550. auto res = std::make_shared<Response>();
  551. return send(req, *res) ? res : nullptr;
  552. }
  553. } // namespace httplib
  554. #endif
  555. // vim: et ts=4 sw=4 cin cino={1s ff=unix