HttpHandler.cpp 29 KB

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