1
0

HttpServer.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. } else {
  172. if (handler->writer && handler->writer->onclose) {
  173. handler->writer->onclose();
  174. }
  175. }
  176. hevent_set_userdata(io, NULL);
  177. delete handler;
  178. }
  179. }
  180. static void on_accept(hio_t* io) {
  181. http_server_t* server = (http_server_t*)hevent_userdata(io);
  182. HttpService* service = server->service;
  183. /*
  184. printf("on_accept connfd=%d\n", hio_fd(io));
  185. char localaddrstr[SOCKADDR_STRLEN] = {0};
  186. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  187. printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io),
  188. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  189. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  190. */
  191. hio_setcb_close(io, on_close);
  192. hio_setcb_read(io, on_recv);
  193. hio_read(io);
  194. hio_set_keepalive_timeout(io, service->keepalive_timeout);
  195. // new HttpHandler, delete on_close
  196. HttpHandler* handler = new HttpHandler;
  197. // ssl
  198. handler->ssl = hio_is_ssl(io);
  199. // ip:port
  200. sockaddr_u* peeraddr = (sockaddr_u*)hio_peeraddr(io);
  201. sockaddr_ip(peeraddr, handler->ip, sizeof(handler->ip));
  202. handler->port = sockaddr_port(peeraddr);
  203. // http service
  204. handler->service = service;
  205. // websocket service
  206. handler->ws_service = server->ws;
  207. // FileCache
  208. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  209. handler->files = &privdata->filecache;
  210. hevent_set_userdata(io, handler);
  211. }
  212. static void loop_thread(void* userdata) {
  213. http_server_t* server = (http_server_t*)userdata;
  214. HttpService* service = server->service;
  215. EventLoopPtr loop(new EventLoop);
  216. hloop_t* hloop = loop->loop();
  217. // http
  218. if (server->listenfd[0] >= 0) {
  219. hio_t* listenio = haccept(hloop, server->listenfd[0], on_accept);
  220. hevent_set_userdata(listenio, server);
  221. }
  222. // https
  223. if (server->listenfd[1] >= 0) {
  224. hio_t* listenio = haccept(hloop, server->listenfd[1], on_accept);
  225. hevent_set_userdata(listenio, server);
  226. hio_enable_ssl(listenio);
  227. }
  228. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  229. privdata->mutex_.lock();
  230. if (privdata->loops.size() == 0) {
  231. // NOTE: fsync logfile when idle
  232. hlog_disable_fsync();
  233. hidle_add(hloop, [](hidle_t*) {
  234. hlog_fsync();
  235. }, INFINITE);
  236. // NOTE: add timer to update s_date every 1s
  237. htimer_add(hloop, [](htimer_t* timer) {
  238. gmtime_fmt(hloop_now(hevent_loop(timer)), HttpMessage::s_date);
  239. }, 1000);
  240. // FileCache
  241. FileCache* filecache = &privdata->filecache;
  242. filecache->stat_interval = service->file_cache_stat_interval;
  243. filecache->expired_time = service->file_cache_expired_time;
  244. if (filecache->expired_time > 0) {
  245. // NOTE: add timer to remove expired file cache
  246. htimer_t* timer = htimer_add(hloop, [](htimer_t* timer) {
  247. FileCache* filecache = (FileCache*)hevent_userdata(timer);
  248. filecache->RemoveExpiredFileCache();
  249. }, filecache->expired_time * 1000);
  250. hevent_set_userdata(timer, filecache);
  251. }
  252. }
  253. privdata->loops.push_back(loop);
  254. privdata->mutex_.unlock();
  255. loop->run();
  256. }
  257. int http_server_run(http_server_t* server, int wait) {
  258. // http_port
  259. if (server->port > 0) {
  260. server->listenfd[0] = Listen(server->port, server->host);
  261. if (server->listenfd[0] < 0) return server->listenfd[0];
  262. hlogi("http server listening on %s:%d", server->host, server->port);
  263. }
  264. // https_port
  265. if (server->https_port > 0 && hssl_ctx_instance() != NULL) {
  266. server->listenfd[1] = Listen(server->https_port, server->host);
  267. if (server->listenfd[1] < 0) return server->listenfd[1];
  268. hlogi("https server listening on %s:%d", server->host, server->https_port);
  269. }
  270. HttpServerPrivdata* privdata = new HttpServerPrivdata;
  271. server->privdata = privdata;
  272. if (server->service == NULL) {
  273. privdata->service.reset(new HttpService);
  274. server->service = privdata->service.get();
  275. }
  276. if (server->worker_processes) {
  277. // multi-processes
  278. return master_workers_run(loop_thread, server, server->worker_processes, server->worker_threads, wait);
  279. }
  280. else {
  281. // multi-threads
  282. if (server->worker_threads == 0) server->worker_threads = 1;
  283. for (int i = wait ? 1 : 0; i < server->worker_threads; ++i) {
  284. hthread_t thrd = hthread_create((hthread_routine)loop_thread, server);
  285. privdata->threads.push_back(thrd);
  286. }
  287. if (wait) {
  288. loop_thread(server);
  289. }
  290. return 0;
  291. }
  292. }
  293. int http_server_stop(http_server_t* server) {
  294. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  295. if (privdata == NULL) return 0;
  296. #ifdef OS_UNIX
  297. if (server->worker_processes) {
  298. signal_handle("stop");
  299. return 0;
  300. }
  301. #endif
  302. // wait for all threads started and all loops running
  303. while (1) {
  304. hv_delay(1);
  305. std::lock_guard<std::mutex> locker(privdata->mutex_);
  306. // wait for all loops created
  307. if (privdata->loops.size() < server->worker_threads) {
  308. continue;
  309. }
  310. // wait for all loops running
  311. bool all_loops_running = true;
  312. for (auto& loop : privdata->loops) {
  313. if (loop->status() < hv::Status::kRunning) {
  314. all_loops_running = false;
  315. break;
  316. }
  317. }
  318. if (all_loops_running) break;
  319. }
  320. // stop all loops
  321. for (auto& loop : privdata->loops) {
  322. loop->stop();
  323. }
  324. // join all threads
  325. for (auto& thrd : privdata->threads) {
  326. hthread_join(thrd);
  327. }
  328. delete privdata;
  329. server->privdata = NULL;
  330. return 0;
  331. }