HttpHandler.cpp 17 KB

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