httplib.h 13 KB

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