CivetServer.cpp 17 KB

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