CivetServer.h 16 KB

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