home *** CD-ROM | disk | FTP | other *** search
/ Cricao de Sites - 650 Layouts Prontos / WebMasters.iso / Servidores / apache_2.2.8-win32-x86-no_ssl.msi / Data1.cab / _502458EC4A0316B61C0B959DE0A8E738 < prev    next >
Extensible Markup Language  |  2007-10-20  |  64KB  |  1,222 lines

  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.2</p>
  16. <img alt="" src="../images/feather.gif" /></div>
  17. <div class="up"><a href="./"><img title="<-" alt="<-" src="../images/left.gif" /></a></div>
  18. <div id="path">
  19. <a href="http://www.apache.org/">Apache</a> > <a href="http://httpd.apache.org/">HTTP Server</a> > <a href="http://httpd.apache.org/docs/">Documentation</a> > <a href="../">Version 2.2</a> > <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"> en </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 -> 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.          * 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.          * module's configuration info.  Note that these are<br />
  225.          * returned, and passed in, as void *'s; the server<br />
  226.          * core keeps track of them, but it doesn't, and can't,<br />
  227.          * know their internal structure.<br />
  228.          */<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->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"><Directory></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.          * an array containing environment variables to<br />
  337.          * be passed to subprocesses, so people can write<br />
  338.          * modules to add to that environment.<br />
  339.          *<br />
  340.          * The difference between headers_out and <br />
  341.          * err_headers_out is that the latter are printed <br />
  342.          * even on error, and persist across internal<br />
  343.          * redirects (so the headers printed for <br />
  344.          * <code class="directive"><a href="../mod/core.html#errordocument">ErrorDocument</a></code> handlers will have
  345.          them).<br />
  346.          */<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.          * the data being returned is volatile, and clients<br />
  368.          * should be told not to cache it.<br />
  369.          */<br />
  370.         <br />
  371.         int no_cache;<br />
  372.         <br />
  373.         /* Various other config info which may change<br />
  374.          * with .htaccess files<br />
  375.          * These are config vectors, with one void*<br />
  376.          * pointer for each module (the thing pointed<br />
  377.          * to being the module's business).<br />
  378.          */<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 */</pre><p><code>
  382.         <br />
  383.         };
  384.       </code></p></div>
  385.     
  386.  
  387.     <h3><a name="req_orig" id="req_orig">Where request_rec structures come from</a></h3>
  388.       <p>Most <code>request_rec</code> structures are built by reading an HTTP
  389.       request from a client, and filling in the fields. However, there are a
  390.       few exceptions:</p>
  391.  
  392.       <ul>
  393.       <li>If the request is to an imagemap, a type map (<em>i.e.</em>, a
  394.       <code>*.var</code> file), or a CGI script which returned a local
  395.       `Location:', then the resource which the user requested is going to be
  396.       ultimately located by some URI other than what the client originally
  397.       supplied. In this case, the server does an <em>internal redirect</em>,
  398.       constructing a new <code>request_rec</code> for the new URI, and
  399.       processing it almost exactly as if the client had requested the new URI
  400.       directly.</li>
  401.  
  402.       <li>If some handler signaled an error, and an <code>ErrorDocument</code>
  403.       is in scope, the same internal redirect machinery comes into play.</li>
  404.  
  405.       <li><p>Finally, a handler occasionally needs to investigate `what would
  406.       happen if' some other request were run. For instance, the directory
  407.       indexing module needs to know what MIME type would be assigned to a
  408.       request for each directory entry, in order to figure out what icon to
  409.       use.</p>
  410.  
  411.       <p>Such handlers can construct a <em>sub-request</em>, using the
  412.       functions <code>ap_sub_req_lookup_file</code>,
  413.       <code>ap_sub_req_lookup_uri</code>, and <code>ap_sub_req_method_uri</code>;
  414.       these construct a new <code>request_rec</code> structure and processes it
  415.       as you would expect, up to but not including the point of actually sending
  416.       a response. (These functions skip over the access checks if the
  417.       sub-request is for a file in the same directory as the original
  418.       request).</p>
  419.  
  420.       <p>(Server-side includes work by building sub-requests and then actually
  421.       invoking the response handler for them, via the function
  422.       <code>ap_run_sub_req</code>).</p>
  423.       </li>
  424.       </ul>
  425.     
  426.  
  427.     <h3><a name="req_return" id="req_return">Handling requests, declining, and returning
  428.     error codes</a></h3>
  429.       <p>As discussed above, each handler, when invoked to handle a particular
  430.       <code>request_rec</code>, has to return an <code>int</code> to indicate
  431.       what happened. That can either be</p>
  432.  
  433.       <ul>
  434.       <li><code>OK</code> -- the request was handled successfully. This may or
  435.       may not terminate the phase.</li>
  436.  
  437.       <li><code>DECLINED</code> -- no erroneous condition exists, but the module
  438.       declines to handle the phase; the server tries to find another.</li>
  439.  
  440.       <li>an HTTP error code, which aborts handling of the request.</li>
  441.       </ul>
  442.  
  443.       <p>Note that if the error code returned is <code>REDIRECT</code>, then
  444.       the module should put a <code>Location</code> in the request's
  445.       <code>headers_out</code>, to indicate where the client should be
  446.       redirected <em>to</em>.</p>
  447.     
  448.  
  449.     <h3><a name="resp_handlers" id="resp_handlers">Special considerations for response
  450.     handlers</a></h3>
  451.       <p>Handlers for most phases do their work by simply setting a few fields
  452.       in the <code>request_rec</code> structure (or, in the case of access
  453.       checkers, simply by returning the correct error code). However, response
  454.       handlers have to actually send a request back to the client.</p>
  455.  
  456.       <p>They should begin by sending an HTTP response header, using the
  457.       function <code>ap_send_http_header</code>. (You don't have to do anything
  458.       special to skip sending the header for HTTP/0.9 requests; the function
  459.       figures out on its own that it shouldn't do anything). If the request is
  460.       marked <code>header_only</code>, that's all they should do; they should
  461.       return after that, without attempting any further output.</p>
  462.  
  463.       <p>Otherwise, they should produce a request body which responds to the
  464.       client as appropriate. The primitives for this are <code>ap_rputc</code>
  465.       and <code>ap_rprintf</code>, for internally generated output, and
  466.       <code>ap_send_fd</code>, to copy the contents of some <code>FILE *</code>
  467.       straight to the client.</p>
  468.  
  469.       <p>At this point, you should more or less understand the following piece
  470.       of code, which is the handler which handles <code>GET</code> requests
  471.       which have no more specific handler; it also shows how conditional
  472.       <code>GET</code>s can be handled, if it's desirable to do so in a
  473.       particular response handler -- <code>ap_set_last_modified</code> checks
  474.       against the <code>If-modified-since</code> value supplied by the client,
  475.       if any, and returns an appropriate code (which will, if nonzero, be
  476.       USE_LOCAL_COPY). No similar considerations apply for
  477.       <code>ap_set_content_length</code>, but it returns an error code for
  478.       symmetry.</p>
  479.  
  480.       <div class="example"><p><code>
  481.         int default_handler (request_rec *r)<br />
  482.         {<br />
  483.         <span class="indent">
  484.           int errstatus;<br />
  485.           FILE *f;<br />
  486.           <br />
  487.           if (r->method_number != M_GET) return DECLINED;<br />
  488.           if (r->finfo.st_mode == 0) return NOT_FOUND;<br />
  489.           <br />
  490.           if ((errstatus = ap_set_content_length (r, r->finfo.st_size))<br />
  491.               ||
  492.              (errstatus = ap_set_last_modified (r, r->finfo.st_mtime)))<br />
  493.           return errstatus;<br />
  494.           <br />
  495.           f = fopen (r->filename, "r");<br />
  496.           <br />
  497.           if (f == NULL) {<br />
  498.           <span class="indent">
  499.             log_reason("file permissions deny server access", r->filename, r);<br />
  500.             return FORBIDDEN;<br />
  501.           </span>
  502.           }<br />
  503.           <br />
  504.           register_timeout ("send", r);<br />
  505.           ap_send_http_header (r);<br />
  506.           <br />
  507.           if (!r->header_only) send_fd (f, r);<br />
  508.           ap_pfclose (r->pool, f);<br />
  509.           return OK;<br />
  510.         </span>
  511.         }
  512.       </code></p></div>
  513.  
  514.       <p>Finally, if all of this is too much of a challenge, there are a few
  515.       ways out of it. First off, as shown above, a response handler which has
  516.       not yet produced any output can simply return an error code, in which
  517.       case the server will automatically produce an error response. Secondly,
  518.       it can punt to some other handler by invoking
  519.       <code>ap_internal_redirect</code>, which is how the internal redirection
  520.       machinery discussed above is invoked. A response handler which has
  521.       internally redirected should always return <code>OK</code>.</p>
  522.  
  523.       <p>(Invoking <code>ap_internal_redirect</code> from handlers which are
  524.       <em>not</em> response handlers will lead to serious confusion).</p>
  525.     
  526.  
  527.     <h3><a name="auth_handlers" id="auth_handlers">Special considerations for authentication
  528.     handlers</a></h3>
  529.       <p>Stuff that should be discussed here in detail:</p>
  530.  
  531.       <ul>
  532.       <li>Authentication-phase handlers not invoked unless auth is
  533.       configured for the directory.</li>
  534.  
  535.       <li>Common auth configuration stored in the core per-dir
  536.       configuration; it has accessors <code>ap_auth_type</code>,
  537.       <code>ap_auth_name</code>, and <code>ap_requires</code>.</li>
  538.  
  539.       <li>Common routines, to handle the protocol end of things, at
  540.       least for HTTP basic authentication
  541.       (<code>ap_get_basic_auth_pw</code>, which sets the
  542.       <code>connection->user</code> structure field
  543.       automatically, and <code>ap_note_basic_auth_failure</code>,
  544.       which arranges for the proper <code>WWW-Authenticate:</code>
  545.       header to be sent back).</li>
  546.       </ul>
  547.     
  548.  
  549.     <h3><a name="log_handlers" id="log_handlers">Special considerations for logging
  550.     handlers</a></h3>
  551.       <p>When a request has internally redirected, there is the question of
  552.       what to log. Apache handles this by bundling the entire chain of redirects
  553.       into a list of <code>request_rec</code> structures which are threaded
  554.       through the <code>r->prev</code> and <code>r->next</code> pointers.
  555.       The <code>request_rec</code> which is passed to the logging handlers in
  556.       such cases is the one which was originally built for the initial request
  557.       from the client; note that the <code>bytes_sent</code> field will only be
  558.       correct in the last request in the chain (the one for which a response was
  559.       actually sent).</p>
  560.     
  561. </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
  562. <div class="section">
  563. <h2><a name="pools" id="pools">Resource allocation and resource pools</a></h2>
  564.     <p>One of the problems of writing and designing a server-pool server is
  565.     that of preventing leakage, that is, allocating resources (memory, open
  566.     files, <em>etc.</em>), without subsequently releasing them. The resource
  567.     pool machinery is designed to make it easy to prevent this from happening,
  568.     by allowing resource to be allocated in such a way that they are
  569.     <em>automatically</em> released when the server is done with them.</p>
  570.  
  571.     <p>The way this works is as follows: the memory which is allocated, file
  572.     opened, <em>etc.</em>, to deal with a particular request are tied to a
  573.     <em>resource pool</em> which is allocated for the request. The pool is a
  574.     data structure which itself tracks the resources in question.</p>
  575.  
  576.     <p>When the request has been processed, the pool is <em>cleared</em>. At
  577.     that point, all the memory associated with it is released for reuse, all
  578.     files associated with it are closed, and any other clean-up functions which
  579.     are associated with the pool are run. When this is over, we can be confident
  580.     that all the resource tied to the pool have been released, and that none of
  581.     them have leaked.</p>
  582.  
  583.     <p>Server restarts, and allocation of memory and resources for per-server
  584.     configuration, are handled in a similar way. There is a <em>configuration
  585.     pool</em>, which keeps track of resources which were allocated while reading
  586.     the server configuration files, and handling the commands therein (for
  587.     instance, the memory that was allocated for per-server module configuration,
  588.     log files and other files that were opened, and so forth). When the server
  589.     restarts, and has to reread the configuration files, the configuration pool
  590.     is cleared, and so the memory and file descriptors which were taken up by
  591.     reading them the last time are made available for reuse.</p>
  592.  
  593.     <p>It should be noted that use of the pool machinery isn't generally
  594.     obligatory, except for situations like logging handlers, where you really
  595.     need to register cleanups to make sure that the log file gets closed when
  596.     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
  597.     underlying file descriptor to be closed before any child processes, such as
  598.     for CGI scripts, are <code>exec</code>ed), or in case you are using the
  599.     timeout machinery (which isn't yet even documented here). However, there are
  600.     two benefits to using it: resources allocated to a pool never leak (even if
  601.     you allocate a scratch string, and just forget about it); also, for memory
  602.     allocation, <code>ap_palloc</code> is generally faster than
  603.     <code>malloc</code>.</p>
  604.  
  605.     <p>We begin here by describing how memory is allocated to pools, and then
  606.     discuss how other resources are tracked by the resource pool machinery.</p>
  607.  
  608.     <h3>Allocation of memory in pools</h3>
  609.       <p>Memory is allocated to pools by calling the function
  610.       <code>ap_palloc</code>, which takes two arguments, one being a pointer to
  611.       a resource pool structure, and the other being the amount of memory to
  612.       allocate (in <code>char</code>s). Within handlers for handling requests,
  613.       the most common way of getting a resource pool structure is by looking at
  614.       the <code>pool</code> slot of the relevant <code>request_rec</code>; hence
  615.       the repeated appearance of the following idiom in module code:</p>
  616.  
  617.       <div class="example"><p><code>
  618.         int my_handler(request_rec *r)<br />
  619.         {<br />
  620.         <span class="indent">
  621.           struct my_structure *foo;<br />
  622.           ...<br />
  623.           <br />
  624.           foo = (foo *)ap_palloc (r->pool, sizeof(my_structure));<br />
  625.         </span>
  626.         }
  627.       </code></p></div>
  628.  
  629.       <p>Note that <em>there is no <code>ap_pfree</code></em> --
  630.       <code>ap_palloc</code>ed memory is freed only when the associated resource
  631.       pool is cleared. This means that <code>ap_palloc</code> does not have to
  632.       do as much accounting as <code>malloc()</code>; all it does in the typical
  633.       case is to round up the size, bump a pointer, and do a range check.</p>
  634.  
  635.       <p>(It also raises the possibility that heavy use of
  636.       <code>ap_palloc</code> could cause a server process to grow excessively
  637.       large. There are two ways to deal with this, which are dealt with below;
  638.       briefly, you can use <code>malloc</code>, and try to be sure that all of
  639.       the memory gets explicitly <code>free</code>d, or you can allocate a
  640.       sub-pool of the main pool, allocate your memory in the sub-pool, and clear
  641.       it out periodically. The latter technique is discussed in the section
  642.       on sub-pools below, and is used in the directory-indexing code, in order
  643.       to avoid excessive storage allocation when listing directories with
  644.       thousands of files).</p>
  645.     
  646.  
  647.     <h3>Allocating initialized memory</h3>
  648.       <p>There are functions which allocate initialized memory, and are
  649.       frequently useful. The function <code>ap_pcalloc</code> has the same
  650.       interface as <code>ap_palloc</code>, but clears out the memory it
  651.       allocates before it returns it. The function <code>ap_pstrdup</code>
  652.       takes a resource pool and a <code>char *</code> as arguments, and
  653.       allocates memory for a copy of the string the pointer points to, returning
  654.       a pointer to the copy. Finally <code>ap_pstrcat</code> is a varargs-style
  655.       function, which takes a pointer to a resource pool, and at least two
  656.       <code>char *</code> arguments, the last of which must be
  657.       <code>NULL</code>. It allocates enough memory to fit copies of each of
  658.       the strings, as a unit; for instance:</p>
  659.  
  660.       <div class="example"><p><code>
  661.         ap_pstrcat (r->pool, "foo", "/", "bar", NULL);
  662.       </code></p></div>
  663.  
  664.       <p>returns a pointer to 8 bytes worth of memory, initialized to
  665.       <code>"foo/bar"</code>.</p>
  666.     
  667.  
  668.     <h3><a name="pools-used" id="pools-used">Commonly-used pools in the Apache Web
  669.     server</a></h3>
  670.       <p>A pool is really defined by its lifetime more than anything else.
  671.       There are some static pools in http_main which are passed to various
  672.       non-http_main functions as arguments at opportune times. Here they
  673.       are:</p>
  674.  
  675.       <dl>
  676.       <dt><code>permanent_pool</code></dt>
  677.       <dd>never passed to anything else, this is the ancestor of all pools</dd>
  678.  
  679.       <dt><code>pconf</code></dt>
  680.       <dd>
  681.         <ul>
  682.           <li>subpool of permanent_pool</li>
  683.  
  684.           <li>created at the beginning of a config "cycle"; exists
  685.           until the server is terminated or restarts; passed to all
  686.           config-time routines, either via cmd->pool, or as the
  687.           "pool *p" argument on those which don't take pools</li>
  688.  
  689.           <li>passed to the module init() functions</li>
  690.         </ul>
  691.       </dd>
  692.  
  693.       <dt><code>ptemp</code></dt>
  694.       <dd>
  695.         <ul>
  696.           <li>sorry I lie, this pool isn't called this currently in
  697.           1.3, I renamed it this in my pthreads development. I'm
  698.           referring to the use of ptrans in the parent... contrast
  699.           this with the later definition of ptrans in the
  700.           child.</li>
  701.  
  702.           <li>subpool of permanent_pool</li>
  703.  
  704.           <li>created at the beginning of a config "cycle"; exists
  705.           until the end of config parsing; passed to config-time
  706.           routines <em>via</em> cmd->temp_pool. Somewhat of a
  707.           "bastard child" because it isn't available everywhere.
  708.           Used for temporary scratch space which may be needed by
  709.           some config routines but which is deleted at the end of
  710.           config.</li>
  711.         </ul>
  712.       </dd>
  713.  
  714.       <dt><code>pchild</code></dt>
  715.       <dd>
  716.         <ul>
  717.           <li>subpool of permanent_pool</li>
  718.  
  719.           <li>created when a child is spawned (or a thread is
  720.           created); lives until that child (thread) is
  721.           destroyed</li>
  722.  
  723.           <li>passed to the module child_init functions</li>
  724.  
  725.           <li>destruction happens right after the child_exit
  726.           functions are called... (which may explain why I think
  727.           child_exit is redundant and unneeded)</li>
  728.         </ul>
  729.       </dd>
  730.  
  731.       <dt><code>ptrans</code></dt>
  732.       <dd>
  733.         <ul>
  734.           <li>should be a subpool of pchild, but currently is a
  735.           subpool of permanent_pool, see above</li>
  736.  
  737.           <li>cleared by the child before going into the accept()
  738.           loop to receive a connection</li>
  739.  
  740.           <li>used as connection->pool</li>
  741.         </ul>
  742.       </dd>
  743.  
  744.       <dt><code>r->pool</code></dt>
  745.       <dd>
  746.         <ul>
  747.           <li>for the main request this is a subpool of
  748.           connection->pool; for subrequests it is a subpool of
  749.           the parent request's pool.</li>
  750.  
  751.           <li>exists until the end of the request (<em>i.e.</em>,
  752.           ap_destroy_sub_req, or in child_main after
  753.           process_request has finished)</li>
  754.  
  755.           <li>note that r itself is allocated from r->pool;
  756.           <em>i.e.</em>, r->pool is first created and then r is
  757.           the first thing palloc()d from it</li>
  758.         </ul>
  759.       </dd>
  760.       </dl>
  761.  
  762.       <p>For almost everything folks do, <code>r->pool</code> is the pool to
  763.       use. But you can see how other lifetimes, such as pchild, are useful to
  764.       some modules... such as modules that need to open a database connection
  765.       once per child, and wish to clean it up when the child dies.</p>
  766.  
  767.       <p>You can also see how some bugs have manifested themself, such as
  768.       setting <code>connection->user</code> to a value from
  769.       <code>r->pool</code> -- in this case connection exists for the
  770.       lifetime of <code>ptrans</code>, which is longer than
  771.       <code>r->pool</code> (especially if <code>r->pool</code> is a
  772.       subrequest!). So the correct thing to do is to allocate from
  773.       <code>connection->pool</code>.</p>
  774.  
  775.       <p>And there was another interesting bug in <code class="module"><a href="../mod/mod_include.html">mod_include</a></code>
  776.       / <code class="module"><a href="../mod/mod_cgi.html">mod_cgi</a></code>. You'll see in those that they do this test
  777.       to decide if they should use <code>r->pool</code> or
  778.       <code>r->main->pool</code>. In this case the resource that they are
  779.       registering for cleanup is a child process. If it were registered in
  780.       <code>r->pool</code>, then the code would <code>wait()</code> for the
  781.       child when the subrequest finishes. With <code class="module"><a href="../mod/mod_include.html">mod_include</a></code> this
  782.       could be any old <code>#include</code>, and the delay can be up to 3
  783.       seconds... and happened quite frequently. Instead the subprocess is
  784.       registered in <code>r->main->pool</code> which causes it to be
  785.       cleaned up when the entire request is done -- <em>i.e.</em>, after the
  786.       output has been sent to the client and logging has happened.</p>
  787.     
  788.  
  789.     <h3><a name="pool-files" id="pool-files">Tracking open files, etc.</a></h3>
  790.       <p>As indicated above, resource pools are also used to track other sorts
  791.       of resources besides memory. The most common are open files. The routine
  792.       which is typically used for this is <code>ap_pfopen</code>, which takes a
  793.       resource pool and two strings as arguments; the strings are the same as
  794.       the typical arguments to <code>fopen</code>, <em>e.g.</em>,</p>
  795.  
  796.       <div class="example"><p><code>
  797.         ...<br />
  798.         FILE *f = ap_pfopen (r->pool, r->filename, "r");<br />
  799.         <br />
  800.         if (f == NULL) { ... } else { ... }<br />
  801.       </code></p></div>
  802.  
  803.       <p>There is also a <code>ap_popenf</code> routine, which parallels the
  804.       lower-level <code>open</code> system call. Both of these routines arrange
  805.       for the file to be closed when the resource pool in question is
  806.       cleared.</p>
  807.  
  808.       <p>Unlike the case for memory, there <em>are</em> functions to close files
  809.       allocated with <code>ap_pfopen</code>, and <code>ap_popenf</code>, namely
  810.       <code>ap_pfclose</code> and <code>ap_pclosef</code>. (This is because, on
  811.       many systems, the number of files which a single process can have open is
  812.       quite limited). It is important to use these functions to close files
  813.       allocated with <code>ap_pfopen</code> and <code>ap_popenf</code>, since to
  814.       do otherwise could cause fatal errors on systems such as Linux, which
  815.       react badly if the same <code>FILE*</code> is closed more than once.</p>
  816.  
  817.       <p>(Using the <code>close</code> functions is not mandatory, since the
  818.       file will eventually be closed regardless, but you should consider it in
  819.       cases where your module is opening, or could open, a lot of files).</p>
  820.     
  821.  
  822.     <h3>Other sorts of resources -- cleanup functions</h3>
  823.       <p>More text goes here. Describe the cleanup primitives in terms of
  824.       which the file stuff is implemented; also, <code>spawn_process</code>.</p>
  825.  
  826.       <p>Pool cleanups live until <code>clear_pool()</code> is called:
  827.       <code>clear_pool(a)</code> recursively calls <code>destroy_pool()</code>
  828.       on all subpools of <code>a</code>; then calls all the cleanups for
  829.       <code>a</code>; then releases all the memory for <code>a</code>.
  830.       <code>destroy_pool(a)</code> calls <code>clear_pool(a)</code> and then
  831.       releases the pool structure itself. <em>i.e.</em>,
  832.       <code>clear_pool(a)</code> doesn't delete <code>a</code>, it just frees
  833.       up all the resources and you can start using it again immediately.</p>
  834.     
  835.  
  836.     <h3>Fine control -- creating and dealing with sub-pools, with
  837.     a note on sub-requests</h3>
  838.       <p>On rare occasions, too-free use of <code>ap_palloc()</code> and the
  839.       associated primitives may result in undesirably profligate resource
  840.       allocation. You can deal with such a case by creating a <em>sub-pool</em>,
  841.       allocating within the sub-pool rather than the main pool, and clearing or
  842.       destroying the sub-pool, which releases the resources which were
  843.       associated with it. (This really <em>is</em> a rare situation; the only
  844.       case in which it comes up in the standard module set is in case of listing
  845.       directories, and then only with <em>very</em> large directories.
  846.       Unnecessary use of the primitives discussed here can hair up your code
  847.       quite a bit, with very little gain).</p>
  848.  
  849.       <p>The primitive for creating a sub-pool is <code>ap_make_sub_pool</code>,
  850.       which takes another pool (the parent pool) as an argument. When the main
  851.       pool is cleared, the sub-pool will be destroyed. The sub-pool may also be
  852.       cleared or destroyed at any time, by calling the functions
  853.       <code>ap_clear_pool</code> and <code>ap_destroy_pool</code>, respectively.
  854.       (The difference is that <code>ap_clear_pool</code> frees resources
  855.       associated with the pool, while <code>ap_destroy_pool</code> also
  856.       deallocates the pool itself. In the former case, you can allocate new
  857.       resources within the pool, and clear it again, and so forth; in the
  858.       latter case, it is simply gone).</p>
  859.  
  860.       <p>One final note -- sub-requests have their own resource pools, which are
  861.       sub-pools of the resource pool for the main request. The polite way to
  862.       reclaim the resources associated with a sub request which you have
  863.       allocated (using the <code>ap_sub_req_...</code> functions) is
  864.       <code>ap_destroy_sub_req</code>, which frees the resource pool. Before
  865.       calling this function, be sure to copy anything that you care about which
  866.       might be allocated in the sub-request's resource pool into someplace a
  867.       little less volatile (for instance, the filename in its
  868.       <code>request_rec</code> structure).</p>
  869.  
  870.       <p>(Again, under most circumstances, you shouldn't feel obliged to call
  871.       this function; only 2K of memory or so are allocated for a typical sub
  872.       request, and it will be freed anyway when the main request pool is
  873.       cleared. It is only when you are allocating many, many sub-requests for a
  874.       single main request that you should seriously consider the
  875.       <code>ap_destroy_...</code> functions).</p>
  876.     
  877. </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
  878. <div class="section">
  879. <h2><a name="config" id="config">Configuration, commands and the like</a></h2>
  880.     <p>One of the design goals for this server was to maintain external
  881.     compatibility with the NCSA 1.3 server --- that is, to read the same
  882.     configuration files, to process all the directives therein correctly, and
  883.     in general to be a drop-in replacement for NCSA. On the other hand, another
  884.     design goal was to move as much of the server's functionality into modules
  885.     which have as little as possible to do with the monolithic server core. The
  886.     only way to reconcile these goals is to move the handling of most commands
  887.     from the central server into the modules.</p>
  888.  
  889.     <p>However, just giving the modules command tables is not enough to divorce
  890.     them completely from the server core. The server has to remember the
  891.     commands in order to act on them later. That involves maintaining data which
  892.     is private to the modules, and which can be either per-server, or
  893.     per-directory. Most things are per-directory, including in particular access
  894.     control and authorization information, but also information on how to
  895.     determine file types from suffixes, which can be modified by
  896.     <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,
  897.     the governing philosophy is that anything which <em>can</em> be made
  898.     configurable by directory should be; per-server information is generally
  899.     used in the standard set of modules for information like
  900.     <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
  901.     request is tied to a particular place in the underlying file system.</p>
  902.  
  903.     <p>Another requirement for emulating the NCSA server is being able to handle
  904.     the per-directory configuration files, generally called
  905.     <code>.htaccess</code> files, though even in the NCSA server they can
  906.     contain directives which have nothing at all to do with access control.
  907.     Accordingly, after URI -> filename translation, but before performing any
  908.     other phase, the server walks down the directory hierarchy of the underlying
  909.     filesystem, following the translated pathname, to read any
  910.     <code>.htaccess</code> files which might be present. The information which
  911.     is read in then has to be <em>merged</em> with the applicable information
  912.     from the server's own config files (either from the <code class="directive"><a href="../mod/core.html#directory"><Directory></a></code> sections in
  913.     <code>access.conf</code>, or from defaults in <code>srm.conf</code>, which
  914.     actually behaves for most purposes almost exactly like <code><Directory
  915.     /></code>).</p>
  916.  
  917.     <p>Finally, after having served a request which involved reading
  918.     <code>.htaccess</code> files, we need to discard the storage allocated for
  919.     handling them. That is solved the same way it is solved wherever else
  920.     similar problems come up, by tying those structures to the per-transaction
  921.     resource pool.</p>
  922.  
  923.     <h3><a name="per-dir" id="per-dir">Per-directory configuration structures</a></h3>
  924.       <p>Let's look out how all of this plays out in <code>mod_mime.c</code>,
  925.       which defines the file typing handler which emulates the NCSA server's
  926.       behavior of determining file types from suffixes. What we'll be looking
  927.       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
  928.       <code>.htaccess</code> files, so they must be handled in the module's
  929.       private per-directory data, which in fact, consists of two separate
  930.       tables for MIME types and encoding information, and is declared as
  931.       follows:</p>
  932.  
  933.       <div class="example"><pre>typedef struct {
  934.     table *forced_types;      /* Additional AddTyped stuff */
  935.     table *encoding_types;    /* Added with AddEncoding... */
  936. } mime_dir_config;</pre></div>
  937.  
  938.       <p>When the server is reading a configuration file, or <code class="directive"><a href="../mod/core.html#directory"><Directory></a></code> section, which includes
  939.       one of the MIME module's commands, it needs to create a
  940.       <code>mime_dir_config</code> structure, so those commands have something
  941.       to act on. It does this by invoking the function it finds in the module's
  942.       `create per-dir config slot', with two arguments: the name of the
  943.       directory to which this configuration information applies (or
  944.       <code>NULL</code> for <code>srm.conf</code>), and a pointer to a
  945.       resource pool in which the allocation should happen.</p>
  946.  
  947.       <p>(If we are reading a <code>.htaccess</code> file, that resource pool
  948.       is the per-request resource pool for the request; otherwise it is a
  949.       resource pool which is used for configuration data, and cleared on
  950.       restarts. Either way, it is important for the structure being created to
  951.       vanish when the pool is cleared, by registering a cleanup on the pool if
  952.       necessary).</p>
  953.  
  954.       <p>For the MIME module, the per-dir config creation function just
  955.       <code>ap_palloc</code>s the structure above, and a creates a couple of
  956.       tables to fill it. That looks like this:</p>
  957.  
  958.       <div class="example"><p><code>
  959.         void *create_mime_dir_config (pool *p, char *dummy)<br />
  960.         {<br />
  961.         <span class="indent">
  962.           mime_dir_config *new =<br />
  963.           <span class="indent">
  964.            (mime_dir_config *) ap_palloc (p, sizeof(mime_dir_config));<br />
  965.           </span>
  966.           <br />
  967.           new->forced_types = ap_make_table (p, 4);<br />
  968.           new->encoding_types = ap_make_table (p, 4);<br />
  969.           <br />
  970.           return new;<br />
  971.         </span>
  972.         }
  973.       </code></p></div>
  974.  
  975.       <p>Now, suppose we've just read in a <code>.htaccess</code> file. We
  976.       already have the per-directory configuration structure for the next
  977.       directory up in the hierarchy. If the <code>.htaccess</code> file we just
  978.       read in didn't have any <code class="directive"><a href="../mod/mod_mime.html#addtype">AddType</a></code>
  979.       or <code class="directive"><a href="../mod/mod_mime.html#addencoding">AddEncoding</a></code> commands, its
  980.       per-directory config structure for the MIME module is still valid, and we
  981.       can just use it. Otherwise, we need to merge the two structures
  982.       somehow.</p>
  983.  
  984.       <p>To do that, the server invokes the module's per-directory config merge
  985.       function, if one is present. That function takes three arguments: the two
  986.       structures being merged, and a resource pool in which to allocate the
  987.       result. For the MIME module, all that needs to be done is overlay the
  988.       tables from the new per-directory config structure with those from the
  989.       parent:</p>
  990.  
  991.       <div class="example"><p><code>
  992.         void *merge_mime_dir_configs (pool *p, void *parent_dirv, void *subdirv)<br />
  993.         {<br />
  994.         <span class="indent">
  995.           mime_dir_config *parent_dir = (mime_dir_config *)parent_dirv;<br />
  996.           mime_dir_config *subdir = (mime_dir_config *)subdirv;<br />
  997.           mime_dir_config *new =<br />
  998.           <span class="indent">
  999.             (mime_dir_config *)ap_palloc (p, sizeof(mime_dir_config));<br />
  1000.           </span>
  1001.           <br />
  1002.           new->forced_types = ap_overlay_tables (p, subdir->forced_types,<br />
  1003.           <span class="indent">
  1004.             parent_dir->forced_types);<br />
  1005.           </span>
  1006.           new->encoding_types = ap_overlay_tables (p, subdir->encoding_types,<br />
  1007.           <span class="indent">
  1008.             parent_dir->encoding_types);<br />
  1009.           </span>
  1010.           <br />
  1011.           return new;<br />
  1012.         </span>
  1013.         }
  1014.       </code></p></div>
  1015.  
  1016.       <p>As a note -- if there is no per-directory merge function present, the
  1017.       server will just use the subdirectory's configuration info, and ignore
  1018.       the parent's. For some modules, that works just fine (<em>e.g.</em>, for
  1019.       the includes module, whose per-directory configuration information
  1020.       consists solely of the state of the <code>XBITHACK</code>), and for those
  1021.       modules, you can just not declare one, and leave the corresponding
  1022.       structure slot in the module itself <code>NULL</code>.</p>
  1023.     
  1024.  
  1025.     <h3><a name="commands" id="commands">Command handling</a></h3>
  1026.       <p>Now that we have these structures, we need to be able to figure out how
  1027.       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
  1028.       the module's command table. That table contains information on how many
  1029.       arguments the commands take, and in what formats, where it is permitted,
  1030.       and so forth. That information is sufficient to allow the server to invoke
  1031.       most command-handling functions with pre-parsed arguments. Without further
  1032.       ado, let's look at the <code class="directive"><a href="../mod/mod_mime.html#addtype">AddType</a></code>
  1033.       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
  1034.       shown here):</p>
  1035.  
  1036.       <div class="example"><p><code>
  1037.         char *add_type(cmd_parms *cmd, mime_dir_config *m, char *ct, char *ext)<br />
  1038.         {<br />
  1039.         <span class="indent">
  1040.           if (*ext == '.') ++ext;<br />
  1041.           ap_table_set (m->forced_types, ext, ct);<br />
  1042.           return NULL;<br />
  1043.         </span>
  1044.         }
  1045.       </code></p></div>
  1046.  
  1047.       <p>This command handler is unusually simple. As you can see, it takes
  1048.       four arguments, two of which are pre-parsed arguments, the third being the
  1049.       per-directory configuration structure for the module in question, and the
  1050.       fourth being a pointer to a <code>cmd_parms</code> structure. That
  1051.       structure contains a bunch of arguments which are frequently of use to
  1052.       some, but not all, commands, including a resource pool (from which memory
  1053.       can be allocated, and to which cleanups should be tied), and the (virtual)
  1054.       server being configured, from which the module's per-server configuration
  1055.       data can be obtained if required.</p>
  1056.  
  1057.       <p>Another way in which this particular command handler is unusually
  1058.       simple is that there are no error conditions which it can encounter. If
  1059.       there were, it could return an error message instead of <code>NULL</code>;
  1060.       this causes an error to be printed out on the server's
  1061.       <code>stderr</code>, followed by a quick exit, if it is in the main config
  1062.       files; for a <code>.htaccess</code> file, the syntax error is logged in
  1063.       the server error log (along with an indication of where it came from), and
  1064.       the request is bounced with a server error response (HTTP error status,
  1065.       code 500).</p>
  1066.  
  1067.       <p>The MIME module's command table has entries for these commands, which
  1068.       look like this:</p>
  1069.  
  1070.       <div class="example"><p><code>
  1071.         command_rec mime_cmds[] = {<br />
  1072.         <span class="indent">
  1073.           { "AddType", add_type, NULL, OR_FILEINFO, TAKE2,<br />
  1074.           <span class="indent">"a mime type followed by a file extension" },<br /></span>
  1075.           { "AddEncoding", add_encoding, NULL, OR_FILEINFO, TAKE2,<br />
  1076.           <span class="indent">
  1077.           "an encoding (<em>e.g.</em>, gzip), followed by a file extension" },<br />
  1078.           </span>
  1079.           { NULL }<br />
  1080.         </span>
  1081.         };
  1082.       </code></p></div>
  1083.  
  1084.       <p>The entries in these tables are:</p>
  1085.       <ul>
  1086.       <li>The name of the command</li>
  1087.       <li>The function which handles it</li>
  1088.       <li>a <code>(void *)</code> pointer, which is passed in the
  1089.       <code>cmd_parms</code> structure to the command handler ---
  1090.       this is useful in case many similar commands are handled by
  1091.       the same function.</li>
  1092.  
  1093.       <li>A bit mask indicating where the command may appear. There
  1094.       are mask bits corresponding to each
  1095.       <code>AllowOverride</code> option, and an additional mask
  1096.       bit, <code>RSRC_CONF</code>, indicating that the command may
  1097.       appear in the server's own config files, but <em>not</em> in
  1098.       any <code>.htaccess</code> file.</li>
  1099.  
  1100.       <li>A flag indicating how many arguments the command handler
  1101.       wants pre-parsed, and how they should be passed in.
  1102.       <code>TAKE2</code> indicates two pre-parsed arguments. Other
  1103.       options are <code>TAKE1</code>, which indicates one
  1104.       pre-parsed argument, <code>FLAG</code>, which indicates that
  1105.       the argument should be <code>On</code> or <code>Off</code>,
  1106.       and is passed in as a boolean flag, <code>RAW_ARGS</code>,
  1107.       which causes the server to give the command the raw, unparsed
  1108.       arguments (everything but the command name itself). There is
  1109.       also <code>ITERATE</code>, which means that the handler looks
  1110.       the same as <code>TAKE1</code>, but that if multiple
  1111.       arguments are present, it should be called multiple times,
  1112.       and finally <code>ITERATE2</code>, which indicates that the
  1113.       command handler looks like a <code>TAKE2</code>, but if more
  1114.       arguments are present, then it should be called multiple
  1115.       times, holding the first argument constant.</li>
  1116.  
  1117.       <li>Finally, we have a string which describes the arguments
  1118.       that should be present. If the arguments in the actual config
  1119.       file are not as required, this string will be used to help
  1120.       give a more specific error message. (You can safely leave
  1121.       this <code>NULL</code>).</li>
  1122.       </ul>
  1123.  
  1124.       <p>Finally, having set this all up, we have to use it. This is ultimately
  1125.       done in the module's handlers, specifically for its file-typing handler,
  1126.       which looks more or less like this; note that the per-directory
  1127.       configuration structure is extracted from the <code>request_rec</code>'s
  1128.       per-directory configuration vector by using the
  1129.       <code>ap_get_module_config</code> function.</p>
  1130.  
  1131.       <div class="example"><p><code>
  1132.         int find_ct(request_rec *r)<br />
  1133.         {<br />
  1134.         <span class="indent">
  1135.           int i;<br />
  1136.           char *fn = ap_pstrdup (r->pool, r->filename);<br />
  1137.           mime_dir_config *conf = (mime_dir_config *)<br />
  1138.           <span class="indent">
  1139.             ap_get_module_config(r->per_dir_config, &mime_module);<br />
  1140.           </span>
  1141.           char *type;<br />
  1142.           <br />
  1143.           if (S_ISDIR(r->finfo.st_mode)) {<br />
  1144.           <span class="indent">
  1145.             r->content_type = DIR_MAGIC_TYPE;<br />
  1146.             return OK;<br />
  1147.           </span>
  1148.           }<br />
  1149.           <br />
  1150.           if((i=ap_rind(fn,'.')) < 0) return DECLINED;<br />
  1151.           ++i;<br />
  1152.           <br />
  1153.           if ((type = ap_table_get (conf->encoding_types, &fn[i])))<br />
  1154.           {<br />
  1155.           <span class="indent">
  1156.             r->content_encoding = type;<br />
  1157.             <br />
  1158.             /* go back to previous extension to try to use it as a type */<br />
  1159.             fn[i-1] = '\0';<br />
  1160.             if((i=ap_rind(fn,'.')) < 0) return OK;<br />
  1161.             ++i;<br />
  1162.           </span>
  1163.           }<br />
  1164.           <br />
  1165.           if ((type = ap_table_get (conf->forced_types, &fn[i])))<br />
  1166.           {<br />
  1167.           <span class="indent">
  1168.             r->content_type = type;<br />
  1169.           </span>
  1170.           }<br />
  1171.           <br />
  1172.           return OK;
  1173.         </span>
  1174.         }
  1175.       </code></p></div>
  1176.     
  1177.  
  1178.     <h3><a name="servconf" id="servconf">Side notes -- per-server configuration,
  1179.     virtual servers, <em>etc</em>.</a></h3>
  1180.       <p>The basic ideas behind per-server module configuration are basically
  1181.       the same as those for per-directory configuration; there is a creation
  1182.       function and a merge function, the latter being invoked where a virtual
  1183.       server has partially overridden the base server configuration, and a
  1184.       combined structure must be computed. (As with per-directory configuration,
  1185.       the default if no merge function is specified, and a module is configured
  1186.       in some virtual server, is that the base configuration is simply
  1187.       ignored).</p>
  1188.  
  1189.       <p>The only substantial difference is that when a command needs to
  1190.       configure the per-server private module data, it needs to go to the
  1191.       <code>cmd_parms</code> data to get at it. Here's an example, from the
  1192.       alias module, which also indicates how a syntax error can be returned
  1193.       (note that the per-directory configuration argument to the command
  1194.       handler is declared as a dummy, since the module doesn't actually have
  1195.       per-directory config data):</p>
  1196.  
  1197.       <div class="example"><p><code>
  1198.         char *add_redirect(cmd_parms *cmd, void *dummy, char *f, char *url)<br />
  1199.         {<br />
  1200.         <span class="indent">
  1201.           server_rec *s = cmd->server;<br />
  1202.           alias_server_conf *conf = (alias_server_conf *)<br />
  1203.           <span class="indent">
  1204.             ap_get_module_config(s->module_config,&alias_module);<br />
  1205.           </span>
  1206.           alias_entry *new = ap_push_array (conf->redirects);<br />
  1207.           <br />
  1208.           if (!ap_is_url (url)) return "Redirect to non-URL";<br />
  1209.           <br />
  1210.           new->fake = f; new->real = url;<br />
  1211.           return NULL;<br />
  1212.         </span>
  1213.         }
  1214.       </code></p></div>
  1215.     
  1216. </div></div>
  1217. <div class="bottomlang">
  1218. <p><span>Available Languages: </span><a href="../en/developer/API.html" title="English"> en </a></p>
  1219. </div><div id="footer">
  1220. <p class="apache">Copyright 2007 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>
  1221. <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>
  1222. </body></html>