]> granicus.if.org Git - apache/blob - docs/manual/developer/API.xml
fix name of The Apache Software Foundation
[apache] / docs / manual / developer / API.xml
1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE manualpage SYSTEM "../style/manualpage.dtd">
3 <?xml-stylesheet type="text/xsl" href="../style/manual.en.xsl"?>
4
5 <!--
6  Copyright 2003-2004 The Apache Software Foundation
7
8  Licensed under the Apache License, Version 2.0 (the "License");
9  you may not use this file except in compliance with the License.
10  You may obtain a copy of the License at
11
12      http://www.apache.org/licenses/LICENSE-2.0
13
14  Unless required by applicable law or agreed to in writing, software
15  distributed under the License is distributed on an "AS IS" BASIS,
16  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  See the License for the specific language governing permissions and
18  limitations under the License.
19 -->
20
21 <manualpage metafile="API.xml.meta">
22 <parentdocument href="./">Developer Documentation</parentdocument>
23
24 <title>Apache 1.3 API notes</title>
25
26 <summary>
27     <note type="warning"><title>Warning</title>
28       <p>This document has not been updated to take into account changes made
29       in the 2.0 version of the Apache HTTP Server. Some of the information may
30       still be relevant, but please use it with care.</p>
31     </note>
32
33     <p>These are some notes on the Apache API and the data structures you have
34     to deal with, <em>etc.</em> They are not yet nearly complete, but hopefully,
35     they will help you get your bearings. Keep in mind that the API is still
36     subject to change as we gain experience with it. (See the TODO file for
37     what <em>might</em> be coming). However, it will be easy to adapt modules
38     to any changes that are made. (We have more modules to adapt than you
39     do).</p>
40
41     <p>A few notes on general pedagogical style here. In the interest of
42     conciseness, all structure declarations here are incomplete -- the real
43     ones have more slots that I'm not telling you about. For the most part,
44     these are reserved to one component of the server core or another, and
45     should be altered by modules with caution. However, in some cases, they
46     really are things I just haven't gotten around to yet. Welcome to the
47     bleeding edge.</p>
48
49     <p>Finally, here's an outline, to give you some bare idea of what's coming
50     up, and in what order:</p>
51
52     <ul>
53       <li>
54         <a href="#basics">Basic concepts.</a> 
55
56         <ul>
57           <li><a href="#HMR">Handlers, Modules, and
58           Requests</a></li>
59
60           <li><a href="#moduletour">A brief tour of a
61           module</a></li>
62         </ul>
63       </li>
64
65       <li>
66         <a href="#handlers">How handlers work</a> 
67
68         <ul>
69           <li><a href="#req_tour">A brief tour of the
70           <code>request_rec</code></a></li>
71
72           <li><a href="#req_orig">Where request_rec structures come
73           from</a></li>
74
75           <li><a href="#req_return">Handling requests, declining,
76           and returning error codes</a></li>
77
78           <li><a href="#resp_handlers">Special considerations for
79           response handlers</a></li>
80
81           <li><a href="#auth_handlers">Special considerations for
82           authentication handlers</a></li>
83
84           <li><a href="#log_handlers">Special considerations for
85           logging handlers</a></li>
86         </ul>
87       </li>
88
89       <li><a href="#pools">Resource allocation and resource
90       pools</a></li>
91
92       <li>
93         <a href="#config">Configuration, commands and the like</a> 
94
95         <ul>
96           <li><a href="#per-dir">Per-directory configuration
97           structures</a></li>
98
99           <li><a href="#commands">Command handling</a></li>
100
101           <li><a href="#servconf">Side notes --- per-server
102           configuration, virtual servers, <em>etc</em>.</a></li>
103         </ul>
104       </li>
105     </ul>
106 </summary>
107   
108 <section id="basics"><title>Basic concepts</title>
109     <p>We begin with an overview of the basic concepts behind the API, and how
110     they are manifested in the code.</p>
111
112     <section id="HMR"><title>Handlers, Modules, and Requests</title>
113       <p>Apache breaks down request handling into a series of steps, more or
114       less the same way the Netscape server API does (although this API has a
115       few more stages than NetSite does, as hooks for stuff I thought might be
116       useful in the future). These are:</p>
117
118       <ul>
119       <li>URI -&gt; Filename translation</li>
120       <li>Auth ID checking [is the user who they say they are?]</li>
121       <li>Auth access checking [is the user authorized <em>here</em>?]</li>
122       <li>Access checking other than auth</li>
123       <li>Determining MIME type of the object requested</li>
124       <li>`Fixups' -- there aren't any of these yet, but the phase is intended
125       as a hook for possible extensions like <directive module="mod_env"
126       >SetEnv</directive>, which don't really fit well elsewhere.</li>
127       <li>Actually sending a response back to the client.</li>
128       <li>Logging the request</li>
129       </ul>
130
131       <p>These phases are handled by looking at each of a succession of
132       <em>modules</em>, looking to see if each of them has a handler for the
133       phase, and attempting invoking it if so. The handler can typically do one
134       of three things:</p>
135
136       <ul>
137       <li><em>Handle</em> the request, and indicate that it has done so by
138       returning the magic constant <code>OK</code>.</li>
139
140       <li><em>Decline</em> to handle the request, by returning the magic integer
141       constant <code>DECLINED</code>. In this case, the server behaves in all
142       respects as if the handler simply hadn't been there.</li>
143
144       <li>Signal an error, by returning one of the HTTP error codes. This
145       terminates normal handling of the request, although an ErrorDocument may
146       be invoked to try to mop up, and it will be logged in any case.</li>
147       </ul>
148
149       <p>Most phases are terminated by the first module that handles them;
150       however, for logging, `fixups', and non-access authentication checking,
151       all handlers always run (barring an error). Also, the response phase is
152       unique in that modules may declare multiple handlers for it, via a
153       dispatch table keyed on the MIME type of the requested object. Modules may
154       declare a response-phase handler which can handle <em>any</em> request,
155       by giving it the key <code>*/*</code> (<em>i.e.</em>, a wildcard MIME type
156       specification). However, wildcard handlers are only invoked if the server
157       has already tried and failed to find a more specific response handler for
158       the MIME type of the requested object (either none existed, or they all
159       declined).</p>
160
161       <p>The handlers themselves are functions of one argument (a
162       <code>request_rec</code> structure. vide infra), which returns an integer,
163       as above.</p>
164     </section>
165
166     <section id="moduletour"><title>A brief tour of a module</title>
167       <p>At this point, we need to explain the structure of a module. Our
168       candidate will be one of the messier ones, the CGI module -- this handles
169       both CGI scripts and the <directive module="mod_alias"
170       >ScriptAlias</directive> config file command. It's actually a great deal
171       more complicated than most modules, but if we're going to have only one
172       example, it might as well be the one with its fingers in every place.</p>
173
174       <p>Let's begin with handlers. In order to handle the CGI scripts, the
175       module declares a response handler for them. Because of <directive
176       module="mod_alias">ScriptAlias</directive>, it also has handlers for the
177       name translation phase (to recognize <directive module="mod_alias"
178       >ScriptAlias</directive>ed URIs), the type-checking phase (any
179       <directive module="mod_alias">ScriptAlias</directive>ed request is typed
180       as a CGI script).</p>
181
182       <p>The module needs to maintain some per (virtual) server information,
183       namely, the <directive module="mod_alias">ScriptAlias</directive>es in
184       effect; the module structure therefore contains pointers to a functions
185       which builds these structures, and to another which combines two of them
186       (in case the main server and a virtual server both have <directive
187       module="mod_alias">ScriptAlias</directive>es declared).</p>
188
189       <p>Finally, this module contains code to handle the <directive
190       module="mod_alias">ScriptAlias</directive> command itself. This particular
191       module only declares one command, but there could be more, so modules have
192       <em>command tables</em> which declare their commands, and describe where
193       they are permitted, and how they are to be invoked.</p>
194
195       <p>A final note on the declared types of the arguments of some of these
196       commands: a <code>pool</code> is a pointer to a <em>resource pool</em>
197       structure; these are used by the server to keep track of the memory which
198       has been allocated, files opened, <em>etc.</em>, either to service a
199       particular request, or to handle the process of configuring itself. That
200       way, when the request is over (or, for the configuration pool, when the
201       server is restarting), the memory can be freed, and the files closed,
202       <em>en masse</em>, without anyone having to write explicit code to track
203       them all down and dispose of them. Also, a <code>cmd_parms</code>
204       structure contains various information about the config file being read,
205       and other status information, which is sometimes of use to the function
206       which processes a config-file command (such as <directive
207       module="mod_alias">ScriptAlias</directive>). With no further ado, the
208       module itself:</p>
209
210       <example>
211         /* Declarations of handlers. */<br />
212         <br />
213         int translate_scriptalias (request_rec *);<br />
214         int type_scriptalias (request_rec *);<br />
215         int cgi_handler (request_rec *);<br />
216         <br />
217         /* Subsidiary dispatch table for response-phase <br />
218         &nbsp;* handlers, by MIME type */<br />
219         <br />
220         handler_rec cgi_handlers[] = {<br />
221         <indent>
222           { "application/x-httpd-cgi", cgi_handler },<br />
223           { NULL }<br />
224         </indent>
225         };<br />
226         <br />
227         /* Declarations of routines to manipulate the <br />
228         &nbsp;* module's configuration info.  Note that these are<br />
229         &nbsp;* returned, and passed in, as void *'s; the server<br />
230         &nbsp;* core keeps track of them, but it doesn't, and can't,<br />
231         &nbsp;* know their internal structure.<br />
232         &nbsp;*/<br />
233         <br />
234         void *make_cgi_server_config (pool *);<br />
235         void *merge_cgi_server_config (pool *, void *, void *);<br />
236         <br />
237         /* Declarations of routines to handle config-file commands */<br />
238         <br />
239         extern char *script_alias(cmd_parms *, void *per_dir_config, char *fake,
240                                   char *real);<br />
241         <br />
242         command_rec cgi_cmds[] = {<br />
243         <indent>
244           { "ScriptAlias", script_alias, NULL, RSRC_CONF, TAKE2,<br />
245           <indent>"a fakename and a realname"},<br /></indent>
246           { NULL }<br />
247         </indent>
248         };<br />
249         <br />
250         module cgi_module = {
251 <pre>  STANDARD_MODULE_STUFF,
252   NULL,                     /* initializer */
253   NULL,                     /* dir config creator */
254   NULL,                     /* dir merger */
255   make_cgi_server_config,   /* server config */
256   merge_cgi_server_config,  /* merge server config */
257   cgi_cmds,                 /* command table */
258   cgi_handlers,             /* handlers */
259   translate_scriptalias,    /* filename translation */
260   NULL,                     /* check_user_id */
261   NULL,                     /* check auth */
262   NULL,                     /* check access */
263   type_scriptalias,         /* type_checker */
264   NULL,                     /* fixups */
265   NULL,                     /* logger */
266   NULL                      /* header parser */
267 };</pre>
268       </example>
269     </section>
270 </section>
271
272 <section id="handlers"><title>How handlers work</title>
273     <p>The sole argument to handlers is a <code>request_rec</code> structure.
274     This structure describes a particular request which has been made to the
275     server, on behalf of a client. In most cases, each connection to the
276     client generates only one <code>request_rec</code> structure.</p>
277
278     <section id="req_tour"><title>A brief tour of the request_rec</title>
279       <p>The <code>request_rec</code> contains pointers to a resource pool
280       which will be cleared when the server is finished handling the request;
281       to structures containing per-server and per-connection information, and
282       most importantly, information on the request itself.</p>
283
284       <p>The most important such information is a small set of character strings
285       describing attributes of the object being requested, including its URI,
286       filename, content-type and content-encoding (these being filled in by the
287       translation and type-check handlers which handle the request,
288       respectively).</p>
289
290       <p>Other commonly used data items are tables giving the MIME headers on
291       the client's original request, MIME headers to be sent back with the
292       response (which modules can add to at will), and environment variables for
293       any subprocesses which are spawned off in the course of servicing the
294       request. These tables are manipulated using the <code>ap_table_get</code>
295       and <code>ap_table_set</code> routines.</p>
296
297       <note>
298         <p>Note that the <code>Content-type</code> header value <em>cannot</em>
299         be set by module content-handlers using the <code>ap_table_*()</code>
300         routines. Rather, it is set by pointing the <code>content_type</code>
301         field in the <code>request_rec</code> structure to an appropriate
302         string. <em>e.g.</em>,</p>
303         <example>
304           r-&gt;content_type = "text/html";
305         </example>
306       </note>
307
308       <p>Finally, there are pointers to two data structures which, in turn,
309       point to per-module configuration structures. Specifically, these hold
310       pointers to the data structures which the module has built to describe
311       the way it has been configured to operate in a given directory (via
312       <code>.htaccess</code> files or <directive type="section" module="core"
313       >Directory</directive> sections), for private data it has built in the
314       course of servicing the request (so modules' handlers for one phase can
315       pass `notes' to their handlers for other phases). There is another such
316       configuration vector in the <code>server_rec</code> data structure pointed
317       to by the <code>request_rec</code>, which contains per (virtual) server
318       configuration data.</p>
319
320       <p>Here is an abridged declaration, giving the fields most commonly
321       used:</p>
322
323       <example>
324         struct request_rec {<br />
325         <br />
326         pool *pool;<br />
327         conn_rec *connection;<br />
328         server_rec *server;<br />
329         <br />
330         /* What object is being requested */<br />
331         <br />
332         char *uri;<br />
333         char *filename;<br />
334         char *path_info;
335 <pre>char *args;           /* QUERY_ARGS, if any */
336 struct stat finfo;    /* Set by server core;
337                        * st_mode set to zero if no such file */</pre>
338         char *content_type;<br />
339         char *content_encoding;<br />
340         <br />
341         /* MIME header environments, in and out. Also, <br />
342         &nbsp;* an array containing environment variables to<br />
343         &nbsp;* be passed to subprocesses, so people can write<br />
344         &nbsp;* modules to add to that environment.<br />
345         &nbsp;*<br />
346         &nbsp;* The difference between headers_out and <br />
347         &nbsp;* err_headers_out is that the latter are printed <br />
348         &nbsp;* even on error, and persist across internal<br />
349         &nbsp;* redirects (so the headers printed for <br />
350         &nbsp;* <directive module="core">ErrorDocument</directive> handlers will have
351          them).<br />
352         &nbsp;*/<br />
353          <br />
354         table *headers_in;<br />
355         table *headers_out;<br />
356         table *err_headers_out;<br />
357         table *subprocess_env;<br />
358         <br />
359         /* Info about the request itself... */<br />
360         <br />
361 <pre>int header_only;     /* HEAD request, as opposed to GET */
362 char *protocol;      /* Protocol, as given to us, or HTTP/0.9 */
363 char *method;        /* GET, HEAD, POST, <em>etc.</em> */
364 int method_number;   /* M_GET, M_POST, <em>etc.</em> */
365
366 </pre>
367         /* Info for logging */<br />
368         <br />
369         char *the_request;<br />
370         int bytes_sent;<br />
371         <br />
372         /* A flag which modules can set, to indicate that<br />
373         &nbsp;* the data being returned is volatile, and clients<br />
374         &nbsp;* should be told not to cache it.<br />
375         &nbsp;*/<br />
376         <br />
377         int no_cache;<br />
378         <br />
379         /* Various other config info which may change<br />
380         &nbsp;* with .htaccess files<br />
381         &nbsp;* These are config vectors, with one void*<br />
382         &nbsp;* pointer for each module (the thing pointed<br />
383         &nbsp;* to being the module's business).<br />
384         &nbsp;*/<br />
385         <br />
386 <pre>void *per_dir_config;   /* Options set in config files, <em>etc.</em> */
387 void *request_config;   /* Notes on *this* request */</pre>
388         <br />
389         };
390       </example>
391     </section>
392
393     <section id="req_orig"><title>Where request_rec structures come from</title>
394       <p>Most <code>request_rec</code> structures are built by reading an HTTP
395       request from a client, and filling in the fields. However, there are a
396       few exceptions:</p>
397
398       <ul>
399       <li>If the request is to an imagemap, a type map (<em>i.e.</em>, a
400       <code>*.var</code> file), or a CGI script which returned a local
401       `Location:', then the resource which the user requested is going to be
402       ultimately located by some URI other than what the client originally
403       supplied. In this case, the server does an <em>internal redirect</em>,
404       constructing a new <code>request_rec</code> for the new URI, and
405       processing it almost exactly as if the client had requested the new URI
406       directly.</li>
407
408       <li>If some handler signaled an error, and an <code>ErrorDocument</code>
409       is in scope, the same internal redirect machinery comes into play.</li>
410
411       <li><p>Finally, a handler occasionally needs to investigate `what would
412       happen if' some other request were run. For instance, the directory
413       indexing module needs to know what MIME type would be assigned to a
414       request for each directory entry, in order to figure out what icon to
415       use.</p>
416
417       <p>Such handlers can construct a <em>sub-request</em>, using the
418       functions <code>ap_sub_req_lookup_file</code>,
419       <code>ap_sub_req_lookup_uri</code>, and <code>ap_sub_req_method_uri</code>;
420       these construct a new <code>request_rec</code> structure and processes it
421       as you would expect, up to but not including the point of actually sending
422       a response. (These functions skip over the access checks if the
423       sub-request is for a file in the same directory as the original
424       request).</p>
425
426       <p>(Server-side includes work by building sub-requests and then actually
427       invoking the response handler for them, via the function
428       <code>ap_run_sub_req</code>).</p>
429       </li>
430       </ul>
431     </section>
432
433     <section id="req_return"><title>Handling requests, declining, and returning
434     error codes</title>
435       <p>As discussed above, each handler, when invoked to handle a particular
436       <code>request_rec</code>, has to return an <code>int</code> to indicate
437       what happened. That can either be</p>
438
439       <ul>
440       <li><code>OK</code> -- the request was handled successfully. This may or
441       may not terminate the phase.</li>
442
443       <li><code>DECLINED</code> -- no erroneous condition exists, but the module
444       declines to handle the phase; the server tries to find another.</li>
445
446       <li>an HTTP error code, which aborts handling of the request.</li>
447       </ul>
448
449       <p>Note that if the error code returned is <code>REDIRECT</code>, then
450       the module should put a <code>Location</code> in the request's
451       <code>headers_out</code>, to indicate where the client should be
452       redirected <em>to</em>.</p>
453     </section>
454
455     <section id="resp_handlers"><title>Special considerations for response
456     handlers</title>
457       <p>Handlers for most phases do their work by simply setting a few fields
458       in the <code>request_rec</code> structure (or, in the case of access
459       checkers, simply by returning the correct error code). However, response
460       handlers have to actually send a request back to the client.</p>
461
462       <p>They should begin by sending an HTTP response header, using the
463       function <code>ap_send_http_header</code>. (You don't have to do anything
464       special to skip sending the header for HTTP/0.9 requests; the function
465       figures out on its own that it shouldn't do anything). If the request is
466       marked <code>header_only</code>, that's all they should do; they should
467       return after that, without attempting any further output.</p>
468
469       <p>Otherwise, they should produce a request body which responds to the
470       client as appropriate. The primitives for this are <code>ap_rputc</code>
471       and <code>ap_rprintf</code>, for internally generated output, and
472       <code>ap_send_fd</code>, to copy the contents of some <code>FILE *</code>
473       straight to the client.</p>
474
475       <p>At this point, you should more or less understand the following piece
476       of code, which is the handler which handles <code>GET</code> requests
477       which have no more specific handler; it also shows how conditional
478       <code>GET</code>s can be handled, if it's desirable to do so in a
479       particular response handler -- <code>ap_set_last_modified</code> checks
480       against the <code>If-modified-since</code> value supplied by the client,
481       if any, and returns an appropriate code (which will, if nonzero, be
482       USE_LOCAL_COPY). No similar considerations apply for
483       <code>ap_set_content_length</code>, but it returns an error code for
484       symmetry.</p>
485
486       <example>
487         int default_handler (request_rec *r)<br />
488         {<br />
489         <indent>
490           int errstatus;<br />
491           FILE *f;<br />
492           <br />
493           if (r-&gt;method_number != M_GET) return DECLINED;<br />
494           if (r-&gt;finfo.st_mode == 0) return NOT_FOUND;<br />
495           <br />
496           if ((errstatus = ap_set_content_length (r, r-&gt;finfo.st_size))<br />
497           &nbsp;&nbsp;&nbsp;&nbsp;||
498              (errstatus = ap_set_last_modified (r, r-&gt;finfo.st_mtime)))<br />
499           return errstatus;<br />
500           <br />
501           f = fopen (r-&gt;filename, "r");<br />
502           <br />
503           if (f == NULL) {<br />
504           <indent>
505             log_reason("file permissions deny server access", r-&gt;filename, r);<br />
506             return FORBIDDEN;<br />
507           </indent>
508           }<br />
509           <br />
510           register_timeout ("send", r);<br />
511           ap_send_http_header (r);<br />
512           <br />
513           if (!r-&gt;header_only) send_fd (f, r);<br />
514           ap_pfclose (r-&gt;pool, f);<br />
515           return OK;<br />
516         </indent>
517         }
518       </example>
519
520       <p>Finally, if all of this is too much of a challenge, there are a few
521       ways out of it. First off, as shown above, a response handler which has
522       not yet produced any output can simply return an error code, in which
523       case the server will automatically produce an error response. Secondly,
524       it can punt to some other handler by invoking
525       <code>ap_internal_redirect</code>, which is how the internal redirection
526       machinery discussed above is invoked. A response handler which has
527       internally redirected should always return <code>OK</code>.</p>
528
529       <p>(Invoking <code>ap_internal_redirect</code> from handlers which are
530       <em>not</em> response handlers will lead to serious confusion).</p>
531     </section>
532
533     <section id="auth_handlers"><title>Special considerations for authentication
534     handlers</title>
535       <p>Stuff that should be discussed here in detail:</p>
536
537       <ul>
538       <li>Authentication-phase handlers not invoked unless auth is
539       configured for the directory.</li>
540
541       <li>Common auth configuration stored in the core per-dir
542       configuration; it has accessors <code>ap_auth_type</code>,
543       <code>ap_auth_name</code>, and <code>ap_requires</code>.</li>
544
545       <li>Common routines, to handle the protocol end of things, at
546       least for HTTP basic authentication
547       (<code>ap_get_basic_auth_pw</code>, which sets the
548       <code>connection-&gt;user</code> structure field
549       automatically, and <code>ap_note_basic_auth_failure</code>,
550       which arranges for the proper <code>WWW-Authenticate:</code>
551       header to be sent back).</li>
552       </ul>
553     </section>
554
555     <section id="log_handlers"><title>Special considerations for logging
556     handlers</title>
557       <p>When a request has internally redirected, there is the question of
558       what to log. Apache handles this by bundling the entire chain of redirects
559       into a list of <code>request_rec</code> structures which are threaded
560       through the <code>r-&gt;prev</code> and <code>r-&gt;next</code> pointers.
561       The <code>request_rec</code> which is passed to the logging handlers in
562       such cases is the one which was originally built for the initial request
563       from the client; note that the <code>bytes_sent</code> field will only be
564       correct in the last request in the chain (the one for which a response was
565       actually sent).</p>
566     </section>
567 </section>
568
569 <section id="pools"><title>Resource allocation and resource pools</title>
570     <p>One of the problems of writing and designing a server-pool server is
571     that of preventing leakage, that is, allocating resources (memory, open
572     files, <em>etc.</em>), without subsequently releasing them. The resource
573     pool machinery is designed to make it easy to prevent this from happening,
574     by allowing resource to be allocated in such a way that they are
575     <em>automatically</em> released when the server is done with them.</p>
576
577     <p>The way this works is as follows: the memory which is allocated, file
578     opened, <em>etc.</em>, to deal with a particular request are tied to a
579     <em>resource pool</em> which is allocated for the request. The pool is a
580     data structure which itself tracks the resources in question.</p>
581
582     <p>When the request has been processed, the pool is <em>cleared</em>. At
583     that point, all the memory associated with it is released for reuse, all
584     files associated with it are closed, and any other clean-up functions which
585     are associated with the pool are run. When this is over, we can be confident
586     that all the resource tied to the pool have been released, and that none of
587     them have leaked.</p>
588
589     <p>Server restarts, and allocation of memory and resources for per-server
590     configuration, are handled in a similar way. There is a <em>configuration
591     pool</em>, which keeps track of resources which were allocated while reading
592     the server configuration files, and handling the commands therein (for
593     instance, the memory that was allocated for per-server module configuration,
594     log files and other files that were opened, and so forth). When the server
595     restarts, and has to reread the configuration files, the configuration pool
596     is cleared, and so the memory and file descriptors which were taken up by
597     reading them the last time are made available for reuse.</p>
598
599     <p>It should be noted that use of the pool machinery isn't generally
600     obligatory, except for situations like logging handlers, where you really
601     need to register cleanups to make sure that the log file gets closed when
602     the server restarts (this is most easily done by using the function <code><a
603     href="#pool-files">ap_pfopen</a></code>, which also arranges for the
604     underlying file descriptor to be closed before any child processes, such as
605     for CGI scripts, are <code>exec</code>ed), or in case you are using the
606     timeout machinery (which isn't yet even documented here). However, there are
607     two benefits to using it: resources allocated to a pool never leak (even if
608     you allocate a scratch string, and just forget about it); also, for memory
609     allocation, <code>ap_palloc</code> is generally faster than
610     <code>malloc</code>.</p>
611
612     <p>We begin here by describing how memory is allocated to pools, and then
613     discuss how other resources are tracked by the resource pool machinery.</p>
614
615     <section><title>Allocation of memory in pools</title>
616       <p>Memory is allocated to pools by calling the function
617       <code>ap_palloc</code>, which takes two arguments, one being a pointer to
618       a resource pool structure, and the other being the amount of memory to
619       allocate (in <code>char</code>s). Within handlers for handling requests,
620       the most common way of getting a resource pool structure is by looking at
621       the <code>pool</code> slot of the relevant <code>request_rec</code>; hence
622       the repeated appearance of the following idiom in module code:</p>
623
624       <example>
625         int my_handler(request_rec *r)<br />
626         {<br />
627         <indent>
628           struct my_structure *foo;<br />
629           ...<br />
630           <br />
631           foo = (foo *)ap_palloc (r-&gt;pool, sizeof(my_structure));<br />
632         </indent>
633         }
634       </example>
635
636       <p>Note that <em>there is no <code>ap_pfree</code></em> --
637       <code>ap_palloc</code>ed memory is freed only when the associated resource
638       pool is cleared. This means that <code>ap_palloc</code> does not have to
639       do as much accounting as <code>malloc()</code>; all it does in the typical
640       case is to round up the size, bump a pointer, and do a range check.</p>
641
642       <p>(It also raises the possibility that heavy use of
643       <code>ap_palloc</code> could cause a server process to grow excessively
644       large. There are two ways to deal with this, which are dealt with below;
645       briefly, you can use <code>malloc</code>, and try to be sure that all of
646       the memory gets explicitly <code>free</code>d, or you can allocate a
647       sub-pool of the main pool, allocate your memory in the sub-pool, and clear
648       it out periodically. The latter technique is discussed in the section
649       on sub-pools below, and is used in the directory-indexing code, in order
650       to avoid excessive storage allocation when listing directories with
651       thousands of files).</p>
652     </section>
653
654     <section><title>Allocating initialized memory</title>
655       <p>There are functions which allocate initialized memory, and are
656       frequently useful. The function <code>ap_pcalloc</code> has the same
657       interface as <code>ap_palloc</code>, but clears out the memory it
658       allocates before it returns it. The function <code>ap_pstrdup</code>
659       takes a resource pool and a <code>char *</code> as arguments, and
660       allocates memory for a copy of the string the pointer points to, returning
661       a pointer to the copy. Finally <code>ap_pstrcat</code> is a varargs-style
662       function, which takes a pointer to a resource pool, and at least two
663       <code>char *</code> arguments, the last of which must be
664       <code>NULL</code>. It allocates enough memory to fit copies of each of
665       the strings, as a unit; for instance:</p>
666
667       <example>
668         ap_pstrcat (r-&gt;pool, "foo", "/", "bar", NULL);
669       </example>
670
671       <p>returns a pointer to 8 bytes worth of memory, initialized to
672       <code>"foo/bar"</code>.</p>
673     </section>
674
675     <section id="pools-used"><title>Commonly-used pools in the Apache Web
676     server</title>
677       <p>A pool is really defined by its lifetime more than anything else.
678       There are some static pools in http_main which are passed to various
679       non-http_main functions as arguments at opportune times. Here they
680       are:</p>
681
682       <dl>
683       <dt><code>permanent_pool</code></dt>
684       <dd>never passed to anything else, this is the ancestor of all pools</dd>
685
686       <dt><code>pconf</code></dt>
687       <dd>
688         <ul>
689           <li>subpool of permanent_pool</li>
690
691           <li>created at the beginning of a config "cycle"; exists
692           until the server is terminated or restarts; passed to all
693           config-time routines, either via cmd-&gt;pool, or as the
694           "pool *p" argument on those which don't take pools</li>
695
696           <li>passed to the module init() functions</li>
697         </ul>
698       </dd>
699
700       <dt><code>ptemp</code></dt>
701       <dd>
702         <ul>
703           <li>sorry I lie, this pool isn't called this currently in
704           1.3, I renamed it this in my pthreads development. I'm
705           referring to the use of ptrans in the parent... contrast
706           this with the later definition of ptrans in the
707           child.</li>
708
709           <li>subpool of permanent_pool</li>
710
711           <li>created at the beginning of a config "cycle"; exists
712           until the end of config parsing; passed to config-time
713           routines <em>via</em> cmd-&gt;temp_pool. Somewhat of a
714           "bastard child" because it isn't available everywhere.
715           Used for temporary scratch space which may be needed by
716           some config routines but which is deleted at the end of
717           config.</li>
718         </ul>
719       </dd>
720
721       <dt><code>pchild</code></dt>
722       <dd>
723         <ul>
724           <li>subpool of permanent_pool</li>
725
726           <li>created when a child is spawned (or a thread is
727           created); lives until that child (thread) is
728           destroyed</li>
729
730           <li>passed to the module child_init functions</li>
731
732           <li>destruction happens right after the child_exit
733           functions are called... (which may explain why I think
734           child_exit is redundant and unneeded)</li>
735         </ul>
736       </dd>
737
738       <dt><code>ptrans</code></dt>
739       <dd>
740         <ul>
741           <li>should be a subpool of pchild, but currently is a
742           subpool of permanent_pool, see above</li>
743
744           <li>cleared by the child before going into the accept()
745           loop to receive a connection</li>
746
747           <li>used as connection-&gt;pool</li>
748         </ul>
749       </dd>
750
751       <dt><code>r-&gt;pool</code></dt>
752       <dd>
753         <ul>
754           <li>for the main request this is a subpool of
755           connection-&gt;pool; for subrequests it is a subpool of
756           the parent request's pool.</li>
757
758           <li>exists until the end of the request (<em>i.e.</em>,
759           ap_destroy_sub_req, or in child_main after
760           process_request has finished)</li>
761
762           <li>note that r itself is allocated from r-&gt;pool;
763           <em>i.e.</em>, r-&gt;pool is first created and then r is
764           the first thing palloc()d from it</li>
765         </ul>
766       </dd>
767       </dl>
768
769       <p>For almost everything folks do, <code>r-&gt;pool</code> is the pool to
770       use. But you can see how other lifetimes, such as pchild, are useful to
771       some modules... such as modules that need to open a database connection
772       once per child, and wish to clean it up when the child dies.</p>
773
774       <p>You can also see how some bugs have manifested themself, such as
775       setting <code>connection-&gt;user</code> to a value from
776       <code>r-&gt;pool</code> -- in this case connection exists for the
777       lifetime of <code>ptrans</code>, which is longer than
778       <code>r-&gt;pool</code> (especially if <code>r-&gt;pool</code> is a
779       subrequest!). So the correct thing to do is to allocate from
780       <code>connection-&gt;pool</code>.</p>
781
782       <p>And there was another interesting bug in <module>mod_include</module>
783       / <module>mod_cgi</module>. You'll see in those that they do this test
784       to decide if they should use <code>r-&gt;pool</code> or
785       <code>r-&gt;main-&gt;pool</code>. In this case the resource that they are
786       registering for cleanup is a child process. If it were registered in
787       <code>r-&gt;pool</code>, then the code would <code>wait()</code> for the
788       child when the subrequest finishes. With <module>mod_include</module> this
789       could be any old <code>#include</code>, and the delay can be up to 3
790       seconds... and happened quite frequently. Instead the subprocess is
791       registered in <code>r-&gt;main-&gt;pool</code> which causes it to be
792       cleaned up when the entire request is done -- <em>i.e.</em>, after the
793       output has been sent to the client and logging has happened.</p>
794     </section>
795
796     <section id="pool-files"><title>Tracking open files, etc.</title>
797       <p>As indicated above, resource pools are also used to track other sorts
798       of resources besides memory. The most common are open files. The routine
799       which is typically used for this is <code>ap_pfopen</code>, which takes a
800       resource pool and two strings as arguments; the strings are the same as
801       the typical arguments to <code>fopen</code>, <em>e.g.</em>,</p>
802
803       <example>
804         ...<br />
805         FILE *f = ap_pfopen (r-&gt;pool, r-&gt;filename, "r");<br />
806         <br />
807         if (f == NULL) { ... } else { ... }<br />
808       </example>
809
810       <p>There is also a <code>ap_popenf</code> routine, which parallels the
811       lower-level <code>open</code> system call. Both of these routines arrange
812       for the file to be closed when the resource pool in question is
813       cleared.</p>
814
815       <p>Unlike the case for memory, there <em>are</em> functions to close files
816       allocated with <code>ap_pfopen</code>, and <code>ap_popenf</code>, namely
817       <code>ap_pfclose</code> and <code>ap_pclosef</code>. (This is because, on
818       many systems, the number of files which a single process can have open is
819       quite limited). It is important to use these functions to close files
820       allocated with <code>ap_pfopen</code> and <code>ap_popenf</code>, since to
821       do otherwise could cause fatal errors on systems such as Linux, which
822       react badly if the same <code>FILE*</code> is closed more than once.</p>
823
824       <p>(Using the <code>close</code> functions is not mandatory, since the
825       file will eventually be closed regardless, but you should consider it in
826       cases where your module is opening, or could open, a lot of files).</p>
827     </section>
828
829     <section><title>Other sorts of resources -- cleanup functions</title>
830       <p>More text goes here. Describe the the cleanup primitives in terms of
831       which the file stuff is implemented; also, <code>spawn_process</code>.</p>
832
833       <p>Pool cleanups live until <code>clear_pool()</code> is called:
834       <code>clear_pool(a)</code> recursively calls <code>destroy_pool()</code>
835       on all subpools of <code>a</code>; then calls all the cleanups for
836       <code>a</code>; then releases all the memory for <code>a</code>.
837       <code>destroy_pool(a)</code> calls <code>clear_pool(a)</code> and then
838       releases the pool structure itself. <em>i.e.</em>,
839       <code>clear_pool(a)</code> doesn't delete <code>a</code>, it just frees
840       up all the resources and you can start using it again immediately.</p>
841     </section>
842
843     <section><title>Fine control -- creating and dealing with sub-pools, with
844     a note on sub-requests</title>
845       <p>On rare occasions, too-free use of <code>ap_palloc()</code> and the
846       associated primitives may result in undesirably profligate resource
847       allocation. You can deal with such a case by creating a <em>sub-pool</em>,
848       allocating within the sub-pool rather than the main pool, and clearing or
849       destroying the sub-pool, which releases the resources which were
850       associated with it. (This really <em>is</em> a rare situation; the only
851       case in which it comes up in the standard module set is in case of listing
852       directories, and then only with <em>very</em> large directories.
853       Unnecessary use of the primitives discussed here can hair up your code
854       quite a bit, with very little gain).</p>
855
856       <p>The primitive for creating a sub-pool is <code>ap_make_sub_pool</code>,
857       which takes another pool (the parent pool) as an argument. When the main
858       pool is cleared, the sub-pool will be destroyed. The sub-pool may also be
859       cleared or destroyed at any time, by calling the functions
860       <code>ap_clear_pool</code> and <code>ap_destroy_pool</code>, respectively.
861       (The difference is that <code>ap_clear_pool</code> frees resources
862       associated with the pool, while <code>ap_destroy_pool</code> also
863       deallocates the pool itself. In the former case, you can allocate new
864       resources within the pool, and clear it again, and so forth; in the
865       latter case, it is simply gone).</p>
866
867       <p>One final note -- sub-requests have their own resource pools, which are
868       sub-pools of the resource pool for the main request. The polite way to
869       reclaim the resources associated with a sub request which you have
870       allocated (using the <code>ap_sub_req_...</code> functions) is
871       <code>ap_destroy_sub_req</code>, which frees the resource pool. Before
872       calling this function, be sure to copy anything that you care about which
873       might be allocated in the sub-request's resource pool into someplace a
874       little less volatile (for instance, the filename in its
875       <code>request_rec</code> structure).</p>
876
877       <p>(Again, under most circumstances, you shouldn't feel obliged to call
878       this function; only 2K of memory or so are allocated for a typical sub
879       request, and it will be freed anyway when the main request pool is
880       cleared. It is only when you are allocating many, many sub-requests for a
881       single main request that you should seriously consider the
882       <code>ap_destroy_...</code> functions).</p>
883     </section>
884 </section>
885
886 <section id="config"><title>Configuration, commands and the like</title>
887     <p>One of the design goals for this server was to maintain external
888     compatibility with the NCSA 1.3 server --- that is, to read the same
889     configuration files, to process all the directives therein correctly, and
890     in general to be a drop-in replacement for NCSA. On the other hand, another
891     design goal was to move as much of the server's functionality into modules
892     which have as little as possible to do with the monolithic server core. The
893     only way to reconcile these goals is to move the handling of most commands
894     from the central server into the modules.</p>
895
896     <p>However, just giving the modules command tables is not enough to divorce
897     them completely from the server core. The server has to remember the
898     commands in order to act on them later. That involves maintaining data which
899     is private to the modules, and which can be either per-server, or
900     per-directory. Most things are per-directory, including in particular access
901     control and authorization information, but also information on how to
902     determine file types from suffixes, which can be modified by
903     <directive module="mod_mime">AddType</directive> and <directive
904     module="core">DefaultType</directive> directives, and so forth. In general,
905     the governing philosophy is that anything which <em>can</em> be made
906     configurable by directory should be; per-server information is generally
907     used in the standard set of modules for information like
908     <directive module="mod_alias">Alias</directive>es and <directive
909     module="mod_alias">Redirect</directive>s which come into play before the
910     request is tied to a particular place in the underlying file system.</p>
911
912     <p>Another requirement for emulating the NCSA server is being able to handle
913     the per-directory configuration files, generally called
914     <code>.htaccess</code> files, though even in the NCSA server they can
915     contain directives which have nothing at all to do with access control.
916     Accordingly, after URI -&gt; filename translation, but before performing any
917     other phase, the server walks down the directory hierarchy of the underlying
918     filesystem, following the translated pathname, to read any
919     <code>.htaccess</code> files which might be present. The information which
920     is read in then has to be <em>merged</em> with the applicable information
921     from the server's own config files (either from the <directive
922     type="section" module="core">Directory</directive> sections in
923     <code>access.conf</code>, or from defaults in <code>srm.conf</code>, which
924     actually behaves for most purposes almost exactly like <code>&lt;Directory
925     /&gt;</code>).</p>
926
927     <p>Finally, after having served a request which involved reading
928     <code>.htaccess</code> files, we need to discard the storage allocated for
929     handling them. That is solved the same way it is solved wherever else
930     similar problems come up, by tying those structures to the per-transaction
931     resource pool.</p>
932
933     <section id="per-dir"><title>Per-directory configuration structures</title>
934       <p>Let's look out how all of this plays out in <code>mod_mime.c</code>,
935       which defines the file typing handler which emulates the NCSA server's
936       behavior of determining file types from suffixes. What we'll be looking
937       at, here, is the code which implements the <directive module="mod_mime"
938       >AddType</directive> and <directive module="mod_mime"
939       >AddEncoding</directive> commands. These commands can appear in
940       <code>.htaccess</code> files, so they must be handled in the module's
941       private per-directory data, which in fact, consists of two separate
942       tables for MIME types and encoding information, and is declared as
943       follows:</p>
944
945       <example>
946 <pre>typedef struct {
947     table *forced_types;      /* Additional AddTyped stuff */
948     table *encoding_types;    /* Added with AddEncoding... */
949 } mime_dir_config;</pre>
950       </example>
951
952       <p>When the server is reading a configuration file, or <directive
953       type="section" module="core">Directory</directive> section, which includes
954       one of the MIME module's commands, it needs to create a
955       <code>mime_dir_config</code> structure, so those commands have something
956       to act on. It does this by invoking the function it finds in the module's
957       `create per-dir config slot', with two arguments: the name of the
958       directory to which this configuration information applies (or
959       <code>NULL</code> for <code>srm.conf</code>), and a pointer to a
960       resource pool in which the allocation should happen.</p>
961
962       <p>(If we are reading a <code>.htaccess</code> file, that resource pool
963       is the per-request resource pool for the request; otherwise it is a
964       resource pool which is used for configuration data, and cleared on
965       restarts. Either way, it is important for the structure being created to
966       vanish when the pool is cleared, by registering a cleanup on the pool if
967       necessary).</p>
968
969       <p>For the MIME module, the per-dir config creation function just
970       <code>ap_palloc</code>s the structure above, and a creates a couple of
971       tables to fill it. That looks like this:</p>
972
973       <example>
974         void *create_mime_dir_config (pool *p, char *dummy)<br />
975         {<br />
976         <indent>
977           mime_dir_config *new =<br />
978           <indent>
979            (mime_dir_config *) ap_palloc (p, sizeof(mime_dir_config));<br />
980           </indent>
981           <br />
982           new-&gt;forced_types = ap_make_table (p, 4);<br />
983           new-&gt;encoding_types = ap_make_table (p, 4);<br />
984           <br />
985           return new;<br />
986         </indent>
987         }
988       </example>
989
990       <p>Now, suppose we've just read in a <code>.htaccess</code> file. We
991       already have the per-directory configuration structure for the next
992       directory up in the hierarchy. If the <code>.htaccess</code> file we just
993       read in didn't have any <directive module="mod_mime">AddType</directive>
994       or <directive module="mod_mime">AddEncoding</directive> commands, its
995       per-directory config structure for the MIME module is still valid, and we
996       can just use it. Otherwise, we need to merge the two structures
997       somehow.</p>
998
999       <p>To do that, the server invokes the module's per-directory config merge
1000       function, if one is present. That function takes three arguments: the two
1001       structures being merged, and a resource pool in which to allocate the
1002       result. For the MIME module, all that needs to be done is overlay the
1003       tables from the new per-directory config structure with those from the
1004       parent:</p>
1005
1006       <example>
1007         void *merge_mime_dir_configs (pool *p, void *parent_dirv, void *subdirv)<br />
1008         {<br />
1009         <indent>
1010           mime_dir_config *parent_dir = (mime_dir_config *)parent_dirv;<br />
1011           mime_dir_config *subdir = (mime_dir_config *)subdirv;<br />
1012           mime_dir_config *new =<br />
1013           <indent>
1014             (mime_dir_config *)ap_palloc (p, sizeof(mime_dir_config));<br />
1015           </indent>
1016           <br />
1017           new-&gt;forced_types = ap_overlay_tables (p, subdir-&gt;forced_types,<br />
1018           <indent>
1019             parent_dir-&gt;forced_types);<br />
1020           </indent>
1021           new-&gt;encoding_types = ap_overlay_tables (p, subdir-&gt;encoding_types,<br />
1022           <indent>
1023             parent_dir-&gt;encoding_types);<br />
1024           </indent>
1025           <br />
1026           return new;<br />
1027         </indent>
1028         }
1029       </example>
1030
1031       <p>As a note -- if there is no per-directory merge function present, the
1032       server will just use the subdirectory's configuration info, and ignore
1033       the parent's. For some modules, that works just fine (<em>e.g.</em>, for
1034       the includes module, whose per-directory configuration information
1035       consists solely of the state of the <code>XBITHACK</code>), and for those
1036       modules, you can just not declare one, and leave the corresponding
1037       structure slot in the module itself <code>NULL</code>.</p>
1038     </section>
1039
1040     <section id="commands"><title>Command handling</title>
1041       <p>Now that we have these structures, we need to be able to figure out how
1042       to fill them. That involves processing the actual <directive
1043       module="mod_mime">AddType</directive> and <directive module="mod_mime"
1044       >AddEncoding</directive> commands. To find commands, the server looks in
1045       the module's command table. That table contains information on how many
1046       arguments the commands take, and in what formats, where it is permitted,
1047       and so forth. That information is sufficient to allow the server to invoke
1048       most command-handling functions with pre-parsed arguments. Without further
1049       ado, let's look at the <directive module="mod_mime">AddType</directive>
1050       command handler, which looks like this (the <directive module="mod_mime"
1051       >AddEncoding</directive> command looks basically the same, and won't be
1052       shown here):</p>
1053
1054       <example>
1055         char *add_type(cmd_parms *cmd, mime_dir_config *m, char *ct, char *ext)<br />
1056         {<br />
1057         <indent>
1058           if (*ext == '.') ++ext;<br />
1059           ap_table_set (m-&gt;forced_types, ext, ct);<br />
1060           return NULL;<br />
1061         </indent>
1062         }
1063       </example>
1064
1065       <p>This command handler is unusually simple. As you can see, it takes
1066       four arguments, two of which are pre-parsed arguments, the third being the
1067       per-directory configuration structure for the module in question, and the
1068       fourth being a pointer to a <code>cmd_parms</code> structure. That
1069       structure contains a bunch of arguments which are frequently of use to
1070       some, but not all, commands, including a resource pool (from which memory
1071       can be allocated, and to which cleanups should be tied), and the (virtual)
1072       server being configured, from which the module's per-server configuration
1073       data can be obtained if required.</p>
1074
1075       <p>Another way in which this particular command handler is unusually
1076       simple is that there are no error conditions which it can encounter. If
1077       there were, it could return an error message instead of <code>NULL</code>;
1078       this causes an error to be printed out on the server's
1079       <code>stderr</code>, followed by a quick exit, if it is in the main config
1080       files; for a <code>.htaccess</code> file, the syntax error is logged in
1081       the server error log (along with an indication of where it came from), and
1082       the request is bounced with a server error response (HTTP error status,
1083       code 500).</p>
1084
1085       <p>The MIME module's command table has entries for these commands, which
1086       look like this:</p>
1087
1088       <example>
1089         command_rec mime_cmds[] = {<br />
1090         <indent>
1091           { "AddType", add_type, NULL, OR_FILEINFO, TAKE2,<br />
1092           <indent>"a mime type followed by a file extension" },<br /></indent>
1093           { "AddEncoding", add_encoding, NULL, OR_FILEINFO, TAKE2,<br />
1094           <indent>
1095           "an encoding (<em>e.g.</em>, gzip), followed by a file extension" },<br />
1096           </indent>
1097           { NULL }<br />
1098         </indent>
1099         };
1100       </example>
1101
1102       <p>The entries in these tables are:</p>
1103       <ul>
1104       <li>The name of the command</li>
1105       <li>The function which handles it</li>
1106       <li>a <code>(void *)</code> pointer, which is passed in the
1107       <code>cmd_parms</code> structure to the command handler ---
1108       this is useful in case many similar commands are handled by
1109       the same function.</li>
1110
1111       <li>A bit mask indicating where the command may appear. There
1112       are mask bits corresponding to each
1113       <code>AllowOverride</code> option, and an additional mask
1114       bit, <code>RSRC_CONF</code>, indicating that the command may
1115       appear in the server's own config files, but <em>not</em> in
1116       any <code>.htaccess</code> file.</li>
1117
1118       <li>A flag indicating how many arguments the command handler
1119       wants pre-parsed, and how they should be passed in.
1120       <code>TAKE2</code> indicates two pre-parsed arguments. Other
1121       options are <code>TAKE1</code>, which indicates one
1122       pre-parsed argument, <code>FLAG</code>, which indicates that
1123       the argument should be <code>On</code> or <code>Off</code>,
1124       and is passed in as a boolean flag, <code>RAW_ARGS</code>,
1125       which causes the server to give the command the raw, unparsed
1126       arguments (everything but the command name itself). There is
1127       also <code>ITERATE</code>, which means that the handler looks
1128       the same as <code>TAKE1</code>, but that if multiple
1129       arguments are present, it should be called multiple times,
1130       and finally <code>ITERATE2</code>, which indicates that the
1131       command handler looks like a <code>TAKE2</code>, but if more
1132       arguments are present, then it should be called multiple
1133       times, holding the first argument constant.</li>
1134
1135       <li>Finally, we have a string which describes the arguments
1136       that should be present. If the arguments in the actual config
1137       file are not as required, this string will be used to help
1138       give a more specific error message. (You can safely leave
1139       this <code>NULL</code>).</li>
1140       </ul>
1141
1142       <p>Finally, having set this all up, we have to use it. This is ultimately
1143       done in the module's handlers, specifically for its file-typing handler,
1144       which looks more or less like this; note that the per-directory
1145       configuration structure is extracted from the <code>request_rec</code>'s
1146       per-directory configuration vector by using the
1147       <code>ap_get_module_config</code> function.</p>
1148
1149       <example>
1150         int find_ct(request_rec *r)<br />
1151         {<br />
1152         <indent>
1153           int i;<br />
1154           char *fn = ap_pstrdup (r-&gt;pool, r-&gt;filename);<br />
1155           mime_dir_config *conf = (mime_dir_config *)<br />
1156           <indent>
1157             ap_get_module_config(r-&gt;per_dir_config, &amp;mime_module);<br />
1158           </indent>
1159           char *type;<br />
1160           <br />
1161           if (S_ISDIR(r-&gt;finfo.st_mode)) {<br />
1162           <indent>
1163             r-&gt;content_type = DIR_MAGIC_TYPE;<br />
1164             return OK;<br />
1165           </indent>
1166           }<br />
1167           <br />
1168           if((i=ap_rind(fn,'.')) &lt; 0) return DECLINED;<br />
1169           ++i;<br />
1170           <br />
1171           if ((type = ap_table_get (conf-&gt;encoding_types, &amp;fn[i])))<br />
1172           {<br />
1173           <indent>
1174             r-&gt;content_encoding = type;<br />
1175             <br />
1176             /* go back to previous extension to try to use it as a type */<br />
1177             fn[i-1] = '\0';<br />
1178             if((i=ap_rind(fn,'.')) &lt; 0) return OK;<br />
1179             ++i;<br />
1180           </indent>
1181           }<br />
1182           <br />
1183           if ((type = ap_table_get (conf-&gt;forced_types, &amp;fn[i])))<br />
1184           {<br />
1185           <indent>
1186             r-&gt;content_type = type;<br />
1187           </indent>
1188           }<br />
1189           <br />
1190           return OK;
1191         </indent>
1192         }
1193       </example>
1194     </section>
1195
1196     <section id="servconf"><title>Side notes -- per-server configuration,
1197     virtual servers, <em>etc</em>.</title>
1198       <p>The basic ideas behind per-server module configuration are basically
1199       the same as those for per-directory configuration; there is a creation
1200       function and a merge function, the latter being invoked where a virtual
1201       server has partially overridden the base server configuration, and a
1202       combined structure must be computed. (As with per-directory configuration,
1203       the default if no merge function is specified, and a module is configured
1204       in some virtual server, is that the base configuration is simply
1205       ignored).</p>
1206
1207       <p>The only substantial difference is that when a command needs to
1208       configure the per-server private module data, it needs to go to the
1209       <code>cmd_parms</code> data to get at it. Here's an example, from the
1210       alias module, which also indicates how a syntax error can be returned
1211       (note that the per-directory configuration argument to the command
1212       handler is declared as a dummy, since the module doesn't actually have
1213       per-directory config data):</p>
1214
1215       <example>
1216         char *add_redirect(cmd_parms *cmd, void *dummy, char *f, char *url)<br />
1217         {<br />
1218         <indent>
1219           server_rec *s = cmd-&gt;server;<br />
1220           alias_server_conf *conf = (alias_server_conf *)<br />
1221           <indent>
1222             ap_get_module_config(s-&gt;module_config,&amp;alias_module);<br />
1223           </indent>
1224           alias_entry *new = ap_push_array (conf-&gt;redirects);<br />
1225           <br />
1226           if (!ap_is_url (url)) return "Redirect to non-URL";<br />
1227           <br />
1228           new-&gt;fake = f; new-&gt;real = url;<br />
1229           return NULL;<br />
1230         </indent>
1231         }
1232       </example>
1233     </section>
1234 </section>
1235
1236 </manualpage>