httpsvrkit.h 11 KB

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