HttpHandler.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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->allow_cors) {
  307. resp->headers["Access-Control-Allow-Origin"] = req->GetHeader("Origin", "*");
  308. if (req->method == HTTP_OPTIONS) {
  309. resp->headers["Access-Control-Allow-Methods"] = req->GetHeader("Access-Control-Request-Method", "OPTIONS, HEAD, GET, POST, PUT, DELETE, PATCH");
  310. resp->headers["Access-Control-Allow-Headers"] = req->GetHeader("Access-Control-Request-Headers", "Content-Type");
  311. status_code = HTTP_STATUS_NO_CONTENT;
  312. goto postprocessor;
  313. }
  314. }
  315. if (service->preprocessor) {
  316. status_code = customHttpHandler(service->preprocessor);
  317. if (status_code != 0) {
  318. goto postprocessor;
  319. }
  320. }
  321. processor:
  322. if (service->processor) {
  323. status_code = customHttpHandler(service->processor);
  324. } else {
  325. status_code = defaultRequestHandler();
  326. }
  327. postprocessor:
  328. if (status_code >= 100 && status_code < 600) {
  329. pResp->status_code = (http_status)status_code;
  330. }
  331. if (pResp->status_code >= 400 && pResp->body.size() == 0 && pReq->method != HTTP_HEAD) {
  332. if (service->errorHandler) {
  333. customHttpHandler(service->errorHandler);
  334. } else {
  335. defaultErrorHandler();
  336. }
  337. }
  338. if (fc) {
  339. pResp->content = fc->filebuf.base;
  340. pResp->content_length = fc->filebuf.len;
  341. pResp->headers["Content-Type"] = fc->content_type;
  342. pResp->headers["Last-Modified"] = fc->last_modified;
  343. pResp->headers["Etag"] = fc->etag;
  344. }
  345. if (service->postprocessor) {
  346. customHttpHandler(service->postprocessor);
  347. }
  348. if (writer && writer->state != hv::HttpResponseWriter::SEND_BEGIN) {
  349. status_code = 0;
  350. }
  351. if (status_code == 0) {
  352. state = HANDLE_CONTINUE;
  353. } else {
  354. state = HANDLE_END;
  355. parser->SubmitResponse(resp.get());
  356. }
  357. return status_code;
  358. }
  359. int HttpHandler::defaultRequestHandler() {
  360. int status_code = HTTP_STATUS_OK;
  361. if (api_handler) {
  362. status_code = invokeHttpHandler(api_handler);
  363. }
  364. else if (req->method == HTTP_GET || req->method == HTTP_HEAD) {
  365. // static handler
  366. if (service->staticHandler) {
  367. status_code = customHttpHandler(service->staticHandler);
  368. }
  369. else if (service->staticDirs.size() > 0) {
  370. status_code = defaultStaticHandler();
  371. }
  372. else {
  373. status_code = HTTP_STATUS_NOT_FOUND;
  374. }
  375. }
  376. else {
  377. // Not Implemented
  378. status_code = HTTP_STATUS_NOT_IMPLEMENTED;
  379. }
  380. return status_code;
  381. }
  382. int HttpHandler::defaultStaticHandler() {
  383. // file service
  384. std::string path = req->Path();
  385. const char* req_path = path.c_str();
  386. // path safe check
  387. if (req_path[0] != '/' || strstr(req_path, "/../")) {
  388. return HTTP_STATUS_BAD_REQUEST;
  389. }
  390. std::string filepath;
  391. bool is_dir = path.back() == '/' &&
  392. service->index_of.size() > 0 &&
  393. hv_strstartswith(req_path, service->index_of.c_str());
  394. if (is_dir) {
  395. filepath = service->document_root + path;
  396. } else {
  397. filepath = service->GetStaticFilepath(req_path);
  398. }
  399. if (filepath.empty()) {
  400. return HTTP_STATUS_NOT_FOUND;
  401. }
  402. int status_code = HTTP_STATUS_OK;
  403. // Range:
  404. bool has_range = false;
  405. long from, to = 0;
  406. if (req->GetRange(from, to)) {
  407. has_range = true;
  408. if (openFile(filepath.c_str()) != 0) {
  409. return HTTP_STATUS_NOT_FOUND;
  410. }
  411. long total = file->size();
  412. if (to == 0 || to >= total) to = total - 1;
  413. file->seek(from);
  414. status_code = HTTP_STATUS_PARTIAL_CONTENT;
  415. resp->status_code = HTTP_STATUS_PARTIAL_CONTENT;
  416. resp->content_length = to - from + 1;
  417. resp->SetContentTypeByFilename(filepath.c_str());
  418. resp->SetRange(from, to, total);
  419. if(resp->content_length < service->max_file_cache_size) {
  420. // read into body directly
  421. int nread = file->readrange(resp->body, from, to);
  422. closeFile();
  423. if (nread != resp->content_length) {
  424. resp->content_length = 0;
  425. resp->body.clear();
  426. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  427. }
  428. }
  429. else {
  430. if (service->largeFileHandler) {
  431. status_code = customHttpHandler(service->largeFileHandler);
  432. } else {
  433. status_code = defaultLargeFileHandler();
  434. }
  435. }
  436. return status_code;
  437. }
  438. // FileCache
  439. FileCache::OpenParam param;
  440. param.max_read = service->max_file_cache_size;
  441. param.need_read = !(req->method == HTTP_HEAD || has_range);
  442. param.path = req_path;
  443. fc = files->Open(filepath.c_str(), &param);
  444. if (fc == NULL) {
  445. if (param.error == ERR_OVER_LIMIT) {
  446. if (service->largeFileHandler) {
  447. status_code = customHttpHandler(service->largeFileHandler);
  448. } else {
  449. status_code = defaultLargeFileHandler();
  450. }
  451. } else {
  452. status_code = HTTP_STATUS_NOT_FOUND;
  453. }
  454. }
  455. else {
  456. // Not Modified
  457. auto iter = req->headers.find("if-not-match");
  458. if (iter != req->headers.end() &&
  459. strcmp(iter->second.c_str(), fc->etag) == 0) {
  460. fc = NULL;
  461. return HTTP_STATUS_NOT_MODIFIED;
  462. }
  463. iter = req->headers.find("if-modified-since");
  464. if (iter != req->headers.end() &&
  465. strcmp(iter->second.c_str(), fc->last_modified) == 0) {
  466. fc = NULL;
  467. return HTTP_STATUS_NOT_MODIFIED;
  468. }
  469. }
  470. return status_code;
  471. }
  472. int HttpHandler::defaultLargeFileHandler() {
  473. if (!writer) return HTTP_STATUS_NOT_IMPLEMENTED;
  474. if (!isFileOpened()) {
  475. std::string filepath = service->GetStaticFilepath(req->Path().c_str());
  476. if (filepath.empty() || openFile(filepath.c_str()) != 0) {
  477. return HTTP_STATUS_NOT_FOUND;
  478. }
  479. resp->content_length = file->size();
  480. resp->SetContentTypeByFilename(filepath.c_str());
  481. }
  482. if (service->limit_rate == 0) {
  483. // forbidden to send large file
  484. resp->content_length = 0;
  485. resp->status_code = HTTP_STATUS_FORBIDDEN;
  486. } else {
  487. size_t bufsize = 40960; // 40K
  488. file->buf.resize(bufsize);
  489. if (service->limit_rate < 0) {
  490. // unlimited: sendFile when writable
  491. writer->onwrite = [this](HBuf* buf) {
  492. if (writer->isWriteComplete()) {
  493. sendFile();
  494. }
  495. };
  496. } else {
  497. // limit_rate=40KB/s interval_ms=1000
  498. // limit_rate=500KB/s interval_ms=80
  499. int interval_ms = file->buf.len * 1000 / 1024 / service->limit_rate;
  500. // limit_rate=40MB/s interval_m=1: 40KB/ms = 40MB/s = 320Mbps
  501. if (interval_ms == 0) interval_ms = 1;
  502. // printf("limit_rate=%dKB/s interval_ms=%d\n", service->limit_rate, interval_ms);
  503. file->timer = setInterval(interval_ms, std::bind(&HttpHandler::sendFile, this));
  504. }
  505. }
  506. writer->EndHeaders();
  507. return HTTP_STATUS_UNFINISHED;
  508. }
  509. int HttpHandler::defaultErrorHandler() {
  510. // error page
  511. if (service->error_page.size() != 0) {
  512. std::string filepath = service->document_root + '/' + service->error_page;
  513. // cache and load error page
  514. FileCache::OpenParam param;
  515. fc = files->Open(filepath.c_str(), &param);
  516. }
  517. // status page
  518. if (fc == NULL && resp->body.size() == 0) {
  519. resp->content_type = TEXT_HTML;
  520. make_http_status_page(resp->status_code, resp->body);
  521. }
  522. return 0;
  523. }
  524. int HttpHandler::FeedRecvData(const char* data, size_t len) {
  525. int nfeed = 0;
  526. if (protocol == HttpHandler::WEBSOCKET) {
  527. nfeed = ws_parser->FeedRecvData(data, len);
  528. if (nfeed != len) {
  529. hloge("[%s:%d] websocket parse error!", ip, port);
  530. }
  531. } else {
  532. if (state != WANT_RECV) {
  533. Reset();
  534. }
  535. nfeed = parser->FeedRecvData(data, len);
  536. if (nfeed != len) {
  537. hloge("[%s:%d] http parse error: %s", ip, port, parser->StrError(parser->GetError()));
  538. }
  539. }
  540. return nfeed;
  541. }
  542. int HttpHandler::GetSendData(char** data, size_t* len) {
  543. if (state == HANDLE_CONTINUE) {
  544. return 0;
  545. }
  546. HttpRequest* pReq = req.get();
  547. HttpResponse* pResp = resp.get();
  548. if (protocol == HTTP_V1) {
  549. switch(state) {
  550. case WANT_RECV:
  551. if (parser->IsComplete()) state = WANT_SEND;
  552. else return 0;
  553. case HANDLE_END:
  554. state = WANT_SEND;
  555. case WANT_SEND:
  556. state = SEND_HEADER;
  557. case SEND_HEADER:
  558. {
  559. size_t content_length = 0;
  560. const char* content = NULL;
  561. // HEAD
  562. if (pReq->method == HTTP_HEAD) {
  563. if (fc) {
  564. pResp->headers["Accept-Ranges"] = "bytes";
  565. pResp->headers["Content-Length"] = hv::to_string(fc->st.st_size);
  566. } else {
  567. pResp->headers["Content-Type"] = "text/html";
  568. pResp->headers["Content-Length"] = "0";
  569. }
  570. state = SEND_DONE;
  571. goto return_nobody;
  572. }
  573. // File service
  574. if (fc) {
  575. // FileCache
  576. // NOTE: no copy filebuf, more efficient
  577. header = pResp->Dump(true, false);
  578. fc->prepend_header(header.c_str(), header.size());
  579. *data = fc->httpbuf.base;
  580. *len = fc->httpbuf.len;
  581. state = SEND_DONE;
  582. return *len;
  583. }
  584. // API service
  585. content_length = pResp->ContentLength();
  586. content = (const char*)pResp->Content();
  587. if (content) {
  588. if (content_length > (1 << 20)) {
  589. state = SEND_BODY;
  590. goto return_header;
  591. } else {
  592. // NOTE: header+body in one package if <= 1M
  593. header = pResp->Dump(true, false);
  594. header.append(content, content_length);
  595. state = SEND_DONE;
  596. goto return_header;
  597. }
  598. } else {
  599. state = SEND_DONE;
  600. goto return_header;
  601. }
  602. return_nobody:
  603. pResp->content_length = 0;
  604. return_header:
  605. if (header.empty()) header = pResp->Dump(true, false);
  606. *data = (char*)header.c_str();
  607. *len = header.size();
  608. return *len;
  609. }
  610. case SEND_BODY:
  611. {
  612. *data = (char*)pResp->Content();
  613. *len = pResp->ContentLength();
  614. state = SEND_DONE;
  615. return *len;
  616. }
  617. case SEND_DONE:
  618. {
  619. // NOTE: remove file cache if > FILE_CACHE_MAX_SIZE
  620. if (fc && fc->filebuf.len > FILE_CACHE_MAX_SIZE) {
  621. files->Close(fc);
  622. }
  623. fc = NULL;
  624. header.clear();
  625. return 0;
  626. }
  627. default:
  628. return 0;
  629. }
  630. } else if (protocol == HTTP_V2) {
  631. return parser->GetSendData(data, len);
  632. }
  633. return 0;
  634. }
  635. int HttpHandler::openFile(const char* filepath) {
  636. closeFile();
  637. file = new LargeFile;
  638. file->timer = INVALID_TIMER_ID;
  639. return file->open(filepath, "rb");
  640. }
  641. bool HttpHandler::isFileOpened() {
  642. return file && file->isopen();
  643. }
  644. int HttpHandler::sendFile() {
  645. if (!writer || !writer->isWriteComplete() ||
  646. !isFileOpened() ||
  647. file->buf.len == 0 ||
  648. resp->content_length == 0) {
  649. return -1;
  650. }
  651. int readbytes = MIN(file->buf.len, resp->content_length);
  652. size_t nread = file->read(file->buf.base, readbytes);
  653. if (nread <= 0) {
  654. hloge("read file error!");
  655. writer->close(true);
  656. return nread;
  657. }
  658. int nwrite = writer->WriteBody(file->buf.base, nread);
  659. if (nwrite < 0) {
  660. // disconnectd
  661. writer->close(true);
  662. return nwrite;
  663. }
  664. resp->content_length -= nread;
  665. if (resp->content_length == 0) {
  666. writer->End();
  667. closeFile();
  668. }
  669. return nread;
  670. }
  671. void HttpHandler::closeFile() {
  672. if (file) {
  673. if (file->timer != INVALID_TIMER_ID) {
  674. killTimer(file->timer);
  675. file->timer = INVALID_TIMER_ID;
  676. }
  677. delete file;
  678. file = NULL;
  679. }
  680. }