1
0

HttpHandler.cpp 21 KB

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