1
0

HttpHandler.cpp 33 KB

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