CivetServer.h 16 KB

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