httpsvrkit.h 11 KB

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