1
0

httpServer.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  1. #include "httpServer.hpp"
  2. #include <chrono>
  3. #include <string>
  4. #include <system_error>
  5. #include <thread>
  6. namespace cpr {
  7. std::string HttpServer::GetBaseUrl() {
  8. return "http://127.0.0.1:" + std::to_string(GetPort());
  9. }
  10. uint16_t HttpServer::GetPort() {
  11. // Unassigned port number in the ephemeral range
  12. return 61936;
  13. }
  14. mg_connection* HttpServer::initServer(mg_mgr* mgr, mg_event_handler_t event_handler) {
  15. // Based on: https://mongoose.ws/tutorials/http-server/
  16. mg_mgr_init(mgr);
  17. std::string port = std::to_string(GetPort());
  18. mg_connection* c = mg_http_listen(mgr, GetBaseUrl().c_str(), event_handler, this);
  19. if (!c) {
  20. throw std::system_error(errno, std::system_category(), "Failed to listen at port " + port);
  21. }
  22. return c;
  23. }
  24. void HttpServer::acceptConnection(mg_connection* /* conn */) {}
  25. void HttpServer::OnRequestHello(mg_connection* conn, mg_http_message* msg) {
  26. if (std::string{msg->method.ptr, msg->method.len} == std::string{"OPTIONS"}) {
  27. OnRequestOptions(conn, msg);
  28. } else {
  29. std::string response{"Hello world!"};
  30. std::string headers = "Content-Type: text/html\r\n";
  31. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  32. }
  33. }
  34. void HttpServer::OnRequestRoot(mg_connection* conn, mg_http_message* msg) {
  35. if (std::string{msg->method.ptr, msg->method.len} == std::string{"OPTIONS"}) {
  36. OnRequestOptions(conn, msg);
  37. } else {
  38. std::string errorMessage{"Method Not Allowed"};
  39. SendError(conn, 405, errorMessage);
  40. }
  41. }
  42. void HttpServer::OnRequestNotFound(mg_connection* conn, mg_http_message* msg) {
  43. if (std::string{msg->method.ptr, msg->method.len} == std::string{"OPTIONS"}) {
  44. OnRequestOptions(conn, msg);
  45. } else {
  46. std::string errorMessage{"Not Found"};
  47. SendError(conn, 404, errorMessage);
  48. }
  49. }
  50. void HttpServer::OnRequestOptions(mg_connection* conn, mg_http_message* /*msg*/) {
  51. std::string headers =
  52. "Content-Type: text/plain\r\n"
  53. "Access-Control-Allow-Origin: *\r\n"
  54. "Access-Control-Allow-Credentials: true\r\n"
  55. "Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS\r\n"
  56. "Access-Control-Max-Age: 3600\r\n";
  57. std::string response;
  58. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  59. }
  60. void HttpServer::OnRequestTimeout(mg_connection* conn, mg_http_message* msg) {
  61. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  62. OnRequestHello(conn, msg);
  63. }
  64. void HttpServer::OnRequestLongTimeout(mg_connection* conn, mg_http_message* msg) {
  65. std::this_thread::sleep_for(std::chrono::seconds(2));
  66. OnRequestHello(conn, msg);
  67. }
  68. // Send the header, then send "Hello world!" every 100ms
  69. // For this, we use a mongoose timer
  70. void HttpServer::OnRequestLowSpeedTimeout(mg_connection* conn, mg_http_message* /* msg */, TimerArg* timer_arg) {
  71. std::string response{"Hello world!"};
  72. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n", response.length() * 20);
  73. timer_arg->connection_id = conn->id;
  74. mg_timer_init(
  75. &timer_arg->mgr->timers, &timer_arg->timer, 100, MG_TIMER_REPEAT,
  76. // The following lambda function gets executed each time the timer is called.
  77. // It sends "Hello world!" to the client each 100ms at most 20 times.
  78. [](void* arg) {
  79. TimerArg* timer_arg = static_cast<TimerArg*>(arg);
  80. if (timer_arg->counter < 20 && IsConnectionActive(timer_arg->mgr, timer_arg->connection) && timer_arg->connection->id == timer_arg->connection_id) {
  81. std::string response{"Hello world!"};
  82. mg_send(timer_arg->connection, response.c_str(), response.length());
  83. ++timer_arg->counter;
  84. } else {
  85. timer_arg->counter = 20; // Make sure that this timer is never called again
  86. }
  87. },
  88. timer_arg);
  89. }
  90. // Before and after calling an endpoint that calls this method, the test needs to wait until all previous connections are closed
  91. // The nested call to mg_mgr_poll can lead to problems otherwise
  92. void HttpServer::OnRequestLowSpeed(mg_connection* conn, mg_http_message* /*msg*/, mg_mgr* mgr) {
  93. std::string response{"Hello world!"};
  94. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n", response.length());
  95. mg_timer_add(
  96. mgr, 2000, MG_TIMER_ONCE,
  97. [](void* connection) {
  98. std::string response{"Hello world!"};
  99. mg_send(static_cast<mg_connection*>(connection), response.c_str(), response.length());
  100. },
  101. conn);
  102. }
  103. // Before and after calling an endpoint that calls this method, the test needs to wait until all previous connections are closed
  104. // The nested call to mg_mgr_poll can lead to problems otherwise
  105. void HttpServer::OnRequestLowSpeedBytes(mg_connection* conn, mg_http_message* /*msg*/, TimerArg* timer_arg) {
  106. std::string response{'a'};
  107. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n", response.length() * 20);
  108. mg_timer_init(
  109. &timer_arg->mgr->timers, &timer_arg->timer, 100, MG_TIMER_REPEAT,
  110. // The following lambda function gets executed each time the timer is called.
  111. // It first waits for 2 seconds, then sends "a" to the client each 100ms at most 20 times.
  112. [](void* arg) {
  113. TimerArg* timer_arg = static_cast<TimerArg*>(arg);
  114. if (timer_arg->counter == 0) {
  115. std::this_thread::sleep_for(std::chrono::seconds(2));
  116. }
  117. if (timer_arg->counter < 20 && IsConnectionActive(timer_arg->mgr, timer_arg->connection) && timer_arg->connection->id == timer_arg->connection_id) {
  118. std::string response{'a'};
  119. mg_send(timer_arg->connection, response.c_str(), response.length());
  120. ++timer_arg->counter;
  121. } else {
  122. timer_arg->counter = 20; // Make sure that this timer is never called again
  123. }
  124. },
  125. timer_arg);
  126. }
  127. void HttpServer::OnRequestBasicCookies(mg_connection* conn, mg_http_message* /*msg*/) {
  128. time_t expires_time = 3905119080; // Expires=Wed, 30 Sep 2093 03:18:00 GMT
  129. std::array<char, EXPIRES_STRING_SIZE> expires_string;
  130. std::strftime(expires_string.data(), expires_string.size(), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&expires_time));
  131. std::string cookie1{"SID=31d4d96e407aad42; Expires=" + std::string(expires_string.data()) + "; Secure"};
  132. std::string cookie2{"lang=en-US; Expires=" + std::string(expires_string.data()) + "; Secure"};
  133. std::string headers =
  134. "Content-Type: text/html\r\n"
  135. "Set-Cookie: " +
  136. cookie1 +
  137. "\r\n"
  138. "Set-Cookie: " +
  139. cookie2 + "\r\n";
  140. std::string response{"Basic Cookies"};
  141. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  142. }
  143. void HttpServer::OnRequestEmptyCookies(mg_connection* conn, mg_http_message* /*msg*/) {
  144. time_t expires_time = 3905119080; // Expires=Wed, 30 Sep 2093 03:18:00 GMT
  145. std::array<char, EXPIRES_STRING_SIZE> expires_string;
  146. std::strftime(expires_string.data(), sizeof(expires_string), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&expires_time));
  147. std::string cookie1{"SID=; Expires=" + std::string(expires_string.data()) + "; Secure"};
  148. std::string cookie2{"lang=; Expires=" + std::string(expires_string.data()) + "; Secure"};
  149. std::string headers =
  150. "Content-Type: text/html\r\n"
  151. "Set-Cookie: " +
  152. cookie1 +
  153. "\r\n"
  154. "Set-Cookie: " +
  155. cookie2 + "\r\n";
  156. std::string response{"Empty Cookies"};
  157. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  158. }
  159. void HttpServer::OnRequestCookiesReflect(mg_connection* conn, mg_http_message* msg) {
  160. mg_str* request_cookies;
  161. if ((request_cookies = mg_http_get_header(msg, "Cookie")) == nullptr) {
  162. std::string errorMessage{"Cookie not found"};
  163. SendError(conn, 400, errorMessage);
  164. return;
  165. }
  166. std::string cookie_str{request_cookies->ptr, request_cookies->len};
  167. std::string headers = "Content-Type: text/html\r\n";
  168. mg_http_reply(conn, 200, headers.c_str(), cookie_str.c_str());
  169. }
  170. void HttpServer::OnRequestRedirectionWithChangingCookies(mg_connection* conn, mg_http_message* msg) {
  171. time_t expires_time = 3905119080; // Expires=Wed, 30 Sep 2093 03:18:00 GMT
  172. std::array<char, EXPIRES_STRING_SIZE> expires_string;
  173. std::strftime(expires_string.data(), sizeof(expires_string), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&expires_time));
  174. mg_str* request_cookies;
  175. std::string cookie_str;
  176. if ((request_cookies = mg_http_get_header(msg, "Cookie")) != nullptr) {
  177. cookie_str = std::string{request_cookies->ptr, request_cookies->len};
  178. }
  179. if (cookie_str.find("SID=31d4d96e407aad42") == std::string::npos) {
  180. std::string cookie1{"SID=31d4d96e407aad42; Expires=" + std::string(expires_string.data()) + "; Secure"};
  181. std::string cookie2{"lang=en-US; Expires=" + std::string(expires_string.data()) + "; Secure"};
  182. std::string headers =
  183. "Content-Type: text/html\r\n"
  184. "Location: http://127.0.0.1:61936/redirection_with_changing_cookies.html\r\n"
  185. "Set-Cookie: " +
  186. cookie1 +
  187. "\r\n"
  188. "Set-Cookie: " +
  189. cookie2 + "\r\n";
  190. mg_http_reply(conn, 302, headers.c_str(), "");
  191. } else {
  192. cookie_str = "Received cookies are: " + cookie_str;
  193. std::string headers = "Content-Type: text/html\r\n";
  194. mg_http_reply(conn, 200, headers.c_str(), cookie_str.c_str());
  195. }
  196. }
  197. void HttpServer::OnRequestBasicAuth(mg_connection* conn, mg_http_message* msg) {
  198. mg_str* requested_auth;
  199. std::string auth{"Basic"};
  200. if ((requested_auth = mg_http_get_header(msg, "Authorization")) == nullptr || mg_ncasecmp(requested_auth->ptr, auth.c_str(), auth.length()) != 0) {
  201. std::string errorMessage{"Unauthorized"};
  202. SendError(conn, 401, errorMessage);
  203. return;
  204. }
  205. std::string auth_string{requested_auth->ptr, requested_auth->len};
  206. size_t basic_token = auth_string.find(' ') + 1;
  207. auth_string = auth_string.substr(basic_token, auth_string.length() - basic_token);
  208. auth_string = Base64Decode(auth_string);
  209. size_t colon = auth_string.find(':');
  210. std::string username = auth_string.substr(0, colon);
  211. std::string password = auth_string.substr(colon + 1, auth_string.length() - colon - 1);
  212. if (username == "user" && password == "password") {
  213. OnRequestHeaderReflect(conn, msg);
  214. } else {
  215. std::string errorMessage{"Unauthorized"};
  216. SendError(conn, 401, errorMessage);
  217. }
  218. }
  219. void HttpServer::OnRequestBearerAuth(mg_connection* conn, mg_http_message* msg) {
  220. mg_str* requested_auth;
  221. std::string auth{"Bearer"};
  222. if ((requested_auth = mg_http_get_header(msg, "Authorization")) == nullptr || mg_ncasecmp(requested_auth->ptr, auth.c_str(), auth.length()) != 0) {
  223. std::string errorMessage{"Unauthorized"};
  224. SendError(conn, 401, errorMessage);
  225. return;
  226. }
  227. std::string auth_string{requested_auth->ptr, requested_auth->len};
  228. size_t basic_token = auth_string.find(' ') + 1;
  229. auth_string = auth_string.substr(basic_token, auth_string.length() - basic_token);
  230. if (auth_string == "the_token") {
  231. OnRequestHeaderReflect(conn, msg);
  232. } else {
  233. std::string errorMessage{"Unauthorized"};
  234. SendError(conn, 401, errorMessage);
  235. }
  236. }
  237. void HttpServer::OnRequestBasicJson(mg_connection* conn, mg_http_message* /*msg*/) {
  238. std::string response =
  239. "[\n"
  240. " {\n"
  241. " \"first_key\": \"first_value\",\n"
  242. " \"second_key\": \"second_value\"\n"
  243. " }\n"
  244. "]";
  245. std::string headers = "Content-Type: application/json\r\n";
  246. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  247. }
  248. void HttpServer::OnRequestHeaderReflect(mg_connection* conn, mg_http_message* msg) {
  249. std::string response = "Header reflect " + std::string{msg->method.ptr, msg->method.len};
  250. std::string headers;
  251. bool hasContentTypeHeader = false;
  252. for (const mg_http_header& header : msg->headers) {
  253. if (!header.name.ptr) {
  254. continue;
  255. }
  256. std::string name = std::string(header.name.ptr, header.name.len);
  257. if (std::string{"Content-Type"} == name) {
  258. hasContentTypeHeader = true;
  259. }
  260. if (std::string{"Host"} != name && std::string{"Accept"} != name) {
  261. if (header.value.ptr) {
  262. headers.append(name + ": " + std::string(header.value.ptr, header.value.len) + "\r\n");
  263. }
  264. }
  265. }
  266. if (!hasContentTypeHeader) {
  267. headers.append("Content-Type: text/html\r\n");
  268. }
  269. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  270. }
  271. void HttpServer::OnRequestTempRedirect(mg_connection* conn, mg_http_message* msg) {
  272. // Get the requested target location:
  273. std::string location;
  274. for (mg_http_header& header : msg->headers) {
  275. if (!header.name.ptr) {
  276. continue;
  277. }
  278. std::string name = std::string(header.name.ptr, header.name.len);
  279. if (std::string{"RedirectLocation"} == name) {
  280. location = std::string(header.value.ptr, header.value.len);
  281. break;
  282. }
  283. }
  284. // Check if the request contains a valid location, else default to 'hello.html':
  285. if (location.empty()) {
  286. location = "hello.html";
  287. }
  288. std::string headers = "Location: " + location + "\r\n";
  289. std::string response = "Moved Temporarily";
  290. mg_http_reply(conn, 302, headers.c_str(), response.c_str());
  291. }
  292. void HttpServer::OnRequestPermRedirect(mg_connection* conn, mg_http_message* msg) {
  293. // Get the requested target location:
  294. std::string location;
  295. for (mg_http_header& header : msg->headers) {
  296. if (!header.name.ptr) {
  297. continue;
  298. }
  299. std::string name = std::string(header.name.ptr, header.name.len);
  300. if (std::string{"RedirectLocation"} == name) {
  301. location = std::string(header.value.ptr, header.value.len);
  302. break;
  303. }
  304. }
  305. // Check if the request contains a valid location, else default to 'hello.html':
  306. if (location.empty()) {
  307. location = "hello.html";
  308. }
  309. std::string headers = "Location: " + location + "\r\n";
  310. std::string response = "Moved Permanently";
  311. mg_http_reply(conn, 301, headers.c_str(), response.c_str());
  312. }
  313. void HttpServer::OnRequestResolvePermRedirect(mg_connection* conn, mg_http_message* msg) {
  314. // Get the requested target location:
  315. std::string location;
  316. for (mg_http_header& header : msg->headers) {
  317. if (!header.name.ptr) {
  318. continue;
  319. }
  320. std::string name = std::string(header.name.ptr, header.name.len);
  321. if (std::string{"RedirectLocation"} == name) {
  322. location = std::string(header.value.ptr, header.value.len);
  323. break;
  324. }
  325. }
  326. if(location.empty()) {
  327. std::string errorMessage{"Redirect location missing"};
  328. SendError(conn, 405, errorMessage);
  329. return;
  330. }
  331. std::string headers = "Location: " + location + "\r\n";
  332. std::string response = "Moved Permanently";
  333. mg_http_reply(conn, 301, headers.c_str(), response.c_str());
  334. }
  335. void HttpServer::OnRequestTwoRedirects(mg_connection* conn, mg_http_message* /*msg*/) {
  336. std::string response = "Moved Permanently";
  337. std::string headers = "Location: permanent_redirect.html\r\n";
  338. mg_http_reply(conn, 301, headers.c_str(), response.c_str());
  339. }
  340. void HttpServer::OnRequestUrlPost(mg_connection* conn, mg_http_message* msg) {
  341. if (std::string{msg->method.ptr, msg->method.len} != std::string{"POST"}) {
  342. std::string errorMessage{"Method Not Allowed"};
  343. SendError(conn, 405, errorMessage);
  344. return;
  345. }
  346. std::string headers = "Content-Type: application/json\r\n";
  347. char x[100];
  348. char y[100];
  349. mg_http_get_var(&(msg->body), "x", x, sizeof(x));
  350. mg_http_get_var(&(msg->body), "y", y, sizeof(y));
  351. std::string x_string{x};
  352. std::string y_string{y};
  353. std::string response;
  354. if (y_string.empty()) {
  355. response = std::string{
  356. "{\n"
  357. " \"x\": " +
  358. x_string +
  359. "\n"
  360. "}"};
  361. } else {
  362. response = std::string{
  363. "{\n"
  364. " \"x\": " +
  365. x_string +
  366. ",\n"
  367. " \"y\": " +
  368. y_string +
  369. ",\n"
  370. " \"sum\": " +
  371. std::to_string(atoi(x) + atoi(y)) +
  372. "\n"
  373. "}"};
  374. }
  375. mg_http_reply(conn, 201, headers.c_str(), response.c_str());
  376. }
  377. void HttpServer::OnRequestBodyGet(mg_connection* conn, mg_http_message* msg) {
  378. if (std::string{msg->method.ptr, msg->method.len} != std::string{"GET"}) {
  379. std::string errorMessage{"Method Not Allowed"};
  380. SendError(conn, 405, errorMessage);
  381. return;
  382. }
  383. std::array<char, 100> message{};
  384. mg_http_get_var(&(msg->body), "message", message.data(), message.size());
  385. if (msg->body.len <= 0) {
  386. std::string errorMessage{"No Content"};
  387. SendError(conn, 405, errorMessage);
  388. return;
  389. }
  390. std::string response = message.data();
  391. std::string headers = "Content-Type: text/html\r\n";
  392. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  393. }
  394. void HttpServer::OnRequestJsonPost(mg_connection* conn, mg_http_message* msg) {
  395. mg_str* content_type{nullptr};
  396. if ((content_type = mg_http_get_header(msg, "Content-Type")) == nullptr || std::string{content_type->ptr, content_type->len} != "application/json") {
  397. std::string errorMessage{"Unsupported Media Type"};
  398. SendError(conn, 415, errorMessage);
  399. return;
  400. }
  401. std::string headers = "Content-Type: application/json\r\n";
  402. mg_http_reply(conn, 201, headers.c_str(), msg->body.ptr);
  403. }
  404. void HttpServer::OnRequestFormPost(mg_connection* conn, mg_http_message* msg) {
  405. size_t pos{0};
  406. mg_http_part part{};
  407. std::string headers = "Content-Type: application/json\r\n";
  408. std::string response{};
  409. response += "{\n";
  410. while ((pos = mg_http_next_multipart(msg->body, pos, &part)) > 0) {
  411. response += " \"" + std::string(part.name.ptr, part.name.len) + "\": \"";
  412. if (!std::string(part.filename.ptr, part.filename.len).empty()) {
  413. response += std::string(part.filename.ptr, part.filename.len) + "=";
  414. }
  415. response += std::string(part.body.ptr, part.body.len) + "\",\n";
  416. }
  417. response.erase(response.find_last_not_of(",\n") + 1);
  418. response += "\n}";
  419. mg_http_reply(conn, 201, headers.c_str(), response.c_str());
  420. }
  421. void HttpServer::OnRequestDelete(mg_connection* conn, mg_http_message* msg) {
  422. bool has_json_header = false;
  423. for (mg_http_header& header : msg->headers) {
  424. if (!header.name.ptr) {
  425. continue;
  426. }
  427. std::string name = std::string(header.name.ptr, header.name.len);
  428. std::string value = std::string(header.value.ptr, header.value.len);
  429. if (std::string{"Content-Type"} == name && std::string{"application/json"} == value) {
  430. has_json_header = true;
  431. break;
  432. }
  433. }
  434. if (std::string{msg->method.ptr, msg->method.len} == std::string{"DELETE"}) {
  435. std::string headers;
  436. std::string response = "Patch success";
  437. if (!has_json_header) {
  438. headers = "Content-Type: text/html\r\n";
  439. response = "Delete success";
  440. } else {
  441. headers = "Content-Type: application/json\r\n";
  442. response = std::string{msg->body.ptr, msg->body.len};
  443. }
  444. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  445. } else {
  446. std::string errorMessage{"Method Not Allowed"};
  447. SendError(conn, 405, errorMessage);
  448. }
  449. }
  450. void HttpServer::OnRequestDeleteNotAllowed(mg_connection* conn, mg_http_message* msg) {
  451. if (std::string{msg->method.ptr, msg->method.len} == std::string{"DELETE"}) {
  452. std::string errorMessage{"Method Not Allowed"};
  453. SendError(conn, 405, errorMessage);
  454. } else {
  455. std::string headers = "Content-Type: text/html\r\n";
  456. std::string response = "Delete success";
  457. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  458. }
  459. }
  460. void HttpServer::OnRequestPut(mg_connection* conn, mg_http_message* msg) {
  461. if (std::string{msg->method.ptr, msg->method.len} == std::string{"PUT"}) {
  462. char x[100];
  463. char y[100];
  464. mg_http_get_var(&(msg->body), "x", x, sizeof(x));
  465. mg_http_get_var(&(msg->body), "y", y, sizeof(y));
  466. std::string x_string = std::string{x};
  467. std::string y_string = std::string{y};
  468. std::string headers = "Content-Type: application/json\r\n";
  469. std::string response;
  470. if (y_string.empty()) {
  471. response = std::string{
  472. "{\n"
  473. " \"x\": " +
  474. x_string +
  475. "\n"
  476. "}"};
  477. } else {
  478. response = std::string{
  479. "{\n"
  480. " \"x\": " +
  481. x_string +
  482. ",\n"
  483. " \"y\": " +
  484. y_string +
  485. ",\n"
  486. " \"sum\": " +
  487. std::to_string(atoi(x) + atoi(y)) +
  488. "\n"
  489. "}"};
  490. }
  491. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  492. } else {
  493. std::string errorMessage{"Method Not Allowed"};
  494. SendError(conn, 405, errorMessage);
  495. }
  496. }
  497. void HttpServer::OnRequestPostReflect(mg_connection* conn, mg_http_message* msg) {
  498. if (std::string{msg->method.ptr, msg->method.len} != std::string{"POST"}) {
  499. std::string errorMessage{"Method Not Allowed"};
  500. SendError(conn, 405, errorMessage);
  501. }
  502. std::string response = std::string{msg->body.ptr, msg->body.len};
  503. std::string headers;
  504. for (mg_http_header& header : msg->headers) {
  505. if (!header.name.ptr) {
  506. continue;
  507. }
  508. std::string name{header.name.ptr, header.name.len};
  509. if (std::string{"Host"} != name && std::string{"Accept"} != name) {
  510. if (header.value.ptr) {
  511. headers.append(name + ": " + std::string(header.value.ptr, header.value.len) + "\r\n");
  512. }
  513. }
  514. }
  515. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  516. }
  517. void HttpServer::OnRequestPutNotAllowed(mg_connection* conn, mg_http_message* msg) {
  518. if (std::string{msg->method.ptr, msg->method.len} == std::string{"PUT"}) {
  519. std::string errorMessage{"Method Not Allowed"};
  520. SendError(conn, 405, errorMessage);
  521. } else {
  522. std::string headers = "Content-Type: text/html\r\n";
  523. std::string response = "Delete success";
  524. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  525. }
  526. }
  527. void HttpServer::OnRequestPatch(mg_connection* conn, mg_http_message* msg) {
  528. if (std::string{msg->method.ptr, msg->method.len} == std::string{"PATCH"}) {
  529. char x[100];
  530. char y[100];
  531. mg_http_get_var(&(msg->body), "x", x, sizeof(x));
  532. mg_http_get_var(&(msg->body), "y", y, sizeof(y));
  533. std::string x_string = std::string{x};
  534. std::string y_string = std::string{y};
  535. std::string headers = "Content-Type: application/json\r\n";
  536. std::string response;
  537. if (y_string.empty()) {
  538. response = std::string{
  539. "{\n"
  540. " \"x\": " +
  541. x_string +
  542. "\n"
  543. "}"};
  544. } else {
  545. response = std::string{
  546. "{\n"
  547. " \"x\": " +
  548. x_string +
  549. ",\n"
  550. " \"y\": " +
  551. y_string +
  552. ",\n"
  553. " \"sum\": " +
  554. std::to_string(atoi(x) + atoi(y)) +
  555. "\n"
  556. "}"};
  557. }
  558. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  559. } else {
  560. std::string errorMessage{"Method Not Allowed"};
  561. SendError(conn, 405, errorMessage);
  562. }
  563. }
  564. void HttpServer::OnRequestPatchNotAllowed(mg_connection* conn, mg_http_message* msg) {
  565. if (std::string{msg->method.ptr, msg->method.len} == std::string{"PATCH"}) {
  566. std::string errorMessage{"Method Not Allowed"};
  567. SendError(conn, 405, errorMessage);
  568. } else {
  569. std::string headers = "Content-Type: text/html\r\n";
  570. std::string response = "Delete success";
  571. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  572. }
  573. }
  574. void HttpServer::OnRequestDownloadGzip(mg_connection* conn, mg_http_message* msg) {
  575. if (std::string{msg->method.ptr, msg->method.len} == std::string{"DOWNLOAD"}) {
  576. std::string errorMessage{"Method Not Allowed"};
  577. SendError(conn, 405, errorMessage);
  578. } else {
  579. std::string encoding;
  580. std::string range;
  581. std::vector<std::pair<int64_t, int64_t>> ranges;
  582. for (mg_http_header& header : msg->headers) {
  583. if (!header.name.ptr) {
  584. continue;
  585. }
  586. std::string name = std::string(header.name.ptr, header.name.len);
  587. if (std::string{"Accept-Encoding"} == name) {
  588. encoding = std::string(header.value.ptr, header.value.len);
  589. } else if (std::string{"Range"} == name) {
  590. range = std::string(header.value.ptr, header.value.len);
  591. }
  592. }
  593. if (encoding.find("gzip") == std::string::npos) {
  594. std::string errorMessage{"Invalid encoding: " + encoding};
  595. SendError(conn, 405, errorMessage);
  596. return;
  597. }
  598. if (!range.empty()) {
  599. std::string::size_type eq_pos = range.find('=');
  600. if (eq_pos == std::string::npos) {
  601. std::string errorMessage{"Invalid range header: " + range};
  602. SendError(conn, 405, errorMessage);
  603. return;
  604. }
  605. int64_t current_start_index = eq_pos + 1;
  606. int64_t current_end_index;
  607. std::string::size_type range_len = range.length();
  608. std::string::size_type com_pos;
  609. std::string::size_type sep_pos;
  610. bool more_ranges_exists;
  611. do {
  612. com_pos = range.find(',', current_start_index);
  613. if (com_pos < range_len) {
  614. current_end_index = com_pos - 1;
  615. } else {
  616. current_end_index = range_len - 1;
  617. }
  618. std::pair<int64_t, int64_t> current_range{0, -1};
  619. sep_pos = range.find('-', current_start_index);
  620. if (sep_pos == std::string::npos) {
  621. std::string errorMessage{"Invalid range format " + range.substr(current_start_index, current_end_index)};
  622. SendError(conn, 405, errorMessage);
  623. return;
  624. }
  625. if (sep_pos == eq_pos + 1) {
  626. std::string errorMessage{"Suffix ranage not supported: " + range.substr(current_start_index, current_end_index)};
  627. SendError(conn, 405, errorMessage);
  628. return;
  629. }
  630. current_range.first = std::strtoll(range.substr(current_start_index, sep_pos - 1).c_str(), nullptr, 10);
  631. if (current_range.first == LLONG_MAX || current_range.first == LLONG_MIN) {
  632. std::string errorMessage{"Start range is invalid number: " + range.substr(current_start_index, current_end_index)};
  633. SendError(conn, 405, errorMessage);
  634. return;
  635. }
  636. std::string er_str = range.substr(sep_pos + 1, current_end_index);
  637. if (!er_str.empty()) {
  638. current_range.second = std::strtoll(er_str.c_str(), nullptr, 10);
  639. if (current_range.second == 0 || current_range.second == LLONG_MAX || current_range.second == LLONG_MIN) {
  640. std::string errorMessage{"End range is invalid number: " + range.substr(current_start_index, current_end_index)};
  641. SendError(conn, 405, errorMessage);
  642. return;
  643. }
  644. }
  645. ranges.push_back(current_range);
  646. if (current_end_index >= static_cast<int64_t>(range.length() - 1)) {
  647. more_ranges_exists = false;
  648. } else {
  649. // Multiple ranges are separated by ', '
  650. more_ranges_exists = true;
  651. current_start_index = current_end_index + 3;
  652. }
  653. } while (more_ranges_exists);
  654. }
  655. std::string response = "Download!";
  656. int status_code = 200;
  657. std::string headers;
  658. if (!ranges.empty()) {
  659. // Create response parts
  660. std::vector<std::string> responses;
  661. for (std::pair<int64_t, int64_t> local_range : ranges) {
  662. if (local_range.first >= 0) {
  663. if (local_range.first >= (int64_t) response.length()) {
  664. responses.push_back("");
  665. } else if (local_range.second == -1 || local_range.second >= (int64_t) response.length()) {
  666. responses.push_back(response.substr(local_range.first));
  667. } else {
  668. responses.push_back(response.substr(local_range.first, local_range.second - local_range.first + 1));
  669. }
  670. }
  671. }
  672. if (responses.size() > 1) {
  673. // Create mime multipart response
  674. std::string boundary = "3d6b6a416f9b5";
  675. status_code = 206;
  676. response.clear();
  677. for (size_t i{0}; i < responses.size(); ++i) {
  678. response += "--" + boundary + "\n";
  679. response += "Content-Range: bytes " + std::to_string(ranges.at(i).first) + "-";
  680. if (ranges.at(i).second > 0) {
  681. response += std::to_string(ranges.at(i).second);
  682. } else {
  683. response += std::to_string(responses.at(i).length());
  684. }
  685. response += "/" + std::to_string(responses.at(i).length()) + "\n\n";
  686. response += responses.at(i) + "\n";
  687. }
  688. response += "--" + boundary + "--";
  689. } else {
  690. if (ranges.at(0).second == -1 || ranges.at(0).second >= (int64_t) response.length()) {
  691. status_code = ranges.at(0).first > 0 ? 206 : 200;
  692. } else {
  693. status_code = 206;
  694. }
  695. response = responses.at(0);
  696. if (status_code == 206) {
  697. headers = "Content-Range: bytes " + std::to_string(ranges.at(0).first) + "-";
  698. if (ranges.at(0).second > 0) {
  699. headers += std::to_string(ranges.at(0).second);
  700. } else {
  701. headers += std::to_string(response.length());
  702. }
  703. headers += "/" + std::to_string(response.length());
  704. }
  705. }
  706. }
  707. if (!headers.empty()) {
  708. headers += "\r\n";
  709. }
  710. mg_http_reply(conn, status_code, headers.c_str(), response.c_str());
  711. }
  712. }
  713. void HttpServer::OnRequestCheckAcceptEncoding(mg_connection* conn, mg_http_message* msg) {
  714. std::string response;
  715. for (mg_http_header& header : msg->headers) {
  716. if (!header.name.ptr) {
  717. continue;
  718. }
  719. std::string name = std::string(header.name.ptr, header.name.len);
  720. if (std::string{"Accept-Encoding"} == name) {
  721. response = std::string(header.value.ptr, header.value.len);
  722. }
  723. }
  724. std::string headers = "Content-Type: text/html\r\n";
  725. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  726. }
  727. void HttpServer::OnRequestCheckExpect100Continue(mg_connection* conn, mg_http_message* msg) {
  728. std::string response;
  729. for (mg_http_header& header : msg->headers) {
  730. if (!header.name.ptr) {
  731. continue;
  732. }
  733. std::string name = std::string(header.name.ptr, header.name.len);
  734. if (std::string{"Expect"} == name) {
  735. response = std::string(header.value.ptr, header.value.len);
  736. }
  737. }
  738. std::string headers = "Content-Type: text/html\r\n";
  739. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  740. }
  741. void HttpServer::OnRequest(mg_connection* conn, mg_http_message* msg) {
  742. std::string uri = std::string(msg->uri.ptr, msg->uri.len);
  743. if (uri == "/") {
  744. OnRequestRoot(conn, msg);
  745. } else if (uri == "/hello.html") {
  746. OnRequestHello(conn, msg);
  747. } else if (uri == "/timeout.html") {
  748. OnRequestTimeout(conn, msg);
  749. } else if (uri == "/long_timeout.html") {
  750. OnRequestLongTimeout(conn, msg);
  751. } else if (uri == "/low_speed_timeout.html") {
  752. timer_args.emplace_back(std::make_unique<TimerArg>(&mgr, conn, mg_timer{}));
  753. OnRequestLowSpeedTimeout(conn, msg, timer_args.back().get());
  754. } else if (uri == "/low_speed.html") {
  755. OnRequestLowSpeed(conn, msg, &mgr);
  756. } else if (uri == "/low_speed_bytes.html") {
  757. timer_args.emplace_back(std::make_unique<TimerArg>(&mgr, conn, mg_timer{}));
  758. OnRequestLowSpeedBytes(conn, msg, timer_args.back().get());
  759. } else if (uri == "/basic_cookies.html") {
  760. OnRequestBasicCookies(conn, msg);
  761. } else if (uri == "/empty_cookies.html") {
  762. OnRequestEmptyCookies(conn, msg);
  763. } else if (uri == "/cookies_reflect.html") {
  764. OnRequestCookiesReflect(conn, msg);
  765. } else if (uri == "/redirection_with_changing_cookies.html") {
  766. OnRequestRedirectionWithChangingCookies(conn, msg);
  767. } else if (uri == "/basic_auth.html") {
  768. OnRequestBasicAuth(conn, msg);
  769. } else if (uri == "/bearer_token.html") {
  770. OnRequestBearerAuth(conn, msg);
  771. } else if (uri == "/digest_auth.html") {
  772. OnRequestHeaderReflect(conn, msg);
  773. } else if (uri == "/basic.json") {
  774. OnRequestBasicJson(conn, msg);
  775. } else if (uri == "/header_reflect.html") {
  776. OnRequestHeaderReflect(conn, msg);
  777. } else if (uri == "/temporary_redirect.html") {
  778. OnRequestTempRedirect(conn, msg);
  779. } else if (uri == "/permanent_redirect.html") {
  780. OnRequestPermRedirect(conn, msg);
  781. } else if (uri == "/resolve_permanent_redirect.html") {
  782. OnRequestResolvePermRedirect(conn, msg);
  783. } else if (uri == "/two_redirects.html") {
  784. OnRequestTwoRedirects(conn, msg);
  785. } else if (uri == "/url_post.html") {
  786. OnRequestUrlPost(conn, msg);
  787. } else if (uri == "/body_get.html") {
  788. OnRequestBodyGet(conn, msg);
  789. } else if (uri == "/json_post.html") {
  790. OnRequestJsonPost(conn, msg);
  791. } else if (uri == "/form_post.html") {
  792. OnRequestFormPost(conn, msg);
  793. } else if (uri == "/post_reflect.html") {
  794. OnRequestPostReflect(conn, msg);
  795. } else if (uri == "/delete.html") {
  796. OnRequestDelete(conn, msg);
  797. } else if (uri == "/delete_unallowed.html") {
  798. OnRequestDeleteNotAllowed(conn, msg);
  799. } else if (uri == "/put.html") {
  800. OnRequestPut(conn, msg);
  801. } else if (uri == "/put_unallowed.html") {
  802. OnRequestPutNotAllowed(conn, msg);
  803. } else if (uri == "/patch.html") {
  804. OnRequestPatch(conn, msg);
  805. } else if (uri == "/patch_unallowed.html") {
  806. OnRequestPatchNotAllowed(conn, msg);
  807. } else if (uri == "/download_gzip.html") {
  808. OnRequestDownloadGzip(conn, msg);
  809. } else if (uri == "/local_port.html") {
  810. OnRequestLocalPort(conn, msg);
  811. } else if (uri == "/check_accept_encoding.html") {
  812. OnRequestCheckAcceptEncoding(conn, msg);
  813. } else if (uri == "/check_expect_100_continue.html") {
  814. OnRequestCheckExpect100Continue(conn, msg);
  815. } else {
  816. OnRequestNotFound(conn, msg);
  817. }
  818. }
  819. void HttpServer::OnRequestLocalPort(mg_connection* conn, mg_http_message* /*msg*/) {
  820. // send source port number as response for checking SetLocalPort/SetLocalPortRange
  821. std::string headers = "Content-Type: text/plain\r\n";
  822. // Convert from big endian to little endian
  823. std::string response = std::to_string(AbstractServer::GetRemotePort(conn));
  824. mg_http_reply(conn, 200, headers.c_str(), response.c_str());
  825. }
  826. } // namespace cpr