HttpHandler.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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) {
  217. // forward proxy
  218. if (service->enable_forward_proxy) {
  219. proxyConnect(pReq->url);
  220. } else {
  221. proxy = 0;
  222. resp->status_code = HTTP_STATUS_FORBIDDEN;
  223. hlogw("Forbidden to forward proxy %s", pReq->url.c_str());
  224. }
  225. }
  226. else if (service->proxies.size() != 0) {
  227. // reverse proxy
  228. std::string proxy_url = service->GetProxyUrl(pReq->path.c_str());
  229. if (!proxy_url.empty()) {
  230. proxy = 1;
  231. pReq->url = proxy_url;
  232. proxyConnect(pReq->url);
  233. }
  234. }
  235. else {
  236. // TODO: rewrite
  237. }
  238. }
  239. }
  240. void HttpHandler::onProxyConnect(hio_t* upstream_io) {
  241. // printf("onProxyConnect\n");
  242. HttpHandler* handler = (HttpHandler*)hevent_userdata(upstream_io);
  243. hio_t* io = hio_get_upstream(upstream_io);
  244. assert(handler != NULL && io != NULL);
  245. HttpRequest* req = handler->req.get();
  246. // NOTE: send head + received body
  247. req->headers.erase("Proxy-Connection");
  248. req->headers["Connection"] = handler->keepalive ? "keep-alive" : "close";
  249. req->headers["X-Real-IP"] = handler->ip;
  250. std::string msg = req->Dump(true, true);
  251. // printf("%s\n", msg.c_str());
  252. hio_write(upstream_io, msg.c_str(), msg.size());
  253. // NOTE: start recv body continue then upstream
  254. hio_setcb_read(io, hio_write_upstream);
  255. hio_read_start(io);
  256. hio_setcb_read(upstream_io, hio_write_upstream);
  257. hio_read_start(upstream_io);
  258. }
  259. int HttpHandler::proxyConnect(const std::string& strUrl) {
  260. if (!writer) return ERR_NULL_POINTER;
  261. hio_t* io = writer->io();
  262. hloop_t* loop = hevent_loop(io);
  263. HUrl url;
  264. if (!url.parse(strUrl)) {
  265. return ERR_PARSE;
  266. }
  267. hlogi("proxy_pass %s", strUrl.c_str());
  268. hio_t* upstream_io = hio_create_socket(loop, url.host.c_str(), url.port, HIO_TYPE_TCP, HIO_CLIENT_SIDE);
  269. if (upstream_io == NULL) {
  270. hio_close_async(io);
  271. return ERR_SOCKET;
  272. }
  273. if (url.scheme == "https") {
  274. hio_enable_ssl(upstream_io);
  275. }
  276. hevent_set_userdata(upstream_io, this);
  277. hio_setup_upstream(io, upstream_io);
  278. hio_setcb_connect(upstream_io, HttpHandler::onProxyConnect);
  279. hio_setcb_close(upstream_io, hio_close_upstream);
  280. if (service->proxy_connect_timeout > 0) {
  281. hio_set_connect_timeout(upstream_io, service->proxy_connect_timeout);
  282. }
  283. if (service->proxy_read_timeout > 0) {
  284. hio_set_read_timeout(io, service->proxy_read_timeout);
  285. }
  286. if (service->proxy_write_timeout > 0) {
  287. hio_set_write_timeout(io, service->proxy_write_timeout);
  288. }
  289. hio_connect(upstream_io);
  290. // NOTE: wait upstream_io connected then start read
  291. hio_read_stop(io);
  292. return 0;
  293. }
  294. int HttpHandler::HandleHttpRequest() {
  295. // preprocessor -> processor -> postprocessor
  296. HttpRequest* pReq = req.get();
  297. HttpResponse* pResp = resp.get();
  298. // NOTE: Not all users want to parse body, we comment it out.
  299. // pReq->ParseBody();
  300. int status_code = pResp->status_code;
  301. if (status_code != HTTP_STATUS_OK) {
  302. goto postprocessor;
  303. }
  304. preprocessor:
  305. state = HANDLE_BEGIN;
  306. if (service->preprocessor) {
  307. status_code = customHttpHandler(service->preprocessor);
  308. if (status_code != 0) {
  309. goto postprocessor;
  310. }
  311. }
  312. processor:
  313. if (service->processor) {
  314. status_code = customHttpHandler(service->processor);
  315. } else {
  316. status_code = defaultRequestHandler();
  317. }
  318. postprocessor:
  319. if (status_code >= 100 && status_code < 600) {
  320. pResp->status_code = (http_status)status_code;
  321. }
  322. if (pResp->status_code >= 400 && pResp->body.size() == 0 && pReq->method != HTTP_HEAD) {
  323. if (service->errorHandler) {
  324. customHttpHandler(service->errorHandler);
  325. } else {
  326. defaultErrorHandler();
  327. }
  328. }
  329. if (fc) {
  330. pResp->content = fc->filebuf.base;
  331. pResp->content_length = fc->filebuf.len;
  332. pResp->headers["Content-Type"] = fc->content_type;
  333. pResp->headers["Last-Modified"] = fc->last_modified;
  334. pResp->headers["Etag"] = fc->etag;
  335. }
  336. if (service->postprocessor) {
  337. customHttpHandler(service->postprocessor);
  338. }
  339. if (writer && writer->state != hv::HttpResponseWriter::SEND_BEGIN) {
  340. status_code = 0;
  341. }
  342. if (status_code == 0) {
  343. state = HANDLE_CONTINUE;
  344. } else {
  345. state = HANDLE_END;
  346. parser->SubmitResponse(resp.get());
  347. }
  348. return status_code;
  349. }
  350. int HttpHandler::defaultRequestHandler() {
  351. int status_code = HTTP_STATUS_OK;
  352. if (api_handler) {
  353. status_code = invokeHttpHandler(api_handler);
  354. }
  355. else if (req->method == HTTP_GET || req->method == HTTP_HEAD) {
  356. // static handler
  357. if (service->staticHandler) {
  358. status_code = customHttpHandler(service->staticHandler);
  359. }
  360. else if (service->staticDirs.size() > 0) {
  361. status_code = defaultStaticHandler();
  362. }
  363. else {
  364. status_code = HTTP_STATUS_NOT_FOUND;
  365. }
  366. }
  367. else {
  368. // Not Implemented
  369. status_code = HTTP_STATUS_NOT_IMPLEMENTED;
  370. }
  371. return status_code;
  372. }
  373. int HttpHandler::defaultStaticHandler() {
  374. // file service
  375. std::string path = req->Path();
  376. const char* req_path = path.c_str();
  377. // path safe check
  378. if (req_path[0] != '/' || strstr(req_path, "/../")) {
  379. return HTTP_STATUS_BAD_REQUEST;
  380. }
  381. std::string filepath;
  382. bool is_dir = path.back() == '/' &&
  383. service->index_of.size() > 0 &&
  384. hv_strstartswith(req_path, service->index_of.c_str());
  385. if (is_dir) {
  386. filepath = service->document_root + path;
  387. } else {
  388. filepath = service->GetStaticFilepath(req_path);
  389. }
  390. if (filepath.empty()) {
  391. return HTTP_STATUS_NOT_FOUND;
  392. }
  393. int status_code = HTTP_STATUS_OK;
  394. // Range:
  395. bool has_range = false;
  396. long from, to = 0;
  397. if (req->GetRange(from, to)) {
  398. has_range = true;
  399. if (openFile(filepath.c_str()) != 0) {
  400. return HTTP_STATUS_NOT_FOUND;
  401. }
  402. long total = file->size();
  403. if (to == 0 || to >= total) to = total - 1;
  404. file->seek(from);
  405. status_code = HTTP_STATUS_PARTIAL_CONTENT;
  406. resp->status_code = HTTP_STATUS_PARTIAL_CONTENT;
  407. resp->content_length = to - from + 1;
  408. resp->SetContentTypeByFilename(filepath.c_str());
  409. resp->SetRange(from, to, total);
  410. if(resp->content_length < service->max_file_cache_size) {
  411. // read into body directly
  412. int nread = file->readrange(resp->body, from, to);
  413. closeFile();
  414. if (nread != resp->content_length) {
  415. resp->content_length = 0;
  416. resp->body.clear();
  417. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  418. }
  419. }
  420. else {
  421. if (service->largeFileHandler) {
  422. status_code = customHttpHandler(service->largeFileHandler);
  423. } else {
  424. status_code = defaultLargeFileHandler();
  425. }
  426. }
  427. return status_code;
  428. }
  429. // FileCache
  430. FileCache::OpenParam param;
  431. param.max_read = service->max_file_cache_size;
  432. param.need_read = !(req->method == HTTP_HEAD || has_range);
  433. param.path = req_path;
  434. fc = files->Open(filepath.c_str(), &param);
  435. if (fc == NULL) {
  436. if (param.error == ERR_OVER_LIMIT) {
  437. if (service->largeFileHandler) {
  438. status_code = customHttpHandler(service->largeFileHandler);
  439. } else {
  440. status_code = defaultLargeFileHandler();
  441. }
  442. } else {
  443. status_code = HTTP_STATUS_NOT_FOUND;
  444. }
  445. }
  446. else {
  447. // Not Modified
  448. auto iter = req->headers.find("if-not-match");
  449. if (iter != req->headers.end() &&
  450. strcmp(iter->second.c_str(), fc->etag) == 0) {
  451. fc = NULL;
  452. return HTTP_STATUS_NOT_MODIFIED;
  453. }
  454. iter = req->headers.find("if-modified-since");
  455. if (iter != req->headers.end() &&
  456. strcmp(iter->second.c_str(), fc->last_modified) == 0) {
  457. fc = NULL;
  458. return HTTP_STATUS_NOT_MODIFIED;
  459. }
  460. }
  461. return status_code;
  462. }
  463. int HttpHandler::defaultLargeFileHandler() {
  464. if (!writer) return HTTP_STATUS_NOT_IMPLEMENTED;
  465. if (!isFileOpened()) {
  466. std::string filepath = service->GetStaticFilepath(req->Path().c_str());
  467. if (filepath.empty() || openFile(filepath.c_str()) != 0) {
  468. return HTTP_STATUS_NOT_FOUND;
  469. }
  470. resp->content_length = file->size();
  471. resp->SetContentTypeByFilename(filepath.c_str());
  472. }
  473. if (service->limit_rate == 0) {
  474. // forbidden to send large file
  475. resp->content_length = 0;
  476. resp->status_code = HTTP_STATUS_FORBIDDEN;
  477. } else {
  478. size_t bufsize = 40960; // 40K
  479. file->buf.resize(bufsize);
  480. if (service->limit_rate < 0) {
  481. // unlimited: sendFile when writable
  482. writer->onwrite = [this](HBuf* buf) {
  483. if (writer->isWriteComplete()) {
  484. sendFile();
  485. }
  486. };
  487. } else {
  488. // limit_rate=40KB/s interval_ms=1000
  489. // limit_rate=500KB/s interval_ms=80
  490. int interval_ms = file->buf.len * 1000 / 1024 / service->limit_rate;
  491. // limit_rate=40MB/s interval_m=1: 40KB/ms = 40MB/s = 320Mbps
  492. if (interval_ms == 0) interval_ms = 1;
  493. // printf("limit_rate=%dKB/s interval_ms=%d\n", service->limit_rate, interval_ms);
  494. file->timer = setInterval(interval_ms, std::bind(&HttpHandler::sendFile, this));
  495. }
  496. }
  497. writer->EndHeaders();
  498. return HTTP_STATUS_UNFINISHED;
  499. }
  500. int HttpHandler::defaultErrorHandler() {
  501. // error page
  502. if (service->error_page.size() != 0) {
  503. std::string filepath = service->document_root + '/' + service->error_page;
  504. // cache and load error page
  505. FileCache::OpenParam param;
  506. fc = files->Open(filepath.c_str(), &param);
  507. }
  508. // status page
  509. if (fc == NULL && resp->body.size() == 0) {
  510. resp->content_type = TEXT_HTML;
  511. make_http_status_page(resp->status_code, resp->body);
  512. }
  513. return 0;
  514. }
  515. int HttpHandler::FeedRecvData(const char* data, size_t len) {
  516. int nfeed = 0;
  517. if (protocol == HttpHandler::WEBSOCKET) {
  518. nfeed = ws_parser->FeedRecvData(data, len);
  519. if (nfeed != len) {
  520. hloge("[%s:%d] websocket parse error!", ip, port);
  521. }
  522. } else {
  523. if (state != WANT_RECV) {
  524. Reset();
  525. }
  526. nfeed = parser->FeedRecvData(data, len);
  527. if (nfeed != len) {
  528. hloge("[%s:%d] http parse error: %s", ip, port, parser->StrError(parser->GetError()));
  529. }
  530. }
  531. return nfeed;
  532. }
  533. int HttpHandler::GetSendData(char** data, size_t* len) {
  534. if (state == HANDLE_CONTINUE) {
  535. return 0;
  536. }
  537. HttpRequest* pReq = req.get();
  538. HttpResponse* pResp = resp.get();
  539. if (protocol == HTTP_V1) {
  540. switch(state) {
  541. case WANT_RECV:
  542. if (parser->IsComplete()) state = WANT_SEND;
  543. else return 0;
  544. case HANDLE_END:
  545. state = WANT_SEND;
  546. case WANT_SEND:
  547. state = SEND_HEADER;
  548. case SEND_HEADER:
  549. {
  550. size_t content_length = 0;
  551. const char* content = NULL;
  552. // HEAD
  553. if (pReq->method == HTTP_HEAD) {
  554. if (fc) {
  555. pResp->headers["Accept-Ranges"] = "bytes";
  556. pResp->headers["Content-Length"] = hv::to_string(fc->st.st_size);
  557. } else {
  558. pResp->headers["Content-Type"] = "text/html";
  559. pResp->headers["Content-Length"] = "0";
  560. }
  561. state = SEND_DONE;
  562. goto return_nobody;
  563. }
  564. // File service
  565. if (fc) {
  566. // FileCache
  567. // NOTE: no copy filebuf, more efficient
  568. header = pResp->Dump(true, false);
  569. fc->prepend_header(header.c_str(), header.size());
  570. *data = fc->httpbuf.base;
  571. *len = fc->httpbuf.len;
  572. state = SEND_DONE;
  573. return *len;
  574. }
  575. // API service
  576. content_length = pResp->ContentLength();
  577. content = (const char*)pResp->Content();
  578. if (content) {
  579. if (content_length > (1 << 20)) {
  580. state = SEND_BODY;
  581. goto return_header;
  582. } else {
  583. // NOTE: header+body in one package if <= 1M
  584. header = pResp->Dump(true, false);
  585. header.append(content, content_length);
  586. state = SEND_DONE;
  587. goto return_header;
  588. }
  589. } else {
  590. state = SEND_DONE;
  591. goto return_header;
  592. }
  593. return_nobody:
  594. pResp->content_length = 0;
  595. return_header:
  596. if (header.empty()) header = pResp->Dump(true, false);
  597. *data = (char*)header.c_str();
  598. *len = header.size();
  599. return *len;
  600. }
  601. case SEND_BODY:
  602. {
  603. *data = (char*)pResp->Content();
  604. *len = pResp->ContentLength();
  605. state = SEND_DONE;
  606. return *len;
  607. }
  608. case SEND_DONE:
  609. {
  610. // NOTE: remove file cache if > FILE_CACHE_MAX_SIZE
  611. if (fc && fc->filebuf.len > FILE_CACHE_MAX_SIZE) {
  612. files->Close(fc);
  613. }
  614. fc = NULL;
  615. header.clear();
  616. return 0;
  617. }
  618. default:
  619. return 0;
  620. }
  621. } else if (protocol == HTTP_V2) {
  622. return parser->GetSendData(data, len);
  623. }
  624. return 0;
  625. }
  626. int HttpHandler::openFile(const char* filepath) {
  627. closeFile();
  628. file = new LargeFile;
  629. file->timer = INVALID_TIMER_ID;
  630. return file->open(filepath, "rb");
  631. }
  632. bool HttpHandler::isFileOpened() {
  633. return file && file->isopen();
  634. }
  635. int HttpHandler::sendFile() {
  636. if (!writer || !writer->isWriteComplete() ||
  637. !isFileOpened() ||
  638. file->buf.len == 0 ||
  639. resp->content_length == 0) {
  640. return -1;
  641. }
  642. int readbytes = MIN(file->buf.len, resp->content_length);
  643. size_t nread = file->read(file->buf.base, readbytes);
  644. if (nread <= 0) {
  645. hloge("read file error!");
  646. writer->close(true);
  647. return nread;
  648. }
  649. int nwrite = writer->WriteBody(file->buf.base, nread);
  650. if (nwrite < 0) {
  651. // disconnectd
  652. writer->close(true);
  653. return nwrite;
  654. }
  655. resp->content_length -= nread;
  656. if (resp->content_length == 0) {
  657. writer->End();
  658. closeFile();
  659. }
  660. return nread;
  661. }
  662. void HttpHandler::closeFile() {
  663. if (file) {
  664. if (file->timer != INVALID_TIMER_ID) {
  665. killTimer(file->timer);
  666. file->timer = INVALID_TIMER_ID;
  667. }
  668. delete file;
  669. file = NULL;
  670. }
  671. }