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; <em>
552 </em><a href="http://ci.apache.org/projects/httpd/trunk/doxygen/structapr__array__header__t.html">apr_array_header_t</a>*POST;
555 <a href="http://ci.apache.org/projects/httpd/trunk/doxygen/group__APACHE__CORE__SCRIPT.html#gaed25877b529623a4d8f99f819ba1b7bd">
556 ap_args_to_table</a>(r, &GET); <em>
557 </em><a href="http://ci.apache.org/projects/httpd/trunk/doxygen/group__APACHE__CORE__DAEMON.html#ga9d426b6382b49754d4f87c55f65af202">
558 ap_parse_form_data</a>(r, NULL, &POST, -1, 8192);
560 <!-- END EXAMPLE CODE -->
563 In our specific example module, we're looking for the <code>digest</code>
564 value from the query string, which now resides inside a table called <code>
565 GET</code>. To extract this value, we need only perform a simple operation:
569 <!-- BEGIN EXAMPLE CODE -->
570 <highlight language="c">
571 /* Get the "digest" key from the query string, if any. */
572 const char *digestType = apr_table_get(GET, "digest");
574 /* If no key was returned, we will set a default value instead. */
575 if (!digestType) digestType = "sha1";
577 <!-- END EXAMPLE CODE -->
580 The structures used for the POST and GET data are not exactly the same, so
581 if we were to fetch a value from POST data instead of the query string, we
582 would have to resort to a few more lines, as outlined in <a href="#get_post"
583 >this example</a> in the last chapter of this document.
587 <section id="advanced_handler"><title>Making an advanced handler</title>
589 Now that we have learned how to parse form data and manage our resources,
590 we can move on to creating an advanced version of our module, that spits
591 out the MD5 or SHA1 digest of files:
595 <!-- BEGIN EXAMPLE CODE -->
596 <highlight language="c">
597 static int example_handler(request_rec *r)
604 apr_size_t readBytes;
607 apr_array_header_t *POST;
608 const char *digestType;
611 /* Check that the "example-handler" handler is being called. */
612 if (!r->handler || strcmp(r->handler, "example-handler")) return (DECLINED);
614 /* Figure out which file is being requested by removing the .sum from it */
615 filename = apr_pstrdup(r->pool, r->filename);
616 filename[strlen(filename)-4] = 0; /* Cut off the last 4 characters. */
618 /* Figure out if the file we request a sum on exists and isn't a directory */
619 rc = apr_stat(&finfo, filename, APR_FINFO_MIN, r->pool);
620 if (rc == APR_SUCCESS) {
623 (finfo.filetype != APR_NOFILE)
624 && !(finfo.filetype & APR_DIR)
626 if (!exists) return HTTP_NOT_FOUND; /* Return a 404 if not found. */
628 /* If apr_stat failed, we're probably not allowed to check this file. */
629 else return HTTP_FORBIDDEN;
631 /* Parse the GET and, optionally, the POST data sent to us */
633 ap_args_to_table(r, &GET);
634 ap_parse_form_data(r, NULL, &POST, -1, 8192);
636 /* Set the appropriate content type */
637 ap_set_content_type(r, "text/html");
639 /* Print a title and some general information */
640 ap_rprintf(r, "<h2>Information on %s:</h2>", filename);
641 ap_rprintf(r, "<b>Size:</b> %u bytes<br/>", finfo.size);
643 /* Get the digest type the client wants to see */
644 digestType = apr_table_get(GET, "digest");
645 if (!digestType) digestType = "MD5";
648 rc = apr_file_open(&file, filename, APR_READ, APR_OS_DEFAULT, r->pool);
649 if (rc == APR_SUCCESS) {
651 /* Are we trying to calculate the MD5 or the SHA1 digest? */
652 if (!strcasecmp(digestType, "md5")) {
653 /* Calculate the MD5 sum of the file */
659 apr_md5_init(&md5);
661 while ( apr_file_read(file, buffer, &readBytes) == APR_SUCCESS ) {
662 apr_md5_update(&md5, buffer, readBytes);
664 apr_md5_final(digest.chr, &md5);
666 /* Print out the MD5 digest */
667 ap_rputs("<b>MD5: </b><code>", r);
668 for (n = 0; n < APR_MD5_DIGESTSIZE/4; n++) {
669 ap_rprintf(r, "%08x", digest.num[n]);
671 ap_rputs("</code>", r);
672 /* Print a link to the SHA1 version */
673 ap_rputs("<br/><a href='?digest=sha1'>View the SHA1 hash instead</a>", r);
676 /* Calculate the SHA1 sum of the file */
682 apr_sha1_init(&sha1);
684 while ( apr_file_read(file, buffer, &readBytes) == APR_SUCCESS ) {
685 apr_sha1_update(&sha1, buffer, readBytes);
687 apr_sha1_final(digest.chr, &sha1);
689 /* Print out the SHA1 digest */
690 ap_rputs("<b>SHA1: </b><code>", r);
691 for (n = 0; n < APR_SHA1_DIGESTSIZE/4; n++) {
692 ap_rprintf(r, "%08x", digest.num[n]);
694 ap_rputs("</code>", r);
696 /* Print a link to the MD5 version */
697 ap_rputs("<br/><a href='?digest=md5'>View the MD5 hash instead</a>", r);
699 apr_file_close(file);
702 /* Let the server know that we responded to this request. */
706 <!-- END EXAMPLE CODE -->
709 This version in its entirity can be found here:
710 <a href="http://people.apache.org/~humbedooh/mods/examples/mod_example_2.c">mod_example_2.c</a>.
716 <section id="configuration"><title>Adding configuration options</title>
718 In this next segment of this document, we will turn our eyes away from the
719 digest module and create a new example module, whose only function is to
720 write out its own configuration. The purpose of this is to examine how
721 the server works with configuration, and what happens when you start writing
722 advanced configurations
725 <section id="config_intro"><title>An introduction to configuration
728 If you are reading this, then you probably already know
729 what a configuration directive is. Simply put, a directive is a way of
730 telling an individual module (or a set of modules) how to behave, such as
731 these directives control how <code>mod_rewrite</code> works:
733 <highlight language="config">
735 RewriteCond %{REQUEST_URI} ^/foo/bar
736 RewriteRule ^/foo/bar/(.*)$ /foobar?page=$1
739 Each of these configuration directives are handled by a separate function,
740 that parses the parameters given and sets up a configuration accordingly.
743 <section id="config_simple"><title>Making an example configuration</title>
744 <p>To begin with, we'll create a basic configuration in C-space:</p>
747 <!-- BEGIN EXAMPLE CODE -->
748 <highlight language="c">
750 int enabled; /* Enable or disable our module */
751 const char *path; /* Some path to...something */
752 int typeOfAction; /* 1 means action A, 2 means action B and so on */
755 <!-- END EXAMPLE CODE -->
758 Now, let's put this into perspective by creating a very small module that
759 just prints out a hard-coded configuration. You'll notice that we use the
760 <code>register_hooks</code> function for initializing the configuration
761 values to their defaults:
764 <!-- BEGIN EXAMPLE CODE -->
765 <highlight language="c">
767 int enabled; /* Enable or disable our module */
768 const char *path; /* Some path to...something */
769 int typeOfAction; /* 1 means action A, 2 means action B and so on */
772 static example_config config;
774 static int example_handler(request_rec *r)
776 if (!r->handler || strcmp(r->handler, "example-handler")) return(DECLINED);
777 ap_set_content_type(r, "text/plain");
778 ap_rprintf(r, "Enabled: %u\n", config.enabled);
779 ap_rprintf(r, "Path: %s\n", config.path);
780 ap_rprintf(r, "TypeOfAction: %x\n", config.typeOfAction);
784 static void register_hooks(apr_pool_t *pool)
787 config.path = "/foo/bar";
788 config.typeOfAction = 0x00;
789 ap_hook_handler(example_handler, NULL, NULL, APR_HOOK_LAST);
792 /* Define our module as an entity and assign a function for registering hooks */
794 module AP_MODULE_DECLARE_DATA example_module =
796 STANDARD20_MODULE_STUFF,
797 NULL, /* Per-directory configuration handler */
798 NULL, /* Merge handler for per-directory configurations */
799 NULL, /* Per-server configuration handler */
800 NULL, /* Merge handler for per-server configurations */
801 NULL, /* Any directives we may have for httpd */
802 register_hooks /* Our hook registering function */
805 <!-- END EXAMPLE CODE -->
808 So far so good. To access our new handler, we could add the following to
811 <highlight language="config">
812 <Location /example>
813 SetHandler example-handler
817 When we visit, we'll see our current configuration being spit out by our
822 <section id="register_directive"><title>Registering directives with the server</title>
824 What if we want to change our configuration, not by hard-coding new values
825 into the module, but by using either the httpd.conf file or possibly a
826 .htaccess file? It's time to let the server know that we want this to be
827 possible. To do so, we must first change our <em>name tag</em> to include a
828 reference to the configuration directives we want to register with the server:
831 <!-- BEGIN EXAMPLE CODE -->
832 <highlight language="c">
833 module AP_MODULE_DECLARE_DATA example_module =
835 STANDARD20_MODULE_STUFF,
836 NULL, /* Per-directory configuration handler */
837 NULL, /* Merge handler for per-directory configurations */
838 NULL, /* Per-server configuration handler */
839 NULL, /* Merge handler for per-server configurations */
840 example_directives, /* Any directives we may have for httpd */
841 register_hooks /* Our hook registering function */
844 <!-- END EXAMPLE CODE -->
847 This will tell the server that we are now accepting directives from the
848 configuration files, and that the structure called <code>example_directives
849 </code> holds information on what our directives are and how they work.
850 Since we have three different variables in our module configuration, we
851 will add a structure with three directives and a NULL at the end:
854 <!-- BEGIN EXAMPLE CODE -->
855 <highlight language="c">
856 static const command_rec example_directives[] =
858 AP_INIT_TAKE1("exampleEnabled", example_set_enabled, NULL, RSRC_CONF, "Enable or disable mod_example"),
859 AP_INIT_TAKE1("examplePath", example_set_path, NULL, RSRC_CONF, "The path to whatever"),
860 AP_INIT_TAKE2("exampleAction", example_set_action, NULL, RSRC_CONF, "Special action value!"),
864 <!-- END EXAMPLE CODE -->
867 <img src="../images/build_a_mod_4.png" alt="Directives structure"/><br />
868 As you can see, each directive needs at least 5 parameters set:
871 <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.
872 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
873 for more macros).</li>
874 <li><code>exampleEnabled</code>: This is the name of our directive. More precisely, it is what the user must put in his/her
875 configuration in order to invoke a configuration change in our module.</li>
876 <li><code>example_set_enabled</code>: This is a reference to a C function that parses the directive and sets the configuration
877 accordingly. We will discuss how to make this in the following paragraph.</li>
878 <li><code>RSRC_CONF</code>: This tells the server where the directive is permitted. We'll go into details on this value in the
879 later chapters, but for now, <code>RSRC_CONF</code> means that the server will only accept these directives in a server context.</li>
880 <li><code>"Enable or disable...."</code>: This is simply a brief description of what the directive does.</li>
883 (<em>The "missing" parameter in our definition, which is usually set to
884 <code>NULL</code>, is an optional function that can be run after the
885 initial function to parse the arguments have been run. This is usually
886 omitted, as the function for verifying arguments might as well be used to
890 <section id="directive_handler"><title>The directive handler function</title>
892 Now that we've told the server to expect some directives for our module, it's
893 time to make a few functions for handling these. What the server reads in the
894 configuration file(s) is text, and so naturally, what it passes along to
895 our directive handler is one or more strings, that we ourselves need to
896 recognize and act upon. You'll notice, that since we set our <code>
897 exampleAction</code> directive to accept two arguments, its C function also
898 has an additional parameter defined:</p>
900 <!-- BEGIN EXAMPLE CODE -->
901 <highlight language="c">
902 /* Handler for the "exambleEnabled" directive */
903 const char *example_set_enabled(cmd_parms *cmd, void *cfg, const char *arg)
905 if(!strcasecmp(arg, "on")) config.enabled = 1;
906 else config.enabled = 0;
910 /* Handler for the "examplePath" directive */
911 const char *example_set_path(cmd_parms *cmd, void *cfg, const char *arg)
917 /* Handler for the "exampleAction" directive */
918 /* Let's pretend this one takes one argument (file or db), and a second (deny or allow), */
919 /* and we store it in a bit-wise manner. */
920 const char *example_set_action(cmd_parms *cmd, void *cfg, const char *arg1, const char* arg2)
922 if(!strcasecmp(arg1, "file")) config.typeOfAction = 0x01;
923 else config.typeOfAction = 0x02;
925 if(!strcasecmp(arg2, "deny")) config.typeOfAction += 0x10;
926 else config.typeOfAction += 0x20;
930 <!-- END EXAMPLE CODE -->
934 <section id="directive_complete"><title>Putting it all together</title>
936 Now that we have our directives set up, and handlers configured for them,
937 we can assemble our module into one big file:
940 <!-- BEGIN EXAMPLE CODE -->
941 <highlight language="c">
942 /* mod_example_config_simple.c: */
943 #include <stdio.h>
944 #include "apr_hash.h"
945 #include "ap_config.h"
946 #include "ap_provider.h"
948 #include "http_core.h"
949 #include "http_config.h"
950 #include "http_log.h"
951 #include "http_protocol.h"
952 #include "http_request.h"
955 ==============================================================================
956 Our configuration prototype and declaration:
957 ==============================================================================
960 int enabled; /* Enable or disable our module */
961 const char *path; /* Some path to...something */
962 int typeOfAction; /* 1 means action A, 2 means action B and so on */
965 static example_config config;
968 ==============================================================================
969 Our directive handlers:
970 ==============================================================================
972 /* Handler for the "exambleEnabled" directive */
973 const char *example_set_enabled(cmd_parms *cmd, void *cfg, const char *arg)
975 if(!strcasecmp(arg, "on")) config.enabled = 1;
976 else config.enabled = 0;
980 /* Handler for the "examplePath" directive */
981 const char *example_set_path(cmd_parms *cmd, void *cfg, const char *arg)
987 /* Handler for the "exampleAction" directive */
988 /* Let's pretend this one takes one argument (file or db), and a second (deny or allow), */
989 /* and we store it in a bit-wise manner. */
990 const char *example_set_action(cmd_parms *cmd, void *cfg, const char *arg1, const char* arg2)
992 if(!strcasecmp(arg1, "file")) config.typeOfAction = 0x01;
993 else config.typeOfAction = 0x02;
995 if(!strcasecmp(arg2, "deny")) config.typeOfAction += 0x10;
996 else config.typeOfAction += 0x20;
1001 ==============================================================================
1002 The directive structure for our name tag:
1003 ==============================================================================
1005 static const command_rec example_directives[] =
1007 AP_INIT_TAKE1("exampleEnabled", example_set_enabled, NULL, RSRC_CONF, "Enable or disable mod_example"),
1008 AP_INIT_TAKE1("examplePath", example_set_path, NULL, RSRC_CONF, "The path to whatever"),
1009 AP_INIT_TAKE2("exampleAction", example_set_action, NULL, RSRC_CONF, "Special action value!"),
1013 ==============================================================================
1015 ==============================================================================
1017 static int example_handler(request_rec *r)
1019 if(!r->handler || strcmp(r->handler, "example-handler")) return(DECLINED);
1020 ap_set_content_type(r, "text/plain");
1021 ap_rprintf(r, "Enabled: %u\n", config.enabled);
1022 ap_rprintf(r, "Path: %s\n", config.path);
1023 ap_rprintf(r, "TypeOfAction: %x\n", config.typeOfAction);
1028 ==============================================================================
1029 The hook registration function (also initializes the default config values):
1030 ==============================================================================
1032 static void register_hooks(apr_pool_t *pool)
1035 config.path = "/foo/bar";
1036 config.typeOfAction = 3;
1037 ap_hook_handler(example_handler, NULL, NULL, APR_HOOK_LAST);
1040 ==============================================================================
1041 Our module name tag:
1042 ==============================================================================
1044 module AP_MODULE_DECLARE_DATA example_module =
1046 STANDARD20_MODULE_STUFF,
1047 NULL, /* Per-directory configuration handler */
1048 NULL, /* Merge handler for per-directory configurations */
1049 NULL, /* Per-server configuration handler */
1050 NULL, /* Merge handler for per-server configurations */
1051 example_directives, /* Any directives we may have for httpd */
1052 register_hooks /* Our hook registering function */
1055 <!-- END EXAMPLE CODE -->
1059 In our httpd.conf file, we can now change the hard-coded configuration by
1062 <highlight language="config">
1064 ExamplePath "/usr/bin/foo"
1065 ExampleAction file allow
1068 And thus we apply the configuration, visit <code>/example</code> on our
1069 web site, and we see the configuration has adapted to what we wrote in our
1077 <section id="context"><title>Context aware configurations</title>
1078 <section id="context_intro"><title>Introduction to context aware configurations</title>
1080 In Apache HTTP Server 2.4, different URLs, virtual hosts, directories etc can have very
1081 different meanings to the user of the server, and thus different contexts
1082 within which modules must operate. For example, let's assume you have this
1083 configuration set up for mod_rewrite:
1085 <highlight language="config">
1086 <Directory "/var/www">
1087 RewriteCond %{HTTP_HOST} ^example.com$
1088 RewriteRule (.*) http://www.example.com/$1
1090 <Directory "/var/www/sub">
1091 RewriteRule ^foobar$ index.php?foobar=true
1095 In this example, you will have set up two different contexts for
1098 <li>Inside <code>/var/www</code>, all requests for <code>http://example.com</code> must go to <code>http://www.example.com</code></li>
1099 <li>Inside <code>/var/www/sub</code>, all requests for <code>foobar</code> must go to <code>index.php?foobar=true</code></li>
1102 If mod_rewrite (or the entire server for that matter) wasn't context aware, then
1103 these rewrite rules would just apply to every and any request made,
1104 regardless of where and how they were made, but since the module can pull
1105 the context specific configuration straight from the server, it does not need
1106 to know itself, which of the directives are valid in this context, since
1107 the server takes care of this.</p>
1110 So how does a module get the specific configuration for the server,
1111 directory or location in question? It does so by making one simple call:
1114 <!-- BEGIN EXAMPLE CODE -->
1115 <highlight language="c">
1116 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);
1118 <!-- END EXAMPLE CODE -->
1121 That's it! Of course, a whole lot goes on behind the scenes, which we will
1122 discuss in this chapter, starting with how the server came to know what our
1123 configuration looks like, and how it came to be set up as it is in the
1128 <section id="context_base"><title>Our basic configuration setup</title>
1129 <p>In this chapter, we will be working with a slightly modified version of
1130 our previous context structure. We will set a <code>context</code>
1131 variable that we can use to track which context configuration is being
1132 used by the server in various places:
1134 <!-- BEGIN EXAMPLE CODE -->
1135 <highlight language="c">
1143 <!-- END EXAMPLE CODE -->
1145 <p>Our handler for requests will also be modified, yet still very simple:</p>
1148 <!-- BEGIN EXAMPLE CODE -->
1149 <highlight language="c">
1150 static int example_handler(request_rec *r)
1152 if(!r->handler || strcmp(r->handler, "example-handler")) return(DECLINED);
1153 example_config *config = (example_config*) ap_get_module_config(r->per_dir_config, &example_module);
1154 ap_set_content_type(r, "text/plain");
1155 ap_rprintf("Enabled: %u\n", config->enabled);
1156 ap_rprintf("Path: %s\n", config->path);
1157 ap_rprintf("TypeOfAction: %x\n", config->typeOfAction);
1158 ap_rprintf("Context: %s\n", config->context);
1162 <!-- END EXAMPLE CODE -->
1166 <section id="context_which"><title>Choosing a context</title>
1168 Before we can start making our module context aware, we must first define,
1169 which contexts we will accept. As we saw in the previous chapter, defining
1170 a directive required five elements be set:</p>
1173 <!-- BEGIN EXAMPLE CODE -->
1174 <highlight language="c">
1175 AP_INIT_TAKE1("exampleEnabled", example_set_enabled, NULL, RSRC_CONF, "Enable or disable mod_example"),
1177 <!-- END EXAMPLE CODE -->
1180 <p>The <code>RSRC_CONF</code> definition told the server that we would only allow
1181 this directive in a global server context, but since we are now trying out
1182 a context aware version of our module, we should set this to something
1183 more lenient, namely the value <code>ACCESS_CONF</code>, which lets us use
1184 the directive inside <Directory> and <Location> blocks.
1188 <section id="context_pool"><title>Using the server to allocate configuration slots</title>
1189 <p> A much smarter way to manage your configurations is by letting the server
1190 help you create them. To do so, we must first start off by changing our
1191 <em>name tag</em> to let the server know, that it should assist us in creating
1192 and managing our configurations. Since we have chosen the per-directory
1193 (or per-location) context for our module configurations, we'll add a
1194 per-directory creator and merger function reference in our tag:</p>
1196 <!-- BEGIN EXAMPLE CODE -->
1197 <highlight language="c">
1198 module AP_MODULE_DECLARE_DATA example_module =
1200 STANDARD20_MODULE_STUFF,
1201 create_dir_conf, /* Per-directory configuration handler */
1202 merge_dir_conf, /* Merge handler for per-directory configurations */
1203 NULL, /* Per-server configuration handler */
1204 NULL, /* Merge handler for per-server configurations */
1205 directives, /* Any directives we may have for httpd */
1206 register_hooks /* Our hook registering function */
1209 <!-- END EXAMPLE CODE -->
1215 <section id="context_new"><title>Creating new context configurations</title>
1217 Now that we have told the server to help us create and manage configurations,
1218 our first step is to make a function for creating new, blank
1219 configurations. We do so by creating the function we just referenced in
1220 our name tag as the Per-directory configuration handler:</p>
1221 <!-- BEGIN EXAMPLE CODE -->
1222 <highlight language="c">
1223 void* example_create_dir_conf(apr_pool_t* pool, char* context) {
1224 context = context ? context : "(undefined context)";
1225 example_config *cfg = apr_pcalloc(pool, sizeof(example_config));
1227 /* Set some default values */
1228 strcpy(cfg->context, x);
1230 cfg->path = "/foo/bar";
1231 cfg->typeOfAction = 0x11;
1236 <!-- END EXAMPLE CODE -->
1241 <section id="context_merge"><title>Merging configurations</title>
1243 Our next step in creating a context aware configuration is merging
1244 configurations. This part of the process particularly apply to scenarios
1245 where you have a parent configuration and a child, such as the following:
1247 <highlight language="config">
1248 <Directory "/var/www">
1250 ExamplePath /foo/bar
1251 ExampleAction file allow
1253 <Directory "/var/www/subdir">
1254 ExampleAction file deny
1258 In this example, it is natural to assume that the directory <code>
1259 /var/www/subdir</code> should inherit the value set for the <code>/var/www
1260 </code> directory, as we did not specify a <code>ExampleEnable</code> nor
1261 an <code>ExamplePath</code> for this directory. The server does not presume to
1262 know if this is true, but cleverly does the following:
1265 <li>Creates a new configuration for <code>/var/www</code></li>
1266 <li>Sets the configuration values according to the directives given for <code>/var/www</code></li>
1267 <li>Creates a new configuration for <code>/var/www/subdir</code></li>
1268 <li>Sets the configuration values according to the directives given for <code>/var/www/subdir</code></li>
1269 <li><strong>Proposes a merge</strong> of the two configurations into a new configuration for <code>/var/www/subdir</code></li>
1272 This proposal is handled by the <code>merge_dir_conf</code> function we
1273 referenced in our name tag. The purpose of this function is to assess the
1274 two configurations and decide how they are to be merged:</p>
1277 <!-- BEGIN EXAMPLE CODE -->
1278 <highlight language="c">
1279 void* merge_dir_conf(apr_pool_t* pool, void* BASE, void* ADD) {
1280 example_config* base = (example_config *) BASE ;
1281 example_config* add = (example_config *) ADD ;
1282 example_config* conf = (example_config *) create_dir_conf(pool, "Merged configuration");
1284 conf->enabled = ( add->enabled == 0 ) ? base->enabled : add->enabled ;
1285 conf->typeOfAction = add->typeOfAction ? add->typeOfAction : base->typeOfAction;
1286 strcpy(conf->path, strlen(add->path) ? add->path : base->path);
1291 <!-- END EXAMPLE CODE -->
1296 <section id="context_example"><title>Trying out our new context aware configurations</title>
1298 Now, let's try putting it all together to create a new module that is
1299 context aware. First off, we'll create a configuration that lets us test
1300 how the module works:
1302 <highlight language="config">
1303 <Location "/a">
1304 SetHandler example-handler
1306 ExamplePath "/foo/bar"
1307 ExampleAction file allow
1310 <Location "/a/b">
1311 ExampleAction file deny
1315 <Location "/a/b/c">
1316 ExampleAction db deny
1317 ExamplePath "/foo/bar/baz"
1322 Then we'll assemble our module code. Note, that since we are now using our
1323 name tag as reference when fetching configurations in our handler, I have
1324 added some prototypes to keep the compiler happy:
1327 <!-- BEGIN EXAMPLE CODE -->
1328 <highlight language="c">
1330 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1331 * mod_example_config.c
1332 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1336 #include <stdio.h>
1337 #include "apr_hash.h"
1338 #include "ap_config.h"
1339 #include "ap_provider.h"
1341 #include "http_core.h"
1342 #include "http_config.h"
1343 #include "http_log.h"
1344 #include "http_protocol.h"
1345 #include "http_request.h"
1348 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1349 Configuration structure
1350 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1362 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1364 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1367 static int example_handler(request_rec *r);
1368 const char *example_set_enabled(cmd_parms *cmd, void *cfg, const char *arg);
1369 const char *example_set_path(cmd_parms *cmd, void *cfg, const char *arg);
1370 const char *example_set_action(cmd_parms *cmd, void *cfg, const char *arg1, const char *arg2);
1371 void *create_dir_conf(apr_pool_t *pool, char *context);
1372 void *merge_dir_conf(apr_pool_t *pool, void *BASE, void *ADD);
1373 static void register_hooks(apr_pool_t *pool);
1376 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1377 Configuration directives
1378 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1381 static const command_rec directives[] =
1383 AP_INIT_TAKE1("exampleEnabled", example_set_enabled, NULL, ACCESS_CONF, "Enable or disable mod_example"),
1384 AP_INIT_TAKE1("examplePath", example_set_path, NULL, ACCESS_CONF, "The path to whatever"),
1385 AP_INIT_TAKE2("exampleAction", example_set_action, NULL, ACCESS_CONF, "Special action value!"),
1390 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1392 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1395 module AP_MODULE_DECLARE_DATA example_module =
1397 STANDARD20_MODULE_STUFF,
1398 create_dir_conf, /* Per-directory configuration handler */
1399 merge_dir_conf, /* Merge handler for per-directory configurations */
1400 NULL, /* Per-server configuration handler */
1401 NULL, /* Merge handler for per-server configurations */
1402 directives, /* Any directives we may have for httpd */
1403 register_hooks /* Our hook registering function */
1407 =======================================================================================================================
1408 Hook registration function
1409 =======================================================================================================================
1411 static void register_hooks(apr_pool_t *pool)
1413 ap_hook_handler(example_handler, NULL, NULL, APR_HOOK_LAST);
1417 =======================================================================================================================
1418 Our example web service handler
1419 =======================================================================================================================
1421 static int example_handler(request_rec *r)
1423 if(!r->handler || strcmp(r->handler, "example-handler")) return(DECLINED);
1425 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1426 example_config *config = (example_config *) ap_get_module_config(r->per_dir_config, &example_module);
1427 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1429 ap_set_content_type(r, "text/plain");
1430 ap_rprintf(r, "Enabled: %u\n", config->enabled);
1431 ap_rprintf(r, "Path: %s\n", config->path);
1432 ap_rprintf(r, "TypeOfAction: %x\n", config->typeOfAction);
1433 ap_rprintf(r, "Context: %s\n", config->context);
1438 =======================================================================================================================
1439 Handler for the "exambleEnabled" directive
1440 =======================================================================================================================
1442 const char *example_set_enabled(cmd_parms *cmd, void *cfg, const char *arg)
1444 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1445 example_config *conf = (example_config *) cfg;
1446 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1450 if(!strcasecmp(arg, "on"))
1451 conf->enabled = 1;
1453 conf->enabled = 0;
1460 =======================================================================================================================
1461 Handler for the "examplePath" directive
1462 =======================================================================================================================
1464 const char *example_set_path(cmd_parms *cmd, void *cfg, const char *arg)
1466 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1467 example_config *conf = (example_config *) cfg;
1468 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1472 strcpy(conf->path, arg);
1479 =======================================================================================================================
1480 Handler for the "exampleAction" directive ;
1481 Let's pretend this one takes one argument (file or db), and a second (deny or allow), ;
1482 and we store it in a bit-wise manner.
1483 =======================================================================================================================
1485 const char *example_set_action(cmd_parms *cmd, void *cfg, const char *arg1, const char *arg2)
1487 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1488 example_config *conf = (example_config *) cfg;
1489 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1494 if(!strcasecmp(arg1, "file"))
1495 conf->typeOfAction = 0x01;
1497 conf->typeOfAction = 0x02;
1498 if(!strcasecmp(arg2, "deny"))
1499 conf->typeOfAction += 0x10;
1501 conf->typeOfAction += 0x20;
1509 =======================================================================================================================
1510 Function for creating new configurations for per-directory contexts
1511 =======================================================================================================================
1513 void *create_dir_conf(apr_pool_t *pool, char *context)
1515 context = context ? context : "Newly created configuration";
1517 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1518 example_config *cfg = apr_pcalloc(pool, sizeof(example_config));
1519 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1524 /* Set some default values */
1525 strcpy(cfg->context, context);
1526 cfg->enabled = 0;
1527 memset(cfg->path, 0, 256);
1528 cfg->typeOfAction = 0x00;
1536 =======================================================================================================================
1537 Merging function for configurations
1538 =======================================================================================================================
1540 void *merge_dir_conf(apr_pool_t *pool, void *BASE, void *ADD)
1542 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1543 example_config *base = (example_config *) BASE;
1544 example_config *add = (example_config *) ADD;
1545 example_config *conf = (example_config *) create_dir_conf(pool, "Merged configuration");
1546 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1548 conf->enabled = (add->enabled == 0) ? base->enabled : add->enabled;
1549 conf->typeOfAction = add->typeOfAction ? add->typeOfAction : base->typeOfAction;
1550 strcpy(conf->path, strlen(add->path) ? add->path : base->path);
1554 <!-- END EXAMPLE CODE -->
1562 <section id="summary"><title>Summing up</title>
1564 We have now looked at how to create simple modules for Apache HTTP Server 2.4 and
1565 configuring them. What you do next is entirely up to you, but it is my
1566 hope that something valuable has come out of reading this documentation.
1567 If you have questions on how to further develop modules, you are welcome
1568 to join our <a href="http://httpd.apache.org/lists.html">mailing lists</a>
1569 or check out the rest of our documentation for further tips.
1573 <section id="snippets"><title>Some useful snippets of code</title>
1575 <section id="get_post"><title>Retrieve variables from POST form data</title>
1578 <!-- BEGIN EXAMPLE CODE -->
1579 <highlight language="c">
1585 keyValuePair* readPost(request_req* r) {
1586 apr_array_header_t *pairs = NULL;
1594 res = ap_parse_form_data(r, NULL, &pairs, -1, HUGE_STRING_LEN);
1595 if (res != OK || !pairs) return NULL; /* Return NULL if we failed or if there are is no POST data */
1596 kvp = apr_pcalloc(r->pool, sizeof(keyValuePair) * (pairs->nelts + 1));
1597 while (pairs && !apr_is_empty_array(pairs)) {
1599 ap_form_pair_t *pair = (ap_form_pair_t *) apr_array_pop(pairs);
1600 apr_brigade_length(pair->value, 1, &len);
1601 size = (apr_size_t) len;
1602 buffer = apr_palloc(r->pool, size + 1);
1603 apr_brigade_flatten(pair->value, buffer, &size);
1605 kvp[i]->key = apr_pstrdup(r->pool, pair->name);
1606 kvp[i]->value = buffer;
1611 static int example_handler(request_req *r)
1613 /*~~~~~~~~~~~~~~~~~~~~~~*/
1615 keyValuePair* formData;
1616 /*~~~~~~~~~~~~~~~~~~~~~~*/
1618 formData = readPost();
1621 for (i = 0; formData[i]; i++) {
1622 ap_rprintf(r, "%s == %s\n", formData[i]->key, formData[i]->value);
1628 <!-- END EXAMPLE CODE -->
1633 <section id="headers_out"><title>Printing out every HTTP header received</title>
1636 <!-- BEGIN EXAMPLE CODE -->
1637 <highlight language="c">
1638 static int example_handler(request_req *r)
1640 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1641 const apr_array_header_t *fields;
1643 apr_table_entry_t *e = 0;
1644 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1646 fields = apr_table_elts(r->headers_in);
1647 e = (apr_table_entry_t *) fields->elts;
1648 for(i = 0; i < fields->nelts; i++) {
1649 ap_rprintf(r, "<b>%s</b>: %s<br/>", e[i].key, e[i].val);
1654 <!-- END EXAMPLE CODE -->
1659 <section id="request_body"><title>Reading the request body into memory</title>
1662 <!-- BEGIN EXAMPLE CODE -->
1663 <highlight language="c">
1664 static int util_read(request_rec *r, const char **rbuf, apr_off_t *size)
1670 if((rc = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) {
1674 if(ap_should_client_block(r)) {
1676 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1677 char argsbuffer[HUGE_STRING_LEN];
1678 apr_off_t rsize, len_read, rpos = 0;
1679 apr_off_t length = r->remaining;
1680 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1682 *rbuf = (const char *) apr_pcalloc(r->pool, (apr_size_t) (length + 1));
1684 while((len_read = ap_get_client_block(r, argsbuffer, sizeof(argsbuffer))) > 0) {
1685 if((rpos + len_read) > length) {
1686 rsize = length - rpos;
1692 memcpy((char *) *rbuf + rpos, argsbuffer, (size_t) rsize);
1699 static int example_handler(request_req* r)
1701 /*~~~~~~~~~~~~~~~~*/
1704 /*~~~~~~~~~~~~~~~~*/
1706 if(util_read(r, &data, &size) == OK) {
1707 ap_rprintf("We read a request body that was %u bytes long", size);
1713 <!-- END EXAMPLE CODE -->