httpsvrkit.h 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. void Response::set_redirect(const char* url)
  141. {
  142. headers.insert(std::make_pair("Location", url));
  143. status = 302;
  144. }
  145. void Response::set_content(const std::string& s, const char* content_type)
  146. {
  147. body = s;
  148. headers.insert(std::make_pair("Content-Type", content_type));
  149. status = 200;
  150. }
  151. inline Server::Server(const char* ipaddr_or_hostname, int port)
  152. : ipaddr_or_hostname_(ipaddr_or_hostname)
  153. , port_(port)
  154. , sock_(-1)
  155. {
  156. #ifdef _WIN32
  157. WSADATA wsaData;
  158. WSAStartup(0x0002, &wsaData);
  159. #endif
  160. }
  161. inline Server::~Server()
  162. {
  163. #ifdef _WIN32
  164. WSACleanup();
  165. #endif
  166. }
  167. inline void Server::get(const char* pattern, Handler handler)
  168. {
  169. get_handlers_.push_back(std::make_pair(pattern, handler));
  170. }
  171. inline void Server::post(const char* pattern, Handler handler)
  172. {
  173. post_handlers_.push_back(std::make_pair(pattern, handler));
  174. }
  175. inline bool Server::run()
  176. {
  177. sock_ = create_server_socket(ipaddr_or_hostname_.c_str(), port_);
  178. if (sock_ == -1) {
  179. return false;
  180. }
  181. for (;;) {
  182. socket_t fd = accept(sock_, NULL, NULL);
  183. if (fd == -1) {
  184. // The server socket was closed by user.
  185. if (sock_ == -1) {
  186. return true;
  187. }
  188. close_socket(sock_);
  189. return false;
  190. }
  191. #ifdef _WIN32
  192. int osfhandle = _open_osfhandle(fd, _O_RDONLY);
  193. FILE* fp_read = fdopen(osfhandle, "rb");
  194. FILE* fp_write = fdopen(osfhandle, "wb");
  195. #else
  196. FILE* fp_read = fdopen(fd, "rb");
  197. FILE* fp_write = fdopen(fd, "wb");
  198. #endif
  199. process_request(fp_read, fp_write);
  200. fflush(fp_write);
  201. close_socket(fd);
  202. }
  203. // NOTREACHED
  204. }
  205. inline void Server::stop()
  206. {
  207. close_socket(sock_);
  208. sock_ = -1;
  209. }
  210. inline bool read_request_line(FILE* fp, Request& request)
  211. {
  212. static std::regex re("(GET|POST) ([^?]+)(?:\\?(.+?))? HTTP/1\\.1\r\n");
  213. const size_t BUFSIZ_REQUESTLINE = 2048;
  214. char buf[BUFSIZ_REQUESTLINE];
  215. fgets(buf, BUFSIZ_REQUESTLINE, fp);
  216. std::cmatch m;
  217. if (std::regex_match(buf, m, re)) {
  218. request.method = std::string(m[1]);
  219. request.url = std::string(m[2]);
  220. // Parse query text
  221. auto len = std::distance(m[3].first, m[3].second);
  222. if (len > 0) {
  223. const auto& pos = m[3];
  224. split(pos.first, pos.second, '&', [&](const char* b, const char* e) {
  225. std::string key;
  226. std::string val;
  227. split(b, e, '=', [&](const char* b, const char* e) {
  228. if (key.empty()) {
  229. key.assign(b, e);
  230. } else {
  231. val.assign(b, e);
  232. }
  233. });
  234. request.query[key] = val;
  235. });
  236. }
  237. return true;
  238. }
  239. return false;
  240. }
  241. inline void read_headers(FILE* fp, Map& headers)
  242. {
  243. static std::regex re("(.+?): (.+?)\r\n");
  244. const size_t BUFSIZ_HEADER = 2048;
  245. char buf[BUFSIZ_HEADER];
  246. while (fgets(buf, BUFSIZ_HEADER, fp) && strcmp(buf, "\r\n")) {
  247. std::cmatch m;
  248. if (std::regex_match(buf, m, re)) {
  249. auto key = std::string(m[1]);
  250. auto val = std::string(m[2]);
  251. headers[key] = val;
  252. }
  253. }
  254. }
  255. inline const char* get_header_value(const MultiMap& map, const char* key, const char* def)
  256. {
  257. auto it = map.find(key);
  258. if (it != map.end()) {
  259. return it->second.c_str();
  260. }
  261. return def;
  262. }
  263. inline void write_response(FILE* fp, const Response& response)
  264. {
  265. fprintf(fp, "HTTP/1.0 %d OK\r\n", response.status);
  266. fprintf(fp, "Connection: close\r\n");
  267. for (auto it = response.headers.begin(); it != response.headers.end(); ++it) {
  268. if (it->first != "Content-Type" && it->second != "Content-Length") {
  269. fprintf(fp, "%s: %s\r\n", it->first.c_str(), it->second.c_str());
  270. }
  271. }
  272. if (!response.body.empty()) {
  273. auto content_type = get_header_value(response.headers, "Content-Type", "text/plain");
  274. fprintf(fp, "Content-Type: %s\r\n", content_type);
  275. fprintf(fp, "Content-Length: %ld\r\n", response.body.size());
  276. }
  277. fprintf(fp, "\r\n");
  278. if (!response.body.empty()) {
  279. fprintf(fp, "%s", response.body.c_str());
  280. }
  281. }
  282. inline void write_error(FILE* fp, int status)
  283. {
  284. const char* msg = NULL;
  285. switch (status) {
  286. case 400:
  287. msg = "Bad Request";
  288. break;
  289. case 404:
  290. msg = "Not Found";
  291. break;
  292. default:
  293. status = 500;
  294. msg = "Internal Server Error";
  295. break;
  296. }
  297. assert(msg);
  298. fprintf(fp, "HTTP/1.0 %d %s\r\n", status, msg);
  299. fprintf(fp, "Content-type: text/plain\r\n");
  300. fprintf(fp, "Connection: close\r\n");
  301. fprintf(fp, "\r\n");
  302. fprintf(fp, "Status: %d\r\n", status);
  303. }
  304. inline void Server::process_request(FILE* fp_read, FILE* fp_write)
  305. {
  306. Context cxt;
  307. // Read and parse request line
  308. if (!read_request_line(fp_read, cxt.request)) {
  309. write_error(fp_write, 400);
  310. return;
  311. }
  312. // Read headers
  313. read_headers(fp_read, cxt.request.headers);
  314. // Routing
  315. cxt.response.status = 404;
  316. if (cxt.request.method == "GET") {
  317. for (auto it = get_handlers_.begin(); it != get_handlers_.end(); ++it) {
  318. const auto& pattern = it->first;
  319. const auto& handler = it->second;
  320. std::smatch m;
  321. if (std::regex_match(cxt.request.url, m, pattern)) {
  322. for (size_t i = 1; i < m.size(); i++) {
  323. cxt.request.params.push_back(m[i]);
  324. }
  325. handler(cxt);
  326. break;
  327. }
  328. }
  329. } else if (cxt.request.method == "POST") {
  330. // TODO: parse body
  331. } else {
  332. cxt.response.status = 400;
  333. }
  334. if (200 <= cxt.response.status && cxt.response.status < 400) {
  335. write_response(fp_write, cxt.response);
  336. } else {
  337. write_error(fp_write, cxt.response.status);
  338. }
  339. }
  340. #define HTTP_SERVER(host, port) \
  341. for (std::shared_ptr<httpsvrkit::Server> svr = std::make_shared<httpsvrkit::Server>(host, port); \
  342. svr; \
  343. svr->run(), svr.reset())
  344. #define GET(url, body) \
  345. svr->get(url, [](httpsvrkit::Context& cxt) { \
  346. const auto& req = cxt.request; \
  347. auto& res = cxt.response; \
  348. body \
  349. });
  350. } // namespace httpsvrkit
  351. #endif
  352. // vim: et ts=4 sw=4 cin cino={1s ff=unix