1
0

HttpHandler.cpp 33 KB

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