HttpServer.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. struct HttpServerPrivdata {
  14. std::vector<hloop_t*> loops;
  15. };
  16. static void on_recv(hio_t* io, void* _buf, int readbytes) {
  17. // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes);
  18. const char* buf = (const char*)_buf;
  19. HttpHandler* handler = (HttpHandler*)hevent_userdata(io);
  20. // HTTP1 / HTTP2 -> HttpSession -> InitRequest
  21. // recv -> FeedRecvData -> !WantRecv -> HttpRequest ->
  22. // HandleRequest -> HttpResponse -> SubmitResponse -> while (GetSendData) -> send
  23. if (handler->session == NULL) {
  24. // check request-line
  25. if (readbytes < MIN_HTTP_REQUEST_LEN) {
  26. hloge("[%s:%d] http request-line too small", handler->ip, handler->port);
  27. hio_close(io);
  28. return;
  29. }
  30. for (int i = 0; i < MIN_HTTP_REQUEST_LEN; ++i) {
  31. if (!IS_GRAPH(buf[i])) {
  32. hloge("[%s:%d] http request-line not plain", handler->ip, handler->port);
  33. hio_close(io);
  34. return;
  35. }
  36. }
  37. http_version version = HTTP_V1;
  38. if (strncmp((char*)buf, HTTP2_MAGIC, MIN(readbytes, HTTP2_MAGIC_LEN)) == 0) {
  39. version = HTTP_V2;
  40. handler->req.http_major = 2;
  41. handler->req.http_minor = 0;
  42. }
  43. handler->session = HttpSession::New(HTTP_SERVER, version);
  44. if (handler->session == NULL) {
  45. hloge("[%s:%d] unsupported HTTP%d", handler->ip, handler->port, (int)version);
  46. hio_close(io);
  47. return;
  48. }
  49. handler->session->InitRequest(&handler->req);
  50. }
  51. HttpSession* session = handler->session;
  52. HttpRequest* req = &handler->req;
  53. HttpResponse* res = &handler->res;
  54. int nfeed = session->FeedRecvData((const char*)buf, readbytes);
  55. if (nfeed != readbytes) {
  56. hloge("[%s:%d] http parse error: %s", handler->ip, handler->port, session->StrError(session->GetError()));
  57. hio_close(io);
  58. return;
  59. }
  60. if (session->WantRecv()) {
  61. // NOTE: KeepAlive will reset keepalive_timer,
  62. // if no data recv within keepalive timeout, closesocket actively.
  63. handler->KeepAlive();
  64. return;
  65. }
  66. #ifdef WITH_NGHTTP2
  67. if (session->version == HTTP_V2) {
  68. // HTTP2 extra processing steps
  69. Http2Session* h2s = (Http2Session*)session;
  70. if (h2s->state == HSS_RECV_PING) {
  71. char* data = NULL;
  72. size_t len = 0;
  73. while (session->GetSendData(&data, &len)) {
  74. hio_write(io, data, len);
  75. }
  76. return;
  77. }
  78. else if ((h2s->state == HSS_RECV_HEADERS && req->method != HTTP_POST) || h2s->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. SAFE_DELETE(handler->session);
  95. session = handler->session = HttpSession::New(HTTP_SERVER, HTTP_V2);
  96. if (session == NULL) {
  97. hloge("[%s:%d] unsupported HTTP2", handler->ip, handler->port);
  98. hio_close(io);
  99. return;
  100. }
  101. HttpRequest http1_req = *req;
  102. session->InitRequest(req);
  103. *req = http1_req;
  104. req->http_major = 2;
  105. req->http_minor = 0;
  106. // HTTP2_Settings: ignore
  107. // session->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", get_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. if (keepalive) {
  137. res->headers["Connection"] = "keep-alive";
  138. }
  139. else {
  140. res->headers["Connection"] = "close";
  141. }
  142. if (req->http_major == 1) {
  143. std::string header = res->Dump(true, false);
  144. hbuf_t sendbuf;
  145. bool send_in_one_packet = true;
  146. int content_length = res->ContentLength();
  147. if (handler->fc) {
  148. // no copy filebuf, more efficient
  149. handler->fc->prepend_header(header.c_str(), header.size());
  150. sendbuf = handler->fc->httpbuf;
  151. }
  152. else {
  153. if (content_length > (1 << 20)) {
  154. send_in_one_packet = false;
  155. }
  156. else if (content_length != 0) {
  157. header.insert(header.size(), (const char*)res->Content(), content_length);
  158. }
  159. sendbuf.base = (char*)header.c_str();
  160. sendbuf.len = header.size();
  161. }
  162. // send header/body
  163. hio_write(io, sendbuf.base, sendbuf.len);
  164. if (send_in_one_packet == false) {
  165. // send body
  166. hio_write(io, res->Content(), content_length);
  167. }
  168. }
  169. else if (req->http_major == 2) {
  170. session->SubmitResponse(res);
  171. char* data = NULL;
  172. size_t len = 0;
  173. while (session->GetSendData(&data, &len)) {
  174. hio_write(io, data, len);
  175. }
  176. }
  177. hlogi("[%s:%d][%s %s]=>[%d %s]",
  178. handler->ip, handler->port,
  179. http_method_str(req->method), req->path.c_str(),
  180. res->status_code, http_status_str(res->status_code));
  181. if (keepalive) {
  182. handler->KeepAlive();
  183. handler->Reset();
  184. session->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->session);
  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. // new HttpHandler
  211. // delete on_close
  212. HttpHandler* handler = new HttpHandler;
  213. handler->service = (HttpService*)hevent_userdata(io);
  214. handler->files = &s_filecache;
  215. sockaddr_ip((sockaddr_un*)hio_peeraddr(io), handler->ip, sizeof(handler->ip));
  216. handler->port = sockaddr_port((sockaddr_un*)hio_peeraddr(io));
  217. handler->io = 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.push_back(loop);
  262. hloop_run(loop);
  263. hloop_free(&loop);
  264. }
  265. int http_server_run(http_server_t* server, int wait) {
  266. // service
  267. if (server->service == NULL) {
  268. server->service = &s_default_service;
  269. }
  270. // port
  271. server->listenfd = Listen(server->port, server->host);
  272. if (server->listenfd < 0) return server->listenfd;
  273. // privdata
  274. server->privdata = new HttpServerPrivdata;
  275. if (server->worker_processes) {
  276. return master_workers_run(worker_fn, server, server->worker_processes, server->worker_threads, wait);
  277. }
  278. else {
  279. // NOTE: master_workers_run use global-vars that may be used by other,
  280. // so we implement Multi-Threads directly.
  281. int worker_threads = server->worker_threads;
  282. if (worker_threads == 0) worker_threads = 1;
  283. if (wait) {
  284. for (int i = 1; i < worker_threads; ++i) {
  285. hthread_create((hthread_routine)worker_fn, server);
  286. }
  287. worker_fn(server);
  288. }
  289. else {
  290. for (int i = 0; i < worker_threads; ++i) {
  291. hthread_create((hthread_routine)worker_fn, server);
  292. }
  293. }
  294. return 0;
  295. }
  296. }
  297. int http_server_stop(http_server_t* server) {
  298. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  299. for (auto& loop : privdata->loops) {
  300. hloop_stop(loop);
  301. }
  302. SAFE_DELETE(privdata);
  303. return 0;
  304. }