1
0

HttpHandler.cpp 33 KB

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