]> granicus.if.org Git - apache/blob - modules/experimental/mod_example.c
Update copyright to 2001
[apache] / modules / experimental / mod_example.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  * Portions of this software are based upon public domain software
55  * originally written at the National Center for Supercomputing Applications,
56  * University of Illinois, Urbana-Champaign.
57  */
58
59 /* 
60  * Apache example module.  Provide demonstrations of how modules do things.
61  *
62  */
63
64 #include "httpd.h"
65 #include "http_config.h"
66 #include "http_core.h"
67 #include "http_log.h"
68 #include "http_main.h"
69 #include "http_protocol.h"
70 #include "http_request.h"
71 #include "util_script.h"
72
73 #include "apr_strings.h"
74
75 #include <stdio.h>
76
77 /*--------------------------------------------------------------------------*/
78 /*                                                                          */
79 /* Data declarations.                                                       */
80 /*                                                                          */
81 /* Here are the static cells and structure declarations private to our      */
82 /* module.                                                                  */
83 /*                                                                          */
84 /*--------------------------------------------------------------------------*/
85
86 /*
87  * Sample configuration record.  Used for both per-directory and per-server
88  * configuration data.
89  *
90  * It's perfectly reasonable to have two different structures for the two
91  * different environments.  The same command handlers will be called for
92  * both, though, so the handlers need to be able to tell them apart.  One
93  * possibility is for both structures to start with an int which is zero for
94  * one and 1 for the other.
95  *
96  * Note that while the per-directory and per-server configuration records are
97  * available to most of the module handlers, they should be treated as
98  * READ-ONLY by all except the command and merge handlers.  Sometimes handlers
99  * are handed a record that applies to the current location by implication or
100  * inheritance, and modifying it will change the rules for other locations.
101  */
102 typedef struct excfg {
103     int cmode;                  /* Environment to which record applies (directory,
104                                  * server, or combination).
105                                  */
106 #define CONFIG_MODE_SERVER 1
107 #define CONFIG_MODE_DIRECTORY 2
108 #define CONFIG_MODE_COMBO 3     /* Shouldn't ever happen. */
109     int local;                  /* Boolean: "Example" directive declared here? */
110     int congenital;             /* Boolean: did we inherit an "Example"? */
111     char *trace;                /* Pointer to trace string. */
112     char *loc;                  /* Location to which this record applies. */
113 } excfg;
114
115 /*
116  * Let's set up a module-local static cell to point to the accreting callback
117  * trace.  As each API callback is made to us, we'll tack on the particulars
118  * to whatever we've already recorded.  To avoid massive memory bloat as
119  * directories are walked again and again, we record the routine/environment
120  * the first time (non-request context only), and ignore subsequent calls for
121  * the same routine/environment.
122  */
123 static const char *trace = NULL;
124 static apr_table_t *static_calls_made = NULL;
125
126 /*
127  * To avoid leaking memory from pools other than the per-request one, we
128  * allocate a module-private pool, and then use a sub-pool of that which gets
129  * freed each time we modify the trace.  That way previous layers of trace
130  * data don't get lost.
131  */
132 static apr_pool_t *example_pool = NULL;
133 static apr_pool_t *example_subpool = NULL;
134
135 /*
136  * Declare ourselves so the configuration routines can find and know us.
137  * We'll fill it in at the end of the module.
138  */
139 module example_module;
140
141 /*--------------------------------------------------------------------------*/
142 /*                                                                          */
143 /* The following pseudo-prototype declarations illustrate the parameters    */
144 /* passed to command handlers for the different types of directive          */
145 /* syntax.  If an argument was specified in the directive definition        */
146 /* (look for "command_rec" below), it's available to the command handler    */
147 /* via the (void *) info field in the cmd_parms argument passed to the      */
148 /* handler (cmd->info for the examples below).                              */
149 /*                                                                          */
150 /*--------------------------------------------------------------------------*/
151
152 /*
153  * Command handler for a NO_ARGS directive.
154  *
155  * static const char *handle_NO_ARGS(cmd_parms *cmd, void *mconfig);
156  */
157
158 /*
159  * Command handler for a RAW_ARGS directive.  The "args" argument is the text
160  * of the commandline following the directive itself.
161  *
162  * static const char *handle_RAW_ARGS(cmd_parms *cmd, void *mconfig,
163  *                                    const char *args);
164  */
165
166 /*
167  * Command handler for a FLAG directive.  The single parameter is passed in
168  * "bool", which is either zero or not for Off or On respectively.
169  *
170  * static const char *handle_FLAG(cmd_parms *cmd, void *mconfig, int bool);
171  */
172
173 /*
174  * Command handler for a TAKE1 directive.  The single parameter is passed in
175  * "word1".
176  *
177  * static const char *handle_TAKE1(cmd_parms *cmd, void *mconfig,
178  *                                 char *word1);
179  */
180
181 /*
182  * Command handler for a TAKE2 directive.  TAKE2 commands must always have
183  * exactly two arguments.
184  *
185  * static const char *handle_TAKE2(cmd_parms *cmd, void *mconfig,
186  *                                 char *word1, char *word2);
187  */
188
189 /*
190  * Command handler for a TAKE3 directive.  Like TAKE2, these must have exactly
191  * three arguments, or the parser complains and doesn't bother calling us.
192  *
193  * static const char *handle_TAKE3(cmd_parms *cmd, void *mconfig,
194  *                                 char *word1, char *word2, char *word3);
195  */
196
197 /*
198  * Command handler for a TAKE12 directive.  These can take either one or two
199  * arguments.
200  * - word2 is a NULL pointer if no second argument was specified.
201  *
202  * static const char *handle_TAKE12(cmd_parms *cmd, void *mconfig,
203  *                                  char *word1, char *word2);
204  */
205
206 /*
207  * Command handler for a TAKE123 directive.  A TAKE123 directive can be given,
208  * as might be expected, one, two, or three arguments.
209  * - word2 is a NULL pointer if no second argument was specified.
210  * - word3 is a NULL pointer if no third argument was specified.
211  *
212  * static const char *handle_TAKE123(cmd_parms *cmd, void *mconfig,
213  *                                   char *word1, char *word2, char *word3);
214  */
215
216 /*
217  * Command handler for a TAKE13 directive.  Either one or three arguments are
218  * permitted - no two-parameters-only syntax is allowed.
219  * - word2 and word3 are NULL pointers if only one argument was specified.
220  *
221  * static const char *handle_TAKE13(cmd_parms *cmd, void *mconfig,
222  *                                  char *word1, char *word2, char *word3);
223  */
224
225 /*
226  * Command handler for a TAKE23 directive.  At least two and as many as three
227  * arguments must be specified.
228  * - word3 is a NULL pointer if no third argument was specified.
229  *
230  * static const char *handle_TAKE23(cmd_parms *cmd, void *mconfig,
231  *                                  char *word1, char *word2, char *word3);
232  */
233
234 /*
235  * Command handler for a ITERATE directive.
236  * - Handler is called once for each of n arguments given to the directive.
237  * - word1 points to each argument in turn.
238  *
239  * static const char *handle_ITERATE(cmd_parms *cmd, void *mconfig,
240  *                                   char *word1);
241  */
242
243 /*
244  * Command handler for a ITERATE2 directive.
245  * - Handler is called once for each of the second and subsequent arguments
246  *   given to the directive.
247  * - word1 is the same for each call for a particular directive instance (the
248  *   first argument).
249  * - word2 points to each of the second and subsequent arguments in turn.
250  *
251  * static const char *handle_ITERATE2(cmd_parms *cmd, void *mconfig,
252  *                                    char *word1, char *word2);
253  */
254
255 /*--------------------------------------------------------------------------*/
256 /*                                                                          */
257 /* These routines are strictly internal to this module, and support its     */
258 /* operation.  They are not referenced by any external portion of the       */
259 /* server.                                                                  */
260 /*                                                                          */
261 /*--------------------------------------------------------------------------*/
262
263 /*
264  * Locate our directory configuration record for the current request.
265  */
266 static excfg *our_dconfig(request_rec *r)
267 {
268
269     return (excfg *) ap_get_module_config(r->per_dir_config, &example_module);
270 }
271
272 #if 0
273 /*
274  * Locate our server configuration record for the specified server.
275  */
276 static excfg *our_sconfig(server_rec *s)
277 {
278
279     return (excfg *) ap_get_module_config(s->module_config, &example_module);
280 }
281
282 /*
283  * Likewise for our configuration record for the specified request.
284  */
285 static excfg *our_rconfig(request_rec *r)
286 {
287
288     return (excfg *) ap_get_module_config(r->request_config, &example_module);
289 }
290 #endif
291
292 /*
293  * This routine sets up some module-wide cells if they haven't been already.
294  */
295 static void setup_module_cells(void)
296 {
297     /*
298      * If we haven't already allocated our module-private pool, do so now.
299      */
300     if (example_pool == NULL) {
301         apr_pool_create(&example_pool, NULL);
302     };
303     /*
304      * Likewise for the apr_table_t of routine/environment pairs we visit outside of
305      * request context.
306      */
307     if (static_calls_made == NULL) {
308         static_calls_made = apr_table_make(example_pool, 16);
309     };
310 }
311
312 /*
313  * This routine is used to add a trace of a callback to the list.  We're
314  * passed the server record (if available), the request record (if available),
315  * a pointer to our private configuration record (if available) for the
316  * environment to which the callback is supposed to apply, and some text.  We
317  * turn this into a textual representation and add it to the tail of the list.
318  * The list can be displayed by the example_handler() routine.
319  *
320  * If the call occurs within a request context (i.e., we're passed a request
321  * record), we put the trace into the request apr_pool_t and attach it to the
322  * request via the notes mechanism.  Otherwise, the trace gets added
323  * to the static (non-request-specific) list.
324  *
325  * Note that the r->notes apr_table_t is only for storing strings; if you need to
326  * maintain per-request data of any other type, you need to use another
327  * mechanism.
328  */
329
330 #define TRACE_NOTE "example-trace"
331
332 static void trace_add(server_rec *s, request_rec *r, excfg *mconfig,
333                       const char *note)
334 {
335
336     const char *sofar;
337     char *addon;
338     char *where;
339     apr_pool_t *p;
340     const char *trace_copy;
341
342     /*
343      * Make sure our pools and tables are set up - we need 'em.
344      */
345     setup_module_cells();
346     /*
347      * Now, if we're in request-context, we use the request pool.
348      */
349     if (r != NULL) {
350         p = r->pool;
351         if ((trace_copy = apr_table_get(r->notes, TRACE_NOTE)) == NULL) {
352             trace_copy = "";
353         }
354     }
355     else {
356         /*
357          * We're not in request context, so the trace gets attached to our
358          * module-wide pool.  We do the create/destroy every time we're called
359          * in non-request context; this avoids leaking memory in some of
360          * the subsequent calls that allocate memory only once (such as the
361          * key formation below).
362          *
363          * Make a new sub-pool and copy any existing trace to it.  Point the
364          * trace cell at the copied value.
365          */
366         apr_pool_create(&p, example_pool);
367         if (trace != NULL) {
368             trace = apr_pstrdup(p, trace);
369         }
370         /*
371          * Now, if we have a sub-pool from before, nuke it and replace with
372          * the one we just allocated.
373          */
374         if (example_subpool != NULL) {
375             apr_pool_destroy(example_subpool);
376         }
377         example_subpool = p;
378         trace_copy = trace;
379     }
380     /*
381      * If we weren't passed a configuration record, we can't figure out to
382      * what location this call applies.  This only happens for co-routines
383      * that don't operate in a particular directory or server context.  If we
384      * got a valid record, extract the location (directory or server) to which
385      * it applies.
386      */
387     where = (mconfig != NULL) ? mconfig->loc : "nowhere";
388     where = (where != NULL) ? where : "";
389     /*
390      * Now, if we're not in request context, see if we've been called with
391      * this particular combination before.  The apr_table_t is allocated in the
392      * module's private pool, which doesn't get destroyed.
393      */
394     if (r == NULL) {
395         char *key;
396
397         key = apr_pstrcat(p, note, ":", where, NULL);
398         if (apr_table_get(static_calls_made, key) != NULL) {
399             /*
400              * Been here, done this.
401              */
402             return;
403         }
404         else {
405             /*
406              * First time for this combination of routine and environment -
407              * log it so we don't do it again.
408              */
409             apr_table_set(static_calls_made, key, "been here");
410         }
411     }
412     addon = apr_pstrcat(p, "   <LI>\n", "    <DL>\n", "     <DT><SAMP>",
413                     note, "</SAMP>\n", "     </DT>\n", "     <DD><SAMP>[",
414                     where, "]</SAMP>\n", "     </DD>\n", "    </DL>\n",
415                     "   </LI>\n", NULL);
416     sofar = (trace_copy == NULL) ? "" : trace_copy;
417     trace_copy = apr_pstrcat(p, sofar, addon, NULL);
418     if (r != NULL) {
419         apr_table_set(r->notes, TRACE_NOTE, trace_copy);
420     }
421     else {
422         trace = trace_copy;
423     }
424     /*
425      * You *could* change the following if you wanted to see the calling
426      * sequence reported in the server's error_log, but beware - almost all of
427      * these co-routines are called for every single request, and the impact
428      * on the size (and readability) of the error_log is considerable.
429      */
430 #define EXAMPLE_LOG_EACH 0
431     if (EXAMPLE_LOG_EACH && (s != NULL)) {
432         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, "mod_example: %s", note);
433     }
434 }
435
436 /*--------------------------------------------------------------------------*/
437 /* We prototyped the various syntax for command handlers (routines that     */
438 /* are called when the configuration parser detects a directive declared    */
439 /* by our module) earlier.  Now we actually declare a "real" routine that   */
440 /* will be invoked by the parser when our "real" directive is               */
441 /* encountered.                                                             */
442 /*                                                                          */
443 /* If a command handler encounters a problem processing the directive, it   */
444 /* signals this fact by returning a non-NULL pointer to a string            */
445 /* describing the problem.                                                  */
446 /*                                                                          */
447 /* The magic return value DECLINE_CMD is used to deal with directives       */
448 /* that might be declared by multiple modules.  If the command handler      */
449 /* returns NULL, the directive was processed; if it returns DECLINE_CMD,    */
450 /* the next module (if any) that declares the directive is given a chance   */
451 /* at it.  If it returns any other value, it's treated as the text of an    */
452 /* error message.                                                           */
453 /*--------------------------------------------------------------------------*/
454 /* 
455  * Command handler for the NO_ARGS "Example" directive.  All we do is mark the
456  * call in the trace log, and flag the applicability of the directive to the
457  * current location in that location's configuration record.
458  */
459 static const char *cmd_example(cmd_parms *cmd, void *mconfig)
460 {
461
462     excfg *cfg = (excfg *) mconfig;
463
464     /*
465      * "Example Wuz Here"
466      */
467     cfg->local = 1;
468     trace_add(cmd->server, NULL, cfg, "cmd_example()");
469     return NULL;
470 }
471
472 /*--------------------------------------------------------------------------*/
473 /*                                                                          */
474 /* Now we declare our content handlers, which are invoked when the server   */
475 /* encounters a document which our module is supposed to have a chance to   */
476 /* see.  (See mod_mime's SetHandler and AddHandler directives, and the      */
477 /* mod_info and mod_status examples, for more details.)                     */
478 /*                                                                          */
479 /* Since content handlers are dumping data directly into the connexion      */
480 /* (using the r*() routines, such as rputs() and rprintf()) without         */
481 /* intervention by other parts of the server, they need to make             */
482 /* sure any accumulated HTTP headers are sent first.  This is done by       */
483 /* calling send_http_header().  Otherwise, no header will be sent at all,   */
484 /* and the output sent to the client will actually be HTTP-uncompliant.     */
485 /*--------------------------------------------------------------------------*/
486 /* 
487  * Sample content handler.  All this does is display the call list that has
488  * been built up so far.
489  *
490  * The return value instructs the caller concerning what happened and what to
491  * do next:
492  *  OK ("we did our thing")
493  *  DECLINED ("this isn't something with which we want to get involved")
494  *  HTTP_mumble ("an error status should be reported")
495  */
496 static int example_handler(request_rec *r)
497 {
498
499     excfg *dcfg;
500
501     dcfg = our_dconfig(r);
502     trace_add(r->server, r, dcfg, "example_handler()");
503     /*
504      * We're about to start sending content, so we need to force the HTTP
505      * headers to be sent at this point.  Otherwise, no headers will be sent
506      * at all.  We can set any we like first, of course.  **NOTE** Here's
507      * where you set the "Content-type" header, and you do so by putting it in
508      * r->content_type, *not* r->headers_out("Content-type").  If you don't
509      * set it, it will be filled in with the server's default type (typically
510      * "text/plain").  You *must* also ensure that r->content_type is lower
511      * case.
512      *
513      * We also need to start a timer so the server can know if the connexion
514      * is broken.
515      */
516     r->content_type = "text/html";
517     ap_send_http_header(r);
518     /*
519      * If we're only supposed to send header information (HEAD request), we're
520      * already there.
521      */
522     if (r->header_only) {
523         return OK;
524     }
525
526     /*
527      * Now send our actual output.  Since we tagged this as being
528      * "text/html", we need to embed any HTML.
529      */
530     ap_rputs(DOCTYPE_HTML_3_2, r);
531     ap_rputs("<HTML>\n", r);
532     ap_rputs(" <HEAD>\n", r);
533     ap_rputs("  <TITLE>mod_example Module Content-Handler Output\n", r);
534     ap_rputs("  </TITLE>\n", r);
535     ap_rputs(" </HEAD>\n", r);
536     ap_rputs(" <BODY>\n", r);
537     ap_rputs("  <H1><SAMP>mod_example</SAMP> Module Content-Handler Output\n", r);
538     ap_rputs("  </H1>\n", r);
539     ap_rputs("  <P>\n", r);
540     ap_rprintf(r, "  Apache HTTP Server version: \"%s\"\n",
541             ap_get_server_version());
542     ap_rputs("  <BR>\n", r);
543     ap_rprintf(r, "  Server built: \"%s\"\n", ap_get_server_built());
544     ap_rputs("  </P>\n", r);;
545     ap_rputs("  <P>\n", r);
546     ap_rputs("  The format for the callback trace is:\n", r);
547     ap_rputs("  </P>\n", r);
548     ap_rputs("  <DL>\n", r);
549     ap_rputs("   <DT><EM>n</EM>.<SAMP>&lt;routine-name&gt;", r);
550     ap_rputs("(&lt;routine-data&gt;)</SAMP>\n", r);
551     ap_rputs("   </DT>\n", r);
552     ap_rputs("   <DD><SAMP>[&lt;applies-to&gt;]</SAMP>\n", r);
553     ap_rputs("   </DD>\n", r);
554     ap_rputs("  </DL>\n", r);
555     ap_rputs("  <P>\n", r);
556     ap_rputs("  The <SAMP>&lt;routine-data&gt;</SAMP> is supplied by\n", r);
557     ap_rputs("  the routine when it requests the trace,\n", r);
558     ap_rputs("  and the <SAMP>&lt;applies-to&gt;</SAMP> is extracted\n", r);
559     ap_rputs("  from the configuration record at the time of the trace.\n", r);
560     ap_rputs("  <STRONG>SVR()</STRONG> indicates a server environment\n", r);
561     ap_rputs("  (blank means the main or default server, otherwise it's\n", r);
562     ap_rputs("  the name of the VirtualHost); <STRONG>DIR()</STRONG>\n", r);
563     ap_rputs("  indicates a location in the URL or filesystem\n", r);
564     ap_rputs("  namespace.\n", r);
565     ap_rputs("  </P>\n", r);
566     ap_rprintf(r, "  <H2>Static callbacks so far:</H2>\n  <OL>\n%s  </OL>\n",
567             trace);
568     ap_rputs("  <H2>Request-specific callbacks so far:</H2>\n", r);
569     ap_rprintf(r, "  <OL>\n%s  </OL>\n", apr_table_get(r->notes, TRACE_NOTE));
570     ap_rputs("  <H2>Environment for <EM>this</EM> call:</H2>\n", r);
571     ap_rputs("  <UL>\n", r);
572     ap_rprintf(r, "   <LI>Applies-to: <SAMP>%s</SAMP>\n   </LI>\n", dcfg->loc);
573     ap_rprintf(r, "   <LI>\"Example\" directive declared here: %s\n   </LI>\n",
574             (dcfg->local ? "YES" : "NO"));
575     ap_rprintf(r, "   <LI>\"Example\" inherited: %s\n   </LI>\n",
576             (dcfg->congenital ? "YES" : "NO"));
577     ap_rputs("  </UL>\n", r);
578     ap_rputs(" </BODY>\n", r);
579     ap_rputs("</HTML>\n", r);
580     /*
581      * We're all done, so cancel the timeout we set.  Since this is probably
582      * the end of the request we *could* assume this would be done during
583      * post-processing - but it's possible that another handler might be
584      * called and inherit our outstanding timer.  Not good; to each its own.
585      */
586     /*
587      * We did what we wanted to do, so tell the rest of the server we
588      * succeeded.
589      */
590     return OK;
591 }
592
593 /*--------------------------------------------------------------------------*/
594 /*                                                                          */
595 /* Now let's declare routines for each of the callback phase in order.      */
596 /* (That's the order in which they're listed in the callback list, *not     */
597 /* the order in which the server calls them!  See the command_rec           */
598 /* declaration near the bottom of this file.)  Note that these may be       */
599 /* called for situations that don't relate primarily to our function - in   */
600 /* other words, the fixup handler shouldn't assume that the request has     */
601 /* to do with "example" stuff.                                              */
602 /*                                                                          */
603 /* With the exception of the content handler, all of our routines will be   */
604 /* called for each request, unless an earlier handler from another module   */
605 /* aborted the sequence.                                                    */
606 /*                                                                          */
607 /* Handlers that are declared as "int" can return the following:            */
608 /*                                                                          */
609 /*  OK          Handler accepted the request and did its thing with it.     */
610 /*  DECLINED    Handler took no action.                                     */
611 /*  HTTP_mumble Handler looked at request and found it wanting.             */
612 /*                                                                          */
613 /* What the server does after calling a module handler depends upon the     */
614 /* handler's return value.  In all cases, if the handler returns            */
615 /* DECLINED, the server will continue to the next module with an handler    */
616 /* for the current phase.  However, if the handler return a non-OK,         */
617 /* non-DECLINED status, the server aborts the request right there.  If      */
618 /* the handler returns OK, the server's next action is phase-specific;      */
619 /* see the individual handler comments below for details.                   */
620 /*                                                                          */
621 /*--------------------------------------------------------------------------*/
622 /* 
623  * This function is called during server initialisation.  Any information
624  * that needs to be recorded must be in static cells, since there's no
625  * configuration record.
626  *
627  * There is no return value.
628  */
629
630 /*
631  * All our module initialiser does is add its trace to the log.
632  */
633 static void example_init(apr_pool_t *p, apr_pool_t *ptemp, 
634                          apr_pool_t *plog, server_rec *s)
635 {
636
637     char *note;
638     char *sname = s->server_hostname;
639
640     /*
641      * Set up any module cells that ought to be initialised.
642      */
643     setup_module_cells();
644     /*
645      * The arbitrary text we add to our trace entry indicates for which server
646      * we're being called.
647      */
648     sname = (sname != NULL) ? sname : "";
649     note = apr_pstrcat(p, "example_init(", sname, ")", NULL);
650     trace_add(s, NULL, NULL, note);
651 }
652
653 /* 
654  * This function is called when an heavy-weight process (such as a child) is
655  * being run down or destroyed.  As with the child initialisation function,
656  * any information that needs to be recorded must be in static cells, since
657  * there's no configuration record.
658  *
659  * There is no return value.
660  */
661
662 /*
663  * All our process-death routine does is add its trace to the log.
664  */
665 static apr_status_t example_child_exit(void *sv)
666 {
667     server_rec *s = sv;
668     char *note;
669     char *sname = s->server_hostname;
670
671     /*
672      * The arbitrary text we add to our trace entry indicates for which server
673      * we're being called.
674      */
675     sname = (sname != NULL) ? sname : "";
676     note = apr_pstrcat(s->process->pool, "example_child_exit(", sname, ")", NULL);
677     trace_add(s, NULL, NULL, note);
678     return APR_SUCCESS;
679 }
680
681 /* 
682  * This function is called during server initialisation when an heavy-weight
683  * process (such as a child) is being initialised.  As with the
684  * module initialisation function, any information that needs to be recorded
685  * must be in static cells, since there's no configuration record.
686  *
687  * There is no return value.
688  */
689
690 /*
691  * All our process initialiser does is add its trace to the log.
692  */
693 static void example_child_init(apr_pool_t *p, server_rec *s)
694 {
695
696     char *note;
697     char *sname = s->server_hostname;
698
699     /*
700      * Set up any module cells that ought to be initialised.
701      */
702     setup_module_cells();
703     /*
704      * The arbitrary text we add to our trace entry indicates for which server
705      * we're being called.
706      */
707     sname = (sname != NULL) ? sname : "";
708     note = apr_pstrcat(p, "example_child_init(", sname, ")", NULL);
709     trace_add(s, NULL, NULL, note);
710
711     apr_pool_cleanup_register(p, s, example_child_exit, example_child_exit);
712 }
713
714 /*
715  * This function gets called to create a per-directory configuration
716  * record.  This will be called for the "default" server environment, and for
717  * each directory for which the parser finds any of our directives applicable.
718  * If a directory doesn't have any of our directives involved (i.e., they
719  * aren't in the .htaccess file, or a <Location>, <Directory>, or related
720  * block), this routine will *not* be called - the configuration for the
721  * closest ancestor is used.
722  *
723  * The return value is a pointer to the created module-specific
724  * structure.
725  */
726 static void *example_create_dir_config(apr_pool_t *p, char *dirspec)
727 {
728
729     excfg *cfg;
730     char *dname = dirspec;
731
732     /*
733      * Allocate the space for our record from the pool supplied.
734      */
735     cfg = (excfg *) apr_pcalloc(p, sizeof(excfg));
736     /*
737      * Now fill in the defaults.  If there are any `parent' configuration
738      * records, they'll get merged as part of a separate callback.
739      */
740     cfg->local = 0;
741     cfg->congenital = 0;
742     cfg->cmode = CONFIG_MODE_DIRECTORY;
743     /*
744      * Finally, add our trace to the callback list.
745      */
746     dname = (dname != NULL) ? dname : "";
747     cfg->loc = apr_pstrcat(p, "DIR(", dname, ")", NULL);
748     trace_add(NULL, NULL, cfg, "example_create_dir_config()");
749     return (void *) cfg;
750 }
751
752 /*
753  * This function gets called to merge two per-directory configuration
754  * records.  This is typically done to cope with things like .htaccess files
755  * or <Location> directives for directories that are beneath one for which a
756  * configuration record was already created.  The routine has the
757  * responsibility of creating a new record and merging the contents of the
758  * other two into it appropriately.  If the module doesn't declare a merge
759  * routine, the record for the closest ancestor location (that has one) is
760  * used exclusively.
761  *
762  * The routine MUST NOT modify any of its arguments!
763  *
764  * The return value is a pointer to the created module-specific structure
765  * containing the merged values.
766  */
767 static void *example_merge_dir_config(apr_pool_t *p, void *parent_conf,
768                                       void *newloc_conf)
769 {
770
771     excfg *merged_config = (excfg *) apr_pcalloc(p, sizeof(excfg));
772     excfg *pconf = (excfg *) parent_conf;
773     excfg *nconf = (excfg *) newloc_conf;
774     char *note;
775
776     /*
777      * Some things get copied directly from the more-specific record, rather
778      * than getting merged.
779      */
780     merged_config->local = nconf->local;
781     merged_config->loc = apr_pstrdup(p, nconf->loc);
782     /*
783      * Others, like the setting of the `congenital' flag, get ORed in.  The
784      * setting of that particular flag, for instance, is TRUE if it was ever
785      * true anywhere in the upstream configuration.
786      */
787     merged_config->congenital = (pconf->congenital | pconf->local);
788     /*
789      * If we're merging records for two different types of environment (server
790      * and directory), mark the new record appropriately.  Otherwise, inherit
791      * the current value.
792      */
793     merged_config->cmode =
794         (pconf->cmode == nconf->cmode) ? pconf->cmode : CONFIG_MODE_COMBO;
795     /*
796      * Now just record our being called in the trace list.  Include the
797      * locations we were asked to merge.
798      */
799     note = apr_pstrcat(p, "example_merge_dir_config(\"", pconf->loc, "\",\"",
800                    nconf->loc, "\")", NULL);
801     trace_add(NULL, NULL, merged_config, note);
802     return (void *) merged_config;
803 }
804
805 /*
806  * This function gets called to create a per-server configuration
807  * record.  It will always be called for the "default" server.
808  *
809  * The return value is a pointer to the created module-specific
810  * structure.
811  */
812 static void *example_create_server_config(apr_pool_t *p, server_rec *s)
813 {
814
815     excfg *cfg;
816     char *sname = s->server_hostname;
817
818     /*
819      * As with the example_create_dir_config() reoutine, we allocate and fill
820      * in an empty record.
821      */
822     cfg = (excfg *) apr_pcalloc(p, sizeof(excfg));
823     cfg->local = 0;
824     cfg->congenital = 0;
825     cfg->cmode = CONFIG_MODE_SERVER;
826     /*
827      * Note that we were called in the trace list.
828      */
829     sname = (sname != NULL) ? sname : "";
830     cfg->loc = apr_pstrcat(p, "SVR(", sname, ")", NULL);
831     trace_add(s, NULL, cfg, "example_create_server_config()");
832     return (void *) cfg;
833 }
834
835 /*
836  * This function gets called to merge two per-server configuration
837  * records.  This is typically done to cope with things like virtual hosts and
838  * the default server configuration  The routine has the responsibility of
839  * creating a new record and merging the contents of the other two into it
840  * appropriately.  If the module doesn't declare a merge routine, the more
841  * specific existing record is used exclusively.
842  *
843  * The routine MUST NOT modify any of its arguments!
844  *
845  * The return value is a pointer to the created module-specific structure
846  * containing the merged values.
847  */
848 static void *example_merge_server_config(apr_pool_t *p, void *server1_conf,
849                                          void *server2_conf)
850 {
851
852     excfg *merged_config = (excfg *) apr_pcalloc(p, sizeof(excfg));
853     excfg *s1conf = (excfg *) server1_conf;
854     excfg *s2conf = (excfg *) server2_conf;
855     char *note;
856
857     /*
858      * Our inheritance rules are our own, and part of our module's semantics.
859      * Basically, just note whence we came.
860      */
861     merged_config->cmode =
862         (s1conf->cmode == s2conf->cmode) ? s1conf->cmode : CONFIG_MODE_COMBO;
863     merged_config->local = s2conf->local;
864     merged_config->congenital = (s1conf->congenital | s1conf->local);
865     merged_config->loc = apr_pstrdup(p, s2conf->loc);
866     /*
867      * Trace our call, including what we were asked to merge.
868      */
869     note = apr_pstrcat(p, "example_merge_server_config(\"", s1conf->loc, "\",\"",
870                    s2conf->loc, "\")", NULL);
871     trace_add(NULL, NULL, merged_config, note);
872     return (void *) merged_config;
873 }
874
875 /*
876  * This routine is called after the request has been read but before any other
877  * phases have been processed.  This allows us to make decisions based upon
878  * the input header fields.
879  *
880  * The return value is OK, DECLINED, or HTTP_mumble.  If we return OK, no
881  * further modules are called for this phase.
882  */
883 static int example_post_read_request(request_rec *r)
884 {
885
886     excfg *cfg;
887
888     cfg = our_dconfig(r);
889     /*
890      * We don't actually *do* anything here, except note the fact that we were
891      * called.
892      */
893     trace_add(r->server, r, cfg, "example_post_read_request()");
894     return DECLINED;
895 }
896
897 /*
898  * This routine gives our module an opportunity to translate the URI into an
899  * actual filename.  If we don't do anything special, the server's default
900  * rules (Alias directives and the like) will continue to be followed.
901  *
902  * The return value is OK, DECLINED, or HTTP_mumble.  If we return OK, no
903  * further modules are called for this phase.
904  */
905 static int example_translate_handler(request_rec *r)
906 {
907
908     excfg *cfg;
909
910     cfg = our_dconfig(r);
911     /*
912      * We don't actually *do* anything here, except note the fact that we were
913      * called.
914      */
915     trace_add(r->server, r, cfg, "example_translate_handler()");
916     return DECLINED;
917 }
918
919 /*
920  * This routine is called to check the authentication information sent with
921  * the request (such as looking up the user in a database and verifying that
922  * the [encrypted] password sent matches the one in the database).
923  *
924  * The return value is OK, DECLINED, or some HTTP_mumble error (typically
925  * HTTP_UNAUTHORIZED).  If we return OK, no other modules are given a chance
926  * at the request during this phase.
927  */
928 static int example_check_user_id(request_rec *r)
929 {
930
931     excfg *cfg;
932
933     cfg = our_dconfig(r);
934     /*
935      * Don't do anything except log the call.
936      */
937     trace_add(r->server, r, cfg, "example_check_user_id()");
938     return DECLINED;
939 }
940
941 /*
942  * This routine is called to check to see if the resource being requested
943  * requires authorisation.
944  *
945  * The return value is OK, DECLINED, or HTTP_mumble.  If we return OK, no
946  * other modules are called during this phase.
947  *
948  * If *all* modules return DECLINED, the request is aborted with a server
949  * error.
950  */
951 static int example_auth_checker(request_rec *r)
952 {
953
954     excfg *cfg;
955
956     cfg = our_dconfig(r);
957     /*
958      * Log the call and return OK, or access will be denied (even though we
959      * didn't actually do anything).
960      */
961     trace_add(r->server, r, cfg, "example_auth_checker()");
962     return DECLINED;
963 }
964
965 /*
966  * This routine is called to check for any module-specific restrictions placed
967  * upon the requested resource.  (See the mod_access module for an example.)
968  *
969  * The return value is OK, DECLINED, or HTTP_mumble.  All modules with an
970  * handler for this phase are called regardless of whether their predecessors
971  * return OK or DECLINED.  The first one to return any other status, however,
972  * will abort the sequence (and the request) as usual.
973  */
974 static int example_access_checker(request_rec *r)
975 {
976
977     excfg *cfg;
978
979     cfg = our_dconfig(r);
980     trace_add(r->server, r, cfg, "example_access_checker()");
981     return DECLINED;
982 }
983
984 /*
985  * This routine is called to determine and/or set the various document type
986  * information bits, like Content-type (via r->content_type), language, et
987  * cetera.
988  *
989  * The return value is OK, DECLINED, or HTTP_mumble.  If we return OK, no
990  * further modules are given a chance at the request for this phase.
991  */
992 static int example_type_checker(request_rec *r)
993 {
994
995     excfg *cfg;
996
997     cfg = our_dconfig(r);
998     /*
999      * Log the call, but don't do anything else - and report truthfully that
1000      * we didn't do anything.
1001      */
1002     trace_add(r->server, r, cfg, "example_type_checker()");
1003     return DECLINED;
1004 }
1005
1006 /*
1007  * This routine is called to perform any module-specific fixing of header
1008  * fields, et cetera.  It is invoked just before any content-handler.
1009  *
1010  * The return value is OK, DECLINED, or HTTP_mumble.  If we return OK, the
1011  * server will still call any remaining modules with an handler for this
1012  * phase.
1013  */
1014 static int example_fixer_upper(request_rec *r)
1015 {
1016
1017     excfg *cfg;
1018
1019     cfg = our_dconfig(r);
1020     /*
1021      * Log the call and exit.
1022      */
1023     trace_add(r->server, r, cfg, "example_fixer_upper()");
1024     return OK;
1025 }
1026
1027 /*
1028  * This routine is called to perform any module-specific logging activities
1029  * over and above the normal server things.
1030  *
1031  * The return value is OK, DECLINED, or HTTP_mumble.  If we return OK, any
1032  * remaining modules with an handler for this phase will still be called.
1033  */
1034 static int example_logger(request_rec *r)
1035 {
1036
1037     excfg *cfg;
1038
1039     cfg = our_dconfig(r);
1040     trace_add(r->server, r, cfg, "example_logger()");
1041     return DECLINED;
1042 }
1043
1044 /*
1045  * This routine is called to give the module a chance to look at the request
1046  * headers and take any appropriate specific actions early in the processing
1047  * sequence.
1048  *
1049  * The return value is OK, DECLINED, or HTTP_mumble.  If we return OK, any
1050  * remaining modules with handlers for this phase will still be called.
1051  */
1052 static int example_header_parser(request_rec *r)
1053 {
1054
1055     excfg *cfg;
1056
1057     cfg = our_dconfig(r);
1058     trace_add(r->server, r, cfg, "example_header_parser()");
1059     return DECLINED;
1060 }
1061
1062 /*--------------------------------------------------------------------------*/
1063 /*                                                                          */
1064 /* Which functions are responsible for which hooks in the server.           */
1065 /*                                                                          */
1066 /*--------------------------------------------------------------------------*/
1067 /* 
1068  * Each function our module provides to handle a particular hook is
1069  * specified here.  The functions are registered using 
1070  * ap_hook_foo(name, predecessors, successors, position)
1071  * where foo is the name of the hook.
1072  *
1073  * The args are as follows:
1074  * name         -> the name of the function to call.
1075  * predecessors -> a list of modules whose calls to this hook must come 
1076  *                 before this module.
1077  * successors   -> a list of modules whose calls to this hook must come 
1078  *                 after this module.
1079  * position     -> The relative position of this module.  One of APR_HOOK_FIRST,
1080  *                 APR_HOOK_MIDDLE, or APR_HOOK_LAST.  Most modules will use
1081  *                 APR_HOOK_MIDDLE.  If multiple modules use the same relative
1082  *                 position, Apache will determine which to call first.
1083  *                 If your module relies on another module to run first,
1084  *                 or another module running after yours, use the 
1085  *                 predecessors and/or successors.
1086  *
1087  * The number in brackets indicates the order in which the routine is called
1088  * during request processing.  Note that not all routines are necessarily
1089  * called (such as if a resource doesn't have access restrictions).
1090  * The actual delivery of content to the browser [9] is not handled by
1091  * a hook; see the handler declarations below.
1092  */
1093 static void example_register_hooks(apr_pool_t *p)
1094 {
1095     /* module initializer */
1096     ap_hook_post_config(example_init,
1097                         NULL, NULL, APR_HOOK_MIDDLE);
1098     /* [1] post read_request handling */
1099     ap_hook_post_read_request(example_post_read_request,
1100                               NULL, NULL, APR_HOOK_MIDDLE);
1101     /* [2] filename-to-URI translation */
1102     ap_hook_translate_name(example_translate_handler,
1103                            NULL, NULL, APR_HOOK_MIDDLE);
1104     /* [3] header parser */
1105     ap_hook_header_parser(example_header_parser,
1106                           NULL, NULL, APR_HOOK_MIDDLE);
1107     /* [4] check access by host address */
1108     ap_hook_access_checker(example_access_checker,
1109                            NULL, NULL, APR_HOOK_MIDDLE);
1110     /* [5] check/validate user_id */
1111     ap_hook_check_user_id(example_check_user_id,
1112                           NULL, NULL, APR_HOOK_MIDDLE);
1113     /* [6] check user_id is valid *here* */
1114     ap_hook_auth_checker(example_auth_checker,
1115                          NULL, NULL, APR_HOOK_MIDDLE);
1116     /* [7] MIME type checker/setter */
1117     ap_hook_type_checker(example_type_checker,
1118                          NULL, NULL, APR_HOOK_MIDDLE);
1119     /* [8] fixups */
1120     ap_hook_fixups(example_fixer_upper,
1121                    NULL, NULL, APR_HOOK_MIDDLE);
1122     /* [9] is for the handlers; see below */
1123
1124     /* [10] logger */
1125     ap_hook_log_transaction(example_logger,
1126                             NULL, NULL, APR_HOOK_MIDDLE);
1127     /* process initializer */
1128     ap_hook_child_init(example_child_init,
1129                        NULL, NULL, APR_HOOK_MIDDLE);
1130 }
1131
1132 /*--------------------------------------------------------------------------*/
1133 /*                                                                          */
1134 /* All of the routines have been declared now.  Here's the list of          */
1135 /* directives specific to our module, and information about where they      */
1136 /* may appear and how the command parser should pass them to us for         */
1137 /* processing.  Note that care must be taken to ensure that there are NO    */
1138 /* collisions of directive names between modules.                           */
1139 /*                                                                          */
1140 /*--------------------------------------------------------------------------*/
1141 /* 
1142  * List of directives specific to our module.
1143  */
1144 static const command_rec example_cmds[] =
1145 {
1146     AP_INIT_NO_ARGS(
1147         "Example",                          /* directive name */
1148         cmd_example,                        /* config action routine */
1149         NULL,                               /* argument to include in call */
1150         OR_OPTIONS,                         /* where available */
1151         "Example directive - no arguments"  /* directive description */
1152     ),
1153     {NULL}
1154 };
1155
1156 /*--------------------------------------------------------------------------*/
1157 /*                                                                          */
1158 /* Now the list of content handlers available from this module.             */
1159 /*                                                                          */
1160 /*--------------------------------------------------------------------------*/
1161 /* 
1162  * List of content handlers our module supplies.  Each handler is defined by
1163  * two parts: a name by which it can be referenced (such as by
1164  * {Add,Set}Handler), and the actual routine name.  The list is terminated by
1165  * a NULL block, since it can be of variable length.
1166  *
1167  * Note that content-handlers are invoked on a most-specific to least-specific
1168  * basis; that is, a handler that is declared for "text/plain" will be
1169  * invoked before one that was declared for "text / *".  Note also that
1170  * if a content-handler returns anything except DECLINED, no other
1171  * content-handlers will be called.
1172  */
1173 static const handler_rec example_handlers[] =
1174 {
1175     {"example-handler", example_handler},
1176     {NULL}
1177 };
1178
1179 /*--------------------------------------------------------------------------*/
1180 /*                                                                          */
1181 /* Finally, the list of callback routines and data structures that provide  */
1182 /* the static hooks into our module from the other parts of the server.     */
1183 /*                                                                          */
1184 /*--------------------------------------------------------------------------*/
1185 /* 
1186  * Module definition for configuration.  If a particular callback is not
1187  * needed, replace its routine name below with the word NULL.
1188  */
1189 module example_module =
1190 {
1191     STANDARD20_MODULE_STUFF,
1192     example_create_dir_config,    /* per-directory config creator */
1193     example_merge_dir_config,     /* dir config merger */
1194     example_create_server_config, /* server config creator */
1195     example_merge_server_config,  /* server config merger */
1196     example_cmds,                 /* command table */
1197     example_handlers,             /* list of content delivery handlers */
1198     example_register_hooks,       /* set up other request processing hooks */
1199 };