HttpHandler.cpp 33 KB

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