CivetServer.h 17 KB

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