http_server.cpp 11 KB

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