httpsvrkit.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. //
  2. // httpsvrkit.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 httpsvrkit
  37. {
  38. typedef std::map<std::string, std::string> Map;
  39. typedef std::vector<std::string> Array;
  40. typedef std::multimap<std::string, std::string> MultiMap;
  41. // HTTP request
  42. struct Request {
  43. std::string method;
  44. std::string url;
  45. Map headers;
  46. std::string body;
  47. Map query;
  48. Array params;
  49. };
  50. // HTTP response
  51. struct Response {
  52. int status;
  53. MultiMap headers;
  54. std::string body;
  55. void set_redirect(const char* url);
  56. void set_content(const std::string& s, const char* content_type = "text/plain");
  57. };
  58. struct Context {
  59. Request request;
  60. Response response;
  61. };
  62. // HTTP server
  63. class Server {
  64. public:
  65. typedef std::function<void (Context& context)> Handler;
  66. Server(const char* ipaddr_or_hostname, int port);
  67. ~Server();
  68. void get(const char* pattern, Handler handler);
  69. void post(const char* pattern, Handler handler);
  70. bool run();
  71. void stop();
  72. private:
  73. void process_request(FILE* fp_read, FILE* fp_write);
  74. const std::string ipaddr_or_hostname_;
  75. const int port_;
  76. socket_t sock_;
  77. std::vector<std::pair<std::regex, Handler>> get_handlers_;
  78. std::vector<std::pair<std::string, Handler>> post_handlers_;
  79. };
  80. // Implementation
  81. template <class Fn>
  82. void split(const char* b, const char* e, char d, Fn fn)
  83. {
  84. int i = 0;
  85. int beg = 0;
  86. while (e ? (b + i != e) : (b[i] != '\0')) {
  87. if (b[i] == d) {
  88. fn(&b[beg], &b[i]);
  89. beg = i + 1;
  90. }
  91. i++;
  92. }
  93. if (i != 0) {
  94. fn(&b[beg], &b[i]);
  95. }
  96. }
  97. inline socket_t create_server_socket(const char* ipaddr_or_hostname, int port)
  98. {
  99. #ifdef _WIN32
  100. int opt = SO_SYNCHRONOUS_NONALERT;
  101. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
  102. #endif
  103. // Create a server socket
  104. socket_t sock = socket(AF_INET, SOCK_STREAM, 0);
  105. if (sock == -1) {
  106. return -1;
  107. }
  108. // Make 'reuse address' option available
  109. int yes = 1;
  110. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
  111. // Get a host entry info
  112. struct hostent* hp;
  113. if (!(hp = gethostbyname(ipaddr_or_hostname))) {
  114. return -1;
  115. }
  116. // Bind the socket to the given address
  117. struct sockaddr_in addr;
  118. memset(&addr, 0, sizeof(addr));
  119. memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
  120. addr.sin_family = AF_INET;
  121. addr.sin_port = htons(port);
  122. if (::bind(sock, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
  123. return -1;
  124. }
  125. // Listen through 5 channels
  126. if (listen(sock, 5) != 0) {
  127. return -1;
  128. }
  129. return sock;
  130. }
  131. inline void close_socket(socket_t sock)
  132. {
  133. #ifdef _WIN32
  134. closesocket(sock);
  135. #else
  136. shutdown(sock, SHUT_RDWR);
  137. close(sock);
  138. #endif
  139. }
  140. std::string dump_request(Context& cxt)
  141. {
  142. const auto& req = cxt.request;
  143. std::string s;
  144. char buf[BUFSIZ];
  145. s += "================================\n";
  146. sprintf(buf, "%s %s", req.method.c_str(), req.url.c_str());
  147. s += buf;
  148. std::string query;
  149. for (auto it = req.query.begin(); it != req.query.end(); ++it) {
  150. const auto& x = *it;
  151. sprintf(buf, "%c%s=%s", (it == req.query.begin()) ? '?' : '&', x.first.c_str(), x.second.c_str());
  152. query += buf;
  153. }
  154. sprintf(buf, "%s\n", query.c_str());
  155. s += buf;
  156. for (auto it = req.headers.begin(); it != req.headers.end(); ++it) {
  157. const auto& x = *it;
  158. sprintf(buf, "%s: %s\n", x.first.c_str(), x.second.c_str());
  159. s += buf;
  160. }
  161. return s;
  162. }
  163. void Response::set_redirect(const char* url)
  164. {
  165. headers.insert(std::make_pair("Location", url));
  166. status = 302;
  167. }
  168. void Response::set_content(const std::string& s, const char* content_type)
  169. {
  170. body = s;
  171. headers.insert(std::make_pair("Content-Type", content_type));
  172. status = 200;
  173. }
  174. inline Server::Server(const char* ipaddr_or_hostname, int port)
  175. : ipaddr_or_hostname_(ipaddr_or_hostname)
  176. , port_(port)
  177. , sock_(-1)
  178. {
  179. #ifdef _WIN32
  180. WSADATA wsaData;
  181. WSAStartup(0x0002, &wsaData);
  182. #endif
  183. }
  184. inline Server::~Server()
  185. {
  186. #ifdef _WIN32
  187. WSACleanup();
  188. #endif
  189. }
  190. inline void Server::get(const char* pattern, Handler handler)
  191. {
  192. get_handlers_.push_back(std::make_pair(pattern, handler));
  193. }
  194. inline void Server::post(const char* pattern, Handler handler)
  195. {
  196. post_handlers_.push_back(std::make_pair(pattern, handler));
  197. }
  198. inline bool Server::run()
  199. {
  200. sock_ = create_server_socket(ipaddr_or_hostname_.c_str(), port_);
  201. if (sock_ == -1) {
  202. return false;
  203. }
  204. for (;;) {
  205. socket_t fd = accept(sock_, NULL, NULL);
  206. if (fd == -1) {
  207. // The server socket was closed by user.
  208. if (sock_ == -1) {
  209. return true;
  210. }
  211. close_socket(sock_);
  212. return false;
  213. }
  214. #ifdef _WIN32
  215. int osfhandle = _open_osfhandle(fd, _O_RDONLY);
  216. FILE* fp_read = fdopen(osfhandle, "rb");
  217. FILE* fp_write = fdopen(osfhandle, "wb");
  218. #else
  219. FILE* fp_read = fdopen(fd, "rb");
  220. FILE* fp_write = fdopen(fd, "wb");
  221. #endif
  222. process_request(fp_read, fp_write);
  223. fflush(fp_write);
  224. close_socket(fd);
  225. }
  226. // NOTREACHED
  227. }
  228. inline void Server::stop()
  229. {
  230. close_socket(sock_);
  231. sock_ = -1;
  232. }
  233. inline bool read_request_line(FILE* fp, Request& request)
  234. {
  235. static std::regex re("(GET|POST) ([^?]+)(?:\\?(.+?))? HTTP/1\\.1\r\n");
  236. const size_t BUFSIZ_REQUESTLINE = 2048;
  237. char buf[BUFSIZ_REQUESTLINE];
  238. fgets(buf, BUFSIZ_REQUESTLINE, fp);
  239. std::cmatch m;
  240. if (std::regex_match(buf, m, re)) {
  241. request.method = std::string(m[1]);
  242. request.url = std::string(m[2]);
  243. // Parse query text
  244. auto len = std::distance(m[3].first, m[3].second);
  245. if (len > 0) {
  246. const auto& pos = m[3];
  247. split(pos.first, pos.second, '&', [&](const char* b, const char* e) {
  248. std::string key;
  249. std::string val;
  250. split(b, e, '=', [&](const char* b, const char* e) {
  251. if (key.empty()) {
  252. key.assign(b, e);
  253. } else {
  254. val.assign(b, e);
  255. }
  256. });
  257. request.query[key] = val;
  258. });
  259. }
  260. return true;
  261. }
  262. return false;
  263. }
  264. inline void read_headers(FILE* fp, Map& headers)
  265. {
  266. static std::regex re("(.+?): (.+?)\r\n");
  267. const size_t BUFSIZ_HEADER = 2048;
  268. char buf[BUFSIZ_HEADER];
  269. while (fgets(buf, BUFSIZ_HEADER, fp) && strcmp(buf, "\r\n")) {
  270. std::cmatch m;
  271. if (std::regex_match(buf, m, re)) {
  272. auto key = std::string(m[1]);
  273. auto val = std::string(m[2]);
  274. headers[key] = val;
  275. }
  276. }
  277. }
  278. inline const char* get_header_value(const MultiMap& map, const char* key, const char* def)
  279. {
  280. auto it = map.find(key);
  281. if (it != map.end()) {
  282. return it->second.c_str();
  283. }
  284. return def;
  285. }
  286. inline void write_response(FILE* fp, const Response& response)
  287. {
  288. fprintf(fp, "HTTP/1.0 %d OK\r\n", response.status);
  289. fprintf(fp, "Connection: close\r\n");
  290. for (auto it = response.headers.begin(); it != response.headers.end(); ++it) {
  291. if (it->first != "Content-Type" && it->second != "Content-Length") {
  292. fprintf(fp, "%s: %s\r\n", it->first.c_str(), it->second.c_str());
  293. }
  294. }
  295. if (!response.body.empty()) {
  296. auto content_type = get_header_value(response.headers, "Content-Type", "text/plain");
  297. fprintf(fp, "Content-Type: %s\r\n", content_type);
  298. fprintf(fp, "Content-Length: %ld\r\n", response.body.size());
  299. }
  300. fprintf(fp, "\r\n");
  301. if (!response.body.empty()) {
  302. fprintf(fp, "%s", response.body.c_str());
  303. }
  304. }
  305. inline void write_error(FILE* fp, int status)
  306. {
  307. const char* msg = NULL;
  308. switch (status) {
  309. case 400:
  310. msg = "Bad Request";
  311. break;
  312. case 404:
  313. msg = "Not Found";
  314. break;
  315. default:
  316. status = 500;
  317. msg = "Internal Server Error";
  318. break;
  319. }
  320. assert(msg);
  321. fprintf(fp, "HTTP/1.0 %d %s\r\n", status, msg);
  322. fprintf(fp, "Content-type: text/plain\r\n");
  323. fprintf(fp, "Connection: close\r\n");
  324. fprintf(fp, "\r\n");
  325. fprintf(fp, "Status: %d\r\n", status);
  326. }
  327. inline void Server::process_request(FILE* fp_read, FILE* fp_write)
  328. {
  329. Context cxt;
  330. // Read and parse request line
  331. if (!read_request_line(fp_read, cxt.request)) {
  332. write_error(fp_write, 400);
  333. return;
  334. }
  335. // Read headers
  336. read_headers(fp_read, cxt.request.headers);
  337. printf("%s", dump_request(cxt).c_str());
  338. // Routing
  339. cxt.response.status = 404;
  340. if (cxt.request.method == "GET") {
  341. for (auto it = get_handlers_.begin(); it != get_handlers_.end(); ++it) {
  342. const auto& pattern = it->first;
  343. const auto& handler = it->second;
  344. std::smatch m;
  345. if (std::regex_match(cxt.request.url, m, pattern)) {
  346. for (size_t i = 1; i < m.size(); i++) {
  347. cxt.request.params.push_back(m[i]);
  348. }
  349. handler(cxt);
  350. break;
  351. }
  352. }
  353. } else if (cxt.request.method == "POST") {
  354. // TODO: parse body
  355. } else {
  356. cxt.response.status = 400;
  357. }
  358. if (200 <= cxt.response.status && cxt.response.status < 400) {
  359. write_response(fp_write, cxt.response);
  360. } else {
  361. write_error(fp_write, cxt.response.status);
  362. }
  363. }
  364. #define HTTP_SERVER(host, port) \
  365. for (std::shared_ptr<httpsvrkit::Server> svr = std::make_shared<httpsvrkit::Server>(host, port); \
  366. svr; \
  367. svr->run(), svr.reset())
  368. #define GET(url, body) \
  369. svr->get(url, [&](httpsvrkit::Context& cxt) { \
  370. const auto& req = cxt.request; \
  371. auto& res = cxt.response; \
  372. body \
  373. });
  374. } // namespace httpsvrkit
  375. #endif
  376. // vim: et ts=4 sw=4 cin cino={1s ff=unix