hooks_user.dox 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. // Copyright (C) 2013-2014 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. // Note: the prefix "hooksdg" to all labels is an abbreviation for "Hooks
  15. // Developer's Guide" and is used to prevent a clash with symbols in any
  16. // other Doxygen file.
  17. /**
  18. @page hooksdgDevelopersGuide Hooks Developer's Guide
  19. @section hooksdgIntroduction Introduction
  20. Although the Kea framework and its DHCP programs
  21. provide comprehensive functionality, there will be times when it does
  22. not quite do what you require: the processing has to be extended in some
  23. way to solve your problem.
  24. Since the Kea source code is freely available (Kea being an
  25. open-source project), one option is to modify it to do what
  26. you want. Whilst perfectly feasible, there are drawbacks:
  27. - Although well-documented, Kea is a large program. Just
  28. understanding how it works will take a significant amount of time. In
  29. addition, despite the fact that its object-oriented design keeps the
  30. coupling between modules to a minimum, an inappropriate change to one
  31. part of the program during the extension could cause another to
  32. behave oddly or to stop working altogether.
  33. - The change may need to be re-applied or re-written with every new
  34. version of Kea. As new functionality is added or bugs are fixed,
  35. the code or algorithms in the core software may change - and may change
  36. significantly.
  37. To overcome these problems, Kea provides the "Hooks" interface -
  38. a defined interface for third-party or user-written code. (For ease of
  39. reference in the rest of this document, all such code will be referred
  40. to as "user code".) At specific points in its processing
  41. ("hook points") Kea will make a call to this code. The call passes
  42. data that the user code can examine and, if required, modify.
  43. Kea uses the modified data in the remainder of its processing.
  44. In order to minimise the interaction between Kea and the user
  45. code, the latter is built independently of Kea in the form of
  46. a shared library (or libraries). These are made known to Kea
  47. through its configuration mechanism, and Kea loads the library at
  48. run time. Libraries can be unloaded and reloaded as needed while Kea
  49. is running.
  50. Use of a defined API and the Kea configuration mechanism means that
  51. as new versions of Kea are released, there is no need to modify
  52. the user code. Unless there is a major change in an interface
  53. (which will be clearly documented), all that will be required is a rebuild
  54. of the libraries.
  55. @note Although the defined interface should not change, the internals
  56. of some of the classes and structures referenced by the user code may
  57. change between versions of Kea. These changes have to be reflected
  58. in the compiled version of the software, hence the need for a rebuild.
  59. @subsection hooksdgLanguages Languages
  60. The core of Kea is written in C++. While it is the intention to
  61. provide interfaces into user code written in other languages, the initial
  62. versions of the Hooks system requires that user code be written in C++.
  63. All examples in this guide are in that language.
  64. @subsection hooksdgTerminology Terminology
  65. In the remainder of this guide, the following terminology is used:
  66. - Hook/Hook Point - used interchageably, this is a point in the code at
  67. which a call to user functions is made. Each hook has a name and
  68. each hook can have any number (including 0) of user functions
  69. attached to it.
  70. - Callout - a user function called by the server at a hook
  71. point. This is so-named because the server "calls out" to the library
  72. to execute a user function.
  73. - Framework function - the functions that a user library needs to
  74. supply in order for the hooks framework to load and unload the library.
  75. - User code/user library - non-Kea code that is compiled into a
  76. shared library and loaded by Kea into its address space.
  77. @section hooksdgTutorial Tutorial
  78. To illustrate how to write code that integrates with Kea, we will
  79. use the following (rather contrived) example:
  80. The Kea DHCPv4 server is used to allocate IPv4 addresses to clients
  81. (as well as to pass them other information such as the address of DNS
  82. servers). We will suppose that we need to classify clients requesting
  83. IPv4 addresses according to their hardware address, and want to log both
  84. the hardware address and allocated IP address for the clients of interest.
  85. The following sections describe how to implement these requirements.
  86. The code presented here is not efficient and there are better ways of
  87. doing the task. The aim however, is to illustrate the main features of
  88. user hook code not to provide an optimal solution.
  89. @subsection hooksdgFrameworkFunctions Framework Functions
  90. Loading and initializing a library holding user code makes use
  91. of three (user-supplied) functions:
  92. - version - defines the version of Kea code with which the user-library
  93. is built
  94. - load - called when the library is loaded by the server.
  95. - unload - called when the library is unloaded by the server.
  96. Of these, only "version" is mandatory, although in our example, all three
  97. are used.
  98. @subsubsection hooksdgVersionFunction The "version" Function
  99. "version" is used by the hooks framework to check that the libraries
  100. it is loading are compatible with the version of Kea being run.
  101. Although the hooks system allows Kea and user code to interface
  102. through a defined API, the relationship is somewhat tight in that the
  103. user code will depend on the internal structures of Kea. If these
  104. change - as they can between Kea releases - and Kea is run with
  105. a version of user code built against an earlier version of Kea, a program
  106. crash could result.
  107. To guard against this, the "version" function must be provided in every
  108. library. It returns a constant defined in header files of the version
  109. of Kea against which it was built. The hooks framework checks this
  110. for compatibility with the running version of Kea before loading
  111. the library.
  112. In this tutorial, we'll put "version" in its own file, version.cc. The
  113. contents are:
  114. @code
  115. // version.cc
  116. #include <hooks/hooks.h>
  117. extern "C" {
  118. int version() {
  119. return (KEA_HOOKS_VERSION);
  120. }
  121. }
  122. @endcode
  123. The file "hooks/hooks.h" is specified relative to the Kea libraries
  124. source directory - this is covered later in the section @ref hooksdgBuild.
  125. It defines the symbol KEA_HOOKS_VERSION, which has a value that changes
  126. on every release of Kea: this is the value that needs to be returned
  127. to the hooks framework.
  128. A final point to note is that the definition of "version" is enclosed
  129. within 'extern "C"' braces. All functions accessed by the hooks
  130. framework use C linkage, mainly to avoid the name mangling that
  131. accompanies use of the C++ compiler, but also to avoid issues related
  132. to namespaces.
  133. @subsubsection hooksdgLoadUnloadFunctions The "load" and "unload" Functions
  134. As the names suggest, "load" is called when a library is loaded and
  135. "unload" called when it is unloaded. (It is always guaranteed that
  136. "load" is called: "unload" may not be called in some circumstances,
  137. e.g. if the system shuts down abnormally.) These functions are the
  138. places where any library-wide resources are allocated and deallocated.
  139. "load" is also the place where any callouts with non-standard names
  140. (names that are not hook point names) can be registered:
  141. this is covered further in the section @ref hooksdgCalloutRegistration.
  142. The example does not make any use callouts with non-standard names. However,
  143. as our design requires that the log file be open while Kea is active
  144. and the library loaded, we'll open the file in the "load" function and close
  145. it in "unload".
  146. We create two files, one for the file handle declaration:
  147. @code
  148. // library_common.h
  149. #ifndef LIBRARY_COMMON_H
  150. #define LIBRARY_COMMON_H
  151. #include <fstream>
  152. // "Interesting clients" log file handle declaration.
  153. extern std::fstream interesting;
  154. #endif // LIBRARY_COMMON_H
  155. @endcode
  156. ... and one to hold the "load" and "unload" functions:
  157. @code
  158. // load_unload.cc
  159. #include <hooks/hooks.h>
  160. #include "library_common.h"
  161. using namespace isc::hooks;
  162. // "Interesting clients" log file handle definition.
  163. std::fstream interesting;
  164. extern "C" {
  165. int load(LibraryHandle&) {
  166. interesting.open("/data/clients/interesting.log",
  167. std::fstream::out | std::fstream::app);
  168. return (interesting ? 0 : 1);
  169. }
  170. int unload() {
  171. if (interesting) {
  172. interesting.close();
  173. }
  174. return (0);
  175. }
  176. }
  177. @endcode
  178. Notes:
  179. - The file handle ("interesting") is declared in a header file and defined
  180. outside of any function. This means it can be accessed by any function
  181. within the user library. For convenience, the definition is in the
  182. load_unload.cc file.
  183. - "load" is called with a LibraryHandle argument, this being used in
  184. the registration of functions. As no functions are being registered
  185. in this example, the argument specification omits the variable name
  186. (whilst retaining the type) to avoid an "unused variable" compiler
  187. warning. (The LibraryHandle and its use is discussed in the section
  188. @ref hooksdgLibraryHandle.)
  189. - In the current version of the hooks framework, it is not possible to pass
  190. any configuration information to the "load" function. The name of the log
  191. file must therefore be hard-coded as an absolute path name or communicated
  192. to the user code by some other means.
  193. - "load" must 0 on success and non-zero on error. The hooks framework
  194. will abandon the loading of the library if "load" returns an error status.
  195. (In this example, "interesting" can be tested as a boolean value,
  196. returning "true" if the file opened successfully.)
  197. - "unload" closes the log file if it is open and is a no-op otherwise. As
  198. with "load", a zero value must be returned on success and a non-zero value
  199. on an error. The hooks framework will record a non-zero status return
  200. as an error in the current Kea log but otherwise ignore it.
  201. - As before, the function definitions are enclosed in 'extern "C"' braces.
  202. @subsection hooksdgCallouts Callouts
  203. Having sorted out the framework, we now come to the functions that
  204. actually do something. These functions are known as "callouts" because
  205. the Kea code "calls out" to them. Each Kea server has a number of
  206. hooks to which callouts can be attached: server-specific documentation
  207. describes in detail the points in the server at which the hooks are
  208. present together with the data passed to callouts attached to them.
  209. Before we continue with the example, we'll discuss how arguments are
  210. passed to callouts and information is returned to the server. We will
  211. also discuss how information can be moved between callouts.
  212. @subsubsection hooksdgCalloutSignature The Callout Signature
  213. All callouts are declared with the signature:
  214. @code
  215. extern "C" {
  216. int callout(CalloutHandle& handle);
  217. }
  218. @endcode
  219. (As before, the callout is declared with "C" linkage.) Information is passed
  220. between Kea and the callout through name/value pairs in the CalloutHandle
  221. object. The object is also used to pass information between callouts on a
  222. per-request basis. (Both of these concepts are explained below.)
  223. A callout returns an "int" as a status return. A value of 0 indicates
  224. success, anything else signifies an error. The status return has no
  225. effect on server processing; the only difference between a success
  226. and error code is that if the latter is returned, the server will
  227. log an error, specifying both the library and hook that generated it.
  228. Effectively the return status provides a quick way for a callout to log
  229. error information to the Kea logging system.
  230. @subsubsection hooksdgArguments Callout Arguments
  231. The CalloutHandle object provides two methods to get and set the
  232. arguments passed to the callout. These methods are called (naturally
  233. enough) getArgument and SetArgument. Their usage is illustrated by the
  234. following code snippets.
  235. @code
  236. // Server-side code snippet to show the setting of arguments
  237. int count = 10;
  238. boost::shared_ptr<Pkt4> pktptr = ... // Set to appropriate value
  239. // Assume that "handle" has been created
  240. handle.setArgument("data_count", count);
  241. handle.setArgument("inpacket", pktptr);
  242. // Call the callouts attached to the hook
  243. ...
  244. // Retrieve the modified values
  245. handle.getArgument("data_count", count);
  246. handle.getArgument("inpacket", pktptr);
  247. @endcode
  248. In the callout
  249. @code
  250. int number;
  251. boost::shared_ptr<Pkt4> packet;
  252. // Retrieve data set by the server.
  253. handle.getArgument("data_count", number);
  254. handle.getArgument("inpacket", packet);
  255. // Modify "number"
  256. number = ...;
  257. // Update the arguments to send the value back to the server.
  258. handle.setArgument("data_count", number);
  259. @endcode
  260. As can be seen "getArgument" is used to retrieve data from the
  261. CalloutHandle, and setArgument used to put data into it. If a callout
  262. wishes to alter data and pass it back to the server, it should retrieve
  263. the data with getArgument, modify it, and call setArgument to send
  264. it back.
  265. There are several points to be aware of:
  266. - the data type of the variable in the call to getArgument must match
  267. the data type of the variable passed to the corresponding setArgument
  268. <B>exactly</B>: using what would normally be considered to be a
  269. "compatible" type is not enough. For example, if the server passed
  270. an argument as an "int" and the callout attempted to retrieve it as a
  271. "long", an exception would be thrown even though any value that can
  272. be stored in an "int" will fit into a "long". This restriction also
  273. applies the "const" attribute but only as applied to data pointed to by
  274. pointers, e.g. if an argument is defined as a "char*", an exception will
  275. be thrown if an attempt is made to retrieve it into a variable of type
  276. "const char*". (However, if an argument is set as a "const int", it can
  277. be retrieved into an "int".) The documentation of each hook point will
  278. detail the data type of each argument.
  279. - Although all arguments can be modified, some altered values may not
  280. be read by the server. (These would be ones that the server considers
  281. "read-only".) Consult the documentation of each hook to see whether an
  282. argument can be used to transfer data back to the server.
  283. - If a pointer to an object is passed to a callout (either a "raw"
  284. pointer, or a boost smart pointer (as in the example above), and the
  285. underlying object is altered through that pointer, the change will be
  286. reflected in the server even if no call is made to setArgument.
  287. In all cases, consult the documentation for the particular hook to see whether
  288. parameters can be modified. As a general rule:
  289. - Do not alter arguments unless you mean the change to be reflected in
  290. the server.
  291. - If you alter an argument, call CalloutHandle::setArgument to update the
  292. value in the CalloutHandle object.
  293. @subsubsection hooksdgSkipFlag The "Skip" Flag
  294. When a to callouts attached to a hook returns, the server will usually continue
  295. its processing. However, a callout might have done something that means that
  296. the server should follow another path. Possible actions a server could take
  297. include:
  298. - Skip the next stage of processing because the callout has already
  299. done it. For example, a hook is located just before the DHCP server
  300. allocates an address to the client. A callout may decide to allocate
  301. special addresses for certain clients, in which case it needs to tell
  302. the server not to allocate an address in this case.
  303. - Drop the packet and continue with the next request. A possible scenario
  304. is a server where a callout inspects the hardware address of the client
  305. sending the packet and compares it against a black list; if the address
  306. is on it, the callout notifies the server to drop the packet.
  307. To handle these common cases, the CalloutHandle has a "skip" flag.
  308. This is set by a callout when it wishes the server to skip normal
  309. processing. It is set false by the hooks framework before callouts on a
  310. hook are called. If the flag is set on return, the server will take the
  311. "skip" action relevant for the hook.
  312. The methods to get and set the "skip" flag are getSkip and setSkip. Their
  313. usage is intuitive:
  314. @code
  315. // Get the current setting of the skip flag.
  316. bool skip = handle.getSkip();
  317. // Do some processing...
  318. :
  319. if (lease_allocated) {
  320. // Flag the server to skip the next step of the processing as we
  321. // already have an address.
  322. handle.setSkip(true);
  323. }
  324. return;
  325. @endcode
  326. Like arguments, the "skip" flag is passed to all callouts on a hook. Callouts
  327. later in the list are able to examine (and modify) the settings of earlier ones.
  328. @subsubsection hooksdgCalloutContext Per-Request Context
  329. Although the Kea modules can be characterised as handling a single
  330. packet at a time - e.g. the DHCPv4 server receives a DHCPDISCOVER packet,
  331. processes it and responds with an DHCPOFFER, this may not always be true.
  332. Future developments may have the server processing multiple packets
  333. simultaneously, or to suspend processing on a packet and resume it at
  334. a later time after other packets have been processed.
  335. As well as argument information, the CalloutHandle object can be used by
  336. callouts to attach information to a packet being handled by the server.
  337. This information (known as "context") is not used by the server: its purpose
  338. is to allow callouts to pass information between one another on a
  339. per-packet basis.
  340. Context associated with a packet only exists only for the duration of the
  341. processing of that packet: when processing is completed, the context is
  342. destroyed. A new packet starts with a new (empty) context. Context is
  343. particularly useful in servers that may be processing multiple packets
  344. simultaneously: callouts can effectively attach data to a packet that
  345. follows the packet around the system.
  346. Context information is held as name/value pairs in the same way
  347. as arguments, being accessed by the pair of methods setContext and
  348. getContext. They have the same restrictions as the setArgument and
  349. getArgument methods - the type of data retrieved from context must
  350. <B>exactly</B> match the type of the data set.
  351. The example in the next section illustrates their use.
  352. @subsection hooksdgExampleCallouts Example Callouts
  353. Continuing with the tutorial, the requirements need us to retrieve the
  354. hardware address of the incoming packet, classify it, and write it,
  355. together with the assigned IP address, to a log file. Although we could
  356. do this in one callout, for this example we'll use two:
  357. - pkt4_receive - a callout on this hook is invoked when a packet has been
  358. received and has been parsed. It is passed a single argument, "query4"
  359. which is an isc::dhcp::Pkt4 object (representing a DHCP v4 packet).
  360. We will do the classification here.
  361. - pkt4_send - called when a response is just about to be sent back to
  362. the client. It is passed a single argument "response4". This is the
  363. point at which the example code will write the hardware and IP addresses
  364. to the log file.
  365. The standard for naming callouts is to give them the same name as
  366. the hook. If this is done, the callouts will be automatically found
  367. by the Hooks system (this is discussed further in section @ref
  368. hooksdgCalloutRegistration). For our example, we will assume this is the
  369. case, so the code for the first callout (used to classify the client's
  370. hardware address) is:
  371. @code
  372. // pkt_receive4.cc
  373. #include <hooks/hooks.h>
  374. #include <dhcp/pkt4.h>
  375. #include "library_common.h"
  376. #include <string>
  377. using namespace isc::dhcp;
  378. using namespace isc::hooks;
  379. using namespace std;
  380. extern "C" {
  381. // This callout is called at the "pkt4_receive" hook.
  382. int pkt4_receive(CalloutHandle& handle) {
  383. // A pointer to the packet is passed to the callout via a "boost" smart
  384. // pointer. The include file "pkt4.h" typedefs a pointer to the Pkt4
  385. // object as Pkt4Ptr. Retrieve a pointer to the object.
  386. Pkt4Ptr query4_ptr;
  387. handle.getArgument("query4", query4_ptr);
  388. // Point to the hardware address.
  389. HWAddrPtr hwaddr_ptr = query4_ptr->getHWAddr();
  390. // The hardware address is held in a public member variable. We'll classify
  391. // it as interesting if the sum of all the bytes in it is divisible by 4.
  392. // (This is a contrived example after all!)
  393. long sum = 0;
  394. for (int i = 0; i < hwaddr_ptr->hwaddr_.size(); ++i) {
  395. sum += hwaddr_ptr->hwaddr_[i];
  396. }
  397. // Classify it.
  398. if (sum % 4 == 0) {
  399. // Store the text form of the hardware address in the context to pass
  400. // to the next callout.
  401. string hwaddr = hwaddr_ptr->toText();
  402. handle.setContext("hwaddr", hwaddr);
  403. }
  404. return (0);
  405. };
  406. }
  407. @endcode
  408. The pkt4_receive callout placed the hardware address of an interesting client in
  409. the "hwaddr" context for the packet. Turning now to the callout that will
  410. write this information to the log file:
  411. @code
  412. // pkt4_send.cc
  413. #include <hooks/hooks.h>
  414. #include <dhcp/pkt4.h>
  415. #include "library_common.h"
  416. #include <string>
  417. using namespace isc::dhcp;
  418. using namespace isc::hooks;
  419. using namespace std;
  420. extern "C" {
  421. // This callout is called at the "pkt4_send" hook.
  422. int pkt4_send(CalloutHandle& handle) {
  423. // Obtain the hardware address of the "interesting" client. We have to
  424. // use a try...catch block here because if the client was not interesting,
  425. // no information would be set and getArgument would thrown an exception.
  426. string hwaddr;
  427. try {
  428. handle.getContext("hwaddr", hwaddr);
  429. // getContext didn't throw so the client is interesting. Get a pointer
  430. // to the reply.
  431. Pkt4Ptr response4_ptr;
  432. handle.getArgument("response4", response4_ptr);
  433. // Get the string form of the IP address.
  434. string ipaddr = response4_ptr->getYiaddr().toText();
  435. // Write the information to the log file.
  436. interesting << hwaddr << " " << ipaddr << "\n";
  437. // ... and to guard against a crash, we'll flush the output stream.
  438. flush(interesting);
  439. } catch (const NoSuchCalloutContext&) {
  440. // No such element in the per-request context with the name "hwaddr".
  441. // This means that the request was not an interesting, so do nothing
  442. // and dismiss the exception.
  443. }
  444. return (0);
  445. }
  446. }
  447. @endcode
  448. @subsection hooksdgBuild Building the Library
  449. Building the code requires building a shareable library. This requires
  450. the the code be compiled as positition-independent code (using the
  451. compiler's "-fpic" switch) and linked as a shared library (with the
  452. linker's "-shared" switch). The build command also needs to point to
  453. the Kea include directory and link in the appropriate libraries.
  454. Assuming that Kea has been installed in the default location, the
  455. command line needed to create the library using the Gnu C++ compiler on a
  456. Linux system is:
  457. @code
  458. g++ -I /usr/include/kea -L /usr/lib/kea/lib -fpic -shared -o example.so \
  459. load_unload.cc pkt4_receive.cc pkt4_send.cc version.cc \
  460. -lkea-dhcpsrv -lkea-dhcp++ -lkea-hooks -lkea-log -lkea-util -lkea-exceptions
  461. @endcode
  462. Notes:
  463. - The compilation command and switches required may vary depending on
  464. your operating system and compiler - consult the relevant documentation
  465. for details.
  466. - The values for the "-I" and "-L" switches depend on where you have
  467. installed Kea.
  468. - The list of libraries that need to be included in the command line
  469. depends on the functionality used by the hook code and the module to
  470. which they are attached. Depending on operating system, you may also need
  471. to explicitly list libraries on which the Kea libraries you link against depend.
  472. @subsection hooksdgConfiguration Configuring the Hooks Library
  473. The final step is to make the library known to Kea. The configuration
  474. keywords of all Kea modules to which hooks can be added contain the
  475. "hooks-libraries" element and user libraries are added to this. (The Kea
  476. hooks system can handle multiple libraries - this is discussed below.)
  477. To add the example library (assumed to be in /usr/local/lib) to the
  478. DHCPv4 module, it must be listed in the "hooks-libraries" element of the
  479. "Dhcp4" part of the configuration file:
  480. @code
  481. "Dhcp4": {
  482. :
  483. "hooks-libraries": [ "/usr/local/lib/example.so" ]
  484. :
  485. }
  486. @endcode
  487. (Note that "hooks" is plural.)
  488. The DHCPv4 server will load the library and execute the callouts each time a
  489. request is received.
  490. @note The above assumes that the hooks library will be used with a version of
  491. Kea that is dynamically-linked. For information regarding running
  492. hooks libraries against a statically-linked Kea, see
  493. @ref hooksdgStaticallyLinkedKea.
  494. @section hooksdgAdvancedTopics Advanced Topics
  495. @subsection hooksdgContextCreateDestroy Context Creation and Destruction
  496. As well as the hooks defined by the server, the hooks framework defines
  497. two hooks of its own, "context_create" and "context_destroy". The first
  498. is called when a request is created in the server, before any of the
  499. server-specific hooks gets called. It's purpose it to allow a library
  500. to initialize per-request context. The second is called after all
  501. server-defined hooks have been processed, and is to allow a library to
  502. tidy up.
  503. As an example, the pkt4_send example above required that the code
  504. check for an exception being thrown when accessing the "hwaddr" context
  505. item in case it was not set. An alternative strategy would have been to
  506. provide a callout for the "context_create" hook and set the context item
  507. "hwaddr" to an empty string. Instead of needing to handle an exception,
  508. pkt4_send would be guaranteed to get something when looking for
  509. the hwaddr item and so could write or not write the output depending on
  510. the value.
  511. In most cases, "context_destroy" is not needed as the Hooks system
  512. automatically deletes context. An example where it could be required
  513. is where memory has been allocated by a callout during the processing
  514. of a request and a raw pointer to it stored in the context object. On
  515. destruction of the context, that memory will not be automatically
  516. released. Freeing in the memory in the "context_destroy callout will solve
  517. that problem.
  518. Actually, when the context is destroyed, the destructor
  519. associated with any objects stored in it are run. Rather than point to
  520. allocated memory with a raw pointer, a better idea would be to point to
  521. it with a boost "smart" pointer and store that pointer in the context.
  522. When the context is destroyed, the smart pointer's destructor is run,
  523. which will automatically delete the pointed-to object.
  524. These approaches are illustrated in the following examples.
  525. Here it is assumed that the hooks library is performing some form of
  526. security checking on the packet and needs to maintain information in
  527. a user-specified "SecurityInformation" object. (The details of this
  528. fictitious object are of no concern here.) The object is created in
  529. the context_create callout and used in both the pkt4_receive and the
  530. pkt4_send callouts.
  531. @code
  532. // Storing information in a "raw" pointer. Assume that the
  533. #include <hooks/hooks.h>
  534. :
  535. extern "C" {
  536. // context_create callout - called when the request is created.
  537. int context_create(CalloutHandle& handle) {
  538. // Create the security information and store it in the context
  539. // for this packet.
  540. SecurityInformation* si = new SecurityInformation();
  541. handle.setContext("security_information", si);
  542. }
  543. // Callouts that use the context
  544. int pkt4_receive(CalloutHandle& handle) {
  545. // Retrieve the pointer to the SecurityInformation object
  546. SecurityInformation si;
  547. handle.getContext("security_information", si);
  548. :
  549. :
  550. // Set the security information
  551. si->setSomething(...);
  552. // The pointed-to information has been updated but the pointer has not been
  553. // altered, so there is no need to call setContext() again.
  554. }
  555. int pkt4_send(CalloutHandle& handle) {
  556. // Retrieve the pointer to the SecurityInformation object
  557. SecurityInformation si;
  558. handle.getContext("security_information", si);
  559. :
  560. :
  561. // Retrieve security information
  562. bool active = si->getSomething(...);
  563. :
  564. }
  565. // Context destruction. We need to delete the pointed-to SecurityInformation
  566. // object because we will lose the pointer to it when the CalloutHandle is
  567. // destroyed.
  568. int context_destroy(CalloutHandle& handle) {
  569. // Retrieve the pointer to the SecurityInformation object
  570. SecurityInformation si;
  571. handle.getContext("security_information", si);
  572. // Delete the pointed-to memory.
  573. delete si;
  574. }
  575. @endcode
  576. The requirement for the context_destroy callout can be eliminated if
  577. a Boost shared ptr is used to point to the allocated memory:
  578. @code
  579. // Storing information in a "raw" pointer. Assume that the
  580. #include <hooks/hooks.h>
  581. #include <boost/shared_ptr.hpp>
  582. :
  583. extern "C" {
  584. // context_create callout - called when the request is created.
  585. int context_create(CalloutHandle& handle) {
  586. // Create the security information and store it in the context for this
  587. // packet.
  588. boost::shared_ptr<SecurityInformation> si(new SecurityInformation());
  589. handle.setContext("security_information", si);
  590. }
  591. // Other than the data type, a shared pointer has similar semantics to a "raw"
  592. // pointer. Only the code from pkt4_receive is shown here.
  593. int pkt4_receive(CalloutHandle& handle) {
  594. // Retrieve the pointer to the SecurityInformation object
  595. boost::shared_ptr<SecurityInformation> si;
  596. handle.setContext("security_information", si);
  597. :
  598. :
  599. // Modify the security information
  600. si->setSomething(...);
  601. // The pointed-to information has been updated but the pointer has not
  602. // altered, so theree is no need to reset the context.
  603. }
  604. // No context_destroy callout is needed to delete the allocated
  605. // SecurityInformation object. When the CalloutHandle is destroyed, the shared
  606. // pointer object will be destroyed. If that is the last shared pointer to the
  607. // allocated memory, then it too will be deleted.
  608. @endcode
  609. (Note that a Boost shared pointer - rather than any other Boost smart pointer -
  610. should be used, as the pointer objects are copied within the hooks framework and
  611. only shared pointers have the correct behavior for the copy operation.)
  612. @subsection hooksdgCalloutRegistration Registering Callouts
  613. As briefly mentioned in @ref hooksdgExampleCallouts, the standard is for
  614. callouts in the user library to have the same name as the name of the
  615. hook to which they are being attached. This convention was followed
  616. in the tutorial, e.g. the callout that needed to be attached to the
  617. "pkt4_receive" hook was named pkt4_receive.
  618. The reason for this convention is that when the library is loaded, the
  619. hook framework automatically searches the library for functions with
  620. the same names as the server hooks. When it finds one, it attaches it
  621. to the appropriate hook point. This simplifies the loading process and
  622. bookkeeping required to create a library of callouts.
  623. However, the hooks system is flexible in this area: callouts can have
  624. non-standard names, and multiple callouts can be registered on a hook.
  625. @subsubsection hooksdgLibraryHandle The LibraryHandle Object
  626. The way into the part of the hooks framework that allows callout
  627. registration is through the LibraryHandle object. This was briefly
  628. introduced in the discussion of the framework functions, in that
  629. an object of this type is pass to the "load" function. A LibraryHandle
  630. can also be obtained from within a callout by calling the CalloutHandle's
  631. getLibraryHandle() method.
  632. The LibraryHandle provides three methods to manipulate callouts:
  633. - registerCallout - register a callout on a hook.
  634. - deregisterCallout - deregister a callout from a hook.
  635. - deregisterAllCallouts - deregister all callouts on a hook.
  636. The following sections cover some of the ways in which these can be used.
  637. @subsubsection hooksdgNonstandardCalloutNames Non-Standard Callout Names
  638. The example in the tutorial used standard names for the callouts. As noted
  639. above, it is possible to use non-standard names. Suppose, instead of the
  640. callout names "pkt4_receive" and "pkt4_send", we had named our callouts
  641. "classify" and "write_data". The hooks framework would not have registered
  642. these callouts, so we would have needed to do it ourself. The place to
  643. do this is the "load" framework function, and its code would have had to
  644. been modified to:
  645. @code
  646. int load(LibraryHandle& libhandle) {
  647. // Register the callouts on the hooks. We assume that a header file
  648. // declares the "classify" and "write_data" functions.
  649. libhandle.registerCallout("pkt4_receive", classify);
  650. libhandle.registerCallout("pkt4_send", write_data);
  651. // Open the log file
  652. interesting.open("/data/clients/interesting.log",
  653. std::fstream::out | std::fstream::app);
  654. return (interesting ? 0 : 1);
  655. }
  656. @endcode
  657. It is possible for a library to contain callouts with both standard and
  658. non-standard names: ones with standard names will be registered automatically,
  659. ones with non-standard names need to be registered manually.
  660. @subsubsection hooksdgMultipleCallouts Multiple Callouts on a Hook
  661. The Kea hooks framework allows multiple callouts to be attached to
  662. a hook point. Although it is likely to be rare for user code to need to
  663. do this, there may be instances where it make sense.
  664. To register multiple callouts on a hook, just call
  665. LibraryHandle::registerCallout multiple times on the same hook, e.g.
  666. @code
  667. libhandle.registerCallout("pkt4_receive", classify);
  668. libhandle.registerCallout("pkt4_receive", write_data);
  669. @endcode
  670. The hooks framework will call the callouts in the order they are
  671. registered. The same CalloutHandle is passed between them, so any
  672. change made to the CalloutHandle's arguments, "skip" flag, or per-request
  673. context by the first is visible to the second.
  674. @subsubsection hooksdgDynamicRegistration Dynamic Registration and Reregistration of Callouts
  675. The previous sections have dealt with callouts being registered during
  676. the call to "load". The hooks framework is more flexible than that
  677. in that callouts can be registered and deregistered within a callout.
  678. In fact, a callout is able to register or deregister itself, and a callout
  679. is able to be registered on a hook multiple times.
  680. Using our contrived example again, the DHCPv4 server processes one request
  681. to completion before it starts processing the next. With this knowledge,
  682. we could alter the logic of the code so that the callout attached to the
  683. "pkt4_receive" hook registers the callout doing the logging when it detects
  684. an interesting packet, and the callout doing the logging deregisters
  685. itself in its execution. The relevant modifications to the code in
  686. the tutorial are shown below:
  687. @code
  688. // pkt4_receive.cc
  689. // :
  690. int pkt4_receive(CalloutHandle& handle) {
  691. :
  692. :
  693. // Classify it.
  694. if (sum % 4 == 0) {
  695. // Store the text form of the hardware address in the context to pass
  696. // to the next callout.
  697. handle.setContext("hwaddr", hwaddr_ptr->hwaddr_.toText());
  698. // Register the callback to log the data.
  699. handle.getLibraryHandle().registerCallout("pkt4_send", write_data);
  700. }
  701. return (0);
  702. };
  703. @endcode
  704. @code
  705. // pkt4_send.cc
  706. :
  707. int write_data(CalloutHandle& handle) {
  708. // Obtain the hardware address of the "interesting" client. As the
  709. // callback is only registered when interesting data is present, we
  710. // know that the context contains the hardware address so an exception
  711. // will not be thrown when we call getArgument().
  712. string hwaddr;
  713. handle.getArgument("hwaddr", hwaddr);
  714. // The pointer to the reply.
  715. ConstPkt4Ptr reply;
  716. handle.getArgument("reply", reply);
  717. // Get the string form of the IP address.
  718. string ipaddr = reply->getYiaddr().toText():
  719. // Write the information to the log file and flush.
  720. interesting << hwaddr << " " << ipaddr << "\n";
  721. flush(interesting);
  722. // We've logged the data, so deregister ourself. This callout will not
  723. // be called again until it is registered by pkt4_receive.
  724. handle.getLibraryHandle().deregisterCallout("pkt4_send", write_data);
  725. return (0);
  726. }
  727. @endcode
  728. Note that the above example used a non-standard name for the callout
  729. that wrote the data. Had the name been a standard one, it would have been
  730. registered when the library was loaded and called for the first request,
  731. regardless of whether that was defined as "interesting". (Although as
  732. callouts with standard names are always registered before "load" gets called,
  733. we could have got round that problem by deregistering that particular
  734. callout in the "load" function.)
  735. @note Deregistration of a callout on the hook that is currently
  736. being called only takes effect when the server next calls the hook.
  737. To illustrate this, suppose the callouts attached to a hook are A, B and C
  738. (in that order), and during execution, A deregisters B and C and adds D.
  739. When callout A returns, B and C will still run. The next time the server
  740. calls the hook's callouts, A and D will run (in that order).
  741. @subsection hooksdgMultipleLibraries Multiple User Libraries
  742. As alluded to in the section @ref hooksdgConfiguration, Kea can load
  743. multiple libraries. The libraries are loaded in the order specified in
  744. the configuration, and the callouts attached to the hooks in the order
  745. presented by the libraries.
  746. The following picture illustrates this, and also illustrates the scope of
  747. data passed around the system.
  748. @image html DataScopeArgument.png "Scope of Arguments"
  749. In this illustration, a server has three hook points, alpha, beta
  750. and gamma. Two libraries are configured, library 1 and library 2.
  751. Library 1 registers the callout "authorize" for hook alpha, "check" for
  752. hook beta and "add_option" for hook gamma. Library 2 registers "logpkt",
  753. "validate" and "putopt"
  754. The horizontal red lines represent arguments to callouts. When the server
  755. calls hook alpha, it creates an argument list and calls the
  756. first callout for the hook, "authorize". When that callout returns, the
  757. same (but possibly modified) argument list is passed to the next callout
  758. in the chain, "logpkt". Another, separate argument list is created for
  759. hook beta and passed to the callouts "check" and "validate" in
  760. that order. A similar sequence occurs for hook gamma.
  761. The next picture shows the scope of the context associated with a
  762. request.
  763. @image html DataScopeContext.png "Illustration of per-library context"
  764. The vertical blue lines represent callout context. Context is
  765. per-packet but also per-library. When the server calls "authorize",
  766. the CalloutHandle's getContext and setContext methods access a context
  767. created purely for library 1. The next callout on the hook will access
  768. context created for library 2. These contexts are passed to the callouts
  769. associated with the next hook. So when "check" is called, it gets the
  770. context data that was set by "authorize", when "validate" is called,
  771. it gets the context data set by "logpkt".
  772. It is stressed that the context for callouts associated with different
  773. libraries is entirely separate. For example, suppose "authorize" sets
  774. the CalloutHandle's context item "foo" to 2 and "logpkt" sets an item of
  775. the same name to the string "bar". When "check" accesses the context
  776. item "foo", it gets a value of 2; when "validate" accesses an item of
  777. the same name, it gets the value "bar".
  778. It is also stressed that all this context exists only for the life of the
  779. request being processed. When that request is complete, all the
  780. context associated with that request - for all libraries - is destroyed,
  781. and new context created for the next request.
  782. This structure means that library authors can use per-request context
  783. without worrying about the presence of other libraries. Other libraries
  784. may be present, but will not affect the context values set by a library's
  785. callouts.
  786. Configuring multiple libraries just requires listing the libraries
  787. as separate elements of the hooks-libraries configuration element, e.g.
  788. @code
  789. "Dhcp4": {
  790. :
  791. "hooks-libraries": [ "/usr/lib/library1.so", "/opt/library2.so" ]
  792. :
  793. }
  794. @endcode
  795. @subsection hooksdgInterLibraryData Passing Data Between Libraries
  796. In rare cases, it is possible that one library may want to pass
  797. data to another. This can be done in a limited way by means of the
  798. CalloutHandle's setArgument and getArgument calls. For example, in the
  799. above diagram, the callout "add_option" can pass a value to "putopt"
  800. by setting a name.value pair in the hook's argument list. "putopt"
  801. would be able to read this, but would not be able to return information
  802. back to "add_option".
  803. All argument names used by Kea will be a combination of letters
  804. (both upper- and lower-case), digits, hyphens and underscores: no
  805. other characters will be used. As argument names are simple strings,
  806. it is suggested that if such a mechanism be used, the names of the data
  807. values passed between the libraries include a special character such as
  808. the dollar symbol or percent sign. In this way there is no danger that
  809. a name will conflict with any existing or future Kea argument names.
  810. @subsection hooksdgRegisterMultipleLibraries Dynamic Callout Registration and Multiple Libraries
  811. On a particular hook, callouts are called in the order the libraries appear
  812. in the configuration and, within a library, in the order the callouts
  813. are registered.
  814. This order applies to dynamically-registered callouts as well. As an
  815. example, consider the diagram above where for hook "beta", callout "check"
  816. is followed by callout "validate". Suppose that when "authorize" is run,
  817. it registers a new callout ("double_check") on hook "beta". That
  818. callout will be inserted at the end of the callouts registered by
  819. library 1 and before any registered by library 2. It would therefore
  820. appear between "check" and "validate". On the other hand, if it were
  821. "logpkt" that registered the new callout, "double_check" would appear
  822. after "validate".
  823. @subsection hooksdgStaticallyLinkedKea Running Against a Statically-Linked Kea
  824. If Kea is built with the --enable-static-link switch (set when
  825. running the "configure" script), no shared Kea libraries are built;
  826. instead, archive libraries are created and Kea is linked to them.
  827. If you create a hooks library also linked against these archive libraries,
  828. when the library is loaded you end up with two copies of the library code,
  829. one in Kea and one in your library.
  830. To run successfully, your library needs to perform run-time initialization
  831. of the Kea code in your library (something performed by Kea
  832. in the case of shared libraries). To do this, call the function
  833. isc::hooks::hooksStaticLinkInit() as the first statement of the load()
  834. function. (If your library does not include a load() function, you need
  835. to add one.) For example:
  836. @code
  837. #include <hooks/hooks.h>
  838. extern "C" {
  839. int version() {
  840. return (BIND10_HOOKS_VERSION);
  841. }
  842. int load() {
  843. isc::hooks::hooksStaticLinkInit();
  844. :
  845. }
  846. // Other callout functions
  847. :
  848. }
  849. @endcode
  850. */