HttpServer.cpp 13 KB

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