CivetServer.cpp 15 KB

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