HttpHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. #include "HttpHandler.h"
  2. #include "hbase.h"
  3. #include "herr.h"
  4. #include "hlog.h"
  5. #include "hasync.h" // import hv::async for http_async_handler
  6. #include "http_page.h"
  7. #include "htime.h"
  8. bool HttpHandler::SwitchWebSocket(hio_t* io, ws_session_type type) {
  9. if(!io || !ws_service) return false;
  10. protocol = WEBSOCKET;
  11. ws_parser.reset(new WebSocketParser);
  12. ws_channel.reset(new hv::WebSocketChannel(io, type));
  13. ws_parser->onMessage = [this](int opcode, const std::string& msg){
  14. switch(opcode) {
  15. case WS_OPCODE_CLOSE:
  16. ws_channel->close(true);
  17. break;
  18. case WS_OPCODE_PING:
  19. // printf("recv ping\n");
  20. // printf("send pong\n");
  21. ws_channel->sendPong();
  22. break;
  23. case WS_OPCODE_PONG:
  24. // printf("recv pong\n");
  25. this->last_recv_pong_time = gethrtime_us();
  26. break;
  27. case WS_OPCODE_TEXT:
  28. case WS_OPCODE_BINARY:
  29. // onmessage
  30. if (ws_service && ws_service->onmessage) {
  31. ws_service->onmessage(ws_channel, msg);
  32. }
  33. break;
  34. default:
  35. break;
  36. }
  37. };
  38. // NOTE: cancel keepalive timer, judge alive by heartbeat.
  39. hio_set_keepalive_timeout(io, 0);
  40. if (ws_service && ws_service->ping_interval > 0) {
  41. int ping_interval = MAX(ws_service->ping_interval, 1000);
  42. ws_channel->setHeartbeat(ping_interval, [this](){
  43. if (last_recv_pong_time < last_send_ping_time) {
  44. hlogw("[%s:%d] websocket no pong!", ip, port);
  45. ws_channel->close(true);
  46. } else {
  47. // printf("send ping\n");
  48. ws_channel->sendPing();
  49. last_send_ping_time = gethrtime_us();
  50. }
  51. });
  52. }
  53. // onopen
  54. WebSocketOnOpen();
  55. return true;
  56. }
  57. int HttpHandler::customHttpHandler(const http_handler& handler) {
  58. return invokeHttpHandler(&handler);
  59. }
  60. int HttpHandler::invokeHttpHandler(const http_handler* handler) {
  61. int status_code = HTTP_STATUS_NOT_IMPLEMENTED;
  62. if (handler->sync_handler) {
  63. // NOTE: sync_handler run on IO thread
  64. status_code = handler->sync_handler(req.get(), resp.get());
  65. } else if (handler->async_handler) {
  66. // NOTE: async_handler run on hv::async threadpool
  67. hv::async(std::bind(handler->async_handler, req, writer));
  68. status_code = HTTP_STATUS_UNFINISHED;
  69. } else if (handler->ctx_handler) {
  70. HttpContextPtr ctx(new hv::HttpContext);
  71. ctx->service = service;
  72. ctx->request = req;
  73. ctx->response = resp;
  74. ctx->writer = writer;
  75. // NOTE: ctx_handler run on IO thread, you can easily post HttpContextPtr to your consumer thread for processing.
  76. status_code = handler->ctx_handler(ctx);
  77. if (writer && writer->state != hv::HttpResponseWriter::SEND_BEGIN) {
  78. status_code = HTTP_STATUS_UNFINISHED;
  79. }
  80. }
  81. return status_code;
  82. }
  83. int HttpHandler::HandleHttpRequest() {
  84. // preprocessor -> processor -> postprocessor
  85. int status_code = HTTP_STATUS_OK;
  86. HttpRequest* pReq = req.get();
  87. HttpResponse* pResp = resp.get();
  88. pReq->scheme = ssl ? "https" : "http";
  89. pReq->client_addr.ip = ip;
  90. pReq->client_addr.port = port;
  91. pReq->Host();
  92. pReq->ParseUrl();
  93. // NOTE: Not all users want to parse body, we comment it out.
  94. // pReq->ParseBody();
  95. preprocessor:
  96. state = HANDLE_BEGIN;
  97. if (service->preprocessor) {
  98. status_code = customHttpHandler(service->preprocessor);
  99. if (status_code != 0) {
  100. goto postprocessor;
  101. }
  102. }
  103. processor:
  104. if (service->processor) {
  105. status_code = customHttpHandler(service->processor);
  106. } else {
  107. status_code = defaultRequestHandler();
  108. }
  109. postprocessor:
  110. if (status_code >= 100 && status_code < 600) {
  111. pResp->status_code = (http_status)status_code;
  112. }
  113. if (pResp->status_code >= 400 && pResp->body.size() == 0 && pReq->method != HTTP_HEAD) {
  114. if (service->errorHandler) {
  115. customHttpHandler(service->errorHandler);
  116. } else {
  117. defaultErrorHandler();
  118. }
  119. }
  120. if (fc) {
  121. pResp->content = fc->filebuf.base;
  122. pResp->content_length = fc->filebuf.len;
  123. pResp->headers["Content-Type"] = fc->content_type;
  124. pResp->headers["Last-Modified"] = fc->last_modified;
  125. pResp->headers["Etag"] = fc->etag;
  126. }
  127. if (service->postprocessor) {
  128. customHttpHandler(service->postprocessor);
  129. }
  130. if (status_code == 0) {
  131. state = HANDLE_CONTINUE;
  132. } else {
  133. state = HANDLE_END;
  134. parser->SubmitResponse(resp.get());
  135. }
  136. return status_code;
  137. }
  138. int HttpHandler::defaultRequestHandler() {
  139. int status_code = HTTP_STATUS_OK;
  140. http_handler* handler = NULL;
  141. if (service->api_handlers.size() != 0) {
  142. service->GetApi(req.get(), &handler);
  143. }
  144. if (handler) {
  145. status_code = invokeHttpHandler(handler);
  146. }
  147. else if (req->method == HTTP_GET || req->method == HTTP_HEAD) {
  148. // static handler
  149. if (service->staticHandler) {
  150. status_code = customHttpHandler(service->staticHandler);
  151. }
  152. else if (service->document_root.size() != 0) {
  153. status_code = defaultStaticHandler();
  154. }
  155. else {
  156. status_code = HTTP_STATUS_NOT_FOUND;
  157. }
  158. }
  159. else {
  160. // Not Implemented
  161. status_code = HTTP_STATUS_NOT_IMPLEMENTED;
  162. }
  163. return status_code;
  164. }
  165. int HttpHandler::defaultStaticHandler() {
  166. // file service
  167. int status_code = HTTP_STATUS_OK;
  168. std::string path = req->Path();
  169. const char* req_path = path.c_str();
  170. // path safe check
  171. if (req_path[0] != '/' || strstr(req_path, "/../")) {
  172. return HTTP_STATUS_BAD_REQUEST;
  173. }
  174. std::string filepath = service->document_root + path;
  175. if (req_path[1] == '\0') {
  176. filepath += service->home_page;
  177. }
  178. bool is_dir = filepath.c_str()[filepath.size()-1] == '/';
  179. bool is_index_of = false;
  180. if (service->index_of.size() != 0 && hv_strstartswith(req_path, service->index_of.c_str())) {
  181. is_index_of = true;
  182. }
  183. if (!is_dir || is_index_of) {
  184. FileCache::OpenParam param;
  185. bool has_range = req->headers.find("Range") != req->headers.end();
  186. param.need_read = !(req->method == HTTP_HEAD || has_range);
  187. param.path = req_path;
  188. fc = files->Open(filepath.c_str(), &param);
  189. if (fc == NULL) {
  190. status_code = HTTP_STATUS_NOT_FOUND;
  191. if (param.error == ERR_OVER_LIMIT) {
  192. if (service->largeFileHandler) {
  193. status_code = customHttpHandler(service->largeFileHandler);
  194. }
  195. }
  196. }
  197. } else {
  198. status_code = HTTP_STATUS_NOT_FOUND;
  199. }
  200. if (fc) {
  201. // Not Modified
  202. auto iter = req->headers.find("if-not-match");
  203. if (iter != req->headers.end() &&
  204. strcmp(iter->second.c_str(), fc->etag) == 0) {
  205. status_code = HTTP_STATUS_NOT_MODIFIED;
  206. fc = NULL;
  207. }
  208. else {
  209. iter = req->headers.find("if-modified-since");
  210. if (iter != req->headers.end() &&
  211. strcmp(iter->second.c_str(), fc->last_modified) == 0) {
  212. status_code = HTTP_STATUS_NOT_MODIFIED;
  213. fc = NULL;
  214. }
  215. }
  216. }
  217. return status_code;
  218. }
  219. int HttpHandler::defaultErrorHandler() {
  220. // error page
  221. if (service->error_page.size() != 0) {
  222. std::string filepath = service->document_root + '/' + service->error_page;
  223. FileCache::OpenParam param;
  224. fc = files->Open(filepath.c_str(), &param);
  225. }
  226. // status page
  227. if (fc == NULL && resp->body.size() == 0) {
  228. resp->content_type = TEXT_HTML;
  229. make_http_status_page(resp->status_code, resp->body);
  230. }
  231. return 0;
  232. }
  233. int HttpHandler::FeedRecvData(const char* data, size_t len) {
  234. int nfeed = 0;
  235. if (protocol == HttpHandler::WEBSOCKET) {
  236. nfeed = ws_parser->FeedRecvData(data, len);
  237. if (nfeed != len) {
  238. hloge("[%s:%d] websocket parse error!", ip, port);
  239. }
  240. } else {
  241. if (state != WANT_RECV) {
  242. Reset();
  243. }
  244. nfeed = parser->FeedRecvData(data, len);
  245. if (nfeed != len) {
  246. hloge("[%s:%d] http parse error: %s", ip, port, parser->StrError(parser->GetError()));
  247. }
  248. }
  249. return nfeed;
  250. }
  251. int HttpHandler::GetSendData(char** data, size_t* len) {
  252. if (state == HANDLE_CONTINUE) {
  253. return 0;
  254. }
  255. HttpRequest* pReq = req.get();
  256. HttpResponse* pResp = resp.get();
  257. if (protocol == HTTP_V1) {
  258. switch(state) {
  259. case WANT_RECV:
  260. if (parser->IsComplete()) state = WANT_SEND;
  261. else return 0;
  262. case HANDLE_END:
  263. state = WANT_SEND;
  264. case WANT_SEND:
  265. state = SEND_HEADER;
  266. case SEND_HEADER:
  267. {
  268. int content_length = 0;
  269. const char* content = NULL;
  270. // HEAD
  271. if (pReq->method == HTTP_HEAD) {
  272. if (fc) {
  273. pResp->headers["Accept-Ranges"] = "bytes";
  274. pResp->headers["Content-Length"] = hv::to_string(fc->st.st_size);
  275. } else {
  276. pResp->headers["Content-Type"] = "text/html";
  277. pResp->headers["Content-Length"] = "0";
  278. }
  279. state = SEND_DONE;
  280. goto return_nobody;
  281. }
  282. // File service
  283. if (fc) {
  284. long from, to, total;
  285. int nread;
  286. // Range:
  287. if (pReq->GetRange(from, to)) {
  288. HFile file;
  289. if (file.open(fc->filepath.c_str(), "rb") != 0) {
  290. pResp->status_code = HTTP_STATUS_NOT_FOUND;
  291. state = SEND_DONE;
  292. goto return_nobody;
  293. }
  294. total = file.size();
  295. if (to == 0 || to >= total) to = total - 1;
  296. pResp->content_length = to - from + 1;
  297. nread = file.readrange(body, from, to);
  298. if (nread != pResp->content_length) {
  299. pResp->status_code = HTTP_STATUS_INTERNAL_SERVER_ERROR;
  300. state = SEND_DONE;
  301. goto return_nobody;
  302. }
  303. pResp->status_code = HTTP_STATUS_PARTIAL_CONTENT;
  304. pResp->SetRange(from, to, total);
  305. state = SEND_BODY;
  306. goto return_header;
  307. }
  308. // FileCache
  309. // NOTE: no copy filebuf, more efficient
  310. header = pResp->Dump(true, false);
  311. fc->prepend_header(header.c_str(), header.size());
  312. *data = fc->httpbuf.base;
  313. *len = fc->httpbuf.len;
  314. state = SEND_DONE;
  315. return *len;
  316. }
  317. // API service
  318. content_length = pResp->ContentLength();
  319. content = (const char*)pResp->Content();
  320. if (content) {
  321. if (content_length > (1 << 20)) {
  322. state = SEND_BODY;
  323. goto return_header;
  324. } else {
  325. // NOTE: header+body in one package if <= 1M
  326. header = pResp->Dump(true, false);
  327. header.append(content, content_length);
  328. state = SEND_DONE;
  329. goto return_header;
  330. }
  331. } else {
  332. state = SEND_DONE;
  333. goto return_header;
  334. }
  335. return_nobody:
  336. pResp->content_length = 0;
  337. return_header:
  338. if (header.empty()) header = pResp->Dump(true, false);
  339. *data = (char*)header.c_str();
  340. *len = header.size();
  341. return *len;
  342. }
  343. case SEND_BODY:
  344. {
  345. if (body.empty()) {
  346. *data = (char*)pResp->Content();
  347. *len = pResp->ContentLength();
  348. } else {
  349. *data = (char*)body.c_str();
  350. *len = body.size();
  351. }
  352. state = SEND_DONE;
  353. return *len;
  354. }
  355. case SEND_DONE:
  356. {
  357. // NOTE: remove file cache if > 16M
  358. if (fc && fc->filebuf.len > (1 << 24)) {
  359. files->Close(fc);
  360. }
  361. fc = NULL;
  362. header.clear();
  363. body.clear();
  364. return 0;
  365. }
  366. default:
  367. return 0;
  368. }
  369. } else if (protocol == HTTP_V2) {
  370. return parser->GetSendData(data, len);
  371. }
  372. return 0;
  373. }