1
0

HttpHandler.cpp 32 KB

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