http_server.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. #include "http_server.h"
  2. #include "h.h"
  3. #include "hmain.h"
  4. #include "hloop.h"
  5. #include "hbuf.h"
  6. #include "HttpParser.h"
  7. #include "FileCache.h"
  8. #define RECV_BUFSIZE 4096
  9. #define SEND_BUFSIZE 4096
  10. static HttpService s_default_service;
  11. static FileCache s_filecache;
  12. /*
  13. <!DOCTYPE html>
  14. <html>
  15. <head>
  16. <title>404 Not Found</title>
  17. </head>
  18. <body>
  19. <center><h1>404 Not Found</h1></center>
  20. <hr>
  21. </body>
  22. </html>
  23. */
  24. static void make_http_status_page(http_status status_code, std::string& page) {
  25. char szCode[8];
  26. snprintf(szCode, sizeof(szCode), "%d ", status_code);
  27. const char* status_message = http_status_str(status_code);
  28. page += R"(<!DOCTYPE html>
  29. <html>
  30. <head>
  31. <title>)";
  32. page += szCode; page += status_message;
  33. page += R"(</title>
  34. </head>
  35. <body>
  36. <center><h1>)";
  37. page += szCode; page += status_message;
  38. page += R"(</h1></center>
  39. <hr>
  40. </body>
  41. </html>)";
  42. }
  43. static void master_init(void* userdata) {
  44. #ifdef OS_UNIX
  45. char proctitle[256] = {0};
  46. snprintf(proctitle, sizeof(proctitle), "%s: master process", g_main_ctx.program_name);
  47. setproctitle(proctitle);
  48. #endif
  49. }
  50. static void master_proc(void* userdata) {
  51. while(1) sleep(1);
  52. }
  53. static void worker_init(void* userdata) {
  54. #ifdef OS_UNIX
  55. char proctitle[256] = {0};
  56. snprintf(proctitle, sizeof(proctitle), "%s: worker process", g_main_ctx.program_name);
  57. setproctitle(proctitle);
  58. signal(SIGNAL_RELOAD, signal_handler);
  59. #endif
  60. }
  61. struct http_connect_userdata {
  62. http_server_t* server;
  63. std::string log;
  64. HttpParser parser;
  65. HttpRequest req;
  66. HttpResponse res;
  67. http_connect_userdata() {
  68. parser.parser_request_init(&req);
  69. }
  70. };
  71. static void on_read(hio_t* io, void* buf, int readbytes, void* userdata) {
  72. //printf("on_read fd=%d readbytes=%d\n", io->fd, readbytes);
  73. http_connect_userdata* hcu = (http_connect_userdata*)userdata;
  74. HttpService* service = hcu->server->service;
  75. HttpRequest* req = &hcu->req;
  76. HttpResponse* res = &hcu->res;
  77. int ret, nparse;
  78. char* recvbuf = (char*)buf;
  79. int nrecv = readbytes;
  80. // recv -> http_parser -> http_request -> http_request_handler -> http_response -> send
  81. //printf("%s\n", recvbuf);
  82. nparse = hcu->parser.execute(recvbuf, nrecv);
  83. if (nparse != nrecv || hcu->parser.get_errno() != HPE_OK) {
  84. hcu->log += asprintf("http parser error: %s", http_errno_description(hcu->parser.get_errno()));
  85. hclose(io);
  86. return;
  87. }
  88. if (hcu->parser.get_state() == HP_MESSAGE_COMPLETE) {
  89. http_api_handler api = NULL;
  90. file_cache_t* fc = NULL;
  91. const char* content = NULL;
  92. int content_length = 0;
  93. bool send_in_one_packet = false;
  94. hcu->log += asprintf("[%s %s]", http_method_str(req->method), req->url.c_str());
  95. static std::string s_Server = std::string("httpd/") + std::string(get_compile_version());
  96. res->headers["Server"] = s_Server;
  97. // preprocessor
  98. if (service->preprocessor) {
  99. service->preprocessor(req, res);
  100. }
  101. ret = service->GetApi(req->url.c_str(), req->method, &api);
  102. if (api) {
  103. // api service
  104. api(req, res);
  105. }
  106. else {
  107. if (ret == HTTP_STATUS_METHOD_NOT_ALLOWED) {
  108. // Method Not Allowed
  109. res->status_code = HTTP_STATUS_METHOD_NOT_ALLOWED;
  110. }
  111. else if (req->method == HTTP_GET) {
  112. // web service
  113. std::string filepath = service->document_root;
  114. filepath += req->url.c_str();
  115. if (strcmp(req->url.c_str(), "/") == 0) {
  116. filepath += service->home_page;
  117. }
  118. fc = s_filecache.Open(filepath.c_str());
  119. // Not Found
  120. if (fc == NULL) {
  121. res->status_code = HTTP_STATUS_NOT_FOUND;
  122. }
  123. else {
  124. // Not Modified
  125. auto iter = req->headers.find("if-not-match");
  126. if (iter != req->headers.end() &&
  127. strcmp(iter->second.c_str(), fc->etag) == 0) {
  128. res->status_code = HTTP_STATUS_NOT_MODIFIED;
  129. fc = NULL;
  130. }
  131. else {
  132. iter = req->headers.find("if-modified-since");
  133. if (iter != req->headers.end() &&
  134. strcmp(iter->second.c_str(), fc->last_modified) == 0) {
  135. res->status_code = HTTP_STATUS_NOT_MODIFIED;
  136. fc = NULL;
  137. }
  138. }
  139. }
  140. }
  141. else {
  142. // Not Implemented
  143. res->status_code = HTTP_STATUS_NOT_IMPLEMENTED;
  144. }
  145. // html page
  146. if (res->status_code >= 400 && res->body.size() == 0) {
  147. // error page
  148. if (service->error_page.size() != 0) {
  149. std::string filepath = service->document_root;
  150. filepath += '/';
  151. filepath += service->error_page;
  152. fc = s_filecache.Open(filepath.c_str());
  153. }
  154. // status page
  155. if (fc == NULL && res->body.size() == 0) {
  156. res->content_type = TEXT_HTML;
  157. make_http_status_page(res->status_code, res->body);
  158. }
  159. }
  160. }
  161. // postprocessor
  162. if (service->postprocessor) {
  163. service->postprocessor(req, res);
  164. }
  165. // send
  166. std::string header;
  167. time_t tt;
  168. time(&tt);
  169. char c_str[256] = {0};
  170. strftime(c_str, sizeof(c_str), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&tt));
  171. res->headers["Date"] = c_str;
  172. if (fc && fc->filebuf.len) {
  173. content = (const char*)fc->filebuf.base;
  174. content_length = fc->filebuf.len;
  175. if (fc->content_type && *fc->content_type != '\0') {
  176. res->headers["Content-Type"] = fc->content_type;
  177. }
  178. res->headers["Content-Length"] = std::to_string(content_length);
  179. res->headers["Last-Modified"] = fc->last_modified;
  180. res->headers["Etag"] = fc->etag;
  181. }
  182. else if (res->body.size()) {
  183. content = res->body.c_str();
  184. content_length = res->body.size();
  185. }
  186. header = res->dump(true, false);
  187. if (header.size() + content_length <= SEND_BUFSIZE) {
  188. header.insert(header.size(), content, content_length);
  189. send_in_one_packet = true;
  190. }
  191. // send header
  192. hwrite(io->loop, io->fd, header.c_str(), header.size());
  193. // send body
  194. if (!send_in_one_packet && content_length != 0) {
  195. hwrite(io->loop, io->fd, content, content_length);
  196. }
  197. hcu->log += asprintf("=>[%d %s]", res->status_code, http_status_str(res->status_code));
  198. hlogi("%s", hcu->log.c_str());
  199. hclose(io);
  200. }
  201. }
  202. static void on_close(hio_t* io, void* userdata) {
  203. http_connect_userdata* hcu = (http_connect_userdata*)userdata;
  204. if (hcu) {
  205. hlogi("%s", hcu->log.c_str());
  206. delete hcu;
  207. }
  208. }
  209. static void on_accept(hio_t* io, int connfd, void* userdata) {
  210. //printf("on_accept listenfd=%d connfd=%d\n", io->fd, connfd);
  211. struct sockaddr_in localaddr, peeraddr;
  212. socklen_t addrlen;
  213. addrlen = sizeof(struct sockaddr_in);
  214. getsockname(connfd, (struct sockaddr*)&localaddr, &addrlen);
  215. addrlen = sizeof(struct sockaddr_in);
  216. getpeername(connfd, (struct sockaddr*)&peeraddr, &addrlen);
  217. //printf("accept connfd=%d [%s:%d] <= [%s:%d]\n", connfd,
  218. //inet_ntoa(localaddr.sin_addr), ntohs(localaddr.sin_port),
  219. //inet_ntoa(peeraddr.sin_addr), ntohs(peeraddr.sin_port));
  220. // new http_connect_userdata
  221. // delete on_close
  222. http_connect_userdata* hcu = new http_connect_userdata;
  223. hcu->server = (http_server_t*)userdata;
  224. hcu->log += asprintf("[%s:%d]", inet_ntoa(peeraddr.sin_addr), ntohs(peeraddr.sin_port));
  225. nonblocking(connfd);
  226. HBuf* buf = (HBuf*)io->loop->custom_data.ptr;
  227. hread(io->loop, connfd, buf->base, buf->len, on_read, hcu, on_close, hcu);
  228. }
  229. void handle_cached_files(htimer_t* timer, void* userdata) {
  230. FileCache* pfc = (FileCache*)userdata;
  231. if (pfc == NULL) {
  232. htimer_del(timer);
  233. return;
  234. }
  235. file_cache_t* fc = NULL;
  236. time_t tt;
  237. time(&tt);
  238. auto iter = pfc->cached_files.begin();
  239. while (iter != pfc->cached_files.end()) {
  240. fc = iter->second;
  241. if (tt - fc->stat_time > pfc->file_cached_time) {
  242. delete fc;
  243. iter = pfc->cached_files.erase(iter);
  244. continue;
  245. }
  246. ++iter;
  247. }
  248. }
  249. static void worker_proc(void* userdata) {
  250. http_server_t* server = (http_server_t*)userdata;
  251. int listenfd = server->listenfd;
  252. hloop_t loop;
  253. hloop_init(&loop);
  254. htimer_add(&loop, handle_cached_files, &s_filecache, s_filecache.file_cached_time*1000);
  255. // one loop one readbuf.
  256. HBuf readbuf;
  257. readbuf.resize(RECV_BUFSIZE);
  258. loop.custom_data.ptr = &readbuf;
  259. haccept(&loop, listenfd, on_accept, server);
  260. hloop_run(&loop);
  261. }
  262. int http_server_run(http_server_t* server, int wait) {
  263. // worker_processes
  264. if (server->worker_processes != 0 && g_worker_processes_num != 0 && g_worker_processes != NULL) {
  265. return ERR_OVER_LIMIT;
  266. }
  267. // service
  268. if (server->service == NULL) {
  269. server->service = &s_default_service;
  270. }
  271. // port
  272. server->listenfd = Listen(server->port);
  273. if (server->listenfd < 0) return server->listenfd;
  274. if (server->worker_processes == 0) {
  275. worker_proc(server);
  276. }
  277. else {
  278. // master-workers processes
  279. g_worker_processes_num = server->worker_processes;
  280. int bytes = g_worker_processes_num * sizeof(proc_ctx_t);
  281. g_worker_processes = (proc_ctx_t*)malloc(bytes);
  282. if (g_worker_processes == NULL) {
  283. perror("malloc");
  284. abort();
  285. }
  286. memset(g_worker_processes, 0, bytes);
  287. for (int i = 0; i < g_worker_processes_num; ++i) {
  288. proc_ctx_t* ctx = g_worker_processes + i;
  289. ctx->init = worker_init;
  290. ctx->init_userdata = NULL;
  291. ctx->proc = worker_proc;
  292. ctx->proc_userdata = server;
  293. spawn_proc(ctx);
  294. }
  295. }
  296. if (wait) {
  297. master_init(NULL);
  298. master_proc(NULL);
  299. }
  300. return 0;
  301. }