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