HttpHandler.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  1. #include "HttpHandler.h"
  2. #include "hversion.h"
  3. #include "herr.h"
  4. #include "hlog.h"
  5. #include "htime.h"
  6. #include "hurl.h"
  7. #include "hasync.h" // import hv::async for http_async_handler
  8. #include "httpdef.h"
  9. #include "http2def.h"
  10. #include "wsdef.h"
  11. #include "http_page.h"
  12. #include "EventLoop.h" // import hv::setInterval
  13. using namespace hv;
  14. #define MIN_HTTP_REQUEST "GET / HTTP/1.1\r\n\r\n"
  15. #define MIN_HTTP_REQUEST_LEN 14 // exclude CRLF
  16. #define HTTP_100_CONTINUE_RESPONSE "HTTP/1.1 100 Continue\r\n\r\n"
  17. #define HTTP_100_CONTINUE_RESPONSE_LEN 25
  18. #define HTTP_200_CONNECT_RESPONSE "HTTP/1.1 200 Connection established\r\n\r\n"
  19. #define HTTP_200_CONNECT_RESPONSE_LEN 39
  20. HttpHandler::HttpHandler(hio_t* io) :
  21. protocol(HttpHandler::UNKNOWN),
  22. state(WANT_RECV),
  23. error(0),
  24. // flags
  25. ssl(0),
  26. keepalive(1),
  27. upgrade(0),
  28. proxy(0),
  29. proxy_connected(0),
  30. forward_proxy(0),
  31. reverse_proxy(0),
  32. ip{'\0'},
  33. port(0),
  34. pid(0),
  35. tid(0),
  36. // for http
  37. io(io),
  38. service(NULL),
  39. api_handler(NULL),
  40. // for websocket
  41. ws_service(NULL),
  42. last_send_ping_time(0),
  43. last_recv_pong_time(0),
  44. // for sendfile
  45. files(NULL),
  46. file(NULL),
  47. // for proxy
  48. proxy_port(0)
  49. {
  50. // Init();
  51. }
  52. HttpHandler::~HttpHandler() {
  53. Close();
  54. }
  55. bool HttpHandler::Init(int http_version) {
  56. parser.reset(HttpParser::New(HTTP_SERVER, (enum http_version)http_version));
  57. if (parser == NULL) {
  58. return false;
  59. }
  60. req = std::make_shared<HttpRequest>();
  61. resp = std::make_shared<HttpResponse>();
  62. if(http_version == 1) {
  63. protocol = HTTP_V1;
  64. } else if (http_version == 2) {
  65. protocol = HTTP_V2;
  66. resp->http_major = req->http_major = 2;
  67. resp->http_minor = req->http_minor = 0;
  68. }
  69. if (io) {
  70. hloop_t* loop = hevent_loop(io);
  71. pid = hloop_pid(loop);
  72. tid = hloop_tid(loop);
  73. writer = std::make_shared<HttpResponseWriter>(io, resp);
  74. writer->status = hv::SocketChannel::CONNECTED;
  75. } else {
  76. pid = hv_getpid();
  77. tid = hv_gettid();
  78. }
  79. parser->InitRequest(req.get());
  80. // NOTE: hook http_cb
  81. req->http_cb = [this](HttpMessage* msg, http_parser_state state, const char* data, size_t size) {
  82. if (this->state == WANT_CLOSE) return;
  83. switch (state) {
  84. case HP_HEADERS_COMPLETE:
  85. if (this->error != 0) return;
  86. onHeadersComplete();
  87. break;
  88. case HP_BODY:
  89. if (this->error != 0) return;
  90. onBody(data, size);
  91. break;
  92. case HP_MESSAGE_COMPLETE:
  93. onMessageComplete();
  94. break;
  95. default:
  96. break;
  97. }
  98. };
  99. return true;
  100. }
  101. void HttpHandler::Reset() {
  102. state = WANT_RECV;
  103. error = 0;
  104. req->Reset();
  105. resp->Reset();
  106. ctx = NULL;
  107. api_handler = NULL;
  108. closeFile();
  109. if (writer) {
  110. writer->Begin();
  111. writer->onwrite = NULL;
  112. writer->onclose = NULL;
  113. }
  114. parser->InitRequest(req.get());
  115. }
  116. void HttpHandler::Close() {
  117. if (writer) {
  118. writer->status = hv::SocketChannel::DISCONNECTED;
  119. }
  120. if (api_handler && api_handler->state_handler) {
  121. if (parser && !parser->IsComplete()) {
  122. api_handler->state_handler(context(), HP_ERROR, NULL, 0);
  123. }
  124. return;
  125. }
  126. // close proxy
  127. closeProxy();
  128. // close file
  129. closeFile();
  130. // onclose
  131. if (protocol == HttpHandler::WEBSOCKET) {
  132. WebSocketOnClose();
  133. } else {
  134. if (writer && writer->onclose) {
  135. writer->onclose();
  136. }
  137. }
  138. }
  139. bool HttpHandler::SwitchHTTP2() {
  140. parser.reset(HttpParser::New(HTTP_SERVER, ::HTTP_V2));
  141. if (parser == NULL) {
  142. return false;
  143. }
  144. protocol = HTTP_V2;
  145. resp->http_major = req->http_major = 2;
  146. resp->http_minor = req->http_minor = 0;
  147. parser->InitRequest(req.get());
  148. return true;
  149. }
  150. bool HttpHandler::SwitchWebSocket() {
  151. if(!io) return false;
  152. protocol = WEBSOCKET;
  153. ws_parser = std::make_shared<WebSocketParser>();
  154. ws_channel = std::make_shared<WebSocketChannel>(io, WS_SERVER);
  155. ws_parser->onMessage = [this](int opcode, const std::string& msg){
  156. ws_channel->opcode = (enum ws_opcode)opcode;
  157. switch(opcode) {
  158. case WS_OPCODE_CLOSE:
  159. ws_channel->send(msg, WS_OPCODE_CLOSE);
  160. ws_channel->close();
  161. break;
  162. case WS_OPCODE_PING:
  163. // printf("recv ping\n");
  164. // printf("send pong\n");
  165. ws_channel->send(msg, WS_OPCODE_PONG);
  166. break;
  167. case WS_OPCODE_PONG:
  168. // printf("recv pong\n");
  169. this->last_recv_pong_time = gethrtime_us();
  170. break;
  171. case WS_OPCODE_TEXT:
  172. case WS_OPCODE_BINARY:
  173. // onmessage
  174. if (ws_service && ws_service->onmessage) {
  175. ws_service->onmessage(ws_channel, msg);
  176. }
  177. break;
  178. default:
  179. break;
  180. }
  181. };
  182. // NOTE: cancel keepalive timer, judge alive by heartbeat.
  183. ws_channel->setKeepaliveTimeout(0);
  184. if (ws_service && ws_service->ping_interval > 0) {
  185. int ping_interval = MAX(ws_service->ping_interval, 1000);
  186. ws_channel->setHeartbeat(ping_interval, [this](){
  187. if (last_recv_pong_time < last_send_ping_time) {
  188. hlogw("[%s:%d] websocket no pong!", ip, port);
  189. ws_channel->close();
  190. } else {
  191. // printf("send ping\n");
  192. ws_channel->sendPing();
  193. last_send_ping_time = gethrtime_us();
  194. }
  195. });
  196. }
  197. return true;
  198. }
  199. const HttpContextPtr& HttpHandler::context() {
  200. if (!ctx) {
  201. ctx = std::make_shared<hv::HttpContext>();
  202. ctx->service = service;
  203. ctx->request = req;
  204. ctx->response = resp;
  205. ctx->writer = writer;
  206. }
  207. return ctx;
  208. }
  209. int HttpHandler::customHttpHandler(const http_handler& handler) {
  210. return invokeHttpHandler(&handler);
  211. }
  212. int HttpHandler::invokeHttpHandler(const http_handler* handler) {
  213. int status_code = HTTP_STATUS_NOT_IMPLEMENTED;
  214. if (handler->sync_handler) {
  215. // NOTE: sync_handler run on IO thread
  216. status_code = handler->sync_handler(req.get(), resp.get());
  217. } else if (handler->async_handler) {
  218. // NOTE: async_handler run on hv::async threadpool
  219. hv::async(std::bind(handler->async_handler, req, writer));
  220. status_code = HTTP_STATUS_NEXT;
  221. } else if (handler->ctx_handler) {
  222. // NOTE: ctx_handler run on IO thread, you can easily post HttpContextPtr to your consumer thread for processing.
  223. status_code = handler->ctx_handler(context());
  224. } else if (handler->state_handler) {
  225. status_code = handler->state_handler(context(), HP_MESSAGE_COMPLETE, NULL, 0);
  226. }
  227. return status_code;
  228. }
  229. void HttpHandler::onHeadersComplete() {
  230. // printf("onHeadersComplete\n");
  231. int status_code = handleRequestHeaders();
  232. if (status_code != HTTP_STATUS_OK) {
  233. error = ERR_REQUEST;
  234. return;
  235. }
  236. HttpRequest* pReq = req.get();
  237. if (service && service->pathHandlers.size() != 0) {
  238. service->GetRoute(pReq, &api_handler);
  239. }
  240. if (api_handler && api_handler->state_handler) {
  241. api_handler->state_handler(context(), HP_HEADERS_COMPLETE, NULL, 0);
  242. return;
  243. }
  244. if (proxy) {
  245. handleProxy();
  246. return;
  247. }
  248. // Expect: 100-continue
  249. handleExpect100();
  250. }
  251. void HttpHandler::onBody(const char* data, size_t size) {
  252. if (api_handler && api_handler->state_handler) {
  253. api_handler->state_handler(context(), HP_BODY, data, size);
  254. return;
  255. }
  256. if (proxy && proxy_connected) {
  257. if (io) hio_write_upstream(io, (void*)data, size);
  258. return;
  259. }
  260. req->body.append(data, size);
  261. return;
  262. }
  263. void HttpHandler::onMessageComplete() {
  264. // printf("onMessageComplete\n");
  265. int status_code = HTTP_STATUS_OK;
  266. if (error) {
  267. SendHttpStatusResponse(resp->status_code);
  268. return;
  269. }
  270. if (proxy) {
  271. if (proxy_connected) Reset();
  272. return;
  273. }
  274. addResponseHeaders();
  275. // upgrade ? handleUpgrade : HandleHttpRequest
  276. if (upgrade) {
  277. auto iter_upgrade = req->headers.find("upgrade");
  278. if (iter_upgrade != req->headers.end()) {
  279. handleUpgrade(iter_upgrade->second.c_str());
  280. status_code = resp->status_code;
  281. }
  282. } else {
  283. status_code = HandleHttpRequest();
  284. if (status_code != HTTP_STATUS_NEXT) {
  285. SendHttpResponse();
  286. }
  287. }
  288. // access log
  289. if (service && service->enable_access_log) {
  290. hlogi("[%ld-%ld][%s:%d][%s %s]=>[%d %s]",
  291. pid, tid, ip, port,
  292. http_method_str(req->method), req->path.c_str(),
  293. resp->status_code, resp->status_message());
  294. }
  295. if (status_code != HTTP_STATUS_NEXT) {
  296. // keepalive ? Reset : Close
  297. if (keepalive) {
  298. Reset();
  299. } else {
  300. state = WANT_CLOSE;
  301. }
  302. }
  303. }
  304. int HttpHandler::handleRequestHeaders() {
  305. HttpRequest* pReq = req.get();
  306. pReq->scheme = ssl ? "https" : "http";
  307. pReq->client_addr.ip = ip;
  308. pReq->client_addr.port = port;
  309. // keepalive
  310. keepalive = pReq->IsKeepAlive();
  311. // upgrade
  312. upgrade = pReq->IsUpgrade();
  313. // proxy
  314. proxy = forward_proxy = reverse_proxy = 0;
  315. if (hv::startswith(pReq->url, "http")) {
  316. // forward proxy
  317. proxy = forward_proxy = 1;
  318. }
  319. else if (pReq->method == HTTP_CONNECT) {
  320. // proxy tunnel
  321. // CONNECT ip:port HTTP/1.1\r\n
  322. pReq->url = "https://" + pReq->url;
  323. proxy = forward_proxy = 1;
  324. keepalive = true;
  325. }
  326. // printf("url=%s\n", pReq->url.c_str());
  327. pReq->ParseUrl();
  328. // printf("path=%s\n", pReq->path.c_str());
  329. // fix CVE-2023-26147
  330. if (pReq->path.find("%") != std::string::npos) {
  331. std::string unescaped_path = HUrl::unescape(pReq->path);
  332. if (unescaped_path.find("\r\n") != std::string::npos) {
  333. hlogw("Illegal path: %s\n", unescaped_path.c_str());
  334. resp->status_code = HTTP_STATUS_BAD_REQUEST;
  335. return resp->status_code;
  336. }
  337. }
  338. if (proxy) {
  339. // Proxy-Connection
  340. auto iter = pReq->headers.find("Proxy-Connection");
  341. if (iter != pReq->headers.end()) {
  342. const char* keepalive_value = iter->second.c_str();
  343. if (stricmp(keepalive_value, "keep-alive") == 0) {
  344. keepalive = true;
  345. }
  346. else if (stricmp(keepalive_value, "close") == 0) {
  347. keepalive = false;
  348. }
  349. else if (stricmp(keepalive_value, "upgrade") == 0) {
  350. keepalive = true;
  351. }
  352. }
  353. }
  354. else {
  355. // reverse proxy
  356. std::string proxy_url = service->GetProxyUrl(pReq->path.c_str());
  357. if (!proxy_url.empty()) {
  358. pReq->url = proxy_url;
  359. proxy = reverse_proxy = 1;
  360. }
  361. }
  362. // TODO: rewrite url
  363. return HTTP_STATUS_OK;
  364. }
  365. void HttpHandler::handleExpect100() {
  366. // Expect: 100-continue
  367. auto iter = req->headers.find("Expect");
  368. if (iter != req->headers.end() &&
  369. stricmp(iter->second.c_str(), "100-continue") == 0) {
  370. if (io) hio_write(io, HTTP_100_CONTINUE_RESPONSE, HTTP_100_CONTINUE_RESPONSE_LEN);
  371. }
  372. }
  373. void HttpHandler::addResponseHeaders() {
  374. HttpResponse* pResp = resp.get();
  375. // Server:
  376. pResp->headers["Server"] = "libhv/" HV_VERSION_STRING;
  377. // Connection:
  378. pResp->headers["Connection"] = keepalive ? "keep-alive" : "close";
  379. }
  380. int HttpHandler::HandleHttpRequest() {
  381. // preprocessor -> middleware -> processor -> postprocessor
  382. HttpRequest* pReq = req.get();
  383. HttpResponse* pResp = resp.get();
  384. // NOTE: Not all users want to parse body, we comment it out.
  385. // pReq->ParseBody();
  386. int status_code = pResp->status_code;
  387. if (status_code != HTTP_STATUS_OK) {
  388. goto postprocessor;
  389. }
  390. preprocessor:
  391. state = HANDLE_BEGIN;
  392. if (service->preprocessor) {
  393. status_code = customHttpHandler(service->preprocessor);
  394. if (status_code != HTTP_STATUS_NEXT) {
  395. goto postprocessor;
  396. }
  397. }
  398. middleware:
  399. for (const auto& middleware : service->middleware) {
  400. status_code = customHttpHandler(middleware);
  401. if (status_code != HTTP_STATUS_NEXT) {
  402. goto postprocessor;
  403. }
  404. }
  405. processor:
  406. if (service->processor) {
  407. status_code = customHttpHandler(service->processor);
  408. } else {
  409. status_code = defaultRequestHandler();
  410. }
  411. postprocessor:
  412. if (status_code >= 100 && status_code < 600) {
  413. pResp->status_code = (http_status)status_code;
  414. if (pResp->status_code >= 400 && pResp->body.size() == 0 && pReq->method != HTTP_HEAD) {
  415. if (service->errorHandler) {
  416. customHttpHandler(service->errorHandler);
  417. } else {
  418. defaultErrorHandler();
  419. }
  420. }
  421. }
  422. if (fc) {
  423. pResp->content = fc->filebuf.base;
  424. pResp->content_length = fc->filebuf.len;
  425. pResp->headers["Content-Type"] = fc->content_type;
  426. pResp->headers["Last-Modified"] = fc->last_modified;
  427. pResp->headers["Etag"] = fc->etag;
  428. }
  429. if (service->postprocessor) {
  430. customHttpHandler(service->postprocessor);
  431. }
  432. if (writer && writer->state != hv::HttpResponseWriter::SEND_BEGIN) {
  433. status_code = HTTP_STATUS_NEXT;
  434. }
  435. if (status_code == HTTP_STATUS_NEXT) {
  436. state = HANDLE_CONTINUE;
  437. } else {
  438. state = HANDLE_END;
  439. }
  440. return status_code;
  441. }
  442. int HttpHandler::defaultRequestHandler() {
  443. int status_code = HTTP_STATUS_OK;
  444. if (api_handler) {
  445. status_code = invokeHttpHandler(api_handler);
  446. }
  447. else if (req->method == HTTP_GET || req->method == HTTP_HEAD) {
  448. // static handler
  449. if (service->staticHandler) {
  450. status_code = customHttpHandler(service->staticHandler);
  451. }
  452. else if (service->staticDirs.size() > 0) {
  453. status_code = defaultStaticHandler();
  454. }
  455. else {
  456. status_code = HTTP_STATUS_NOT_FOUND;
  457. }
  458. }
  459. else {
  460. // Not Implemented
  461. status_code = HTTP_STATUS_NOT_IMPLEMENTED;
  462. }
  463. return status_code;
  464. }
  465. int HttpHandler::defaultStaticHandler() {
  466. // file service
  467. std::string path = req->Path();
  468. const char* req_path = path.c_str();
  469. // path safe check
  470. if (req_path[0] != '/' || strstr(req_path, "/..") || strstr(req_path, "\\..")) {
  471. return HTTP_STATUS_BAD_REQUEST;
  472. }
  473. std::string filepath;
  474. bool is_dir = path.back() == '/' &&
  475. service->index_of.size() > 0 &&
  476. hv_strstartswith(req_path, service->index_of.c_str());
  477. if (is_dir) {
  478. filepath = service->document_root + path;
  479. } else {
  480. filepath = service->GetStaticFilepath(req_path);
  481. }
  482. if (filepath.empty()) {
  483. return HTTP_STATUS_NOT_FOUND;
  484. }
  485. int status_code = HTTP_STATUS_OK;
  486. // Range:
  487. bool has_range = false;
  488. long from, to = 0;
  489. if (req->GetRange(from, to)) {
  490. has_range = true;
  491. if (openFile(filepath.c_str()) != 0) {
  492. return HTTP_STATUS_NOT_FOUND;
  493. }
  494. long total = file->size();
  495. if (to == 0 || to >= total) to = total - 1;
  496. file->seek(from);
  497. status_code = HTTP_STATUS_PARTIAL_CONTENT;
  498. resp->status_code = HTTP_STATUS_PARTIAL_CONTENT;
  499. resp->content_length = to - from + 1;
  500. resp->SetContentTypeByFilename(filepath.c_str());
  501. resp->SetRange(from, to, total);
  502. if(resp->content_length < service->max_file_cache_size) {
  503. // read into body directly
  504. int nread = file->readrange(resp->body, from, to);
  505. closeFile();
  506. if (nread != resp->content_length) {
  507. resp->content_length = 0;
  508. resp->body.clear();
  509. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  510. }
  511. }
  512. else {
  513. if (service->largeFileHandler) {
  514. status_code = customHttpHandler(service->largeFileHandler);
  515. } else {
  516. status_code = defaultLargeFileHandler();
  517. }
  518. }
  519. return status_code;
  520. }
  521. // FileCache
  522. FileCache::OpenParam param;
  523. param.max_read = service->max_file_cache_size;
  524. param.need_read = !(req->method == HTTP_HEAD || has_range);
  525. param.path = req_path;
  526. if (files) {
  527. fc = files->Open(filepath.c_str(), &param);
  528. }
  529. if (fc == NULL) {
  530. if (param.error == ERR_OVER_LIMIT) {
  531. if (service->largeFileHandler) {
  532. status_code = customHttpHandler(service->largeFileHandler);
  533. } else {
  534. status_code = defaultLargeFileHandler();
  535. }
  536. } else {
  537. status_code = HTTP_STATUS_NOT_FOUND;
  538. }
  539. }
  540. else {
  541. // Not Modified
  542. auto iter = req->headers.find("if-none-match");
  543. if (iter != req->headers.end() &&
  544. strcmp(iter->second.c_str(), fc->etag) == 0) {
  545. fc = NULL;
  546. return HTTP_STATUS_NOT_MODIFIED;
  547. }
  548. iter = req->headers.find("if-modified-since");
  549. if (iter != req->headers.end() &&
  550. strcmp(iter->second.c_str(), fc->last_modified) == 0) {
  551. fc = NULL;
  552. return HTTP_STATUS_NOT_MODIFIED;
  553. }
  554. }
  555. return status_code;
  556. }
  557. int HttpHandler::defaultLargeFileHandler() {
  558. if (!writer) return HTTP_STATUS_NOT_IMPLEMENTED;
  559. if (!isFileOpened()) {
  560. std::string filepath = service->GetStaticFilepath(req->Path().c_str());
  561. if (filepath.empty() || openFile(filepath.c_str()) != 0) {
  562. return HTTP_STATUS_NOT_FOUND;
  563. }
  564. resp->content_length = file->size();
  565. resp->SetContentTypeByFilename(filepath.c_str());
  566. }
  567. if (service->limit_rate == 0) {
  568. // forbidden to send large file
  569. resp->content_length = 0;
  570. resp->status_code = HTTP_STATUS_FORBIDDEN;
  571. } else {
  572. size_t bufsize = 40960; // 40K
  573. file->buf.resize(bufsize);
  574. if (service->limit_rate < 0) {
  575. // unlimited: sendFile when writable
  576. writer->onwrite = [this](HBuf* buf) {
  577. if (writer->isWriteComplete()) {
  578. sendFile();
  579. }
  580. };
  581. } else {
  582. // limit_rate=40KB/s interval_ms=1000
  583. // limit_rate=500KB/s interval_ms=80
  584. int interval_ms = file->buf.len * 1000 / 1024 / service->limit_rate;
  585. // limit_rate=40MB/s interval_m=1: 40KB/ms = 40MB/s = 320Mbps
  586. if (interval_ms == 0) interval_ms = 1;
  587. // printf("limit_rate=%dKB/s interval_ms=%d\n", service->limit_rate, interval_ms);
  588. file->timer = setInterval(interval_ms, std::bind(&HttpHandler::sendFile, this));
  589. }
  590. }
  591. writer->EndHeaders();
  592. return HTTP_STATUS_UNFINISHED;
  593. }
  594. int HttpHandler::defaultErrorHandler() {
  595. // error page
  596. if (service->error_page.size() != 0) {
  597. std::string filepath = service->document_root + '/' + service->error_page;
  598. if (files) {
  599. // cache and load error page
  600. FileCache::OpenParam param;
  601. fc = files->Open(filepath.c_str(), &param);
  602. }
  603. }
  604. // status page
  605. if (fc == NULL && resp->body.size() == 0) {
  606. resp->content_type = TEXT_HTML;
  607. make_http_status_page(resp->status_code, resp->body);
  608. }
  609. return 0;
  610. }
  611. int HttpHandler::FeedRecvData(const char* data, size_t len) {
  612. if (protocol == HttpHandler::UNKNOWN) {
  613. int http_version = 1;
  614. #if WITH_NGHTTP2
  615. if (strncmp(data, HTTP2_MAGIC, MIN(len, HTTP2_MAGIC_LEN)) == 0) {
  616. http_version = 2;
  617. }
  618. #else
  619. // check request-line
  620. if (len < MIN_HTTP_REQUEST_LEN) {
  621. hloge("[%s:%d] http request-line too small", ip, port);
  622. error = ERR_REQUEST;
  623. return -1;
  624. }
  625. for (int i = 0; i < MIN_HTTP_REQUEST_LEN; ++i) {
  626. if (!IS_GRAPH(data[i])) {
  627. hloge("[%s:%d] http request-line not plain", ip, port);
  628. error = ERR_REQUEST;
  629. return -1;
  630. }
  631. }
  632. #endif
  633. if (!Init(http_version)) {
  634. hloge("[%s:%d] unsupported HTTP%d", ip, port, http_version);
  635. error = ERR_INVALID_PROTOCOL;
  636. return -1;
  637. }
  638. }
  639. int nfeed = 0;
  640. switch (protocol) {
  641. case HttpHandler::HTTP_V1:
  642. case HttpHandler::HTTP_V2:
  643. if (state != WANT_RECV) {
  644. Reset();
  645. }
  646. nfeed = parser->FeedRecvData(data, len);
  647. // printf("FeedRecvData %d=>%d\n", (int)len, nfeed);
  648. if (nfeed != len) {
  649. hloge("[%s:%d] http parse error: %s", ip, port, parser->StrError(parser->GetError()));
  650. error = ERR_PARSE;
  651. return -1;
  652. }
  653. break;
  654. case HttpHandler::WEBSOCKET:
  655. nfeed = ws_parser->FeedRecvData(data, len);
  656. if (nfeed != len) {
  657. hloge("[%s:%d] websocket parse error!", ip, port);
  658. error = ERR_PARSE;
  659. return -1;
  660. }
  661. break;
  662. default:
  663. hloge("[%s:%d] unknown protocol", ip, port);
  664. error = ERR_INVALID_PROTOCOL;
  665. return -1;
  666. }
  667. if (state == WANT_CLOSE) return 0;
  668. return error ? -1 : nfeed;
  669. }
  670. int HttpHandler::GetSendData(char** data, size_t* len) {
  671. if (state == HANDLE_CONTINUE) {
  672. return 0;
  673. }
  674. HttpRequest* pReq = req.get();
  675. HttpResponse* pResp = resp.get();
  676. if (protocol == HTTP_V1) {
  677. switch(state) {
  678. case WANT_RECV:
  679. if (parser->IsComplete()) state = WANT_SEND;
  680. else return 0;
  681. case HANDLE_END:
  682. state = WANT_SEND;
  683. case WANT_SEND:
  684. state = SEND_HEADER;
  685. case SEND_HEADER:
  686. {
  687. size_t content_length = 0;
  688. const char* content = NULL;
  689. // HEAD
  690. if (pReq->method == HTTP_HEAD) {
  691. if (fc) {
  692. pResp->headers["Accept-Ranges"] = "bytes";
  693. pResp->headers["Content-Length"] = hv::to_string(fc->st.st_size);
  694. } else {
  695. pResp->headers["Content-Type"] = "text/html";
  696. pResp->headers["Content-Length"] = "0";
  697. }
  698. state = SEND_DONE;
  699. goto return_nobody;
  700. }
  701. // File service
  702. if (fc) {
  703. // FileCache
  704. // NOTE: no copy filebuf, more efficient
  705. header = pResp->Dump(true, false);
  706. fc->prepend_header(header.c_str(), header.size());
  707. *data = fc->httpbuf.base;
  708. *len = fc->httpbuf.len;
  709. state = SEND_DONE;
  710. return *len;
  711. }
  712. // API service
  713. content_length = pResp->ContentLength();
  714. content = (const char*)pResp->Content();
  715. if (content) {
  716. if (content_length > (1 << 20)) {
  717. state = SEND_BODY;
  718. goto return_header;
  719. } else {
  720. // NOTE: header+body in one package if <= 1M
  721. header = pResp->Dump(true, false);
  722. header.append(content, content_length);
  723. state = SEND_DONE;
  724. goto return_header;
  725. }
  726. } else {
  727. state = SEND_DONE;
  728. goto return_header;
  729. }
  730. return_nobody:
  731. pResp->content_length = 0;
  732. return_header:
  733. if (header.empty()) header = pResp->Dump(true, false);
  734. *data = (char*)header.c_str();
  735. *len = header.size();
  736. return *len;
  737. }
  738. case SEND_BODY:
  739. {
  740. *data = (char*)pResp->Content();
  741. *len = pResp->ContentLength();
  742. state = SEND_DONE;
  743. return *len;
  744. }
  745. case SEND_DONE:
  746. {
  747. // NOTE: remove file cache if > FILE_CACHE_MAX_SIZE
  748. if (fc && fc->filebuf.len > FILE_CACHE_MAX_SIZE) {
  749. files->Close(fc);
  750. }
  751. fc = NULL;
  752. header.clear();
  753. return 0;
  754. }
  755. default:
  756. return 0;
  757. }
  758. } else if (protocol == HTTP_V2) {
  759. int ret = parser->GetSendData(data, len);
  760. if (ret == 0) state = SEND_DONE;
  761. return ret;
  762. }
  763. return 0;
  764. }
  765. int HttpHandler::SendHttpResponse(bool submit) {
  766. if (!io || !parser) return -1;
  767. char* data = NULL;
  768. size_t len = 0, total_len = 0;
  769. if (submit) parser->SubmitResponse(resp.get());
  770. while (GetSendData(&data, &len)) {
  771. // printf("GetSendData %d\n", (int)len);
  772. if (data && len) {
  773. hio_write(io, data, len);
  774. total_len += len;
  775. }
  776. }
  777. return total_len;
  778. }
  779. int HttpHandler::SendHttpStatusResponse(http_status status_code) {
  780. if (state > WANT_SEND) return 0;
  781. resp->status_code = status_code;
  782. addResponseHeaders();
  783. HandleHttpRequest();
  784. state = WANT_SEND;
  785. return SendHttpResponse();
  786. }
  787. //------------------sendfile--------------------------------------
  788. int HttpHandler::openFile(const char* filepath) {
  789. closeFile();
  790. file = new LargeFile;
  791. file->timer = INVALID_TIMER_ID;
  792. return file->open(filepath, "rb");
  793. }
  794. bool HttpHandler::isFileOpened() {
  795. return file && file->isopen();
  796. }
  797. int HttpHandler::sendFile() {
  798. if (!writer || !writer->isWriteComplete() ||
  799. !isFileOpened() ||
  800. file->buf.len == 0 ||
  801. resp->content_length == 0) {
  802. return -1;
  803. }
  804. int readbytes = MIN(file->buf.len, resp->content_length);
  805. size_t nread = file->read(file->buf.base, readbytes);
  806. if (nread <= 0) {
  807. hloge("read file error!");
  808. error = ERR_READ_FILE;
  809. writer->close(true);
  810. return nread;
  811. }
  812. int nwrite = writer->WriteBody(file->buf.base, nread);
  813. if (nwrite < 0) {
  814. // disconnectd
  815. writer->close(true);
  816. return nwrite;
  817. }
  818. resp->content_length -= nread;
  819. if (resp->content_length == 0) {
  820. writer->End();
  821. closeFile();
  822. }
  823. return nread;
  824. }
  825. void HttpHandler::closeFile() {
  826. if (file) {
  827. if (file->timer != INVALID_TIMER_ID) {
  828. killTimer(file->timer);
  829. file->timer = INVALID_TIMER_ID;
  830. }
  831. delete file;
  832. file = NULL;
  833. }
  834. }
  835. //------------------upgrade--------------------------------------
  836. int HttpHandler::handleUpgrade(const char* upgrade_protocol) {
  837. hlogi("[%s:%d] Upgrade: %s", ip, port, upgrade_protocol);
  838. // websocket
  839. if (stricmp(upgrade_protocol, "websocket") == 0) {
  840. return upgradeWebSocket();
  841. }
  842. // h2/h2c
  843. if (strnicmp(upgrade_protocol, "h2", 2) == 0) {
  844. return upgradeHTTP2();
  845. }
  846. hloge("[%s:%d] unsupported Upgrade: %s", ip, port, upgrade_protocol);
  847. return SetError(ERR_INVALID_PROTOCOL);
  848. }
  849. int HttpHandler::upgradeWebSocket() {
  850. /*
  851. HTTP/1.1 101 Switching Protocols
  852. Connection: Upgrade
  853. Upgrade: websocket
  854. Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
  855. */
  856. resp->status_code = HTTP_STATUS_SWITCHING_PROTOCOLS;
  857. resp->headers["Connection"] = "Upgrade";
  858. resp->headers["Upgrade"] = "websocket";
  859. // Sec-WebSocket-Accept:
  860. auto iter_key = req->headers.find(SEC_WEBSOCKET_KEY);
  861. if (iter_key != req->headers.end()) {
  862. char ws_accept[32] = {0};
  863. ws_encode_key(iter_key->second.c_str(), ws_accept);
  864. resp->headers[SEC_WEBSOCKET_ACCEPT] = ws_accept;
  865. }
  866. // Sec-WebSocket-Protocol:
  867. auto iter_protocol = req->headers.find(SEC_WEBSOCKET_PROTOCOL);
  868. if (iter_protocol != req->headers.end()) {
  869. hv::StringList subprotocols = hv::split(iter_protocol->second, ',');
  870. if (subprotocols.size() > 0) {
  871. hlogw("%s: %s => just select first protocol %s", SEC_WEBSOCKET_PROTOCOL, iter_protocol->second.c_str(), subprotocols[0].c_str());
  872. resp->headers[SEC_WEBSOCKET_PROTOCOL] = subprotocols[0];
  873. }
  874. }
  875. SendHttpResponse();
  876. if (!SwitchWebSocket()) {
  877. hloge("[%s:%d] unsupported websocket", ip, port);
  878. return SetError(ERR_INVALID_PROTOCOL);
  879. }
  880. // onopen
  881. WebSocketOnOpen();
  882. return 0;
  883. }
  884. int HttpHandler::upgradeHTTP2() {
  885. /*
  886. HTTP/1.1 101 Switching Protocols
  887. Connection: Upgrade
  888. Upgrade: h2c
  889. */
  890. resp->status_code = HTTP_STATUS_SWITCHING_PROTOCOLS;
  891. resp->headers["Connection"] = "Upgrade";
  892. resp->headers["Upgrade"] = "h2c";
  893. SendHttpResponse();
  894. if (!SwitchHTTP2()) {
  895. hloge("[%s:%d] unsupported HTTP2", ip, port);
  896. return SetError(ERR_INVALID_PROTOCOL);
  897. }
  898. // NOTE: send HTTP2_SETTINGS frame
  899. SendHttpResponse(false);
  900. return 0;
  901. }
  902. //------------------proxy--------------------------------------
  903. int HttpHandler::handleProxy() {
  904. if (forward_proxy) {
  905. return handleForwardProxy();
  906. }
  907. if (reverse_proxy) {
  908. return handleReverseProxy();
  909. }
  910. return 0;
  911. }
  912. int HttpHandler::handleForwardProxy() {
  913. if (service && service->enable_forward_proxy) {
  914. return connectProxy(req->url);
  915. } else {
  916. hlogw("Forbidden to forward proxy %s", req->url.c_str());
  917. SetError(HTTP_STATUS_FORBIDDEN, HTTP_STATUS_FORBIDDEN);
  918. }
  919. return 0;
  920. }
  921. int HttpHandler::handleReverseProxy() {
  922. return connectProxy(req->url);
  923. }
  924. int HttpHandler::connectProxy(const std::string& strUrl) {
  925. if (!io) return ERR_NULL_POINTER;
  926. HUrl url;
  927. url.parse(strUrl);
  928. hlogi("[%s:%d] proxy_pass %s", ip, port, strUrl.c_str());
  929. if (proxy_connected) {
  930. if (url.host == proxy_host && url.port == proxy_port) {
  931. // reuse keepalive connection
  932. sendProxyRequest();
  933. return 0;
  934. } else {
  935. // detach and close previous connection
  936. hio_t* upstream_io = hio_get_upstream(io);
  937. if (upstream_io) {
  938. hio_setcb_close(upstream_io, NULL);
  939. closeProxy();
  940. }
  941. }
  942. }
  943. if (forward_proxy && !service->IsTrustProxy(url.host.c_str())) {
  944. hlogw("Forbidden to proxy %s", url.host.c_str());
  945. SetError(HTTP_STATUS_FORBIDDEN, HTTP_STATUS_FORBIDDEN);
  946. return 0;
  947. }
  948. hloop_t* loop = hevent_loop(io);
  949. proxy = 1;
  950. proxy_host = url.host;
  951. proxy_port = url.port;
  952. hio_t* upstream_io = hio_create_socket(loop, proxy_host.c_str(), proxy_port, HIO_TYPE_TCP, HIO_CLIENT_SIDE);
  953. if (upstream_io == NULL) {
  954. return SetError(ERR_SOCKET, HTTP_STATUS_BAD_GATEWAY);
  955. }
  956. if (url.scheme == "https") {
  957. hio_enable_ssl(upstream_io);
  958. }
  959. hevent_set_userdata(upstream_io, this);
  960. hio_setup_upstream(io, upstream_io);
  961. hio_setcb_connect(upstream_io, HttpHandler::onProxyConnect);
  962. hio_setcb_close(upstream_io, HttpHandler::onProxyClose);
  963. if (service->proxy_connect_timeout > 0) {
  964. hio_set_connect_timeout(upstream_io, service->proxy_connect_timeout);
  965. }
  966. if (service->proxy_read_timeout > 0) {
  967. hio_set_read_timeout(io, service->proxy_read_timeout);
  968. }
  969. if (service->proxy_write_timeout > 0) {
  970. hio_set_write_timeout(io, service->proxy_write_timeout);
  971. }
  972. hio_connect(upstream_io);
  973. // NOTE: wait upstream_io connected then start read
  974. hio_read_stop(io);
  975. return 0;
  976. }
  977. int HttpHandler::closeProxy() {
  978. if (proxy && proxy_connected) {
  979. proxy_connected = 0;
  980. if (io) hio_close_upstream(io);
  981. }
  982. return 0;
  983. }
  984. int HttpHandler::sendProxyRequest() {
  985. if (!io || !proxy_connected) return -1;
  986. req->headers.erase("Host");
  987. req->FillHost(proxy_host.c_str(), proxy_port);
  988. req->headers.erase("Proxy-Connection");
  989. req->headers["Connection"] = keepalive ? "keep-alive" : "close";
  990. req->headers["X-Real-IP"] = ip;
  991. // NOTE: send head + received body
  992. std::string msg = req->Dump(true, false) + req->body;
  993. // printf("%s\n", msg.c_str());
  994. req->Reset();
  995. hio_write_upstream(io, (void*)msg.c_str(), msg.size());
  996. if (parser->IsComplete()) state = WANT_SEND;
  997. return msg.size();
  998. }
  999. void HttpHandler::onProxyConnect(hio_t* upstream_io) {
  1000. // printf("onProxyConnect\n");
  1001. HttpHandler* handler = (HttpHandler*)hevent_userdata(upstream_io);
  1002. hio_t* io = hio_get_upstream(upstream_io);
  1003. assert(handler != NULL && io != NULL);
  1004. handler->proxy_connected = 1;
  1005. if (handler->req->method == HTTP_CONNECT) {
  1006. // handler->resp->status_code = HTTP_STATUS_OK;
  1007. // handler->SendHttpResponse();
  1008. hio_write(io, HTTP_200_CONNECT_RESPONSE, HTTP_200_CONNECT_RESPONSE_LEN);
  1009. handler->state = SEND_DONE;
  1010. // NOTE: recv request then upstream
  1011. hio_setcb_read(io, hio_write_upstream);
  1012. } else {
  1013. handler->sendProxyRequest();
  1014. }
  1015. // NOTE: start recv request continue then upstream
  1016. if (handler->upgrade) hio_setcb_read(io, hio_write_upstream);
  1017. hio_read_start(io);
  1018. // NOTE: start recv response then upstream
  1019. hio_setcb_read(upstream_io, hio_write_upstream);
  1020. hio_read_start(upstream_io);
  1021. }
  1022. void HttpHandler::onProxyClose(hio_t* upstream_io) {
  1023. // printf("onProxyClose\n");
  1024. HttpHandler* handler = (HttpHandler*)hevent_userdata(upstream_io);
  1025. if (handler == NULL) return;
  1026. handler->proxy_connected = 0;
  1027. hevent_set_userdata(upstream_io, NULL);
  1028. int error = hio_error(upstream_io);
  1029. if (error == ETIMEDOUT) {
  1030. handler->SendHttpStatusResponse(HTTP_STATUS_GATEWAY_TIMEOUT);
  1031. }
  1032. handler->error = error;
  1033. hio_close_upstream(upstream_io);
  1034. }