httplib.h 15 KB

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