HttpHandler.cpp 18 KB

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