1
0

HttpHandler.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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 hv::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. http_handler ctx_handler = NULL;
  73. if (service->api_handlers.size() != 0) {
  74. service->GetApi(req.get(), &sync_handler, &async_handler, &ctx_handler);
  75. }
  76. if (sync_handler) {
  77. // sync api handler
  78. status_code = sync_handler(req.get(), resp.get());
  79. }
  80. else if (async_handler) {
  81. // async api handler
  82. async_handler(req, writer);
  83. status_code = 0;
  84. }
  85. else if (ctx_handler) {
  86. // HttpContext handler
  87. status_code = customHttpHandler(ctx_handler);
  88. if (writer->state != hv::HttpResponseWriter::SEND_BEGIN) {
  89. status_code = 0;
  90. }
  91. }
  92. else if (req->method == HTTP_GET || req->method == HTTP_HEAD) {
  93. // static handler
  94. if (service->staticHandler) {
  95. status_code = customHttpHandler(service->staticHandler);
  96. }
  97. else if (service->document_root.size() != 0) {
  98. status_code = defaultStaticHandler();
  99. }
  100. else {
  101. status_code = HTTP_STATUS_NOT_FOUND;
  102. }
  103. }
  104. else {
  105. // Not Implemented
  106. status_code = HTTP_STATUS_NOT_IMPLEMENTED;
  107. }
  108. return status_code;
  109. }
  110. int HttpHandler::defaultStaticHandler() {
  111. // file service
  112. int status_code = HTTP_STATUS_OK;
  113. std::string path = req->Path();
  114. const char* req_path = path.c_str();
  115. // path safe check
  116. if (req_path[0] != '/' || strstr(req_path, "/../")) {
  117. return HTTP_STATUS_BAD_REQUEST;
  118. }
  119. std::string filepath = service->document_root + path;
  120. if (req_path[1] == '\0') {
  121. filepath += service->home_page;
  122. }
  123. bool is_dir = filepath.c_str()[filepath.size()-1] == '/';
  124. bool is_index_of = false;
  125. if (service->index_of.size() != 0 && strstartswith(req_path, service->index_of.c_str())) {
  126. is_index_of = true;
  127. }
  128. if (!is_dir || is_index_of) {
  129. FileCache::OpenParam param;
  130. param.need_read = req->method == HTTP_HEAD ? false : true;
  131. param.path = req_path;
  132. fc = files->Open(filepath.c_str(), &param);
  133. if (fc == NULL) {
  134. status_code = HTTP_STATUS_NOT_FOUND;
  135. if (param.error == ERR_OVER_LIMIT) {
  136. if (service->largeFileHandler) {
  137. status_code = customHttpHandler(service->largeFileHandler);
  138. }
  139. }
  140. }
  141. } else {
  142. status_code = HTTP_STATUS_NOT_FOUND;
  143. }
  144. if (fc) {
  145. // Not Modified
  146. auto iter = req->headers.find("if-not-match");
  147. if (iter != req->headers.end() &&
  148. strcmp(iter->second.c_str(), fc->etag) == 0) {
  149. status_code = HTTP_STATUS_NOT_MODIFIED;
  150. fc = NULL;
  151. }
  152. else {
  153. iter = req->headers.find("if-modified-since");
  154. if (iter != req->headers.end() &&
  155. strcmp(iter->second.c_str(), fc->last_modified) == 0) {
  156. status_code = HTTP_STATUS_NOT_MODIFIED;
  157. fc = NULL;
  158. }
  159. }
  160. }
  161. return status_code;
  162. }
  163. int HttpHandler::defaultErrorHandler() {
  164. // error page
  165. if (service->error_page.size() != 0) {
  166. std::string filepath = service->document_root;
  167. filepath += '/';
  168. filepath += service->error_page;
  169. FileCache::OpenParam param;
  170. fc = files->Open(filepath.c_str(), &param);
  171. }
  172. // status page
  173. if (fc == NULL && resp->body.size() == 0) {
  174. resp->content_type = TEXT_HTML;
  175. make_http_status_page(resp->status_code, resp->body);
  176. }
  177. return 0;
  178. }
  179. int HttpHandler::FeedRecvData(const char* data, size_t len) {
  180. int nfeed = 0;
  181. if (protocol == HttpHandler::WEBSOCKET) {
  182. nfeed = ws->parser->FeedRecvData(data, len);
  183. if (nfeed != len) {
  184. hloge("[%s:%d] websocket parse error!", ip, port);
  185. }
  186. } else {
  187. if (state != WANT_RECV) {
  188. Reset();
  189. }
  190. nfeed = parser->FeedRecvData(data, len);
  191. if (nfeed != len) {
  192. hloge("[%s:%d] http parse error: %s", ip, port, parser->StrError(parser->GetError()));
  193. }
  194. }
  195. return nfeed;
  196. }
  197. int HttpHandler::GetSendData(char** data, size_t* len) {
  198. if (state == HANDLE_CONTINUE) {
  199. return 0;
  200. }
  201. HttpRequest* pReq = req.get();
  202. HttpResponse* pResp = resp.get();
  203. if (protocol == HTTP_V1) {
  204. switch(state) {
  205. case WANT_RECV:
  206. if (parser->IsComplete()) state = WANT_SEND;
  207. else return 0;
  208. case HANDLE_END:
  209. state = WANT_SEND;
  210. case WANT_SEND:
  211. state = SEND_HEADER;
  212. case SEND_HEADER:
  213. {
  214. int content_length = 0;
  215. const char* content = NULL;
  216. // HEAD
  217. if (pReq->method == HTTP_HEAD) {
  218. if (fc) {
  219. pResp->headers["Accept-Ranges"] = "bytes";
  220. pResp->headers["Content-Length"] = hv::to_string(fc->st.st_size);
  221. } else {
  222. pResp->headers["Content-Type"] = "text/html";
  223. pResp->headers["Content-Length"] = "0";
  224. }
  225. state = SEND_DONE;
  226. goto return_nobody;
  227. }
  228. // File service
  229. if (fc) {
  230. long from, to, total;
  231. int nread;
  232. // Range:
  233. if (pReq->GetRange(from, to)) {
  234. HFile file;
  235. if (file.open(fc->filepath.c_str(), "rb") != 0) {
  236. pResp->status_code = HTTP_STATUS_NOT_FOUND;
  237. state = SEND_DONE;
  238. goto return_nobody;
  239. }
  240. total = file.size();
  241. if (to == 0 || to >= total) to = total - 1;
  242. pResp->content_length = to - from + 1;
  243. nread = file.readrange(body, from, to);
  244. if (nread != pResp->content_length) {
  245. pResp->status_code = HTTP_STATUS_INTERNAL_SERVER_ERROR;
  246. state = SEND_DONE;
  247. goto return_nobody;
  248. }
  249. pResp->SetRange(from, to, total);
  250. state = SEND_BODY;
  251. goto return_header;
  252. }
  253. // FileCache
  254. // NOTE: no copy filebuf, more efficient
  255. header = pResp->Dump(true, false);
  256. fc->prepend_header(header.c_str(), header.size());
  257. *data = fc->httpbuf.base;
  258. *len = fc->httpbuf.len;
  259. state = SEND_DONE;
  260. return *len;
  261. }
  262. // API service
  263. content_length = pResp->ContentLength();
  264. content = (const char*)pResp->Content();
  265. if (content) {
  266. if (content_length > (1 << 20)) {
  267. state = SEND_BODY;
  268. goto return_header;
  269. } else {
  270. // NOTE: header+body in one package if <= 1M
  271. header = pResp->Dump(true, false);
  272. header.append(content, content_length);
  273. state = SEND_DONE;
  274. goto return_header;
  275. }
  276. } else {
  277. state = SEND_DONE;
  278. goto return_header;
  279. }
  280. return_nobody:
  281. pResp->content_length = 0;
  282. return_header:
  283. if (header.empty()) header = pResp->Dump(true, false);
  284. *data = (char*)header.c_str();
  285. *len = header.size();
  286. return *len;
  287. }
  288. case SEND_BODY:
  289. {
  290. if (body.empty()) {
  291. *data = (char*)pResp->Content();
  292. *len = pResp->ContentLength();
  293. } else {
  294. *data = (char*)body.c_str();
  295. *len = body.size();
  296. }
  297. state = SEND_DONE;
  298. return *len;
  299. }
  300. case SEND_DONE:
  301. {
  302. // NOTE: remove file cache if > 16M
  303. if (fc && fc->filebuf.len > (1 << 24)) {
  304. files->Close(fc);
  305. }
  306. fc = NULL;
  307. header.clear();
  308. body.clear();
  309. return 0;
  310. }
  311. default:
  312. return 0;
  313. }
  314. } else if (protocol == HTTP_V2) {
  315. return parser->GetSendData(data, len);
  316. }
  317. return 0;
  318. }