1 <?xml version='1.0' encoding='UTF-8' ?>
2 <!DOCTYPE manualpage SYSTEM "../style/manualpage.dtd">
3 <?xml-stylesheet type="text/xsl" href="../style/manual.en.xsl"?>
5 <!-- $LastChangedRevision$ -->
8 Licensed to the Apache Software Foundation (ASF) under one or more
9 contributor license agreements. See the NOTICE file distributed with
10 this work for additional information regarding copyright ownership.
11 The ASF licenses this file to You under the Apache License, Version 2.0
12 (the "License"); you may not use this file except in compliance with
13 the License. You may obtain a copy of the License at
15 http://www.apache.org/licenses/LICENSE-2.0
17 Unless required by applicable law or agreed to in writing, software
18 distributed under the License is distributed on an "AS IS" BASIS,
19 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 See the License for the specific language governing permissions and
21 limitations under the License.
24 <manualpage metafile="modguide.xml.meta">
25 <parentdocument href="./">Developer</parentdocument>
27 <title>Developing modules for the Apache HTTP Server 2.4</title>
30 <p>This document explains how you can develop modules for the Apache HTTP
34 <seealso><a href="request.html">Request Processing in Apache 2.4</a></seealso>
35 <seealso><a href="hooks.html">Apache 2.x Hook Functions</a></seealso>
37 <section id="introduction"><title>Introduction</title>
38 <section id="what"><title>What we will be discussing in this document</title>
40 This document will discuss how you can easily create modules for the Apache
41 HTTP Server 2.4, by exploring an example module called
42 <code>mod_example</code>. In the first part of this document, the purpose
43 of this module will be to calculate and print out various digest values for
44 existing files on your web server, whenever we access the URL <code>
45 http://hostname/filename.sum</code>. For instance, if we want to know the
46 MD5 digest value of the file located at <code>
47 http://www.example.com/index.html</code>, we would visit <code>
48 http://www.example.com/index.html.sum</code>.
52 In the second part of this document, which deals with configuration
53 directive and context awareness, we will be looking at a module that simply
54 write out its own configuration to the client.
58 <section id="prerequisites"><title>Prerequisites</title>
60 First and foremost, you are expected to have a basic knowledge of how the C
61 programming language works. In most cases, we will try to be as pedagogical
62 as possible and link to documents describing the functions used in the
63 examples, but there are also many cases where it is necessary to either
64 just assume that "it works" or do some digging yourself into what the hows
65 and whys of various function calls.
68 Lastly, you will need to have a basic understanding of how modules are
69 loaded and configured in the Apache HTTP Server, as well as how to get the headers for
70 Apache if you do not have them already, as these are needed for compiling
74 <section id="compiling"><title>Compiling your module</title>
76 To compile the source code we are building in this document, we will be
77 using <a href="../programs/apxs.html">APXS</a>. Assuming your source file
78 is called mod_example.c, compiling, installing and activating the module is
82 apxs -i -a -c mod_example.c
88 <section id="basics"><title>Defining a module</title>
90 <img src="../images/build_a_mod_3.png" alt="Module name tags"/><br/>
91 Every module starts with the same declaration, or name tag if you will,
92 that defines a module as <em>a separate entity within Apache</em>:</p>
95 <!-- BEGIN EXAMPLE CODE -->
96 <highlight language="c">
97 module AP_MODULE_DECLARE_DATA example_module =
99 STANDARD20_MODULE_STUFF,
100 create_dir_conf, /* Per-directory configuration handler */
101 merge_dir_conf, /* Merge handler for per-directory configurations */
102 create_svr_conf, /* Per-server configuration handler */
103 merge_svr_conf, /* Merge handler for per-server configurations */
104 directives, /* Any directives we may have for httpd */
105 register_hooks /* Our hook registering function */
108 <!-- END EXAMPLE CODE -->
111 This bit of code lets the server know that we have now registered a new module
112 in the system, and that its name is <code>example_module</code>. The name
113 of the module is used primarily for two things:<br/>
116 <li>Letting the server know how to load the module using the LoadModule</li>
117 <li>Setting up a namespace for the module to use in configurations</li>
120 For now, we're only concerned with the first purpose of the module name,
121 which comes into play when we need to load the module:
123 <highlight language="config">
124 LoadModule example_module modules/mod_example.so
127 In essence, this tells the server to open up <code>mod_example.so</code> and look for a module
128 called <code>example_module</code>.
131 Within this name tag of ours is also a bunch of references to how we would
132 like to handle things: Which directives do we respond to in a configuration
133 file or .htaccess, how do we operate within specific contexts, and what
134 handlers are we interested in registering with the Apache HTTP service. We'll
135 return to all these elements later in this document.
138 <section id="hooking"><title>Getting started: Hooking into the server</title>
139 <section id="hook_intro"><title>An introduction to hooks</title>
141 When handling requests in Apache HTTP Server 2.4, the first thing you will need to do is
142 create a hook into the request handling process. A hook is essentially a
143 message telling the server that you are willing to either serve or at least
144 take a glance at certain requests given by clients. All handlers, whether
145 it's mod_rewrite, mod_authn_*, mod_proxy and so on, are hooked into
146 specific parts of the request process. As you are probably aware, modules
147 serve different purposes; Some are authentication/authorization handlers,
148 others are file or script handlers while some third modules rewrite URIs or
149 proxies content. Furthermore, in the end, it is up to the user of the server
150 how and when each module will come into place. Thus, the server itself does not
151 presume to know which module is responsible for handling a specific
152 request, and will ask each module whether they have an interest in a given
153 request or not. It is then up to each module to either gently decline
154 serving a request, accept serving it or flat out deny the request from
155 being served, as authentication/authorization modules do: <br/>
156 <img src="../images/build_a_mod_2.png" alt="Hook handling in httpd"/><br/>
157 To make it a bit easier for handlers such as our mod_example to know
158 whether the client is requesting content we should handle or not, the server
159 has directives for hinting to modules whether their assistance is needed or
160 not. Two of these are <directive module="mod_mime">AddHandler</directive>
161 and <directive module="core">SetHandler</directive>. Let's take a look at
162 an example using <directive module="mod_mime">AddHandler</directive>. In
163 our example case, we want every request ending with .sum to be served by
164 <code>mod_example</code>, so we'll add a configuration directive that tells
165 the server to do just that:
167 <highlight language="config">
168 AddHandler example-handler .sum
171 What this tells the server is the following: <em>Whenever we receive a request
172 for a URI ending in .sum, we are to let all modules know that we are
173 looking for whoever goes by the name of "example-handler" </em>.
174 Thus, when a request is being served that ends in .sum, the server will let all
175 modules know, that this request should be served by "example-handler
176 ". As you will see later, when we start building mod_example, we will
177 check for this handler tag relayed by <code>AddHandler</code> and reply to
178 the server based on the value of this tag.
181 <section id="hook_declaration"><title>Hooking into httpd</title>
183 To begin with, we only want to create a simple handler, that replies to the
184 client browser when a specific URL is requested, so we won't bother setting
185 up configuration handlers and directives just yet. Our initial module
186 definition will look like this:</p>
189 <!-- BEGIN EXAMPLE CODE -->
190 <highlight language="c">
191 module AP_MODULE_DECLARE_DATA example_module =
193 STANDARD20_MODULE_STUFF,
199 register_hooks /* Our hook registering function */
202 <!-- END EXAMPLE CODE -->
205 <p>This lets the server know that we are not interesting in anything fancy, we
206 just want to hook onto the requests and possibly handle some of them. </p>
208 <p> The reference in our example declaration, <code>register_hooks</code>
209 is the name of a function we will create to manage how we hook onto the
210 request process. In this example module, the function has just one purpose;
211 To create a simple hook that gets called after all the rewrites, access
212 control etc has been handled. Thus, we will let the server know, that we want
213 to hook into its process as one of the last modules:
216 <!-- BEGIN EXAMPLE CODE -->
217 <highlight language="c">
218 static void register_hooks(apr_pool_t *pool)
220 /* Create a hook in the request handler, so we get called when a request arrives */
221 ap_hook_handler(example_handler, NULL, NULL, APR_HOOK_LAST);
224 <!-- END EXAMPLE CODE -->
227 The <code>example_handler</code> reference is the function that will handle
228 the request. We will discuss how to create a handler in the next chapter.
231 <section id="hook_others"><title>Other useful hooks</title>
233 Hooking into the request handling phase is but one of many hooks that you
234 can create. Some other ways of hooking are:
237 <li><code>ap_hook_child_init</code>: Place a hook that executes when a child process is spawned (commonly used for initializing modules after the server has forked)</li>
238 <li><code>ap_hook_pre_config</code>: Place a hook that executes before any configuration data has been read (very early hook)</li>
239 <li><code>ap_hook_post_config</code>: Place a hook that executes after configuration has been parsed, but before the server has forked</li>
240 <li><code>ap_hook_translate_name</code>: Place a hook that executes when a URI needs to be translated into a filename on the server (think <code>mod_rewrite</code>)</li>
246 <section id="handling"><title>Building a handler</title>
248 A handler is essentially a function that receives a callback when a request
249 to the server is made. It is passed a record of the current request (how it was
250 made, which headers and requests were passed along, who's giving the
251 request and so on), and is put in charge of either telling the server that it's
252 not interested in the request or handle the request with the tools provided.
254 <section id="simple_handler"><title>A simple "Hello, world!"
256 <p>Let's start off by making a very simple request handler
257 that does the following:
260 <li>Check that this is a request that should be served by "example-handler"</li>
261 <li>Set the content type of our output to <code>text/html</code></li>
262 <li>Write "Hello, world!" back to the client browser</li>
263 <li>Let the server know that we took care of this request and everything went fine</li>
266 In C code, our example handler will now look like this:
269 <!-- BEGIN EXAMPLE CODE -->
270 <highlight language="c">
271 static int example_handler(request_rec *r)
273 /* First off, we need to check if this is a call for the "example-handler" handler.
274 * If it is, we accept it and do our things, if not, we simply return DECLINED,
275 * and the server will try somewhere else.
277 if (!r->handler || strcmp(r->handler, "example-handler")) return (DECLINED);
279 /* Now that we are handling this request, we'll write out "Hello, world!" to the client.
280 * To do so, we must first set the appropriate content type, followed by our output.
282 ap_set_content_type(r, "text/html");
283 ap_rprintf(r, "Hello, world!");
285 /* Lastly, we must tell the server that we took care of this request and everything went fine.
286 * We do so by simply returning the value OK to the server.
291 <!-- END EXAMPLE CODE -->
294 Now, we put all we have learned together and end up with a program that
296 <a href="http://people.apache.org/~humbedooh/mods/examples/mod_example_1.c">mod_example_1.c</a>
297 . The functions used in this example will be explained later in the section
298 <a href= "#functions">"Some useful functions you should know"</a>.
301 <section id="request_rec"><title>The request_rec structure</title>
302 <p>The most essential part of any request is the <em>request record
303 </em>. In a call to a handler function, this is represented by the <code>
304 request_req* </code> structure passed along with every call that is made.
305 This struct, typically just refered to as <code>r</code> in modules,
306 contains all the information you need for your module to fully process any
307 HTTP request and respond accordingly.</p> <p>Some key elements of the <code>
308 request_req </code> structure are:
311 <li><code>r->handler (char*):</code> Contains the name of the handler the server is currently asking to do the handling of this request</li>
312 <li><code>r->method (char*):</code> Contains the HTTP method being used, f.x. GET or POST</li>
313 <li><code>r->filename (char*):</code> Contains the translated filename the client is requesting</li>
314 <li><code>r->args (char*):</code> Contains the query string of the request, if any</li>
315 <li><code>r->headers_in (apr_table_t*):</code> Contains all the headers sent by the client</li>
316 <li><code>r->connection (conn_rec*):</code> A record containing information about the current connection</li>
317 <li><code>r->useragent_ip (char*):</code> The IP address of the client connecting to us</li>
318 <li><code>r->pool (apr_pool_t*)</code>: The memory pool of this request. We'll discuss this in the "
319 <a href="#memory">Memory management</a>" chapter.</li>
322 A complete list of all the values contained with in the <code>request_req</code> structure can be found in
323 the <a href="http://svn.apache.org/repos/asf/httpd/httpd/trunk/include/httpd.h"><code>httpd.h</code></a> header
324 file or at <a href="http://ci.apache.org/projects/httpd/trunk/doxygen/structrequest__rec.html">http://ci.apache.org/projects/httpd/trunk/doxygen/structrequest__rec.html</a>.
329 Let's try out some of these variables in another example handler:<br/>
332 <!-- BEGIN EXAMPLE CODE -->
333 <highlight language="c">
334 static int example_handler(request_rec *r)
336 /* Set the appropriate content type */
337 ap_set_content_type(r, "text/html");
339 /* Print out the IP address of the client connecting to us: */
340 ap_rprintf(r, "<h2>Hello, %s!</h2>", r->useragent_ip);
342 /* If we were reached through a GET or a POST request, be happy, else sad. */
343 if ( !strcmp(r->method, "POST") || !strcmp(r->method, "GET") ) {
344 ap_rputs("You used a GET or a POST method, that makes us happy!<br/>", r);
347 ap_rputs("You did not use POST or GET, that makes us sad :(<br/>", r);
350 /* Lastly, if there was a query string, let's print that too! */
352 ap_rprintf(r, "Your query string was: %s", r->args);
357 <!-- END EXAMPLE CODE -->
361 <section id="return_value"><title>Return values</title>
363 Apache relies on return values from handlers to signify whether a request
364 was handled or not, and if so, whether the request went well or not. If a
365 module is not interested in handling a specific request, it should always
366 return the value <code>DECLINED</code>. If it is handling a request, it
367 should either return the generic value <code>OK</code>, or a specific HTTP
368 status code, for example:
371 <!-- BEGIN EXAMPLE CODE -->
372 <highlight language="c">
373 static int example_handler(request_rec *r)
375 /* Return 404: Not found */
376 return HTTP_NOT_FOUND;
379 <!-- END EXAMPLE CODE -->
382 Returning <code>OK</code> or a HTTP status code does not necessarily mean
383 that the request will end. The server may still have other handlers that are
384 interested in this request, for instance the logging modules which, upon a
385 successful request, will write down a summary of what was requested and how
386 it went. To do a full stop and prevent any further processing after your
387 module is done, you can return the value <code>DONE</code> to let the server
388 know that it should cease all activity on this request and carry on with
389 the next, without informing other handlers.
391 <strong>General response codes:</strong>
394 <li><code>DECLINED</code>: We are not handling this request</li>
395 <li><code>OK</code>: We handled this request and it went well</li>
396 <li><code>DONE</code>: We handled this request and the server should just close this thread without further processing</li>
399 <strong>HTTP specific return codes (excerpt):</strong>
402 <li><code>HTTP_OK (200)</code>: Request was okay</li>
403 <li><code>HTTP_MOVED_PERMANENTLY (301)</code>: The resource has moved to a new URL</li>
404 <li><code>HTTP_UNAUTHORIZED (401)</code>: Client is not authorized to visit this page</li>
405 <li><code>HTTP_FORBIDDEN (403)</code>: Permission denied</li>
406 <li><code>HTTP_NOT_FOUND (404)</code>: File not found</li>
407 <li><code>HTTP_INTERNAL_SERVER_ERROR (500)</code>: Internal server error (self explanatory)</li>
411 <section id="functions"><title>Some useful functions you should know</title>
415 <code>ap_rputs(const char *string, request_req *r)</code>: <br/>
416 Sends a string of text to the client. This is a shorthand version of <a
417 href="http://ci.apache.org/projects/httpd/trunk/doxygen/group__APACHE__CORE__PROTO.html#gac827cd0537d2b6213a7c06d7c26cc36e">
421 <!-- BEGIN EXAMPLE CODE -->
422 <highlight language="c">ap_rputs("Hello, world!", r);</highlight>
423 <!-- END EXAMPLE CODE -->
429 <a href="http://ci.apache.org/projects/httpd/trunk/doxygen/group__APACHE__CORE__PROTO.html#ga5e91eb6ca777c9a427b2e82bf1eeb81d">ap_rprintf</a></code>: <br/>
430 This function works just like <code>printf</code>, except it sends the result to the client.
433 <!-- BEGIN EXAMPLE CODE -->
434 <highlight language="c">ap_rprintf(r, "Hello, %s!", r->useragent_ip);</highlight>
435 <!-- END EXAMPLE CODE -->
440 <a href="http://ci.apache.org/projects/httpd/trunk/doxygen/group__APACHE__CORE__PROTO.html#gaa2f8412c400197338ec509f4a45e4579">ap_set_content_type</a>(request_req *r, const char *type)</code>: <br/>
441 Sets the content type of the output you are sending.
444 <!-- BEGIN EXAMPLE CODE -->
445 <highlight language="c">ap_set_content_type(r, "text/plain"); /* force a raw text output */</highlight>
446 <!-- END EXAMPLE CODE -->
454 <section id="memory"><title>Memory management</title>
456 Managing your resources in Apache HTTP Server 2.4 is quite easy, thanks to the memory pool
457 system. In essence, each server, connection and request have their own
458 memory pool that gets cleaned up when its scope ends, e.g. when a request
459 is done or when a server process shuts down. All your module needs to do is
460 latch onto this memory pool, and you won't have to worry about having to
461 clean up after yourself - pretty neat, huh?
465 In our module, we will primarily be allocating memory for each request, so
466 it's appropriate to use the <code>r->pool</code>
467 reference when creating new objects. A few of the functions for allocating
468 memory within a pool are:
471 <li><code>void* <a href="http://apr.apache.org/docs/apr/1.4/group__apr__pools.html#ga85f1e193c31d109affda72f9a92c6915">apr_palloc</a>(
472 apr_pool_t *p, apr_size_t size)</code>: Allocates <code>size</code> number of bytes in the pool for you</li>
473 <li><code>void* <a href="http://apr.apache.org/docs/apr/1.4/group__apr__pools.html#gaf61c098ad258069d64cdf8c0a9369f9e">apr_pcalloc</a>(
474 apr_pool_t *p, apr_size_t size)</code>: Allocates <code>size</code> number of bytes in the pool for you and sets all bytes to 0</li>
475 <li><code>char* <a href="http://apr.apache.org/docs/apr/1.4/group__apr__strings.html#gabc79e99ff19abbd7cfd18308c5f85d47">apr_pstrdup</a>(
476 apr_pool_t *p, const char *s)</code>: Creates a duplicate of the string <code>s</code>. This is useful for copying constant values so you can edit them</li>
477 <li><code>char* <a href="http://apr.apache.org/docs/apr/1.4/group__apr__strings.html#ga3eca76b8d293c5c3f8021e45eda813d8">apr_psprintf</a>(
478 apr_pool_t *p, const char *fmt, ...)</code>: Similar to <code>sprintf</code>, except the server supplies you with an appropriately allocated target variable</li>
481 <p>Let's put these functions into an example handler:</p>
484 <!-- BEGIN EXAMPLE CODE -->
485 <highlight language="c">
486 static int example_handler(request_rec *r)
488 const char* original = "You can't edit this!";
492 /* Allocate space for 10 integer values and set them all to zero. */
493 integers = apr_pcalloc(r->pool, sizeof(int)*10);
495 /* Create a copy of the 'original' variable that we can edit. */
496 copy = apr_pstrdup(r->pool, original);
500 <!-- END EXAMPLE CODE -->
503 This is all well and good for our module, which won't need any
504 pre-initialized variables or structures. However, if we wanted to
505 initialize something early on, before the requests come rolling in, we
506 could simply add a call to a function in our <code>register_hooks</code>
507 function to sort it out:
510 <!-- BEGIN EXAMPLE CODE -->
511 <highlight language="c">
512 static void register_hooks(apr_pool_t *pool)
514 /* Call a function that initializes some stuff */
515 example_init_function(pool);
516 /* Create a hook in the request handler, so we get called when a request arrives */
517 ap_hook_handler(example_handler, NULL, NULL, APR_HOOK_LAST);
520 <!-- END EXAMPLE CODE -->
523 In this pre-request initialization function we would not be using the
524 same pool as we did when allocating resources for request-based functions.
525 Instead, we would use the pool given to us by the server for allocating memory
526 on a per-process based level.
530 <section id="parsing"><title>Parsing request data</title>
532 In our example module, we would like to add a feature, that checks which
533 type of digest, MD5 or SHA1 the client would like to see. This could be
534 solved by adding a query string to the request. A query string is typically
535 comprised of several keys and values put together in a string, for instance
536 <code>valueA=yes&valueB=no&valueC=maybe</code>. It is up to the
537 module itself to parse these and get the data it requires. In our example,
538 we'll be looking for a key called <code>digest</code>, and if set to <code>
539 md5</code>, we'll produce an MD5 digest, otherwise we'll produce a SHA1
543 Since the introduction of Apache HTTP Server 2.4, parsing request data from GET and
544 POST requests have never been easier. All we require to parse both GET and
545 POST data is four simple lines:
549 <!-- BEGIN EXAMPLE CODE -->
550 <highlight language="c">
551 <a href="http://ci.apache.org/projects/httpd/trunk/doxygen/group__apr__tables.html#gad7ea82d6608a4a633fc3775694ab71e4">apr_table_t</a> *GET;
552 <a href="http://ci.apache.org/projects/httpd/trunk/doxygen/structapr__array__header__t.html">apr_array_header_t</a> *POST;
554 <a href="http://ci.apache.org/projects/httpd/trunk/doxygen/group__APACHE__CORE__SCRIPT.html#gaed25877b529623a4d8f99f819ba1b7bd">ap_args_to_table</a>(r, &GET);
555 <a href="http://ci.apache.org/projects/httpd/trunk/doxygen/group__APACHE__CORE__DAEMON.html#ga9d426b6382b49754d4f87c55f65af202">ap_parse_form_data</a>(r, NULL, &POST, -1, 8192);
557 <!-- END EXAMPLE CODE -->
560 In our specific example module, we're looking for the <code>digest</code>
561 value from the query string, which now resides inside a table called <code>
562 GET</code>. To extract this value, we need only perform a simple operation:
566 <!-- BEGIN EXAMPLE CODE -->
567 <highlight language="c">
568 /* Get the "digest" key from the query string, if any. */
569 const char *digestType = apr_table_get(GET, "digest");
571 /* If no key was returned, we will set a default value instead. */
572 if (!digestType) digestType = "sha1";
574 <!-- END EXAMPLE CODE -->
577 The structures used for the POST and GET data are not exactly the same, so
578 if we were to fetch a value from POST data instead of the query string, we
579 would have to resort to a few more lines, as outlined in <a href="#get_post"
580 >this example</a> in the last chapter of this document.
584 <section id="advanced_handler"><title>Making an advanced handler</title>
586 Now that we have learned how to parse form data and manage our resources,
587 we can move on to creating an advanced version of our module, that spits
588 out the MD5 or SHA1 digest of files:
592 <!-- BEGIN EXAMPLE CODE -->
593 <highlight language="c">
594 static int example_handler(request_rec *r)
601 apr_size_t readBytes;
604 apr_array_header_t *POST;
605 const char *digestType;
608 /* Check that the "example-handler" handler is being called. */
609 if (!r->handler || strcmp(r->handler, "example-handler")) return (DECLINED);
611 /* Figure out which file is being requested by removing the .sum from it */
612 filename = apr_pstrdup(r->pool, r->filename);
613 filename[strlen(filename)-4] = 0; /* Cut off the last 4 characters. */
615 /* Figure out if the file we request a sum on exists and isn't a directory */
616 rc = apr_stat(&finfo, filename, APR_FINFO_MIN, r->pool);
617 if (rc == APR_SUCCESS) {
620 (finfo.filetype != APR_NOFILE)
621 && !(finfo.filetype & APR_DIR)
623 if (!exists) return HTTP_NOT_FOUND; /* Return a 404 if not found. */
625 /* If apr_stat failed, we're probably not allowed to check this file. */
626 else return HTTP_FORBIDDEN;
628 /* Parse the GET and, optionally, the POST data sent to us */
630 ap_args_to_table(r, &GET);
631 ap_parse_form_data(r, NULL, &POST, -1, 8192);
633 /* Set the appropriate content type */
634 ap_set_content_type(r, "text/html");
636 /* Print a title and some general information */
637 ap_rprintf(r, "<h2>Information on %s:</h2>", filename);
638 ap_rprintf(r, "<b>Size:</b> %u bytes<br/>", finfo.size);
640 /* Get the digest type the client wants to see */
641 digestType = apr_table_get(GET, "digest");
642 if (!digestType) digestType = "MD5";
645 rc = apr_file_open(&file, filename, APR_READ, APR_OS_DEFAULT, r->pool);
646 if (rc == APR_SUCCESS) {
648 /* Are we trying to calculate the MD5 or the SHA1 digest? */
649 if (!strcasecmp(digestType, "md5")) {
650 /* Calculate the MD5 sum of the file */
656 apr_md5_init(&md5);
658 while ( apr_file_read(file, buffer, &readBytes) == APR_SUCCESS ) {
659 apr_md5_update(&md5, buffer, readBytes);
661 apr_md5_final(digest.chr, &md5);
663 /* Print out the MD5 digest */
664 ap_rputs("<b>MD5: </b><code>", r);
665 for (n = 0; n < APR_MD5_DIGESTSIZE/4; n++) {
666 ap_rprintf(r, "%08x", digest.num[n]);
668 ap_rputs("</code>", r);
669 /* Print a link to the SHA1 version */
670 ap_rputs("<br/><a href='?digest=sha1'>View the SHA1 hash instead</a>", r);
673 /* Calculate the SHA1 sum of the file */
679 apr_sha1_init(&sha1);
681 while ( apr_file_read(file, buffer, &readBytes) == APR_SUCCESS ) {
682 apr_sha1_update(&sha1, buffer, readBytes);
684 apr_sha1_final(digest.chr, &sha1);
686 /* Print out the SHA1 digest */
687 ap_rputs("<b>SHA1: </b><code>", r);
688 for (n = 0; n < APR_SHA1_DIGESTSIZE/4; n++) {
689 ap_rprintf(r, "%08x", digest.num[n]);
691 ap_rputs("</code>", r);
693 /* Print a link to the MD5 version */
694 ap_rputs("<br/><a href='?digest=md5'>View the MD5 hash instead</a>", r);
696 apr_file_close(file);
699 /* Let the server know that we responded to this request. */
703 <!-- END EXAMPLE CODE -->
706 This version in its entirity can be found here:
707 <a href="http://people.apache.org/~humbedooh/mods/examples/mod_example_2.c">mod_example_2.c</a>.
713 <section id="configuration"><title>Adding configuration options</title>
715 In this next segment of this document, we will turn our eyes away from the
716 digest module and create a new example module, whose only function is to
717 write out its own configuration. The purpose of this is to examine how
718 the server works with configuration, and what happens when you start writing
719 advanced configurations
722 <section id="config_intro"><title>An introduction to configuration
725 If you are reading this, then you probably already know
726 what a configuration directive is. Simply put, a directive is a way of
727 telling an individual module (or a set of modules) how to behave, such as
728 these directives control how <code>mod_rewrite</code> works:
730 <highlight language="config">
732 RewriteCond %{REQUEST_URI} ^/foo/bar
733 RewriteRule ^/foo/bar/(.*)$ /foobar?page=$1
736 Each of these configuration directives are handled by a separate function,
737 that parses the parameters given and sets up a configuration accordingly.
740 <section id="config_simple"><title>Making an example configuration</title>
741 <p>To begin with, we'll create a basic configuration in C-space:</p>
744 <!-- BEGIN EXAMPLE CODE -->
745 <highlight language="c">
747 int enabled; /* Enable or disable our module */
748 const char *path; /* Some path to...something */
749 int typeOfAction; /* 1 means action A, 2 means action B and so on */
752 <!-- END EXAMPLE CODE -->
755 Now, let's put this into perspective by creating a very small module that
756 just prints out a hard-coded configuration. You'll notice that we use the
757 <code>register_hooks</code> function for initializing the configuration
758 values to their defaults:
761 <!-- BEGIN EXAMPLE CODE -->
762 <highlight language="c">
764 int enabled; /* Enable or disable our module */
765 const char *path; /* Some path to...something */
766 int typeOfAction; /* 1 means action A, 2 means action B and so on */
769 static example_config config;
771 static int example_handler(request_rec *r)
773 if (!r->handler || strcmp(r->handler, "example-handler")) return(DECLINED);
774 ap_set_content_type(r, "text/plain");
775 ap_rprintf(r, "Enabled: %u\n", config.enabled);
776 ap_rprintf(r, "Path: %s\n", config.path);
777 ap_rprintf(r, "TypeOfAction: %x\n", config.typeOfAction);
781 static void register_hooks(apr_pool_t *pool)
784 config.path = "/foo/bar";
785 config.typeOfAction = 0x00;
786 ap_hook_handler(example_handler, NULL, NULL, APR_HOOK_LAST);
789 /* Define our module as an entity and assign a function for registering hooks */
791 module AP_MODULE_DECLARE_DATA example_module =
793 STANDARD20_MODULE_STUFF,
794 NULL, /* Per-directory configuration handler */
795 NULL, /* Merge handler for per-directory configurations */
796 NULL, /* Per-server configuration handler */
797 NULL, /* Merge handler for per-server configurations */
798 NULL, /* Any directives we may have for httpd */
799 register_hooks /* Our hook registering function */
802 <!-- END EXAMPLE CODE -->
805 So far so good. To access our new handler, we could add the following to
808 <highlight language="config">
809 <Location /example>
810 SetHandler example-handler
814 When we visit, we'll see our current configuration being spit out by our
819 <section id="register_directive"><title>Registering directives with the server</title>
821 What if we want to change our configuration, not by hard-coding new values
822 into the module, but by using either the httpd.conf file or possibly a
823 .htaccess file? It's time to let the server know that we want this to be
824 possible. To do so, we must first change our <em>name tag</em> to include a
825 reference to the configuration directives we want to register with the server:
828 <!-- BEGIN EXAMPLE CODE -->
829 <highlight language="c">
830 module AP_MODULE_DECLARE_DATA example_module =
832 STANDARD20_MODULE_STUFF,
833 NULL, /* Per-directory configuration handler */
834 NULL, /* Merge handler for per-directory configurations */
835 NULL, /* Per-server configuration handler */
836 NULL, /* Merge handler for per-server configurations */
837 example_directives, /* Any directives we may have for httpd */
838 register_hooks /* Our hook registering function */
841 <!-- END EXAMPLE CODE -->
844 This will tell the server that we are now accepting directives from the
845 configuration files, and that the structure called <code>example_directives
846 </code> holds information on what our directives are and how they work.
847 Since we have three different variables in our module configuration, we
848 will add a structure with three directives and a NULL at the end:
851 <!-- BEGIN EXAMPLE CODE -->
852 <highlight language="c">
853 static const command_rec example_directives[] =
855 AP_INIT_TAKE1("exampleEnabled", example_set_enabled, NULL, RSRC_CONF, "Enable or disable mod_example"),
856 AP_INIT_TAKE1("examplePath", example_set_path, NULL, RSRC_CONF, "The path to whatever"),
857 AP_INIT_TAKE2("exampleAction", example_set_action, NULL, RSRC_CONF, "Special action value!"),
861 <!-- END EXAMPLE CODE -->
864 <img src="../images/build_a_mod_4.png" alt="Directives structure"/><br />
865 As you can see, each directive needs at least 5 parameters set:
868 <li><code><a href="http://ci.apache.org/projects/httpd/trunk/doxygen/group__APACHE__CORE__CONFIG.html#ga07c7d22ae17805e61204463326cf9c34">AP_INIT_TAKE1</a></code>: This is a macro that tells the server that this directive takes one and only one argument.
869 If we required two arguments, we could use the macro <code><a href="http://ci.apache.org/projects/httpd/trunk/doxygen/group__APACHE__CORE__CONFIG.html#gafaec43534fcf200f37d9fecbf9247c21">AP_INIT_TAKE2</a></code> and so on (refer to httpd_conf.h
870 for more macros).</li>
871 <li><code>exampleEnabled</code>: This is the name of our directive. More precisely, it is what the user must put in his/her
872 configuration in order to invoke a configuration change in our module.</li>
873 <li><code>example_set_enabled</code>: This is a reference to a C function that parses the directive and sets the configuration
874 accordingly. We will discuss how to make this in the following paragraph.</li>
875 <li><code>RSRC_CONF</code>: This tells the server where the directive is permitted. We'll go into details on this value in the
876 later chapters, but for now, <code>RSRC_CONF</code> means that the server will only accept these directives in a server context.</li>
877 <li><code>"Enable or disable...."</code>: This is simply a brief description of what the directive does.</li>
880 (<em>The "missing" parameter in our definition, which is usually set to
881 <code>NULL</code>, is an optional function that can be run after the
882 initial function to parse the arguments have been run. This is usually
883 omitted, as the function for verifying arguments might as well be used to
887 <section id="directive_handler"><title>The directive handler function</title>
889 Now that we've told the server to expect some directives for our module, it's
890 time to make a few functions for handling these. What the server reads in the
891 configuration file(s) is text, and so naturally, what it passes along to
892 our directive handler is one or more strings, that we ourselves need to
893 recognize and act upon. You'll notice, that since we set our <code>
894 exampleAction</code> directive to accept two arguments, its C function also
895 has an additional parameter defined:</p>
897 <!-- BEGIN EXAMPLE CODE -->
898 <highlight language="c">
899 /* Handler for the "exambleEnabled" directive */
900 const char *example_set_enabled(cmd_parms *cmd, void *cfg, const char *arg)
902 if(!strcasecmp(arg, "on")) config.enabled = 1;
903 else config.enabled = 0;
907 /* Handler for the "examplePath" directive */
908 const char *example_set_path(cmd_parms *cmd, void *cfg, const char *arg)
914 /* Handler for the "exampleAction" directive */
915 /* Let's pretend this one takes one argument (file or db), and a second (deny or allow), */
916 /* and we store it in a bit-wise manner. */
917 const char *example_set_action(cmd_parms *cmd, void *cfg, const char *arg1, const char* arg2)
919 if(!strcasecmp(arg1, "file")) config.typeOfAction = 0x01;
920 else config.typeOfAction = 0x02;
922 if(!strcasecmp(arg2, "deny")) config.typeOfAction += 0x10;
923 else config.typeOfAction += 0x20;
927 <!-- END EXAMPLE CODE -->
931 <section id="directive_complete"><title>Putting it all together</title>
933 Now that we have our directives set up, and handlers configured for them,
934 we can assemble our module into one big file:
937 <!-- BEGIN EXAMPLE CODE -->
938 <highlight language="c">
939 /* mod_example_config_simple.c: */
940 #include <stdio.h>
941 #include "apr_hash.h"
942 #include "ap_config.h"
943 #include "ap_provider.h"
945 #include "http_core.h"
946 #include "http_config.h"
947 #include "http_log.h"
948 #include "http_protocol.h"
949 #include "http_request.h"
952 ==============================================================================
953 Our configuration prototype and declaration:
954 ==============================================================================
957 int enabled; /* Enable or disable our module */
958 const char *path; /* Some path to...something */
959 int typeOfAction; /* 1 means action A, 2 means action B and so on */
962 static example_config config;
965 ==============================================================================
966 Our directive handlers:
967 ==============================================================================
969 /* Handler for the "exambleEnabled" directive */
970 const char *example_set_enabled(cmd_parms *cmd, void *cfg, const char *arg)
972 if(!strcasecmp(arg, "on")) config.enabled = 1;
973 else config.enabled = 0;
977 /* Handler for the "examplePath" directive */
978 const char *example_set_path(cmd_parms *cmd, void *cfg, const char *arg)
984 /* Handler for the "exampleAction" directive */
985 /* Let's pretend this one takes one argument (file or db), and a second (deny or allow), */
986 /* and we store it in a bit-wise manner. */
987 const char *example_set_action(cmd_parms *cmd, void *cfg, const char *arg1, const char* arg2)
989 if(!strcasecmp(arg1, "file")) config.typeOfAction = 0x01;
990 else config.typeOfAction = 0x02;
992 if(!strcasecmp(arg2, "deny")) config.typeOfAction += 0x10;
993 else config.typeOfAction += 0x20;
998 ==============================================================================
999 The directive structure for our name tag:
1000 ==============================================================================
1002 static const command_rec example_directives[] =
1004 AP_INIT_TAKE1("exampleEnabled", example_set_enabled, NULL, RSRC_CONF, "Enable or disable mod_example"),
1005 AP_INIT_TAKE1("examplePath", example_set_path, NULL, RSRC_CONF, "The path to whatever"),
1006 AP_INIT_TAKE2("exampleAction", example_set_action, NULL, RSRC_CONF, "Special action value!"),
1010 ==============================================================================
1012 ==============================================================================
1014 static int example_handler(request_rec *r)
1016 if(!r->handler || strcmp(r->handler, "example-handler")) return(DECLINED);
1017 ap_set_content_type(r, "text/plain");
1018 ap_rprintf(r, "Enabled: %u\n", config.enabled);
1019 ap_rprintf(r, "Path: %s\n", config.path);
1020 ap_rprintf(r, "TypeOfAction: %x\n", config.typeOfAction);
1025 ==============================================================================
1026 The hook registration function (also initializes the default config values):
1027 ==============================================================================
1029 static void register_hooks(apr_pool_t *pool)
1032 config.path = "/foo/bar";
1033 config.typeOfAction = 3;
1034 ap_hook_handler(example_handler, NULL, NULL, APR_HOOK_LAST);
1037 ==============================================================================
1038 Our module name tag:
1039 ==============================================================================
1041 module AP_MODULE_DECLARE_DATA example_module =
1043 STANDARD20_MODULE_STUFF,
1044 NULL, /* Per-directory configuration handler */
1045 NULL, /* Merge handler for per-directory configurations */
1046 NULL, /* Per-server configuration handler */
1047 NULL, /* Merge handler for per-server configurations */
1048 example_directives, /* Any directives we may have for httpd */
1049 register_hooks /* Our hook registering function */
1052 <!-- END EXAMPLE CODE -->
1056 In our httpd.conf file, we can now change the hard-coded configuration by
1059 <highlight language="config">
1061 ExamplePath "/usr/bin/foo"
1062 ExampleAction file allow
1065 And thus we apply the configuration, visit <code>/example</code> on our
1066 web site, and we see the configuration has adapted to what we wrote in our
1074 <section id="context"><title>Context aware configurations</title>
1075 <section id="context_intro"><title>Introduction to context aware configurations</title>
1077 In Apache HTTP Server 2.4, different URLs, virtual hosts, directories etc can have very
1078 different meanings to the user of the server, and thus different contexts
1079 within which modules must operate. For example, let's assume you have this
1080 configuration set up for mod_rewrite:
1082 <highlight language="config">
1083 <Directory "/var/www">
1084 RewriteCond %{HTTP_HOST} ^example.com$
1085 RewriteRule (.*) http://www.example.com/$1
1087 <Directory "/var/www/sub">
1088 RewriteRule ^foobar$ index.php?foobar=true
1092 In this example, you will have set up two different contexts for
1095 <li>Inside <code>/var/www</code>, all requests for <code>http://example.com</code> must go to <code>http://www.example.com</code></li>
1096 <li>Inside <code>/var/www/sub</code>, all requests for <code>foobar</code> must go to <code>index.php?foobar=true</code></li>
1099 If mod_rewrite (or the entire server for that matter) wasn't context aware, then
1100 these rewrite rules would just apply to every and any request made,
1101 regardless of where and how they were made, but since the module can pull
1102 the context specific configuration straight from the server, it does not need
1103 to know itself, which of the directives are valid in this context, since
1104 the server takes care of this.</p>
1107 So how does a module get the specific configuration for the server,
1108 directory or location in question? It does so by making one simple call:
1111 <!-- BEGIN EXAMPLE CODE -->
1112 <highlight language="c">
1113 example_config *config = (example_config*) <a href="http://ci.apache.org/projects/httpd/trunk/doxygen/group__APACHE__CORE__CONFIG.html#ga1093a5908a384eacc929b028c79f2a02">ap_get_module_config</a>(r->per_dir_config, &example_module);
1115 <!-- END EXAMPLE CODE -->
1118 That's it! Of course, a whole lot goes on behind the scenes, which we will
1119 discuss in this chapter, starting with how the server came to know what our
1120 configuration looks like, and how it came to be set up as it is in the
1125 <section id="context_base"><title>Our basic configuration setup</title>
1126 <p>In this chapter, we will be working with a slightly modified version of
1127 our previous context structure. We will set a <code>context</code>
1128 variable that we can use to track which context configuration is being
1129 used by the server in various places:
1131 <!-- BEGIN EXAMPLE CODE -->
1132 <highlight language="c">
1140 <!-- END EXAMPLE CODE -->
1142 <p>Our handler for requests will also be modified, yet still very simple:</p>
1145 <!-- BEGIN EXAMPLE CODE -->
1146 <highlight language="c">
1147 static int example_handler(request_rec *r)
1149 if(!r->handler || strcmp(r->handler, "example-handler")) return(DECLINED);
1150 example_config *config = (example_config*) ap_get_module_config(r->per_dir_config, &example_module);
1151 ap_set_content_type(r, "text/plain");
1152 ap_rprintf("Enabled: %u\n", config->enabled);
1153 ap_rprintf("Path: %s\n", config->path);
1154 ap_rprintf("TypeOfAction: %x\n", config->typeOfAction);
1155 ap_rprintf("Context: %s\n", config->context);
1159 <!-- END EXAMPLE CODE -->
1163 <section id="context_which"><title>Choosing a context</title>
1165 Before we can start making our module context aware, we must first define,
1166 which contexts we will accept. As we saw in the previous chapter, defining
1167 a directive required five elements be set:</p>
1170 <!-- BEGIN EXAMPLE CODE -->
1171 <highlight language="c">
1172 AP_INIT_TAKE1("exampleEnabled", example_set_enabled, NULL, RSRC_CONF, "Enable or disable mod_example"),
1174 <!-- END EXAMPLE CODE -->
1177 <p>The <code>RSRC_CONF</code> definition told the server that we would only allow
1178 this directive in a global server context, but since we are now trying out
1179 a context aware version of our module, we should set this to something
1180 more lenient, namely the value <code>ACCESS_CONF</code>, which lets us use
1181 the directive inside <Directory> and <Location> blocks.
1185 <section id="context_pool"><title>Using the server to allocate configuration slots</title>
1186 <p> A much smarter way to manage your configurations is by letting the server
1187 help you create them. To do so, we must first start off by changing our
1188 <em>name tag</em> to let the server know, that it should assist us in creating
1189 and managing our configurations. Since we have chosen the per-directory
1190 (or per-location) context for our module configurations, we'll add a
1191 per-directory creator and merger function reference in our tag:</p>
1193 <!-- BEGIN EXAMPLE CODE -->
1194 <highlight language="c">
1195 module AP_MODULE_DECLARE_DATA example_module =
1197 STANDARD20_MODULE_STUFF,
1198 create_dir_conf, /* Per-directory configuration handler */
1199 merge_dir_conf, /* Merge handler for per-directory configurations */
1200 NULL, /* Per-server configuration handler */
1201 NULL, /* Merge handler for per-server configurations */
1202 directives, /* Any directives we may have for httpd */
1203 register_hooks /* Our hook registering function */
1206 <!-- END EXAMPLE CODE -->
1212 <section id="context_new"><title>Creating new context configurations</title>
1214 Now that we have told the server to help us create and manage configurations,
1215 our first step is to make a function for creating new, blank
1216 configurations. We do so by creating the function we just referenced in
1217 our name tag as the Per-directory configuration handler:</p>
1218 <!-- BEGIN EXAMPLE CODE -->
1219 <highlight language="c">
1220 void* example_create_dir_conf(apr_pool_t* pool, char* context) {
1221 context = context ? context : "(undefined context)";
1222 example_config *cfg = apr_pcalloc(pool, sizeof(example_config));
1224 /* Set some default values */
1225 strcpy(cfg->context, x);
1227 cfg->path = "/foo/bar";
1228 cfg->typeOfAction = 0x11;
1233 <!-- END EXAMPLE CODE -->
1238 <section id="context_merge"><title>Merging configurations</title>
1240 Our next step in creating a context aware configuration is merging
1241 configurations. This part of the process particularly apply to scenarios
1242 where you have a parent configuration and a child, such as the following:
1244 <highlight language="config">
1245 <Directory "/var/www">
1247 ExamplePath /foo/bar
1248 ExampleAction file allow
1250 <Directory "/var/www/subdir">
1251 ExampleAction file deny
1255 In this example, it is natural to assume that the directory <code>
1256 /var/www/subdir</code> should inherit the value set for the <code>/var/www
1257 </code> directory, as we did not specify a <code>ExampleEnable</code> nor
1258 an <code>ExamplePath</code> for this directory. The server does not presume to
1259 know if this is true, but cleverly does the following:
1262 <li>Creates a new configuration for <code>/var/www</code></li>
1263 <li>Sets the configuration values according to the directives given for <code>/var/www</code></li>
1264 <li>Creates a new configuration for <code>/var/www/subdir</code></li>
1265 <li>Sets the configuration values according to the directives given for <code>/var/www/subdir</code></li>
1266 <li><strong>Proposes a merge</strong> of the two configurations into a new configuration for <code>/var/www/subdir</code></li>
1269 This proposal is handled by the <code>merge_dir_conf</code> function we
1270 referenced in our name tag. The purpose of this function is to assess the
1271 two configurations and decide how they are to be merged:</p>
1274 <!-- BEGIN EXAMPLE CODE -->
1275 <highlight language="c">
1276 void* merge_dir_conf(apr_pool_t* pool, void* BASE, void* ADD) {
1277 example_config* base = (example_config *) BASE ;
1278 example_config* add = (example_config *) ADD ;
1279 example_config* conf = (example_config *) create_dir_conf(pool, "Merged configuration");
1281 conf->enabled = ( add->enabled == 0 ) ? base->enabled : add->enabled ;
1282 conf->typeOfAction = add->typeOfAction ? add->typeOfAction : base->typeOfAction;
1283 strcpy(conf->path, strlen(add->path) ? add->path : base->path);
1288 <!-- END EXAMPLE CODE -->
1293 <section id="context_example"><title>Trying out our new context aware configurations</title>
1295 Now, let's try putting it all together to create a new module that is
1296 context aware. First off, we'll create a configuration that lets us test
1297 how the module works:
1299 <highlight language="config">
1300 <Location "/a">
1301 SetHandler example-handler
1303 ExamplePath "/foo/bar"
1304 ExampleAction file allow
1307 <Location "/a/b">
1308 ExampleAction file deny
1312 <Location "/a/b/c">
1313 ExampleAction db deny
1314 ExamplePath "/foo/bar/baz"
1319 Then we'll assemble our module code. Note, that since we are now using our
1320 name tag as reference when fetching configurations in our handler, I have
1321 added some prototypes to keep the compiler happy:
1324 <!-- BEGIN EXAMPLE CODE -->
1325 <highlight language="c">
1327 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1328 * mod_example_config.c
1329 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1333 #include <stdio.h>
1334 #include "apr_hash.h"
1335 #include "ap_config.h"
1336 #include "ap_provider.h"
1338 #include "http_core.h"
1339 #include "http_config.h"
1340 #include "http_log.h"
1341 #include "http_protocol.h"
1342 #include "http_request.h"
1345 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1346 Configuration structure
1347 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1359 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1361 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1364 static int example_handler(request_rec *r);
1365 const char *example_set_enabled(cmd_parms *cmd, void *cfg, const char *arg);
1366 const char *example_set_path(cmd_parms *cmd, void *cfg, const char *arg);
1367 const char *example_set_action(cmd_parms *cmd, void *cfg, const char *arg1, const char *arg2);
1368 void *create_dir_conf(apr_pool_t *pool, char *context);
1369 void *merge_dir_conf(apr_pool_t *pool, void *BASE, void *ADD);
1370 static void register_hooks(apr_pool_t *pool);
1373 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1374 Configuration directives
1375 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1378 static const command_rec directives[] =
1380 AP_INIT_TAKE1("exampleEnabled", example_set_enabled, NULL, ACCESS_CONF, "Enable or disable mod_example"),
1381 AP_INIT_TAKE1("examplePath", example_set_path, NULL, ACCESS_CONF, "The path to whatever"),
1382 AP_INIT_TAKE2("exampleAction", example_set_action, NULL, ACCESS_CONF, "Special action value!"),
1387 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1389 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1392 module AP_MODULE_DECLARE_DATA example_module =
1394 STANDARD20_MODULE_STUFF,
1395 create_dir_conf, /* Per-directory configuration handler */
1396 merge_dir_conf, /* Merge handler for per-directory configurations */
1397 NULL, /* Per-server configuration handler */
1398 NULL, /* Merge handler for per-server configurations */
1399 directives, /* Any directives we may have for httpd */
1400 register_hooks /* Our hook registering function */
1404 =======================================================================================================================
1405 Hook registration function
1406 =======================================================================================================================
1408 static void register_hooks(apr_pool_t *pool)
1410 ap_hook_handler(example_handler, NULL, NULL, APR_HOOK_LAST);
1414 =======================================================================================================================
1415 Our example web service handler
1416 =======================================================================================================================
1418 static int example_handler(request_rec *r)
1420 if(!r->handler || strcmp(r->handler, "example-handler")) return(DECLINED);
1422 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1423 example_config *config = (example_config *) ap_get_module_config(r->per_dir_config, &example_module);
1424 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1426 ap_set_content_type(r, "text/plain");
1427 ap_rprintf(r, "Enabled: %u\n", config->enabled);
1428 ap_rprintf(r, "Path: %s\n", config->path);
1429 ap_rprintf(r, "TypeOfAction: %x\n", config->typeOfAction);
1430 ap_rprintf(r, "Context: %s\n", config->context);
1435 =======================================================================================================================
1436 Handler for the "exambleEnabled" directive
1437 =======================================================================================================================
1439 const char *example_set_enabled(cmd_parms *cmd, void *cfg, const char *arg)
1441 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1442 example_config *conf = (example_config *) cfg;
1443 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1447 if(!strcasecmp(arg, "on"))
1448 conf->enabled = 1;
1450 conf->enabled = 0;
1457 =======================================================================================================================
1458 Handler for the "examplePath" directive
1459 =======================================================================================================================
1461 const char *example_set_path(cmd_parms *cmd, void *cfg, const char *arg)
1463 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1464 example_config *conf = (example_config *) cfg;
1465 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1469 strcpy(conf->path, arg);
1476 =======================================================================================================================
1477 Handler for the "exampleAction" directive ;
1478 Let's pretend this one takes one argument (file or db), and a second (deny or allow), ;
1479 and we store it in a bit-wise manner.
1480 =======================================================================================================================
1482 const char *example_set_action(cmd_parms *cmd, void *cfg, const char *arg1, const char *arg2)
1484 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1485 example_config *conf = (example_config *) cfg;
1486 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1491 if(!strcasecmp(arg1, "file"))
1492 conf->typeOfAction = 0x01;
1494 conf->typeOfAction = 0x02;
1495 if(!strcasecmp(arg2, "deny"))
1496 conf->typeOfAction += 0x10;
1498 conf->typeOfAction += 0x20;
1506 =======================================================================================================================
1507 Function for creating new configurations for per-directory contexts
1508 =======================================================================================================================
1510 void *create_dir_conf(apr_pool_t *pool, char *context)
1512 context = context ? context : "Newly created configuration";
1514 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1515 example_config *cfg = apr_pcalloc(pool, sizeof(example_config));
1516 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1521 /* Set some default values */
1522 strcpy(cfg->context, context);
1523 cfg->enabled = 0;
1524 memset(cfg->path, 0, 256);
1525 cfg->typeOfAction = 0x00;
1533 =======================================================================================================================
1534 Merging function for configurations
1535 =======================================================================================================================
1537 void *merge_dir_conf(apr_pool_t *pool, void *BASE, void *ADD)
1539 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1540 example_config *base = (example_config *) BASE;
1541 example_config *add = (example_config *) ADD;
1542 example_config *conf = (example_config *) create_dir_conf(pool, "Merged configuration");
1543 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1545 conf->enabled = (add->enabled == 0) ? base->enabled : add->enabled;
1546 conf->typeOfAction = add->typeOfAction ? add->typeOfAction : base->typeOfAction;
1547 strcpy(conf->path, strlen(add->path) ? add->path : base->path);
1551 <!-- END EXAMPLE CODE -->
1559 <section id="summary"><title>Summing up</title>
1561 We have now looked at how to create simple modules for Apache HTTP Server 2.4 and
1562 configuring them. What you do next is entirely up to you, but it is my
1563 hope that something valuable has come out of reading this documentation.
1564 If you have questions on how to further develop modules, you are welcome
1565 to join our <a href="http://httpd.apache.org/lists.html">mailing lists</a>
1566 or check out the rest of our documentation for further tips.
1570 <section id="snippets"><title>Some useful snippets of code</title>
1572 <section id="get_post"><title>Retrieve a variable from POST form data</title>
1575 <!-- BEGIN EXAMPLE CODE -->
1576 <highlight language="c">
1577 const char *read_post_value(const apr_array_header_t *fields, const char *key)
1579 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1581 apr_table_entry_t *e = 0;
1582 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1583 e = (apr_table_entry_t *) fields->elts;
1584 for(i = 0; i < fields->nelts; i++) {
1585 if(!strcmp(e[i].key, key)) return e[i].val;
1589 static int example_handler(request_req *r)
1591 /*~~~~~~~~~~~~~~~~~~~~~~*/
1592 apr_array_header_t *POST;
1594 /*~~~~~~~~~~~~~~~~~~~~~~*/
1595 ap_parse_form_data(r, NULL, &POST, -1, 8192);
1597 value = read_post_value(POST, "valueA");
1598 if (!value) value = "(undefined)";
1599 ap_rprintf(r, "The value of valueA is: %s", value);
1603 <!-- END EXAMPLE CODE -->
1608 <section id="headers_out"><title>Printing out every HTTP header received</title>
1611 <!-- BEGIN EXAMPLE CODE -->
1612 <highlight language="c">
1613 static int example_handler(request_req *r)
1615 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1616 const apr_array_header_t *fields;
1618 apr_table_entry_t *e = 0;
1619 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1621 fields = apr_table_elts(r->headers_in);
1622 e = (apr_table_entry_t *) fields->elts;
1623 for(i = 0; i < fields->nelts; i++) {
1624 ap_rprintf(r, "<b>%s</b>: %s<br/>", e[i].key, e[i].val);
1629 <!-- END EXAMPLE CODE -->
1634 <section id="request_body"><title>Reading the request body into memory</title>
1637 <!-- BEGIN EXAMPLE CODE -->
1638 <highlight language="c">
1639 static int util_read(request_rec *r, const char **rbuf, apr_off_t *size)
1645 if((rc = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) {
1649 if(ap_should_client_block(r)) {
1651 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1652 char argsbuffer[HUGE_STRING_LEN];
1653 apr_off_t rsize, len_read, rpos = 0;
1654 apr_off_t length = r->remaining;
1655 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1657 *rbuf = (const char *) apr_pcalloc(r->pool, (apr_size_t) (length + 1));
1659 while((len_read = ap_get_client_block(r, argsbuffer, sizeof(argsbuffer))) > 0) {
1660 if((rpos + len_read) > length) {
1661 rsize = length - rpos;
1667 memcpy((char *) *rbuf + rpos, argsbuffer, (size_t) rsize);
1674 static int example_handler(request_req* r)
1676 /*~~~~~~~~~~~~~~~~*/
1679 /*~~~~~~~~~~~~~~~~*/
1681 if(util_read(r, &data, &size) == OK) {
1682 ap_rprintf("We read a request body that was %u bytes long", size);
1688 <!-- END EXAMPLE CODE -->