1
0

HttpServer.cpp 11 KB

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