CivetServer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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. const struct mg_request_info *request_info = mg_get_request_info(conn);
  272. assert(request_info != NULL);
  273. CivetServer *me = (CivetServer *)(request_info->user_data);
  274. assert(me != NULL);
  275. // Happens when a request hits the server before the context is saved
  276. if (me->context == NULL)
  277. return;
  278. if (me->userCloseHandler)
  279. me->userCloseHandler(conn);
  280. mg_lock_context(me->context);
  281. me->connections.erase(const_cast<struct mg_connection *>(conn));
  282. mg_unlock_context(me->context);
  283. }
  284. void
  285. CivetServer::addHandler(const std::string &uri, CivetHandler *handler)
  286. {
  287. mg_set_request_handler(context, uri.c_str(), requestHandler, handler);
  288. }
  289. void
  290. CivetServer::addWebSocketHandler(const std::string &uri,
  291. CivetWebSocketHandler *handler)
  292. {
  293. mg_set_websocket_handler(context,
  294. uri.c_str(),
  295. webSocketConnectionHandler,
  296. webSocketReadyHandler,
  297. webSocketDataHandler,
  298. webSocketCloseHandler,
  299. handler);
  300. }
  301. void
  302. CivetServer::addAuthHandler(const std::string &uri, CivetAuthHandler *handler)
  303. {
  304. mg_set_auth_handler(context, uri.c_str(), authHandler, handler);
  305. }
  306. void
  307. CivetServer::removeHandler(const std::string &uri)
  308. {
  309. mg_set_request_handler(context, uri.c_str(), NULL, NULL);
  310. }
  311. void
  312. CivetServer::removeWebSocketHandler(const std::string &uri)
  313. {
  314. mg_set_websocket_handler(
  315. context, uri.c_str(), NULL, NULL, NULL, NULL, NULL);
  316. }
  317. void
  318. CivetServer::removeAuthHandler(const std::string &uri)
  319. {
  320. mg_set_auth_handler(context, uri.c_str(), NULL, NULL);
  321. }
  322. void
  323. CivetServer::close()
  324. {
  325. if (context) {
  326. mg_stop(context);
  327. context = 0;
  328. }
  329. }
  330. int
  331. CivetServer::getCookie(struct mg_connection *conn,
  332. const std::string &cookieName,
  333. std::string &cookieValue)
  334. {
  335. // Maximum cookie length as per microsoft is 4096.
  336. // http://msdn.microsoft.com/en-us/library/ms178194.aspx
  337. char _cookieValue[4096];
  338. const char *cookie = mg_get_header(conn, "Cookie");
  339. int lRead = mg_get_cookie(cookie,
  340. cookieName.c_str(),
  341. _cookieValue,
  342. sizeof(_cookieValue));
  343. cookieValue.clear();
  344. cookieValue.append(_cookieValue);
  345. return lRead;
  346. }
  347. const char *
  348. CivetServer::getHeader(struct mg_connection *conn,
  349. const std::string &headerName)
  350. {
  351. return mg_get_header(conn, headerName.c_str());
  352. }
  353. void
  354. CivetServer::urlDecode(const char *src,
  355. std::string &dst,
  356. bool is_form_url_encoded)
  357. {
  358. urlDecode(src, strlen(src), dst, is_form_url_encoded);
  359. }
  360. void
  361. CivetServer::urlDecode(const char *src,
  362. size_t src_len,
  363. std::string &dst,
  364. bool is_form_url_encoded)
  365. {
  366. int i, j, a, b;
  367. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  368. dst.clear();
  369. for (i = j = 0; i < (int)src_len; i++, j++) {
  370. if (i < (int)src_len - 2 && src[i] == '%'
  371. && isxdigit(*(const unsigned char *)(src + i + 1))
  372. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  373. a = tolower(*(const unsigned char *)(src + i + 1));
  374. b = tolower(*(const unsigned char *)(src + i + 2));
  375. dst.push_back((char)((HEXTOI(a) << 4) | HEXTOI(b)));
  376. i += 2;
  377. } else if (is_form_url_encoded && src[i] == '+') {
  378. dst.push_back(' ');
  379. } else {
  380. dst.push_back(src[i]);
  381. }
  382. }
  383. }
  384. bool
  385. CivetServer::getParam(struct mg_connection *conn,
  386. const char *name,
  387. std::string &dst,
  388. size_t occurrence)
  389. {
  390. const char *formParams = NULL;
  391. const struct mg_request_info *ri = mg_get_request_info(conn);
  392. assert(ri != NULL);
  393. CivetServer *me = (CivetServer *)(ri->user_data);
  394. assert(me != NULL);
  395. mg_lock_context(me->context);
  396. CivetConnection &conobj = me->connections[conn];
  397. mg_lock_connection(conn);
  398. mg_unlock_context(me->context);
  399. if (conobj.postData != NULL) {
  400. formParams = conobj.postData;
  401. } else {
  402. const char *con_len_str = mg_get_header(conn, "Content-Length");
  403. if (con_len_str) {
  404. unsigned long con_len = atoi(con_len_str);
  405. if (con_len > 0) {
  406. // Add one extra character: in case the post-data is a text, it
  407. // is required as 0-termination.
  408. // Do not increment con_len, since the 0 terminating is not part
  409. // of the content (text or binary).
  410. conobj.postData = (char *)malloc(con_len + 1);
  411. if (conobj.postData != NULL) {
  412. // malloc may fail for huge requests
  413. mg_read(conn, conobj.postData, con_len);
  414. conobj.postData[con_len] = 0;
  415. formParams = conobj.postData;
  416. conobj.postDataLen = con_len;
  417. }
  418. }
  419. }
  420. }
  421. if (formParams == NULL) {
  422. // get requests do store html <form> field values in the http
  423. // query_string
  424. formParams = ri->query_string;
  425. }
  426. mg_unlock_connection(conn);
  427. if (formParams != NULL) {
  428. return getParam(formParams, strlen(formParams), name, dst, occurrence);
  429. }
  430. return false;
  431. }
  432. bool
  433. CivetServer::getParam(const char *data,
  434. size_t data_len,
  435. const char *name,
  436. std::string &dst,
  437. size_t occurrence)
  438. {
  439. const char *p, *e, *s;
  440. size_t name_len;
  441. dst.clear();
  442. if (data == NULL || name == NULL || data_len == 0) {
  443. return false;
  444. }
  445. name_len = strlen(name);
  446. e = data + data_len;
  447. // data is "var1=val1&var2=val2...". Find variable first
  448. for (p = data; p + name_len < e; p++) {
  449. if ((p == data || p[-1] == '&') && p[name_len] == '='
  450. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  451. // Point p to variable value
  452. p += name_len + 1;
  453. // Point s to the end of the value
  454. s = (const char *)memchr(p, '&', (size_t)(e - p));
  455. if (s == NULL) {
  456. s = e;
  457. }
  458. assert(s >= p);
  459. // Decode variable into destination buffer
  460. urlDecode(p, (int)(s - p), dst, true);
  461. return true;
  462. }
  463. }
  464. return false;
  465. }
  466. void
  467. CivetServer::urlEncode(const char *src, std::string &dst, bool append)
  468. {
  469. urlEncode(src, strlen(src), dst, append);
  470. }
  471. void
  472. CivetServer::urlEncode(const char *src,
  473. size_t src_len,
  474. std::string &dst,
  475. bool append)
  476. {
  477. static const char *dont_escape = "._-$,;~()";
  478. static const char *hex = "0123456789abcdef";
  479. if (!append)
  480. dst.clear();
  481. for (; src_len > 0; src++, src_len--) {
  482. if (isalnum(*(const unsigned char *)src)
  483. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  484. dst.push_back(*src);
  485. } else {
  486. dst.push_back('%');
  487. dst.push_back(hex[(*(const unsigned char *)src) >> 4]);
  488. dst.push_back(hex[(*(const unsigned char *)src) & 0xf]);
  489. }
  490. }
  491. }
  492. std::vector<int>
  493. CivetServer::getListeningPorts()
  494. {
  495. std::vector<int> ports(50);
  496. std::vector<struct mg_server_ports> server_ports(50);
  497. int size =
  498. mg_get_server_ports(context, server_ports.size(), &server_ports[0]);
  499. if (size <= 0) {
  500. ports.resize(0);
  501. return ports;
  502. }
  503. ports.resize(size);
  504. server_ports.resize(size);
  505. for (int i = 0; i < size; i++) {
  506. ports[i] = server_ports[i].port;
  507. }
  508. return ports;
  509. }
  510. CivetServer::CivetConnection::CivetConnection()
  511. {
  512. postData = NULL;
  513. postDataLen = 0;
  514. }
  515. CivetServer::CivetConnection::~CivetConnection()
  516. {
  517. free(postData);
  518. }