http_server.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. //goto recv_done;
  85. return;
  86. }
  87. else {
  88. perror("recv");
  89. hcu->log += asprintf("recv: %s", strerror(errno));
  90. goto recv_error;
  91. }
  92. }
  93. if (nrecv == 0) {
  94. hcu->log += "disconnect";
  95. goto disconnect;
  96. }
  97. //printf("%s\n", recvbuf);
  98. nparse = hcu->parser.execute(recvbuf, nrecv);
  99. if (nparse != nrecv || hcu->parser.get_errno() != HPE_OK) {
  100. hcu->log += asprintf("http parser error: %s", http_errno_description(hcu->parser.get_errno()));
  101. goto parser_error;
  102. }
  103. if (hcu->parser.get_state() == HP_MESSAGE_COMPLETE) {
  104. http_api_handler api = NULL;
  105. file_cache_t* fc = NULL;
  106. const char* content = NULL;
  107. int content_length = 0;
  108. bool send_in_one_packet = false;
  109. hcu->log += asprintf("[%s %s]", http_method_str(req->method), req->url.c_str());
  110. static std::string s_Server = std::string("httpd/") + std::string(get_compile_version());
  111. res->headers["Server"] = s_Server;
  112. // preprocessor
  113. if (service->preprocessor) {
  114. service->preprocessor(req, res);
  115. }
  116. ret = service->GetApi(req->url.c_str(), req->method, &api);
  117. if (api) {
  118. // api service
  119. api(req, res);
  120. }
  121. else {
  122. if (ret == HTTP_STATUS_METHOD_NOT_ALLOWED) {
  123. // Method Not Allowed
  124. res->status_code = HTTP_STATUS_METHOD_NOT_ALLOWED;
  125. }
  126. else if (req->method == HTTP_GET) {
  127. // web service
  128. std::string filepath = service->document_root;
  129. filepath += req->url.c_str();
  130. if (strcmp(req->url.c_str(), "/") == 0) {
  131. filepath += service->home_page;
  132. }
  133. fc = s_filecache.Open(filepath.c_str());
  134. // Not Found
  135. if (fc == NULL) {
  136. res->status_code = HTTP_STATUS_NOT_FOUND;
  137. }
  138. else {
  139. // Not Modified
  140. auto iter = req->headers.find("if-not-match");
  141. if (iter != req->headers.end() &&
  142. strcmp(iter->second.c_str(), fc->etag) == 0) {
  143. res->status_code = HTTP_STATUS_NOT_MODIFIED;
  144. fc = NULL;
  145. }
  146. else {
  147. iter = req->headers.find("if-modified-since");
  148. if (iter != req->headers.end() &&
  149. strcmp(iter->second.c_str(), fc->last_modified) == 0) {
  150. res->status_code = HTTP_STATUS_NOT_MODIFIED;
  151. fc = NULL;
  152. }
  153. }
  154. }
  155. }
  156. else {
  157. // Not Implemented
  158. res->status_code = HTTP_STATUS_NOT_IMPLEMENTED;
  159. }
  160. // html page
  161. if (res->status_code >= 400 && res->body.size() == 0) {
  162. // error page
  163. if (service->error_page.size() != 0) {
  164. std::string filepath = service->document_root;
  165. filepath += '/';
  166. filepath += service->error_page;
  167. fc = s_filecache.Open(filepath.c_str());
  168. }
  169. // status page
  170. if (fc == NULL && res->body.size() == 0) {
  171. res->content_type = TEXT_HTML;
  172. make_http_status_page(res->status_code, res->body);
  173. }
  174. }
  175. }
  176. // postprocessor
  177. if (service->postprocessor) {
  178. service->postprocessor(req, res);
  179. }
  180. // send
  181. std::string header;
  182. time_t tt;
  183. time(&tt);
  184. char c_str[256] = {0};
  185. strftime(c_str, sizeof(c_str), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&tt));
  186. res->headers["Date"] = c_str;
  187. if (fc && fc->filebuf.len) {
  188. content = (const char*)fc->filebuf.base;
  189. content_length = fc->filebuf.len;
  190. if (fc->content_type && *fc->content_type != '\0') {
  191. res->headers["Content-Type"] = fc->content_type;
  192. }
  193. res->headers["Content-Length"] = std::to_string(content_length);
  194. res->headers["Last-Modified"] = fc->last_modified;
  195. res->headers["Etag"] = fc->etag;
  196. }
  197. else if (res->body.size()) {
  198. content = res->body.c_str();
  199. content_length = res->body.size();
  200. }
  201. header = res->dump(true, false);
  202. if (header.size() + content_length <= SEND_BUFSIZE) {
  203. header.insert(header.size(), content, content_length);
  204. send_in_one_packet = true;
  205. }
  206. // send header
  207. nsend = send(event->fd, header.c_str(), header.size(), 0);
  208. if (nsend != header.size()) {
  209. hcu->log += asprintf("send header: %s", strerror(errno));
  210. goto send_error;
  211. }
  212. // send body
  213. if (!send_in_one_packet && content_length != 0) {
  214. //queue send ?
  215. //if (content_length > SEND_BUFSIZE) {
  216. //}
  217. nsend = send(event->fd, content, content_length, 0);
  218. if (nsend != res->body.size()) {
  219. hcu->log += asprintf("send body: %s", strerror(errno));
  220. goto send_error;
  221. }
  222. }
  223. hcu->log += asprintf("=>[%d %s]", res->status_code, http_status_str(res->status_code));
  224. hlogi("%s", hcu->log.c_str());
  225. goto end;
  226. }
  227. if (nrecv == sizeof(recvbuf)) {
  228. goto recv;
  229. }
  230. goto end;
  231. recv_error:
  232. disconnect:
  233. parser_error:
  234. send_error:
  235. hloge("%s", hcu->log.c_str());
  236. end:
  237. closesocket(event->fd);
  238. hevent_del(event);
  239. delete hcu;
  240. }
  241. static void on_accept(hevent_t* event, void* userdata) {
  242. //printf("on_accept listenfd=%d\n", event->fd);
  243. struct sockaddr_in localaddr, peeraddr;
  244. socklen_t addrlen = sizeof(struct sockaddr_in);
  245. getsockname(event->fd, (struct sockaddr*)&localaddr, &addrlen);
  246. accept:
  247. addrlen = sizeof(struct sockaddr_in);
  248. int connfd = accept(event->fd, (struct sockaddr*)&peeraddr, &addrlen);
  249. if (connfd < 0) {
  250. if (sockerrno == NIO_EAGAIN) {
  251. //goto accept_done;
  252. return;
  253. }
  254. else {
  255. perror("accept");
  256. hloge("accept failed: %s: %d", strerror(sockerrno), sockerrno);
  257. goto accept_error;
  258. }
  259. }
  260. {
  261. // new http_connect
  262. // delete on on_read
  263. http_connect_userdata* hcu = new http_connect_userdata;
  264. hcu->server = (http_server_t*)userdata;
  265. hcu->log += asprintf("[%s:%d]", inet_ntoa(peeraddr.sin_addr), ntohs(peeraddr.sin_port));
  266. nonblocking(connfd);
  267. hevent_read(event->loop, connfd, on_read, hcu);
  268. }
  269. goto accept;
  270. accept_error:
  271. closesocket(event->fd);
  272. hevent_del(event);
  273. }
  274. void handle_cached_files(htimer_t* timer, void* userdata) {
  275. FileCache* pfc = (FileCache*)userdata;
  276. if (pfc == NULL) {
  277. htimer_del(timer);
  278. return;
  279. }
  280. file_cache_t* fc = NULL;
  281. time_t tt;
  282. time(&tt);
  283. auto iter = pfc->cached_files.begin();
  284. while (iter != pfc->cached_files.end()) {
  285. fc = iter->second;
  286. if (tt - fc->stat_time > pfc->file_cached_time) {
  287. delete fc;
  288. iter = pfc->cached_files.erase(iter);
  289. continue;
  290. }
  291. ++iter;
  292. }
  293. }
  294. static void worker_proc(void* userdata) {
  295. http_server_t* server = (http_server_t*)userdata;
  296. int listenfd = server->listenfd;
  297. hloop_t loop;
  298. hloop_init(&loop);
  299. htimer_add(&loop, handle_cached_files, &s_filecache, s_filecache.file_cached_time*1000);
  300. hevent_accept(&loop, listenfd, on_accept, server);
  301. hloop_run(&loop);
  302. }
  303. int http_server_run(http_server_t* server, int wait) {
  304. // worker_processes
  305. if (server->worker_processes != 0 && g_worker_processes_num != 0 && g_worker_processes != NULL) {
  306. return ERR_OVER_LIMIT;
  307. }
  308. // service
  309. if (server->service == NULL) {
  310. server->service = &s_default_service;
  311. }
  312. // port
  313. server->listenfd = Listen(server->port);
  314. if (server->listenfd < 0) return server->listenfd;
  315. if (server->worker_processes == 0) {
  316. worker_proc(server);
  317. }
  318. else {
  319. // master-workers processes
  320. g_worker_processes_num = server->worker_processes;
  321. int bytes = g_worker_processes_num * sizeof(proc_ctx_t);
  322. g_worker_processes = (proc_ctx_t*)malloc(bytes);
  323. if (g_worker_processes == NULL) {
  324. perror("malloc");
  325. abort();
  326. }
  327. memset(g_worker_processes, 0, bytes);
  328. for (int i = 0; i < g_worker_processes_num; ++i) {
  329. proc_ctx_t* ctx = g_worker_processes + i;
  330. ctx->init = worker_init;
  331. ctx->init_userdata = NULL;
  332. ctx->proc = worker_proc;
  333. ctx->proc_userdata = server;
  334. spawn_proc(ctx);
  335. }
  336. }
  337. if (wait) {
  338. master_init(NULL);
  339. master_proc(NULL);
  340. }
  341. return 0;
  342. }