httplib.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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(FILE* fp_read, FILE* fp_write);
  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 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. bool get(const char* url, Response& res);
  98. bool post(const char* url, const std::string& body, const char* content_type, Response& res);
  99. bool send(const Request& req, Response& res);
  100. private:
  101. bool read_response_line(FILE* fp, Response& res);
  102. const std::string host_;
  103. const int port_;
  104. };
  105. // Implementation
  106. template <class Fn>
  107. void split(const char* b, const char* e, char d, Fn fn)
  108. {
  109. int i = 0;
  110. int beg = 0;
  111. while (e ? (b + i != e) : (b[i] != '\0')) {
  112. if (b[i] == d) {
  113. fn(&b[beg], &b[i]);
  114. beg = i + 1;
  115. }
  116. i++;
  117. }
  118. if (i) {
  119. fn(&b[beg], &b[i]);
  120. }
  121. }
  122. inline void get_flie_pointers(int fd, FILE*& fp_read, FILE*& fp_write)
  123. {
  124. #ifdef _WIN32
  125. int osfhandle = _open_osfhandle(fd, _O_RDONLY);
  126. fp_read = fdopen(osfhandle, "rb");
  127. fp_write = fdopen(osfhandle, "wb");
  128. #else
  129. fp_read = fdopen(fd, "rb");
  130. fp_write = fdopen(fd, "wb");
  131. #endif
  132. }
  133. template <typename Fn>
  134. socket_t create_socket(const char* host, int port, Fn fn)
  135. {
  136. #ifdef _WIN32
  137. int opt = SO_SYNCHRONOUS_NONALERT;
  138. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
  139. #endif
  140. // Create a server socket
  141. socket_t sock = socket(AF_INET, SOCK_STREAM, 0);
  142. if (sock == -1) {
  143. return -1;
  144. }
  145. // Make 'reuse address' option available
  146. int yes = 1;
  147. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
  148. // Get a host entry info
  149. struct hostent* hp;
  150. if (!(hp = gethostbyname(host))) {
  151. return -1;
  152. }
  153. // Bind the socket to the given address
  154. struct sockaddr_in addr;
  155. memset(&addr, 0, sizeof(addr));
  156. memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
  157. addr.sin_family = AF_INET;
  158. addr.sin_port = htons(port);
  159. return fn(sock, addr);
  160. }
  161. inline socket_t create_server_socket(const char* host, int port)
  162. {
  163. return create_socket(host, port, [](socket_t sock, struct sockaddr_in& addr) -> socket_t {
  164. if (::bind(sock, (struct sockaddr*)&addr, sizeof(addr))) {
  165. return -1;
  166. }
  167. // Listen through 5 channels
  168. if (listen(sock, 5)) {
  169. return -1;
  170. }
  171. return sock;
  172. });
  173. }
  174. inline int close_socket(socket_t sock)
  175. {
  176. #ifdef _WIN32
  177. shutdown(sock, SD_BOTH);
  178. return closesocket(sock);
  179. #else
  180. shutdown(sock, SHUT_RDWR);
  181. return close(sock);
  182. #endif
  183. }
  184. inline socket_t create_client_socket(const char* host, int port)
  185. {
  186. return create_socket(host, port,
  187. [](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. const char* s = NULL;
  197. switch (status) {
  198. case 400:
  199. s = "Bad Request";
  200. break;
  201. case 404:
  202. s = "Not Found";
  203. break;
  204. default:
  205. status = 500;
  206. s = "Internal Server Error";
  207. break;
  208. }
  209. return s;
  210. }
  211. inline const char* get_header_value_text(const MultiMap& map, const char* key, const char* def)
  212. {
  213. auto it = map.find(key);
  214. if (it != map.end()) {
  215. return it->second.c_str();
  216. }
  217. return def;
  218. }
  219. inline int get_header_value_int(const MultiMap& map, const char* key, int def)
  220. {
  221. auto it = map.find(key);
  222. if (it != map.end()) {
  223. return std::atoi(it->second.c_str());
  224. }
  225. return def;
  226. }
  227. inline bool read_headers(FILE* fp, MultiMap& headers)
  228. {
  229. static std::regex re("(.+?): (.+?)\r\n");
  230. const size_t BUFSIZ_HEADER = 2048;
  231. char buf[BUFSIZ_HEADER];
  232. for (;;) {
  233. if (!fgets(buf, BUFSIZ_HEADER, fp)) {
  234. return false;
  235. }
  236. if (!strcmp(buf, "\r\n")) {
  237. break;
  238. }
  239. std::cmatch m;
  240. if (std::regex_match(buf, m, re)) {
  241. auto key = std::string(m[1]);
  242. auto val = std::string(m[2]);
  243. headers.insert(std::make_pair(key, val));
  244. }
  245. }
  246. return true;
  247. }
  248. template <typename T>
  249. bool read_content(T& x, FILE* fp)
  250. {
  251. auto len = get_header_value_int(x.headers, "Content-Length", 0);
  252. if (len) {
  253. x.body.assign(len, 0);
  254. if (!fgets(&x.body[0], x.body.size() + 1, fp)) {
  255. return false;
  256. }
  257. }
  258. return true;
  259. }
  260. template <typename T>
  261. inline void write_headers(FILE* fp, const T& x)
  262. {
  263. fprintf(fp, "Connection: close\r\n");
  264. for (auto it = x.headers.begin(); it != x.headers.end(); ++it) {
  265. if (it->first != "Content-Type" && it->first != "Content-Length") {
  266. fprintf(fp, "%s: %s\r\n", it->first.c_str(), it->second.c_str());
  267. }
  268. }
  269. if (!x.body.empty()) {
  270. auto content_type = get_header_value_text(x.headers, "Content-Type", "text/plain");
  271. fprintf(fp, "Content-Type: %s\r\n", content_type);
  272. fprintf(fp, "Content-Length: %ld\r\n", x.body.size());
  273. }
  274. fprintf(fp, "\r\n");
  275. }
  276. inline void write_response(FILE* fp, const Response& res)
  277. {
  278. fprintf(fp, "HTTP/1.0 %d %s\r\n", res.status, status_message(res.status));
  279. write_headers(fp, res);
  280. if (!res.body.empty()) {
  281. fprintf(fp, "%s", res.body.c_str());
  282. }
  283. }
  284. inline void write_request(FILE* fp, const Request& req)
  285. {
  286. fprintf(fp, "%s %s HTTP/1.0\r\n", req.method.c_str(), req.url.c_str());
  287. write_headers(fp, req);
  288. if (!req.body.empty()) {
  289. fprintf(fp, "%s", req.body.c_str());
  290. }
  291. }
  292. inline void parse_query_text(const char* b, const char* e, Map& params)
  293. {
  294. split(b, e, '&', [&](const char* b, const char* e) {
  295. std::string key;
  296. std::string val;
  297. split(b, e, '=', [&](const char* b, const char* e) {
  298. if (key.empty()) {
  299. key.assign(b, e);
  300. } else {
  301. val.assign(b, e);
  302. }
  303. });
  304. params[key] = val;
  305. });
  306. }
  307. // HTTP server implementation
  308. inline bool Request::has_header(const char* key) const
  309. {
  310. return headers.find(key) != headers.end();
  311. }
  312. inline std::string Request::get_header_value(const char* key) const
  313. {
  314. return get_header_value_text(headers, key, "");
  315. }
  316. inline void Request::set_header(const char* key, const char* val)
  317. {
  318. headers.insert(std::make_pair(key, val));
  319. }
  320. inline bool Request::has_param(const char* key) const
  321. {
  322. return params.find(key) != params.end();
  323. }
  324. inline bool Response::has_header(const char* key) const
  325. {
  326. return headers.find(key) != headers.end();
  327. }
  328. inline std::string Response::get_header_value(const char* key) const
  329. {
  330. return get_header_value_text(headers, key, "");
  331. }
  332. inline void Response::set_header(const char* key, const char* val)
  333. {
  334. headers.insert(std::make_pair(key, val));
  335. }
  336. inline void Response::set_redirect(const char* url)
  337. {
  338. set_header("Location", url);
  339. status = 302;
  340. }
  341. inline void Response::set_content(const std::string& s, const char* content_type)
  342. {
  343. body = s;
  344. set_header("Content-Type", content_type);
  345. }
  346. inline Server::Server(const char* host, int port)
  347. : host_(host)
  348. , port_(port)
  349. , 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. sock_ = create_server_socket(host_.c_str(), port_);
  381. if (sock_ == -1) {
  382. return false;
  383. }
  384. for (;;) {
  385. socket_t fd = accept(sock_, NULL, NULL);
  386. if (fd == -1) {
  387. // The server socket was closed by user.
  388. if (sock_ == -1) {
  389. return true;
  390. }
  391. close_socket(sock_);
  392. return false;
  393. }
  394. FILE* fp_read;
  395. FILE* fp_write;
  396. get_flie_pointers(fd, fp_read, fp_write);
  397. process_request(fp_read, fp_write);
  398. fflush(fp_write);
  399. close_socket(fd);
  400. }
  401. // NOTREACHED
  402. }
  403. inline void Server::stop()
  404. {
  405. close_socket(sock_);
  406. sock_ = -1;
  407. }
  408. inline bool Server::read_request_line(FILE* fp, Request& req)
  409. {
  410. const size_t BUFSIZ_REQUESTLINE = 2048;
  411. char buf[BUFSIZ_REQUESTLINE];
  412. if (!fgets(buf, BUFSIZ_REQUESTLINE, fp)) {
  413. return false;
  414. }
  415. static std::regex re("(GET|POST) ([^?]+)(?:\\?(.+?))? HTTP/1\\.[01]\r\n");
  416. std::cmatch m;
  417. if (std::regex_match(buf, m, re)) {
  418. req.method = std::string(m[1]);
  419. req.url = std::string(m[2]);
  420. // Parse query text
  421. auto len = std::distance(m[3].first, m[3].second);
  422. if (len > 0) {
  423. const auto& pos = m[3];
  424. parse_query_text(pos.first, pos.second, req.params);
  425. }
  426. return true;
  427. }
  428. return false;
  429. }
  430. inline bool Server::routing(Connection& c)
  431. {
  432. if (c.request.method == "GET") {
  433. return dispatch_request(c, get_handlers_);
  434. } else if (c.request.method == "POST") {
  435. return dispatch_request(c, post_handlers_);
  436. }
  437. return false;
  438. }
  439. inline bool Server::dispatch_request(Connection& c, Handlers& handlers)
  440. {
  441. for (auto it = handlers.begin(); it != handlers.end(); ++it) {
  442. const auto& pattern = it->first;
  443. const auto& handler = it->second;
  444. if (std::regex_match(c.request.url, c.request.matches, pattern)) {
  445. handler(c);
  446. return true;
  447. }
  448. }
  449. return false;
  450. }
  451. inline void Server::process_request(FILE* fp_read, FILE* fp_write)
  452. {
  453. Connection c;
  454. auto& req = c.request;
  455. if (!read_request_line(fp_read, req) ||
  456. !read_headers(fp_read, req.headers)) {
  457. return;
  458. }
  459. if (req.method == "POST") {
  460. if (!read_content(req, fp_read)) {
  461. return;
  462. }
  463. if (req.get_header_value("Content-Type") == "application/x-www-form-urlencoded") {
  464. parse_query_text(&req.body[0], &req.body[req.body.size()], req.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. write_response(fp_write, c.response);
  479. if (logger_) {
  480. logger_(c);
  481. }
  482. }
  483. // HTTP client implementation
  484. inline Client::Client(const char* host, int port)
  485. : host_(host)
  486. , port_(port)
  487. {
  488. #ifdef _WIN32
  489. WSADATA wsaData;
  490. WSAStartup(0x0002, &wsaData);
  491. #endif
  492. }
  493. inline Client::~Client()
  494. {
  495. #ifdef _WIN32
  496. WSACleanup();
  497. #endif
  498. }
  499. inline bool Client::read_response_line(FILE* fp, Response& res)
  500. {
  501. const size_t BUFSIZ_RESPONSELINE = 2048;
  502. char buf[BUFSIZ_RESPONSELINE];
  503. if (!fgets(buf, BUFSIZ_RESPONSELINE, fp)) {
  504. return false;
  505. }
  506. static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
  507. std::cmatch m;
  508. if (std::regex_match(buf, m, re)) {
  509. res.status = std::atoi(std::string(m[1]).c_str());
  510. }
  511. return true;
  512. }
  513. inline bool Client::get(const char* url, Response& res)
  514. {
  515. Request req;
  516. req.method = "GET";
  517. req.url = url;
  518. return send(req, res);
  519. }
  520. inline bool Client::post(const char* url, const std::string& body, const char* content_type, Response& res)
  521. {
  522. Request req;
  523. req.method = "POST";
  524. req.url = url;
  525. req.set_header("Content-Type", content_type);
  526. req.body = body;
  527. return send(req, res);
  528. }
  529. inline bool Client::send(const Request& req, Response& res)
  530. {
  531. socket_t sock = create_client_socket(host_.c_str(), port_);
  532. if (sock == -1) {
  533. return false;
  534. }
  535. FILE* fp_read;
  536. FILE* fp_write;
  537. get_flie_pointers(sock, fp_read, fp_write);
  538. // Send request
  539. write_request(fp_write, req);
  540. fflush(fp_write);
  541. if (!read_response_line(fp_read, res) ||
  542. !read_headers(fp_read, res.headers) ||
  543. !read_content(res, fp_read)) {
  544. return false;
  545. }
  546. close_socket(sock);
  547. return true;
  548. }
  549. } // namespace httplib
  550. #endif
  551. // vim: et ts=4 sw=4 cin cino={1s ff=unix