CivetServer.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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. #ifndef CIVETSERVER_HEADER_INCLUDED
  7. #define CIVETSERVER_HEADER_INCLUDED
  8. #ifdef __cplusplus
  9. #include "civetweb.h"
  10. #include <map>
  11. #include <stdexcept>
  12. #include <string>
  13. #include <vector>
  14. #ifndef CIVETWEB_CXX_API
  15. #if defined(_WIN32)
  16. #if defined(CIVETWEB_CXX_DLL_EXPORTS)
  17. #define CIVETWEB_CXX_API __declspec(dllexport)
  18. #elif defined(CIVETWEB_CXX_DLL_IMPORTS)
  19. #define CIVETWEB_CXX_API __declspec(dllimport)
  20. #else
  21. #define CIVETWEB_CXX_API
  22. #endif
  23. #elif __GNUC__ >= 4
  24. #define CIVETWEB_CXX_API __attribute__((visibility("default")))
  25. #else
  26. #define CIVETWEB_CXX_API
  27. #endif
  28. #endif
  29. // forward declaration
  30. class CivetServer;
  31. /**
  32. * Exception class for thrown exceptions within the CivetHandler object.
  33. */
  34. class CIVETWEB_CXX_API CivetException : public std::runtime_error
  35. {
  36. public:
  37. CivetException(const std::string &msg) : std::runtime_error(msg)
  38. {
  39. }
  40. };
  41. /**
  42. * Basic interface for a URI request handler. Handlers implementations
  43. * must be reentrant.
  44. */
  45. class CIVETWEB_CXX_API CivetHandler
  46. {
  47. public:
  48. /**
  49. * Destructor
  50. */
  51. virtual ~CivetHandler()
  52. {
  53. }
  54. /**
  55. * Callback method for GET request.
  56. *
  57. * @param server - the calling server
  58. * @param conn - the connection information
  59. * @returns true if implemented, false otherwise
  60. */
  61. virtual bool handleGet(CivetServer *server, struct mg_connection *conn);
  62. /**
  63. * Callback method for POST request.
  64. *
  65. * @param server - the calling server
  66. * @param conn - the connection information
  67. * @returns true if implemented, false otherwise
  68. */
  69. virtual bool handlePost(CivetServer *server, struct mg_connection *conn);
  70. /**
  71. * Callback method for HEAD request.
  72. *
  73. * @param server - the calling server
  74. * @param conn - the connection information
  75. * @returns true if implemented, false otherwise
  76. */
  77. virtual bool handleHead(CivetServer *server, struct mg_connection *conn);
  78. /**
  79. * Callback method for PUT request.
  80. *
  81. * @param server - the calling server
  82. * @param conn - the connection information
  83. * @returns true if implemented, false otherwise
  84. */
  85. virtual bool handlePut(CivetServer *server, struct mg_connection *conn);
  86. /**
  87. * Callback method for DELETE request.
  88. *
  89. * @param server - the calling server
  90. * @param conn - the connection information
  91. * @returns true if implemented, false otherwise
  92. */
  93. virtual bool handleDelete(CivetServer *server, struct mg_connection *conn);
  94. /**
  95. * Callback method for OPTIONS request.
  96. *
  97. * @param server - the calling server
  98. * @param conn - the connection information
  99. * @returns true if implemented, false otherwise
  100. */
  101. virtual bool handleOptions(CivetServer *server, struct mg_connection *conn);
  102. /**
  103. * Callback method for PATCH request.
  104. *
  105. * @param server - the calling server
  106. * @param conn - the connection information
  107. * @returns true if implemented, false otherwise
  108. */
  109. virtual bool handlePatch(CivetServer *server, struct mg_connection *conn);
  110. };
  111. /**
  112. * Basic interface for a URI authorization handler. Handler implementations
  113. * must be reentrant.
  114. */
  115. class CIVETWEB_CXX_API CivetAuthHandler
  116. {
  117. public:
  118. /**
  119. * Destructor
  120. */
  121. virtual ~CivetAuthHandler()
  122. {
  123. }
  124. /**
  125. * Callback method for authorization requests. It is up the this handler
  126. * to generate 401 responses if authorization fails.
  127. *
  128. * @param server - the calling server
  129. * @param conn - the connection information
  130. * @returns true if authorization succeeded, false otherwise
  131. */
  132. virtual bool authorize(CivetServer *server, struct mg_connection *conn) = 0;
  133. };
  134. /**
  135. * Basic interface for a websocket handler. Handlers implementations
  136. * must be reentrant.
  137. */
  138. class CIVETWEB_CXX_API CivetWebSocketHandler
  139. {
  140. public:
  141. /**
  142. * Destructor
  143. */
  144. virtual ~CivetWebSocketHandler()
  145. {
  146. }
  147. /**
  148. * Callback method for when the client intends to establish a websocket
  149. *connection, before websocket handshake.
  150. *
  151. * @param server - the calling server
  152. * @param conn - the connection information
  153. * @returns true to keep socket open, false to close it
  154. */
  155. virtual bool handleConnection(CivetServer *server,
  156. const struct mg_connection *conn);
  157. /**
  158. * Callback method for when websocket handshake is successfully completed,
  159. *and connection is ready for data exchange.
  160. *
  161. * @param server - the calling server
  162. * @param conn - the connection information
  163. */
  164. virtual void handleReadyState(CivetServer *server,
  165. struct mg_connection *conn);
  166. /**
  167. * Callback method for when a data frame has been received from the client.
  168. *
  169. * @param server - the calling server
  170. * @param conn - the connection information
  171. * @bits: first byte of the websocket frame, see websocket RFC at
  172. *http://tools.ietf.org/html/rfc6455, section 5.2
  173. * @data, data_len: payload, with mask (if any) already applied.
  174. * @returns true to keep socket open, false to close it
  175. */
  176. virtual bool handleData(CivetServer *server,
  177. struct mg_connection *conn,
  178. int bits,
  179. char *data,
  180. size_t data_len);
  181. /**
  182. * Callback method for when the connection is closed.
  183. *
  184. * @param server - the calling server
  185. * @param conn - the connection information
  186. */
  187. virtual void handleClose(CivetServer *server,
  188. const struct mg_connection *conn);
  189. };
  190. /**
  191. * CivetCallbacks
  192. *
  193. * wrapper for mg_callbacks
  194. */
  195. struct CIVETWEB_CXX_API CivetCallbacks : public mg_callbacks {
  196. CivetCallbacks();
  197. };
  198. /**
  199. * CivetServer
  200. *
  201. * Basic class for embedded web server. This has an URL mapping built-in.
  202. */
  203. class CIVETWEB_CXX_API CivetServer
  204. {
  205. public:
  206. /**
  207. * Constructor
  208. *
  209. * This automatically starts the sever.
  210. * It is good practice to call getContext() after this in case there
  211. * were errors starting the server.
  212. *
  213. * Note: CivetServer should not be used as a static instance in a Windows
  214. * DLL, since the constructor creates threads and the destructor joins
  215. * them again (creating/joining threads should not be done in static
  216. * constructors).
  217. *
  218. * @param options - the web server options.
  219. * @param callbacks - optional web server callback methods.
  220. *
  221. * @throws CivetException
  222. */
  223. CivetServer(const char **options,
  224. const struct CivetCallbacks *callbacks = 0,
  225. const void *UserContext = 0);
  226. CivetServer(std::vector<std::string> options,
  227. const struct CivetCallbacks *callbacks = 0,
  228. const void *UserContext = 0);
  229. /**
  230. * Destructor
  231. */
  232. virtual ~CivetServer();
  233. /**
  234. * close()
  235. *
  236. * Stops server and frees resources.
  237. */
  238. void close();
  239. /**
  240. * getContext()
  241. *
  242. * @return the context or 0 if not running.
  243. */
  244. const struct mg_context *
  245. getContext() const
  246. {
  247. return context;
  248. }
  249. /**
  250. * addHandler(const std::string &, CivetHandler *)
  251. *
  252. * Adds a URI handler. If there is existing URI handler, it will
  253. * be replaced with this one.
  254. *
  255. * URI's are ordered and prefix (REST) URI's are supported.
  256. *
  257. * @param uri - URI to match.
  258. * @param handler - handler instance to use.
  259. */
  260. void addHandler(const std::string &uri, CivetHandler *handler);
  261. void
  262. addHandler(const std::string &uri, CivetHandler &handler)
  263. {
  264. addHandler(uri, &handler);
  265. }
  266. /**
  267. * addWebSocketHandler
  268. *
  269. * Adds a WebSocket handler for a specific URI. If there is existing URI
  270. *handler, it will
  271. * be replaced with this one.
  272. *
  273. * URI's are ordered and prefix (REST) URI's are supported.
  274. *
  275. * @param uri - URI to match.
  276. * @param handler - handler instance to use.
  277. */
  278. void addWebSocketHandler(const std::string &uri,
  279. CivetWebSocketHandler *handler);
  280. void
  281. addWebSocketHandler(const std::string &uri, CivetWebSocketHandler &handler)
  282. {
  283. addWebSocketHandler(uri, &handler);
  284. }
  285. /**
  286. * removeHandler(const std::string &)
  287. *
  288. * Removes a handler.
  289. *
  290. * @param uri - the exact URL used in addHandler().
  291. */
  292. void removeHandler(const std::string &uri);
  293. /**
  294. * removeWebSocketHandler(const std::string &)
  295. *
  296. * Removes a web socket handler.
  297. *
  298. * @param uri - the exact URL used in addWebSocketHandler().
  299. */
  300. void removeWebSocketHandler(const std::string &uri);
  301. /**
  302. * addAuthHandler(const std::string &, CivetAuthHandler *)
  303. *
  304. * Adds a URI authorization handler. If there is existing URI authorization
  305. * handler, it will be replaced with this one.
  306. *
  307. * URI's are ordered and prefix (REST) URI's are supported.
  308. *
  309. * @param uri - URI to match.
  310. * @param handler - authorization handler instance to use.
  311. */
  312. void addAuthHandler(const std::string &uri, CivetAuthHandler *handler);
  313. void
  314. addAuthHandler(const std::string &uri, CivetAuthHandler &handler)
  315. {
  316. addAuthHandler(uri, &handler);
  317. }
  318. /**
  319. * removeAuthHandler(const std::string &)
  320. *
  321. * Removes an authorization handler.
  322. *
  323. * @param uri - the exact URL used in addAuthHandler().
  324. */
  325. void removeAuthHandler(const std::string &uri);
  326. /**
  327. * getListeningPorts()
  328. *
  329. * Returns a list of ports that are listening
  330. *
  331. * @return A vector of ports
  332. */
  333. std::vector<int> getListeningPorts();
  334. /**
  335. * getListeningPorts()
  336. *
  337. * Variant of getListeningPorts() returning the full port information
  338. * (protocol, SSL, ...)
  339. *
  340. * @return A vector of ports
  341. */
  342. std::vector<struct mg_server_port> getListeningPortsFull();
  343. /**
  344. * getCookie(struct mg_connection *conn, const std::string &cookieName,
  345. * std::string &cookieValue)
  346. *
  347. * Puts the cookie value string that matches the cookie name in the
  348. * cookieValue destination string.
  349. *
  350. * @param conn - the connection information
  351. * @param cookieName - cookie name to get the value from
  352. * @param cookieValue - cookie value is returned using this reference
  353. * @returns the size of the cookie value string read.
  354. */
  355. static int getCookie(struct mg_connection *conn,
  356. const std::string &cookieName,
  357. std::string &cookieValue);
  358. /**
  359. * getHeader(struct mg_connection *conn, const std::string &headerName)
  360. * @param conn - the connection information
  361. * @param headerName - header name to get the value from
  362. * @returns a char array which contains the header value as string
  363. */
  364. static const char *getHeader(struct mg_connection *conn,
  365. const std::string &headerName);
  366. /**
  367. * getParam(struct mg_connection *conn, const char *, std::string &, size_t)
  368. *
  369. * Returns a query which contained in the supplied buffer. The
  370. * occurrence value is a zero-based index of a particular key name. This
  371. * should not be confused with the index over all of the keys. Note that
  372. *this
  373. * function assumes that parameters are sent as text in http query string
  374. * format, which is the default for web forms. This function will work for
  375. * html forms with method="GET" and method="POST" attributes. In other
  376. *cases,
  377. * you may use a getParam version that directly takes the data instead of
  378. *the
  379. * connection as a first argument.
  380. *
  381. * @param conn - parameters are read from the data sent through this
  382. *connection
  383. * @param name - the key to search for
  384. * @param dst - the destination string
  385. * @param occurrence - the occurrence of the selected name in the query (0
  386. *based).
  387. * @return true if key was found
  388. */
  389. static bool getParam(struct mg_connection *conn,
  390. const char *name,
  391. std::string &dst,
  392. size_t occurrence = 0);
  393. /**
  394. * getParam(const std::string &, const char *, std::string &, size_t)
  395. *
  396. * Returns a query parameter contained in the supplied buffer. The
  397. * occurrence value is a zero-based index of a particular key name. This
  398. * should not be confused with the index over all of the keys.
  399. *
  400. * @param data - the query string (text)
  401. * @param name - the key to search for
  402. * @param dst - the destination string
  403. * @param occurrence - the occurrence of the selected name in the query (0
  404. *based).
  405. * @return true if key was found
  406. */
  407. static bool
  408. getParam(const std::string &data,
  409. const char *name,
  410. std::string &dst,
  411. size_t occurrence = 0)
  412. {
  413. return getParam(data.c_str(), data.length(), name, dst, occurrence);
  414. }
  415. /**
  416. * getParam(const char *, size_t, const char *, std::string &, size_t)
  417. *
  418. * Returns a query parameter contained in the supplied buffer. The
  419. * occurrence value is a zero-based index of a particular key name. This
  420. * should not be confused with the index over all of the keys.
  421. *
  422. * @param data the - query string (text)
  423. * @param data_len - length of the query string
  424. * @param name - the key to search for
  425. * @param dst - the destination string
  426. * @param occurrence - the occurrence of the selected name in the query (0
  427. *based).
  428. * @return true if key was found
  429. */
  430. static bool getParam(const char *data,
  431. size_t data_len,
  432. const char *name,
  433. std::string &dst,
  434. size_t occurrence = 0);
  435. /**
  436. * getPostData(struct mg_connection *)
  437. *
  438. * Returns response body from a request made as POST. Since the
  439. * connections map is protected, it can't be directly accessed.
  440. * This uses string to store post data to handle big posts.
  441. *
  442. * @param conn - connection from which post data will be read
  443. * @return Post data (empty if not available).
  444. */
  445. static std::string getPostData(struct mg_connection *conn);
  446. /**
  447. * urlDecode(const std::string &, std::string &, bool)
  448. *
  449. * @param src - string to be decoded
  450. * @param dst - destination string
  451. * @param is_form_url_encoded - true if form url encoded
  452. * form-url-encoded data differs from URI encoding in a way that it
  453. * uses '+' as character for space, see RFC 1866 section 8.2.1
  454. * http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  455. */
  456. static void
  457. urlDecode(const std::string &src,
  458. std::string &dst,
  459. bool is_form_url_encoded = true)
  460. {
  461. urlDecode(src.c_str(), src.length(), dst, is_form_url_encoded);
  462. }
  463. /**
  464. * urlDecode(const char *, size_t, std::string &, bool)
  465. *
  466. * @param src - buffer to be decoded
  467. * @param src_len - length of buffer to be decoded
  468. * @param dst - destination string
  469. * @param is_form_url_encoded - true if form url encoded
  470. * form-url-encoded data differs from URI encoding in a way that it
  471. * uses '+' as character for space, see RFC 1866 section 8.2.1
  472. * http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  473. */
  474. static void urlDecode(const char *src,
  475. size_t src_len,
  476. std::string &dst,
  477. bool is_form_url_encoded = true);
  478. /**
  479. * urlDecode(const char *, std::string &, bool)
  480. *
  481. * @param src - buffer to be decoded (0 terminated)
  482. * @param dst - destination string
  483. * @param is_form_url_encoded true - if form url encoded
  484. * form-url-encoded data differs from URI encoding in a way that it
  485. * uses '+' as character for space, see RFC 1866 section 8.2.1
  486. * http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  487. */
  488. static void urlDecode(const char *src,
  489. std::string &dst,
  490. bool is_form_url_encoded = true);
  491. /**
  492. * urlEncode(const std::string &, std::string &, bool)
  493. *
  494. * @param src - buffer to be encoded
  495. * @param dst - destination string
  496. * @param append - true if string should not be cleared before encoding.
  497. */
  498. static void
  499. urlEncode(const std::string &src, std::string &dst, bool append = false)
  500. {
  501. urlEncode(src.c_str(), src.length(), dst, append);
  502. }
  503. /**
  504. * urlEncode(const char *, size_t, std::string &, bool)
  505. *
  506. * @param src - buffer to be encoded (0 terminated)
  507. * @param dst - destination string
  508. * @param append - true if string should not be cleared before encoding.
  509. */
  510. static void
  511. urlEncode(const char *src, std::string &dst, bool append = false);
  512. /**
  513. * urlEncode(const char *, size_t, std::string &, bool)
  514. *
  515. * @param src - buffer to be encoded
  516. * @param src_len - length of buffer to be decoded
  517. * @param dst - destination string
  518. * @param append - true if string should not be cleared before encoding.
  519. */
  520. static void urlEncode(const char *src,
  521. size_t src_len,
  522. std::string &dst,
  523. bool append = false);
  524. // generic user context which can be set/read,
  525. // the server does nothing with this apart from keep it.
  526. const void *
  527. getUserContext() const
  528. {
  529. return UserContext;
  530. }
  531. protected:
  532. class CivetConnection
  533. {
  534. public:
  535. char *postData;
  536. unsigned long postDataLen;
  537. CivetConnection();
  538. ~CivetConnection();
  539. };
  540. struct mg_context *context;
  541. std::map<struct mg_connection *, class CivetConnection> connections;
  542. // generic user context which can be set/read,
  543. // the server does nothing with this apart from keep it.
  544. const void *UserContext;
  545. private:
  546. /**
  547. * requestHandler(struct mg_connection *, void *cbdata)
  548. *
  549. * Handles the incoming request.
  550. *
  551. * @param conn - the connection information
  552. * @param cbdata - pointer to the CivetHandler instance.
  553. * @returns 0 if implemented, false otherwise
  554. */
  555. static int requestHandler(struct mg_connection *conn, void *cbdata);
  556. static int webSocketConnectionHandler(const struct mg_connection *conn,
  557. void *cbdata);
  558. static void webSocketReadyHandler(struct mg_connection *conn, void *cbdata);
  559. static int webSocketDataHandler(struct mg_connection *conn,
  560. int bits,
  561. char *data,
  562. size_t data_len,
  563. void *cbdata);
  564. static void webSocketCloseHandler(const struct mg_connection *conn,
  565. void *cbdata);
  566. /**
  567. * authHandler(struct mg_connection *, void *cbdata)
  568. *
  569. * Handles the authorization requests.
  570. *
  571. * @param conn - the connection information
  572. * @param cbdata - pointer to the CivetAuthHandler instance.
  573. * @returns 1 if authorized, 0 otherwise
  574. */
  575. static int authHandler(struct mg_connection *conn, void *cbdata);
  576. /**
  577. * closeHandler(struct mg_connection *)
  578. *
  579. * Handles closing a request (internal handler)
  580. *
  581. * @param conn - the connection information
  582. */
  583. static void closeHandler(const struct mg_connection *conn);
  584. /**
  585. * Stores the user provided close handler
  586. */
  587. void (*userCloseHandler)(const struct mg_connection *conn);
  588. };
  589. #endif /* __cplusplus */
  590. #endif /* CIVETSERVER_HEADER_INCLUDED */