]> granicus.if.org Git - apache/blob - docs/manual/developer/modguide.html.en
91fffe1cb9b36846c8f4bf0a8c02935ff57f6865
[apache] / docs / manual / developer / modguide.html.en
1 <?xml version="1.0" encoding="ISO-8859-1"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head><!--
4         XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5               This file is generated from xml source: DO NOT EDIT
6         XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7       -->
8 <title>Developing modules for the Apache HTTP Server 2.4 - Apache HTTP Server</title>
9 <link href="../style/css/manual.css" rel="stylesheet" media="all" type="text/css" title="Main stylesheet" />
10 <link href="../style/css/manual-loose-100pc.css" rel="alternate stylesheet" media="all" type="text/css" title="No Sidebar - Default font size" />
11 <link href="../style/css/manual-print.css" rel="stylesheet" media="print" type="text/css" /><link rel="stylesheet" type="text/css" href="../style/css/prettify.css" />
12 <script src="../style/scripts/prettify.js" type="text/javascript">
13 </script>
14
15 <link href="../images/favicon.ico" rel="shortcut icon" /></head>
16 <body id="manual-page"><div id="page-header">
17 <p class="menu"><a href="../mod/">Modules</a> | <a href="../mod/directives.html">Directives</a> | <a href="http://wiki.apache.org/httpd/FAQ">FAQ</a> | <a href="../glossary.html">Glossary</a> | <a href="../sitemap.html">Sitemap</a></p>
18 <p class="apache">Apache HTTP Server Version 2.5</p>
19 <img alt="" src="../images/feather.gif" /></div>
20 <div class="up"><a href="./"><img title="&lt;-" alt="&lt;-" src="../images/left.gif" /></a></div>
21 <div id="path">
22 <a href="http://www.apache.org/">Apache</a> &gt; <a href="http://httpd.apache.org/">HTTP Server</a> &gt; <a href="http://httpd.apache.org/docs/">Documentation</a> &gt; <a href="../">Version 2.5</a> &gt; <a href="./">Developer</a></div><div id="page-content"><div id="preamble"><h1>Developing modules for the Apache HTTP Server 2.4</h1>
23 <div class="toplang">
24 <p><span>Available Languages: </span><a href="../en/developer/modguide.html" title="English">&nbsp;en&nbsp;</a></p>
25 </div>
26
27 <p>This document explains how you can develop modules for the Apache HTTP 
28 Server 2.4</p>
29 </div>
30 <div id="quickview"><ul id="toc"><li><img alt="" src="../images/down.gif" /> <a href="#introduction">Introduction</a></li>
31 <li><img alt="" src="../images/down.gif" /> <a href="#basics">Defining a module</a></li>
32 <li><img alt="" src="../images/down.gif" /> <a href="#hooking">Getting started: Hooking into the server</a></li>
33 <li><img alt="" src="../images/down.gif" /> <a href="#handling">Building a handler</a></li>
34 <li><img alt="" src="../images/down.gif" /> <a href="#configuration">Adding configuration options</a></li>
35 <li><img alt="" src="../images/down.gif" /> <a href="#context">Context aware configurations</a></li>
36 <li><img alt="" src="../images/down.gif" /> <a href="#summary">Summing up</a></li>
37 <li><img alt="" src="../images/down.gif" /> <a href="#snippets">Some useful snippets of code</a></li>
38 </ul><h3>See also</h3><ul class="seealso"><li><a href="request.html">Request Processing in Apache 2.4</a></li><li><a href="hooks.html">Apache 2.x Hook Functions</a></li></ul><ul class="seealso"><li><a href="#comments_section">Comments</a></li></ul></div>
39 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
40 <div class="section">
41 <h2><a name="introduction" id="introduction">Introduction</a></h2>
42 <h3><a name="what" id="what">What we will be discussing in this document</a></h3>
43 <p>
44 This document will discuss how you can create modules for the Apache 
45 HTTP Server 2.4, by exploring an example module called 
46 <code>mod_example</code>. In the first part of this document, the purpose 
47 of this module will be to calculate and print out various digest values for 
48 existing files on your web server, whenever we access the URL <code>
49 http://hostname/filename.sum</code>. For instance, if we want to know the 
50 MD5 digest value of the file located at <code>
51 http://www.example.com/index.html</code>, we would visit <code>
52 http://www.example.com/index.html.sum</code>. 
53 </p>
54
55 <p>
56 In the second part of this document, which deals with configuration 
57 directive and context awareness, we will be looking at a module that simply 
58 write out its own configuration to the client.
59 </p>
60
61
62 <h3><a name="prerequisites" id="prerequisites">Prerequisites</a></h3>
63 <p>
64 First and foremost, you are expected to have a basic knowledge of how the C 
65 programming language works. In most cases, we will try to be as pedagogical 
66 as possible and link to documents describing the functions used in the 
67 examples, but there are also many cases where it is necessary to either 
68 just assume that "it works" or do some digging yourself into what the hows 
69 and whys of various function calls. 
70 </p>
71 <p>
72 Lastly, you will need to have a basic understanding of how modules are 
73 loaded and configured in the Apache HTTP Server, as well as how to get the headers for 
74 Apache if you do not have them already, as these are needed for compiling 
75 new modules.
76 </p>
77
78 <h3><a name="compiling" id="compiling">Compiling your module</a></h3>
79 <p>
80 To compile the source code we are building in this document, we will be 
81 using <a href="../programs/apxs.html">APXS</a>. Assuming your source file 
82 is called mod_example.c, compiling, installing and activating the module is 
83 as simple as: 
84 </p>
85 <div class="example"><pre>
86 apxs -i -a -c mod_example.c
87 </pre></div>
88
89
90 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
91 <div class="section">
92 <h2><a name="basics" id="basics">Defining a module</a></h2>
93 <p>
94 <img src="../images/build_a_mod_3.png" alt="Module name tags" /><br />
95 Every module starts with the same declaration, or name tag if you will, 
96 that defines a module as <em>a separate entity within Apache</em>:</p>
97
98
99
100 <pre class="prettyprint lang-c">
101 module AP_MODULE_DECLARE_DATA   example_module =
102
103     STANDARD20_MODULE_STUFF,
104     create_dir_conf, /* Per-directory configuration handler */
105     merge_dir_conf,  /* Merge handler for per-directory configurations */
106     create_svr_conf, /* Per-server configuration handler */
107     merge_svr_conf,  /* Merge handler for per-server configurations */
108     directives,      /* Any directives we may have for httpd */
109     register_hooks   /* Our hook registering function */
110 };
111 </pre>
112
113
114
115 <p>
116 This bit of code lets the server know that we have now registered a new module 
117 in the system, and that its name is <code>example_module</code>. The name 
118 of the module is used primarily for two things:<br />
119 </p>
120 <ul>
121 <li>Letting the server know how to load the module using the LoadModule</li>
122 <li>Setting up a namespace for the module to use in configurations</li>
123 </ul>
124 <p>
125 For now, we're only concerned with the first purpose of the module name, 
126 which comes into play when we need to load the module:
127 </p>
128 <pre class="prettyprint lang-config">
129 LoadModule example_module modules/mod_example.so
130 </pre>
131
132 <p>
133 In essence, this tells the server to open up <code>mod_example.so</code> and look for a module 
134 called <code>example_module</code>.
135 </p>
136 <p>
137 Within this name tag of ours is also a bunch of references to how we would 
138 like to handle things: Which directives do we respond to in a configuration 
139 file or .htaccess, how do we operate within specific contexts, and what 
140 handlers are we interested in registering with the Apache HTTP service. We'll 
141 return to all these elements later in this document.
142 </p>
143 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
144 <div class="section">
145 <h2><a name="hooking" id="hooking">Getting started: Hooking into the server</a></h2>
146 <h3><a name="hook_intro" id="hook_intro">An introduction to hooks</a></h3>
147 <p>
148 When handling requests in Apache HTTP Server 2.4, the first thing you will need to do is 
149 create a hook into the request handling process. A hook is essentially a 
150 message telling the server that you are willing to either serve or at least 
151 take a glance at certain requests given by clients. All handlers, whether 
152 it's mod_rewrite, mod_authn_*, mod_proxy and so on, are hooked into 
153 specific parts of the request process. As you are probably aware, modules 
154 serve different purposes; Some are authentication/authorization handlers, 
155 others are file or script handlers while some third modules rewrite URIs or 
156 proxies content. Furthermore, in the end, it is up to the user of the server 
157 how and when each module will come into place. Thus, the server itself does not 
158 presume to know which module is responsible for handling a specific 
159 request, and will ask each module whether they have an interest in a given 
160 request or not. It is then up to each module to either gently decline 
161 serving a request, accept serving it or flat out deny the request from 
162 being served, as authentication/authorization modules do: <br />
163 <img src="../images/build_a_mod_2.png" alt="Hook handling in httpd" /><br />
164 To make it a bit easier for handlers such as our mod_example to know 
165 whether the client is requesting content we should handle or not, the server 
166 has directives for hinting to modules whether their assistance is needed or 
167 not. Two of these are <code class="directive"><a href="../mod/mod_mime.html#addhandler">AddHandler</a></code> 
168 and <code class="directive"><a href="../mod/core.html#sethandler">SetHandler</a></code>. Let's take a look at 
169 an example using <code class="directive"><a href="../mod/mod_mime.html#addhandler">AddHandler</a></code>. In 
170 our example case, we want every request ending with .sum to be served by 
171 <code>mod_example</code>, so we'll add a configuration directive that tells 
172 the server to do just that:
173 </p>
174 <pre class="prettyprint lang-config">
175 AddHandler example-handler .sum
176 </pre>
177
178 <p>
179 What this tells the server is the following: <em>Whenever we receive a request 
180 for a URI ending in .sum, we are to let all modules know that we are 
181 looking for whoever goes by the name of "example-handler" </em>. 
182 Thus, when a request is being served that ends in .sum, the server will let all 
183 modules know, that this request should be served by "example-handler
184 ". As you will see later, when we start building mod_example, we will 
185 check for this handler tag relayed by <code>AddHandler</code> and reply to 
186 the server based on the value of this tag.
187 </p>
188
189 <h3><a name="hook_declaration" id="hook_declaration">Hooking into httpd</a></h3>
190 <p>
191 To begin with, we only want to create a simple handler, that replies to the 
192 client browser when a specific URL is requested, so we won't bother setting 
193 up configuration handlers and directives just yet. Our initial module 
194 definition will look like this:</p>
195
196
197
198 <pre class="prettyprint lang-c">
199 module AP_MODULE_DECLARE_DATA   example_module =
200 {
201     STANDARD20_MODULE_STUFF,
202     NULL,
203     NULL,
204     NULL,
205     NULL,
206     NULL,
207     register_hooks   /* Our hook registering function */
208 };
209 </pre>
210
211
212
213
214 <p>This lets the server know that we are not interesting in anything fancy, we 
215 just want to hook onto the requests and possibly handle some of them. </p> 
216
217 <p> The reference in our example declaration, <code>register_hooks</code> 
218 is the name of a function we will create to manage how we hook onto the 
219 request process. In this example module, the function has just one purpose; 
220 To create a simple hook that gets called after all the rewrites, access 
221 control etc has been handled. Thus, we will let the server know, that we want 
222 to hook into its process as one of the last modules: 
223 </p>
224
225
226 <pre class="prettyprint lang-c">
227 static void register_hooks(apr_pool_t *pool)
228 {
229     /* Create a hook in the request handler, so we get called when a request arrives */
230     ap_hook_handler(example_handler, NULL, NULL, APR_HOOK_LAST);
231 }
232 </pre>
233
234
235
236 <p>
237 The <code>example_handler</code> reference is the function that will handle 
238 the request. We will discuss how to create a handler in the next chapter.
239 </p>
240
241 <h3><a name="hook_others" id="hook_others">Other useful hooks</a></h3>
242 <p>
243 Hooking into the request handling phase is but one of many hooks that you 
244 can create. Some other ways of hooking are:
245 </p>
246 <ul>
247 <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>
248 <li><code>ap_hook_pre_config</code>: Place a hook that executes before any configuration data has been read (very early hook)</li>
249 <li><code>ap_hook_post_config</code>: Place a hook that executes after configuration has been parsed, but before the server has forked</li>
250 <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>
251 <li><code>ap_hook_quick_handler</code>: Similar to <code>ap_hook_handler</code>, except it is run before any other request hooks (translation, auth, fixups etc)</li>
252 <li><code>ap_hook_log_transaction</code>: Place a hook that executes when the server is about to add a log entry of the current request</li>
253 </ul>
254
255
256 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
257 <div class="section">
258 <h2><a name="handling" id="handling">Building a handler</a></h2>
259 <p>
260 A handler is essentially a function that receives a callback when a request 
261 to the server is made. It is passed a record of the current request (how it was 
262 made, which headers and requests were passed along, who's giving the 
263 request and so on), and is put in charge of either telling the server that it's 
264 not interested in the request or handle the request with the tools provided.
265 </p>
266 <h3><a name="simple_handler" id="simple_handler">A simple "Hello, world!" 
267 handler</a></h3> 
268 <p>Let's start off by making a very simple request handler 
269 that does the following:
270 </p>
271 <ol>
272 <li>Check that this is a request that should be served by "example-handler"</li>
273 <li>Set the content type of our output to <code>text/html</code></li>
274 <li>Write "Hello, world!" back to the client browser</li>
275 <li>Let the server know that we took care of this request and everything went fine</li>
276 </ol>
277 <p>
278 In C code, our example handler will now look like this:
279 </p>
280
281
282 <pre class="prettyprint lang-c">
283 static int example_handler(request_rec *r)
284 {
285     /* First off, we need to check if this is a call for the "example-handler" handler.
286      * If it is, we accept it and do our things, if not, we simply return DECLINED,
287      * and the server will try somewhere else.
288      */
289     if (!r-&gt;handler || strcmp(r-&gt;handler, "example-handler")) return (DECLINED);
290     
291     /* Now that we are handling this request, we'll write out "Hello, world!" to the client.
292      * To do so, we must first set the appropriate content type, followed by our output.
293      */
294     ap_set_content_type(r, "text/html");
295     ap_rprintf(r, "Hello, world!");
296     
297     /* Lastly, we must tell the server that we took care of this request and everything went fine.
298      * We do so by simply returning the value OK to the server.
299      */
300     return OK;
301 }
302 </pre>
303
304
305
306 <p>
307 Now, we put all we have learned together and end up with a program that 
308 looks like 
309 <a href="http://people.apache.org/~humbedooh/mods/examples/mod_example_1.c">mod_example_1.c</a>
310 . The functions used in this example will be explained later in the section 
311 <a href="#functions">"Some useful functions you should know"</a>. 
312 </p>
313  
314 <h3><a name="request_rec" id="request_rec">The request_rec structure</a></h3> 
315 <p>The most essential part of any request is the <em>request record
316 </em>. In a call to a handler function, this is represented by the <code>
317 request_req* </code> structure passed along with every call that is made. 
318 This struct, typically just refered to as <code>r</code> in modules, 
319 contains all the information you need for your module to fully process any 
320 HTTP request and respond accordingly.</p> <p>Some key elements of the <code>
321 request_req </code> structure are:
322 </p>
323 <ul>
324 <li><code>r-&gt;handler (char*):</code> Contains the name of the handler the server is currently asking to do the handling of this request</li>
325 <li><code>r-&gt;method (char*):</code> Contains the HTTP method being used, f.x. GET or POST</li>
326 <li><code>r-&gt;filename (char*):</code> Contains the translated filename the client is requesting</li>
327 <li><code>r-&gt;args (char*):</code> Contains the query string of the request, if any</li>
328 <li><code>r-&gt;headers_in (apr_table_t*):</code> Contains all the headers sent by the client</li>
329 <li><code>r-&gt;connection (conn_rec*):</code> A record containing information about the current connection</li>
330 <li><code>r-&gt;user (char*):</code> If the URI requires authentication, this is set to the username provided</li>
331 <li><code>r-&gt;useragent_ip (char*):</code> The IP address of the client connecting to us</li>
332 <li><code>r-&gt;pool (apr_pool_t*)</code>: The memory pool of this request. We'll discuss this in the 
333 "<a href="#memory">Memory management</a>" chapter.</li>
334 </ul>
335 <p>
336 A complete list of all the values contained with in the <code>request_req</code> structure can be found in 
337 the <a href="http://svn.apache.org/repos/asf/httpd/httpd/trunk/include/httpd.h"><code>httpd.h</code></a> header 
338 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>.
339 </p>
340
341
342 <p>
343 Let's try out some of these variables in another example handler:<br />
344 </p>
345
346
347 <pre class="prettyprint lang-c">
348 static int example_handler(request_rec *r)
349 {
350     /* Set the appropriate content type */
351     ap_set_content_type(r, "text/html");
352
353     /* Print out the IP address of the client connecting to us: */
354     ap_rprintf(r, "&lt;h2&gt;Hello, %s!&lt;/h2&gt;", r-&gt;useragent_ip);
355     
356     /* If we were reached through a GET or a POST request, be happy, else sad. */
357     if ( !strcmp(r-&gt;method, "POST") || !strcmp(r-&gt;method, "GET") ) {
358         ap_rputs("You used a GET or a POST method, that makes us happy!&lt;br/&gt;", r);
359     }
360     else {
361         ap_rputs("You did not use POST or GET, that makes us sad :(&lt;br/&gt;", r);
362     }
363
364     /* Lastly, if there was a query string, let's print that too! */
365     if (r-&gt;args) {
366         ap_rprintf(r, "Your query string was: %s", r-&gt;args);
367     }
368     return OK;
369 }
370 </pre>
371
372
373
374
375
376 <h3><a name="return_value" id="return_value">Return values</a></h3>
377 <p>
378 Apache relies on return values from handlers to signify whether a request 
379 was handled or not, and if so, whether the request went well or not. If a 
380 module is not interested in handling a specific request, it should always 
381 return the value <code>DECLINED</code>. If it is handling a request, it 
382 should either return the generic value <code>OK</code>, or a specific HTTP 
383 status code, for example:
384 </p>
385
386
387 <pre class="prettyprint lang-c">
388 static int example_handler(request_rec *r)
389 {
390     /* Return 404: Not found */
391     return HTTP_NOT_FOUND;
392 }
393 </pre>
394
395
396
397 <p>
398 Returning <code>OK</code> or a HTTP status code does not necessarily mean 
399 that the request will end. The server may still have other handlers that are 
400 interested in this request, for instance the logging modules which, upon a 
401 successful request, will write down a summary of what was requested and how 
402 it went. To do a full stop and prevent any further processing after your 
403 module is done, you can return the value <code>DONE</code> to let the server 
404 know that it should cease all activity on this request and carry on with 
405 the next, without informing other handlers.
406 <br />
407 <strong>General response codes:</strong>
408 </p>
409 <ul>
410 <li><code>DECLINED</code>: We are not handling this request</li>
411 <li><code>OK</code>: We handled this request and it went well</li>
412 <li><code>DONE</code>: We handled this request and the server should just close this thread without further processing</li>
413 </ul>
414 <p>
415 <strong>HTTP specific return codes (excerpt):</strong>
416 </p>
417 <ul>
418 <li><code>HTTP_OK (200)</code>: Request was okay</li>
419 <li><code>HTTP_MOVED_PERMANENTLY (301)</code>: The resource has moved to a new URL</li>
420 <li><code>HTTP_UNAUTHORIZED (401)</code>: Client is not authorized to visit this page</li>
421 <li><code>HTTP_FORBIDDEN (403)</code>: Permission denied</li>
422 <li><code>HTTP_NOT_FOUND (404)</code>: File not found</li>
423 <li><code>HTTP_INTERNAL_SERVER_ERROR (500)</code>: Internal server error (self explanatory)</li>
424 </ul>
425
426
427 <h3><a name="functions" id="functions">Some useful functions you should know</a></h3>
428
429 <ul>
430 <li>
431     <code>ap_rputs(const char *string, request_req *r)</code>: <br />
432     Sends a string of text to the client. This is a shorthand version of <a href="http://ci.apache.org/projects/httpd/trunk/doxygen/group__APACHE__CORE__PROTO.html#gac827cd0537d2b6213a7c06d7c26cc36e">
433     ap_rwrite</a>.
434     
435
436
437 <pre class="prettyprint lang-c">ap_rputs("Hello, world!", r);</pre>
438
439
440
441
442 </li>
443 <li>
444     <code>
445     <a href="http://ci.apache.org/projects/httpd/trunk/doxygen/group__APACHE__CORE__PROTO.html#ga5e91eb6ca777c9a427b2e82bf1eeb81d">ap_rprintf</a></code>: <br />
446     This function works just like <code>printf</code>, except it sends the result to the client. 
447     
448
449
450 <pre class="prettyprint lang-c">ap_rprintf(r, "Hello, %s!", r-&gt;useragent_ip);</pre>
451
452
453
454 </li>
455 <li>
456     <code>
457     <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 />
458     Sets the content type of the output you are sending.
459     
460
461
462 <pre class="prettyprint lang-c">ap_set_content_type(r, "text/plain"); /* force a raw text output */</pre>
463
464
465
466 </li>
467
468
469 </ul>
470
471
472 <h3><a name="memory" id="memory">Memory management</a></h3>
473 <p>
474 Managing your resources in Apache HTTP Server 2.4 is quite easy, thanks to the memory pool 
475 system. In essence, each server, connection and request have their own 
476 memory pool that gets cleaned up when its scope ends, e.g. when a request 
477 is done or when a server process shuts down. All your module needs to do is 
478 latch onto this memory pool, and you won't have to worry about having to 
479 clean up after yourself - pretty neat, huh?
480 </p>
481
482 <p>
483 In our module, we will primarily be allocating memory for each request, so 
484 it's appropriate to use the <code>r-&gt;pool</code> 
485 reference when creating new objects. A few of the functions for allocating 
486 memory within a pool are:
487 </p>
488 <ul>
489 <li><code>void* <a href="http://apr.apache.org/docs/apr/1.4/group__apr__pools.html#ga85f1e193c31d109affda72f9a92c6915">apr_palloc</a>(
490 apr_pool_t *p, apr_size_t size)</code>: Allocates <code>size</code> number of bytes in the pool for you</li>
491 <li><code>void* <a href="http://apr.apache.org/docs/apr/1.4/group__apr__pools.html#gaf61c098ad258069d64cdf8c0a9369f9e">apr_pcalloc</a>(
492 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>
493 <li><code>char* <a href="http://apr.apache.org/docs/apr/1.4/group__apr__strings.html#gabc79e99ff19abbd7cfd18308c5f85d47">apr_pstrdup</a>(
494 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>
495 <li><code>char* <a href="http://apr.apache.org/docs/apr/1.4/group__apr__strings.html#ga3eca76b8d293c5c3f8021e45eda813d8">apr_psprintf</a>(
496 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>
497 </ul>
498
499 <p>Let's put these functions into an example handler:</p>
500
501
502
503 <pre class="prettyprint lang-c">
504 static int example_handler(request_rec *r)
505 {
506     const char* original = "You can't edit this!";
507     char* copy;
508     int* integers;
509     
510     /* Allocate space for 10 integer values and set them all to zero. */
511     integers = apr_pcalloc(r-&gt;pool, sizeof(int)*10); 
512     
513     /* Create a copy of the 'original' variable that we can edit. */
514     copy = apr_pstrdup(r-&gt;pool, original);
515     return OK;
516 }
517 </pre>
518
519
520
521 <p>
522 This is all well and good for our module, which won't need any 
523 pre-initialized variables or structures. However, if we wanted to 
524 initialize something early on, before the requests come rolling in, we 
525 could simply add a call to a function in our <code>register_hooks</code> 
526 function to sort it out:
527 </p>
528
529
530 <pre class="prettyprint lang-c">
531 static void register_hooks(apr_pool_t *pool)
532 {
533     /* Call a function that initializes some stuff */
534     example_init_function(pool);
535     /* Create a hook in the request handler, so we get called when a request arrives */
536     ap_hook_handler(example_handler, NULL, NULL, APR_HOOK_LAST);
537 }
538 </pre>
539
540
541
542 <p>
543 In this pre-request initialization function we would not be using the 
544 same pool as we did when allocating resources for request-based functions. 
545 Instead, we would use the pool given to us by the server for allocating memory 
546 on a per-process based level.
547 </p>
548
549
550 <h3><a name="parsing" id="parsing">Parsing request data</a></h3>
551 <p>
552 In our example module, we would like to add a feature, that checks which 
553 type of digest, MD5 or SHA1 the client would like to see. This could be 
554 solved by adding a query string to the request. A query string is typically 
555 comprised of several keys and values put together in a string, for instance 
556 <code>valueA=yes&amp;valueB=no&amp;valueC=maybe</code>. It is up to the 
557 module itself to parse these and get the data it requires. In our example, 
558 we'll be looking for a key called <code>digest</code>, and if set to <code>
559 md5</code>, we'll produce an MD5 digest, otherwise we'll produce a SHA1 
560 digest.
561 </p>
562 <p>
563 Since the introduction of Apache HTTP Server 2.4, parsing request data from GET and 
564 POST requests have never been easier. All we require to parse both GET and 
565 POST data is four simple lines:
566 </p> 
567
568
569
570 <pre class="prettyprint lang-c">
571 <a href="http://ci.apache.org/projects/httpd/trunk/doxygen/group__apr__tables.html#gad7ea82d6608a4a633fc3775694ab71e4">apr_table_t</a> *GET; <em>
572 </em><a href="http://ci.apache.org/projects/httpd/trunk/doxygen/structapr__array__header__t.html">apr_array_header_t</a>*POST; 
573 <em>
574 </em>
575 <a href="http://ci.apache.org/projects/httpd/trunk/doxygen/group__APACHE__CORE__SCRIPT.html#gaed25877b529623a4d8f99f819ba1b7bd">
576 ap_args_to_table</a>(r, &amp;GET); <em>
577 </em><a href="http://ci.apache.org/projects/httpd/trunk/doxygen/group__APACHE__CORE__DAEMON.html#ga9d426b6382b49754d4f87c55f65af202">
578 ap_parse_form_data</a>(r, NULL, &amp;POST, -1, 8192); 
579 </pre>
580
581
582
583 <p>
584 In our specific example module, we're looking for the <code>digest</code> 
585 value from the query string, which now resides inside a table called <code>
586 GET</code>. To extract this value, we need only perform a simple operation:
587 </p>
588
589
590
591 <pre class="prettyprint lang-c">
592 /* Get the "digest" key from the query string, if any. */
593 const char *digestType = apr_table_get(GET, "digest");
594
595 /* If no key was returned, we will set a default value instead. */
596 if (!digestType) digestType = "sha1";
597 </pre>
598
599
600
601 <p>
602 The structures used for the POST and GET data are not exactly the same, so 
603 if we were to fetch a value from POST data instead of the query string, we 
604 would have to resort to a few more lines, as outlined in <a href="#get_post">this example</a> in the last chapter of this document.
605 </p>
606
607
608 <h3><a name="advanced_handler" id="advanced_handler">Making an advanced handler</a></h3>
609 <p>
610 Now that we have learned how to parse form data and manage our resources, 
611 we can move on to creating an advanced version of our module, that spits 
612 out the MD5 or SHA1 digest of files:
613 </p>
614
615
616
617 <pre class="prettyprint lang-c">
618 static int example_handler(request_rec *r)
619 {
620     int rc, exists;
621     apr_finfo_t finfo;
622     apr_file_t *file;
623     char *filename;
624     char buffer[256];
625     apr_size_t readBytes;
626     int n;
627     apr_table_t *GET;
628     apr_array_header_t *POST;
629     const char *digestType;
630     
631     
632     /* Check that the "example-handler" handler is being called. */
633     if (!r-&gt;handler || strcmp(r-&gt;handler, "example-handler")) return (DECLINED);
634     
635     /* Figure out which file is being requested by removing the .sum from it */
636     filename = apr_pstrdup(r-&gt;pool, r-&gt;filename);
637     filename[strlen(filename)-4] = 0; /* Cut off the last 4 characters. */
638     
639     /* Figure out if the file we request a sum on exists and isn't a directory */
640     rc = apr_stat(&amp;finfo, filename, APR_FINFO_MIN, r-&gt;pool);
641     if (rc == APR_SUCCESS) {
642         exists =
643         (
644             (finfo.filetype != APR_NOFILE)
645         &amp;&amp;  !(finfo.filetype &amp; APR_DIR)
646         );
647         if (!exists) return HTTP_NOT_FOUND; /* Return a 404 if not found. */
648     }
649     /* If apr_stat failed, we're probably not allowed to check this file. */
650     else return HTTP_FORBIDDEN;
651     
652     /* Parse the GET and, optionally, the POST data sent to us */
653     
654     ap_args_to_table(r, &amp;GET);
655     ap_parse_form_data(r, NULL, &amp;POST, -1, 8192);
656     
657     /* Set the appropriate content type */
658     ap_set_content_type(r, "text/html");
659     
660     /* Print a title and some general information */
661     ap_rprintf(r, "&lt;h2&gt;Information on %s:&lt;/h2&gt;", filename);
662     ap_rprintf(r, "&lt;b&gt;Size:&lt;/b&gt; %u bytes&lt;br/&gt;", finfo.size);
663     
664     /* Get the digest type the client wants to see */
665     digestType = apr_table_get(GET, "digest");
666     if (!digestType) digestType = "MD5";
667     
668     
669     rc = apr_file_open(&amp;file, filename, APR_READ, APR_OS_DEFAULT, r-&gt;pool);
670     if (rc == APR_SUCCESS) {
671         
672         /* Are we trying to calculate the MD5 or the SHA1 digest? */
673         if (!strcasecmp(digestType, "md5")) {
674             /* Calculate the MD5 sum of the file */
675             union {
676                 char      chr[16];
677                 uint32_t  num[4];
678             } digest;
679             apr_md5_ctx_t md5;
680             apr_md5_init(&amp;md5);
681             readBytes = 256;
682             while ( apr_file_read(file, buffer, &amp;readBytes) == APR_SUCCESS ) {
683                 apr_md5_update(&amp;md5, buffer, readBytes);
684             }
685             apr_md5_final(digest.chr, &amp;md5);
686             
687             /* Print out the MD5 digest */
688             ap_rputs("&lt;b&gt;MD5: &lt;/b&gt;&lt;code&gt;", r);
689             for (n = 0; n &lt; APR_MD5_DIGESTSIZE/4; n++) {
690                 ap_rprintf(r, "%08x", digest.num[n]);
691             }
692             ap_rputs("&lt;/code&gt;", r);
693             /* Print a link to the SHA1 version */
694             ap_rputs("&lt;br/&gt;&lt;a href='?digest=sha1'&gt;View the SHA1 hash instead&lt;/a&gt;", r);
695         }
696         else {
697             /* Calculate the SHA1 sum of the file */
698             union {
699                 char      chr[20];
700                 uint32_t  num[5];
701             } digest;
702             apr_sha1_ctx_t sha1;
703             apr_sha1_init(&amp;sha1);
704             readBytes = 256;
705             while ( apr_file_read(file, buffer, &amp;readBytes) == APR_SUCCESS ) {
706                 apr_sha1_update(&amp;sha1, buffer, readBytes);
707             }
708             apr_sha1_final(digest.chr, &amp;sha1);
709             
710             /* Print out the SHA1 digest */
711             ap_rputs("&lt;b&gt;SHA1: &lt;/b&gt;&lt;code&gt;", r);
712             for (n = 0; n &lt; APR_SHA1_DIGESTSIZE/4; n++) {
713                 ap_rprintf(r, "%08x", digest.num[n]);
714             }
715             ap_rputs("&lt;/code&gt;", r);
716             
717             /* Print a link to the MD5 version */
718             ap_rputs("&lt;br/&gt;&lt;a href='?digest=md5'&gt;View the MD5 hash instead&lt;/a&gt;", r);
719         }
720         apr_file_close(file);
721         
722     }    
723     /* Let the server know that we responded to this request. */
724     return OK;
725 }
726 </pre>
727
728
729
730 <p>
731 This version in its entirity can be found here: 
732 <a href="http://people.apache.org/~humbedooh/mods/examples/mod_example_2.c">mod_example_2.c</a>.
733 </p>
734
735
736 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
737 <div class="section">
738 <h2><a name="configuration" id="configuration">Adding configuration options</a></h2>
739 <p>
740 In this next segment of this document, we will turn our eyes away from the 
741 digest module and create a new example module, whose only function is to 
742 write out its own configuration. The purpose of this is to examine how 
743 the server works with configuration, and what happens when you start writing 
744 advanced configurations 
745 for your modules.
746 </p>
747 <h3><a name="config_intro" id="config_intro">An introduction to configuration 
748 directives</a></h3>
749 <p>
750 If you are reading this, then you probably already know 
751 what a configuration directive is. Simply put, a directive is a way of 
752 telling an individual module (or a set of modules) how to behave, such as 
753 these directives control how <code>mod_rewrite</code> works:
754 </p>
755 <pre class="prettyprint lang-config">
756 RewriteEngine On
757 RewriteCond %{REQUEST_URI} ^/foo/bar
758 RewriteRule ^/foo/bar/(.*)$ /foobar?page=$1
759 </pre>
760
761 <p>
762 Each of these configuration directives are handled by a separate function, 
763 that parses the parameters given and sets up a configuration accordingly.
764 </p>
765
766 <h3><a name="config_simple" id="config_simple">Making an example configuration</a></h3>
767 <p>To begin with, we'll create a basic configuration in C-space:</p>
768
769
770
771 <pre class="prettyprint lang-c">
772 typedef struct {
773     int         enabled;      /* Enable or disable our module */
774     const char *path;         /* Some path to...something */
775     int         typeOfAction; /* 1 means action A, 2 means action B and so on */
776 } example_config;
777 </pre>
778
779
780
781 <p>
782 Now, let's put this into perspective by creating a very small module that 
783 just prints out a hard-coded configuration. You'll notice that we use the 
784 <code>register_hooks</code> function for initializing the configuration 
785 values to their defaults:
786 </p>
787
788
789 <pre class="prettyprint lang-c">
790 typedef struct {
791     int         enabled;      /* Enable or disable our module */
792     const char *path;         /* Some path to...something */
793     int         typeOfAction; /* 1 means action A, 2 means action B and so on */
794 } example_config;
795
796 static example_config config;
797
798 static int example_handler(request_rec *r)
799 {
800     if (!r-&gt;handler || strcmp(r-&gt;handler, "example-handler")) return(DECLINED);
801     ap_set_content_type(r, "text/plain");
802     ap_rprintf(r, "Enabled: %u\n", config.enabled);
803     ap_rprintf(r, "Path: %s\n", config.path);
804     ap_rprintf(r, "TypeOfAction: %x\n", config.typeOfAction);
805     return OK;
806 }
807
808 static void register_hooks(apr_pool_t *pool) 
809 {
810     config.enabled = 1;
811     config.path = "/foo/bar";
812     config.typeOfAction = 0x00;
813     ap_hook_handler(example_handler, NULL, NULL, APR_HOOK_LAST);
814 }
815
816 /* Define our module as an entity and assign a function for registering hooks  */
817
818 module AP_MODULE_DECLARE_DATA   example_module =
819 {
820     STANDARD20_MODULE_STUFF,
821     NULL,            /* Per-directory configuration handler */
822     NULL,            /* Merge handler for per-directory configurations */
823     NULL,            /* Per-server configuration handler */
824     NULL,            /* Merge handler for per-server configurations */
825     NULL,            /* Any directives we may have for httpd */
826     register_hooks   /* Our hook registering function */
827 };
828 </pre>
829
830
831
832 <p>
833 So far so good. To access our new handler, we could add the following to 
834 our configuration:
835 </p>
836 <pre class="prettyprint lang-config">
837 &lt;Location /example&gt;
838     SetHandler example-handler
839 &lt;/Location&gt;
840 </pre>
841
842 <p>
843 When we visit, we'll see our current configuration being spit out by our 
844 module. 
845 </p>
846
847
848 <h3><a name="register_directive" id="register_directive">Registering directives with the server</a></h3>
849 <p>
850 What if we want to change our configuration, not by hard-coding new values 
851 into the module, but by using either the httpd.conf file or possibly a 
852 .htaccess file? It's time to let the server know that we want this to be 
853 possible. To do so, we must first change our <em>name tag</em> to include a 
854 reference to the configuration directives we want to register with the server:
855 </p>
856
857
858 <pre class="prettyprint lang-c">
859 module AP_MODULE_DECLARE_DATA   example_module =
860 {
861     STANDARD20_MODULE_STUFF,
862     NULL,               /* Per-directory configuration handler */
863     NULL,               /* Merge handler for per-directory configurations */
864     NULL,               /* Per-server configuration handler */
865     NULL,               /* Merge handler for per-server configurations */
866     example_directives, /* Any directives we may have for httpd */
867     register_hooks      /* Our hook registering function */
868 };
869 </pre>
870
871
872
873 <p>
874 This will tell the server that we are now accepting directives from the 
875 configuration files, and that the structure called <code>example_directives
876 </code> holds information on what our directives are and how they work. 
877 Since we have three different variables in our module configuration, we 
878 will add a structure with three directives and a NULL at the end:
879 </p>
880
881
882 <pre class="prettyprint lang-c">
883 static const command_rec        example_directives[] =
884 {
885     AP_INIT_TAKE1("exampleEnabled", example_set_enabled, NULL, RSRC_CONF, "Enable or disable mod_example"),
886     AP_INIT_TAKE1("examplePath", example_set_path, NULL, RSRC_CONF, "The path to whatever"),
887     AP_INIT_TAKE2("exampleAction", example_set_action, NULL, RSRC_CONF, "Special action value!"),
888     { NULL }
889 };
890 </pre>
891
892
893
894 <p>
895 <img src="../images/build_a_mod_4.png" alt="Directives structure" /><br />
896 As you can see, each directive needs at least 5 parameters set:
897 </p>
898 <ol>
899 <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. 
900 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 
901 for more macros).</li>
902 <li><code>exampleEnabled</code>: This is the name of our directive. More precisely, it is what the user must put in his/her 
903 configuration in order to invoke a configuration change in our module.</li>
904 <li><code>example_set_enabled</code>: This is a reference to a C function that parses the directive and sets the configuration 
905 accordingly. We will discuss how to make this in the following paragraph.</li>
906 <li><code>RSRC_CONF</code>: This tells the server where the directive is permitted. We'll go into details on this value in the 
907 later chapters, but for now, <code>RSRC_CONF</code> means that the server will only accept these directives in a server context.</li>
908 <li><code>"Enable or disable...."</code>: This is simply a brief description of what the directive does.</li>
909 </ol>
910 <p>
911 (<em>The "missing" parameter in our definition, which is usually set to 
912 <code>NULL</code>, is an optional function that can be run after the 
913 initial function to parse the arguments have been run. This is usually 
914 omitted, as the function for verifying arguments might as well be used to 
915 set them.</em>)
916 </p>
917
918 <h3><a name="directive_handler" id="directive_handler">The directive handler function</a></h3>
919 <p>
920 Now that we've told the server to expect some directives for our module, it's 
921 time to make a few functions for handling these. What the server reads in the 
922 configuration file(s) is text, and so naturally, what it passes along to 
923 our directive handler is one or more strings, that we ourselves need to 
924 recognize and act upon. You'll notice, that since we set our <code>
925 exampleAction</code> directive to accept two arguments, its C function also 
926 has an additional parameter defined:</p> 
927
928
929 <pre class="prettyprint lang-c">
930 /* Handler for the "exambleEnabled" directive */
931 const char *example_set_enabled(cmd_parms *cmd, void *cfg, const char *arg)
932 {
933     if(!strcasecmp(arg, "on")) config.enabled = 1;
934     else config.enabled = 0;
935     return NULL;
936 }
937
938 /* Handler for the "examplePath" directive */
939 const char *example_set_path(cmd_parms *cmd, void *cfg, const char *arg)
940 {
941     config.path = arg;
942     return NULL;
943 }
944
945 /* Handler for the "exampleAction" directive */
946 /* Let's pretend this one takes one argument (file or db), and a second (deny or allow), */
947 /* and we store it in a bit-wise manner. */
948 const char *example_set_action(cmd_parms *cmd, void *cfg, const char *arg1, const char* arg2)
949 {
950     if(!strcasecmp(arg1, "file")) config.typeOfAction = 0x01;
951     else config.typeOfAction = 0x02;
952     
953     if(!strcasecmp(arg2, "deny")) config.typeOfAction += 0x10;
954     else config.typeOfAction += 0x20;
955     return NULL;
956 }
957 </pre>
958
959
960
961
962
963 <h3><a name="directive_complete" id="directive_complete">Putting it all together</a></h3>
964 <p>
965 Now that we have our directives set up, and handlers configured for them, 
966 we can assemble our module into one big file:
967 </p>
968
969
970 <pre class="prettyprint lang-c">
971 /* mod_example_config_simple.c: */
972 #include &lt;stdio.h&gt;
973 #include "apr_hash.h"
974 #include "ap_config.h"
975 #include "ap_provider.h"
976 #include "httpd.h"
977 #include "http_core.h"
978 #include "http_config.h"
979 #include "http_log.h"
980 #include "http_protocol.h"
981 #include "http_request.h"
982
983 /*
984  ==============================================================================
985  Our configuration prototype and declaration:
986  ==============================================================================
987  */
988 typedef struct {
989     int         enabled;      /* Enable or disable our module */
990     const char *path;         /* Some path to...something */
991     int         typeOfAction; /* 1 means action A, 2 means action B and so on */
992 } example_config;
993
994 static example_config config;
995
996 /*
997  ==============================================================================
998  Our directive handlers:
999  ==============================================================================
1000  */
1001 /* Handler for the "exambleEnabled" directive */
1002 const char *example_set_enabled(cmd_parms *cmd, void *cfg, const char *arg)
1003 {
1004     if(!strcasecmp(arg, "on")) config.enabled = 1;
1005     else config.enabled = 0;
1006     return NULL;
1007 }
1008
1009 /* Handler for the "examplePath" directive */
1010 const char *example_set_path(cmd_parms *cmd, void *cfg, const char *arg)
1011 {
1012     config.path = arg;
1013     return NULL;
1014 }
1015
1016 /* Handler for the "exampleAction" directive */
1017 /* Let's pretend this one takes one argument (file or db), and a second (deny or allow), */
1018 /* and we store it in a bit-wise manner. */
1019 const char *example_set_action(cmd_parms *cmd, void *cfg, const char *arg1, const char* arg2)
1020 {
1021     if(!strcasecmp(arg1, "file")) config.typeOfAction = 0x01;
1022     else config.typeOfAction = 0x02;
1023     
1024     if(!strcasecmp(arg2, "deny")) config.typeOfAction += 0x10;
1025     else config.typeOfAction += 0x20;
1026     return NULL;
1027 }
1028
1029 /*
1030  ==============================================================================
1031  The directive structure for our name tag:
1032  ==============================================================================
1033  */
1034 static const command_rec        example_directives[] =
1035 {
1036     AP_INIT_TAKE1("exampleEnabled", example_set_enabled, NULL, RSRC_CONF, "Enable or disable mod_example"),
1037     AP_INIT_TAKE1("examplePath", example_set_path, NULL, RSRC_CONF, "The path to whatever"),
1038     AP_INIT_TAKE2("exampleAction", example_set_action, NULL, RSRC_CONF, "Special action value!"),
1039     { NULL }
1040 };
1041 /*
1042  ==============================================================================
1043  Our module handler:
1044  ==============================================================================
1045  */
1046 static int example_handler(request_rec *r)
1047 {
1048     if(!r-&gt;handler || strcmp(r-&gt;handler, "example-handler")) return(DECLINED);
1049     ap_set_content_type(r, "text/plain");
1050     ap_rprintf(r, "Enabled: %u\n", config.enabled);
1051     ap_rprintf(r, "Path: %s\n", config.path);
1052     ap_rprintf(r, "TypeOfAction: %x\n", config.typeOfAction);
1053     return OK;
1054 }
1055
1056 /*
1057  ==============================================================================
1058  The hook registration function (also initializes the default config values):
1059  ==============================================================================
1060  */
1061 static void register_hooks(apr_pool_t *pool) 
1062 {
1063     config.enabled = 1;
1064     config.path = "/foo/bar";
1065     config.typeOfAction = 3;
1066     ap_hook_handler(example_handler, NULL, NULL, APR_HOOK_LAST);
1067 }
1068 /*
1069  ==============================================================================
1070  Our module name tag:
1071  ==============================================================================
1072  */
1073 module AP_MODULE_DECLARE_DATA   example_module =
1074 {
1075     STANDARD20_MODULE_STUFF,
1076     NULL,               /* Per-directory configuration handler */
1077     NULL,               /* Merge handler for per-directory configurations */
1078     NULL,               /* Per-server configuration handler */
1079     NULL,               /* Merge handler for per-server configurations */
1080     example_directives, /* Any directives we may have for httpd */
1081     register_hooks      /* Our hook registering function */
1082 };
1083 </pre>
1084
1085
1086
1087
1088 <p>
1089 In our httpd.conf file, we can now change the hard-coded configuration by 
1090 adding a few lines:
1091 </p>
1092 <pre class="prettyprint lang-config">
1093 ExampleEnabled On
1094 ExamplePath "/usr/bin/foo"
1095 ExampleAction file allow
1096 </pre>
1097
1098 <p>
1099 And thus we apply the configuration, visit <code>/example</code> on our 
1100 web site, and we see the configuration has adapted to what we wrote in our 
1101 configuration file.
1102 </p>
1103
1104
1105
1106 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1107 <div class="section">
1108 <h2><a name="context" id="context">Context aware configurations</a></h2>
1109 <h3><a name="context_intro" id="context_intro">Introduction to context aware configurations</a></h3>
1110 <p>
1111 In Apache HTTP Server 2.4, different URLs, virtual hosts, directories etc can have very 
1112 different meanings to the user of the server, and thus different contexts 
1113 within which modules must operate. For example, let's assume you have this 
1114 configuration set up for mod_rewrite:
1115 </p>
1116 <pre class="prettyprint lang-config">
1117 &lt;Directory "/var/www"&gt;
1118     RewriteCond %{HTTP_HOST} ^example.com$
1119     RewriteRule (.*) http://www.example.com/$1
1120 &lt;/Directory&gt;
1121 &lt;Directory "/var/www/sub"&gt;
1122     RewriteRule ^foobar$ index.php?foobar=true
1123 &lt;/Directory&gt;
1124 </pre>
1125
1126 <p>
1127 In this example, you will have set up two different contexts for 
1128 mod_rewrite:</p>
1129 <ol>
1130 <li>Inside <code>/var/www</code>, all requests for <code>http://example.com</code> must go to <code>http://www.example.com</code></li>
1131 <li>Inside <code>/var/www/sub</code>, all requests for <code>foobar</code> must go to <code>index.php?foobar=true</code></li>
1132 </ol>
1133 <p>
1134 If mod_rewrite (or the entire server for that matter) wasn't context aware, then 
1135 these rewrite rules would just apply to every and any request made, 
1136 regardless of where and how they were made, but since the module can pull 
1137 the context specific configuration straight from the server, it does not need 
1138 to know itself, which of the directives are valid in this context, since 
1139 the server takes care of this.</p>
1140
1141 <p>
1142 So how does a module get the specific configuration for the server, 
1143 directory or location in question? It does so by making one simple call:
1144 </p>
1145
1146
1147 <pre class="prettyprint lang-c">
1148 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-&gt;per_dir_config, &amp;example_module);
1149 </pre>
1150
1151
1152
1153 <p>
1154 That's it! Of course, a whole lot goes on behind the scenes, which we will 
1155 discuss in this chapter, starting with how the server came to know what our 
1156 configuration looks like, and how it came to be set up as it is in the 
1157 specific context.
1158 </p>
1159
1160
1161 <h3><a name="context_base" id="context_base">Our basic configuration setup</a></h3>
1162 <p>In this chapter, we will be working with a slightly modified version of 
1163 our previous context structure. We will set a <code>context</code> 
1164 variable that we can use to track which context configuration is being 
1165 used by the server in various places:
1166 </p>
1167
1168 <pre class="prettyprint lang-c">
1169 typedef struct {
1170     char        context[256];
1171     char        path[256];
1172     int         typeOfAction;
1173     int         enabled;
1174 } example_config;
1175 </pre>
1176
1177
1178
1179 <p>Our handler for requests will also be modified, yet still very simple:</p>
1180
1181
1182
1183 <pre class="prettyprint lang-c">
1184 static int example_handler(request_rec *r)
1185 {
1186     if(!r-&gt;handler || strcmp(r-&gt;handler, "example-handler")) return(DECLINED);
1187     example_config *config = (example_config*) ap_get_module_config(r-&gt;per_dir_config, &amp;example_module);
1188     ap_set_content_type(r, "text/plain");
1189     ap_rprintf("Enabled: %u\n", config-&gt;enabled);
1190     ap_rprintf("Path: %s\n", config-&gt;path);
1191     ap_rprintf("TypeOfAction: %x\n", config-&gt;typeOfAction);
1192     ap_rprintf("Context: %s\n", config-&gt;context);
1193     return OK;
1194 }
1195 </pre>
1196
1197
1198
1199
1200
1201 <h3><a name="context_which" id="context_which">Choosing a context</a></h3>
1202 <p>
1203 Before we can start making our module context aware, we must first define, 
1204 which contexts we will accept. As we saw in the previous chapter, defining 
1205 a directive required five elements be set:</p>
1206
1207
1208
1209 <pre class="prettyprint lang-c">
1210 AP_INIT_TAKE1("exampleEnabled", example_set_enabled, NULL, RSRC_CONF, "Enable or disable mod_example"),
1211 </pre>
1212
1213
1214
1215
1216 <p>The <code>RSRC_CONF</code> definition told the server that we would only allow 
1217 this directive in a global server context, but since we are now trying out 
1218 a context aware version of our module, we should set this to something 
1219 more lenient, namely the value <code>ACCESS_CONF</code>, which lets us use 
1220 the directive inside &lt;Directory&gt; and &lt;Location&gt; blocks.
1221 </p>
1222
1223
1224 <h3><a name="context_pool" id="context_pool">Using the server to allocate configuration slots</a></h3>
1225 <p> A much smarter way to manage your configurations is by letting the server 
1226 help you create them. To do so, we must first start off by changing our 
1227 <em>name tag</em> to let the server know, that it should assist us in creating 
1228 and managing our configurations. Since we have chosen the per-directory 
1229 (or per-location) context for our module configurations, we'll add a 
1230 per-directory creator and merger function reference in our tag:</p>
1231
1232
1233 <pre class="prettyprint lang-c">
1234 module AP_MODULE_DECLARE_DATA   example_module =
1235 {
1236     STANDARD20_MODULE_STUFF,
1237     create_dir_conf, /* Per-directory configuration handler */
1238     merge_dir_conf,  /* Merge handler for per-directory configurations */
1239     NULL,            /* Per-server configuration handler */
1240     NULL,            /* Merge handler for per-server configurations */
1241     directives,      /* Any directives we may have for httpd */
1242     register_hooks   /* Our hook registering function */
1243 };
1244 </pre>
1245
1246
1247
1248
1249
1250
1251
1252 <h3><a name="context_new" id="context_new">Creating new context configurations</a></h3>
1253 <p>
1254 Now that we have told the server to help us create and manage configurations, 
1255 our first step is to make a function for creating new, blank 
1256 configurations. We do so by creating the function we just referenced in 
1257 our name tag as the Per-directory configuration handler:</p>
1258
1259 <pre class="prettyprint lang-c">
1260 void* example_create_dir_conf(apr_pool_t* pool, char* context) {
1261     context = context ? context : "(undefined context)";
1262     example_config *cfg = apr_pcalloc(pool, sizeof(example_config));
1263     if(cfg) {
1264         /* Set some default values */
1265         strcpy(cfg-&gt;context, x);
1266         cfg-&gt;enabled = 0;
1267         cfg-&gt;path = "/foo/bar";
1268         cfg-&gt;typeOfAction = 0x11;
1269     }
1270     return cfg;
1271 }
1272 </pre>
1273
1274
1275
1276
1277
1278
1279 <h3><a name="context_merge" id="context_merge">Merging configurations</a></h3>
1280 <p>
1281 Our next step in creating a context aware configuration is merging 
1282 configurations. This part of the process particularly apply to scenarios 
1283 where you have a parent configuration and a child, such as the following: 
1284 </p>
1285 <pre class="prettyprint lang-config">
1286 &lt;Directory "/var/www"&gt;
1287     ExampleEnable On
1288     ExamplePath /foo/bar
1289     ExampleAction file allow
1290 &lt;/Directory&gt;
1291 &lt;Directory "/var/www/subdir"&gt;
1292     ExampleAction file deny
1293 &lt;/Directory&gt;
1294 </pre>
1295
1296 <p>
1297 In this example, it is natural to assume that the directory <code>
1298 /var/www/subdir</code> should inherit the value set for the <code>/var/www
1299 </code> directory, as we did not specify a <code>ExampleEnable</code> nor 
1300 an <code>ExamplePath</code> for this directory. The server does not presume to 
1301 know if this is true, but cleverly does the following:
1302 </p>
1303 <ol>
1304 <li>Creates a new configuration for <code>/var/www</code></li>
1305 <li>Sets the configuration values according to the directives given for <code>/var/www</code></li>
1306 <li>Creates a new configuration for <code>/var/www/subdir</code></li>
1307 <li>Sets the configuration values according to the directives given for <code>/var/www/subdir</code></li>
1308 <li><strong>Proposes a merge</strong> of the two configurations into a new configuration for <code>/var/www/subdir</code></li>
1309 </ol>
1310 <p>
1311 This proposal is handled by the <code>merge_dir_conf</code> function we 
1312 referenced in our name tag. The purpose of this function is to assess the 
1313 two configurations and decide how they are to be merged:</p>
1314
1315
1316
1317 <pre class="prettyprint lang-c">
1318 void* merge_dir_conf(apr_pool_t* pool, void* BASE, void* ADD) {
1319     example_config* base = (example_config *) BASE ; /* This is what was set in the parent context */
1320     example_config* add = (example_config *) ADD ;   /* This is what is set in the new context */
1321     example_config* conf = (example_config *) create_dir_conf(pool, "Merged configuration"); /* This will be the merged configuration */
1322     
1323     /* Merge configurations */
1324     conf-&gt;enabled = ( add-&gt;enabled == 0 ) ? base-&gt;enabled : add-&gt;enabled ;
1325     conf-&gt;typeOfAction = add-&gt;typeOfAction ? add-&gt;typeOfAction : base-&gt;typeOfAction;
1326     strcpy(conf-&gt;path, strlen(add-&gt;path) ? add-&gt;path : base-&gt;path);
1327     
1328     return conf ;
1329 }
1330 </pre>
1331
1332
1333
1334
1335
1336
1337 <h3><a name="context_example" id="context_example">Trying out our new context aware configurations</a></h3>
1338 <p>
1339 Now, let's try putting it all together to create a new module that is 
1340 context aware. First off, we'll create a configuration that lets us test 
1341 how the module works:
1342 </p>
1343 <pre class="prettyprint lang-config">
1344 &lt;Location "/a"&gt;
1345     SetHandler example-handler
1346     ExampleEnabled on
1347     ExamplePath "/foo/bar"
1348     ExampleAction file allow
1349 &lt;/Location&gt;
1350
1351 &lt;Location "/a/b"&gt;
1352     ExampleAction file deny
1353     ExampleEnabled off
1354 &lt;/Location&gt;
1355
1356 &lt;Location "/a/b/c"&gt;
1357     ExampleAction db deny
1358     ExamplePath "/foo/bar/baz"
1359     ExampleEnabled on
1360 &lt;/Location&gt;
1361 </pre>
1362
1363 <p>
1364 Then we'll assemble our module code. Note, that since we are now using our 
1365 name tag as reference when fetching configurations in our handler, I have 
1366 added some prototypes to keep the compiler happy:
1367 </p>
1368
1369
1370 <pre class="prettyprint lang-c">
1371 /*$6
1372  +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1373  * mod_example_config.c
1374  +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1375  */
1376
1377
1378 #include &lt;stdio.h&gt;
1379 #include "apr_hash.h"
1380 #include "ap_config.h"
1381 #include "ap_provider.h"
1382 #include "httpd.h"
1383 #include "http_core.h"
1384 #include "http_config.h"
1385 #include "http_log.h"
1386 #include "http_protocol.h"
1387 #include "http_request.h"
1388
1389 /*$1
1390  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1391     Configuration structure
1392  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1393  */
1394
1395 typedef struct
1396 {
1397     char    context[256];
1398     char    path[256];
1399     int     typeOfAction;
1400     int     enabled;
1401 } example_config;
1402
1403 /*$1
1404  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1405     Prototypes
1406  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1407  */
1408
1409 static int    example_handler(request_rec *r);
1410 const char    *example_set_enabled(cmd_parms *cmd, void *cfg, const char *arg);
1411 const char    *example_set_path(cmd_parms *cmd, void *cfg, const char *arg);
1412 const char    *example_set_action(cmd_parms *cmd, void *cfg, const char *arg1, const char *arg2);
1413 void          *create_dir_conf(apr_pool_t *pool, char *context);
1414 void          *merge_dir_conf(apr_pool_t *pool, void *BASE, void *ADD);
1415 static void   register_hooks(apr_pool_t *pool);
1416
1417 /*$1
1418  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1419     Configuration directives
1420  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1421  */
1422
1423 static const command_rec    directives[] =
1424 {
1425     AP_INIT_TAKE1("exampleEnabled", example_set_enabled, NULL, ACCESS_CONF, "Enable or disable mod_example"),
1426     AP_INIT_TAKE1("examplePath", example_set_path, NULL, ACCESS_CONF, "The path to whatever"),
1427     AP_INIT_TAKE2("exampleAction", example_set_action, NULL, ACCESS_CONF, "Special action value!"),
1428     { NULL }
1429 };
1430
1431 /*$1
1432  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1433     Our name tag
1434  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1435  */
1436
1437 module AP_MODULE_DECLARE_DATA    example_module =
1438 {
1439     STANDARD20_MODULE_STUFF,
1440     create_dir_conf,    /* Per-directory configuration handler */
1441     merge_dir_conf,     /* Merge handler for per-directory configurations */
1442     NULL,               /* Per-server configuration handler */
1443     NULL,               /* Merge handler for per-server configurations */
1444     directives,         /* Any directives we may have for httpd */
1445     register_hooks      /* Our hook registering function */
1446 };
1447
1448 /*
1449  =======================================================================================================================
1450     Hook registration function
1451  =======================================================================================================================
1452  */
1453 static void register_hooks(apr_pool_t *pool)
1454 {
1455     ap_hook_handler(example_handler, NULL, NULL, APR_HOOK_LAST);
1456 }
1457
1458 /*
1459  =======================================================================================================================
1460     Our example web service handler
1461  =======================================================================================================================
1462  */
1463 static int example_handler(request_rec *r)
1464 {
1465     if(!r-&gt;handler || strcmp(r-&gt;handler, "example-handler")) return(DECLINED);
1466
1467     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1468     example_config    *config = (example_config *) ap_get_module_config(r-&gt;per_dir_config, &amp;example_module);
1469     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1470
1471     ap_set_content_type(r, "text/plain");
1472     ap_rprintf(r, "Enabled: %u\n", config-&gt;enabled);
1473     ap_rprintf(r, "Path: %s\n", config-&gt;path);
1474     ap_rprintf(r, "TypeOfAction: %x\n", config-&gt;typeOfAction);
1475     ap_rprintf(r, "Context: %s\n", config-&gt;context);
1476     return OK;
1477 }
1478
1479 /*
1480  =======================================================================================================================
1481     Handler for the "exambleEnabled" directive
1482  =======================================================================================================================
1483  */
1484 const char *example_set_enabled(cmd_parms *cmd, void *cfg, const char *arg)
1485 {
1486     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1487     example_config    *conf = (example_config *) cfg;
1488     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1489
1490     if(conf)
1491     {
1492         if(!strcasecmp(arg, "on"))
1493             conf-&gt;enabled = 1;
1494         else
1495             conf-&gt;enabled = 0;
1496     }
1497
1498     return NULL;
1499 }
1500
1501 /*
1502  =======================================================================================================================
1503     Handler for the "examplePath" directive
1504  =======================================================================================================================
1505  */
1506 const char *example_set_path(cmd_parms *cmd, void *cfg, const char *arg)
1507 {
1508     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1509     example_config    *conf = (example_config *) cfg;
1510     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1511
1512     if(conf)
1513     {
1514         strcpy(conf-&gt;path, arg);
1515     }
1516
1517     return NULL;
1518 }
1519
1520 /*
1521  =======================================================================================================================
1522     Handler for the "exampleAction" directive ;
1523     Let's pretend this one takes one argument (file or db), and a second (deny or allow), ;
1524     and we store it in a bit-wise manner.
1525  =======================================================================================================================
1526  */
1527 const char *example_set_action(cmd_parms *cmd, void *cfg, const char *arg1, const char *arg2)
1528 {
1529     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1530     example_config    *conf = (example_config *) cfg;
1531     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1532
1533     if(conf)
1534     {
1535         {
1536             if(!strcasecmp(arg1, "file"))
1537                 conf-&gt;typeOfAction = 0x01;
1538             else
1539                 conf-&gt;typeOfAction = 0x02;
1540             if(!strcasecmp(arg2, "deny"))
1541                 conf-&gt;typeOfAction += 0x10;
1542             else
1543                 conf-&gt;typeOfAction += 0x20;
1544         }
1545     }
1546
1547     return NULL;
1548 }
1549
1550 /*
1551  =======================================================================================================================
1552     Function for creating new configurations for per-directory contexts
1553  =======================================================================================================================
1554  */
1555 void *create_dir_conf(apr_pool_t *pool, char *context)
1556 {
1557     context = context ? context : "Newly created configuration";
1558
1559     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1560     example_config    *cfg = apr_pcalloc(pool, sizeof(example_config));
1561     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1562
1563     if(cfg)
1564     {
1565         {
1566             /* Set some default values */
1567             strcpy(cfg-&gt;context, context);
1568             cfg-&gt;enabled = 0;
1569             memset(cfg-&gt;path, 0, 256);
1570             cfg-&gt;typeOfAction = 0x00;
1571         }
1572     }
1573
1574     return cfg;
1575 }
1576
1577 /*
1578  =======================================================================================================================
1579     Merging function for configurations
1580  =======================================================================================================================
1581  */
1582 void *merge_dir_conf(apr_pool_t *pool, void *BASE, void *ADD)
1583 {
1584     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1585     example_config    *base = (example_config *) BASE;
1586     example_config    *add = (example_config *) ADD;
1587     example_config    *conf = (example_config *) create_dir_conf(pool, "Merged configuration");
1588     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1589
1590     conf-&gt;enabled = (add-&gt;enabled == 0) ? base-&gt;enabled : add-&gt;enabled;
1591     conf-&gt;typeOfAction = add-&gt;typeOfAction ? add-&gt;typeOfAction : base-&gt;typeOfAction;
1592     strcpy(conf-&gt;path, strlen(add-&gt;path) ? add-&gt;path : base-&gt;path);
1593     return conf;
1594 }
1595 </pre>
1596
1597
1598
1599
1600
1601
1602
1603 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1604 <div class="section">
1605 <h2><a name="summary" id="summary">Summing up</a></h2>
1606 <p>
1607 We have now looked at how to create simple modules for Apache HTTP Server 2.4 and 
1608 configuring them. What you do next is entirely up to you, but it is my 
1609 hope that something valuable has come out of reading this documentation. 
1610 If you have questions on how to further develop modules, you are welcome 
1611 to join our <a href="http://httpd.apache.org/lists.html">mailing lists</a> 
1612 or check out the rest of our documentation for further tips.
1613 </p>
1614 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1615 <div class="section">
1616 <h2><a name="snippets" id="snippets">Some useful snippets of code</a></h2>
1617
1618 <h3><a name="get_post" id="get_post">Retrieve variables from POST form data</a></h3>
1619
1620
1621
1622 <pre class="prettyprint lang-c">
1623 typedef struct {
1624     const char* key;
1625     const char* value;
1626 } keyValuePair;
1627
1628 keyValuePair* readPost(request_req* r) {
1629     apr_array_header_t *pairs = NULL;
1630     apr_off_t len;
1631     apr_size_t size;
1632     int res;
1633     int i = 0;
1634     char *buffer;
1635     keyValuePair* kvp;
1636
1637     res = ap_parse_form_data(r, NULL, &amp;pairs, -1, HUGE_STRING_LEN);
1638     if (res != OK || !pairs) return NULL; /* Return NULL if we failed or if there are is no POST data */
1639     kvp = apr_pcalloc(r-&gt;pool, sizeof(keyValuePair) * (pairs-&gt;nelts + 1));
1640     while (pairs &amp;&amp; !apr_is_empty_array(pairs)) {
1641         i++;
1642         ap_form_pair_t *pair = (ap_form_pair_t *) apr_array_pop(pairs);
1643         apr_brigade_length(pair-&gt;value, 1, &amp;len);
1644         size = (apr_size_t) len;
1645         buffer = apr_palloc(r-&gt;pool, size + 1);
1646         apr_brigade_flatten(pair-&gt;value, buffer, &amp;size);
1647         buffer[len] = 0;
1648         kvp[i]-&gt;key = apr_pstrdup(r-&gt;pool, pair-&gt;name);
1649         kvp[i]-&gt;value = buffer;
1650     }
1651     return kvp;    
1652 }
1653
1654 static int example_handler(request_req *r) 
1655 {
1656     /*~~~~~~~~~~~~~~~~~~~~~~*/
1657     
1658     keyValuePair* formData;
1659     /*~~~~~~~~~~~~~~~~~~~~~~*/
1660
1661     formData = readPost();
1662     if (formData) {
1663         int i;
1664         for (i = 0; formData[i]; i++) {
1665             ap_rprintf(r, "%s = %s\n", formData[i]-&gt;key, formData[i]-&gt;value);
1666         }
1667     }
1668     return OK;
1669 }
1670 </pre>
1671
1672
1673
1674
1675     
1676     
1677     <h3><a name="headers_out" id="headers_out">Printing out every HTTP header received</a></h3>
1678     
1679
1680
1681 <pre class="prettyprint lang-c">
1682 static int example_handler(request_req *r) 
1683 {
1684     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1685     const apr_array_header_t    *fields;
1686     int                         i;
1687     apr_table_entry_t           *e = 0;
1688     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1689
1690     fields = apr_table_elts(r-&gt;headers_in);
1691     e = (apr_table_entry_t *) fields-&gt;elts;
1692     for(i = 0; i &lt; fields-&gt;nelts; i++) {
1693         ap_rprintf(r, "&lt;b&gt;%s&lt;/b&gt;: %s&lt;br/&gt;", e[i].key, e[i].val);
1694     }
1695     return OK;
1696 }
1697 </pre>
1698
1699
1700
1701
1702     
1703     
1704     <h3><a name="request_body" id="request_body">Reading the request body into memory</a></h3>
1705     
1706
1707
1708 <pre class="prettyprint lang-c">
1709 static int util_read(request_rec *r, const char **rbuf, apr_off_t *size)
1710 {
1711     /*~~~~~~~~*/
1712     int rc = OK;
1713     /*~~~~~~~~*/
1714
1715     if((rc = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) {
1716         return(rc);
1717     }
1718
1719     if(ap_should_client_block(r)) {
1720
1721         /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1722         char         argsbuffer[HUGE_STRING_LEN];
1723         apr_off_t    rsize, len_read, rpos = 0;
1724         apr_off_t length = r-&gt;remaining;
1725         /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1726
1727         *rbuf = (const char *) apr_pcalloc(r-&gt;pool, (apr_size_t) (length + 1));
1728         *size = length;
1729         while((len_read = ap_get_client_block(r, argsbuffer, sizeof(argsbuffer))) &gt; 0) {
1730             if((rpos + len_read) &gt; length) {
1731                 rsize = length - rpos;
1732             }
1733             else {
1734                 rsize = len_read;
1735             }
1736
1737             memcpy((char *) *rbuf + rpos, argsbuffer, (size_t) rsize);
1738             rpos += rsize;
1739         }
1740     }
1741     return(rc);
1742 }
1743
1744 static int example_handler(request_req* r) 
1745 {
1746     /*~~~~~~~~~~~~~~~~*/
1747     apr_off_t   size;
1748     const char  *buffer;
1749     /*~~~~~~~~~~~~~~~~*/
1750
1751     if(util_read(r, &amp;data, &amp;size) == OK) {
1752         ap_rprintf("We read a request body that was %u bytes long", size);
1753     }
1754     return OK;
1755 }
1756     </pre>
1757
1758
1759
1760
1761
1762     
1763
1764 </div></div>
1765 <div class="bottomlang">
1766 <p><span>Available Languages: </span><a href="../en/developer/modguide.html" title="English">&nbsp;en&nbsp;</a></p>
1767 </div><div class="top"><a href="#page-header"><img src="../images/up.gif" alt="top" /></a></div><div class="section"><h2><a id="comments_section" name="comments_section">Comments</a></h2><div class="warning"><strong>Notice:</strong><br />This is not a Q&amp;A section. Comments placed here should be pointed towards suggestions on improving the documentation or server, and may be removed again by our moderators if they are either implemented or considered invalid/off-topic. Questions on how to manage the Apache HTTP Server should be directed at either our IRC channel, #httpd, on Freenode, or sent to our <a href="http://httpd.apache.org/lists.html">mailing lists</a>.</div>
1768 <script type="text/javascript"><!--//--><![CDATA[//><!--
1769 var comments_shortname = 'httpd';
1770 var comments_identifier = 'http://httpd.apache.org/docs/trunk/developer/modguide.html';
1771 (function(w, d) {
1772     if (w.location.hostname.toLowerCase() == "httpd.apache.org") {
1773         d.write('<div id="comments_thread"><\/div>');
1774         var s = d.createElement('script');
1775         s.type = 'text/javascript';
1776         s.async = true;
1777         s.src = 'https://comments.apache.org/show_comments.lua?site=' + comments_shortname + '&page=' + comments_identifier;
1778         (d.getElementsByTagName('head')[0] || d.getElementsByTagName('body')[0]).appendChild(s);
1779     }
1780     else {
1781         d.write('<div id="comments_thread">Comments are disabled for this page at the moment.<\/div>');
1782     }
1783 })(window, document);
1784 //--><!]]></script></div><div id="footer">
1785 <p class="apache">Copyright 2012 The Apache Software Foundation.<br />Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a>.</p>
1786 <p class="menu"><a href="../mod/">Modules</a> | <a href="../mod/directives.html">Directives</a> | <a href="http://wiki.apache.org/httpd/FAQ">FAQ</a> | <a href="../glossary.html">Glossary</a> | <a href="../sitemap.html">Sitemap</a></p></div><script type="text/javascript"><!--//--><![CDATA[//><!--
1787 if (typeof(prettyPrint) !== 'undefined') {
1788     prettyPrint();
1789 }
1790 //--><!]]></script>
1791 </body></html>