1
0

HttpHandler.cpp 17 KB

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