1
0

HttpHandler.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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->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->status_code = HTTP_STATUS_PARTIAL_CONTENT;
  257. resp->content_length = to - from + 1;
  258. resp->SetContentTypeByFilename(filepath.c_str());
  259. resp->SetRange(from, to, total);
  260. if(resp->content_length < service->max_file_cache_size) {
  261. // read into body directly
  262. int nread = file->readrange(resp->body, from, to);
  263. closeFile();
  264. if (nread != resp->content_length) {
  265. resp->content_length = 0;
  266. resp->body.clear();
  267. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  268. }
  269. }
  270. else {
  271. if (service->largeFileHandler) {
  272. status_code = customHttpHandler(service->largeFileHandler);
  273. } else {
  274. status_code = defaultLargeFileHandler();
  275. }
  276. }
  277. return status_code;
  278. }
  279. // FileCache
  280. FileCache::OpenParam param;
  281. param.max_read = service->max_file_cache_size;
  282. param.need_read = !(req->method == HTTP_HEAD || has_range);
  283. param.path = req_path;
  284. fc = files->Open(filepath.c_str(), &param);
  285. if (fc == NULL) {
  286. if (param.error == ERR_OVER_LIMIT) {
  287. if (service->largeFileHandler) {
  288. status_code = customHttpHandler(service->largeFileHandler);
  289. } else {
  290. status_code = defaultLargeFileHandler();
  291. }
  292. } else {
  293. status_code = HTTP_STATUS_NOT_FOUND;
  294. }
  295. }
  296. else {
  297. // Not Modified
  298. auto iter = req->headers.find("if-not-match");
  299. if (iter != req->headers.end() &&
  300. strcmp(iter->second.c_str(), fc->etag) == 0) {
  301. fc = NULL;
  302. return HTTP_STATUS_NOT_MODIFIED;
  303. }
  304. iter = req->headers.find("if-modified-since");
  305. if (iter != req->headers.end() &&
  306. strcmp(iter->second.c_str(), fc->last_modified) == 0) {
  307. fc = NULL;
  308. return HTTP_STATUS_NOT_MODIFIED;
  309. }
  310. }
  311. return status_code;
  312. }
  313. int HttpHandler::defaultLargeFileHandler() {
  314. if (!writer) return HTTP_STATUS_NOT_IMPLEMENTED;
  315. if (!isFileOpened()) {
  316. std::string filepath = service->document_root + req->Path();
  317. if (openFile(filepath.c_str()) != 0) {
  318. return HTTP_STATUS_NOT_FOUND;
  319. }
  320. resp->content_length = file->size();
  321. resp->SetContentTypeByFilename(filepath.c_str());
  322. }
  323. if (service->limit_rate == 0) {
  324. // forbidden to send large file
  325. resp->content_length = 0;
  326. resp->status_code = HTTP_STATUS_FORBIDDEN;
  327. } else {
  328. size_t bufsize = 40960; // 40K
  329. file->buf.resize(bufsize);
  330. if (service->limit_rate < 0) {
  331. // unlimited: sendFile when writable
  332. writer->onwrite = [this](HBuf* buf) {
  333. if (writer->isWriteComplete()) {
  334. sendFile();
  335. }
  336. };
  337. } else {
  338. // limit_rate=40KB/s interval_ms=1000
  339. // limit_rate=500KB/s interval_ms=80
  340. int interval_ms = file->buf.len * 1000 / 1024 / service->limit_rate;
  341. // limit_rate=40MB/s interval_m=1: 40KB/ms = 40MB/s = 320Mbps
  342. if (interval_ms == 0) interval_ms = 1;
  343. // printf("limit_rate=%dKB/s interval_ms=%d\n", service->limit_rate, interval_ms);
  344. file->timer = setInterval(interval_ms, std::bind(&HttpHandler::sendFile, this));
  345. }
  346. }
  347. writer->EndHeaders();
  348. return HTTP_STATUS_UNFINISHED;
  349. }
  350. int HttpHandler::defaultErrorHandler() {
  351. // error page
  352. if (service->error_page.size() != 0) {
  353. std::string filepath = service->document_root + '/' + service->error_page;
  354. // cache and load error page
  355. FileCache::OpenParam param;
  356. fc = files->Open(filepath.c_str(), &param);
  357. }
  358. // status page
  359. if (fc == NULL && resp->body.size() == 0) {
  360. resp->content_type = TEXT_HTML;
  361. make_http_status_page(resp->status_code, resp->body);
  362. }
  363. return 0;
  364. }
  365. int HttpHandler::FeedRecvData(const char* data, size_t len) {
  366. int nfeed = 0;
  367. if (protocol == HttpHandler::WEBSOCKET) {
  368. nfeed = ws_parser->FeedRecvData(data, len);
  369. if (nfeed != len) {
  370. hloge("[%s:%d] websocket parse error!", ip, port);
  371. }
  372. } else {
  373. if (state != WANT_RECV) {
  374. Reset();
  375. }
  376. nfeed = parser->FeedRecvData(data, len);
  377. if (nfeed != len) {
  378. hloge("[%s:%d] http parse error: %s", ip, port, parser->StrError(parser->GetError()));
  379. }
  380. }
  381. return nfeed;
  382. }
  383. int HttpHandler::GetSendData(char** data, size_t* len) {
  384. if (state == HANDLE_CONTINUE) {
  385. return 0;
  386. }
  387. HttpRequest* pReq = req.get();
  388. HttpResponse* pResp = resp.get();
  389. if (protocol == HTTP_V1) {
  390. switch(state) {
  391. case WANT_RECV:
  392. if (parser->IsComplete()) state = WANT_SEND;
  393. else return 0;
  394. case HANDLE_END:
  395. state = WANT_SEND;
  396. case WANT_SEND:
  397. state = SEND_HEADER;
  398. case SEND_HEADER:
  399. {
  400. size_t content_length = 0;
  401. const char* content = NULL;
  402. // HEAD
  403. if (pReq->method == HTTP_HEAD) {
  404. if (fc) {
  405. pResp->headers["Accept-Ranges"] = "bytes";
  406. pResp->headers["Content-Length"] = hv::to_string(fc->st.st_size);
  407. } else {
  408. pResp->headers["Content-Type"] = "text/html";
  409. pResp->headers["Content-Length"] = "0";
  410. }
  411. state = SEND_DONE;
  412. goto return_nobody;
  413. }
  414. // File service
  415. if (fc) {
  416. // FileCache
  417. // NOTE: no copy filebuf, more efficient
  418. header = pResp->Dump(true, false);
  419. fc->prepend_header(header.c_str(), header.size());
  420. *data = fc->httpbuf.base;
  421. *len = fc->httpbuf.len;
  422. state = SEND_DONE;
  423. return *len;
  424. }
  425. // API service
  426. content_length = pResp->ContentLength();
  427. content = (const char*)pResp->Content();
  428. if (content) {
  429. if (content_length > (1 << 20)) {
  430. state = SEND_BODY;
  431. goto return_header;
  432. } else {
  433. // NOTE: header+body in one package if <= 1M
  434. header = pResp->Dump(true, false);
  435. header.append(content, content_length);
  436. state = SEND_DONE;
  437. goto return_header;
  438. }
  439. } else {
  440. state = SEND_DONE;
  441. goto return_header;
  442. }
  443. return_nobody:
  444. pResp->content_length = 0;
  445. return_header:
  446. if (header.empty()) header = pResp->Dump(true, false);
  447. *data = (char*)header.c_str();
  448. *len = header.size();
  449. return *len;
  450. }
  451. case SEND_BODY:
  452. {
  453. *data = (char*)pResp->Content();
  454. *len = pResp->ContentLength();
  455. state = SEND_DONE;
  456. return *len;
  457. }
  458. case SEND_DONE:
  459. {
  460. // NOTE: remove file cache if > FILE_CACHE_MAX_SIZE
  461. if (fc && fc->filebuf.len > FILE_CACHE_MAX_SIZE) {
  462. files->Close(fc);
  463. }
  464. fc = NULL;
  465. header.clear();
  466. return 0;
  467. }
  468. default:
  469. return 0;
  470. }
  471. } else if (protocol == HTTP_V2) {
  472. return parser->GetSendData(data, len);
  473. }
  474. return 0;
  475. }
  476. int HttpHandler::openFile(const char* filepath) {
  477. closeFile();
  478. file = new LargeFile;
  479. file->timer = INVALID_TIMER_ID;
  480. return file->open(filepath, "rb");
  481. }
  482. bool HttpHandler::isFileOpened() {
  483. return file && file->isopen();
  484. }
  485. int HttpHandler::sendFile() {
  486. if (!writer || !writer->isWriteComplete() ||
  487. !isFileOpened() ||
  488. file->buf.len == 0 ||
  489. resp->content_length == 0) {
  490. return -1;
  491. }
  492. int readbytes = MIN(file->buf.len, resp->content_length);
  493. size_t nread = file->read(file->buf.base, readbytes);
  494. if (nread <= 0) {
  495. hloge("read file error!");
  496. writer->close(true);
  497. return nread;
  498. }
  499. int nwrite = writer->WriteBody(file->buf.base, nread);
  500. if (nwrite < 0) {
  501. // disconnectd
  502. writer->close(true);
  503. return nwrite;
  504. }
  505. resp->content_length -= nread;
  506. if (resp->content_length == 0) {
  507. writer->End();
  508. closeFile();
  509. }
  510. return nread;
  511. }
  512. void HttpHandler::closeFile() {
  513. if (file) {
  514. if (file->timer != INVALID_TIMER_ID) {
  515. killTimer(file->timer);
  516. file->timer = INVALID_TIMER_ID;
  517. }
  518. delete file;
  519. file = NULL;
  520. }
  521. }