HttpHandler.cpp 21 KB

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