CivetServer.cpp 16 KB

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