HttpServer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. static HttpService* default_http_service() {
  17. static HttpService* s_default_service = new HttpService;
  18. return s_default_service;
  19. }
  20. static FileCache* default_filecache() {
  21. static FileCache s_filecache;
  22. return &s_filecache;
  23. }
  24. struct HttpServerPrivdata {
  25. std::vector<EventLoopPtr> loops;
  26. std::vector<hthread_t> threads;
  27. std::mutex mutex_;
  28. };
  29. static void on_recv(hio_t* io, void* _buf, int readbytes) {
  30. // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes);
  31. const char* buf = (const char*)_buf;
  32. HttpHandler* handler = (HttpHandler*)hevent_userdata(io);
  33. assert(handler != NULL);
  34. // HttpHandler::Init(http_version) -> upgrade ? SwitchHTTP2 / SwitchWebSocket
  35. // on_recv -> FeedRecvData -> HttpRequest
  36. // onComplete -> HandleRequest -> HttpResponse -> while (GetSendData) -> send
  37. HttpHandler::ProtocolType protocol = handler->protocol;
  38. if (protocol == HttpHandler::UNKNOWN) {
  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. int http_version = 1;
  53. if (strncmp((char*)buf, HTTP2_MAGIC, MIN(readbytes, HTTP2_MAGIC_LEN)) == 0) {
  54. http_version = 2;
  55. }
  56. if (!handler->Init(http_version, io)) {
  57. hloge("[%s:%d] unsupported HTTP%d", handler->ip, handler->port, http_version);
  58. hio_close(io);
  59. return;
  60. }
  61. }
  62. int nfeed = handler->FeedRecvData(buf, readbytes);
  63. if (nfeed != readbytes) {
  64. hio_close(io);
  65. return;
  66. }
  67. if (protocol == HttpHandler::WEBSOCKET) {
  68. return;
  69. }
  70. HttpParser* parser = handler->parser.get();
  71. if (parser->WantRecv()) {
  72. return;
  73. }
  74. HttpRequest* req = handler->req.get();
  75. HttpResponse* resp = handler->resp.get();
  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 = req->IsKeepAlive();
  84. if (keepalive) {
  85. resp->headers["Connection"] = "keep-alive";
  86. } else {
  87. resp->headers["Connection"] = "close";
  88. }
  89. // Upgrade:
  90. bool upgrade = false;
  91. auto iter_upgrade = req->headers.find("upgrade");
  92. if (iter_upgrade != req->headers.end()) {
  93. upgrade = true;
  94. const char* upgrade_proto = iter_upgrade->second.c_str();
  95. hlogi("[%s:%d] Upgrade: %s", handler->ip, handler->port, upgrade_proto);
  96. // websocket
  97. if (stricmp(upgrade_proto, "websocket") == 0) {
  98. if (!handler->SwitchWebSocket(io)) {
  99. hloge("[%s:%d] unsupported websocket", handler->ip, handler->port);
  100. hio_close(io);
  101. return;
  102. }
  103. /*
  104. HTTP/1.1 101 Switching Protocols
  105. Connection: Upgrade
  106. Upgrade: websocket
  107. Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
  108. */
  109. resp->status_code = HTTP_STATUS_SWITCHING_PROTOCOLS;
  110. resp->headers["Connection"] = "Upgrade";
  111. resp->headers["Upgrade"] = "websocket";
  112. auto iter_key = req->headers.find(SEC_WEBSOCKET_KEY);
  113. if (iter_key != req->headers.end()) {
  114. char ws_accept[32] = {0};
  115. ws_encode_key(iter_key->second.c_str(), ws_accept);
  116. resp->headers[SEC_WEBSOCKET_ACCEPT] = ws_accept;
  117. }
  118. // write upgrade resp
  119. std::string header = resp->Dump(true, false);
  120. hio_write(io, header.data(), header.length());
  121. }
  122. // h2/h2c
  123. else if (strnicmp(upgrade_proto, "h2", 2) == 0) {
  124. /*
  125. HTTP/1.1 101 Switching Protocols
  126. Connection: Upgrade
  127. Upgrade: h2c
  128. */
  129. hio_write(io, HTTP2_UPGRADE_RESPONSE, strlen(HTTP2_UPGRADE_RESPONSE));
  130. if (!handler->SwitchHTTP2()) {
  131. hloge("[%s:%d] unsupported HTTP2", handler->ip, handler->port);
  132. hio_close(io);
  133. return;
  134. }
  135. parser = handler->parser.get();
  136. }
  137. else {
  138. hio_close(io);
  139. return;
  140. }
  141. }
  142. int status_code = 200;
  143. if (parser->IsComplete() && !upgrade) {
  144. status_code = handler->HandleHttpRequest();
  145. }
  146. char* data = NULL;
  147. size_t len = 0;
  148. while (handler->GetSendData(&data, &len)) {
  149. // printf("%.*s\n", (int)len, data);
  150. if (data && len) {
  151. hio_write(io, data, len);
  152. }
  153. }
  154. // LOG
  155. hloop_t* loop = hevent_loop(io);
  156. hlogi("[%ld-%ld][%s:%d][%s %s]=>[%d %s]",
  157. hloop_pid(loop), hloop_tid(loop),
  158. handler->ip, handler->port,
  159. http_method_str(req->method), req->path.c_str(),
  160. resp->status_code, resp->status_message());
  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. handler->files = default_filecache();
  205. hevent_set_userdata(io, handler);
  206. }
  207. static void loop_thread(void* userdata) {
  208. http_server_t* server = (http_server_t*)userdata;
  209. EventLoopPtr loop(new EventLoop);
  210. hloop_t* hloop = loop->loop();
  211. // http
  212. if (server->listenfd[0] >= 0) {
  213. hio_t* listenio = haccept(hloop, server->listenfd[0], on_accept);
  214. hevent_set_userdata(listenio, server);
  215. }
  216. // https
  217. if (server->listenfd[1] >= 0) {
  218. hio_t* listenio = haccept(hloop, server->listenfd[1], on_accept);
  219. hevent_set_userdata(listenio, server);
  220. hio_enable_ssl(listenio);
  221. }
  222. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  223. privdata->mutex_.lock();
  224. if (privdata->loops.size() == 0) {
  225. // NOTE: fsync logfile when idle
  226. hlog_disable_fsync();
  227. hidle_add(hloop, [](hidle_t*) {
  228. hlog_fsync();
  229. }, INFINITE);
  230. // NOTE: add timer to remove expired file cache
  231. htimer_add(hloop, [](htimer_t*) {
  232. FileCache* filecache = default_filecache();
  233. filecache->RemoveExpiredFileCache();
  234. }, DEFAULT_FILE_EXPIRED_TIME * 1000);
  235. // NOTE: add timer to update s_date every 1s
  236. htimer_add(hloop, [](htimer_t* timer) {
  237. gmtime_fmt(hloop_now(hevent_loop(timer)), HttpMessage::s_date);
  238. }, 1000);
  239. }
  240. privdata->loops.push_back(loop);
  241. privdata->mutex_.unlock();
  242. loop->run();
  243. }
  244. int http_server_run(http_server_t* server, int wait) {
  245. // http_port
  246. if (server->port > 0) {
  247. server->listenfd[0] = Listen(server->port, server->host);
  248. if (server->listenfd[0] < 0) return server->listenfd[0];
  249. hlogi("http server listening on %s:%d", server->host, server->port);
  250. }
  251. // https_port
  252. if (server->https_port > 0 && hssl_ctx_instance() != NULL) {
  253. server->listenfd[1] = Listen(server->https_port, server->host);
  254. if (server->listenfd[1] < 0) return server->listenfd[1];
  255. hlogi("https server listening on %s:%d", server->host, server->https_port);
  256. }
  257. // service
  258. if (server->service == NULL) {
  259. server->service = default_http_service();
  260. }
  261. HttpServerPrivdata* privdata = new HttpServerPrivdata;
  262. server->privdata = privdata;
  263. if (server->worker_processes) {
  264. // multi-processes
  265. return master_workers_run(loop_thread, server, server->worker_processes, server->worker_threads, wait);
  266. }
  267. else {
  268. // multi-threads
  269. if (server->worker_threads == 0) server->worker_threads = 1;
  270. for (int i = wait ? 1 : 0; i < server->worker_threads; ++i) {
  271. hthread_t thrd = hthread_create((hthread_routine)loop_thread, server);
  272. privdata->threads.push_back(thrd);
  273. }
  274. if (wait) {
  275. loop_thread(server);
  276. }
  277. return 0;
  278. }
  279. }
  280. int http_server_stop(http_server_t* server) {
  281. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  282. if (privdata == NULL) return 0;
  283. #ifdef OS_UNIX
  284. if (server->worker_processes) {
  285. signal_handle("stop");
  286. return 0;
  287. }
  288. #endif
  289. // wait for all threads started and all loops running
  290. while (1) {
  291. hv_delay(1);
  292. std::lock_guard<std::mutex> locker(privdata->mutex_);
  293. // wait for all loops created
  294. if (privdata->loops.size() < server->worker_threads) {
  295. continue;
  296. }
  297. // wait for all loops running
  298. bool all_loops_running = true;
  299. for (auto& loop : privdata->loops) {
  300. if (loop->status() < hv::Status::kRunning) {
  301. all_loops_running = false;
  302. break;
  303. }
  304. }
  305. if (all_loops_running) break;
  306. }
  307. // stop all loops
  308. for (auto& loop : privdata->loops) {
  309. loop->stop();
  310. }
  311. // join all threads
  312. for (auto& thrd : privdata->threads) {
  313. hthread_join(thrd);
  314. }
  315. delete privdata;
  316. server->privdata = NULL;
  317. return 0;
  318. }