HttpServer.cpp 13 KB

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