loader.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. // Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #ifndef ACL_LOADER_H
  15. #define ACL_LOADER_H
  16. #include "acl.h"
  17. #include <cc/data.h>
  18. #include <boost/function.hpp>
  19. #include <boost/shared_ptr.hpp>
  20. #include <map>
  21. namespace isc {
  22. namespace acl {
  23. /**
  24. * \brief Exception for bad ACL specifications.
  25. *
  26. * This will be thrown by the Loader if the ACL description is malformed
  27. * in some way.
  28. *
  29. * It also can hold optional JSON element where was the error detected, so
  30. * it can be examined.
  31. *
  32. * Checks may subclass this exception for similar errors if they see it fit.
  33. */
  34. class LoaderError : public BadValue {
  35. private:
  36. const data::ConstElementPtr element_;
  37. public:
  38. /**
  39. * \brief Constructor.
  40. *
  41. * Should be used with isc_throw if the fourth argument isn't used.
  42. *
  43. * \param file The file where the throw happened.
  44. * \param line Similar as file, just for the line number.
  45. * \param what Human readable description of what happened.
  46. * \param element This might be passed to hold the JSON element where
  47. * the error was detected.
  48. */
  49. LoaderError(const char* file, size_t line, const char* what,
  50. data::ConstElementPtr element = data::ConstElementPtr()) :
  51. BadValue(file, line, what),
  52. element_(element)
  53. {}
  54. ~ LoaderError() throw() {}
  55. /**
  56. * \brief Get the element.
  57. *
  58. * This returns the element where the error was detected. Note that it
  59. * might be NULL in some situations.
  60. */
  61. const data::ConstElementPtr& element() const {
  62. return (element_);
  63. }
  64. };
  65. /**
  66. * \brief Loader of the default actions of ACLs.
  67. *
  68. * Declared outside the Loader class, as this one does not need to be
  69. * templated. This will throw LoaderError if the parameter isn't string
  70. * or if it doesn't contain one of the accepted values.
  71. *
  72. * \param action The JSON representation of the action. It must be a string
  73. * and contain one of "ACCEPT", "REJECT" or "DENY".
  74. * \note We could define different names or add aliases if needed.
  75. */
  76. Action defaultActionLoader(data::ConstElementPtr action);
  77. /**
  78. * \brief Loader of ACLs.
  79. *
  80. * The goal of this class is to convert JSON description of an ACL to object
  81. * of the Acl class (including the checks inside it).
  82. *
  83. * The class can be used to load the checks only. This is supposed to be used
  84. * by compound checks to create the subexpressions.
  85. *
  86. * To allow any kind of checks to exist in the application, creators are
  87. * registered for the names of the checks.
  88. */
  89. template<typename Context, typename Action = isc::acl::Action> class Loader {
  90. public:
  91. /**
  92. * \brief Constructor.
  93. *
  94. * \param default_action The default action for created ACLs.
  95. * \param actionLoader is the loader which will be used to convert actions
  96. * from their JSON representation. The default value is suitable for
  97. * the isc::acl::Action enum. If you did not specify the second
  98. * template argument, you don't need to specify this loader.
  99. */
  100. Loader(const Action& defaultAction,
  101. const boost::function1<Action, data::ConstElementPtr>
  102. &actionLoader = &defaultActionLoader) :
  103. default_action_(defaultAction),
  104. action_loader_(actionLoader)
  105. {}
  106. /**
  107. * \brief Creator of the checks.
  108. *
  109. * This can be registered within the Loader and will be used to create the
  110. * checks.
  111. */
  112. class CheckCreator {
  113. public:
  114. /**
  115. * \brief List of names supported by this loader.
  116. *
  117. * List of all names for which this loader is able to create the
  118. * checks. There can be multiple names, to support both aliases
  119. * to the same checks and creators capable of creating multiple
  120. * types of checks.
  121. */
  122. virtual std::vector<std::string> names() const = 0;
  123. /**
  124. * \brief Creates the check.
  125. *
  126. * This function does the actuall creation. It is passed all the
  127. * relevant data and is supposed to return shared pointer to the
  128. * check.
  129. *
  130. * It is expected to throw the LoaderError exception when the
  131. * definition is invalid.
  132. *
  133. * \param name The type name of the check. If the creator creates
  134. * only one type of check, it can safely ignore this parameter.
  135. * \param definition The part of JSON describing the parameters of
  136. * check. As there's no way for the loader to know how the
  137. * parameters might look like, they are not checked in any way.
  138. * Therefore it's up to the creator (or the check being created)
  139. * to validate the data and throw if it is bad.
  140. */
  141. virtual boost::shared_ptr<Check<Context> > create(
  142. const std::string& name, data::ConstElementPtr definition) = 0;
  143. /**
  144. * \brief Is list or-abbreviation allowed?
  145. *
  146. * If this returns true and the parameter is list, the loader will
  147. * call the create method with each element of the list and aggregate
  148. * all the results in OR compound check. If it is false, the parameter
  149. * is passed verbatim no matter if it is or isn't a list.
  150. *
  151. * The rationale behind this is that it is common to specify list of
  152. * something that matches (eg. list of IP addresses).
  153. */
  154. virtual bool allowListAbbreviation() const {
  155. return (true);
  156. }
  157. };
  158. /**
  159. * \brief Register another check creator.
  160. *
  161. * Adds a creator to the list of known ones. The creator's list of names
  162. * must be disjoint with the names already known to the creator or the
  163. * LoaderError exception is thrown. In such case, the creator is not
  164. * registered under any of the names. In case of other exceptions, like
  165. * bad_alloc, only weak exception safety is guaranteed.
  166. *
  167. * \param creator Shared pointer to the creator.
  168. * \note We don't support deregistration yet, but it is expected it will
  169. * be needed in future, when we have some kind of plugins. These
  170. * plugins might want to unload, in which case they would need to
  171. * deregister their creators. It is expected they would pass the same
  172. * pointer to such method as they pass here.
  173. */
  174. void registerCreator(boost::shared_ptr<CheckCreator> creator) {
  175. // First check we can insert all the names
  176. typedef std::vector<std::string> Strings;
  177. const Strings names(creator->names());
  178. for (Strings::const_iterator i(names.begin()); i != names.end();
  179. ++i) {
  180. if (creators_.find(*i) != creators_.end()) {
  181. isc_throw(LoaderError, "The loader already contains creator "
  182. "named " << *i);
  183. }
  184. }
  185. // Now insert them
  186. for (Strings::const_iterator i(names.begin()); i != names.end();
  187. ++i) {
  188. creators_[*i] = creator;
  189. }
  190. }
  191. /**
  192. * \brief Load a check.
  193. *
  194. * This parses a check dict (block) and calls a creator (or creators, if
  195. * more than one check is found inside) for it. It ignores the "action"
  196. * key, as it is a reserved keyword used to specify actions inside the
  197. * ACL.
  198. *
  199. * This may throw LoaderError if it is not a dict or if some of the type
  200. * names is not known (there's no creator registered for it). The
  201. * exceptions from creators aren't caught.
  202. *
  203. * \param description The JSON description of the check.
  204. */
  205. boost::shared_ptr<Check<Context> > loadCheck(const data::ConstElementPtr&
  206. description)
  207. {
  208. // Get the description as a map
  209. typedef std::map<std::string, data::ConstElementPtr> Map;
  210. Map map;
  211. try {
  212. map = description->mapValue();
  213. }
  214. catch (const data::TypeError&) {
  215. throw LoaderError(__FILE__, __LINE__,
  216. "Check description is not a map",
  217. description);
  218. }
  219. // Call the internal part with extracted map
  220. return (loadCheck(description, map));
  221. }
  222. /**
  223. * \brief Load an ACL.
  224. *
  225. * This parses an ACL list, creates the checks and actions of each element
  226. * and returns it. It may throw LoaderError if it isn't a list or the
  227. * "action" key is missing in some element. Also, no exceptions from
  228. * loadCheck (therefore from whatever creator is used) and from the
  229. * actionLoader passed to constructor are not caught.
  230. *
  231. * \param description The JSON list of ACL.
  232. */
  233. boost::shared_ptr<Acl<Context, Action> > load(const data::ConstElementPtr&
  234. description)
  235. {
  236. // We first check it's a list, so we can use the list reference
  237. // (the list may be huge)
  238. if (description->getType() != data::Element::list) {
  239. throw LoaderError(__FILE__, __LINE__, "ACL not a list",
  240. description);
  241. }
  242. // First create an empty ACL
  243. const List &list(description->listValue());
  244. boost::shared_ptr<Acl<Context, Action> > result(
  245. new Acl<Context, Action>(default_action_));
  246. // Run trough the list of elements
  247. for (List::const_iterator i(list.begin()); i != list.end(); ++i) {
  248. Map map;
  249. try {
  250. map = (*i)->mapValue();
  251. }
  252. catch (const data::TypeError&) {
  253. throw LoaderError(__FILE__, __LINE__, "ACL element not a map",
  254. *i);
  255. }
  256. // Create an action for the element
  257. const Map::const_iterator action(map.find("action"));
  258. if (action == map.end()) {
  259. throw LoaderError(__FILE__, __LINE__,
  260. "No action in ACL element", *i);
  261. }
  262. const Action acValue(action_loader_(action->second));
  263. // Now create the check if there's one
  264. if (map.size() >= 2) { // One is the action, another one the check
  265. result->append(loadCheck(*i, map), acValue);
  266. } else {
  267. // In case there's no check, this matches every time. We
  268. // simulate it by our own private "True" check.
  269. result->append(boost::shared_ptr<Check<Context> >(new True()),
  270. acValue);
  271. }
  272. }
  273. return (result);
  274. }
  275. private:
  276. // Some type aliases to save typing
  277. typedef std::map<std::string, boost::shared_ptr<CheckCreator> > Creators;
  278. typedef std::map<std::string, data::ConstElementPtr> Map;
  279. typedef std::vector<data::ConstElementPtr> List;
  280. // Private members
  281. Creators creators_;
  282. const Action default_action_;
  283. const boost::function1<Action, data::ConstElementPtr> action_loader_;
  284. /**
  285. * \brief Internal version of loadCheck.
  286. *
  287. * This is the internal part, shared between load and loadCheck.
  288. * \param description The bit of JSON (used in exceptions).
  289. * \param map The extracted map describing the check. It does change
  290. * the map.
  291. */
  292. boost::shared_ptr<Check<Context> > loadCheck(const data::ConstElementPtr&
  293. description, Map& map)
  294. {
  295. // Remove the action keyword
  296. map.erase("action");
  297. // Now, do we have any definition? Or is it and abbreviation?
  298. switch (map.size()) {
  299. case 0:
  300. throw LoaderError(__FILE__, __LINE__,
  301. "Check description is empty",
  302. description);
  303. case 1: {
  304. // Get the first and only item
  305. const Map::const_iterator checkDesc(map.begin());
  306. const std::string& name(checkDesc->first);
  307. const typename Creators::const_iterator
  308. creatorIt(creators_.find(name));
  309. if (creatorIt == creators_.end()) {
  310. throw LoaderError(__FILE__, __LINE__,
  311. ("No creator for ACL check " +
  312. name).c_str(),
  313. description);
  314. }
  315. if (creatorIt->second->allowListAbbreviation() &&
  316. checkDesc->second->getType() == data::Element::list) {
  317. throw LoaderError(__FILE__, __LINE__,
  318. "Not implemented (OR-abbreviated form)",
  319. checkDesc->second);
  320. }
  321. // Create the check and return it
  322. return (creatorIt->second->create(name, checkDesc->second));
  323. }
  324. default:
  325. throw LoaderError(__FILE__, __LINE__,
  326. "Not implemented (AND-abbreviated form)",
  327. description);
  328. }
  329. }
  330. /**
  331. * \brief Check that always matches.
  332. *
  333. * This one is used internally for ACL elements without condition. We may
  334. * want to make this publicly accesible sometime maybe, but for now,
  335. * there's no need.
  336. */
  337. class True : public Check<Context> {
  338. public:
  339. virtual bool matches(const Context&) const { return (true); };
  340. virtual unsigned cost() const { return (1); }
  341. // We don't write "true" here, as this one was created using empty
  342. // input
  343. virtual std::string toText() const { return ""; }
  344. };
  345. };
  346. }
  347. }
  348. #endif