Hooks, Optional Hooks, and Optional Functions

In Apache 1.x modules hooked into the appropriate “phases” of the main server by putting functions into appropriate slots in the module structure. This process is known as “hooking.” This has been revised in Apache 2.0 — instead a single function is called at startup in each module, and this registers the functions that need to be called. The registration process also permits the module to specify how it should be ordered relative to other modules for each hook. (In Apache 1.x this was only possible for all hooks in a module instead of individually and also had to be done in the configuration file, rather than being done by the module itself.)

This approach has various advantages. First, the list of hooks can be extended arbitrarily without causing each function to have a huge unwieldy list of NULL entries. Second, optional modules can export their own hooks, which are only invoked when the module is present, but can be registered regardless — and this can be done without modification of the core code.

Another feature of hooks that we think is pretty cool is that, although they are dynamic, they are still typesafe — that is, the compiler will complain if the type of the function registered for a hook doesn’t match the hook (and each hook can use a different type of function).[2] They are also extremely efficient.

So, what exactly is a hook? Its a point at which a module can request to be called. So, each hook specifies a function prototype, and each module can specify one (or more in 2.0) function that gets called at the appropriate moment. When the moment arrives, the provider of the hook calls all the functions in order.[3] It may terminate when particular values are returned — the hook functions can return either “declined” or “ok” or an error. In the first case all are called until an error is returned (if one is, of course); in the second, functions are called until either an error or “ok” is returned. A slight complication in Apache 2.0 is that because each hook function can define the return type, it must also define how “ok,” “decline,” and errors are returned (in 1.x, the return type was fixed, so this was easier).

Although you are unlikely to want to define a hook, it is useful to know how to go about it, so you can understand them when you come across them (plus, advanced module writers may wish to define optional hooks or optional functions).

Before we get started, it is worth noting that Apache hooks are defined in terms of APR hooks — but the only reason for that is to provide namespace separation between Apache and some other package linked into Apache that also uses hooks.



[2] We’ll admit to bias here — Ben designed and implemented the hooking mechanisms in Apache 2.0.

[3] Note that the order is determined at runtime in Apache 2.0.