HttpServer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. #include "HttpServer.h"
  2. #include "h.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 18
  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. // base check
  42. if (readbytes < MIN_HTTP_REQUEST_LEN) {
  43. hloge("[%s:%d] http request too small", handler->ip, handler->port);
  44. hio_close(io);
  45. return;
  46. }
  47. for (int i = 0; i < 3; ++i) {
  48. if (!IS_GRAPH(buf[i])) {
  49. hloge("[%s:%d] http check failed", 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. return;
  79. }
  80. #ifdef WITH_NGHTTP2
  81. if (session->version == HTTP_V2) {
  82. // HTTP2 extra processing steps
  83. Http2Session* h2s = (Http2Session*)session;
  84. if (h2s->state == HSS_RECV_PING) {
  85. char* data = NULL;
  86. size_t len = 0;
  87. while (session->GetSendData(&data, &len)) {
  88. hio_write(io, data, len);
  89. }
  90. return;
  91. }
  92. else if ((h2s->state == HSS_RECV_HEADERS && req->method != HTTP_POST) || h2s->state == HSS_RECV_DATA) {
  93. goto handle_request;
  94. }
  95. else {
  96. // ignore other http2 frame
  97. return;
  98. }
  99. }
  100. // Upgrade: h2
  101. {
  102. auto iter_upgrade = req->headers.find("upgrade");
  103. if (iter_upgrade != req->headers.end()) {
  104. hlogi("[%s:%d] Upgrade: %s", handler->ip, handler->port, iter_upgrade->second.c_str());
  105. // h2/h2c
  106. if (strnicmp(iter_upgrade->second.c_str(), "h2", 2) == 0) {
  107. hio_write(io, HTTP2_UPGRADE_RESPONSE, strlen(HTTP2_UPGRADE_RESPONSE));
  108. SAFE_DELETE(handler->session);
  109. session = handler->session = HttpSession::New(HTTP_SERVER, HTTP_V2);
  110. if (session == NULL) {
  111. hloge("[%s:%d] unsupported HTTP2", handler->ip, handler->port);
  112. hio_close(io);
  113. return;
  114. }
  115. HttpRequest http1_req = *req;
  116. session->InitRequest(req);
  117. *req = http1_req;
  118. req->http_major = 2;
  119. req->http_minor = 0;
  120. // HTTP2_Settings: ignore
  121. //session->FeedRecvData(HTTP2_Settings, );
  122. }
  123. else {
  124. hio_close(io);
  125. return;
  126. }
  127. }
  128. }
  129. #endif
  130. handle_request:
  131. int ret = handler->HandleRequest();
  132. // prepare headers body
  133. // Server:
  134. static char s_Server[64] = {'\0'};
  135. if (s_Server[0] == '\0') {
  136. snprintf(s_Server, sizeof(s_Server), "httpd/%s", get_compile_version());
  137. }
  138. res->headers["Server"] = s_Server;
  139. // Connection:
  140. bool keepalive = true;
  141. auto iter_keepalive = req->headers.find("connection");
  142. if (iter_keepalive != req->headers.end()) {
  143. if (stricmp(iter_keepalive->second.c_str(), "keep-alive") == 0) {
  144. keepalive = true;
  145. }
  146. else if (stricmp(iter_keepalive->second.c_str(), "close") == 0) {
  147. keepalive = false;
  148. }
  149. }
  150. if (keepalive) {
  151. res->headers["Connection"] = "keep-alive";
  152. }
  153. else {
  154. res->headers["Connection"] = "close";
  155. }
  156. if (req->http_major == 1) {
  157. std::string header = res->Dump(true, false);
  158. hbuf_t sendbuf;
  159. bool send_in_one_packet = true;
  160. int content_length = res->ContentLength();
  161. if (handler->fc) {
  162. // no copy filebuf, more efficient
  163. handler->fc->prepend_header(header.c_str(), header.size());
  164. sendbuf = handler->fc->httpbuf;
  165. }
  166. else {
  167. if (content_length > (1<<20)) {
  168. send_in_one_packet = false;
  169. } else if (content_length != 0) {
  170. header.insert(header.size(), (const char*)res->Content(), content_length);
  171. }
  172. sendbuf.base = (char*)header.c_str();
  173. sendbuf.len = header.size();
  174. }
  175. // send header/body
  176. hio_write(io, sendbuf.base, sendbuf.len);
  177. if (send_in_one_packet == false) {
  178. // send body
  179. hio_write(io, res->Content(), content_length);
  180. }
  181. }
  182. else if (req->http_major == 2) {
  183. session->SubmitResponse(res);
  184. char* data = NULL;
  185. size_t len = 0;
  186. while (session->GetSendData(&data, &len)) {
  187. hio_write(io, data, len);
  188. }
  189. }
  190. hlogi("[%s:%d][%s %s]=>[%d %s]",
  191. handler->ip, handler->port,
  192. http_method_str(req->method), req->path.c_str(),
  193. res->status_code, http_status_str(res->status_code));
  194. if (keepalive) {
  195. handler->KeepAlive();
  196. handler->Reset();
  197. session->InitRequest(req);
  198. }
  199. else {
  200. hio_close(io);
  201. }
  202. }
  203. static void on_close(hio_t* io) {
  204. HttpHandler* handler = (HttpHandler*)hevent_userdata(io);
  205. if (handler) {
  206. SAFE_DELETE(handler->session);
  207. delete handler;
  208. hevent_set_userdata(io, NULL);
  209. }
  210. }
  211. static void on_accept(hio_t* io) {
  212. printd("on_accept connfd=%d\n", hio_fd(io));
  213. /*
  214. char localaddrstr[SOCKADDR_STRLEN] = {0};
  215. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  216. printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io),
  217. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  218. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  219. */
  220. HBuf* buf = (HBuf*)hloop_userdata(hevent_loop(io));
  221. hio_setcb_close(io, on_close);
  222. hio_setcb_read(io, on_recv);
  223. hio_set_readbuf(io, buf->base, buf->len);
  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 fflush_log(hidle_t* idle) {
  256. logger_fsync(hlog);
  257. }
  258. // for implement http_server_stop
  259. static hloop_t* s_loop = NULL;
  260. static void worker_proc(void* userdata) {
  261. http_server_t* server = (http_server_t*)userdata;
  262. int listenfd = server->listenfd;
  263. hloop_t* loop = hloop_new(0);
  264. s_loop = loop;
  265. // one loop one readbuf.
  266. HBuf readbuf;
  267. readbuf.resize(RECV_BUFSIZE);
  268. hloop_set_userdata(loop, &readbuf);
  269. hio_t* listenio = haccept(loop, listenfd, on_accept);
  270. hevent_set_userdata(listenio, server->service);
  271. if (server->ssl) {
  272. hio_enable_ssl(listenio);
  273. }
  274. // fflush logfile when idle
  275. logger_enable_fsync(hlog, 0);
  276. hidle_add(loop, fflush_log, INFINITE);
  277. // timer handle_cached_files
  278. htimer_t* timer = htimer_add(loop, handle_cached_files, s_filecache.file_cached_time*1000);
  279. hevent_set_userdata(timer, &s_filecache);
  280. hloop_run(loop);
  281. hloop_free(&loop);
  282. }
  283. int http_server_run(http_server_t* server, int wait) {
  284. // worker_processes
  285. if (server->worker_processes != 0 && g_worker_processes_num != 0 && g_worker_processes != NULL) {
  286. return ERR_OVER_LIMIT;
  287. }
  288. // service
  289. if (server->service == NULL) {
  290. server->service = &s_default_service;
  291. }
  292. // port
  293. server->listenfd = Listen(server->port, server->host);
  294. if (server->listenfd < 0) return server->listenfd;
  295. #ifdef OS_WIN
  296. if (server->worker_processes > 1) {
  297. server->worker_processes = 1;
  298. }
  299. #endif
  300. if (server->worker_processes == 0) {
  301. worker_proc(server);
  302. }
  303. else {
  304. // master-workers processes
  305. g_worker_processes_num = server->worker_processes;
  306. int bytes = g_worker_processes_num * sizeof(proc_ctx_t);
  307. g_worker_processes = (proc_ctx_t*)malloc(bytes);
  308. memset(g_worker_processes, 0, bytes);
  309. for (int i = 0; i < g_worker_processes_num; ++i) {
  310. proc_ctx_t* ctx = g_worker_processes + i;
  311. ctx->init = worker_init;
  312. ctx->init_userdata = NULL;
  313. ctx->proc = worker_proc;
  314. ctx->proc_userdata = server;
  315. spawn_proc(ctx);
  316. }
  317. if (wait) {
  318. master_init(NULL);
  319. master_proc(NULL);
  320. }
  321. }
  322. return 0;
  323. }
  324. // for SDK, just use for singleton
  325. int http_server_stop(http_server_t* server) {
  326. if (s_loop) {
  327. hloop_stop(s_loop);
  328. s_loop = NULL;
  329. }
  330. return 0;
  331. }