CivetServer.cpp 13 KB

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