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