HttpHandler.cpp 18 KB

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