1
0

HttpServer.cpp 13 KB

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