CivetServer.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. /* Copyright (c) 2013-2017 the Civetweb developers
  2. * Copyright (c) 2013 No Face Press, LLC
  3. *
  4. * License http://opensource.org/licenses/mit-license.php MIT License
  5. */
  6. #include "CivetServer.h"
  7. #include <assert.h>
  8. #include <stdexcept>
  9. #include <string.h>
  10. #ifndef UNUSED_PARAMETER
  11. #define UNUSED_PARAMETER(x) (void)(x)
  12. #endif
  13. #ifndef MAX_PARAM_BODY_LENGTH
  14. // Set a default limit for parameters in a form body: 2 MB
  15. #define MAX_PARAM_BODY_LENGTH (1024 * 1024 * 2)
  16. #endif
  17. bool
  18. CivetHandler::handleGet(CivetServer *server, struct mg_connection *conn)
  19. {
  20. UNUSED_PARAMETER(server);
  21. UNUSED_PARAMETER(conn);
  22. return false;
  23. }
  24. bool
  25. CivetHandler::handlePost(CivetServer *server, struct mg_connection *conn)
  26. {
  27. UNUSED_PARAMETER(server);
  28. UNUSED_PARAMETER(conn);
  29. return false;
  30. }
  31. bool
  32. CivetHandler::handleHead(CivetServer *server, struct mg_connection *conn)
  33. {
  34. UNUSED_PARAMETER(server);
  35. UNUSED_PARAMETER(conn);
  36. return false;
  37. }
  38. bool
  39. CivetHandler::handlePut(CivetServer *server, struct mg_connection *conn)
  40. {
  41. UNUSED_PARAMETER(server);
  42. UNUSED_PARAMETER(conn);
  43. return false;
  44. }
  45. bool
  46. CivetHandler::handlePatch(CivetServer *server, struct mg_connection *conn)
  47. {
  48. UNUSED_PARAMETER(server);
  49. UNUSED_PARAMETER(conn);
  50. return false;
  51. }
  52. bool
  53. CivetHandler::handleDelete(CivetServer *server, struct mg_connection *conn)
  54. {
  55. UNUSED_PARAMETER(server);
  56. UNUSED_PARAMETER(conn);
  57. return false;
  58. }
  59. bool
  60. CivetHandler::handleOptions(CivetServer *server, struct mg_connection *conn)
  61. {
  62. UNUSED_PARAMETER(server);
  63. UNUSED_PARAMETER(conn);
  64. return false;
  65. }
  66. bool
  67. CivetWebSocketHandler::handleConnection(CivetServer *server,
  68. const struct mg_connection *conn)
  69. {
  70. UNUSED_PARAMETER(server);
  71. UNUSED_PARAMETER(conn);
  72. return true;
  73. }
  74. void
  75. CivetWebSocketHandler::handleReadyState(CivetServer *server,
  76. struct mg_connection *conn)
  77. {
  78. UNUSED_PARAMETER(server);
  79. UNUSED_PARAMETER(conn);
  80. return;
  81. }
  82. bool
  83. CivetWebSocketHandler::handleData(CivetServer *server,
  84. struct mg_connection *conn,
  85. int bits,
  86. char *data,
  87. size_t data_len)
  88. {
  89. UNUSED_PARAMETER(server);
  90. UNUSED_PARAMETER(conn);
  91. UNUSED_PARAMETER(bits);
  92. UNUSED_PARAMETER(data);
  93. UNUSED_PARAMETER(data_len);
  94. return true;
  95. }
  96. void
  97. CivetWebSocketHandler::handleClose(CivetServer *server,
  98. const struct mg_connection *conn)
  99. {
  100. UNUSED_PARAMETER(server);
  101. UNUSED_PARAMETER(conn);
  102. return;
  103. }
  104. int
  105. CivetServer::requestHandler(struct mg_connection *conn, void *cbdata)
  106. {
  107. const struct mg_request_info *request_info = mg_get_request_info(conn);
  108. assert(request_info != NULL);
  109. CivetServer *me = (CivetServer *)(request_info->user_data);
  110. assert(me != NULL);
  111. // Happens when a request hits the server before the context is saved
  112. if (me->context == NULL)
  113. return 0;
  114. mg_lock_context(me->context);
  115. me->connections[conn] = CivetConnection();
  116. mg_unlock_context(me->context);
  117. CivetHandler *handler = (CivetHandler *)cbdata;
  118. if (handler) {
  119. if (strcmp(request_info->request_method, "GET") == 0) {
  120. return handler->handleGet(me, conn) ? 1 : 0;
  121. } else if (strcmp(request_info->request_method, "POST") == 0) {
  122. return handler->handlePost(me, conn) ? 1 : 0;
  123. } else if (strcmp(request_info->request_method, "HEAD") == 0) {
  124. return handler->handleHead(me, conn) ? 1 : 0;
  125. } else if (strcmp(request_info->request_method, "PUT") == 0) {
  126. return handler->handlePut(me, conn) ? 1 : 0;
  127. } else if (strcmp(request_info->request_method, "DELETE") == 0) {
  128. return handler->handleDelete(me, conn) ? 1 : 0;
  129. } else if (strcmp(request_info->request_method, "OPTIONS") == 0) {
  130. return handler->handleOptions(me, conn) ? 1 : 0;
  131. } else if (strcmp(request_info->request_method, "PATCH") == 0) {
  132. return handler->handlePatch(me, conn) ? 1 : 0;
  133. }
  134. }
  135. return 0; // No handler found
  136. }
  137. int
  138. CivetServer::authHandler(struct mg_connection *conn, void *cbdata)
  139. {
  140. const struct mg_request_info *request_info = mg_get_request_info(conn);
  141. assert(request_info != NULL);
  142. CivetServer *me = (CivetServer *)(request_info->user_data);
  143. assert(me != NULL);
  144. // Happens when a request hits the server before the context is saved
  145. if (me->context == NULL)
  146. return 0;
  147. mg_lock_context(me->context);
  148. me->connections[conn] = CivetConnection();
  149. mg_unlock_context(me->context);
  150. CivetAuthHandler *handler = (CivetAuthHandler *)cbdata;
  151. if (handler) {
  152. return handler->authorize(me, conn) ? 1 : 0;
  153. }
  154. return 0; // No handler found
  155. }
  156. int
  157. CivetServer::webSocketConnectionHandler(const struct mg_connection *conn,
  158. void *cbdata)
  159. {
  160. const struct mg_request_info *request_info = mg_get_request_info(conn);
  161. assert(request_info != NULL);
  162. CivetServer *me = (CivetServer *)(request_info->user_data);
  163. assert(me != NULL);
  164. // Happens when a request hits the server before the context is saved
  165. if (me->context == NULL)
  166. return 0;
  167. CivetWebSocketHandler *handler = (CivetWebSocketHandler *)cbdata;
  168. if (handler) {
  169. return handler->handleConnection(me, conn) ? 0 : 1;
  170. }
  171. return 1; // No handler found, close connection
  172. }
  173. void
  174. CivetServer::webSocketReadyHandler(struct mg_connection *conn, void *cbdata)
  175. {
  176. const struct mg_request_info *request_info = mg_get_request_info(conn);
  177. assert(request_info != NULL);
  178. CivetServer *me = (CivetServer *)(request_info->user_data);
  179. assert(me != NULL);
  180. // Happens when a request hits the server before the context is saved
  181. if (me->context == NULL)
  182. return;
  183. CivetWebSocketHandler *handler = (CivetWebSocketHandler *)cbdata;
  184. if (handler) {
  185. handler->handleReadyState(me, conn);
  186. }
  187. }
  188. int
  189. CivetServer::webSocketDataHandler(struct mg_connection *conn,
  190. int bits,
  191. char *data,
  192. size_t data_len,
  193. void *cbdata)
  194. {
  195. const struct mg_request_info *request_info = mg_get_request_info(conn);
  196. assert(request_info != NULL);
  197. CivetServer *me = (CivetServer *)(request_info->user_data);
  198. assert(me != NULL);
  199. // Happens when a request hits the server before the context is saved
  200. if (me->context == NULL)
  201. return 0;
  202. CivetWebSocketHandler *handler = (CivetWebSocketHandler *)cbdata;
  203. if (handler) {
  204. return handler->handleData(me, conn, bits, data, data_len) ? 1 : 0;
  205. }
  206. return 1; // No handler found
  207. }
  208. void
  209. CivetServer::webSocketCloseHandler(const struct mg_connection *conn,
  210. void *cbdata)
  211. {
  212. const struct mg_request_info *request_info = mg_get_request_info(conn);
  213. assert(request_info != NULL);
  214. CivetServer *me = (CivetServer *)(request_info->user_data);
  215. assert(me != NULL);
  216. // Happens when a request hits the server before the context is saved
  217. if (me->context == NULL)
  218. return;
  219. CivetWebSocketHandler *handler = (CivetWebSocketHandler *)cbdata;
  220. if (handler) {
  221. handler->handleClose(me, conn);
  222. }
  223. }
  224. CivetCallbacks::CivetCallbacks()
  225. {
  226. memset(this, 0, sizeof(*this));
  227. }
  228. CivetServer::CivetServer(const char **options,
  229. const struct CivetCallbacks *_callbacks,
  230. const void *UserContextIn)
  231. : context(0)
  232. {
  233. struct CivetCallbacks callbacks;
  234. UserContext = UserContextIn;
  235. if (_callbacks) {
  236. callbacks = *_callbacks;
  237. userCloseHandler = _callbacks->connection_close;
  238. } else {
  239. userCloseHandler = NULL;
  240. }
  241. callbacks.connection_close = closeHandler;
  242. context = mg_start(&callbacks, this, options);
  243. if (context == NULL)
  244. throw CivetException("null context when constructing CivetServer. "
  245. "Possible problem binding to port.");
  246. }
  247. CivetServer::CivetServer(const std::vector<std::string> &options,
  248. const struct CivetCallbacks *_callbacks,
  249. const void *UserContextIn)
  250. : context(0)
  251. {
  252. struct CivetCallbacks callbacks;
  253. UserContext = UserContextIn;
  254. if (_callbacks) {
  255. callbacks = *_callbacks;
  256. userCloseHandler = _callbacks->connection_close;
  257. } else {
  258. userCloseHandler = NULL;
  259. }
  260. callbacks.connection_close = closeHandler;
  261. std::vector<const char *> pointers(options.size() + 1);
  262. for (size_t i = 0; i < options.size(); i++) {
  263. pointers[i] = (options[i].c_str());
  264. }
  265. pointers.back() = NULL;
  266. context = mg_start(&callbacks, this, &pointers[0]);
  267. if (context == NULL)
  268. throw CivetException("null context when constructing CivetServer. "
  269. "Possible problem binding to port.");
  270. }
  271. CivetServer::~CivetServer()
  272. {
  273. close();
  274. }
  275. void
  276. CivetServer::closeHandler(const struct mg_connection *conn)
  277. {
  278. CivetServer *me = (CivetServer *)mg_get_user_data(mg_get_context(conn));
  279. assert(me != NULL);
  280. // Happens when a request hits the server before the context is saved
  281. if (me->context == NULL)
  282. return;
  283. if (me->userCloseHandler) {
  284. me->userCloseHandler(conn);
  285. }
  286. mg_lock_context(me->context);
  287. me->connections.erase(conn);
  288. mg_unlock_context(me->context);
  289. }
  290. void
  291. CivetServer::addHandler(const std::string &uri, CivetHandler *handler)
  292. {
  293. mg_set_request_handler(context, uri.c_str(), requestHandler, handler);
  294. }
  295. void
  296. CivetServer::addWebSocketHandler(const std::string &uri,
  297. CivetWebSocketHandler *handler)
  298. {
  299. mg_set_websocket_handler(context,
  300. uri.c_str(),
  301. webSocketConnectionHandler,
  302. webSocketReadyHandler,
  303. webSocketDataHandler,
  304. webSocketCloseHandler,
  305. handler);
  306. }
  307. void
  308. CivetServer::addAuthHandler(const std::string &uri, CivetAuthHandler *handler)
  309. {
  310. mg_set_auth_handler(context, uri.c_str(), authHandler, handler);
  311. }
  312. void
  313. CivetServer::removeHandler(const std::string &uri)
  314. {
  315. mg_set_request_handler(context, uri.c_str(), NULL, NULL);
  316. }
  317. void
  318. CivetServer::removeWebSocketHandler(const std::string &uri)
  319. {
  320. mg_set_websocket_handler(
  321. context, uri.c_str(), NULL, NULL, NULL, NULL, NULL);
  322. }
  323. void
  324. CivetServer::removeAuthHandler(const std::string &uri)
  325. {
  326. mg_set_auth_handler(context, uri.c_str(), NULL, NULL);
  327. }
  328. void
  329. CivetServer::close()
  330. {
  331. if (context) {
  332. mg_stop(context);
  333. context = 0;
  334. }
  335. }
  336. int
  337. CivetServer::getCookie(struct mg_connection *conn,
  338. const std::string &cookieName,
  339. std::string &cookieValue)
  340. {
  341. // Maximum cookie length as per microsoft is 4096.
  342. // http://msdn.microsoft.com/en-us/library/ms178194.aspx
  343. char _cookieValue[4096];
  344. const char *cookie = mg_get_header(conn, "Cookie");
  345. int lRead = mg_get_cookie(cookie,
  346. cookieName.c_str(),
  347. _cookieValue,
  348. sizeof(_cookieValue));
  349. cookieValue.clear();
  350. cookieValue.append(_cookieValue);
  351. return lRead;
  352. }
  353. const char *
  354. CivetServer::getHeader(struct mg_connection *conn,
  355. const std::string &headerName)
  356. {
  357. return mg_get_header(conn, headerName.c_str());
  358. }
  359. void
  360. CivetServer::urlDecode(const char *src,
  361. std::string &dst,
  362. bool is_form_url_encoded)
  363. {
  364. urlDecode(src, strlen(src), dst, is_form_url_encoded);
  365. }
  366. void
  367. CivetServer::urlDecode(const char *src,
  368. size_t src_len,
  369. std::string &dst,
  370. bool is_form_url_encoded)
  371. {
  372. // assign enough buffer
  373. std::vector<char> buf(src_len + 1);
  374. int r = mg_url_decode(src,
  375. static_cast<int>(src_len),
  376. &buf[0],
  377. static_cast<int>(buf.size()),
  378. is_form_url_encoded);
  379. if (r < 0) {
  380. // never reach here
  381. throw std::out_of_range("");
  382. }
  383. // dst can contain NUL characters
  384. dst.assign(buf.begin(), buf.begin() + r);
  385. }
  386. bool
  387. CivetServer::getParam(struct mg_connection *conn,
  388. const char *name,
  389. std::string &dst,
  390. size_t occurrence)
  391. {
  392. const char *formParams = NULL;
  393. const char *queryString = NULL;
  394. const struct mg_request_info *ri = mg_get_request_info(conn);
  395. assert(ri != NULL);
  396. CivetServer *me = (CivetServer *)(ri->user_data);
  397. assert(me != NULL);
  398. mg_lock_context(me->context);
  399. CivetConnection &conobj = me->connections[conn];
  400. mg_lock_connection(conn);
  401. mg_unlock_context(me->context);
  402. if (conobj.postData.empty()) {
  403. // check if there is a request body
  404. for (;;) {
  405. char buf[2048];
  406. int r = mg_read(conn, buf, sizeof(buf));
  407. try {
  408. if (r == 0) {
  409. conobj.postData.push_back('\0');
  410. break;
  411. } else if ((r < 0)
  412. || ((conobj.postData.size() + r)
  413. > MAX_PARAM_BODY_LENGTH)) {
  414. conobj.postData.assign(1, '\0');
  415. break;
  416. }
  417. conobj.postData.insert(conobj.postData.end(), buf, buf + r);
  418. } catch (...) {
  419. conobj.postData.clear();
  420. break;
  421. }
  422. }
  423. }
  424. if (!conobj.postData.empty()) {
  425. // check if form parameter are already stored
  426. formParams = &conobj.postData[0];
  427. }
  428. if (ri->query_string != NULL) {
  429. // get requests do store html <form> field values in the http
  430. // query_string
  431. queryString = ri->query_string;
  432. }
  433. mg_unlock_connection(conn);
  434. bool get_param_success = false;
  435. if (formParams != NULL) {
  436. get_param_success =
  437. getParam(formParams, strlen(formParams), name, dst, occurrence);
  438. }
  439. if (!get_param_success && queryString != NULL) {
  440. get_param_success =
  441. getParam(queryString, strlen(queryString), name, dst, occurrence);
  442. }
  443. return get_param_success;
  444. }
  445. bool
  446. CivetServer::getParam(const char *data,
  447. size_t data_len,
  448. const char *name,
  449. std::string &dst,
  450. size_t occurrence)
  451. {
  452. char buf[256];
  453. int r = mg_get_var2(data, data_len, name, buf, sizeof(buf), occurrence);
  454. if (r >= 0) {
  455. // dst can contain NUL characters
  456. dst.assign(buf, r);
  457. return true;
  458. } else if (r == -2) {
  459. // more buffer
  460. std::vector<char> vbuf(sizeof(buf) * 2);
  461. for (;;) {
  462. r = mg_get_var2(
  463. data, data_len, name, &vbuf[0], vbuf.size(), occurrence);
  464. if (r >= 0) {
  465. dst.assign(vbuf.begin(), vbuf.begin() + r);
  466. return true;
  467. } else if (r != -2) {
  468. break;
  469. }
  470. // more buffer
  471. vbuf.resize(vbuf.size() * 2);
  472. }
  473. }
  474. dst.clear();
  475. return false;
  476. }
  477. std::string
  478. CivetServer::getPostData(struct mg_connection *conn)
  479. {
  480. mg_lock_connection(conn);
  481. std::string postdata;
  482. char buf[2048];
  483. int r = mg_read(conn, buf, sizeof(buf));
  484. while (r > 0) {
  485. postdata.append(buf, r);
  486. r = mg_read(conn, buf, sizeof(buf));
  487. }
  488. mg_unlock_connection(conn);
  489. return postdata;
  490. }
  491. void
  492. CivetServer::urlEncode(const char *src, std::string &dst, bool append)
  493. {
  494. urlEncode(src, strlen(src), dst, append);
  495. }
  496. void
  497. CivetServer::urlEncode(const char *src,
  498. size_t src_len,
  499. std::string &dst,
  500. bool append)
  501. {
  502. if (!append)
  503. dst.clear();
  504. for (; src_len > 0; src++, src_len--) {
  505. if (*src == '\0') {
  506. // src and dst can contain NUL characters without encoding
  507. dst.push_back(*src);
  508. } else {
  509. char buf[2] = {*src, '\0'};
  510. char dst_buf[4];
  511. if (mg_url_encode(buf, dst_buf, sizeof(dst_buf)) < 0) {
  512. // never reach here
  513. throw std::out_of_range("");
  514. }
  515. dst.append(dst_buf);
  516. }
  517. }
  518. }
  519. std::vector<int>
  520. CivetServer::getListeningPorts()
  521. {
  522. std::vector<struct mg_server_port> server_ports = getListeningPortsFull();
  523. std::vector<int> ports(server_ports.size());
  524. for (size_t i = 0; i < server_ports.size(); i++) {
  525. ports[i] = server_ports[i].port;
  526. }
  527. return ports;
  528. }
  529. std::vector<struct mg_server_port>
  530. CivetServer::getListeningPortsFull()
  531. {
  532. std::vector<struct mg_server_port> server_ports(8);
  533. for (;;) {
  534. int size = mg_get_server_ports(context,
  535. static_cast<int>(server_ports.size()),
  536. &server_ports[0]);
  537. if (size < static_cast<int>(server_ports.size())) {
  538. server_ports.resize(size < 0 ? 0 : size);
  539. break;
  540. }
  541. server_ports.resize(server_ports.size() * 2);
  542. }
  543. return server_ports;
  544. }