1
0

HttpServer.cpp 10 KB

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