HttpServer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. #include "HttpServer.h"
  2. #include "hv.h"
  3. #include "hmain.h"
  4. #include "hloop.h"
  5. #include "http2def.h"
  6. #include "FileCache.h"
  7. #include "HttpHandler.h"
  8. #include "Http2Session.h"
  9. #define RECV_BUFSIZE 8192
  10. #define SEND_BUFSIZE 8192
  11. #define MIN_HTTP_REQUEST "GET / HTTP/1.1\r\n\r\n"
  12. #define MIN_HTTP_REQUEST_LEN 14 // exclude CRLF
  13. static HttpService s_default_service;
  14. static FileCache s_filecache;
  15. static void master_init(void* userdata) {
  16. #ifdef OS_UNIX
  17. char proctitle[256] = {0};
  18. snprintf(proctitle, sizeof(proctitle), "%s: master process", g_main_ctx.program_name);
  19. setproctitle(proctitle);
  20. #endif
  21. }
  22. static void master_proc(void* userdata) {
  23. while (1) sleep(1);
  24. }
  25. static void worker_init(void* userdata) {
  26. #ifdef OS_UNIX
  27. char proctitle[256] = {0};
  28. snprintf(proctitle, sizeof(proctitle), "%s: worker process", g_main_ctx.program_name);
  29. setproctitle(proctitle);
  30. signal(SIGNAL_RELOAD, signal_handler);
  31. #endif
  32. }
  33. static void on_recv(hio_t* io, void* _buf, int readbytes) {
  34. // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes);
  35. const char* buf = (const char*)_buf;
  36. HttpHandler* handler = (HttpHandler*)hevent_userdata(io);
  37. // HTTP1 / HTTP2 -> HttpSession -> InitRequest
  38. // recv -> FeedRecvData -> !WantRecv -> HttpRequest ->
  39. // HandleRequest -> HttpResponse -> SubmitResponse -> while (GetSendData) -> send
  40. if (handler->session == NULL) {
  41. // check request-line
  42. if (readbytes < MIN_HTTP_REQUEST_LEN) {
  43. hloge("[%s:%d] http request-line too small", handler->ip, handler->port);
  44. hio_close(io);
  45. return;
  46. }
  47. for (int i = 0; i < MIN_HTTP_REQUEST_LEN; ++i) {
  48. if (!IS_GRAPH(buf[i])) {
  49. hloge("[%s:%d] http request-line not plain", handler->ip, handler->port);
  50. hio_close(io);
  51. return;
  52. }
  53. }
  54. http_version version = HTTP_V1;
  55. if (strncmp((char*)buf, HTTP2_MAGIC, MIN(readbytes, HTTP2_MAGIC_LEN)) == 0) {
  56. version = HTTP_V2;
  57. handler->req.http_major = 2;
  58. handler->req.http_minor = 0;
  59. }
  60. handler->session = HttpSession::New(HTTP_SERVER, version);
  61. if (handler->session == NULL) {
  62. hloge("[%s:%d] unsupported HTTP%d", handler->ip, handler->port, (int)version);
  63. hio_close(io);
  64. return;
  65. }
  66. handler->session->InitRequest(&handler->req);
  67. }
  68. HttpSession* session = handler->session;
  69. HttpRequest* req = &handler->req;
  70. HttpResponse* res = &handler->res;
  71. int nfeed = session->FeedRecvData((const char*)buf, readbytes);
  72. if (nfeed != readbytes) {
  73. hloge("[%s:%d] http parse error: %s", handler->ip, handler->port, session->StrError(session->GetError()));
  74. hio_close(io);
  75. return;
  76. }
  77. if (session->WantRecv()) {
  78. // NOTE: KeepAlive will reset keepalive_timer,
  79. // if no data recv within keepalive timeout, closesocket actively.
  80. handler->KeepAlive();
  81. return;
  82. }
  83. #ifdef WITH_NGHTTP2
  84. if (session->version == HTTP_V2) {
  85. // HTTP2 extra processing steps
  86. Http2Session* h2s = (Http2Session*)session;
  87. if (h2s->state == HSS_RECV_PING) {
  88. char* data = NULL;
  89. size_t len = 0;
  90. while (session->GetSendData(&data, &len)) {
  91. hio_write(io, data, len);
  92. }
  93. return;
  94. }
  95. else if ((h2s->state == HSS_RECV_HEADERS && req->method != HTTP_POST) || h2s->state == HSS_RECV_DATA) {
  96. goto handle_request;
  97. }
  98. else {
  99. // ignore other http2 frame
  100. return;
  101. }
  102. }
  103. // Upgrade: h2
  104. {
  105. auto iter_upgrade = req->headers.find("upgrade");
  106. if (iter_upgrade != req->headers.end()) {
  107. hlogi("[%s:%d] Upgrade: %s", handler->ip, handler->port, iter_upgrade->second.c_str());
  108. // h2/h2c
  109. if (strnicmp(iter_upgrade->second.c_str(), "h2", 2) == 0) {
  110. hio_write(io, HTTP2_UPGRADE_RESPONSE, strlen(HTTP2_UPGRADE_RESPONSE));
  111. SAFE_DELETE(handler->session);
  112. session = handler->session = HttpSession::New(HTTP_SERVER, HTTP_V2);
  113. if (session == NULL) {
  114. hloge("[%s:%d] unsupported HTTP2", handler->ip, handler->port);
  115. hio_close(io);
  116. return;
  117. }
  118. HttpRequest http1_req = *req;
  119. session->InitRequest(req);
  120. *req = http1_req;
  121. req->http_major = 2;
  122. req->http_minor = 0;
  123. // HTTP2_Settings: ignore
  124. // session->FeedRecvData(HTTP2_Settings, );
  125. }
  126. else {
  127. hio_close(io);
  128. return;
  129. }
  130. }
  131. }
  132. #endif
  133. handle_request:
  134. int ret = handler->HandleRequest();
  135. // prepare headers body
  136. // Server:
  137. static char s_Server[64] = {'\0'};
  138. if (s_Server[0] == '\0') {
  139. snprintf(s_Server, sizeof(s_Server), "httpd/%s", get_compile_version());
  140. }
  141. res->headers["Server"] = s_Server;
  142. // Connection:
  143. bool keepalive = true;
  144. auto iter_keepalive = req->headers.find("connection");
  145. if (iter_keepalive != req->headers.end()) {
  146. if (stricmp(iter_keepalive->second.c_str(), "keep-alive") == 0) {
  147. keepalive = true;
  148. }
  149. else if (stricmp(iter_keepalive->second.c_str(), "close") == 0) {
  150. keepalive = false;
  151. }
  152. }
  153. if (keepalive) {
  154. res->headers["Connection"] = "keep-alive";
  155. }
  156. else {
  157. res->headers["Connection"] = "close";
  158. }
  159. if (req->http_major == 1) {
  160. std::string header = res->Dump(true, false);
  161. hbuf_t sendbuf;
  162. bool send_in_one_packet = true;
  163. int content_length = res->ContentLength();
  164. if (handler->fc) {
  165. // no copy filebuf, more efficient
  166. handler->fc->prepend_header(header.c_str(), header.size());
  167. sendbuf = handler->fc->httpbuf;
  168. }
  169. else {
  170. if (content_length > (1 << 20)) {
  171. send_in_one_packet = false;
  172. }
  173. else if (content_length != 0) {
  174. header.insert(header.size(), (const char*)res->Content(), content_length);
  175. }
  176. sendbuf.base = (char*)header.c_str();
  177. sendbuf.len = header.size();
  178. }
  179. // send header/body
  180. hio_write(io, sendbuf.base, sendbuf.len);
  181. if (send_in_one_packet == false) {
  182. // send body
  183. hio_write(io, res->Content(), content_length);
  184. }
  185. }
  186. else if (req->http_major == 2) {
  187. session->SubmitResponse(res);
  188. char* data = NULL;
  189. size_t len = 0;
  190. while (session->GetSendData(&data, &len)) {
  191. hio_write(io, data, len);
  192. }
  193. }
  194. hlogi("[%s:%d][%s %s]=>[%d %s]",
  195. handler->ip, handler->port,
  196. http_method_str(req->method), req->path.c_str(),
  197. res->status_code, http_status_str(res->status_code));
  198. if (keepalive) {
  199. handler->KeepAlive();
  200. handler->Reset();
  201. session->InitRequest(req);
  202. }
  203. else {
  204. hio_close(io);
  205. }
  206. }
  207. static void on_close(hio_t* io) {
  208. HttpHandler* handler = (HttpHandler*)hevent_userdata(io);
  209. if (handler) {
  210. SAFE_DELETE(handler->session);
  211. delete handler;
  212. hevent_set_userdata(io, NULL);
  213. }
  214. }
  215. static void on_accept(hio_t* io) {
  216. printd("on_accept connfd=%d\n", hio_fd(io));
  217. /*
  218. char localaddrstr[SOCKADDR_STRLEN] = {0};
  219. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  220. printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io),
  221. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  222. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  223. */
  224. HBuf* buf = (HBuf*)hloop_userdata(hevent_loop(io));
  225. hio_setcb_close(io, on_close);
  226. hio_setcb_read(io, on_recv);
  227. hio_set_readbuf(io, buf->base, buf->len);
  228. hio_read(io);
  229. // new HttpHandler
  230. // delete on_close
  231. HttpHandler* handler = new HttpHandler;
  232. handler->service = (HttpService*)hevent_userdata(io);
  233. handler->files = &s_filecache;
  234. sockaddr_ip((sockaddr_un*)hio_peeraddr(io), handler->ip, sizeof(handler->ip));
  235. handler->port = sockaddr_port((sockaddr_un*)hio_peeraddr(io));
  236. handler->io = io;
  237. hevent_set_userdata(io, handler);
  238. }
  239. static void handle_cached_files(htimer_t* timer) {
  240. FileCache* pfc = (FileCache*)hevent_userdata(timer);
  241. if (pfc == NULL) {
  242. htimer_del(timer);
  243. return;
  244. }
  245. file_cache_t* fc = NULL;
  246. time_t tt;
  247. time(&tt);
  248. auto iter = pfc->cached_files.begin();
  249. while (iter != pfc->cached_files.end()) {
  250. fc = iter->second;
  251. if (tt - fc->stat_time > pfc->file_cached_time) {
  252. delete fc;
  253. iter = pfc->cached_files.erase(iter);
  254. continue;
  255. }
  256. ++iter;
  257. }
  258. }
  259. static void fsync_logfile(hidle_t* idle) {
  260. hlog_fsync();
  261. }
  262. static void worker_proc(void* userdata) {
  263. http_server_t* server = (http_server_t*)userdata;
  264. int listenfd = server->listenfd;
  265. hloop_t* loop = hloop_new(0);
  266. // for SDK implement http_server_stop
  267. if (server->worker_processes == 0) {
  268. server->privdata = (void*)loop;
  269. }
  270. // one loop one readbuf.
  271. HBuf readbuf;
  272. readbuf.resize(RECV_BUFSIZE);
  273. hloop_set_userdata(loop, &readbuf);
  274. hio_t* listenio = haccept(loop, listenfd, on_accept);
  275. hevent_set_userdata(listenio, server->service);
  276. if (server->ssl) {
  277. hio_enable_ssl(listenio);
  278. }
  279. // fsync logfile when idle
  280. hlog_disable_fsync();
  281. hidle_add(loop, fsync_logfile, INFINITE);
  282. // timer handle_cached_files
  283. htimer_t* timer = htimer_add(loop, handle_cached_files, s_filecache.file_cached_time * 1000);
  284. hevent_set_userdata(timer, &s_filecache);
  285. hloop_run(loop);
  286. hloop_free(&loop);
  287. }
  288. int http_server_run(http_server_t* server, int wait) {
  289. // worker_processes
  290. if (server->worker_processes != 0 && g_worker_processes_num != 0 && g_worker_processes != NULL) {
  291. return ERR_OVER_LIMIT;
  292. }
  293. // service
  294. if (server->service == NULL) {
  295. server->service = &s_default_service;
  296. }
  297. // port
  298. server->listenfd = Listen(server->port, server->host);
  299. if (server->listenfd < 0) return server->listenfd;
  300. #ifdef OS_WIN
  301. if (server->worker_processes > 1) {
  302. server->worker_processes = 1;
  303. }
  304. #endif
  305. if (server->worker_processes == 0) {
  306. worker_proc(server);
  307. }
  308. else {
  309. // master-workers processes
  310. g_worker_processes_num = server->worker_processes;
  311. int bytes = g_worker_processes_num * sizeof(proc_ctx_t);
  312. g_worker_processes = (proc_ctx_t*)malloc(bytes);
  313. memset(g_worker_processes, 0, bytes);
  314. for (int i = 0; i < g_worker_processes_num; ++i) {
  315. proc_ctx_t* ctx = g_worker_processes + i;
  316. ctx->init = worker_init;
  317. ctx->init_userdata = NULL;
  318. ctx->proc = worker_proc;
  319. ctx->proc_userdata = server;
  320. spawn_proc(ctx);
  321. }
  322. if (wait) {
  323. master_init(NULL);
  324. master_proc(NULL);
  325. }
  326. }
  327. return 0;
  328. }
  329. int http_server_stop(http_server_t* server) {
  330. if (server->worker_processes == 0) {
  331. if (server->privdata) {
  332. hloop_t* loop = (hloop_t*)server->privdata;
  333. hloop_stop(loop);
  334. server->privdata = NULL;
  335. }
  336. }
  337. return 0;
  338. }