1
0

http_server.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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) {
  72. //printf("on_read fd=%d readbytes=%d\n", io->fd, readbytes);
  73. http_connect_userdata* hcu = (http_connect_userdata*)io->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. hclose(io);
  199. }
  200. }
  201. static void on_close(hio_t* io) {
  202. http_connect_userdata* hcu = (http_connect_userdata*)io->userdata;
  203. if (hcu) {
  204. hlogi("%s", hcu->log.c_str());
  205. delete hcu;
  206. io->userdata = NULL;
  207. }
  208. }
  209. static void on_accept(hio_t* io, int connfd) {
  210. //printf("on_accept listenfd=%d connfd=%d\n", io->fd, connfd);
  211. struct sockaddr_in* localaddr = (struct sockaddr_in*)io->localaddr;
  212. struct sockaddr_in* peeraddr = (struct sockaddr_in*)io->peeraddr;
  213. //char localip[64];
  214. char peerip[64];
  215. //inet_ntop(AF_INET, &localaddr->sin_addr, localip, sizeof(localip));
  216. inet_ntop(AF_INET, &peeraddr->sin_addr, peerip, sizeof(peerip));
  217. //printd("accept listenfd=%d connfd=%d [%s:%d] <= [%s:%d]\n", io->fd, connfd,
  218. //localip, ntohs(localaddr->sin_port),
  219. //peerip, 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*)io->userdata;
  224. hcu->log += asprintf("[%s:%d]", peerip, ntohs(peeraddr->sin_port));
  225. nonblocking(connfd);
  226. HBuf* buf = (HBuf*)io->loop->userdata;
  227. hio_t* connio = hread(io->loop, connfd, buf->base, buf->len, on_read);
  228. connio->close_cb = on_close;
  229. connio->userdata = hcu;
  230. }
  231. void handle_cached_files(htimer_t* timer) {
  232. FileCache* pfc = (FileCache*)timer->userdata;
  233. if (pfc == NULL) {
  234. htimer_del(timer);
  235. return;
  236. }
  237. file_cache_t* fc = NULL;
  238. time_t tt;
  239. time(&tt);
  240. auto iter = pfc->cached_files.begin();
  241. while (iter != pfc->cached_files.end()) {
  242. fc = iter->second;
  243. if (tt - fc->stat_time > pfc->file_cached_time) {
  244. delete fc;
  245. iter = pfc->cached_files.erase(iter);
  246. continue;
  247. }
  248. ++iter;
  249. }
  250. }
  251. void fflush_log(hidle_t* idle) {
  252. hlog_fflush();
  253. }
  254. static void worker_proc(void* userdata) {
  255. http_server_t* server = (http_server_t*)userdata;
  256. int listenfd = server->listenfd;
  257. hloop_t loop;
  258. hloop_init(&loop);
  259. // one loop one readbuf.
  260. HBuf readbuf;
  261. readbuf.resize(RECV_BUFSIZE);
  262. loop.userdata = &readbuf;
  263. hio_t* listenio = haccept(&loop, listenfd, on_accept);
  264. listenio->userdata = server;
  265. // fflush logfile when idle
  266. hlog_set_fflush(0);
  267. hidle_add(&loop, fflush_log, INFINITE);
  268. // timer handle_cached_files
  269. htimer_t* timer = htimer_add(&loop, handle_cached_files, s_filecache.file_cached_time*1000);
  270. timer->userdata = &s_filecache;
  271. hloop_run(&loop);
  272. }
  273. int http_server_run(http_server_t* server, int wait) {
  274. // worker_processes
  275. if (server->worker_processes != 0 && g_worker_processes_num != 0 && g_worker_processes != NULL) {
  276. return ERR_OVER_LIMIT;
  277. }
  278. // service
  279. if (server->service == NULL) {
  280. server->service = &s_default_service;
  281. }
  282. // port
  283. server->listenfd = Listen(server->port);
  284. if (server->listenfd < 0) return server->listenfd;
  285. #ifdef OS_WIN
  286. if (server->worker_processes > 1) {
  287. server->worker_processes = 1;
  288. }
  289. #endif
  290. if (server->worker_processes == 0) {
  291. worker_proc(server);
  292. }
  293. else {
  294. // master-workers processes
  295. g_worker_processes_num = server->worker_processes;
  296. int bytes = g_worker_processes_num * sizeof(proc_ctx_t);
  297. g_worker_processes = (proc_ctx_t*)malloc(bytes);
  298. if (g_worker_processes == NULL) {
  299. perror("malloc");
  300. abort();
  301. }
  302. memset(g_worker_processes, 0, bytes);
  303. for (int i = 0; i < g_worker_processes_num; ++i) {
  304. proc_ctx_t* ctx = g_worker_processes + i;
  305. ctx->init = worker_init;
  306. ctx->init_userdata = NULL;
  307. ctx->proc = worker_proc;
  308. ctx->proc_userdata = server;
  309. spawn_proc(ctx);
  310. }
  311. }
  312. if (wait) {
  313. master_init(NULL);
  314. master_proc(NULL);
  315. }
  316. return 0;
  317. }