HttpServer.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. if (protocol == HttpHandler::WEBSOCKET) {
  62. return;
  63. }
  64. HttpParser* parser = handler->parser.get();
  65. if (parser->WantRecv()) {
  66. return;
  67. }
  68. HttpRequest* req = handler->req.get();
  69. HttpResponse* resp = handler->resp.get();
  70. // Server:
  71. static char s_Server[64] = {'\0'};
  72. if (s_Server[0] == '\0') {
  73. snprintf(s_Server, sizeof(s_Server), "httpd/%s", hv_compile_version());
  74. }
  75. resp->headers["Server"] = s_Server;
  76. // Connection:
  77. bool keepalive = req->IsKeepAlive();
  78. if (keepalive) {
  79. resp->headers["Connection"] = "keep-alive";
  80. } else {
  81. resp->headers["Connection"] = "close";
  82. }
  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. hloop_t* loop = hevent_loop(io);
  145. hlogi("[%ld-%ld][%s:%d][%s %s]=>[%d %s]",
  146. hloop_pid(loop), hloop_tid(loop),
  147. handler->ip, handler->port,
  148. http_method_str(req->method), req->path.c_str(),
  149. resp->status_code, resp->status_message());
  150. // switch protocol to websocket
  151. if (upgrade && upgrade_protocol == HttpHandler::WEBSOCKET) {
  152. if (!handler->SwitchWebSocket(io)) {
  153. hloge("[%s:%d] unsupported websocket", handler->ip, handler->port);
  154. hio_close(io);
  155. return;
  156. }
  157. // onopen
  158. handler->WebSocketOnOpen();
  159. return;
  160. }
  161. if (status_code && !keepalive) {
  162. hio_close(io);
  163. }
  164. }
  165. static void on_close(hio_t* io) {
  166. HttpHandler* handler = (HttpHandler*)hevent_userdata(io);
  167. if (handler) {
  168. if (handler->protocol == HttpHandler::WEBSOCKET) {
  169. // onclose
  170. handler->WebSocketOnClose();
  171. }
  172. hevent_set_userdata(io, NULL);
  173. delete handler;
  174. }
  175. }
  176. static void on_accept(hio_t* io) {
  177. http_server_t* server = (http_server_t*)hevent_userdata(io);
  178. HttpService* service = server->service;
  179. /*
  180. printf("on_accept connfd=%d\n", hio_fd(io));
  181. char localaddrstr[SOCKADDR_STRLEN] = {0};
  182. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  183. printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io),
  184. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  185. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  186. */
  187. hio_setcb_close(io, on_close);
  188. hio_setcb_read(io, on_recv);
  189. hio_read(io);
  190. hio_set_keepalive_timeout(io, service->keepalive_timeout);
  191. // new HttpHandler, delete on_close
  192. HttpHandler* handler = new HttpHandler;
  193. // ssl
  194. handler->ssl = hio_is_ssl(io);
  195. // ip:port
  196. sockaddr_u* peeraddr = (sockaddr_u*)hio_peeraddr(io);
  197. sockaddr_ip(peeraddr, handler->ip, sizeof(handler->ip));
  198. handler->port = sockaddr_port(peeraddr);
  199. // http service
  200. handler->service = service;
  201. // websocket service
  202. handler->ws_service = server->ws;
  203. // FileCache
  204. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  205. handler->files = &privdata->filecache;
  206. hevent_set_userdata(io, handler);
  207. }
  208. static void loop_thread(void* userdata) {
  209. http_server_t* server = (http_server_t*)userdata;
  210. HttpService* service = server->service;
  211. EventLoopPtr loop(new EventLoop);
  212. hloop_t* hloop = loop->loop();
  213. // http
  214. if (server->listenfd[0] >= 0) {
  215. hio_t* listenio = haccept(hloop, server->listenfd[0], on_accept);
  216. hevent_set_userdata(listenio, server);
  217. }
  218. // https
  219. if (server->listenfd[1] >= 0) {
  220. hio_t* listenio = haccept(hloop, server->listenfd[1], on_accept);
  221. hevent_set_userdata(listenio, server);
  222. hio_enable_ssl(listenio);
  223. }
  224. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  225. privdata->mutex_.lock();
  226. if (privdata->loops.size() == 0) {
  227. // NOTE: fsync logfile when idle
  228. hlog_disable_fsync();
  229. hidle_add(hloop, [](hidle_t*) {
  230. hlog_fsync();
  231. }, INFINITE);
  232. // NOTE: add timer to update s_date every 1s
  233. htimer_add(hloop, [](htimer_t* timer) {
  234. gmtime_fmt(hloop_now(hevent_loop(timer)), HttpMessage::s_date);
  235. }, 1000);
  236. // FileCache
  237. FileCache* filecache = &privdata->filecache;
  238. filecache->stat_interval = service->file_cache_stat_interval;
  239. filecache->expired_time = service->file_cache_expired_time;
  240. if (filecache->expired_time > 0) {
  241. // NOTE: add timer to remove expired file cache
  242. htimer_t* timer = htimer_add(hloop, [](htimer_t* timer) {
  243. FileCache* filecache = (FileCache*)hevent_userdata(timer);
  244. filecache->RemoveExpiredFileCache();
  245. }, filecache->expired_time * 1000);
  246. hevent_set_userdata(timer, filecache);
  247. }
  248. }
  249. privdata->loops.push_back(loop);
  250. privdata->mutex_.unlock();
  251. loop->run();
  252. }
  253. int http_server_run(http_server_t* server, int wait) {
  254. // http_port
  255. if (server->port > 0) {
  256. server->listenfd[0] = Listen(server->port, server->host);
  257. if (server->listenfd[0] < 0) return server->listenfd[0];
  258. hlogi("http server listening on %s:%d", server->host, server->port);
  259. }
  260. // https_port
  261. if (server->https_port > 0 && hssl_ctx_instance() != NULL) {
  262. server->listenfd[1] = Listen(server->https_port, server->host);
  263. if (server->listenfd[1] < 0) return server->listenfd[1];
  264. hlogi("https server listening on %s:%d", server->host, server->https_port);
  265. }
  266. HttpServerPrivdata* privdata = new HttpServerPrivdata;
  267. server->privdata = privdata;
  268. if (server->service == NULL) {
  269. privdata->service.reset(new HttpService);
  270. server->service = privdata->service.get();
  271. }
  272. if (server->worker_processes) {
  273. // multi-processes
  274. return master_workers_run(loop_thread, server, server->worker_processes, server->worker_threads, wait);
  275. }
  276. else {
  277. // multi-threads
  278. if (server->worker_threads == 0) server->worker_threads = 1;
  279. for (int i = wait ? 1 : 0; i < server->worker_threads; ++i) {
  280. hthread_t thrd = hthread_create((hthread_routine)loop_thread, server);
  281. privdata->threads.push_back(thrd);
  282. }
  283. if (wait) {
  284. loop_thread(server);
  285. }
  286. return 0;
  287. }
  288. }
  289. int http_server_stop(http_server_t* server) {
  290. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  291. if (privdata == NULL) return 0;
  292. #ifdef OS_UNIX
  293. if (server->worker_processes) {
  294. signal_handle("stop");
  295. return 0;
  296. }
  297. #endif
  298. // wait for all threads started and all loops running
  299. while (1) {
  300. hv_delay(1);
  301. std::lock_guard<std::mutex> locker(privdata->mutex_);
  302. // wait for all loops created
  303. if (privdata->loops.size() < server->worker_threads) {
  304. continue;
  305. }
  306. // wait for all loops running
  307. bool all_loops_running = true;
  308. for (auto& loop : privdata->loops) {
  309. if (loop->status() < hv::Status::kRunning) {
  310. all_loops_running = false;
  311. break;
  312. }
  313. }
  314. if (all_loops_running) break;
  315. }
  316. // stop all loops
  317. for (auto& loop : privdata->loops) {
  318. loop->stop();
  319. }
  320. // join all threads
  321. for (auto& thrd : privdata->threads) {
  322. hthread_join(thrd);
  323. }
  324. delete privdata;
  325. server->privdata = NULL;
  326. return 0;
  327. }