HttpHandler.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. #include "HttpHandler.h"
  2. #include "hbase.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 "http_page.h"
  9. #include "EventLoop.h" // import hv::setInterval
  10. using namespace hv;
  11. HttpHandler::HttpHandler() {
  12. protocol = UNKNOWN;
  13. state = WANT_RECV;
  14. ssl = false;
  15. service = NULL;
  16. ws_service = NULL;
  17. api_handler = NULL;
  18. last_send_ping_time = 0;
  19. last_recv_pong_time = 0;
  20. files = NULL;
  21. file = NULL;
  22. }
  23. HttpHandler::~HttpHandler() {
  24. closeFile();
  25. if (writer) {
  26. writer->status = hv::SocketChannel::DISCONNECTED;
  27. }
  28. }
  29. bool HttpHandler::Init(int http_version, hio_t* io) {
  30. parser.reset(HttpParser::New(HTTP_SERVER, (enum http_version)http_version));
  31. if (parser == NULL) {
  32. return false;
  33. }
  34. req.reset(new HttpRequest);
  35. resp.reset(new HttpResponse);
  36. if(http_version == 1) {
  37. protocol = HTTP_V1;
  38. } else if (http_version == 2) {
  39. protocol = HTTP_V2;
  40. resp->http_major = req->http_major = 2;
  41. resp->http_minor = req->http_minor = 0;
  42. }
  43. if (io) {
  44. writer.reset(new hv::HttpResponseWriter(io, resp));
  45. writer->status = hv::SocketChannel::CONNECTED;
  46. }
  47. initRequest();
  48. return true;
  49. }
  50. void HttpHandler::Reset() {
  51. state = WANT_RECV;
  52. req->Reset();
  53. resp->Reset();
  54. ctx = NULL;
  55. api_handler = NULL;
  56. closeFile();
  57. if (writer) {
  58. writer->Begin();
  59. writer->onwrite = NULL;
  60. writer->onclose = NULL;
  61. }
  62. initRequest();
  63. }
  64. void HttpHandler::initRequest() {
  65. parser->InitRequest(req.get());
  66. // NOTE: hook http_cb
  67. req->http_cb = [this](HttpMessage* msg, http_parser_state state, const char* data, size_t size) {
  68. if (state == HP_HEADERS_COMPLETE) {
  69. onHeadersComplete();
  70. }
  71. if (api_handler && api_handler->state_handler) {
  72. api_handler->state_handler(getHttpContext(), state, data, size);
  73. }
  74. };
  75. }
  76. bool HttpHandler::SwitchHTTP2() {
  77. parser.reset(HttpParser::New(HTTP_SERVER, ::HTTP_V2));
  78. if (parser == NULL) {
  79. return false;
  80. }
  81. protocol = HTTP_V2;
  82. resp->http_major = req->http_major = 2;
  83. resp->http_minor = req->http_minor = 0;
  84. parser->InitRequest(req.get());
  85. return true;
  86. }
  87. bool HttpHandler::SwitchWebSocket(hio_t* io) {
  88. if (!io && writer) io = writer->io();
  89. if(!io) return false;
  90. protocol = WEBSOCKET;
  91. ws_parser.reset(new WebSocketParser);
  92. ws_channel.reset(new hv::WebSocketChannel(io, WS_SERVER));
  93. ws_parser->onMessage = [this](int opcode, const std::string& msg){
  94. ws_channel->opcode = (enum ws_opcode)opcode;
  95. switch(opcode) {
  96. case WS_OPCODE_CLOSE:
  97. ws_channel->close(true);
  98. break;
  99. case WS_OPCODE_PING:
  100. // printf("recv ping\n");
  101. // printf("send pong\n");
  102. ws_channel->sendPong();
  103. break;
  104. case WS_OPCODE_PONG:
  105. // printf("recv pong\n");
  106. this->last_recv_pong_time = gethrtime_us();
  107. break;
  108. case WS_OPCODE_TEXT:
  109. case WS_OPCODE_BINARY:
  110. // onmessage
  111. if (ws_service && ws_service->onmessage) {
  112. ws_service->onmessage(ws_channel, msg);
  113. }
  114. break;
  115. default:
  116. break;
  117. }
  118. };
  119. if (ws_service && ws_service->ping_interval > 0) {
  120. // NOTE: cancel keepalive timer, judge alive by heartbeat.
  121. ws_channel->setKeepaliveTimeout(0);
  122. int ping_interval = MAX(ws_service->ping_interval, 1000);
  123. ws_channel->setHeartbeat(ping_interval, [this](){
  124. if (last_recv_pong_time < last_send_ping_time) {
  125. hlogw("[%s:%d] websocket no pong!", ip, port);
  126. ws_channel->close(true);
  127. } else {
  128. // printf("send ping\n");
  129. ws_channel->sendPing();
  130. last_send_ping_time = gethrtime_us();
  131. }
  132. });
  133. }
  134. return true;
  135. }
  136. const HttpContextPtr& HttpHandler::getHttpContext() {
  137. if (!ctx) {
  138. ctx = std::make_shared<hv::HttpContext>();
  139. ctx->service = service;
  140. ctx->request = req;
  141. ctx->response = resp;
  142. ctx->writer = writer;
  143. }
  144. return ctx;
  145. }
  146. int HttpHandler::customHttpHandler(const http_handler& handler) {
  147. return invokeHttpHandler(&handler);
  148. }
  149. int HttpHandler::invokeHttpHandler(const http_handler* handler) {
  150. int status_code = HTTP_STATUS_NOT_IMPLEMENTED;
  151. if (handler->sync_handler) {
  152. // NOTE: sync_handler run on IO thread
  153. status_code = handler->sync_handler(req.get(), resp.get());
  154. } else if (handler->async_handler) {
  155. // NOTE: async_handler run on hv::async threadpool
  156. hv::async(std::bind(handler->async_handler, req, writer));
  157. status_code = HTTP_STATUS_UNFINISHED;
  158. } else if (handler->ctx_handler) {
  159. // NOTE: ctx_handler run on IO thread, you can easily post HttpContextPtr to your consumer thread for processing.
  160. status_code = handler->ctx_handler(getHttpContext());
  161. } else if (handler->state_handler) {
  162. status_code = resp->status_code;
  163. }
  164. return status_code;
  165. }
  166. void HttpHandler::onHeadersComplete() {
  167. HttpRequest* pReq = req.get();
  168. pReq->scheme = ssl ? "https" : "http";
  169. pReq->client_addr.ip = ip;
  170. pReq->client_addr.port = port;
  171. // keepalive
  172. keepalive = pReq->IsKeepAlive();
  173. // NOTE: Detect proxy before ParseUrl
  174. proxy = 0;
  175. if (hv::startswith(pReq->url, "http")) {
  176. // forward proxy
  177. proxy = 1;
  178. auto iter = pReq->headers.find("Proxy-Connection");
  179. if (iter != pReq->headers.end()) {
  180. const char* keepalive_value = iter->second.c_str();
  181. if (stricmp(keepalive_value, "keep-alive") == 0) {
  182. keepalive = true;
  183. }
  184. else if (stricmp(keepalive_value, "close") == 0) {
  185. keepalive = false;
  186. }
  187. else if (stricmp(keepalive_value, "upgrade") == 0) {
  188. keepalive = true;
  189. }
  190. }
  191. }
  192. // printf("url=%s\n", pReq->url.c_str());
  193. pReq->ParseUrl();
  194. if (service->api_handlers.size() != 0) {
  195. service->GetApi(pReq, &api_handler);
  196. }
  197. if (api_handler && api_handler->state_handler) {
  198. writer->onclose = [this](){
  199. // HP_ERROR
  200. if (!parser->IsComplete()) {
  201. if (api_handler && api_handler->state_handler) {
  202. api_handler->state_handler(getHttpContext(), HP_ERROR, NULL, 0);
  203. }
  204. }
  205. };
  206. } else {
  207. // NOTE: not hook http_cb
  208. pReq->http_cb = NULL;
  209. if (!proxy && service->proxies.size() != 0) {
  210. // reverse proxy
  211. std::string proxy_url = service->GetProxyUrl(pReq->path.c_str());
  212. if (!proxy_url.empty()) {
  213. proxy = 1;
  214. pReq->url = proxy_url;
  215. }
  216. }
  217. if (proxy) {
  218. proxyConnect(pReq->url);
  219. } else {
  220. // TODO: rewrite
  221. }
  222. }
  223. }
  224. void HttpHandler::onProxyConnect(hio_t* upstream_io) {
  225. // printf("onProxyConnect\n");
  226. HttpHandler* handler = (HttpHandler*)hevent_userdata(upstream_io);
  227. hio_t* io = hio_get_upstream(upstream_io);
  228. assert(handler != NULL && io != NULL);
  229. HttpRequest* req = handler->req.get();
  230. // NOTE: send head + received body
  231. req->headers.erase("Proxy-Connection");
  232. req->headers["Connection"] = handler->keepalive ? "keep-alive" : "close";
  233. req->headers["X-Origin-IP"] = handler->ip;
  234. std::string msg = req->Dump(true, true);
  235. // printf("%s\n", msg.c_str());
  236. hio_write(upstream_io, msg.c_str(), msg.size());
  237. // NOTE: start recv body continue then upstream
  238. hio_setcb_read(io, hio_write_upstream);
  239. hio_read_start(io);
  240. hio_setcb_read(upstream_io, hio_write_upstream);
  241. hio_read_start(upstream_io);
  242. }
  243. int HttpHandler::proxyConnect(const std::string& strUrl) {
  244. if (!writer) return ERR_NULL_POINTER;
  245. hio_t* io = writer->io();
  246. hloop_t* loop = hevent_loop(io);
  247. HUrl url;
  248. if (!url.parse(strUrl)) {
  249. return ERR_PARSE;
  250. }
  251. hlogi("proxy_pass %s", strUrl.c_str());
  252. hio_t* upstream_io = hio_create_socket(loop, url.host.c_str(), url.port, HIO_TYPE_TCP, HIO_CLIENT_SIDE);
  253. if (upstream_io == NULL) {
  254. hio_close_async(io);
  255. return ERR_SOCKET;
  256. }
  257. if (url.scheme == "https") {
  258. hio_enable_ssl(upstream_io);
  259. }
  260. hevent_set_userdata(upstream_io, this);
  261. hio_setup_upstream(io, upstream_io);
  262. hio_setcb_connect(upstream_io, HttpHandler::onProxyConnect);
  263. hio_setcb_close(upstream_io, hio_close_upstream);
  264. if (service->proxy_connect_timeout > 0) {
  265. hio_set_connect_timeout(upstream_io, service->proxy_connect_timeout);
  266. }
  267. if (service->proxy_read_timeout > 0) {
  268. hio_set_read_timeout(io, service->proxy_read_timeout);
  269. }
  270. if (service->proxy_write_timeout > 0) {
  271. hio_set_write_timeout(io, service->proxy_write_timeout);
  272. }
  273. hio_connect(upstream_io);
  274. // NOTE: wait upstream_io connected then start read
  275. hio_read_stop(io);
  276. return 0;
  277. }
  278. int HttpHandler::HandleHttpRequest() {
  279. // preprocessor -> processor -> postprocessor
  280. int status_code = HTTP_STATUS_OK;
  281. HttpRequest* pReq = req.get();
  282. HttpResponse* pResp = resp.get();
  283. // NOTE: Not all users want to parse body, we comment it out.
  284. // pReq->ParseBody();
  285. preprocessor:
  286. state = HANDLE_BEGIN;
  287. if (service->preprocessor) {
  288. status_code = customHttpHandler(service->preprocessor);
  289. if (status_code != 0) {
  290. goto postprocessor;
  291. }
  292. }
  293. processor:
  294. if (service->processor) {
  295. status_code = customHttpHandler(service->processor);
  296. } else {
  297. status_code = defaultRequestHandler();
  298. }
  299. postprocessor:
  300. if (status_code >= 100 && status_code < 600) {
  301. pResp->status_code = (http_status)status_code;
  302. }
  303. if (pResp->status_code >= 400 && pResp->body.size() == 0 && pReq->method != HTTP_HEAD) {
  304. if (service->errorHandler) {
  305. customHttpHandler(service->errorHandler);
  306. } else {
  307. defaultErrorHandler();
  308. }
  309. }
  310. if (fc) {
  311. pResp->content = fc->filebuf.base;
  312. pResp->content_length = fc->filebuf.len;
  313. pResp->headers["Content-Type"] = fc->content_type;
  314. pResp->headers["Last-Modified"] = fc->last_modified;
  315. pResp->headers["Etag"] = fc->etag;
  316. }
  317. if (service->postprocessor) {
  318. customHttpHandler(service->postprocessor);
  319. }
  320. if (writer && writer->state != hv::HttpResponseWriter::SEND_BEGIN) {
  321. status_code = 0;
  322. }
  323. if (status_code == 0) {
  324. state = HANDLE_CONTINUE;
  325. } else {
  326. state = HANDLE_END;
  327. parser->SubmitResponse(resp.get());
  328. }
  329. return status_code;
  330. }
  331. int HttpHandler::defaultRequestHandler() {
  332. int status_code = HTTP_STATUS_OK;
  333. if (api_handler) {
  334. status_code = invokeHttpHandler(api_handler);
  335. }
  336. else if (req->method == HTTP_GET || req->method == HTTP_HEAD) {
  337. // static handler
  338. if (service->staticHandler) {
  339. status_code = customHttpHandler(service->staticHandler);
  340. }
  341. else if (service->staticDirs.size() > 0) {
  342. status_code = defaultStaticHandler();
  343. }
  344. else {
  345. status_code = HTTP_STATUS_NOT_FOUND;
  346. }
  347. }
  348. else {
  349. // Not Implemented
  350. status_code = HTTP_STATUS_NOT_IMPLEMENTED;
  351. }
  352. return status_code;
  353. }
  354. int HttpHandler::defaultStaticHandler() {
  355. // file service
  356. std::string path = req->Path();
  357. const char* req_path = path.c_str();
  358. // path safe check
  359. if (req_path[0] != '/' || strstr(req_path, "/../")) {
  360. return HTTP_STATUS_BAD_REQUEST;
  361. }
  362. std::string filepath;
  363. bool is_dir = path.back() == '/' &&
  364. service->index_of.size() > 0 &&
  365. hv_strstartswith(req_path, service->index_of.c_str());
  366. if (is_dir) {
  367. filepath = service->document_root + path;
  368. } else {
  369. filepath = service->GetStaticFilepath(req_path);
  370. }
  371. if (filepath.empty()) {
  372. return HTTP_STATUS_NOT_FOUND;
  373. }
  374. int status_code = HTTP_STATUS_OK;
  375. // Range:
  376. bool has_range = false;
  377. long from, to = 0;
  378. if (req->GetRange(from, to)) {
  379. has_range = true;
  380. if (openFile(filepath.c_str()) != 0) {
  381. return HTTP_STATUS_NOT_FOUND;
  382. }
  383. long total = file->size();
  384. if (to == 0 || to >= total) to = total - 1;
  385. file->seek(from);
  386. status_code = HTTP_STATUS_PARTIAL_CONTENT;
  387. resp->status_code = HTTP_STATUS_PARTIAL_CONTENT;
  388. resp->content_length = to - from + 1;
  389. resp->SetContentTypeByFilename(filepath.c_str());
  390. resp->SetRange(from, to, total);
  391. if(resp->content_length < service->max_file_cache_size) {
  392. // read into body directly
  393. int nread = file->readrange(resp->body, from, to);
  394. closeFile();
  395. if (nread != resp->content_length) {
  396. resp->content_length = 0;
  397. resp->body.clear();
  398. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  399. }
  400. }
  401. else {
  402. if (service->largeFileHandler) {
  403. status_code = customHttpHandler(service->largeFileHandler);
  404. } else {
  405. status_code = defaultLargeFileHandler();
  406. }
  407. }
  408. return status_code;
  409. }
  410. // FileCache
  411. FileCache::OpenParam param;
  412. param.max_read = service->max_file_cache_size;
  413. param.need_read = !(req->method == HTTP_HEAD || has_range);
  414. param.path = req_path;
  415. fc = files->Open(filepath.c_str(), &param);
  416. if (fc == NULL) {
  417. if (param.error == ERR_OVER_LIMIT) {
  418. if (service->largeFileHandler) {
  419. status_code = customHttpHandler(service->largeFileHandler);
  420. } else {
  421. status_code = defaultLargeFileHandler();
  422. }
  423. } else {
  424. status_code = HTTP_STATUS_NOT_FOUND;
  425. }
  426. }
  427. else {
  428. // Not Modified
  429. auto iter = req->headers.find("if-not-match");
  430. if (iter != req->headers.end() &&
  431. strcmp(iter->second.c_str(), fc->etag) == 0) {
  432. fc = NULL;
  433. return HTTP_STATUS_NOT_MODIFIED;
  434. }
  435. iter = req->headers.find("if-modified-since");
  436. if (iter != req->headers.end() &&
  437. strcmp(iter->second.c_str(), fc->last_modified) == 0) {
  438. fc = NULL;
  439. return HTTP_STATUS_NOT_MODIFIED;
  440. }
  441. }
  442. return status_code;
  443. }
  444. int HttpHandler::defaultLargeFileHandler() {
  445. if (!writer) return HTTP_STATUS_NOT_IMPLEMENTED;
  446. if (!isFileOpened()) {
  447. std::string filepath = service->GetStaticFilepath(req->Path().c_str());
  448. if (filepath.empty() || openFile(filepath.c_str()) != 0) {
  449. return HTTP_STATUS_NOT_FOUND;
  450. }
  451. resp->content_length = file->size();
  452. resp->SetContentTypeByFilename(filepath.c_str());
  453. }
  454. if (service->limit_rate == 0) {
  455. // forbidden to send large file
  456. resp->content_length = 0;
  457. resp->status_code = HTTP_STATUS_FORBIDDEN;
  458. } else {
  459. size_t bufsize = 40960; // 40K
  460. file->buf.resize(bufsize);
  461. if (service->limit_rate < 0) {
  462. // unlimited: sendFile when writable
  463. writer->onwrite = [this](HBuf* buf) {
  464. if (writer->isWriteComplete()) {
  465. sendFile();
  466. }
  467. };
  468. } else {
  469. // limit_rate=40KB/s interval_ms=1000
  470. // limit_rate=500KB/s interval_ms=80
  471. int interval_ms = file->buf.len * 1000 / 1024 / service->limit_rate;
  472. // limit_rate=40MB/s interval_m=1: 40KB/ms = 40MB/s = 320Mbps
  473. if (interval_ms == 0) interval_ms = 1;
  474. // printf("limit_rate=%dKB/s interval_ms=%d\n", service->limit_rate, interval_ms);
  475. file->timer = setInterval(interval_ms, std::bind(&HttpHandler::sendFile, this));
  476. }
  477. }
  478. writer->EndHeaders();
  479. return HTTP_STATUS_UNFINISHED;
  480. }
  481. int HttpHandler::defaultErrorHandler() {
  482. // error page
  483. if (service->error_page.size() != 0) {
  484. std::string filepath = service->document_root + '/' + service->error_page;
  485. // cache and load error page
  486. FileCache::OpenParam param;
  487. fc = files->Open(filepath.c_str(), &param);
  488. }
  489. // status page
  490. if (fc == NULL && resp->body.size() == 0) {
  491. resp->content_type = TEXT_HTML;
  492. make_http_status_page(resp->status_code, resp->body);
  493. }
  494. return 0;
  495. }
  496. int HttpHandler::FeedRecvData(const char* data, size_t len) {
  497. int nfeed = 0;
  498. if (protocol == HttpHandler::WEBSOCKET) {
  499. nfeed = ws_parser->FeedRecvData(data, len);
  500. if (nfeed != len) {
  501. hloge("[%s:%d] websocket parse error!", ip, port);
  502. }
  503. } else {
  504. if (state != WANT_RECV) {
  505. Reset();
  506. }
  507. nfeed = parser->FeedRecvData(data, len);
  508. if (nfeed != len) {
  509. hloge("[%s:%d] http parse error: %s", ip, port, parser->StrError(parser->GetError()));
  510. }
  511. }
  512. return nfeed;
  513. }
  514. int HttpHandler::GetSendData(char** data, size_t* len) {
  515. if (state == HANDLE_CONTINUE) {
  516. return 0;
  517. }
  518. HttpRequest* pReq = req.get();
  519. HttpResponse* pResp = resp.get();
  520. if (protocol == HTTP_V1) {
  521. switch(state) {
  522. case WANT_RECV:
  523. if (parser->IsComplete()) state = WANT_SEND;
  524. else return 0;
  525. case HANDLE_END:
  526. state = WANT_SEND;
  527. case WANT_SEND:
  528. state = SEND_HEADER;
  529. case SEND_HEADER:
  530. {
  531. size_t content_length = 0;
  532. const char* content = NULL;
  533. // HEAD
  534. if (pReq->method == HTTP_HEAD) {
  535. if (fc) {
  536. pResp->headers["Accept-Ranges"] = "bytes";
  537. pResp->headers["Content-Length"] = hv::to_string(fc->st.st_size);
  538. } else {
  539. pResp->headers["Content-Type"] = "text/html";
  540. pResp->headers["Content-Length"] = "0";
  541. }
  542. state = SEND_DONE;
  543. goto return_nobody;
  544. }
  545. // File service
  546. if (fc) {
  547. // FileCache
  548. // NOTE: no copy filebuf, more efficient
  549. header = pResp->Dump(true, false);
  550. fc->prepend_header(header.c_str(), header.size());
  551. *data = fc->httpbuf.base;
  552. *len = fc->httpbuf.len;
  553. state = SEND_DONE;
  554. return *len;
  555. }
  556. // API service
  557. content_length = pResp->ContentLength();
  558. content = (const char*)pResp->Content();
  559. if (content) {
  560. if (content_length > (1 << 20)) {
  561. state = SEND_BODY;
  562. goto return_header;
  563. } else {
  564. // NOTE: header+body in one package if <= 1M
  565. header = pResp->Dump(true, false);
  566. header.append(content, content_length);
  567. state = SEND_DONE;
  568. goto return_header;
  569. }
  570. } else {
  571. state = SEND_DONE;
  572. goto return_header;
  573. }
  574. return_nobody:
  575. pResp->content_length = 0;
  576. return_header:
  577. if (header.empty()) header = pResp->Dump(true, false);
  578. *data = (char*)header.c_str();
  579. *len = header.size();
  580. return *len;
  581. }
  582. case SEND_BODY:
  583. {
  584. *data = (char*)pResp->Content();
  585. *len = pResp->ContentLength();
  586. state = SEND_DONE;
  587. return *len;
  588. }
  589. case SEND_DONE:
  590. {
  591. // NOTE: remove file cache if > FILE_CACHE_MAX_SIZE
  592. if (fc && fc->filebuf.len > FILE_CACHE_MAX_SIZE) {
  593. files->Close(fc);
  594. }
  595. fc = NULL;
  596. header.clear();
  597. return 0;
  598. }
  599. default:
  600. return 0;
  601. }
  602. } else if (protocol == HTTP_V2) {
  603. return parser->GetSendData(data, len);
  604. }
  605. return 0;
  606. }
  607. int HttpHandler::openFile(const char* filepath) {
  608. closeFile();
  609. file = new LargeFile;
  610. file->timer = INVALID_TIMER_ID;
  611. return file->open(filepath, "rb");
  612. }
  613. bool HttpHandler::isFileOpened() {
  614. return file && file->isopen();
  615. }
  616. int HttpHandler::sendFile() {
  617. if (!writer || !writer->isWriteComplete() ||
  618. !isFileOpened() ||
  619. file->buf.len == 0 ||
  620. resp->content_length == 0) {
  621. return -1;
  622. }
  623. int readbytes = MIN(file->buf.len, resp->content_length);
  624. size_t nread = file->read(file->buf.base, readbytes);
  625. if (nread <= 0) {
  626. hloge("read file error!");
  627. writer->close(true);
  628. return nread;
  629. }
  630. int nwrite = writer->WriteBody(file->buf.base, nread);
  631. if (nwrite < 0) {
  632. // disconnectd
  633. writer->close(true);
  634. return nwrite;
  635. }
  636. resp->content_length -= nread;
  637. if (resp->content_length == 0) {
  638. writer->End();
  639. closeFile();
  640. }
  641. return nread;
  642. }
  643. void HttpHandler::closeFile() {
  644. if (file) {
  645. if (file->timer != INVALID_TIMER_ID) {
  646. killTimer(file->timer);
  647. file->timer = INVALID_TIMER_ID;
  648. }
  649. delete file;
  650. file = NULL;
  651. }
  652. }