1
0

HttpHandler.cpp 29 KB

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