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