handler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. #include "handler.h"
  2. #include <thread> // import std::thread
  3. #include <chrono> // import std::chrono
  4. #include "hbase.h"
  5. #include "htime.h"
  6. #include "hfile.h"
  7. #include "hstring.h"
  8. #include "EventLoop.h" // import setTimeout, setInterval
  9. int Handler::preprocessor(HttpRequest* req, HttpResponse* resp) {
  10. // printf("%s:%d\n", req->client_addr.ip.c_str(), req->client_addr.port);
  11. // printf("%s\n", req->Dump(true, true).c_str());
  12. #if REDIRECT_HTTP_TO_HTTPS
  13. // 301
  14. if (req->scheme == "http") {
  15. std::string location = hv::asprintf("https://%s:%d%s", req->host.c_str(), 8443, req->path.c_str());
  16. return resp->Redirect(location, HTTP_STATUS_MOVED_PERMANENTLY);
  17. }
  18. #endif
  19. // cors
  20. resp->headers["Access-Control-Allow-Origin"] = "*";
  21. if (req->method == HTTP_OPTIONS) {
  22. resp->headers["Access-Control-Allow-Origin"] = req->GetHeader("Origin", "*");
  23. resp->headers["Access-Control-Allow-Methods"] = req->GetHeader("Access-Control-Request-Method", "OPTIONS, HEAD, GET, POST, PUT, DELETE, PATCH");
  24. resp->headers["Access-Control-Allow-Headers"] = req->GetHeader("Access-Control-Request-Headers", "Content-Type");
  25. return HTTP_STATUS_NO_CONTENT;
  26. }
  27. // Unified verification request Content-Type?
  28. // if (req->content_type != APPLICATION_JSON) {
  29. // return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  30. // }
  31. // Deserialize request body to json, form, etc.
  32. req->ParseBody();
  33. // Unified setting response Content-Type?
  34. resp->content_type = APPLICATION_JSON;
  35. #if 0
  36. // authentication sample code
  37. if (strcmp(req->path.c_str(), "/login") != 0) {
  38. string token = req->GetHeader("token");
  39. if (token.empty()) {
  40. response_status(resp, 10011, "Miss token");
  41. return HTTP_STATUS_UNAUTHORIZED;
  42. }
  43. else if (strcmp(token.c_str(), "abcdefg") != 0) {
  44. response_status(resp, 10012, "Token wrong");
  45. return HTTP_STATUS_UNAUTHORIZED;
  46. }
  47. return HTTP_STATUS_UNFINISHED;
  48. }
  49. #endif
  50. return HTTP_STATUS_UNFINISHED;
  51. }
  52. int Handler::postprocessor(HttpRequest* req, HttpResponse* resp) {
  53. // printf("%s\n", resp->Dump(true, true).c_str());
  54. return resp->status_code;
  55. }
  56. int Handler::errorHandler(const HttpContextPtr& ctx) {
  57. int error_code = ctx->response->status_code;
  58. return response_status(ctx, error_code);
  59. }
  60. int Handler::sleep(const HttpRequestPtr& req, const HttpResponseWriterPtr& writer) {
  61. writer->WriteHeader("X-Response-tid", hv_gettid());
  62. unsigned long long start_ms = gettimeofday_ms();
  63. writer->response->Set("start_ms", start_ms);
  64. std::string strTime = req->GetParam("t", "1000");
  65. if (!strTime.empty()) {
  66. int ms = atoi(strTime.c_str());
  67. if (ms > 0) {
  68. hv_delay(ms);
  69. }
  70. }
  71. unsigned long long end_ms = gettimeofday_ms();
  72. writer->response->Set("end_ms", end_ms);
  73. writer->response->Set("cost_ms", end_ms - start_ms);
  74. response_status(writer, 0, "OK");
  75. return 200;
  76. }
  77. int Handler::setTimeout(const HttpContextPtr& ctx) {
  78. unsigned long long start_ms = gettimeofday_ms();
  79. ctx->set("start_ms", start_ms);
  80. std::string strTime = ctx->param("t", "1000");
  81. if (!strTime.empty()) {
  82. int ms = atoi(strTime.c_str());
  83. if (ms > 0) {
  84. hv::setTimeout(ms, [ctx, start_ms](hv::TimerID timerID){
  85. unsigned long long end_ms = gettimeofday_ms();
  86. ctx->set("end_ms", end_ms);
  87. ctx->set("cost_ms", end_ms - start_ms);
  88. response_status(ctx, 0, "OK");
  89. });
  90. }
  91. }
  92. return HTTP_STATUS_UNFINISHED;
  93. }
  94. int Handler::query(const HttpContextPtr& ctx) {
  95. // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
  96. // ?query => HttpRequest::query_params
  97. for (auto& param : ctx->params()) {
  98. ctx->set(param.first.c_str(), param.second);
  99. }
  100. response_status(ctx, 0, "OK");
  101. return 200;
  102. }
  103. int Handler::kv(HttpRequest* req, HttpResponse* resp) {
  104. if (req->content_type != APPLICATION_URLENCODED) {
  105. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  106. }
  107. resp->content_type = APPLICATION_URLENCODED;
  108. resp->kv = req->GetUrlEncoded();
  109. resp->SetUrlEncoded("int", 123);
  110. resp->SetUrlEncoded("float", 3.14);
  111. resp->SetUrlEncoded("string", "hello");
  112. return 200;
  113. }
  114. int Handler::json(HttpRequest* req, HttpResponse* resp) {
  115. if (req->content_type != APPLICATION_JSON) {
  116. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  117. }
  118. resp->content_type = APPLICATION_JSON;
  119. resp->json = req->GetJson();
  120. resp->json["int"] = 123;
  121. resp->json["float"] = 3.14;
  122. resp->json["string"] = "hello";
  123. return 200;
  124. }
  125. int Handler::form(HttpRequest* req, HttpResponse* resp) {
  126. if (req->content_type != MULTIPART_FORM_DATA) {
  127. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  128. }
  129. resp->content_type = MULTIPART_FORM_DATA;
  130. resp->form = req->GetForm();
  131. resp->SetFormData("int", 123);
  132. resp->SetFormData("float", 3.14);
  133. resp->SetFormData("string", "hello");
  134. // resp->SetFormFile("file", "test.jpg");
  135. return 200;
  136. }
  137. int Handler::grpc(HttpRequest* req, HttpResponse* resp) {
  138. if (req->content_type != APPLICATION_GRPC) {
  139. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  140. }
  141. // parse protobuf
  142. // ParseFromString(req->body);
  143. // resp->content_type = APPLICATION_GRPC;
  144. // serailize protobuf
  145. // resp->body = SerializeAsString(xxx);
  146. response_status(resp, 0, "OK");
  147. return 200;
  148. }
  149. int Handler::test(const HttpContextPtr& ctx) {
  150. ctx->setContentType(ctx->type());
  151. ctx->set("bool", ctx->get<bool>("bool"));
  152. ctx->set("int", ctx->get<int>("int"));
  153. ctx->set("float", ctx->get<float>("float"));
  154. ctx->set("string", ctx->get("string"));
  155. response_status(ctx, 0, "OK");
  156. return 200;
  157. }
  158. int Handler::restful(const HttpContextPtr& ctx) {
  159. // RESTful /:field/ => HttpRequest::query_params
  160. // path=/group/:group_name/user/:user_id
  161. std::string group_name = ctx->param("group_name");
  162. std::string user_id = ctx->param("user_id");
  163. ctx->set("group_name", group_name);
  164. ctx->set("user_id", user_id);
  165. response_status(ctx, 0, "OK");
  166. return 200;
  167. }
  168. int Handler::login(const HttpContextPtr& ctx) {
  169. std::string username = ctx->get("username");
  170. std::string password = ctx->get("password");
  171. if (username.empty() || password.empty()) {
  172. response_status(ctx, 10001, "Miss username or password");
  173. return HTTP_STATUS_BAD_REQUEST;
  174. }
  175. else if (strcmp(username.c_str(), "admin") != 0) {
  176. response_status(ctx, 10002, "Username not exist");
  177. return HTTP_STATUS_BAD_REQUEST;
  178. }
  179. else if (strcmp(password.c_str(), "123456") != 0) {
  180. response_status(ctx, 10003, "Password wrong");
  181. return HTTP_STATUS_BAD_REQUEST;
  182. }
  183. else {
  184. ctx->set("token", "abcdefg");
  185. response_status(ctx, 0, "OK");
  186. return HTTP_STATUS_OK;
  187. }
  188. }
  189. int Handler::upload(const HttpContextPtr& ctx) {
  190. int status_code = 200;
  191. std::string save_path = "html/uploads/";
  192. if (ctx->is(MULTIPART_FORM_DATA)) {
  193. status_code = ctx->request->SaveFormFile("file", save_path.c_str());
  194. } else {
  195. std::string filename = ctx->param("filename", "unnamed.txt");
  196. std::string filepath = save_path + filename;
  197. status_code = ctx->request->SaveFile(filepath.c_str());
  198. }
  199. return response_status(ctx, status_code);
  200. }
  201. int Handler::recvLargeFile(const HttpContextPtr& ctx, http_parser_state state, const char* data, size_t size) {
  202. // printf("recvLargeFile state=%d\n", (int)state);
  203. int status_code = HTTP_STATUS_UNFINISHED;
  204. HFile* file = (HFile*)ctx->userdata;
  205. switch (state) {
  206. case HP_HEADERS_COMPLETE:
  207. {
  208. if (ctx->is(MULTIPART_FORM_DATA)) {
  209. // NOTE: You can use multipart_parser if you want to use multipart/form-data.
  210. ctx->close();
  211. return HTTP_STATUS_BAD_REQUEST;
  212. }
  213. std::string save_path = "html/uploads/";
  214. std::string filename = ctx->param("filename", "unnamed.txt");
  215. std::string filepath = save_path + filename;
  216. file = new HFile;
  217. if (file->open(filepath.c_str(), "wb") != 0) {
  218. ctx->close();
  219. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  220. }
  221. ctx->userdata = file;
  222. }
  223. break;
  224. case HP_BODY:
  225. {
  226. if (file && data && size) {
  227. if (file->write(data, size) != size) {
  228. ctx->close();
  229. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  230. }
  231. }
  232. }
  233. break;
  234. case HP_MESSAGE_COMPLETE:
  235. {
  236. status_code = HTTP_STATUS_OK;
  237. ctx->setContentType(APPLICATION_JSON);
  238. response_status(ctx, status_code);
  239. if (file) {
  240. delete file;
  241. ctx->userdata = NULL;
  242. }
  243. }
  244. break;
  245. case HP_ERROR:
  246. {
  247. if (file) {
  248. file->remove();
  249. delete file;
  250. ctx->userdata = NULL;
  251. }
  252. }
  253. break;
  254. default:
  255. break;
  256. }
  257. return status_code;
  258. }
  259. int Handler::sendLargeFile(const HttpContextPtr& ctx) {
  260. std::thread([ctx](){
  261. ctx->writer->Begin();
  262. std::string filepath = ctx->service->document_root + ctx->request->Path();
  263. HFile file;
  264. if (file.open(filepath.c_str(), "rb") != 0) {
  265. ctx->writer->WriteStatus(HTTP_STATUS_NOT_FOUND);
  266. ctx->writer->WriteHeader("Content-Type", "text/html");
  267. ctx->writer->WriteBody("<center><h1>404 Not Found</h1></center>");
  268. ctx->writer->End();
  269. return;
  270. }
  271. http_content_type content_type = CONTENT_TYPE_NONE;
  272. const char* suffix = hv_suffixname(filepath.c_str());
  273. if (suffix) {
  274. content_type = http_content_type_enum_by_suffix(suffix);
  275. }
  276. if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) {
  277. content_type = APPLICATION_OCTET_STREAM;
  278. }
  279. size_t filesize = file.size();
  280. ctx->writer->WriteHeader("Content-Type", http_content_type_str(content_type));
  281. #if USE_TRANSFER_ENCODING_CHUNKED
  282. ctx->writer->WriteHeader("Transfer-Encoding", "chunked");
  283. #else
  284. ctx->writer->WriteHeader("Content-Length", filesize);
  285. #endif
  286. ctx->writer->EndHeaders();
  287. char* buf = NULL;
  288. int len = 40960; // 40K
  289. SAFE_ALLOC(buf, len);
  290. size_t total_readbytes = 0;
  291. int last_progress = 0;
  292. int sleep_ms_per_send = 0;
  293. if (ctx->service->limit_rate <= 0) {
  294. // unlimited
  295. } else {
  296. sleep_ms_per_send = len * 1000 / 1024 / ctx->service->limit_rate;
  297. }
  298. if (sleep_ms_per_send == 0) sleep_ms_per_send = 1;
  299. int sleep_ms = sleep_ms_per_send;
  300. auto start_time = std::chrono::steady_clock::now();
  301. auto end_time = start_time;
  302. while (total_readbytes < filesize) {
  303. if (!ctx->writer->isConnected()) {
  304. break;
  305. }
  306. if (!ctx->writer->isWriteComplete()) {
  307. hv_delay(1);
  308. continue;
  309. }
  310. size_t readbytes = file.read(buf, len);
  311. if (readbytes <= 0) {
  312. // read file error!
  313. ctx->writer->close();
  314. break;
  315. }
  316. int nwrite = ctx->writer->WriteBody(buf, readbytes);
  317. if (nwrite < 0) {
  318. // disconnected!
  319. break;
  320. }
  321. total_readbytes += readbytes;
  322. int cur_progress = total_readbytes * 100 / filesize;
  323. if (cur_progress > last_progress) {
  324. // printf("<< %s progress: %ld/%ld = %d%%\n",
  325. // ctx->request->path.c_str(), (long)total_readbytes, (long)filesize, (int)cur_progress);
  326. last_progress = cur_progress;
  327. }
  328. end_time += std::chrono::milliseconds(sleep_ms);
  329. std::this_thread::sleep_until(end_time);
  330. }
  331. ctx->writer->End();
  332. SAFE_FREE(buf);
  333. // auto elapsed_time = std::chrono::duration_cast<std::chrono::seconds>(end_time - start_time);
  334. // printf("<< %s taked %ds\n", ctx->request->path.c_str(), (int)elapsed_time.count());
  335. }).detach();
  336. return HTTP_STATUS_UNFINISHED;
  337. }
  338. int Handler::sse(const HttpContextPtr& ctx) {
  339. // SSEvent(message) every 1s
  340. hv::setInterval(1000, [ctx](hv::TimerID timerID) {
  341. if (ctx->writer->isConnected()) {
  342. char szTime[DATETIME_FMT_BUFLEN] = {0};
  343. datetime_t now = datetime_now();
  344. datetime_fmt(&now, szTime);
  345. ctx->writer->SSEvent(szTime);
  346. } else {
  347. hv::killTimer(timerID);
  348. }
  349. });
  350. return HTTP_STATUS_UNFINISHED;
  351. }