HttpServer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. #include "HttpServer.h"
  2. #include "hv.h"
  3. #include "hmain.h"
  4. #include "hloop.h"
  5. #include "httpdef.h"
  6. #include "http2def.h"
  7. #include "wsdef.h"
  8. #include "HttpHandler.h"
  9. #define MIN_HTTP_REQUEST "GET / HTTP/1.1\r\n\r\n"
  10. #define MIN_HTTP_REQUEST_LEN 14 // exclude CRLF
  11. static HttpService s_default_service;
  12. static FileCache s_filecache;
  13. struct HttpServerPrivdata {
  14. int quit;
  15. std::vector<hloop_t*> loops;
  16. std::vector<hthread_t> threads;
  17. std::mutex mutex_;
  18. };
  19. static void on_recv(hio_t* io, void* _buf, int readbytes) {
  20. // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes);
  21. const char* buf = (const char*)_buf;
  22. HttpHandler* handler = (HttpHandler*)hevent_userdata(io);
  23. if (handler->proto == HttpHandler::WEBSOCKET) {
  24. // TODO: HandleWebsocketMessage
  25. return;
  26. }
  27. // HTTP1 / HTTP2 -> HttpParser -> InitRequest
  28. // recv -> FeedRecvData -> !WantRecv -> HttpRequest ->
  29. // HandleRequest -> HttpResponse -> SubmitResponse -> while (GetSendData) -> send
  30. if (handler->parser == NULL) {
  31. // check request-line
  32. if (readbytes < MIN_HTTP_REQUEST_LEN) {
  33. hloge("[%s:%d] http request-line too small", handler->ip, handler->port);
  34. hio_close(io);
  35. return;
  36. }
  37. for (int i = 0; i < MIN_HTTP_REQUEST_LEN; ++i) {
  38. if (!IS_GRAPH(buf[i])) {
  39. hloge("[%s:%d] http request-line not plain", handler->ip, handler->port);
  40. hio_close(io);
  41. return;
  42. }
  43. }
  44. http_version version = HTTP_V1;
  45. handler->proto = HttpHandler::HTTP_V1;
  46. if (strncmp((char*)buf, HTTP2_MAGIC, MIN(readbytes, HTTP2_MAGIC_LEN)) == 0) {
  47. version = HTTP_V2;
  48. handler->proto = HttpHandler::HTTP_V2;
  49. handler->req.http_major = 2;
  50. handler->req.http_minor = 0;
  51. }
  52. handler->parser = HttpParserPtr(HttpParser::New(HTTP_SERVER, version));
  53. if (handler->parser == NULL) {
  54. hloge("[%s:%d] unsupported HTTP%d", handler->ip, handler->port, (int)version);
  55. hio_close(io);
  56. return;
  57. }
  58. handler->parser->InitRequest(&handler->req);
  59. }
  60. HttpParser* parser = handler->parser.get();
  61. HttpRequest* req = &handler->req;
  62. HttpResponse* res = &handler->res;
  63. int nfeed = parser->FeedRecvData(buf, readbytes);
  64. if (nfeed != readbytes) {
  65. hloge("[%s:%d] http parse error: %s", handler->ip, handler->port, parser->StrError(parser->GetError()));
  66. hio_close(io);
  67. return;
  68. }
  69. if (parser->WantRecv()) {
  70. return;
  71. }
  72. // Server:
  73. static char s_Server[64] = {'\0'};
  74. if (s_Server[0] == '\0') {
  75. snprintf(s_Server, sizeof(s_Server), "httpd/%s", hv_compile_version());
  76. }
  77. res->headers["Server"] = s_Server;
  78. // Connection:
  79. bool keepalive = true;
  80. auto iter_keepalive = req->headers.find("connection");
  81. if (iter_keepalive != req->headers.end()) {
  82. const char* keepalive_value = iter_keepalive->second.c_str();
  83. if (stricmp(keepalive_value, "keep-alive") == 0) {
  84. keepalive = true;
  85. }
  86. else if (stricmp(keepalive_value, "close") == 0) {
  87. keepalive = false;
  88. }
  89. else if (stricmp(keepalive_value, "upgrade") == 0) {
  90. keepalive = true;
  91. }
  92. }
  93. else if (req->http_major == 1 && req->http_minor == 0) {
  94. keepalive = false;
  95. }
  96. if (keepalive) {
  97. res->headers["Connection"] = "keep-alive";
  98. } else {
  99. res->headers["Connection"] = "close";
  100. }
  101. // Upgrade:
  102. bool upgrade = false;
  103. auto iter_upgrade = req->headers.find("upgrade");
  104. if (iter_upgrade != req->headers.end()) {
  105. upgrade = true;
  106. const char* upgrade_proto = iter_upgrade->second.c_str();
  107. hlogi("[%s:%d] Upgrade: %s", handler->ip, handler->port, upgrade_proto);
  108. // websocket
  109. if (stricmp(upgrade_proto, "websocket") == 0) {
  110. /*
  111. HTTP/1.1 101 Switching Protocols
  112. Connection: Upgrade
  113. Upgrade: websocket
  114. Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
  115. */
  116. res->status_code = HTTP_STATUS_SWITCHING_PROTOCOLS;
  117. res->headers["Connection"] = "Upgrade";
  118. res->headers["Upgrade"] = "websocket";
  119. auto iter_key = req->headers.find(SEC_WEBSOCKET_KEY);
  120. if (iter_key != req->headers.end()) {
  121. char ws_accept[32] = {0};
  122. ws_encode_key(iter_key->second.c_str(), ws_accept);
  123. res->headers[SEC_WEBSOCKET_ACCEPT] = ws_accept;
  124. }
  125. handler->proto = HttpHandler::WEBSOCKET;
  126. }
  127. // h2/h2c
  128. else if (strnicmp(upgrade_proto, "h2", 2) == 0) {
  129. /*
  130. HTTP/1.1 101 Switching Protocols
  131. Connection: Upgrade
  132. Upgrade: h2c
  133. */
  134. hio_write(io, HTTP2_UPGRADE_RESPONSE, strlen(HTTP2_UPGRADE_RESPONSE));
  135. parser = HttpParser::New(HTTP_SERVER, HTTP_V2);
  136. if (parser == NULL) {
  137. hloge("[%s:%d] unsupported HTTP2", handler->ip, handler->port);
  138. hio_close(io);
  139. return;
  140. }
  141. handler->parser.reset(parser);
  142. parser->InitRequest(req);
  143. }
  144. else {
  145. hio_close(io);
  146. return;
  147. }
  148. }
  149. if (parser->IsComplete() && !upgrade) {
  150. handler->HandleHttpRequest();
  151. parser->SubmitResponse(res);
  152. }
  153. if (req->http_major == 1) {
  154. std::string header = res->Dump(true, false);
  155. hbuf_t sendbuf;
  156. bool send_in_one_packet = true;
  157. int content_length = res->ContentLength();
  158. if (handler->fc) {
  159. // no copy filebuf, more efficient
  160. handler->fc->prepend_header(header.c_str(), header.size());
  161. sendbuf = handler->fc->httpbuf;
  162. }
  163. else {
  164. if (content_length > (1 << 20)) {
  165. send_in_one_packet = false;
  166. }
  167. else if (content_length != 0) {
  168. header.insert(header.size(), (const char*)res->Content(), content_length);
  169. }
  170. sendbuf.base = (char*)header.c_str();
  171. sendbuf.len = header.size();
  172. }
  173. // send header/body
  174. hio_write(io, sendbuf.base, sendbuf.len);
  175. if (send_in_one_packet == false) {
  176. // send body
  177. hio_write(io, res->Content(), content_length);
  178. }
  179. }
  180. else if (req->http_major == 2) {
  181. char* data = NULL;
  182. size_t len = 0;
  183. while (parser->GetSendData(&data, &len)) {
  184. hio_write(io, data, len);
  185. }
  186. }
  187. hloop_t* loop = hevent_loop(io);
  188. hlogi("[%ld-%ld][%s:%d][%s %s]=>[%d %s]",
  189. hloop_pid(loop), hloop_tid(loop),
  190. handler->ip, handler->port,
  191. http_method_str(req->method), req->path.c_str(),
  192. res->status_code, res->status_message());
  193. if (keepalive) {
  194. handler->Reset();
  195. parser->InitRequest(req);
  196. } else {
  197. hio_close(io);
  198. }
  199. }
  200. static void on_close(hio_t* io) {
  201. HttpHandler* handler = (HttpHandler*)hevent_userdata(io);
  202. if (handler) {
  203. hevent_set_userdata(io, NULL);
  204. delete handler;
  205. }
  206. }
  207. static void on_accept(hio_t* io) {
  208. printd("on_accept connfd=%d\n", hio_fd(io));
  209. /*
  210. char localaddrstr[SOCKADDR_STRLEN] = {0};
  211. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  212. printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io),
  213. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  214. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  215. */
  216. hio_setcb_close(io, on_close);
  217. hio_setcb_read(io, on_recv);
  218. hio_read(io);
  219. hio_set_keepalive_timeout(io, HIO_DEFAULT_KEEPALIVE_TIMEOUT);
  220. // new HttpHandler
  221. // delete on_close
  222. HttpHandler* handler = new HttpHandler;
  223. handler->service = (HttpService*)hevent_userdata(io);
  224. handler->files = &s_filecache;
  225. sockaddr_ip((sockaddr_u*)hio_peeraddr(io), handler->ip, sizeof(handler->ip));
  226. handler->port = sockaddr_port((sockaddr_u*)hio_peeraddr(io));
  227. hevent_set_userdata(io, handler);
  228. }
  229. static void handle_cached_files(htimer_t* timer) {
  230. FileCache* pfc = (FileCache*)hevent_userdata(timer);
  231. if (pfc == NULL) {
  232. htimer_del(timer);
  233. return;
  234. }
  235. file_cache_t* fc = NULL;
  236. time_t tt;
  237. time(&tt);
  238. std::lock_guard<std::mutex> locker(pfc->mutex_);
  239. auto iter = pfc->cached_files.begin();
  240. while (iter != pfc->cached_files.end()) {
  241. fc = iter->second;
  242. if (tt - fc->stat_time > pfc->file_cached_time) {
  243. delete fc;
  244. iter = pfc->cached_files.erase(iter);
  245. continue;
  246. }
  247. ++iter;
  248. }
  249. }
  250. static void fsync_logfile(hidle_t* idle) {
  251. hlog_fsync();
  252. }
  253. static void worker_fn(void* userdata) {
  254. http_server_t* server = (http_server_t*)userdata;
  255. int listenfd = server->listenfd;
  256. hloop_t* loop = hloop_new(0);
  257. hio_t* listenio = haccept(loop, listenfd, on_accept);
  258. hevent_set_userdata(listenio, server->service);
  259. if (server->ssl) {
  260. hio_enable_ssl(listenio);
  261. }
  262. // fsync logfile when idle
  263. hlog_disable_fsync();
  264. hidle_add(loop, fsync_logfile, INFINITE);
  265. // timer handle_cached_files
  266. htimer_t* timer = htimer_add(loop, handle_cached_files, s_filecache.file_cached_time * 1000);
  267. hevent_set_userdata(timer, &s_filecache);
  268. // for SDK implement http_server_stop
  269. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  270. if (privdata) {
  271. std::lock_guard<std::mutex> locker(privdata->mutex_);
  272. if (privdata->quit) {
  273. hloop_free(&loop);
  274. return;
  275. }
  276. privdata->loops.push_back(loop);
  277. }
  278. hloop_run(loop);
  279. hloop_free(&loop);
  280. }
  281. int http_server_run(http_server_t* server, int wait) {
  282. // service
  283. if (server->service == NULL) {
  284. server->service = &s_default_service;
  285. }
  286. // port
  287. server->listenfd = Listen(server->port, server->host);
  288. if (server->listenfd < 0) return server->listenfd;
  289. if (server->worker_processes) {
  290. // multi-processes
  291. return master_workers_run(worker_fn, server, server->worker_processes, server->worker_threads, wait);
  292. }
  293. else {
  294. // multi-threads
  295. int worker_threads = server->worker_threads;
  296. if (worker_threads == 0) worker_threads = 1;
  297. // for SDK implement http_server_stop
  298. HttpServerPrivdata* privdata = new HttpServerPrivdata;
  299. privdata->quit = 0;
  300. server->privdata = privdata;
  301. int i = wait ? 1 : 0;
  302. for (; i < worker_threads; ++i) {
  303. hthread_t thrd = hthread_create((hthread_routine)worker_fn, server);
  304. privdata->threads.push_back(thrd);
  305. }
  306. if (wait) {
  307. worker_fn(server);
  308. }
  309. return 0;
  310. }
  311. }
  312. int http_server_stop(http_server_t* server) {
  313. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  314. if (privdata == NULL) return 0;
  315. privdata->mutex_.lock();
  316. privdata->quit = 1;
  317. for (auto loop : privdata->loops) {
  318. hloop_stop(loop);
  319. }
  320. privdata->mutex_.unlock();
  321. for (auto thrd : privdata->threads) {
  322. hthread_join(thrd);
  323. }
  324. delete privdata;
  325. server->privdata = NULL;
  326. return 0;
  327. }