httplib.h 13 KB

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