HttpHandler.cpp 28 KB

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