CivetServer.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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. * Note: CivetServer should not be used as a static instance in a Windows
  191. * DLL, since the constructor creates threads and the destructor joins
  192. * them again (creating/joining threads should not be done in static
  193. * constructors).
  194. *
  195. * @param options - the web server options.
  196. * @param callbacks - optional web server callback methods.
  197. *
  198. * @throws CivetException
  199. */
  200. CivetServer(const char **options, const struct mg_callbacks *callbacks = 0);
  201. CivetServer(std::vector<std::string> options,
  202. const struct mg_callbacks *callbacks = 0);
  203. /**
  204. * Destructor
  205. */
  206. virtual ~CivetServer();
  207. /**
  208. * close()
  209. *
  210. * Stops server and frees resources.
  211. */
  212. void close();
  213. /**
  214. * getContext()
  215. *
  216. * @return the context or 0 if not running.
  217. */
  218. const struct mg_context *
  219. getContext() const
  220. {
  221. return context;
  222. }
  223. /**
  224. * addHandler(const std::string &, CivetHandler *)
  225. *
  226. * Adds a URI handler. If there is existing URI handler, it will
  227. * be replaced with this one.
  228. *
  229. * URI's are ordered and prefix (REST) URI's are supported.
  230. *
  231. * @param uri - URI to match.
  232. * @param handler - handler instance to use.
  233. */
  234. void addHandler(const std::string &uri, CivetHandler *handler);
  235. void
  236. addHandler(const std::string &uri, CivetHandler &handler)
  237. {
  238. addHandler(uri, &handler);
  239. }
  240. /**
  241. * addWebSocketHandler
  242. *
  243. * Adds a WebSocket handler for a specific URI. If there is existing URI
  244. *handler, it will
  245. * be replaced with this one.
  246. *
  247. * URI's are ordered and prefix (REST) URI's are supported.
  248. *
  249. * @param uri - URI to match.
  250. * @param handler - handler instance to use.
  251. */
  252. void addWebSocketHandler(const std::string &uri,
  253. CivetWebSocketHandler *handler);
  254. void
  255. addWebSocketHandler(const std::string &uri, CivetWebSocketHandler &handler)
  256. {
  257. addWebSocketHandler(uri, &handler);
  258. }
  259. /**
  260. * removeHandler(const std::string &)
  261. *
  262. * Removes a handler.
  263. *
  264. * @param uri - the exact URL used in addHandler().
  265. */
  266. void removeHandler(const std::string &uri);
  267. /**
  268. * removeWebSocketHandler(const std::string &)
  269. *
  270. * Removes a web socket handler.
  271. *
  272. * @param uri - the exact URL used in addWebSocketHandler().
  273. */
  274. void removeWebSocketHandler(const std::string &uri);
  275. /**
  276. * addAuthHandler(const std::string &, CivetAuthHandler *)
  277. *
  278. * Adds a URI authorization handler. If there is existing URI authorization
  279. * handler, it will be replaced with this one.
  280. *
  281. * URI's are ordered and prefix (REST) URI's are supported.
  282. *
  283. * @param uri - URI to match.
  284. * @param handler - authorization handler instance to use.
  285. */
  286. void addAuthHandler(const std::string &uri, CivetAuthHandler *handler);
  287. void
  288. addAuthHandler(const std::string &uri, CivetAuthHandler &handler)
  289. {
  290. addAuthHandler(uri, &handler);
  291. }
  292. /**
  293. * removeAuthHandler(const std::string &)
  294. *
  295. * Removes an authorization handler.
  296. *
  297. * @param uri - the exact URL used in addAuthHandler().
  298. */
  299. void removeAuthHandler(const std::string &uri);
  300. /**
  301. * getListeningPorts()
  302. *
  303. * Returns a list of ports that are listening
  304. *
  305. * @return A vector of ports
  306. */
  307. std::vector<int> getListeningPorts();
  308. /**
  309. * getCookie(struct mg_connection *conn, const std::string &cookieName,
  310. *std::string &cookieValue)
  311. *
  312. * Puts the cookie value string that matches the cookie name in the
  313. *cookieValue destinaton string.
  314. *
  315. * @param conn - the connection information
  316. * @param cookieName - cookie name to get the value from
  317. * @param cookieValue - cookie value is returned using thiis reference
  318. * @returns the size of the cookie value string read.
  319. */
  320. static int getCookie(struct mg_connection *conn,
  321. const std::string &cookieName,
  322. std::string &cookieValue);
  323. /**
  324. * getHeader(struct mg_connection *conn, const std::string &headerName)
  325. * @param conn - the connection information
  326. * @param headerName - header name to get the value from
  327. * @returns a char array whcih contains the header value as string
  328. */
  329. static const char *getHeader(struct mg_connection *conn,
  330. const std::string &headerName);
  331. /**
  332. * getParam(struct mg_connection *conn, const char *, std::string &, size_t)
  333. *
  334. * Returns a query paramter contained in the supplied buffer. The
  335. * occurance value is a zero-based index of a particular key name. This
  336. * should not be confused with the index over all of the keys. Note that
  337. *this
  338. * function assumes that parameters are sent as text in http query string
  339. * format, which is the default for web forms. This function will work for
  340. * html forms with method="GET" and method="POST" attributes. In other
  341. *cases,
  342. * you may use a getParam version that directly takes the data instead of
  343. *the
  344. * connection as a first argument.
  345. *
  346. * @param conn - parameters are read from the data sent through this
  347. *connection
  348. * @param name - the key to search for
  349. * @param dst - the destination string
  350. * @param occurrence - the occurrence of the selected name in the query (0
  351. *based).
  352. * @return true if key was found
  353. */
  354. static bool getParam(struct mg_connection *conn,
  355. const char *name,
  356. std::string &dst,
  357. size_t occurrence = 0);
  358. /**
  359. * getParam(const std::string &, const char *, std::string &, size_t)
  360. *
  361. * Returns a query paramter contained in the supplied buffer. The
  362. * occurance value is a zero-based index of a particular key name. This
  363. * should not be confused with the index over all of the keys.
  364. *
  365. * @param data - the query string (text)
  366. * @param name - the key to search for
  367. * @param dst - the destination string
  368. * @param occurrence - the occurrence of the selected name in the query (0
  369. *based).
  370. * @return true if key was found
  371. */
  372. static bool
  373. getParam(const std::string &data,
  374. const char *name,
  375. std::string &dst,
  376. size_t occurrence = 0)
  377. {
  378. return getParam(data.c_str(), data.length(), name, dst, occurrence);
  379. }
  380. /**
  381. * getParam(const char *, size_t, const char *, std::string &, size_t)
  382. *
  383. * Returns a query paramter contained in the supplied buffer. The
  384. * occurance value is a zero-based index of a particular key name. This
  385. * should not be confused with the index over all of the keys.
  386. *
  387. * @param data the - query string (text)
  388. * @param data_len - length of the query string
  389. * @param name - the key to search for
  390. * @param dst - the destination string
  391. * @param occurrence - the occurrence of the selected name in the query (0
  392. *based).
  393. * @return true if key was found
  394. */
  395. static bool getParam(const char *data,
  396. size_t data_len,
  397. const char *name,
  398. std::string &dst,
  399. size_t occurrence = 0);
  400. /**
  401. * urlDecode(const std::string &, std::string &, bool)
  402. *
  403. * @param src - string to be decoded
  404. * @param dst - destination string
  405. * @param is_form_url_encoded - true if form url encoded
  406. * form-url-encoded data differs from URI encoding in a way that it
  407. * uses '+' as character for space, see RFC 1866 section 8.2.1
  408. * http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  409. */
  410. static void
  411. urlDecode(const std::string &src,
  412. std::string &dst,
  413. bool is_form_url_encoded = true)
  414. {
  415. urlDecode(src.c_str(), src.length(), dst, is_form_url_encoded);
  416. }
  417. /**
  418. * urlDecode(const char *, size_t, std::string &, bool)
  419. *
  420. * @param src - buffer to be decoded
  421. * @param src_len - length of buffer to be decoded
  422. * @param dst - destination string
  423. * @param is_form_url_encoded - true if form url encoded
  424. * form-url-encoded data differs from URI encoding in a way that it
  425. * uses '+' as character for space, see RFC 1866 section 8.2.1
  426. * http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  427. */
  428. static void urlDecode(const char *src,
  429. size_t src_len,
  430. std::string &dst,
  431. bool is_form_url_encoded = true);
  432. /**
  433. * urlDecode(const char *, std::string &, bool)
  434. *
  435. * @param src - buffer to be decoded (0 terminated)
  436. * @param dst - destination string
  437. * @param is_form_url_encoded true - if form url encoded
  438. * form-url-encoded data differs from URI encoding in a way that it
  439. * uses '+' as character for space, see RFC 1866 section 8.2.1
  440. * http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  441. */
  442. static void urlDecode(const char *src,
  443. std::string &dst,
  444. bool is_form_url_encoded = true);
  445. /**
  446. * urlEncode(const std::string &, std::string &, bool)
  447. *
  448. * @param src - buffer to be encoded
  449. * @param dst - destination string
  450. * @param append - true if string should not be cleared before encoding.
  451. */
  452. static void
  453. urlEncode(const std::string &src, std::string &dst, bool append = false)
  454. {
  455. urlEncode(src.c_str(), src.length(), dst, append);
  456. }
  457. /**
  458. * urlEncode(const char *, size_t, std::string &, bool)
  459. *
  460. * @param src - buffer to be encoded (0 terminated)
  461. * @param dst - destination string
  462. * @param append - true if string should not be cleared before encoding.
  463. */
  464. static void
  465. urlEncode(const char *src, std::string &dst, bool append = false);
  466. /**
  467. * urlEncode(const char *, size_t, std::string &, bool)
  468. *
  469. * @param src - buffer to be encoded
  470. * @param src_len - length of buffer to be decoded
  471. * @param dst - destination string
  472. * @param append - true if string should not be cleared before encoding.
  473. */
  474. static void urlEncode(const char *src,
  475. size_t src_len,
  476. std::string &dst,
  477. bool append = false);
  478. protected:
  479. class CivetConnection
  480. {
  481. public:
  482. char *postData;
  483. unsigned long postDataLen;
  484. CivetConnection();
  485. ~CivetConnection();
  486. };
  487. struct mg_context *context;
  488. std::map<struct mg_connection *, class CivetConnection> connections;
  489. private:
  490. /**
  491. * requestHandler(struct mg_connection *, void *cbdata)
  492. *
  493. * Handles the incomming request.
  494. *
  495. * @param conn - the connection information
  496. * @param cbdata - pointer to the CivetHandler instance.
  497. * @returns 0 if implemented, false otherwise
  498. */
  499. static int requestHandler(struct mg_connection *conn, void *cbdata);
  500. static int webSocketConnectionHandler(const struct mg_connection *conn,
  501. void *cbdata);
  502. static void webSocketReadyHandler(struct mg_connection *conn, void *cbdata);
  503. static int webSocketDataHandler(struct mg_connection *conn,
  504. int bits,
  505. char *data,
  506. size_t data_len,
  507. void *cbdata);
  508. static void webSocketCloseHandler(const struct mg_connection *conn,
  509. void *cbdata);
  510. /**
  511. * authHandler(struct mg_connection *, void *cbdata)
  512. *
  513. * Handles the authorization requests.
  514. *
  515. * @param conn - the connection information
  516. * @param cbdata - pointer to the CivetAuthHandler instance.
  517. * @returns 1 if authorized, 0 otherwise
  518. */
  519. static int authHandler(struct mg_connection *conn, void *cbdata);
  520. /**
  521. * closeHandler(struct mg_connection *)
  522. *
  523. * Handles closing a request (internal handler)
  524. *
  525. * @param conn - the connection information
  526. */
  527. static void closeHandler(const struct mg_connection *conn);
  528. /**
  529. * Stores the user provided close handler
  530. */
  531. void (*userCloseHandler)(const struct mg_connection *conn);
  532. };
  533. #endif /* __cplusplus */
  534. #endif /* _CIVETWEB_SERVER_H_ */