CivetServer.cpp 15 KB

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