HttpServer.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. #include "HttpServer.h"
  2. #include "hv.h"
  3. #include "hssl.h"
  4. #include "hmain.h"
  5. #include "httpdef.h"
  6. #include "http2def.h"
  7. #include "wsdef.h"
  8. #include "EventLoop.h"
  9. using namespace hv;
  10. #include "HttpHandler.h"
  11. #define MIN_HTTP_REQUEST "GET / HTTP/1.1\r\n\r\n"
  12. #define MIN_HTTP_REQUEST_LEN 14 // exclude CRLF
  13. static void on_accept(hio_t* io);
  14. static void on_recv(hio_t* io, void* _buf, int readbytes);
  15. static void on_close(hio_t* io);
  16. struct HttpServerPrivdata {
  17. std::vector<EventLoopPtr> loops;
  18. std::vector<hthread_t> threads;
  19. std::mutex mutex_;
  20. std::shared_ptr<HttpService> service;
  21. FileCache filecache;
  22. };
  23. static void on_recv(hio_t* io, void* _buf, int readbytes) {
  24. // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes);
  25. const char* buf = (const char*)_buf;
  26. HttpHandler* handler = (HttpHandler*)hevent_userdata(io);
  27. assert(handler != NULL);
  28. // HttpHandler::Init(http_version) -> upgrade ? SwitchHTTP2 / SwitchWebSocket
  29. // on_recv -> FeedRecvData -> HttpRequest
  30. // onComplete -> HandleRequest -> HttpResponse -> while (GetSendData) -> send
  31. HttpHandler::ProtocolType protocol = handler->protocol;
  32. if (protocol == HttpHandler::UNKNOWN) {
  33. // check request-line
  34. if (readbytes < MIN_HTTP_REQUEST_LEN) {
  35. hloge("[%s:%d] http request-line too small", handler->ip, handler->port);
  36. hio_close(io);
  37. return;
  38. }
  39. for (int i = 0; i < MIN_HTTP_REQUEST_LEN; ++i) {
  40. if (!IS_GRAPH(buf[i])) {
  41. hloge("[%s:%d] http request-line not plain", handler->ip, handler->port);
  42. hio_close(io);
  43. return;
  44. }
  45. }
  46. int http_version = 1;
  47. if (strncmp((char*)buf, HTTP2_MAGIC, MIN(readbytes, HTTP2_MAGIC_LEN)) == 0) {
  48. http_version = 2;
  49. }
  50. if (!handler->Init(http_version, io)) {
  51. hloge("[%s:%d] unsupported HTTP%d", handler->ip, handler->port, http_version);
  52. hio_close(io);
  53. return;
  54. }
  55. }
  56. int nfeed = handler->FeedRecvData(buf, readbytes);
  57. if (nfeed != readbytes) {
  58. hio_close(io);
  59. return;
  60. }
  61. hloop_t* loop = hevent_loop(io);
  62. HttpParser* parser = handler->parser.get();
  63. HttpRequest* req = handler->req.get();
  64. HttpResponse* resp = handler->resp.get();
  65. if (handler->proxy) {
  66. return;
  67. }
  68. if (protocol == HttpHandler::WEBSOCKET) {
  69. return;
  70. }
  71. if (parser->WantRecv()) {
  72. return;
  73. }
  74. // Server:
  75. static char s_Server[64] = {'\0'};
  76. if (s_Server[0] == '\0') {
  77. snprintf(s_Server, sizeof(s_Server), "httpd/%s", hv_compile_version());
  78. }
  79. resp->headers["Server"] = s_Server;
  80. // Connection:
  81. bool keepalive = handler->keepalive;
  82. resp->headers["Connection"] = keepalive ? "keep-alive" : "close";
  83. // Upgrade:
  84. bool upgrade = false;
  85. HttpHandler::ProtocolType upgrade_protocol = HttpHandler::UNKNOWN;
  86. auto iter_upgrade = req->headers.find("upgrade");
  87. if (iter_upgrade != req->headers.end()) {
  88. upgrade = true;
  89. const char* upgrade_proto = iter_upgrade->second.c_str();
  90. hlogi("[%s:%d] Upgrade: %s", handler->ip, handler->port, upgrade_proto);
  91. // websocket
  92. if (stricmp(upgrade_proto, "websocket") == 0) {
  93. /*
  94. HTTP/1.1 101 Switching Protocols
  95. Connection: Upgrade
  96. Upgrade: websocket
  97. Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
  98. */
  99. resp->status_code = HTTP_STATUS_SWITCHING_PROTOCOLS;
  100. resp->headers["Connection"] = "Upgrade";
  101. resp->headers["Upgrade"] = "websocket";
  102. auto iter_key = req->headers.find(SEC_WEBSOCKET_KEY);
  103. if (iter_key != req->headers.end()) {
  104. char ws_accept[32] = {0};
  105. ws_encode_key(iter_key->second.c_str(), ws_accept);
  106. resp->headers[SEC_WEBSOCKET_ACCEPT] = ws_accept;
  107. }
  108. upgrade_protocol = HttpHandler::WEBSOCKET;
  109. // NOTE: SwitchWebSocket after send handshake response
  110. }
  111. // h2/h2c
  112. else if (strnicmp(upgrade_proto, "h2", 2) == 0) {
  113. /*
  114. HTTP/1.1 101 Switching Protocols
  115. Connection: Upgrade
  116. Upgrade: h2c
  117. */
  118. hio_write(io, HTTP2_UPGRADE_RESPONSE, strlen(HTTP2_UPGRADE_RESPONSE));
  119. if (!handler->SwitchHTTP2()) {
  120. hloge("[%s:%d] unsupported HTTP2", handler->ip, handler->port);
  121. hio_close(io);
  122. return;
  123. }
  124. parser = handler->parser.get();
  125. }
  126. else {
  127. hio_close(io);
  128. return;
  129. }
  130. }
  131. int status_code = 200;
  132. if (parser->IsComplete() && !upgrade) {
  133. status_code = handler->HandleHttpRequest();
  134. }
  135. char* data = NULL;
  136. size_t len = 0;
  137. while (handler->GetSendData(&data, &len)) {
  138. // printf("%.*s\n", (int)len, data);
  139. if (data && len) {
  140. hio_write(io, data, len);
  141. }
  142. }
  143. // LOG
  144. hlogi("[%ld-%ld][%s:%d][%s %s]=>[%d %s]",
  145. hloop_pid(loop), hloop_tid(loop),
  146. handler->ip, handler->port,
  147. http_method_str(req->method), req->path.c_str(),
  148. resp->status_code, resp->status_message());
  149. // switch protocol to websocket
  150. if (upgrade && upgrade_protocol == HttpHandler::WEBSOCKET) {
  151. if (!handler->SwitchWebSocket(io)) {
  152. hloge("[%s:%d] unsupported websocket", handler->ip, handler->port);
  153. hio_close(io);
  154. return;
  155. }
  156. // onopen
  157. handler->WebSocketOnOpen();
  158. return;
  159. }
  160. if (status_code && !keepalive) {
  161. hio_close(io);
  162. }
  163. }
  164. static void on_close(hio_t* io) {
  165. HttpHandler* handler = (HttpHandler*)hevent_userdata(io);
  166. if (handler == NULL) return;
  167. // close proxy
  168. if (handler->proxy) {
  169. hio_close_upstream(io);
  170. }
  171. // onclose
  172. if (handler->protocol == HttpHandler::WEBSOCKET) {
  173. handler->WebSocketOnClose();
  174. } else {
  175. if (handler->writer && handler->writer->onclose) {
  176. handler->writer->onclose();
  177. }
  178. }
  179. EventLoop* loop = currentThreadEventLoop;
  180. if (loop) {
  181. --loop->connectionNum;
  182. }
  183. hevent_set_userdata(io, NULL);
  184. delete handler;
  185. }
  186. static void on_accept(hio_t* io) {
  187. http_server_t* server = (http_server_t*)hevent_userdata(io);
  188. HttpService* service = server->service;
  189. /*
  190. printf("on_accept connfd=%d\n", hio_fd(io));
  191. char localaddrstr[SOCKADDR_STRLEN] = {0};
  192. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  193. printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io),
  194. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  195. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  196. */
  197. EventLoop* loop = currentThreadEventLoop;
  198. if (loop->connectionNum >= server->worker_connections) {
  199. hlogw("over worker_connections");
  200. hio_close(io);
  201. return;
  202. }
  203. ++loop->connectionNum;
  204. hio_setcb_close(io, on_close);
  205. hio_setcb_read(io, on_recv);
  206. hio_read(io);
  207. if (service->keepalive_timeout > 0) {
  208. hio_set_keepalive_timeout(io, service->keepalive_timeout);
  209. }
  210. // new HttpHandler, delete on_close
  211. HttpHandler* handler = new HttpHandler;
  212. // ssl
  213. handler->ssl = hio_is_ssl(io);
  214. // ip:port
  215. sockaddr_u* peeraddr = (sockaddr_u*)hio_peeraddr(io);
  216. sockaddr_ip(peeraddr, handler->ip, sizeof(handler->ip));
  217. handler->port = sockaddr_port(peeraddr);
  218. // http service
  219. handler->service = service;
  220. // websocket service
  221. handler->ws_service = server->ws;
  222. // FileCache
  223. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  224. handler->files = &privdata->filecache;
  225. hevent_set_userdata(io, handler);
  226. }
  227. static void loop_thread(void* userdata) {
  228. http_server_t* server = (http_server_t*)userdata;
  229. HttpService* service = server->service;
  230. EventLoopPtr loop(new EventLoop);
  231. hloop_t* hloop = loop->loop();
  232. // http
  233. if (server->listenfd[0] >= 0) {
  234. hio_t* listenio = haccept(hloop, server->listenfd[0], on_accept);
  235. hevent_set_userdata(listenio, server);
  236. }
  237. // https
  238. if (server->listenfd[1] >= 0) {
  239. hio_t* listenio = haccept(hloop, server->listenfd[1], on_accept);
  240. hevent_set_userdata(listenio, server);
  241. hio_enable_ssl(listenio);
  242. }
  243. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  244. privdata->mutex_.lock();
  245. if (privdata->loops.size() == 0) {
  246. // NOTE: fsync logfile when idle
  247. hlog_disable_fsync();
  248. hidle_add(hloop, [](hidle_t*) {
  249. hlog_fsync();
  250. }, INFINITE);
  251. // NOTE: add timer to update s_date every 1s
  252. htimer_add(hloop, [](htimer_t* timer) {
  253. gmtime_fmt(hloop_now(hevent_loop(timer)), HttpMessage::s_date);
  254. }, 1000);
  255. // document_root
  256. if (service->document_root.size() > 0 && service->GetStaticFilepath("/").empty()) {
  257. service->Static("/", service->document_root.c_str());
  258. }
  259. // FileCache
  260. FileCache* filecache = &privdata->filecache;
  261. filecache->stat_interval = service->file_cache_stat_interval;
  262. filecache->expired_time = service->file_cache_expired_time;
  263. if (filecache->expired_time > 0) {
  264. // NOTE: add timer to remove expired file cache
  265. htimer_t* timer = htimer_add(hloop, [](htimer_t* timer) {
  266. FileCache* filecache = (FileCache*)hevent_userdata(timer);
  267. filecache->RemoveExpiredFileCache();
  268. }, filecache->expired_time * 1000);
  269. hevent_set_userdata(timer, filecache);
  270. }
  271. }
  272. privdata->loops.push_back(loop);
  273. privdata->mutex_.unlock();
  274. loop->run();
  275. }
  276. int http_server_run(http_server_t* server, int wait) {
  277. // http_port
  278. if (server->port > 0) {
  279. server->listenfd[0] = Listen(server->port, server->host);
  280. if (server->listenfd[0] < 0) return server->listenfd[0];
  281. hlogi("http server listening on %s:%d", server->host, server->port);
  282. }
  283. // https_port
  284. if (server->https_port > 0 && hssl_ctx_instance() != NULL) {
  285. server->listenfd[1] = Listen(server->https_port, server->host);
  286. if (server->listenfd[1] < 0) return server->listenfd[1];
  287. hlogi("https server listening on %s:%d", server->host, server->https_port);
  288. }
  289. HttpServerPrivdata* privdata = new HttpServerPrivdata;
  290. server->privdata = privdata;
  291. if (server->service == NULL) {
  292. privdata->service.reset(new HttpService);
  293. server->service = privdata->service.get();
  294. }
  295. if (server->worker_processes) {
  296. // multi-processes
  297. return master_workers_run(loop_thread, server, server->worker_processes, server->worker_threads, wait);
  298. }
  299. else {
  300. // multi-threads
  301. if (server->worker_threads == 0) server->worker_threads = 1;
  302. for (int i = wait ? 1 : 0; i < server->worker_threads; ++i) {
  303. hthread_t thrd = hthread_create((hthread_routine)loop_thread, server);
  304. privdata->threads.push_back(thrd);
  305. }
  306. if (wait) {
  307. loop_thread(server);
  308. }
  309. return 0;
  310. }
  311. }
  312. int http_server_stop(http_server_t* server) {
  313. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  314. if (privdata == NULL) return 0;
  315. #ifdef OS_UNIX
  316. if (server->worker_processes) {
  317. signal_handle("stop");
  318. return 0;
  319. }
  320. #endif
  321. // wait for all threads started and all loops running
  322. while (1) {
  323. hv_delay(1);
  324. std::lock_guard<std::mutex> locker(privdata->mutex_);
  325. // wait for all loops created
  326. if (privdata->loops.size() < server->worker_threads) {
  327. continue;
  328. }
  329. // wait for all loops running
  330. bool all_loops_running = true;
  331. for (auto& loop : privdata->loops) {
  332. if (loop->status() < hv::Status::kRunning) {
  333. all_loops_running = false;
  334. break;
  335. }
  336. }
  337. if (all_loops_running) break;
  338. }
  339. // stop all loops
  340. for (auto& loop : privdata->loops) {
  341. loop->stop();
  342. }
  343. // join all threads
  344. for (auto& thrd : privdata->threads) {
  345. hthread_join(thrd);
  346. }
  347. delete privdata;
  348. server->privdata = NULL;
  349. return 0;
  350. }