httpsvrkit.h 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. //
  2. // httpsvrkit.h
  3. //
  4. // Copyright (c) 2012 Yuji Hirose. All rights reserved.
  5. // The Boost Software License 1.0
  6. //
  7. #ifdef _WIN32
  8. //#define _CRT_SECURE_NO_WARNINGS
  9. #define _CRT_NONSTDC_NO_DEPRECATE
  10. #include <fcntl.h>
  11. #include <io.h>
  12. #include <winsock2.h>
  13. typedef SOCKET socket_t;
  14. #else
  15. #include <pthread.h>
  16. #include <unistd.h>
  17. #include <netdb.h>
  18. #include <netinet/in.h>
  19. #include <arpa/inet.h>
  20. #include <sys/socket.h>
  21. typedef int socket_t;
  22. #endif
  23. #include <functional>
  24. #include <map>
  25. #include <regex>
  26. #include <string>
  27. #include <assert.h>
  28. namespace httpsvrkit
  29. {
  30. typedef std::map<std::string, std::string> Map;
  31. typedef std::vector<std::string> Array;
  32. typedef std::multimap<std::string, std::string> MultiMap;
  33. // HTTP request
  34. struct Request {
  35. std::string method;
  36. std::string url;
  37. Map headers;
  38. std::string body;
  39. Map query;
  40. Array params;
  41. };
  42. // HTTP response
  43. struct Response {
  44. MultiMap headers;
  45. std::string body;
  46. };
  47. struct Context {
  48. Request request;
  49. Response response;
  50. };
  51. // HTTP server
  52. class Server {
  53. public:
  54. typedef std::function<int (Context& context)> Handler;
  55. Server();
  56. ~Server();
  57. void get(const char* pattern, Handler handler);
  58. void post(const char* pattern, Handler handler);
  59. bool run(const char* ipaddr_or_hostname, int port);
  60. void stop();
  61. private:
  62. void process_request(FILE* fp_read, FILE* fp_write);
  63. socket_t sock_;
  64. std::vector<std::pair<std::regex, Handler>> get_handlers_;
  65. std::vector<std::pair<std::string, Handler>> post_handlers_;
  66. };
  67. // Implementation
  68. template <class Fn>
  69. void split(const char* b, const char* e, char d, Fn fn)
  70. {
  71. int i = 0;
  72. int beg = 0;
  73. while (e ? (b + i != e) : (b[i] != '\0')) {
  74. if (b[i] == d) {
  75. fn(&b[beg], &b[i]);
  76. beg = i + 1;
  77. }
  78. i++;
  79. }
  80. if (i != 0) {
  81. fn(&b[beg], &b[i]);
  82. }
  83. }
  84. inline socket_t create_server_socket(const const char* ipaddr_or_hostname, int port)
  85. {
  86. // Create a server socket
  87. socket_t sock = socket(AF_INET, SOCK_STREAM, 0);
  88. if (sock == -1) {
  89. return -1;
  90. }
  91. // Make 'reuse address' option available
  92. int opt = 1;
  93. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&opt, sizeof(opt));
  94. // Get a host entry info
  95. struct hostent* hp;
  96. if (!(hp = gethostbyname(ipaddr_or_hostname))) {
  97. return -1;
  98. }
  99. // Bind the socket to the given address
  100. struct sockaddr_in addr;
  101. memset(&addr, 0, sizeof(addr));
  102. memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
  103. addr.sin_family = AF_INET;
  104. addr.sin_port = htons(port);
  105. if (::bind(sock, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
  106. puts("(error)\n");
  107. return -1;
  108. }
  109. // Listen through 5 channels
  110. if (listen(sock, 5) != 0) {
  111. return -1;
  112. }
  113. return sock;
  114. }
  115. inline void close_socket(socket_t sock)
  116. {
  117. #ifdef _WIN32
  118. closesocket(sock);
  119. #else
  120. shutdown(sock, SHUT_RDWR);
  121. close(sock);
  122. #endif
  123. }
  124. inline Server::Server()
  125. : sock_(-1)
  126. {
  127. #ifdef _WIN32
  128. WSADATA wsaData;
  129. WSAStartup(0x0002, &wsaData);
  130. #ifndef SO_SYNCHRONOUS_NONALERT
  131. #define SO_SYNCHRONOUS_NONALERT 0x20;
  132. #endif
  133. #ifndef SO_OPENTYPE
  134. #define SO_OPENTYPE 0x7008
  135. #endif
  136. int opt = SO_SYNCHRONOUS_NONALERT;
  137. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
  138. #endif
  139. }
  140. inline Server::~Server()
  141. {
  142. #ifdef _WIN32
  143. WSACleanup();
  144. #endif
  145. }
  146. inline void Server::get(const char* pattern, Handler handler)
  147. {
  148. get_handlers_.push_back(std::make_pair(pattern, handler));
  149. }
  150. inline void Server::post(const char* pattern, Handler handler)
  151. {
  152. post_handlers_.push_back(std::make_pair(pattern, handler));
  153. }
  154. inline bool Server::run(const const char*ipaddr_or_hostname, int port)
  155. {
  156. sock_ = create_server_socket(ipaddr_or_hostname, port);
  157. if (sock_ == -1) {
  158. return false;
  159. }
  160. for (;;) {
  161. socket_t fd = accept(sock_, NULL, NULL);
  162. if (fd == -1) {
  163. // The server socket was closed by user.
  164. if (sock_ == -1) {
  165. return true;
  166. }
  167. close_socket(sock_);
  168. return false;
  169. }
  170. #ifdef _WIN32
  171. int osfhandle = _open_osfhandle(fd, _O_RDONLY);
  172. FILE* fp_read = fdopen(osfhandle, "r");
  173. FILE* fp_write = fdopen(osfhandle, "w");
  174. #else
  175. FILE* fp_read = fdopen(fd, "r");
  176. FILE* fp_write = fdopen(fd, "w");
  177. #endif
  178. process_request(fp_read, fp_write);
  179. fflush(fp_write);
  180. close_socket(fd);
  181. }
  182. // NOTREACHED
  183. }
  184. inline void Server::stop()
  185. {
  186. close_socket(sock_);
  187. sock_ = -1;
  188. }
  189. inline bool read_request_line(FILE* fp, Request& request)
  190. {
  191. static std::regex re("(GET|POST) ([^?]+)(?:\\?(.+?))? HTTP/1\\.1\r\n");
  192. const size_t BUFSIZ_REQUESTLINE = 2048;
  193. char buf[BUFSIZ_REQUESTLINE];
  194. fgets(buf, BUFSIZ_REQUESTLINE, fp);
  195. std::cmatch m;
  196. if (std::regex_match(buf, m, re)) {
  197. request.method = std::string(m[1]);
  198. request.url = std::string(m[2]);
  199. // Parse query text
  200. auto len = std::distance(m[3].first, m[3].second);
  201. if (len > 0) {
  202. const auto& pos = m[3];
  203. split(pos.first, pos.second, '&', [&](const char* b, const char* e) {
  204. std::string key;
  205. std::string val;
  206. split(b, e, '=', [&](const char* b, const char* e) {
  207. if (key.empty()) {
  208. key.assign(b, e);
  209. } else {
  210. val.assign(b, e);
  211. }
  212. });
  213. request.query[key] = val;
  214. });
  215. }
  216. return true;
  217. }
  218. return false;
  219. }
  220. inline void read_headers(FILE* fp, Map& headers)
  221. {
  222. static std::regex re("(.+?): (.+?)\r\n");
  223. const size_t BUFSIZ_HEADER = 2048;
  224. char buf[BUFSIZ_HEADER];
  225. while (fgets(buf, BUFSIZ_HEADER, fp) && strcmp(buf, "\r\n")) {
  226. std::cmatch m;
  227. if (std::regex_match(buf, m, re)) {
  228. auto key = std::string(m[1]);
  229. auto val = std::string(m[2]);
  230. headers[key] = val;
  231. }
  232. }
  233. }
  234. inline void write_plain_text(FILE* fp, const char* s)
  235. {
  236. fprintf(fp, "HTTP/1.0 200 OK\r\n");
  237. fprintf(fp, "Content-type: text/plain\r\n");
  238. fprintf(fp, "Connection: close\r\n");
  239. fprintf(fp, "\r\n");
  240. fprintf(fp, "%s", s);
  241. }
  242. inline void write_error(FILE* fp, int status)
  243. {
  244. const char* msg = NULL;
  245. switch (status) {
  246. case 400:
  247. msg = "Bad Request";
  248. break;
  249. case 404:
  250. msg = "Not Found";
  251. break;
  252. default:
  253. status = 500;
  254. msg = "Internal Server Error";
  255. break;
  256. }
  257. assert(msg);
  258. fprintf(fp, "HTTP/1.0 %d %s\r\n", status, msg);
  259. fprintf(fp, "Content-type: text/plain\r\n");
  260. fprintf(fp, "Connection: close\r\n");
  261. fprintf(fp, "\r\n");
  262. fprintf(fp, "Status: %d\r\n", status);
  263. }
  264. inline void Server::process_request(FILE* fp_read, FILE* fp_write)
  265. {
  266. Context cxt;
  267. // Read and parse request line
  268. if (!read_request_line(fp_read, cxt.request)) {
  269. write_error(fp_write, 400);
  270. return;
  271. }
  272. // Read headers
  273. read_headers(fp_read, cxt.request.headers);
  274. // Routing
  275. int status = 404;
  276. if (cxt.request.method == "GET") {
  277. for (auto it = get_handlers_.begin(); it != get_handlers_.end(); ++it) {
  278. const auto& pattern = it->first;
  279. const auto& handler = it->second;
  280. std::smatch m;
  281. if (std::regex_match(cxt.request.url, m, pattern)) {
  282. for (size_t i = 1; i < m.size(); i++) {
  283. cxt.request.params.push_back(m[i]);
  284. }
  285. status = handler(cxt);
  286. }
  287. }
  288. } else if (cxt.request.method == "POST") {
  289. // TODO: parse body
  290. } else {
  291. status = 400;
  292. }
  293. if (status == 200) {
  294. write_plain_text(fp_write, cxt.response.body.c_str());
  295. } else {
  296. write_error(fp_write, status);
  297. }
  298. }
  299. } // namespace httpsvrkit
  300. // vim: et ts=4 sw=4 cin cino={1s ff=unix