HttpHandler.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. #include "HttpHandler.h"
  2. #include "hversion.h"
  3. #include "herr.h"
  4. #include "hlog.h"
  5. #include "htime.h"
  6. #include "hurl.h"
  7. #include "hasync.h" // import hv::async for http_async_handler
  8. #include "httpdef.h"
  9. #include "http2def.h"
  10. #include "wsdef.h"
  11. #include "http_page.h"
  12. #include "EventLoop.h" // import hv::setInterval
  13. using namespace hv;
  14. #define MIN_HTTP_REQUEST "GET / HTTP/1.1\r\n\r\n"
  15. #define MIN_HTTP_REQUEST_LEN 14 // exclude CRLF
  16. HttpHandler::HttpHandler(hio_t* io) :
  17. protocol(HttpHandler::UNKNOWN),
  18. state(WANT_RECV),
  19. error(0),
  20. // flags
  21. ssl(false),
  22. keepalive(true),
  23. proxy(false),
  24. upgrade(false),
  25. port(0),
  26. pid(0),
  27. tid(0),
  28. // for http
  29. io(io),
  30. service(NULL),
  31. ws_service(NULL),
  32. api_handler(NULL),
  33. // for sendfile
  34. files(NULL),
  35. file(NULL),
  36. // for websocket
  37. last_send_ping_time(0),
  38. last_recv_pong_time(0)
  39. {
  40. // Init();
  41. }
  42. HttpHandler::~HttpHandler() {
  43. Close();
  44. }
  45. bool HttpHandler::Init(int http_version) {
  46. parser.reset(HttpParser::New(HTTP_SERVER, (enum http_version)http_version));
  47. if (parser == NULL) {
  48. return false;
  49. }
  50. req = std::make_shared<HttpRequest>();
  51. resp = std::make_shared<HttpResponse>();
  52. if(http_version == 1) {
  53. protocol = HTTP_V1;
  54. } else if (http_version == 2) {
  55. protocol = HTTP_V2;
  56. resp->http_major = req->http_major = 2;
  57. resp->http_minor = req->http_minor = 0;
  58. }
  59. if (io) {
  60. hloop_t* loop = hevent_loop(io);
  61. pid = hloop_pid(loop);
  62. tid = hloop_tid(loop);
  63. writer = std::make_shared<HttpResponseWriter>(io, resp);
  64. writer->status = hv::SocketChannel::CONNECTED;
  65. } else {
  66. pid = hv_getpid();
  67. tid = hv_gettid();
  68. }
  69. parser->InitRequest(req.get());
  70. // NOTE: hook http_cb
  71. req->http_cb = [this](HttpMessage* msg, http_parser_state state, const char* data, size_t size) {
  72. if (this->state == WANT_CLOSE || this->error != 0) return;
  73. switch (state) {
  74. case HP_HEADERS_COMPLETE:
  75. onHeadersComplete();
  76. break;
  77. case HP_BODY:
  78. if (api_handler && api_handler->state_handler) {
  79. break;
  80. }
  81. msg->body.append(data, size);
  82. return;
  83. case HP_MESSAGE_COMPLETE:
  84. onMessageComplete();
  85. return;
  86. default:
  87. break;
  88. }
  89. if (api_handler && api_handler->state_handler) {
  90. api_handler->state_handler(getHttpContext(), state, data, size);
  91. }
  92. };
  93. return true;
  94. }
  95. void HttpHandler::Reset() {
  96. state = WANT_RECV;
  97. error = 0;
  98. req->Reset();
  99. resp->Reset();
  100. ctx = NULL;
  101. api_handler = NULL;
  102. closeFile();
  103. if (writer) {
  104. writer->Begin();
  105. writer->onwrite = NULL;
  106. writer->onclose = NULL;
  107. }
  108. parser->InitRequest(req.get());
  109. }
  110. void HttpHandler::Close() {
  111. if (writer) {
  112. writer->status = hv::SocketChannel::DISCONNECTED;
  113. }
  114. // close proxy
  115. if (proxy) {
  116. if (io) hio_close_upstream(io);
  117. }
  118. // close file
  119. closeFile();
  120. // onclose
  121. if (protocol == HttpHandler::WEBSOCKET) {
  122. WebSocketOnClose();
  123. } else {
  124. if (writer && writer->onclose) {
  125. writer->onclose();
  126. }
  127. }
  128. }
  129. bool HttpHandler::SwitchHTTP2() {
  130. parser.reset(HttpParser::New(HTTP_SERVER, ::HTTP_V2));
  131. if (parser == NULL) {
  132. return false;
  133. }
  134. protocol = HTTP_V2;
  135. resp->http_major = req->http_major = 2;
  136. resp->http_minor = req->http_minor = 0;
  137. parser->InitRequest(req.get());
  138. return true;
  139. }
  140. bool HttpHandler::SwitchWebSocket() {
  141. if(!io) return false;
  142. protocol = WEBSOCKET;
  143. ws_parser = std::make_shared<WebSocketParser>();
  144. ws_channel = std::make_shared<WebSocketChannel>(io, WS_SERVER);
  145. ws_parser->onMessage = [this](int opcode, const std::string& msg){
  146. ws_channel->opcode = (enum ws_opcode)opcode;
  147. switch(opcode) {
  148. case WS_OPCODE_CLOSE:
  149. ws_channel->close();
  150. break;
  151. case WS_OPCODE_PING:
  152. // printf("recv ping\n");
  153. // printf("send pong\n");
  154. ws_channel->sendPong();
  155. break;
  156. case WS_OPCODE_PONG:
  157. // printf("recv pong\n");
  158. this->last_recv_pong_time = gethrtime_us();
  159. break;
  160. case WS_OPCODE_TEXT:
  161. case WS_OPCODE_BINARY:
  162. // onmessage
  163. if (ws_service && ws_service->onmessage) {
  164. ws_service->onmessage(ws_channel, msg);
  165. }
  166. break;
  167. default:
  168. break;
  169. }
  170. };
  171. // NOTE: cancel keepalive timer, judge alive by heartbeat.
  172. ws_channel->setKeepaliveTimeout(0);
  173. if (ws_service && ws_service->ping_interval > 0) {
  174. int ping_interval = MAX(ws_service->ping_interval, 1000);
  175. ws_channel->setHeartbeat(ping_interval, [this](){
  176. if (last_recv_pong_time < last_send_ping_time) {
  177. hlogw("[%s:%d] websocket no pong!", ip, port);
  178. ws_channel->close();
  179. } else {
  180. // printf("send ping\n");
  181. ws_channel->sendPing();
  182. last_send_ping_time = gethrtime_us();
  183. }
  184. });
  185. }
  186. return true;
  187. }
  188. const HttpContextPtr& HttpHandler::getHttpContext() {
  189. if (!ctx) {
  190. ctx = std::make_shared<hv::HttpContext>();
  191. ctx->service = service;
  192. ctx->request = req;
  193. ctx->response = resp;
  194. ctx->writer = writer;
  195. }
  196. return ctx;
  197. }
  198. int HttpHandler::customHttpHandler(const http_handler& handler) {
  199. return invokeHttpHandler(&handler);
  200. }
  201. int HttpHandler::invokeHttpHandler(const http_handler* handler) {
  202. int status_code = HTTP_STATUS_NOT_IMPLEMENTED;
  203. if (handler->sync_handler) {
  204. // NOTE: sync_handler run on IO thread
  205. status_code = handler->sync_handler(req.get(), resp.get());
  206. } else if (handler->async_handler) {
  207. // NOTE: async_handler run on hv::async threadpool
  208. hv::async(std::bind(handler->async_handler, req, writer));
  209. status_code = HTTP_STATUS_NEXT;
  210. } else if (handler->ctx_handler) {
  211. // NOTE: ctx_handler run on IO thread, you can easily post HttpContextPtr to your consumer thread for processing.
  212. status_code = handler->ctx_handler(getHttpContext());
  213. } else if (handler->state_handler) {
  214. status_code = handler->state_handler(getHttpContext(), HP_MESSAGE_COMPLETE, NULL, 0);
  215. }
  216. return status_code;
  217. }
  218. void HttpHandler::onHeadersComplete() {
  219. HttpRequest* pReq = req.get();
  220. pReq->scheme = ssl ? "https" : "http";
  221. pReq->client_addr.ip = ip;
  222. pReq->client_addr.port = port;
  223. // keepalive
  224. keepalive = pReq->IsKeepAlive();
  225. // NOTE: Detect proxy before ParseUrl
  226. proxy = 0;
  227. if (hv::startswith(pReq->url, "http")) {
  228. // forward proxy
  229. proxy = 1;
  230. auto iter = pReq->headers.find("Proxy-Connection");
  231. if (iter != pReq->headers.end()) {
  232. const char* keepalive_value = iter->second.c_str();
  233. if (stricmp(keepalive_value, "keep-alive") == 0) {
  234. keepalive = true;
  235. }
  236. else if (stricmp(keepalive_value, "close") == 0) {
  237. keepalive = false;
  238. }
  239. else if (stricmp(keepalive_value, "upgrade") == 0) {
  240. keepalive = true;
  241. }
  242. }
  243. }
  244. // printf("url=%s\n", pReq->url.c_str());
  245. pReq->ParseUrl();
  246. if (service && service->pathHandlers.size() != 0) {
  247. service->GetRoute(pReq, &api_handler);
  248. }
  249. if (api_handler && api_handler->state_handler && writer) {
  250. writer->onclose = [this](){
  251. // HP_ERROR
  252. if (!parser->IsComplete()) {
  253. if (api_handler && api_handler->state_handler) {
  254. api_handler->state_handler(getHttpContext(), HP_ERROR, NULL, 0);
  255. }
  256. }
  257. };
  258. return;
  259. }
  260. if (proxy) {
  261. // forward proxy
  262. if (service && service->enable_forward_proxy) {
  263. proxyConnect(pReq->url);
  264. } else {
  265. proxy = 0;
  266. resp->status_code = HTTP_STATUS_FORBIDDEN;
  267. hlogw("Forbidden to forward proxy %s", pReq->url.c_str());
  268. }
  269. }
  270. else if (service && service->proxies.size() != 0) {
  271. // reverse proxy
  272. std::string proxy_url = service->GetProxyUrl(pReq->path.c_str());
  273. if (!proxy_url.empty()) {
  274. proxy = 1;
  275. pReq->url = proxy_url;
  276. proxyConnect(pReq->url);
  277. }
  278. }
  279. else {
  280. // TODO: rewrite
  281. }
  282. }
  283. void HttpHandler::onMessageComplete() {
  284. int status_code = 200;
  285. // Server:
  286. static char s_Server[64] = {'\0'};
  287. if (s_Server[0] == '\0') {
  288. snprintf(s_Server, sizeof(s_Server), "httpd/%s", hv_version());
  289. }
  290. resp->headers["Server"] = s_Server;
  291. // Connection:
  292. resp->headers["Connection"] = keepalive ? "keep-alive" : "close";
  293. // Upgrade ? SwitchHTTP2 / SwitchWebSocket : HandleHttpRequest ->
  294. // while (GetSendData) -> send
  295. upgrade = false;
  296. HttpHandler::ProtocolType upgrade_protocol = HttpHandler::UNKNOWN;
  297. auto iter_upgrade = req->headers.find("upgrade");
  298. if (iter_upgrade != req->headers.end()) {
  299. upgrade = true;
  300. const char* upgrade_proto = iter_upgrade->second.c_str();
  301. hlogi("[%s:%d] Upgrade: %s", ip, port, upgrade_proto);
  302. // websocket
  303. if (stricmp(upgrade_proto, "websocket") == 0) {
  304. /*
  305. HTTP/1.1 101 Switching Protocols
  306. Connection: Upgrade
  307. Upgrade: websocket
  308. Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
  309. */
  310. resp->status_code = HTTP_STATUS_SWITCHING_PROTOCOLS;
  311. resp->headers["Connection"] = "Upgrade";
  312. resp->headers["Upgrade"] = "websocket";
  313. auto iter_key = req->headers.find(SEC_WEBSOCKET_KEY);
  314. if (iter_key != req->headers.end()) {
  315. char ws_accept[32] = {0};
  316. ws_encode_key(iter_key->second.c_str(), ws_accept);
  317. resp->headers[SEC_WEBSOCKET_ACCEPT] = ws_accept;
  318. }
  319. auto iter_protocol = req->headers.find(SEC_WEBSOCKET_PROTOCOL);
  320. if (iter_protocol != req->headers.end()) {
  321. hv::StringList subprotocols = hv::split(iter_protocol->second, ',');
  322. if (subprotocols.size() > 0) {
  323. hlogw("%s: %s => just select first protocol %s", SEC_WEBSOCKET_PROTOCOL, iter_protocol->second.c_str(), subprotocols[0].c_str());
  324. resp->headers[SEC_WEBSOCKET_PROTOCOL] = subprotocols[0];
  325. }
  326. }
  327. upgrade_protocol = HttpHandler::WEBSOCKET;
  328. // NOTE: SwitchWebSocket after send handshake response
  329. }
  330. // h2/h2c
  331. else if (strnicmp(upgrade_proto, "h2", 2) == 0) {
  332. /*
  333. HTTP/1.1 101 Switching Protocols
  334. Connection: Upgrade
  335. Upgrade: h2c
  336. */
  337. if (io) hio_write(io, HTTP2_UPGRADE_RESPONSE, strlen(HTTP2_UPGRADE_RESPONSE));
  338. if (!SwitchHTTP2()) {
  339. hloge("[%s:%d] unsupported HTTP2", ip, port);
  340. error = ERR_INVALID_PROTOCOL;
  341. return;
  342. }
  343. }
  344. else {
  345. hloge("[%s:%d] unsupported Upgrade: %s", upgrade_proto);
  346. error = ERR_INVALID_PROTOCOL;
  347. return;
  348. }
  349. } else {
  350. status_code = HandleHttpRequest();
  351. }
  352. if (io) {
  353. char* data = NULL;
  354. size_t len = 0;
  355. while (GetSendData(&data, &len)) {
  356. // printf("%.*s\n", (int)len, data);
  357. if (data && len) {
  358. hio_write(io, data, len);
  359. }
  360. }
  361. }
  362. // access log
  363. if (service && service->enable_access_log) {
  364. hlogi("[%ld-%ld][%s:%d][%s %s]=>[%d %s]",
  365. pid, tid, ip, port,
  366. http_method_str(req->method), req->path.c_str(),
  367. resp->status_code, resp->status_message());
  368. }
  369. // switch protocol to websocket
  370. if (upgrade && upgrade_protocol == HttpHandler::WEBSOCKET) {
  371. if (!SwitchWebSocket()) {
  372. hloge("[%s:%d] unsupported websocket", ip, port);
  373. error = ERR_INVALID_PROTOCOL;
  374. return;
  375. }
  376. // onopen
  377. WebSocketOnOpen();
  378. return;
  379. }
  380. if (status_code != HTTP_STATUS_NEXT) {
  381. if (keepalive) {
  382. Reset();
  383. } else {
  384. state = WANT_CLOSE;
  385. }
  386. }
  387. }
  388. int HttpHandler::HandleHttpRequest() {
  389. // preprocessor -> processor -> postprocessor
  390. HttpRequest* pReq = req.get();
  391. HttpResponse* pResp = resp.get();
  392. // NOTE: Not all users want to parse body, we comment it out.
  393. // pReq->ParseBody();
  394. int status_code = pResp->status_code;
  395. if (status_code != HTTP_STATUS_OK) {
  396. goto postprocessor;
  397. }
  398. preprocessor:
  399. state = HANDLE_BEGIN;
  400. if (service->preprocessor) {
  401. status_code = customHttpHandler(service->preprocessor);
  402. if (status_code != HTTP_STATUS_NEXT) {
  403. goto postprocessor;
  404. }
  405. }
  406. middleware:
  407. for (const auto& middleware : service->middleware) {
  408. status_code = customHttpHandler(middleware);
  409. if (status_code != HTTP_STATUS_NEXT) {
  410. goto postprocessor;
  411. }
  412. }
  413. processor:
  414. if (service->processor) {
  415. status_code = customHttpHandler(service->processor);
  416. } else {
  417. status_code = defaultRequestHandler();
  418. }
  419. postprocessor:
  420. if (status_code >= 100 && status_code < 600) {
  421. pResp->status_code = (http_status)status_code;
  422. if (pResp->status_code >= 400 && pResp->body.size() == 0 && pReq->method != HTTP_HEAD) {
  423. if (service->errorHandler) {
  424. customHttpHandler(service->errorHandler);
  425. } else {
  426. defaultErrorHandler();
  427. }
  428. }
  429. }
  430. if (fc) {
  431. pResp->content = fc->filebuf.base;
  432. pResp->content_length = fc->filebuf.len;
  433. pResp->headers["Content-Type"] = fc->content_type;
  434. pResp->headers["Last-Modified"] = fc->last_modified;
  435. pResp->headers["Etag"] = fc->etag;
  436. }
  437. if (service->postprocessor) {
  438. customHttpHandler(service->postprocessor);
  439. }
  440. if (writer && writer->state != hv::HttpResponseWriter::SEND_BEGIN) {
  441. status_code = HTTP_STATUS_NEXT;
  442. }
  443. if (status_code == HTTP_STATUS_NEXT) {
  444. state = HANDLE_CONTINUE;
  445. } else {
  446. state = HANDLE_END;
  447. parser->SubmitResponse(resp.get());
  448. }
  449. return status_code;
  450. }
  451. int HttpHandler::defaultRequestHandler() {
  452. int status_code = HTTP_STATUS_OK;
  453. if (api_handler) {
  454. status_code = invokeHttpHandler(api_handler);
  455. }
  456. else if (req->method == HTTP_GET || req->method == HTTP_HEAD) {
  457. // static handler
  458. if (service->staticHandler) {
  459. status_code = customHttpHandler(service->staticHandler);
  460. }
  461. else if (service->staticDirs.size() > 0) {
  462. status_code = defaultStaticHandler();
  463. }
  464. else {
  465. status_code = HTTP_STATUS_NOT_FOUND;
  466. }
  467. }
  468. else {
  469. // Not Implemented
  470. status_code = HTTP_STATUS_NOT_IMPLEMENTED;
  471. }
  472. return status_code;
  473. }
  474. int HttpHandler::defaultStaticHandler() {
  475. // file service
  476. std::string path = req->Path();
  477. const char* req_path = path.c_str();
  478. // path safe check
  479. if (req_path[0] != '/' || strstr(req_path, "/../")) {
  480. return HTTP_STATUS_BAD_REQUEST;
  481. }
  482. std::string filepath;
  483. bool is_dir = path.back() == '/' &&
  484. service->index_of.size() > 0 &&
  485. hv_strstartswith(req_path, service->index_of.c_str());
  486. if (is_dir) {
  487. filepath = service->document_root + path;
  488. } else {
  489. filepath = service->GetStaticFilepath(req_path);
  490. }
  491. if (filepath.empty()) {
  492. return HTTP_STATUS_NOT_FOUND;
  493. }
  494. int status_code = HTTP_STATUS_OK;
  495. // Range:
  496. bool has_range = false;
  497. long from, to = 0;
  498. if (req->GetRange(from, to)) {
  499. has_range = true;
  500. if (openFile(filepath.c_str()) != 0) {
  501. return HTTP_STATUS_NOT_FOUND;
  502. }
  503. long total = file->size();
  504. if (to == 0 || to >= total) to = total - 1;
  505. file->seek(from);
  506. status_code = HTTP_STATUS_PARTIAL_CONTENT;
  507. resp->status_code = HTTP_STATUS_PARTIAL_CONTENT;
  508. resp->content_length = to - from + 1;
  509. resp->SetContentTypeByFilename(filepath.c_str());
  510. resp->SetRange(from, to, total);
  511. if(resp->content_length < service->max_file_cache_size) {
  512. // read into body directly
  513. int nread = file->readrange(resp->body, from, to);
  514. closeFile();
  515. if (nread != resp->content_length) {
  516. resp->content_length = 0;
  517. resp->body.clear();
  518. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  519. }
  520. }
  521. else {
  522. if (service->largeFileHandler) {
  523. status_code = customHttpHandler(service->largeFileHandler);
  524. } else {
  525. status_code = defaultLargeFileHandler();
  526. }
  527. }
  528. return status_code;
  529. }
  530. // FileCache
  531. FileCache::OpenParam param;
  532. param.max_read = service->max_file_cache_size;
  533. param.need_read = !(req->method == HTTP_HEAD || has_range);
  534. param.path = req_path;
  535. if (files) {
  536. fc = files->Open(filepath.c_str(), &param);
  537. }
  538. if (fc == NULL) {
  539. if (param.error == ERR_OVER_LIMIT) {
  540. if (service->largeFileHandler) {
  541. status_code = customHttpHandler(service->largeFileHandler);
  542. } else {
  543. status_code = defaultLargeFileHandler();
  544. }
  545. } else {
  546. status_code = HTTP_STATUS_NOT_FOUND;
  547. }
  548. }
  549. else {
  550. // Not Modified
  551. auto iter = req->headers.find("if-not-match");
  552. if (iter != req->headers.end() &&
  553. strcmp(iter->second.c_str(), fc->etag) == 0) {
  554. fc = NULL;
  555. return HTTP_STATUS_NOT_MODIFIED;
  556. }
  557. iter = req->headers.find("if-modified-since");
  558. if (iter != req->headers.end() &&
  559. strcmp(iter->second.c_str(), fc->last_modified) == 0) {
  560. fc = NULL;
  561. return HTTP_STATUS_NOT_MODIFIED;
  562. }
  563. }
  564. return status_code;
  565. }
  566. int HttpHandler::defaultLargeFileHandler() {
  567. if (!writer) return HTTP_STATUS_NOT_IMPLEMENTED;
  568. if (!isFileOpened()) {
  569. std::string filepath = service->GetStaticFilepath(req->Path().c_str());
  570. if (filepath.empty() || openFile(filepath.c_str()) != 0) {
  571. return HTTP_STATUS_NOT_FOUND;
  572. }
  573. resp->content_length = file->size();
  574. resp->SetContentTypeByFilename(filepath.c_str());
  575. }
  576. if (service->limit_rate == 0) {
  577. // forbidden to send large file
  578. resp->content_length = 0;
  579. resp->status_code = HTTP_STATUS_FORBIDDEN;
  580. } else {
  581. size_t bufsize = 40960; // 40K
  582. file->buf.resize(bufsize);
  583. if (service->limit_rate < 0) {
  584. // unlimited: sendFile when writable
  585. writer->onwrite = [this](HBuf* buf) {
  586. if (writer->isWriteComplete()) {
  587. sendFile();
  588. }
  589. };
  590. } else {
  591. // limit_rate=40KB/s interval_ms=1000
  592. // limit_rate=500KB/s interval_ms=80
  593. int interval_ms = file->buf.len * 1000 / 1024 / service->limit_rate;
  594. // limit_rate=40MB/s interval_m=1: 40KB/ms = 40MB/s = 320Mbps
  595. if (interval_ms == 0) interval_ms = 1;
  596. // printf("limit_rate=%dKB/s interval_ms=%d\n", service->limit_rate, interval_ms);
  597. file->timer = setInterval(interval_ms, std::bind(&HttpHandler::sendFile, this));
  598. }
  599. }
  600. writer->EndHeaders();
  601. return HTTP_STATUS_UNFINISHED;
  602. }
  603. int HttpHandler::defaultErrorHandler() {
  604. // error page
  605. if (service->error_page.size() != 0) {
  606. std::string filepath = service->document_root + '/' + service->error_page;
  607. if (files) {
  608. // cache and load error page
  609. FileCache::OpenParam param;
  610. fc = files->Open(filepath.c_str(), &param);
  611. }
  612. }
  613. // status page
  614. if (fc == NULL && resp->body.size() == 0) {
  615. resp->content_type = TEXT_HTML;
  616. make_http_status_page(resp->status_code, resp->body);
  617. }
  618. return 0;
  619. }
  620. int HttpHandler::FeedRecvData(const char* data, size_t len) {
  621. if (protocol == HttpHandler::UNKNOWN) {
  622. int http_version = 1;
  623. #if WITH_NGHTTP2
  624. if (strncmp(data, HTTP2_MAGIC, MIN(len, HTTP2_MAGIC_LEN)) == 0) {
  625. http_version = 2;
  626. }
  627. #else
  628. // check request-line
  629. if (len < MIN_HTTP_REQUEST_LEN) {
  630. hloge("[%s:%d] http request-line too small", ip, port);
  631. error = ERR_REQUEST;
  632. return -1;
  633. }
  634. for (int i = 0; i < MIN_HTTP_REQUEST_LEN; ++i) {
  635. if (!IS_GRAPH(data[i])) {
  636. hloge("[%s:%d] http request-line not plain", ip, port);
  637. error = ERR_REQUEST;
  638. return -1;
  639. }
  640. }
  641. #endif
  642. if (!Init(http_version)) {
  643. hloge("[%s:%d] unsupported HTTP%d", ip, port, http_version);
  644. error = ERR_INVALID_PROTOCOL;
  645. return -1;
  646. }
  647. }
  648. int nfeed = 0;
  649. switch (protocol) {
  650. case HttpHandler::HTTP_V1:
  651. case HttpHandler::HTTP_V2:
  652. if (state != WANT_RECV) {
  653. Reset();
  654. }
  655. nfeed = parser->FeedRecvData(data, len);
  656. if (nfeed != len) {
  657. hloge("[%s:%d] http parse error: %s", ip, port, parser->StrError(parser->GetError()));
  658. error = ERR_PARSE;
  659. return -1;
  660. }
  661. break;
  662. case HttpHandler::WEBSOCKET:
  663. nfeed = ws_parser->FeedRecvData(data, len);
  664. if (nfeed != len) {
  665. hloge("[%s:%d] websocket parse error!", ip, port);
  666. error = ERR_PARSE;
  667. return -1;
  668. }
  669. break;
  670. default:
  671. hloge("[%s:%d] unknown protocol", ip, port);
  672. error = ERR_INVALID_PROTOCOL;
  673. return -1;
  674. }
  675. if (state == WANT_CLOSE) return 0;
  676. return error ? -1 : nfeed;
  677. }
  678. int HttpHandler::GetSendData(char** data, size_t* len) {
  679. if (state == HANDLE_CONTINUE) {
  680. return 0;
  681. }
  682. HttpRequest* pReq = req.get();
  683. HttpResponse* pResp = resp.get();
  684. if (protocol == HTTP_V1) {
  685. switch(state) {
  686. case WANT_RECV:
  687. if (parser->IsComplete()) state = WANT_SEND;
  688. else return 0;
  689. case HANDLE_END:
  690. state = WANT_SEND;
  691. case WANT_SEND:
  692. state = SEND_HEADER;
  693. case SEND_HEADER:
  694. {
  695. size_t content_length = 0;
  696. const char* content = NULL;
  697. // HEAD
  698. if (pReq->method == HTTP_HEAD) {
  699. if (fc) {
  700. pResp->headers["Accept-Ranges"] = "bytes";
  701. pResp->headers["Content-Length"] = hv::to_string(fc->st.st_size);
  702. } else {
  703. pResp->headers["Content-Type"] = "text/html";
  704. pResp->headers["Content-Length"] = "0";
  705. }
  706. state = SEND_DONE;
  707. goto return_nobody;
  708. }
  709. // File service
  710. if (fc) {
  711. // FileCache
  712. // NOTE: no copy filebuf, more efficient
  713. header = pResp->Dump(true, false);
  714. fc->prepend_header(header.c_str(), header.size());
  715. *data = fc->httpbuf.base;
  716. *len = fc->httpbuf.len;
  717. state = SEND_DONE;
  718. return *len;
  719. }
  720. // API service
  721. content_length = pResp->ContentLength();
  722. content = (const char*)pResp->Content();
  723. if (content) {
  724. if (content_length > (1 << 20)) {
  725. state = SEND_BODY;
  726. goto return_header;
  727. } else {
  728. // NOTE: header+body in one package if <= 1M
  729. header = pResp->Dump(true, false);
  730. header.append(content, content_length);
  731. state = SEND_DONE;
  732. goto return_header;
  733. }
  734. } else {
  735. state = SEND_DONE;
  736. goto return_header;
  737. }
  738. return_nobody:
  739. pResp->content_length = 0;
  740. return_header:
  741. if (header.empty()) header = pResp->Dump(true, false);
  742. *data = (char*)header.c_str();
  743. *len = header.size();
  744. return *len;
  745. }
  746. case SEND_BODY:
  747. {
  748. *data = (char*)pResp->Content();
  749. *len = pResp->ContentLength();
  750. state = SEND_DONE;
  751. return *len;
  752. }
  753. case SEND_DONE:
  754. {
  755. // NOTE: remove file cache if > FILE_CACHE_MAX_SIZE
  756. if (fc && fc->filebuf.len > FILE_CACHE_MAX_SIZE) {
  757. files->Close(fc);
  758. }
  759. fc = NULL;
  760. header.clear();
  761. return 0;
  762. }
  763. default:
  764. return 0;
  765. }
  766. } else if (protocol == HTTP_V2) {
  767. return parser->GetSendData(data, len);
  768. }
  769. return 0;
  770. }
  771. int HttpHandler::openFile(const char* filepath) {
  772. closeFile();
  773. file = new LargeFile;
  774. file->timer = INVALID_TIMER_ID;
  775. return file->open(filepath, "rb");
  776. }
  777. bool HttpHandler::isFileOpened() {
  778. return file && file->isopen();
  779. }
  780. int HttpHandler::sendFile() {
  781. if (!writer || !writer->isWriteComplete() ||
  782. !isFileOpened() ||
  783. file->buf.len == 0 ||
  784. resp->content_length == 0) {
  785. return -1;
  786. }
  787. int readbytes = MIN(file->buf.len, resp->content_length);
  788. size_t nread = file->read(file->buf.base, readbytes);
  789. if (nread <= 0) {
  790. hloge("read file error!");
  791. error = ERR_READ_FILE;
  792. writer->close(true);
  793. return nread;
  794. }
  795. int nwrite = writer->WriteBody(file->buf.base, nread);
  796. if (nwrite < 0) {
  797. // disconnectd
  798. writer->close(true);
  799. return nwrite;
  800. }
  801. resp->content_length -= nread;
  802. if (resp->content_length == 0) {
  803. writer->End();
  804. closeFile();
  805. }
  806. return nread;
  807. }
  808. void HttpHandler::closeFile() {
  809. if (file) {
  810. if (file->timer != INVALID_TIMER_ID) {
  811. killTimer(file->timer);
  812. file->timer = INVALID_TIMER_ID;
  813. }
  814. delete file;
  815. file = NULL;
  816. }
  817. }
  818. void HttpHandler::onProxyConnect(hio_t* upstream_io) {
  819. // printf("onProxyConnect\n");
  820. HttpHandler* handler = (HttpHandler*)hevent_userdata(upstream_io);
  821. hio_t* io = hio_get_upstream(upstream_io);
  822. assert(handler != NULL && io != NULL);
  823. HttpRequest* req = handler->req.get();
  824. // NOTE: send head + received body
  825. req->headers.erase("Proxy-Connection");
  826. req->headers["Connection"] = handler->keepalive ? "keep-alive" : "close";
  827. req->headers["X-Real-IP"] = handler->ip;
  828. std::string msg = req->Dump(true, true);
  829. // printf("%s\n", msg.c_str());
  830. hio_write(upstream_io, msg.c_str(), msg.size());
  831. // NOTE: start recv body continue then upstream
  832. hio_setcb_read(io, hio_write_upstream);
  833. hio_read_start(io);
  834. hio_setcb_read(upstream_io, hio_write_upstream);
  835. hio_read_start(upstream_io);
  836. }
  837. int HttpHandler::proxyConnect(const std::string& strUrl) {
  838. if (!io) return ERR_NULL_POINTER;
  839. hloop_t* loop = hevent_loop(io);
  840. HUrl url;
  841. if (!url.parse(strUrl)) {
  842. return ERR_PARSE;
  843. }
  844. hlogi("proxy_pass %s", strUrl.c_str());
  845. hio_t* upstream_io = hio_create_socket(loop, url.host.c_str(), url.port, HIO_TYPE_TCP, HIO_CLIENT_SIDE);
  846. if (upstream_io == NULL) {
  847. hio_close_async(io);
  848. return ERR_SOCKET;
  849. }
  850. if (url.scheme == "https") {
  851. hio_enable_ssl(upstream_io);
  852. }
  853. hevent_set_userdata(upstream_io, this);
  854. hio_setup_upstream(io, upstream_io);
  855. hio_setcb_connect(upstream_io, HttpHandler::onProxyConnect);
  856. hio_setcb_close(upstream_io, hio_close_upstream);
  857. if (service->proxy_connect_timeout > 0) {
  858. hio_set_connect_timeout(upstream_io, service->proxy_connect_timeout);
  859. }
  860. if (service->proxy_read_timeout > 0) {
  861. hio_set_read_timeout(io, service->proxy_read_timeout);
  862. }
  863. if (service->proxy_write_timeout > 0) {
  864. hio_set_write_timeout(io, service->proxy_write_timeout);
  865. }
  866. hio_connect(upstream_io);
  867. // NOTE: wait upstream_io connected then start read
  868. hio_read_stop(io);
  869. return 0;
  870. }