1
0

HttpServer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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(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. if (handler->protocol == HttpHandler::WEBSOCKET) {
  70. WebSocketParser* parser = handler->ws->parser.get();
  71. int nfeed = parser->FeedRecvData(buf, readbytes);
  72. if (nfeed != readbytes) {
  73. hloge("[%s:%d] websocket parse error!", handler->ip, handler->port);
  74. hio_close(io);
  75. }
  76. return;
  77. }
  78. // HTTP1 / HTTP2 -> HttpParser -> InitRequest
  79. // recv -> FeedRecvData -> !WantRecv -> HttpRequest ->
  80. // HandleRequest -> HttpResponse -> SubmitResponse -> while (GetSendData) -> send
  81. if (handler->parser == NULL) {
  82. // check request-line
  83. if (readbytes < MIN_HTTP_REQUEST_LEN) {
  84. hloge("[%s:%d] http request-line too small", handler->ip, handler->port);
  85. hio_close(io);
  86. return;
  87. }
  88. for (int i = 0; i < MIN_HTTP_REQUEST_LEN; ++i) {
  89. if (!IS_GRAPH(buf[i])) {
  90. hloge("[%s:%d] http request-line not plain", handler->ip, handler->port);
  91. hio_close(io);
  92. return;
  93. }
  94. }
  95. http_version version = HTTP_V1;
  96. handler->protocol = HttpHandler::HTTP_V1;
  97. if (strncmp((char*)buf, HTTP2_MAGIC, MIN(readbytes, HTTP2_MAGIC_LEN)) == 0) {
  98. version = HTTP_V2;
  99. handler->protocol = HttpHandler::HTTP_V2;
  100. handler->req.http_major = 2;
  101. handler->req.http_minor = 0;
  102. }
  103. handler->parser = HttpParserPtr(HttpParser::New(HTTP_SERVER, version));
  104. if (handler->parser == NULL) {
  105. hloge("[%s:%d] unsupported HTTP%d", handler->ip, handler->port, (int)version);
  106. hio_close(io);
  107. return;
  108. }
  109. handler->parser->InitRequest(&handler->req);
  110. }
  111. HttpParser* parser = handler->parser.get();
  112. HttpRequest* req = &handler->req;
  113. HttpResponse* res = &handler->res;
  114. int nfeed = parser->FeedRecvData(buf, readbytes);
  115. if (nfeed != readbytes) {
  116. hloge("[%s:%d] http parse error: %s", handler->ip, handler->port, parser->StrError(parser->GetError()));
  117. hio_close(io);
  118. return;
  119. }
  120. if (parser->WantRecv()) {
  121. return;
  122. }
  123. // Server:
  124. static char s_Server[64] = {'\0'};
  125. if (s_Server[0] == '\0') {
  126. snprintf(s_Server, sizeof(s_Server), "httpd/%s", hv_compile_version());
  127. }
  128. res->headers["Server"] = s_Server;
  129. // Connection:
  130. bool keepalive = true;
  131. auto iter_keepalive = req->headers.find("connection");
  132. if (iter_keepalive != req->headers.end()) {
  133. const char* keepalive_value = iter_keepalive->second.c_str();
  134. if (stricmp(keepalive_value, "keep-alive") == 0) {
  135. keepalive = true;
  136. }
  137. else if (stricmp(keepalive_value, "close") == 0) {
  138. keepalive = false;
  139. }
  140. else if (stricmp(keepalive_value, "upgrade") == 0) {
  141. keepalive = true;
  142. }
  143. }
  144. else if (req->http_major == 1 && req->http_minor == 0) {
  145. keepalive = false;
  146. }
  147. if (keepalive) {
  148. res->headers["Connection"] = "keep-alive";
  149. } else {
  150. res->headers["Connection"] = "close";
  151. }
  152. // Upgrade:
  153. bool upgrade = false;
  154. auto iter_upgrade = req->headers.find("upgrade");
  155. if (iter_upgrade != req->headers.end()) {
  156. upgrade = true;
  157. const char* upgrade_proto = iter_upgrade->second.c_str();
  158. hlogi("[%s:%d] Upgrade: %s", handler->ip, handler->port, upgrade_proto);
  159. // websocket
  160. if (stricmp(upgrade_proto, "websocket") == 0) {
  161. /*
  162. HTTP/1.1 101 Switching Protocols
  163. Connection: Upgrade
  164. Upgrade: websocket
  165. Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
  166. */
  167. res->status_code = HTTP_STATUS_SWITCHING_PROTOCOLS;
  168. res->headers["Connection"] = "Upgrade";
  169. res->headers["Upgrade"] = "websocket";
  170. auto iter_key = req->headers.find(SEC_WEBSOCKET_KEY);
  171. if (iter_key != req->headers.end()) {
  172. char ws_accept[32] = {0};
  173. ws_encode_key(iter_key->second.c_str(), ws_accept);
  174. res->headers[SEC_WEBSOCKET_ACCEPT] = ws_accept;
  175. }
  176. handler->protocol = HttpHandler::WEBSOCKET;
  177. }
  178. // h2/h2c
  179. else if (strnicmp(upgrade_proto, "h2", 2) == 0) {
  180. /*
  181. HTTP/1.1 101 Switching Protocols
  182. Connection: Upgrade
  183. Upgrade: h2c
  184. */
  185. hio_write(io, HTTP2_UPGRADE_RESPONSE, strlen(HTTP2_UPGRADE_RESPONSE));
  186. parser = HttpParser::New(HTTP_SERVER, HTTP_V2);
  187. if (parser == NULL) {
  188. hloge("[%s:%d] unsupported HTTP2", handler->ip, handler->port);
  189. hio_close(io);
  190. return;
  191. }
  192. handler->parser.reset(parser);
  193. parser->InitRequest(req);
  194. }
  195. else {
  196. hio_close(io);
  197. return;
  198. }
  199. }
  200. if (parser->IsComplete() && !upgrade) {
  201. handler->HandleHttpRequest();
  202. parser->SubmitResponse(res);
  203. }
  204. if (req->http_major == 1) {
  205. std::string header = res->Dump(true, false);
  206. hbuf_t sendbuf;
  207. bool send_in_one_packet = true;
  208. int content_length = res->ContentLength();
  209. if (handler->fc) {
  210. // no copy filebuf, more efficient
  211. handler->fc->prepend_header(header.c_str(), header.size());
  212. sendbuf = handler->fc->httpbuf;
  213. }
  214. else {
  215. if (content_length > (1 << 20)) {
  216. send_in_one_packet = false;
  217. }
  218. else if (content_length != 0) {
  219. header.insert(header.size(), (const char*)res->Content(), content_length);
  220. }
  221. sendbuf.base = (char*)header.c_str();
  222. sendbuf.len = header.size();
  223. }
  224. // send header/body
  225. hio_write(io, sendbuf.base, sendbuf.len);
  226. if (send_in_one_packet == false) {
  227. // send body
  228. hio_write(io, res->Content(), content_length);
  229. }
  230. }
  231. else if (req->http_major == 2) {
  232. char* data = NULL;
  233. size_t len = 0;
  234. while (parser->GetSendData(&data, &len)) {
  235. hio_write(io, data, len);
  236. }
  237. }
  238. hloop_t* loop = hevent_loop(io);
  239. hlogi("[%ld-%ld][%s:%d][%s %s]=>[%d %s]",
  240. hloop_pid(loop), hloop_tid(loop),
  241. handler->ip, handler->port,
  242. http_method_str(req->method), req->path.c_str(),
  243. res->status_code, res->status_message());
  244. // switch protocol to websocket
  245. if (upgrade && handler->protocol == HttpHandler::WEBSOCKET) {
  246. WebSocketHandler* ws = handler->SwitchWebSocket();
  247. ws->channel.reset(new WebSocketChannel(io, WS_SERVER));
  248. ws->parser->onMessage = std::bind(websocket_onmessage, std::placeholders::_1, std::placeholders::_2, io);
  249. // NOTE: need to reset callbacks
  250. hio_setcb_read(io, on_recv);
  251. hio_setcb_close(io, on_close);
  252. // NOTE: cancel keepalive timer, judge alive by heartbeat.
  253. hio_set_keepalive_timeout(io, 0);
  254. hio_set_heartbeat(io, HIO_DEFAULT_HEARTBEAT_INTERVAL, websocket_heartbeat);
  255. // onopen
  256. handler->WebSocketOnOpen();
  257. return;
  258. }
  259. if (keepalive) {
  260. handler->Reset();
  261. parser->InitRequest(req);
  262. } else {
  263. hio_close(io);
  264. }
  265. }
  266. static void on_close(hio_t* io) {
  267. HttpHandler* handler = (HttpHandler*)hevent_userdata(io);
  268. if (handler) {
  269. if (handler->protocol == HttpHandler::WEBSOCKET) {
  270. // onclose
  271. handler->WebSocketOnClose();
  272. }
  273. hevent_set_userdata(io, NULL);
  274. delete handler;
  275. }
  276. }
  277. static void on_accept(hio_t* io) {
  278. /*
  279. printf("on_accept connfd=%d\n", hio_fd(io));
  280. char localaddrstr[SOCKADDR_STRLEN] = {0};
  281. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  282. printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io),
  283. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  284. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  285. */
  286. hio_setcb_close(io, on_close);
  287. hio_setcb_read(io, on_recv);
  288. hio_read(io);
  289. hio_set_keepalive_timeout(io, HIO_DEFAULT_KEEPALIVE_TIMEOUT);
  290. // new HttpHandler, delete on_close
  291. HttpHandler* handler = new HttpHandler;
  292. // ip
  293. sockaddr_ip((sockaddr_u*)hio_peeraddr(io), handler->ip, sizeof(handler->ip));
  294. // port
  295. handler->port = sockaddr_port((sockaddr_u*)hio_peeraddr(io));
  296. // service
  297. http_server_t* server = (http_server_t*)hevent_userdata(io);
  298. handler->service = server->service;
  299. // ws
  300. handler->ws_cbs = server->ws;
  301. // FileCache
  302. handler->files = default_filecache();
  303. hevent_set_userdata(io, handler);
  304. }
  305. static void handle_cached_files(htimer_t* timer) {
  306. FileCache* pfc = (FileCache*)hevent_userdata(timer);
  307. file_cache_t* fc = NULL;
  308. time_t tt = time(NULL);
  309. std::lock_guard<std::mutex> locker(pfc->mutex_);
  310. auto iter = pfc->cached_files.begin();
  311. while (iter != pfc->cached_files.end()) {
  312. fc = iter->second;
  313. if (tt - fc->stat_time > pfc->file_cached_time) {
  314. delete fc;
  315. iter = pfc->cached_files.erase(iter);
  316. continue;
  317. }
  318. ++iter;
  319. }
  320. }
  321. static void loop_thread(void* userdata) {
  322. http_server_t* server = (http_server_t*)userdata;
  323. int listenfd = server->listenfd;
  324. EventLoopPtr loop(new EventLoop);
  325. hloop_t* hloop = loop->loop();
  326. hio_t* listenio = haccept(hloop, listenfd, on_accept);
  327. hevent_set_userdata(listenio, server);
  328. if (server->ssl) {
  329. hio_enable_ssl(listenio);
  330. }
  331. // fsync logfile when idle
  332. hlog_disable_fsync();
  333. hidle_add(hloop, [](hidle_t*) {
  334. hlog_fsync();
  335. }, INFINITE);
  336. // timer handle_cached_files
  337. FileCache* filecache = default_filecache();
  338. htimer_t* timer = htimer_add(hloop, handle_cached_files, filecache->file_cached_time * 1000);
  339. hevent_set_userdata(timer, filecache);
  340. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  341. if (privdata) {
  342. privdata->mutex_.lock();
  343. privdata->loops.push_back(loop);
  344. privdata->mutex_.unlock();
  345. }
  346. loop->run();
  347. }
  348. int http_server_run(http_server_t* server, int wait) {
  349. // port
  350. server->listenfd = Listen(server->port, server->host);
  351. if (server->listenfd < 0) return server->listenfd;
  352. // service
  353. if (server->service == NULL) {
  354. server->service = default_http_service();
  355. }
  356. if (server->worker_processes) {
  357. // multi-processes
  358. return master_workers_run(loop_thread, server, server->worker_processes, server->worker_threads, wait);
  359. }
  360. else {
  361. // multi-threads
  362. if (server->worker_threads == 0) server->worker_threads = 1;
  363. // for SDK implement http_server_stop
  364. HttpServerPrivdata* privdata = new HttpServerPrivdata;
  365. server->privdata = privdata;
  366. int i = wait ? 1 : 0;
  367. for (; i < server->worker_threads; ++i) {
  368. hthread_t thrd = hthread_create((hthread_routine)loop_thread, server);
  369. privdata->threads.push_back(thrd);
  370. }
  371. if (wait) {
  372. loop_thread(server);
  373. }
  374. return 0;
  375. }
  376. }
  377. int http_server_stop(http_server_t* server) {
  378. #ifdef OS_UNIX
  379. if (server->worker_processes) {
  380. signal_handle("stop");
  381. return 0;
  382. }
  383. #endif
  384. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  385. if (privdata == NULL) return 0;
  386. // wait for all threads started and all loops running
  387. while (1) {
  388. hv_delay(1);
  389. std::lock_guard<std::mutex> locker(privdata->mutex_);
  390. // wait for all loops created
  391. if (privdata->loops.size() < server->worker_threads) {
  392. continue;
  393. }
  394. // wait for all loops running
  395. for (auto& loop : privdata->loops) {
  396. if (loop->status() < hv::Status::kRunning) {
  397. continue;
  398. }
  399. }
  400. break;
  401. }
  402. // stop all loops
  403. for (auto& loop : privdata->loops) {
  404. loop->stop();
  405. }
  406. // join all threads
  407. for (auto& thrd : privdata->threads) {
  408. hthread_join(thrd);
  409. }
  410. delete privdata;
  411. server->privdata = NULL;
  412. return 0;
  413. }