httplib.h 13 KB

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