HttpServer.cpp 13 KB

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