HttpServer.cpp 10 KB

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