HttpHandler.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. #include "HttpHandler.h"
  2. #include "hbase.h"
  3. #include "herr.h"
  4. #include "hlog.h"
  5. #include "http_page.h"
  6. int HttpHandler::HandleHttpRequest() {
  7. // preprocessor -> processor -> postprocessor
  8. int status_code = HTTP_STATUS_OK;
  9. HttpRequest* pReq = req.get();
  10. HttpResponse* pResp = resp.get();
  11. pReq->scheme = ssl ? "https" : "http";
  12. pReq->client_addr.ip = ip;
  13. pReq->client_addr.port = port;
  14. pReq->Host();
  15. pReq->ParseUrl();
  16. // pReq->ParseBody();
  17. preprocessor:
  18. state = HANDLE_BEGIN;
  19. if (service->preprocessor) {
  20. status_code = service->preprocessor(pReq, pResp);
  21. if (status_code != 0) {
  22. goto postprocessor;
  23. }
  24. }
  25. processor:
  26. if (service->processor) {
  27. status_code = customHttpHandler(service->processor);
  28. } else {
  29. status_code = defaultRequestHandler();
  30. }
  31. postprocessor:
  32. if (status_code >= 100 && status_code < 600) {
  33. pResp->status_code = (http_status)status_code;
  34. }
  35. if (pResp->status_code >= 400 && pResp->body.size() == 0 && pReq->method != HTTP_HEAD) {
  36. if (service->errorHandler) {
  37. customHttpHandler(service->errorHandler);
  38. } else {
  39. defaultErrorHandler();
  40. }
  41. }
  42. if (fc) {
  43. pResp->content = fc->filebuf.base;
  44. pResp->content_length = fc->filebuf.len;
  45. pResp->headers["Content-Type"] = fc->content_type;
  46. pResp->headers["Last-Modified"] = fc->last_modified;
  47. pResp->headers["Etag"] = fc->etag;
  48. }
  49. if (service->postprocessor) {
  50. service->postprocessor(pReq, pResp);
  51. }
  52. if (status_code == 0) {
  53. state = HANDLE_CONTINUE;
  54. } else {
  55. state = HANDLE_END;
  56. parser->SubmitResponse(resp.get());
  57. }
  58. return status_code;
  59. }
  60. int HttpHandler::customHttpHandler(http_handler& fn) {
  61. HttpContextPtr ctx(new HttpContext);
  62. ctx->service = service;
  63. ctx->request = req;
  64. ctx->response = resp;
  65. ctx->writer = writer;
  66. return fn(ctx);
  67. }
  68. int HttpHandler::defaultRequestHandler() {
  69. int status_code = HTTP_STATUS_OK;
  70. http_sync_handler sync_handler = NULL;
  71. http_async_handler async_handler = NULL;
  72. if (service->api_handlers.size() != 0) {
  73. service->GetApi(req.get(), &sync_handler, &async_handler);
  74. }
  75. if (sync_handler) {
  76. // sync api handler
  77. status_code = sync_handler(req.get(), resp.get());
  78. if (status_code != 0) {
  79. return status_code;
  80. }
  81. }
  82. else if (async_handler) {
  83. // async api handler
  84. async_handler(req, writer);
  85. status_code = 0;
  86. }
  87. else if (req->method == HTTP_GET || req->method == HTTP_HEAD) {
  88. // static handler
  89. if (service->staticHandler) {
  90. customHttpHandler(service->staticHandler);
  91. }
  92. else if (service->document_root.size() != 0) {
  93. status_code = defaultStaticHandler();
  94. }
  95. else {
  96. status_code = HTTP_STATUS_NOT_FOUND;
  97. }
  98. }
  99. else {
  100. // Not Implemented
  101. status_code = HTTP_STATUS_NOT_IMPLEMENTED;
  102. }
  103. return status_code;
  104. }
  105. int HttpHandler::defaultStaticHandler() {
  106. // file service
  107. int status_code = HTTP_STATUS_OK;
  108. std::string path = req->Path();
  109. const char* req_path = path.c_str();
  110. // path safe check
  111. if (req_path[0] != '/' || strstr(req_path, "/../")) {
  112. return HTTP_STATUS_BAD_REQUEST;
  113. }
  114. std::string filepath = service->document_root + path;
  115. if (req_path[1] == '\0') {
  116. filepath += service->home_page;
  117. }
  118. bool is_dir = filepath.c_str()[filepath.size()-1] == '/';
  119. bool is_index_of = false;
  120. if (service->index_of.size() != 0 && strstartswith(req_path, service->index_of.c_str())) {
  121. is_index_of = true;
  122. }
  123. if (!is_dir || is_index_of) {
  124. FileCache::OpenParam param;
  125. param.need_read = req->method == HTTP_HEAD ? false : true;
  126. param.path = req_path;
  127. fc = files->Open(filepath.c_str(), &param);
  128. if (fc == NULL) {
  129. status_code = HTTP_STATUS_NOT_FOUND;
  130. if (param.error == ERR_OVER_LIMIT) {
  131. if (service->largeFileHandler) {
  132. status_code = customHttpHandler(service->largeFileHandler);
  133. }
  134. }
  135. }
  136. } else {
  137. status_code = HTTP_STATUS_NOT_FOUND;
  138. }
  139. if (fc) {
  140. // Not Modified
  141. auto iter = req->headers.find("if-not-match");
  142. if (iter != req->headers.end() &&
  143. strcmp(iter->second.c_str(), fc->etag) == 0) {
  144. status_code = HTTP_STATUS_NOT_MODIFIED;
  145. fc = NULL;
  146. }
  147. else {
  148. iter = req->headers.find("if-modified-since");
  149. if (iter != req->headers.end() &&
  150. strcmp(iter->second.c_str(), fc->last_modified) == 0) {
  151. status_code = HTTP_STATUS_NOT_MODIFIED;
  152. fc = NULL;
  153. }
  154. }
  155. }
  156. return status_code;
  157. }
  158. int HttpHandler::defaultErrorHandler() {
  159. // error page
  160. if (service->error_page.size() != 0) {
  161. std::string filepath = service->document_root;
  162. filepath += '/';
  163. filepath += service->error_page;
  164. FileCache::OpenParam param;
  165. fc = files->Open(filepath.c_str(), &param);
  166. }
  167. // status page
  168. if (fc == NULL && resp->body.size() == 0) {
  169. resp->content_type = TEXT_HTML;
  170. make_http_status_page(resp->status_code, resp->body);
  171. }
  172. return 0;
  173. }
  174. int HttpHandler::FeedRecvData(const char* data, size_t len) {
  175. int nfeed = 0;
  176. if (protocol == HttpHandler::WEBSOCKET) {
  177. nfeed = ws->parser->FeedRecvData(data, len);
  178. if (nfeed != len) {
  179. hloge("[%s:%d] websocket parse error!", ip, port);
  180. }
  181. } else {
  182. if (state != WANT_RECV) {
  183. Reset();
  184. }
  185. nfeed = parser->FeedRecvData(data, len);
  186. if (nfeed != len) {
  187. hloge("[%s:%d] http parse error: %s", ip, port, parser->StrError(parser->GetError()));
  188. }
  189. }
  190. return nfeed;
  191. }
  192. int HttpHandler::GetSendData(char** data, size_t* len) {
  193. if (state == HANDLE_CONTINUE) {
  194. return 0;
  195. }
  196. HttpRequest* pReq = req.get();
  197. HttpResponse* pResp = resp.get();
  198. if (protocol == HTTP_V1) {
  199. switch(state) {
  200. case WANT_RECV:
  201. if (parser->IsComplete()) state = WANT_SEND;
  202. else return 0;
  203. case HANDLE_END:
  204. state = WANT_SEND;
  205. case WANT_SEND:
  206. state = SEND_HEADER;
  207. case SEND_HEADER:
  208. {
  209. int content_length = 0;
  210. const char* content = NULL;
  211. // HEAD
  212. if (pReq->method == HTTP_HEAD) {
  213. if (fc) {
  214. pResp->headers["Accept-Ranges"] = "bytes";
  215. pResp->headers["Content-Length"] = hv::to_string(fc->st.st_size);
  216. } else {
  217. pResp->headers["Content-Type"] = "text/html";
  218. pResp->headers["Content-Length"] = "0";
  219. }
  220. state = SEND_DONE;
  221. goto return_nobody;
  222. }
  223. // File service
  224. if (fc) {
  225. long from, to, total;
  226. int nread;
  227. // Range:
  228. if (pReq->GetRange(from, to)) {
  229. HFile file;
  230. if (file.open(fc->filepath.c_str(), "rb") != 0) {
  231. pResp->status_code = HTTP_STATUS_NOT_FOUND;
  232. state = SEND_DONE;
  233. goto return_nobody;
  234. }
  235. total = file.size();
  236. if (to == 0 || to >= total) to = total - 1;
  237. pResp->content_length = to - from + 1;
  238. nread = file.readrange(body, from, to);
  239. if (nread != pResp->content_length) {
  240. pResp->status_code = HTTP_STATUS_INTERNAL_SERVER_ERROR;
  241. state = SEND_DONE;
  242. goto return_nobody;
  243. }
  244. pResp->SetRange(from, to, total);
  245. state = SEND_BODY;
  246. goto return_header;
  247. }
  248. // FileCache
  249. // NOTE: no copy filebuf, more efficient
  250. header = pResp->Dump(true, false);
  251. fc->prepend_header(header.c_str(), header.size());
  252. *data = fc->httpbuf.base;
  253. *len = fc->httpbuf.len;
  254. state = SEND_DONE;
  255. return *len;
  256. }
  257. // API service
  258. content_length = pResp->ContentLength();
  259. content = (const char*)pResp->Content();
  260. if (content) {
  261. if (content_length > (1 << 20)) {
  262. state = SEND_BODY;
  263. goto return_header;
  264. } else {
  265. // NOTE: header+body in one package if <= 1M
  266. header = pResp->Dump(true, false);
  267. header.append(content, content_length);
  268. state = SEND_DONE;
  269. goto return_header;
  270. }
  271. } else {
  272. state = SEND_DONE;
  273. goto return_header;
  274. }
  275. return_nobody:
  276. pResp->content_length = 0;
  277. return_header:
  278. if (header.empty()) header = pResp->Dump(true, false);
  279. *data = (char*)header.c_str();
  280. *len = header.size();
  281. return *len;
  282. }
  283. case SEND_BODY:
  284. {
  285. if (body.empty()) {
  286. *data = (char*)pResp->Content();
  287. *len = pResp->ContentLength();
  288. } else {
  289. *data = (char*)body.c_str();
  290. *len = body.size();
  291. }
  292. state = SEND_DONE;
  293. return *len;
  294. }
  295. case SEND_DONE:
  296. {
  297. // NOTE: remove file cache if > 16M
  298. if (fc && fc->filebuf.len > (1 << 24)) {
  299. files->Close(fc);
  300. }
  301. fc = NULL;
  302. header.clear();
  303. body.clear();
  304. return 0;
  305. }
  306. default:
  307. return 0;
  308. }
  309. } else if (protocol == HTTP_V2) {
  310. return parser->GetSendData(data, len);
  311. }
  312. return 0;
  313. }