CivetServer.cpp 15 KB

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