HttpHandler.cpp 17 KB

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