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"?>
6 Copyright 2003-2004 The Apache Software Foundation
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
12 http://www.apache.org/licenses/LICENSE-2.0
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.
21 <manualpage metafile="API.xml.meta">
22 <parentdocument href="./">Developer Documentation</parentdocument>
24 <title>Apache 1.3 API notes</title>
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>
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
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
49 <p>Finally, here's an outline, to give you some bare idea of what's coming
50 up, and in what order:</p>
54 <a href="#basics">Basic concepts.</a>
57 <li><a href="#HMR">Handlers, Modules, and
60 <li><a href="#moduletour">A brief tour of a
66 <a href="#handlers">How handlers work</a>
69 <li><a href="#req_tour">A brief tour of the
70 <code>request_rec</code></a></li>
72 <li><a href="#req_orig">Where request_rec structures come
75 <li><a href="#req_return">Handling requests, declining,
76 and returning error codes</a></li>
78 <li><a href="#resp_handlers">Special considerations for
79 response handlers</a></li>
81 <li><a href="#auth_handlers">Special considerations for
82 authentication handlers</a></li>
84 <li><a href="#log_handlers">Special considerations for
85 logging handlers</a></li>
89 <li><a href="#pools">Resource allocation and resource
93 <a href="#config">Configuration, commands and the like</a>
96 <li><a href="#per-dir">Per-directory configuration
99 <li><a href="#commands">Command handling</a></li>
101 <li><a href="#servconf">Side notes --- per-server
102 configuration, virtual servers, <em>etc</em>.</a></li>
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>
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>
119 <li>URI -> 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>
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
137 <li><em>Handle</em> the request, and indicate that it has done so by
138 returning the magic constant <code>OK</code>.</li>
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>
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>
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
161 <p>The handlers themselves are functions of one argument (a
162 <code>request_rec</code> structure. vide infra), which returns an integer,
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>
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>
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>
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>
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
211 /* Declarations of handlers. */<br />
213 int translate_scriptalias (request_rec *);<br />
214 int type_scriptalias (request_rec *);<br />
215 int cgi_handler (request_rec *);<br />
217 /* Subsidiary dispatch table for response-phase <br />
218 * handlers, by MIME type */<br />
220 handler_rec cgi_handlers[] = {<br />
222 { "application/x-httpd-cgi", cgi_handler },<br />
227 /* Declarations of routines to manipulate the <br />
228 * module's configuration info. Note that these are<br />
229 * returned, and passed in, as void *'s; the server<br />
230 * core keeps track of them, but it doesn't, and can't,<br />
231 * know their internal structure.<br />
234 void *make_cgi_server_config (pool *);<br />
235 void *merge_cgi_server_config (pool *, void *, void *);<br />
237 /* Declarations of routines to handle config-file commands */<br />
239 extern char *script_alias(cmd_parms *, void *per_dir_config, char *fake,
242 command_rec cgi_cmds[] = {<br />
244 { "ScriptAlias", script_alias, NULL, RSRC_CONF, TAKE2,<br />
245 <indent>"a fakename and a realname"},<br /></indent>
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 */
266 NULL /* header parser */
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>
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>
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,
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>
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>
304 r->content_type = "text/html";
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>
320 <p>Here is an abridged declaration, giving the fields most commonly
324 struct request_rec {<br />
327 conn_rec *connection;<br />
328 server_rec *server;<br />
330 /* What object is being requested */<br />
333 char *filename;<br />
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 />
341 /* MIME header environments, in and out. Also, <br />
342 * an array containing environment variables to<br />
343 * be passed to subprocesses, so people can write<br />
344 * modules to add to that environment.<br />
346 * The difference between headers_out and <br />
347 * err_headers_out is that the latter are printed <br />
348 * even on error, and persist across internal<br />
349 * redirects (so the headers printed for <br />
350 * <directive module="core">ErrorDocument</directive> handlers will have
354 table *headers_in;<br />
355 table *headers_out;<br />
356 table *err_headers_out;<br />
357 table *subprocess_env;<br />
359 /* Info about the request itself... */<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> */
367 /* Info for logging */<br />
369 char *the_request;<br />
370 int bytes_sent;<br />
372 /* A flag which modules can set, to indicate that<br />
373 * the data being returned is volatile, and clients<br />
374 * should be told not to cache it.<br />
379 /* Various other config info which may change<br />
380 * with .htaccess files<br />
381 * These are config vectors, with one void*<br />
382 * pointer for each module (the thing pointed<br />
383 * to being the module's business).<br />
386 <pre>void *per_dir_config; /* Options set in config files, <em>etc.</em> */
387 void *request_config; /* Notes on *this* request */</pre>
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
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
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>
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
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
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>
433 <section id="req_return"><title>Handling requests, declining, and returning
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>
440 <li><code>OK</code> -- the request was handled successfully. This may or
441 may not terminate the phase.</li>
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>
446 <li>an HTTP error code, which aborts handling of the request.</li>
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>
455 <section id="resp_handlers"><title>Special considerations for response
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>
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>
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>
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
487 int default_handler (request_rec *r)<br />
493 if (r->method_number != M_GET) return DECLINED;<br />
494 if (r->finfo.st_mode == 0) return NOT_FOUND;<br />
496 if ((errstatus = ap_set_content_length (r, r->finfo.st_size))<br />
497 ||
498 (errstatus = ap_set_last_modified (r, r->finfo.st_mtime)))<br />
499 return errstatus;<br />
501 f = fopen (r->filename, "r");<br />
503 if (f == NULL) {<br />
505 log_reason("file permissions deny server access", r->filename, r);<br />
506 return FORBIDDEN;<br />
510 register_timeout ("send", r);<br />
511 ap_send_http_header (r);<br />
513 if (!r->header_only) send_fd (f, r);<br />
514 ap_pfclose (r->pool, f);<br />
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>
529 <p>(Invoking <code>ap_internal_redirect</code> from handlers which are
530 <em>not</em> response handlers will lead to serious confusion).</p>
533 <section id="auth_handlers"><title>Special considerations for authentication
535 <p>Stuff that should be discussed here in detail:</p>
538 <li>Authentication-phase handlers not invoked unless auth is
539 configured for the directory.</li>
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>
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->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>
555 <section id="log_handlers"><title>Special considerations for logging
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->prev</code> and <code>r->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
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>
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>
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>
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>
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>
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>
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>
625 int my_handler(request_rec *r)<br />
628 struct my_structure *foo;<br />
631 foo = (foo *)ap_palloc (r->pool, sizeof(my_structure));<br />
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>
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>
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>
668 ap_pstrcat (r->pool, "foo", "/", "bar", NULL);
671 <p>returns a pointer to 8 bytes worth of memory, initialized to
672 <code>"foo/bar"</code>.</p>
675 <section id="pools-used"><title>Commonly-used pools in the Apache Web
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
683 <dt><code>permanent_pool</code></dt>
684 <dd>never passed to anything else, this is the ancestor of all pools</dd>
686 <dt><code>pconf</code></dt>
689 <li>subpool of permanent_pool</li>
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->pool, or as the
694 "pool *p" argument on those which don't take pools</li>
696 <li>passed to the module init() functions</li>
700 <dt><code>ptemp</code></dt>
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
709 <li>subpool of permanent_pool</li>
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->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
721 <dt><code>pchild</code></dt>
724 <li>subpool of permanent_pool</li>
726 <li>created when a child is spawned (or a thread is
727 created); lives until that child (thread) is
730 <li>passed to the module child_init functions</li>
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>
738 <dt><code>ptrans</code></dt>
741 <li>should be a subpool of pchild, but currently is a
742 subpool of permanent_pool, see above</li>
744 <li>cleared by the child before going into the accept()
745 loop to receive a connection</li>
747 <li>used as connection->pool</li>
751 <dt><code>r->pool</code></dt>
754 <li>for the main request this is a subpool of
755 connection->pool; for subrequests it is a subpool of
756 the parent request's pool.</li>
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>
762 <li>note that r itself is allocated from r->pool;
763 <em>i.e.</em>, r->pool is first created and then r is
764 the first thing palloc()d from it</li>
769 <p>For almost everything folks do, <code>r->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>
774 <p>You can also see how some bugs have manifested themself, such as
775 setting <code>connection->user</code> to a value from
776 <code>r->pool</code> -- in this case connection exists for the
777 lifetime of <code>ptrans</code>, which is longer than
778 <code>r->pool</code> (especially if <code>r->pool</code> is a
779 subrequest!). So the correct thing to do is to allocate from
780 <code>connection->pool</code>.</p>
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->pool</code> or
785 <code>r->main->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->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->main->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>
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>
805 FILE *f = ap_pfopen (r->pool, r->filename, "r");<br />
807 if (f == NULL) { ... } else { ... }<br />
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
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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 -> 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><Directory
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
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
946 <pre>typedef struct {
947 table *forced_types; /* Additional AddTyped stuff */
948 table *encoding_types; /* Added with AddEncoding... */
949 } mime_dir_config;</pre>
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>
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
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>
974 void *create_mime_dir_config (pool *p, char *dummy)<br />
977 mime_dir_config *new =<br />
979 (mime_dir_config *) ap_palloc (p, sizeof(mime_dir_config));<br />
982 new->forced_types = ap_make_table (p, 4);<br />
983 new->encoding_types = ap_make_table (p, 4);<br />
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
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
1007 void *merge_mime_dir_configs (pool *p, void *parent_dirv, void *subdirv)<br />
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 />
1014 (mime_dir_config *)ap_palloc (p, sizeof(mime_dir_config));<br />
1017 new->forced_types = ap_overlay_tables (p, subdir->forced_types,<br />
1019 parent_dir->forced_types);<br />
1021 new->encoding_types = ap_overlay_tables (p, subdir->encoding_types,<br />
1023 parent_dir->encoding_types);<br />
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>
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
1055 char *add_type(cmd_parms *cmd, mime_dir_config *m, char *ct, char *ext)<br />
1058 if (*ext == '.') ++ext;<br />
1059 ap_table_set (m->forced_types, ext, ct);<br />
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>
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,
1085 <p>The MIME module's command table has entries for these commands, which
1089 command_rec mime_cmds[] = {<br />
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 />
1095 "an encoding (<em>e.g.</em>, gzip), followed by a file extension" },<br />
1102 <p>The entries in these tables are:</p>
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>
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>
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>
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>
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>
1150 int find_ct(request_rec *r)<br />
1154 char *fn = ap_pstrdup (r->pool, r->filename);<br />
1155 mime_dir_config *conf = (mime_dir_config *)<br />
1157 ap_get_module_config(r->per_dir_config, &mime_module);<br />
1161 if (S_ISDIR(r->finfo.st_mode)) {<br />
1163 r->content_type = DIR_MAGIC_TYPE;<br />
1168 if((i=ap_rind(fn,'.')) < 0) return DECLINED;<br />
1171 if ((type = ap_table_get (conf->encoding_types, &fn[i])))<br />
1174 r->content_encoding = type;<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,'.')) < 0) return OK;<br />
1183 if ((type = ap_table_get (conf->forced_types, &fn[i])))<br />
1186 r->content_type = type;<br />
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
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>
1216 char *add_redirect(cmd_parms *cmd, void *dummy, char *f, char *url)<br />
1219 server_rec *s = cmd->server;<br />
1220 alias_server_conf *conf = (alias_server_conf *)<br />
1222 ap_get_module_config(s->module_config,&alias_module);<br />
1224 alias_entry *new = ap_push_array (conf->redirects);<br />
1226 if (!ap_is_url (url)) return "Redirect to non-URL";<br />
1228 new->fake = f; new->real = url;<br />