HttpServer.cpp 12 KB

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