HttpHandler.cpp 32 KB

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