CivetServer.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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 _CIVETWEB_SERVER_H_
  7. #define _CIVETWEB_SERVER_H_
  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. * getCookie(struct mg_connection *conn, const std::string &cookieName,
  336. *std::string &cookieValue)
  337. *
  338. * Puts the cookie value string that matches the cookie name in the
  339. *cookieValue destinaton string.
  340. *
  341. * @param conn - the connection information
  342. * @param cookieName - cookie name to get the value from
  343. * @param cookieValue - cookie value is returned using thiis reference
  344. * @returns the size of the cookie value string read.
  345. */
  346. static int getCookie(struct mg_connection *conn,
  347. const std::string &cookieName,
  348. std::string &cookieValue);
  349. /**
  350. * getHeader(struct mg_connection *conn, const std::string &headerName)
  351. * @param conn - the connection information
  352. * @param headerName - header name to get the value from
  353. * @returns a char array which contains the header value as string
  354. */
  355. static const char *getHeader(struct mg_connection *conn,
  356. const std::string &headerName);
  357. /**
  358. * getParam(struct mg_connection *conn, const char *, std::string &, size_t)
  359. *
  360. * Returns a query which contained in the supplied buffer. The
  361. * occurrence value is a zero-based index of a particular key name. This
  362. * should not be confused with the index over all of the keys. Note that
  363. *this
  364. * function assumes that parameters are sent as text in http query string
  365. * format, which is the default for web forms. This function will work for
  366. * html forms with method="GET" and method="POST" attributes. In other
  367. *cases,
  368. * you may use a getParam version that directly takes the data instead of
  369. *the
  370. * connection as a first argument.
  371. *
  372. * @param conn - parameters are read from the data sent through this
  373. *connection
  374. * @param name - the key to search for
  375. * @param dst - the destination string
  376. * @param occurrence - the occurrence of the selected name in the query (0
  377. *based).
  378. * @return true if key was found
  379. */
  380. static bool getParam(struct mg_connection *conn,
  381. const char *name,
  382. std::string &dst,
  383. size_t occurrence = 0);
  384. /**
  385. * getParam(const std::string &, const char *, std::string &, size_t)
  386. *
  387. * Returns a query parameter contained in the supplied buffer. The
  388. * occurrence value is a zero-based index of a particular key name. This
  389. * should not be confused with the index over all of the keys.
  390. *
  391. * @param data - the query string (text)
  392. * @param name - the key to search for
  393. * @param dst - the destination string
  394. * @param occurrence - the occurrence of the selected name in the query (0
  395. *based).
  396. * @return true if key was found
  397. */
  398. static bool
  399. getParam(const std::string &data,
  400. const char *name,
  401. std::string &dst,
  402. size_t occurrence = 0)
  403. {
  404. return getParam(data.c_str(), data.length(), name, dst, occurrence);
  405. }
  406. /**
  407. * getParam(const char *, size_t, const char *, std::string &, size_t)
  408. *
  409. * Returns a query parameter contained in the supplied buffer. The
  410. * occurrence value is a zero-based index of a particular key name. This
  411. * should not be confused with the index over all of the keys.
  412. *
  413. * @param data the - query string (text)
  414. * @param data_len - length of the query string
  415. * @param name - the key to search for
  416. * @param dst - the destination string
  417. * @param occurrence - the occurrence of the selected name in the query (0
  418. *based).
  419. * @return true if key was found
  420. */
  421. static bool getParam(const char *data,
  422. size_t data_len,
  423. const char *name,
  424. std::string &dst,
  425. size_t occurrence = 0);
  426. /**
  427. * getPostData(struct mg_connection *)
  428. *
  429. * Returns response body from a request made as POST. Since the
  430. * connections map is protected, it can't be directly accessed.
  431. * This uses string to store post data to handle big posts.
  432. *
  433. * @param conn - connection from which post data will be read
  434. * @return Post data (empty if not available).
  435. */
  436. static std::string getPostData(struct mg_connection *conn);
  437. /**
  438. * urlDecode(const std::string &, std::string &, bool)
  439. *
  440. * @param src - string to be decoded
  441. * @param dst - destination string
  442. * @param is_form_url_encoded - true if form url encoded
  443. * form-url-encoded data differs from URI encoding in a way that it
  444. * uses '+' as character for space, see RFC 1866 section 8.2.1
  445. * http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  446. */
  447. static void
  448. urlDecode(const std::string &src,
  449. std::string &dst,
  450. bool is_form_url_encoded = true)
  451. {
  452. urlDecode(src.c_str(), src.length(), dst, is_form_url_encoded);
  453. }
  454. /**
  455. * urlDecode(const char *, size_t, std::string &, bool)
  456. *
  457. * @param src - buffer to be decoded
  458. * @param src_len - length of buffer to be decoded
  459. * @param dst - destination string
  460. * @param is_form_url_encoded - true if form url encoded
  461. * form-url-encoded data differs from URI encoding in a way that it
  462. * uses '+' as character for space, see RFC 1866 section 8.2.1
  463. * http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  464. */
  465. static void urlDecode(const char *src,
  466. size_t src_len,
  467. std::string &dst,
  468. bool is_form_url_encoded = true);
  469. /**
  470. * urlDecode(const char *, std::string &, bool)
  471. *
  472. * @param src - buffer to be decoded (0 terminated)
  473. * @param dst - destination string
  474. * @param is_form_url_encoded true - if form url encoded
  475. * form-url-encoded data differs from URI encoding in a way that it
  476. * uses '+' as character for space, see RFC 1866 section 8.2.1
  477. * http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  478. */
  479. static void urlDecode(const char *src,
  480. std::string &dst,
  481. bool is_form_url_encoded = true);
  482. /**
  483. * urlEncode(const std::string &, std::string &, bool)
  484. *
  485. * @param src - buffer to be encoded
  486. * @param dst - destination string
  487. * @param append - true if string should not be cleared before encoding.
  488. */
  489. static void
  490. urlEncode(const std::string &src, std::string &dst, bool append = false)
  491. {
  492. urlEncode(src.c_str(), src.length(), dst, append);
  493. }
  494. /**
  495. * urlEncode(const char *, size_t, std::string &, bool)
  496. *
  497. * @param src - buffer to be encoded (0 terminated)
  498. * @param dst - destination string
  499. * @param append - true if string should not be cleared before encoding.
  500. */
  501. static void
  502. urlEncode(const char *src, std::string &dst, bool append = false);
  503. /**
  504. * urlEncode(const char *, size_t, std::string &, bool)
  505. *
  506. * @param src - buffer to be encoded
  507. * @param src_len - length of buffer to be decoded
  508. * @param dst - destination string
  509. * @param append - true if string should not be cleared before encoding.
  510. */
  511. static void urlEncode(const char *src,
  512. size_t src_len,
  513. std::string &dst,
  514. bool append = false);
  515. // generic user context which can be set/read,
  516. // the server does nothing with this apart from keep it.
  517. const void *
  518. getUserContext() const
  519. {
  520. return UserContext;
  521. }
  522. protected:
  523. class CivetConnection
  524. {
  525. public:
  526. char *postData;
  527. unsigned long postDataLen;
  528. CivetConnection();
  529. ~CivetConnection();
  530. };
  531. struct mg_context *context;
  532. std::map<struct mg_connection *, class CivetConnection> connections;
  533. // generic user context which can be set/read,
  534. // the server does nothing with this apart from keep it.
  535. const void *UserContext;
  536. private:
  537. /**
  538. * requestHandler(struct mg_connection *, void *cbdata)
  539. *
  540. * Handles the incoming request.
  541. *
  542. * @param conn - the connection information
  543. * @param cbdata - pointer to the CivetHandler instance.
  544. * @returns 0 if implemented, false otherwise
  545. */
  546. static int requestHandler(struct mg_connection *conn, void *cbdata);
  547. static int webSocketConnectionHandler(const struct mg_connection *conn,
  548. void *cbdata);
  549. static void webSocketReadyHandler(struct mg_connection *conn, void *cbdata);
  550. static int webSocketDataHandler(struct mg_connection *conn,
  551. int bits,
  552. char *data,
  553. size_t data_len,
  554. void *cbdata);
  555. static void webSocketCloseHandler(const struct mg_connection *conn,
  556. void *cbdata);
  557. /**
  558. * authHandler(struct mg_connection *, void *cbdata)
  559. *
  560. * Handles the authorization requests.
  561. *
  562. * @param conn - the connection information
  563. * @param cbdata - pointer to the CivetAuthHandler instance.
  564. * @returns 1 if authorized, 0 otherwise
  565. */
  566. static int authHandler(struct mg_connection *conn, void *cbdata);
  567. /**
  568. * closeHandler(struct mg_connection *)
  569. *
  570. * Handles closing a request (internal handler)
  571. *
  572. * @param conn - the connection information
  573. */
  574. static void closeHandler(const struct mg_connection *conn);
  575. /**
  576. * Stores the user provided close handler
  577. */
  578. void (*userCloseHandler)(const struct mg_connection *conn);
  579. };
  580. #endif /* __cplusplus */
  581. #endif /* _CIVETWEB_SERVER_H_ */