1
0

HttpHandler.cpp 33 KB

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