]> granicus.if.org Git - apache/blob - modules/generators/mod_autoindex.c
PR:
[apache] / modules / generators / mod_autoindex.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000 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  * mod_autoindex.c: Handles the on-the-fly html index generation
61  * 
62  * Rob McCool
63  * 3/23/93
64  * 
65  * Adapted to Apache by rst.
66  *
67  * Version sort added by Martin Pool <mbp@humbug.org.au>. */
68
69 #include "ap_config.h"
70 #include "httpd.h"
71 #include "http_config.h"
72 #include "http_core.h"
73 #include "http_request.h"
74 #include "http_protocol.h"
75 #include "http_log.h"
76 #include "http_main.h"
77 #include "util_script.h"
78 #include "apr_fnmatch.h"
79 #include "apr_strnatcmp.h"
80 #ifdef HAVE_STRING_H
81 #include <string.h>
82 #endif
83
84 module MODULE_VAR_EXPORT autoindex_module;
85
86 /****************************************************************
87  *
88  * Handling configuration directives...
89  */
90
91 #define HRULE 1
92 #define NO_HRULE 0
93 #define FRONT_MATTER 1
94 #define END_MATTER 0
95
96 #define FANCY_INDEXING 1        /* Indexing options */
97 #define ICONS_ARE_LINKS 2
98 #define SCAN_HTML_TITLES 4
99 #define SUPPRESS_LAST_MOD 8
100 #define SUPPRESS_SIZE 16
101 #define SUPPRESS_DESC 32
102 #define SUPPRESS_PREAMBLE 64
103 #define SUPPRESS_COLSORT 128
104 #define NO_OPTIONS 256
105 #define VERSION_SORT    512
106
107 #define K_PAD 1
108 #define K_NOPAD 0
109
110 #define K_NOADJUST 0
111 #define K_ADJUST 1
112 #define K_UNSET 2
113
114 /*
115  * Define keys for sorting.
116  */
117 #define K_NAME 'N'              /* Sort by file name (default) */
118 #define K_LAST_MOD 'M'          /* Last modification date */
119 #define K_SIZE 'S'              /* Size (absolute, not as displayed) */
120 #define K_DESC 'D'              /* Description */
121
122 #define D_ASCENDING 'A'
123 #define D_DESCENDING 'D'
124
125 /*
126  * These are the dimensions of the default icons supplied with Apache.
127  */
128 #define DEFAULT_ICON_WIDTH 20
129 #define DEFAULT_ICON_HEIGHT 22
130
131 /*
132  * Other default dimensions.
133  */
134 #define DEFAULT_NAME_WIDTH 23
135
136 struct item {
137     char *type;
138     char *apply_to;
139     char *apply_path;
140     char *data;
141 };
142
143 typedef struct ai_desc_t {
144     char *pattern;
145     char *description;
146     int full_path;
147     int wildcards;
148 } ai_desc_t;
149
150 typedef struct autoindex_config_struct {
151
152     char *default_icon;
153     int opts;
154     int incremented_opts;
155     int decremented_opts;
156     int name_width;
157     int name_adjust;
158     int icon_width;
159     int icon_height;
160     char *default_order;
161
162     ap_array_header_t *icon_list;
163     ap_array_header_t *alt_list;
164     ap_array_header_t *desc_list;
165     ap_array_header_t *ign_list;
166     ap_array_header_t *hdr_list;
167     ap_array_header_t *rdme_list;
168
169 } autoindex_config_rec;
170
171 static char c_by_encoding, c_by_type, c_by_path;
172
173 #define BY_ENCODING &c_by_encoding
174 #define BY_TYPE &c_by_type
175 #define BY_PATH &c_by_path
176
177 /*
178  * Return true if the specified string refers to the parent directory (i.e.,
179  * matches ".." or "../").  Hopefully this one call is significantly less
180  * expensive than multiple strcmp() calls.
181  */
182 static ap_inline int is_parent(const char *name)
183 {
184     /*
185      * Now, IFF the first two bytes are dots, and the third byte is either
186      * EOS (\0) or a slash followed by EOS, we have a match.
187      */
188     if (((name[0] == '.') && (name[1] == '.'))
189         && ((name[2] == '\0')
190             || ((name[2] == '/') && (name[3] == '\0')))) {
191         return 1;
192     }
193     return 0;
194 }
195
196 /*
197  * This routine puts the standard HTML header at the top of the index page.
198  * We include the DOCTYPE because we may be using features therefrom (i.e.,
199  * HEIGHT and WIDTH attributes on the icons if we're FancyIndexing).
200  */
201 static void emit_preamble(request_rec *r, char *title)
202 {
203     ap_rvputs(r, DOCTYPE_HTML_3_2,
204               "<HTML>\n <HEAD>\n  <TITLE>Index of ", title,
205               "</TITLE>\n </HEAD>\n <BODY>\n", NULL);
206 }
207
208 static void push_item(ap_array_header_t *arr, char *type, char *to, char *path,
209                       char *data)
210 {
211     struct item *p = (struct item *) ap_push_array(arr);
212
213     if (!to) {
214         to = "";
215     }
216     if (!path) {
217         path = "";
218     }
219
220     p->type = type;
221     p->data = data ? ap_pstrdup(arr->cont, data) : NULL;
222     p->apply_path = ap_pstrcat(arr->cont, path, "*", NULL);
223
224     if ((type == BY_PATH) && (!ap_is_matchexp(to))) {
225         p->apply_to = ap_pstrcat(arr->cont, "*", to, NULL);
226     }
227     else if (to) {
228         p->apply_to = ap_pstrdup(arr->cont, to);
229     }
230     else {
231         p->apply_to = NULL;
232     }
233 }
234
235 static const char *add_alt(cmd_parms *cmd, void *d, char *alt, char *to)
236 {
237     if (cmd->info == BY_PATH) {
238         if (!strcmp(to, "**DIRECTORY**")) {
239             to = "^^DIRECTORY^^";
240         }
241     }
242     if (cmd->info == BY_ENCODING) {
243         ap_str_tolower(to);
244     }
245
246     push_item(((autoindex_config_rec *) d)->alt_list, cmd->info, to,
247               cmd->path, alt);
248     return NULL;
249 }
250
251 static const char *add_icon(cmd_parms *cmd, void *d, char *icon, char *to)
252 {
253     char *iconbak = ap_pstrdup(cmd->pool, icon);
254
255     if (icon[0] == '(') {
256         char *alt;
257         char *cl = strchr(iconbak, ')');
258
259         if (cl == NULL) {
260             return "missing closing paren";
261         }
262         alt = ap_getword_nc(cmd->pool, &iconbak, ',');
263         *cl = '\0';                             /* Lose closing paren */
264         add_alt(cmd, d, &alt[1], to);
265     }
266     if (cmd->info == BY_PATH) {
267         if (!strcmp(to, "**DIRECTORY**")) {
268             to = "^^DIRECTORY^^";
269         }
270     }
271     if (cmd->info == BY_ENCODING) {
272         ap_str_tolower(to);
273     }
274
275     push_item(((autoindex_config_rec *) d)->icon_list, cmd->info, to,
276               cmd->path, iconbak);
277     return NULL;
278 }
279
280 /*
281  * Add description text for a filename pattern.  If the pattern has
282  * wildcards already (or we need to add them), add leading and
283  * trailing wildcards to it to ensure substring processing.  If the
284  * pattern contains a '/' anywhere, force wildcard matching mode,
285  * add a slash to the prefix so that "bar/bletch" won't be matched
286  * by "foobar/bletch", and make a note that there's a delimiter;
287  * the matching routine simplifies to just the actual filename
288  * whenever it can.  This allows definitions in parent directories
289  * to be made for files in subordinate ones using relative paths.
290  */
291
292 /*
293  * Absent a strcasestr() function, we have to force wildcards on
294  * systems for which "AAA" and "aaa" mean the same file.
295  */
296 #ifdef CASE_BLIND_FILESYSTEM
297 #define WILDCARDS_REQUIRED 1
298 #else
299 #define WILDCARDS_REQUIRED 0
300 #endif
301
302 static const char *add_desc(cmd_parms *cmd, void *d, char *desc, char *to)
303 {
304     autoindex_config_rec *dcfg = (autoindex_config_rec *) d;
305     ai_desc_t *desc_entry;
306     char *prefix = "";
307
308     desc_entry = (ai_desc_t *) ap_push_array(dcfg->desc_list);
309     desc_entry->full_path = (strchr(to, '/') == NULL) ? 0 : 1;
310     desc_entry->wildcards = (WILDCARDS_REQUIRED
311                              || desc_entry->full_path
312                              || ap_is_fnmatch(to));
313     if (desc_entry->wildcards) {
314         prefix = desc_entry->full_path ? "*/" : "*";
315         desc_entry->pattern = ap_pstrcat(dcfg->desc_list->cont,
316                                          prefix, to, "*", NULL);
317     }
318     else {
319         desc_entry->pattern = ap_pstrdup(dcfg->desc_list->cont, to);
320     }
321     desc_entry->description = ap_pstrdup(dcfg->desc_list->cont, desc);
322     return NULL;
323 }
324
325 static const char *add_ignore(cmd_parms *cmd, void *d, char *ext)
326 {
327     push_item(((autoindex_config_rec *) d)->ign_list, 0, ext, cmd->path, NULL);
328     return NULL;
329 }
330
331 static const char *add_header(cmd_parms *cmd, void *d, char *name)
332 {
333     push_item(((autoindex_config_rec *) d)->hdr_list, 0, NULL, cmd->path,
334               name);
335     return NULL;
336 }
337
338 static const char *add_readme(cmd_parms *cmd, void *d, char *name)
339 {
340     push_item(((autoindex_config_rec *) d)->rdme_list, 0, NULL, cmd->path,
341               name);
342     return NULL;
343 }
344
345 /* A legacy directive, FancyIndexing is superseded by the IndexOptions
346  * keyword.  But for compatibility..
347  */
348 static const char *fancy_indexing(cmd_parms *cmd, void *d, int arg)
349 {
350     int curopts;
351     int newopts;
352     autoindex_config_rec *cfg;
353
354     cfg = (autoindex_config_rec *) d;
355     curopts = cfg->opts;
356     if (curopts & NO_OPTIONS) {
357         return "FancyIndexing directive conflicts with existing "
358                "IndexOptions None";
359     }
360     newopts = (arg ? (curopts | FANCY_INDEXING) : (curopts & ~FANCY_INDEXING));
361     cfg->opts = newopts;
362     return NULL;
363 }
364
365 static const char *add_opts(cmd_parms *cmd, void *d, const char *optstr)
366 {
367     char *w;
368     int opts;
369     int opts_add;
370     int opts_remove;
371     char action;
372     autoindex_config_rec *d_cfg = (autoindex_config_rec *) d;
373
374     opts = d_cfg->opts;
375     opts_add = d_cfg->incremented_opts;
376     opts_remove = d_cfg->decremented_opts;
377     while (optstr[0]) {
378         int option = 0;
379
380         w = ap_getword_conf(cmd->pool, &optstr);
381         if ((*w == '+') || (*w == '-')) {
382             action = *(w++);
383         }
384         else {
385             action = '\0';
386         }
387         if (!strcasecmp(w, "FancyIndexing")) {
388             option = FANCY_INDEXING;
389         }
390         else if (!strcasecmp(w, "IconsAreLinks")) {
391             option = ICONS_ARE_LINKS;
392         }
393         else if (!strcasecmp(w, "ScanHTMLTitles")) {
394             option = SCAN_HTML_TITLES;
395         }
396         else if (!strcasecmp(w, "SuppressLastModified")) {
397             option = SUPPRESS_LAST_MOD;
398         }
399         else if (!strcasecmp(w, "SuppressSize")) {
400             option = SUPPRESS_SIZE;
401         }
402         else if (!strcasecmp(w, "SuppressDescription")) {
403             option = SUPPRESS_DESC;
404         }
405         else if (!strcasecmp(w, "SuppressHTMLPreamble")) {
406             option = SUPPRESS_PREAMBLE;
407         }
408         else if (!strcasecmp(w, "SuppressColumnSorting")) {
409             option = SUPPRESS_COLSORT;
410         }
411         else if (!strcasecmp(w, "VersionSort")) {
412             option = VERSION_SORT;
413         }
414         else if (!strcasecmp(w, "None")) {
415             if (action != '\0') {
416                 return "Cannot combine '+' or '-' with 'None' keyword";
417             }
418             opts = NO_OPTIONS;
419             opts_add = 0;
420             opts_remove = 0;
421         }
422         else if (!strcasecmp(w, "IconWidth")) {
423             if (action != '-') {
424                 d_cfg->icon_width = DEFAULT_ICON_WIDTH;
425             }
426             else {
427                 d_cfg->icon_width = 0;
428             }
429         }
430         else if (!strncasecmp(w, "IconWidth=", 10)) {
431             if (action == '-') {
432                 return "Cannot combine '-' with IconWidth=n";
433             }
434             d_cfg->icon_width = atoi(&w[10]);
435         }
436         else if (!strcasecmp(w, "IconHeight")) {
437             if (action != '-') {
438                 d_cfg->icon_height = DEFAULT_ICON_HEIGHT;
439             }
440             else {
441                 d_cfg->icon_height = 0;
442             }
443         }
444         else if (!strncasecmp(w, "IconHeight=", 11)) {
445             if (action == '-') {
446                 return "Cannot combine '-' with IconHeight=n";
447             }
448             d_cfg->icon_height = atoi(&w[11]);
449         }
450         else if (!strcasecmp(w, "NameWidth")) {
451             if (action != '-') {
452                 return "NameWidth with no value may only appear as "
453                        "'-NameWidth'";
454             }
455             d_cfg->name_width = DEFAULT_NAME_WIDTH;
456             d_cfg->name_adjust = K_NOADJUST;
457         }
458         else if (!strncasecmp(w, "NameWidth=", 10)) {
459             if (action == '-') {
460                 return "Cannot combine '-' with NameWidth=n";
461             }
462             if (w[10] == '*') {
463                 d_cfg->name_adjust = K_ADJUST;
464             }
465             else {
466                 int width = atoi(&w[10]);
467
468                 if (width < 5) {
469                     return "NameWidth value must be greater than 5";
470                 }
471                 d_cfg->name_width = width;
472                 d_cfg->name_adjust = K_NOADJUST;
473             }
474         }
475         else {
476             return "Invalid directory indexing option";
477         }
478         if (action == '\0') {
479             opts |= option;
480             opts_add = 0;
481             opts_remove = 0;
482         }
483         else if (action == '+') {
484             opts_add |= option;
485             opts_remove &= ~option;
486         }
487         else {
488             opts_remove |= option;
489             opts_add &= ~option;
490         }
491     }
492     if ((opts & NO_OPTIONS) && (opts & ~NO_OPTIONS)) {
493         return "Cannot combine other IndexOptions keywords with 'None'";
494     }
495     d_cfg->incremented_opts = opts_add;
496     d_cfg->decremented_opts = opts_remove;
497     d_cfg->opts = opts;
498     return NULL;
499 }
500
501 static const char *set_default_order(cmd_parms *cmd, void *m, char *direction,
502                                      char *key)
503 {
504     char temp[4];
505     autoindex_config_rec *d_cfg = (autoindex_config_rec *) m;
506
507     ap_cpystrn(temp, "k=d", sizeof(temp));
508     if (!strcasecmp(direction, "Ascending")) {
509         temp[2] = D_ASCENDING;
510     }
511     else if (!strcasecmp(direction, "Descending")) {
512         temp[2] = D_DESCENDING;
513     }
514     else {
515         return "First keyword must be 'Ascending' or 'Descending'";
516     }
517
518     if (!strcasecmp(key, "Name")) {
519         temp[0] = K_NAME;
520     }
521     else if (!strcasecmp(key, "Date")) {
522         temp[0] = K_LAST_MOD;
523     }
524     else if (!strcasecmp(key, "Size")) {
525         temp[0] = K_SIZE;
526     }
527     else if (!strcasecmp(key, "Description")) {
528         temp[0] = K_DESC;
529     }
530     else {
531         return "Second keyword must be 'Name', 'Date', 'Size', or "
532             "'Description'";
533     }
534
535     if (d_cfg->default_order == NULL) {
536         d_cfg->default_order = ap_palloc(cmd->pool, 4);
537         d_cfg->default_order[3] = '\0';
538     }
539     ap_cpystrn(d_cfg->default_order, temp, sizeof(temp));
540     return NULL;
541 }
542
543 #define DIR_CMD_PERMS OR_INDEXES
544
545 static const command_rec autoindex_cmds[] =
546 {
547     {"AddIcon", add_icon, BY_PATH, DIR_CMD_PERMS, ITERATE2,
548      "an icon URL followed by one or more filenames"},
549     {"AddIconByType", add_icon, BY_TYPE, DIR_CMD_PERMS, ITERATE2,
550      "an icon URL followed by one or more MIME types"},
551     {"AddIconByEncoding", add_icon, BY_ENCODING, DIR_CMD_PERMS, ITERATE2,
552      "an icon URL followed by one or more content encodings"},
553     {"AddAlt", add_alt, BY_PATH, DIR_CMD_PERMS, ITERATE2,
554      "alternate descriptive text followed by one or more filenames"},
555     {"AddAltByType", add_alt, BY_TYPE, DIR_CMD_PERMS, ITERATE2,
556      "alternate descriptive text followed by one or more MIME types"},
557     {"AddAltByEncoding", add_alt, BY_ENCODING, DIR_CMD_PERMS, ITERATE2,
558      "alternate descriptive text followed by one or more content encodings"},
559     {"IndexOptions", add_opts, NULL, DIR_CMD_PERMS, RAW_ARGS,
560      "one or more index options"},
561     {"IndexOrderDefault", set_default_order, NULL, DIR_CMD_PERMS, TAKE2,
562      "{Ascending,Descending} {Name,Size,Description,Date}"},
563     {"IndexIgnore", add_ignore, NULL, DIR_CMD_PERMS, ITERATE,
564      "one or more file extensions"},
565     {"AddDescription", add_desc, BY_PATH, DIR_CMD_PERMS, ITERATE2,
566      "Descriptive text followed by one or more filenames"},
567     {"HeaderName", add_header, NULL, DIR_CMD_PERMS, TAKE1, "a filename"},
568     {"ReadmeName", add_readme, NULL, DIR_CMD_PERMS, TAKE1, "a filename"},
569     {"FancyIndexing", fancy_indexing, NULL, DIR_CMD_PERMS, FLAG,
570      "Limited to 'on' or 'off' (superseded by IndexOptions FancyIndexing)"},
571     {"DefaultIcon", ap_set_string_slot,
572      (void *) XtOffsetOf(autoindex_config_rec, default_icon),
573      DIR_CMD_PERMS, TAKE1, "an icon URL"},
574     {NULL}
575 };
576
577 static void *create_autoindex_config(ap_pool_t *p, char *dummy)
578 {
579     autoindex_config_rec *new =
580     (autoindex_config_rec *) ap_pcalloc(p, sizeof(autoindex_config_rec));
581
582     new->icon_width = 0;
583     new->icon_height = 0;
584     new->name_width = DEFAULT_NAME_WIDTH;
585     new->name_adjust = K_UNSET;
586     new->icon_list = ap_make_array(p, 4, sizeof(struct item));
587     new->alt_list = ap_make_array(p, 4, sizeof(struct item));
588     new->desc_list = ap_make_array(p, 4, sizeof(ai_desc_t));
589     new->ign_list = ap_make_array(p, 4, sizeof(struct item));
590     new->hdr_list = ap_make_array(p, 4, sizeof(struct item));
591     new->rdme_list = ap_make_array(p, 4, sizeof(struct item));
592     new->opts = 0;
593     new->incremented_opts = 0;
594     new->decremented_opts = 0;
595     new->default_order = NULL;
596
597     return (void *) new;
598 }
599
600 static void *merge_autoindex_configs(ap_pool_t *p, void *basev, void *addv)
601 {
602     autoindex_config_rec *new;
603     autoindex_config_rec *base = (autoindex_config_rec *) basev;
604     autoindex_config_rec *add = (autoindex_config_rec *) addv;
605
606     new = (autoindex_config_rec *) ap_pcalloc(p, sizeof(autoindex_config_rec));
607     new->default_icon = add->default_icon ? add->default_icon
608                                           : base->default_icon;
609     new->icon_height = add->icon_height ? add->icon_height : base->icon_height;
610     new->icon_width = add->icon_width ? add->icon_width : base->icon_width;
611
612     new->alt_list = ap_append_arrays(p, add->alt_list, base->alt_list);
613     new->ign_list = ap_append_arrays(p, add->ign_list, base->ign_list);
614     new->hdr_list = ap_append_arrays(p, add->hdr_list, base->hdr_list);
615     new->desc_list = ap_append_arrays(p, add->desc_list, base->desc_list);
616     new->icon_list = ap_append_arrays(p, add->icon_list, base->icon_list);
617     new->rdme_list = ap_append_arrays(p, add->rdme_list, base->rdme_list);
618     if (add->opts & NO_OPTIONS) {
619         /*
620          * If the current directory says 'no options' then we also
621          * clear any incremental mods from being inheritable further down.
622          */
623         new->opts = NO_OPTIONS;
624         new->incremented_opts = 0;
625         new->decremented_opts = 0;
626     }
627     else {
628         /*
629          * If there were any nonincremental options selected for
630          * this directory, they dominate and we don't inherit *anything.*
631          * Contrariwise, we *do* inherit if the only settings here are
632          * incremental ones.
633          */
634         if (add->opts == 0) {
635             new->incremented_opts = (base->incremented_opts 
636                                      | add->incremented_opts)
637                                     & ~add->decremented_opts;
638             new->decremented_opts = (base->decremented_opts
639                                      | add->decremented_opts);
640             /*
641              * We may have incremental settings, so make sure we don't
642              * inadvertently inherit an IndexOptions None from above.
643              */
644             new->opts = (base->opts & ~NO_OPTIONS);
645         }
646         else {
647             /*
648              * There are local nonincremental settings, which clear
649              * all inheritance from above.  They *are* the new base settings.
650              */
651             new->opts = add->opts;;
652         }
653         /*
654          * We're guaranteed that there'll be no overlap between
655          * the add-options and the remove-options.
656          */
657         new->opts |= new->incremented_opts;
658         new->opts &= ~new->decremented_opts;
659     }
660     /*
661      * Inherit the NameWidth settings if there aren't any specific to
662      * the new location; otherwise we'll end up using the defaults set in the
663      * config-rec creation routine.
664      */
665     if (add->name_adjust == K_UNSET) {
666         new->name_width = base->name_width;
667         new->name_adjust = base->name_adjust;
668     }
669     else {
670         new->name_width = add->name_width;
671         new->name_adjust = add->name_adjust;
672     }
673
674     new->default_order = (add->default_order != NULL)
675         ? add->default_order : base->default_order;
676     return new;
677 }
678
679 /****************************************************************
680  *
681  * Looking things up in config entries...
682  */
683
684 /* Structure used to hold entries when we're actually building an index */
685
686 struct ent {
687     char *name;
688     char *icon;
689     char *alt;
690     char *desc;
691     off_t size;
692     ap_time_t lm;
693     struct ent *next;
694     int ascending, version_sort;
695     char key;
696 };
697
698 static char *find_item(request_rec *r, ap_array_header_t *list, int path_only)
699 {
700     const char *content_type = ap_field_noparam(r->pool, r->content_type);
701     const char *content_encoding = r->content_encoding;
702     char *path = r->filename;
703
704     struct item *items = (struct item *) list->elts;
705     int i;
706
707     for (i = 0; i < list->nelts; ++i) {
708         struct item *p = &items[i];
709
710         /* Special cased for ^^DIRECTORY^^ and ^^BLANKICON^^ */
711         if ((path[0] == '^') || (!ap_strcmp_match(path, p->apply_path))) {
712             if (!*(p->apply_to)) {
713                 return p->data;
714             }
715             else if (p->type == BY_PATH || path[0] == '^') {
716                 if (!ap_strcmp_match(path, p->apply_to)) {
717                     return p->data;
718                 }
719             }
720             else if (!path_only) {
721                 if (!content_encoding) {
722                     if (p->type == BY_TYPE) {
723                         if (content_type
724                             && !ap_strcasecmp_match(content_type,
725                                                     p->apply_to)) {
726                             return p->data;
727                         }
728                     }
729                 }
730                 else {
731                     if (p->type == BY_ENCODING) {
732                         if (!ap_strcasecmp_match(content_encoding,
733                                                  p->apply_to)) {
734                             return p->data;
735                         }
736                     }
737                 }
738             }
739         }
740     }
741     return NULL;
742 }
743
744 #define find_icon(d,p,t) find_item(p,d->icon_list,t)
745 #define find_alt(d,p,t) find_item(p,d->alt_list,t)
746 #define find_header(d,p) find_item(p,d->hdr_list,0)
747 #define find_readme(d,p) find_item(p,d->rdme_list,0)
748
749 static char *find_default_icon(autoindex_config_rec *d, char *bogus_name)
750 {
751     request_rec r;
752
753     /* Bleah.  I tried to clean up find_item, and it lead to this bit
754      * of ugliness.   Note that the fields initialized are precisely
755      * those that find_item looks at...
756      */
757
758     r.filename = bogus_name;
759     r.content_type = r.content_encoding = NULL;
760
761     return find_item(&r, d->icon_list, 1);
762 }
763
764 /*
765  * Look through the list of pattern/description pairs and return the first one
766  * if any) that matches the filename in the request.  If multiple patterns
767  * match, only the first one is used; since the order in the array is the
768  * same as the order in which directives were processed, earlier matching
769  * directives will dominate.
770  */
771
772 #ifdef CASE_BLIND_FILESYSTEM
773 #define MATCH_FLAGS FNM_CASE_BLIND
774 #else
775 #define MATCH_FLAGS 0
776 #endif
777
778 static char *find_desc(autoindex_config_rec *dcfg, request_rec *r)
779 {
780     int i;
781     ai_desc_t *list = (ai_desc_t *) dcfg->desc_list->elts;
782     const char *filename_full = r->filename;
783     const char *filename_only;
784     const char *filename;
785
786     /*
787      * If the filename includes a path, extract just the name itself
788      * for the simple matches.
789      */
790     if ((filename_only = strrchr(filename_full, '/')) == NULL) {
791         filename_only = filename_full;
792     }
793     else {
794         filename_only++;
795     }
796     for (i = 0; i < dcfg->desc_list->nelts; ++i) {
797         ai_desc_t *tuple = &list[i];
798         int found;
799
800         /*
801          * Only use the full-path filename if the pattern contains '/'s.
802          */
803         filename = (tuple->full_path) ? filename_full : filename_only;
804         /*
805          * Make the comparison using the cheapest method; only do
806          * wildcard checking if we must.
807          */
808         if (tuple->wildcards) {
809             found = (ap_fnmatch(tuple->pattern, filename, MATCH_FLAGS) == 0);
810         }
811         else {
812             found = (strstr(filename, tuple->pattern) != NULL);
813         }
814         if (found) {
815             return tuple->description;
816         }
817     }
818     return NULL;
819 }
820
821 static int ignore_entry(autoindex_config_rec *d, char *path)
822 {
823     ap_array_header_t *list = d->ign_list;
824     struct item *items = (struct item *) list->elts;
825     char *tt;
826     int i;
827
828     if ((tt = strrchr(path, '/')) == NULL) {
829         tt = path;
830     }
831     else {
832         tt++;
833     }
834
835     for (i = 0; i < list->nelts; ++i) {
836         struct item *p = &items[i];
837         char *ap;
838
839         if ((ap = strrchr(p->apply_to, '/')) == NULL) {
840             ap = p->apply_to;
841         }
842         else {
843             ap++;
844         }
845
846 #ifndef CASE_BLIND_FILESYSTEM
847         if (!ap_strcmp_match(path, p->apply_path)
848             && !ap_strcmp_match(tt, ap)) {
849             return 1;
850         }
851 #else  /* !CASE_BLIND_FILESYSTEM */
852         /*
853          * On some platforms, the match must be case-blind.  This is really
854          * a factor of the filesystem involved, but we can't detect that
855          * reliably - so we have to granularise at the OS level.
856          */
857         if (!ap_strcasecmp_match(path, p->apply_path)
858             && !ap_strcasecmp_match(tt, ap)) {
859             return 1;
860         }
861 #endif /* !CASE_BLIND_FILESYSTEM */
862     }
863     return 0;
864 }
865
866 /*****************************************************************
867  *
868  * Actually generating output
869  */
870
871 /*
872  * Elements of the emitted document:
873  *      Preamble
874  *              Emitted unless SUPPRESS_PREAMBLE is set AND ap_run_sub_req
875  *              succeeds for the (content_type == text/html) header file.
876  *      Header file
877  *              Emitted if found (and able).
878  *      H1 tag line
879  *              Emitted if a header file is NOT emitted.
880  *      Directory stuff
881  *              Always emitted.
882  *      HR
883  *              Emitted if FANCY_INDEXING is set.
884  *      Readme file
885  *              Emitted if found (and able).
886  *      ServerSig
887  *              Emitted if ServerSignature is not Off AND a readme file
888  *              is NOT emitted.
889  *      Postamble
890  *              Emitted unless SUPPRESS_PREAMBLE is set AND ap_run_sub_req
891  *              succeeds for the (content_type == text/html) readme file.
892  */
893
894
895 /*
896  * emit a plain text file
897  */
898 static void do_emit_plain(request_rec *r, ap_file_t *f)
899 {
900     char buf[IOBUFSIZE + 1];
901     int i, c, ch;
902     ap_ssize_t n;
903     ap_status_t stat;
904
905     ap_rputs("<PRE>\n", r);
906     while (!ap_eof(f)) {
907         do {
908             n = sizeof(char) * IOBUFSIZE;
909             stat = ap_read(f, buf, &n);
910         }
911         while (stat != APR_SUCCESS && stat == EINTR);
912         if (n == -1 || n == 0) {
913             break;
914         }
915         buf[n] = '\0';
916         c = 0;
917         while (c < n) {
918             for (i = c; i < n; i++) {
919                 if (buf[i] == '<' || buf[i] == '>' || buf[i] == '&') {
920                     break;
921                 }
922             }
923             ch = buf[i];
924             buf[i] = '\0';
925             ap_rputs(&buf[c], r);
926             if (ch == '<') {
927                 ap_rputs("&lt;", r);
928             }
929             else if (ch == '>') {
930                 ap_rputs("&gt;", r);
931             }
932             else if (ch == '&') {
933                 ap_rputs("&amp;", r);
934             }
935             c = i + 1;
936         }
937     }
938     ap_rputs("</PRE>\n", r);
939 }
940
941 /*
942  * Handle the preamble through the H1 tag line, inclusive.  Locate
943  * the file with a subrequests.  Process text/html documents by actually
944  * running the subrequest; text/xxx documents get copied verbatim,
945  * and any other content type is ignored.  This means that a non-text
946  * document (such as HEADER.gif) might get multiviewed as the result
947  * instead of a text document, meaning nothing will be displayed, but
948  * oh well.
949  */
950 static void emit_head(request_rec *r, char *header_fname, int suppress_amble,
951                       char *title)
952 {
953     ap_file_t *f = NULL;
954     request_rec *rr = NULL;
955     int emit_amble = 1;
956     int emit_H1 = 1;
957
958     /*
959      * If there's a header file, send a subrequest to look for it.  If it's
960      * found and a text file, handle it -- otherwise fall through and
961      * pretend there's nothing there.
962      */
963     if ((header_fname != NULL)
964         && (rr = ap_sub_req_lookup_uri(header_fname, r))
965         && (rr->status == HTTP_OK)
966         && (rr->filename != NULL)
967         && rr->finfo.filetype == APR_REG) {
968         /*
969          * Check for the two specific cases we allow: text/html and
970          * text/anything-else.  The former is allowed to be processed for
971          * SSIs.
972          */
973         if (rr->content_type != NULL) {
974             if (!strcasecmp(ap_field_noparam(r->pool, rr->content_type),
975                             "text/html")) {
976                 /* Hope everything will work... */
977                 emit_amble = 0;
978                 emit_H1 = 0;
979
980                 if (! suppress_amble) {
981                     emit_preamble(r, title);
982                 }
983                 /*
984                  * If there's a problem running the subrequest, display the
985                  * preamble if we didn't do it before -- the header file
986                  * didn't get displayed.
987                  */
988                 if (ap_run_sub_req(rr) != OK) {
989                     /* It didn't work */
990                     emit_amble = suppress_amble;
991                     emit_H1 = 1;
992                 }
993             }
994             else if (!strncasecmp("text/", rr->content_type, 5)) {
995                 /*
996                  * If we can open the file, prefix it with the preamble
997                  * regardless; since we'll be sending a <PRE> block around
998                  * the file's contents, any HTML header it had won't end up
999                  * where it belongs.
1000                  */
1001                 if (ap_open(&f, rr->filename, APR_READ,
1002                             APR_OS_DEFAULT, r->pool) == APR_SUCCESS) {
1003                     emit_preamble(r, title);
1004                     emit_amble = 0;
1005                     do_emit_plain(r, f);
1006                     ap_close(f);
1007                     emit_H1 = 0;
1008                 }
1009             }
1010         }
1011     }
1012
1013     if (emit_amble) {
1014         emit_preamble(r, title);
1015     }
1016     if (emit_H1) {
1017         ap_rvputs(r, "<H1>Index of ", title, "</H1>\n", NULL);
1018     }
1019     if (rr != NULL) {
1020         ap_destroy_sub_req(rr);
1021     }
1022 }
1023
1024
1025 /*
1026  * Handle the Readme file through the postamble, inclusive.  Locate
1027  * the file with a subrequests.  Process text/html documents by actually
1028  * running the subrequest; text/xxx documents get copied verbatim,
1029  * and any other content type is ignored.  This means that a non-text
1030  * document (such as FOOTER.gif) might get multiviewed as the result
1031  * instead of a text document, meaning nothing will be displayed, but
1032  * oh well.
1033  */
1034 static void emit_tail(request_rec *r, char *readme_fname, int suppress_amble)
1035 {
1036     ap_file_t *f = NULL;
1037     request_rec *rr = NULL;
1038     int suppress_post = 0;
1039     int suppress_sig = 0;
1040
1041     /*
1042      * If there's a readme file, send a subrequest to look for it.  If it's
1043      * found and a text file, handle it -- otherwise fall through and
1044      * pretend there's nothing there.
1045      */
1046     if ((readme_fname != NULL)
1047         && (rr = ap_sub_req_lookup_uri(readme_fname, r))
1048         && (rr->status == HTTP_OK)
1049         && (rr->filename != NULL)
1050         && rr->finfo.filetype == APR_REG) {
1051         /*
1052          * Check for the two specific cases we allow: text/html and
1053          * text/anything-else.  The former is allowed to be processed for
1054          * SSIs.
1055          */
1056         if (rr->content_type != NULL) {
1057             if (!strcasecmp(ap_field_noparam(r->pool, rr->content_type),
1058                             "text/html")) {
1059                 if (ap_run_sub_req(rr) == OK) {
1060                     /* worked... */
1061                     suppress_sig = 1;
1062                     suppress_post = suppress_amble;
1063                 }
1064             }
1065             else if (!strncasecmp("text/", rr->content_type, 5)) {
1066                 /*
1067                  * If we can open the file, suppress the signature.
1068                  */
1069                 if (ap_open(&f, rr->filename, APR_READ,
1070                             APR_OS_DEFAULT, r->pool) == APR_SUCCESS) {
1071                     do_emit_plain(r, f);
1072                     ap_close(f);
1073                     suppress_sig = 1;
1074                 }
1075             }
1076         }
1077     }
1078     
1079     if (!suppress_sig) {
1080         ap_rputs(ap_psignature("", r), r);
1081     }
1082     if (!suppress_post) {
1083         ap_rputs("</BODY></HTML>\n", r);
1084     }
1085     if (rr != NULL) {
1086         ap_destroy_sub_req(rr);
1087     }
1088 }
1089
1090
1091 static char *find_title(request_rec *r)
1092 {
1093     char titlebuf[MAX_STRING_LEN], *find = "<TITLE>";
1094     ap_file_t *thefile = NULL;
1095     int x, y, p;
1096     ap_ssize_t n;
1097
1098     if (r->status != HTTP_OK) {
1099         return NULL;
1100     }
1101     if ((r->content_type != NULL)
1102         && (!strcasecmp(ap_field_noparam(r->pool, r->content_type),
1103                         "text/html")
1104             || !strcmp(r->content_type, INCLUDES_MAGIC_TYPE))
1105         && !r->content_encoding) {
1106         if (ap_open(&thefile, r->filename, APR_READ,
1107                     APR_OS_DEFAULT, r->pool) != APR_SUCCESS) {
1108             return NULL;
1109         }
1110         n = sizeof(char) * (MAX_STRING_LEN - 1);
1111         ap_read(thefile, titlebuf, &n);
1112         if (n <= 0) {
1113             ap_close(thefile);
1114             return NULL;
1115         }
1116         titlebuf[n] = '\0';
1117         for (x = 0, p = 0; titlebuf[x]; x++) {
1118             if (ap_toupper(titlebuf[x]) == find[p]) {
1119                 if (!find[++p]) {
1120                     if ((p = ap_ind(&titlebuf[++x], '<')) != -1) {
1121                         titlebuf[x + p] = '\0';
1122                     }
1123                     /* Scan for line breaks for Tanmoy's secretary */
1124                     for (y = x; titlebuf[y]; y++) {
1125                         if ((titlebuf[y] == CR) || (titlebuf[y] == LF)) {
1126                             if (y == x) {
1127                                 x++;
1128                             }
1129                             else {
1130                                 titlebuf[y] = ' ';
1131                             }
1132                         }
1133                     }
1134                     ap_close(thefile);
1135                     return ap_pstrdup(r->pool, &titlebuf[x]);
1136                 }
1137             }
1138             else {
1139                 p = 0;
1140             }
1141         }
1142         ap_close(thefile);
1143     }
1144     return NULL;
1145 }
1146
1147 static struct ent *make_autoindex_entry(char *name, int autoindex_opts,
1148                                         autoindex_config_rec *d,
1149                                         request_rec *r, char keyid,
1150                                         char direction)
1151 {
1152     struct ent *p;
1153
1154     if ((name[0] == '.') && (!name[1])) {
1155         return (NULL);
1156     }
1157
1158     if (ignore_entry(d, ap_make_full_path(r->pool, r->filename, name))) {
1159         return (NULL);
1160     }
1161
1162     p = (struct ent *) ap_pcalloc(r->pool, sizeof(struct ent));
1163     p->name = ap_pstrdup(r->pool, name);
1164     p->size = -1;
1165     p->icon = NULL;
1166     p->alt = NULL;
1167     p->desc = NULL;
1168     p->lm = -1;
1169     p->key = ap_toupper(keyid);
1170     p->ascending = (ap_toupper(direction) == D_ASCENDING);
1171     p->version_sort = autoindex_opts & VERSION_SORT;
1172
1173     if (autoindex_opts & FANCY_INDEXING) {
1174         request_rec *rr = ap_sub_req_lookup_file(name, r);
1175
1176         if (rr->finfo.protection != 0) {
1177             p->lm = rr->finfo.mtime;
1178             if (rr->finfo.filetype == APR_DIR) {
1179                 if (!(p->icon = find_icon(d, rr, 1))) {
1180                     p->icon = find_default_icon(d, "^^DIRECTORY^^");
1181                 }
1182                 if (!(p->alt = find_alt(d, rr, 1))) {
1183                     p->alt = "DIR";
1184                 }
1185                 p->size = -1;
1186                 p->name = ap_pstrcat(r->pool, name, "/", NULL);
1187             }
1188             else {
1189                 p->icon = find_icon(d, rr, 0);
1190                 p->alt = find_alt(d, rr, 0);
1191                 p->size = rr->finfo.size;
1192             }
1193         }
1194
1195         p->desc = find_desc(d, rr);
1196
1197         if ((!p->desc) && (autoindex_opts & SCAN_HTML_TITLES)) {
1198             p->desc = ap_pstrdup(r->pool, find_title(rr));
1199         }
1200
1201         ap_destroy_sub_req(rr);
1202     }
1203     /*
1204      * We don't need to take any special action for the file size key.  If
1205      * we did, it would go here.
1206      */
1207     if (keyid == K_LAST_MOD) {
1208         if (p->lm < 0) {
1209             p->lm = 0;
1210         }
1211     }
1212     return (p);
1213 }
1214
1215 static char *terminate_description(autoindex_config_rec *d, char *desc,
1216                                    int autoindex_opts)
1217 {
1218     int maxsize = 23;
1219     register int x;
1220
1221     if (autoindex_opts & SUPPRESS_LAST_MOD) {
1222         maxsize += 19;
1223     }
1224     if (autoindex_opts & SUPPRESS_SIZE) {
1225         maxsize += 7;
1226     }
1227
1228     for (x = 0; desc[x] && (maxsize > 0 || desc[x]=='<'); x++) {
1229         if (desc[x] == '<') {
1230             while (desc[x] != '>') {
1231                 if (!desc[x]) {
1232                     maxsize = 0;
1233                     break;
1234                 }
1235                 ++x;
1236             }
1237         }
1238         else if (desc[x] == '&') {
1239             /* entities like &auml; count as one character */
1240             --maxsize;
1241             for ( ; desc[x] != ';'; ++x) {
1242                 if (desc[x] == '\0') {
1243                      maxsize = 0;
1244                      break;
1245                 }
1246             }
1247         }
1248         else {
1249             --maxsize;
1250         }
1251     }
1252     if (!maxsize && desc[x] != '\0') {
1253         desc[x - 1] = '>';      /* Grump. */
1254         desc[x] = '\0';         /* Double Grump! */
1255     }
1256     return desc;
1257 }
1258
1259 /*
1260  * Emit the anchor for the specified field.  If a field is the key for the
1261  * current request, the link changes its meaning to reverse the order when
1262  * selected again.  Non-active fields always start in ascending order.
1263  */
1264 static void emit_link(request_rec *r, char *anchor, char fname, char curkey,
1265                       char curdirection, int nosort)
1266 {
1267     char qvalue[5];
1268     int reverse;
1269
1270     if (!nosort) {
1271         qvalue[0] = '?';
1272         qvalue[1] = fname;
1273         qvalue[2] = '=';
1274         qvalue[4] = '\0';
1275         reverse = ((curkey == fname) && (curdirection == D_ASCENDING));
1276         qvalue[3] = reverse ? D_DESCENDING : D_ASCENDING;
1277         ap_rvputs(r, "<A HREF=\"", qvalue, "\">", anchor, "</A>", NULL);
1278     }
1279     else {
1280         ap_rputs(anchor, r);
1281     }
1282 }
1283
1284 static void output_directories(struct ent **ar, int n,
1285                                autoindex_config_rec *d, request_rec *r,
1286                                int autoindex_opts, char keyid, char direction)
1287 {
1288     int x;
1289     ap_size_t rv;
1290     char *name = r->uri;
1291     char *tp;
1292     int static_columns = (autoindex_opts & SUPPRESS_COLSORT);
1293     ap_pool_t *scratch;
1294     int name_width;
1295     char *name_scratch;
1296     char *pad_scratch;
1297
1298     ap_create_pool(&scratch, r->pool);
1299     if (name[0] == '\0') {
1300         name = "/";
1301     }
1302
1303     name_width = d->name_width;
1304     if (d->name_adjust == K_ADJUST) {
1305         for (x = 0; x < n; x++) {
1306             int t = strlen(ar[x]->name);
1307             if (t > name_width) {
1308                 name_width = t;
1309             }
1310         }
1311     }
1312     name_scratch = ap_palloc(r->pool, name_width + 1);
1313     pad_scratch = ap_palloc(r->pool, name_width + 1);
1314     memset(pad_scratch, ' ', name_width);
1315     pad_scratch[name_width] = '\0';
1316
1317     if (autoindex_opts & FANCY_INDEXING) {
1318         ap_rputs("<PRE>", r);
1319         if ((tp = find_default_icon(d, "^^BLANKICON^^"))) {
1320             ap_rvputs(r, "<IMG SRC=\"", ap_escape_html(scratch, tp),
1321                    "\" ALT=\"     \"", NULL);
1322             if (d->icon_width && d->icon_height) {
1323                 ap_rprintf
1324                     (
1325                         r,
1326                         " HEIGHT=\"%d\" WIDTH=\"%d\"",
1327                         d->icon_height,
1328                         d->icon_width
1329                     );
1330             }
1331             ap_rputs("> ", r);
1332         }
1333         emit_link(r, "Name", K_NAME, keyid, direction, static_columns);
1334         ap_rputs(pad_scratch + 4, r);
1335         /*
1336          * Emit the guaranteed-at-least-one-space-between-columns byte.
1337          */
1338         ap_rputs(" ", r);
1339         if (!(autoindex_opts & SUPPRESS_LAST_MOD)) {
1340             emit_link(r, "Last modified", K_LAST_MOD, keyid, direction,
1341                       static_columns);
1342             ap_rputs("       ", r);
1343         }
1344         if (!(autoindex_opts & SUPPRESS_SIZE)) {
1345             emit_link(r, "Size", K_SIZE, keyid, direction, static_columns);
1346             ap_rputs("  ", r);
1347         }
1348         if (!(autoindex_opts & SUPPRESS_DESC)) {
1349             emit_link(r, "Description", K_DESC, keyid, direction,
1350                       static_columns);
1351         }
1352         ap_rputs("\n<HR>\n", r);
1353     }
1354     else {
1355         ap_rputs("<UL>", r);
1356     }
1357
1358     for (x = 0; x < n; x++) {
1359         char *anchor, *t, *t2;
1360         int nwidth;
1361
1362         ap_clear_pool(scratch);
1363
1364         if (is_parent(ar[x]->name)) {
1365             t = ap_make_full_path(scratch, name, "../");
1366             ap_getparents(t);
1367             if (t[0] == '\0') {
1368                 t = "/";
1369             }
1370             t2 = "Parent Directory";
1371             anchor = ap_escape_html(scratch, ap_os_escape_path(scratch, t, 0));
1372         }
1373         else {
1374             t = ar[x]->name;
1375             t2 = t;
1376             anchor = ap_escape_html(scratch, ap_os_escape_path(scratch, t, 0));
1377         }
1378
1379         if (autoindex_opts & FANCY_INDEXING) {
1380             if (autoindex_opts & ICONS_ARE_LINKS) {
1381                 ap_rvputs(r, "<A HREF=\"", anchor, "\">", NULL);
1382             }
1383             if ((ar[x]->icon) || d->default_icon) {
1384                 ap_rvputs(r, "<IMG SRC=\"",
1385                           ap_escape_html(scratch,
1386                                          ar[x]->icon ? ar[x]->icon
1387                                                      : d->default_icon),
1388                           "\" ALT=\"[", (ar[x]->alt ? ar[x]->alt : "   "),
1389                           "]\"", NULL);
1390                 if (d->icon_width && d->icon_height) {
1391                     ap_rprintf(r, " HEIGHT=\"%d\" WIDTH=\"%d\"",
1392                                d->icon_height, d->icon_width);
1393                 }
1394                 ap_rputs(">", r);
1395             }
1396             if (autoindex_opts & ICONS_ARE_LINKS) {
1397                 ap_rputs("</A>", r);
1398             }
1399
1400             nwidth = strlen(t2);
1401             if (nwidth > name_width) {
1402               memcpy(name_scratch, t2, name_width - 3);
1403               name_scratch[name_width - 3] = '.';
1404               name_scratch[name_width - 2] = '.';
1405               name_scratch[name_width - 1] = '>';
1406               name_scratch[name_width] = 0;
1407               t2 = name_scratch;
1408               nwidth = name_width;
1409             }
1410             ap_rvputs(r, " <A HREF=\"", anchor, "\">",
1411               ap_escape_html(scratch, t2), "</A>", pad_scratch + nwidth,
1412               NULL);
1413             /*
1414              * The blank before the storm.. er, before the next field.
1415              */
1416             ap_rputs(" ", r);
1417             if (!(autoindex_opts & SUPPRESS_LAST_MOD)) {
1418                 if (ar[x]->lm != -1) {
1419                     char time_str[MAX_STRING_LEN];
1420                     ap_exploded_time_t ts;
1421                     ap_explode_localtime(&ts, ar[x]->lm);
1422                     ap_strftime(time_str, &rv, MAX_STRING_LEN, 
1423                                 "%d-%b-%Y %H:%M  ", &ts);
1424                     ap_rputs(time_str, r);
1425                 }
1426                 else {
1427                     /*Length="22-Feb-1998 23:42  " (see 4 lines above) */
1428                     ap_rputs("                   ", r);
1429                 }
1430             }
1431             if (!(autoindex_opts & SUPPRESS_SIZE)) {
1432                 ap_send_size(ar[x]->size, r);
1433                 ap_rputs("  ", r);
1434             }
1435             if (!(autoindex_opts & SUPPRESS_DESC)) {
1436                 if (ar[x]->desc) {
1437                     ap_rputs(terminate_description(d, ar[x]->desc,
1438                                                    autoindex_opts), r);
1439                 }
1440             }
1441         }
1442         else {
1443             ap_rvputs(r, "<LI><A HREF=\"", anchor, "\"> ", t2,
1444                       "</A>", NULL);
1445         }
1446         ap_rputc('\n', r);
1447     }
1448     if (autoindex_opts & FANCY_INDEXING) {
1449         ap_rputs("</PRE>", r);
1450     }
1451     else {
1452         ap_rputs("</UL>", r);
1453     }
1454 }
1455
1456 /*
1457  * Compare two file entries according to the sort criteria.  The return
1458  * is essentially a signum function value.
1459  */
1460
1461 static int dsortf(struct ent **e1, struct ent **e2)
1462 {
1463     struct ent *c1;
1464     struct ent *c2;
1465     int result = 0;
1466
1467     /*
1468      * First, see if either of the entries is for the parent directory.
1469      * If so, that *always* sorts lower than anything else.
1470      */
1471     if (is_parent((*e1)->name)) {
1472         return -1;
1473     }
1474     if (is_parent((*e2)->name)) {
1475         return 1;
1476     }
1477     /*
1478      * All of our comparisons will be of the c1 entry against the c2 one,
1479      * so assign them appropriately to take care of the ordering.
1480      */
1481     if ((*e1)->ascending) {
1482         c1 = *e1;
1483         c2 = *e2;
1484     }
1485     else {
1486         c1 = *e2;
1487         c2 = *e1;
1488     }
1489
1490     switch (c1->key) {
1491     case K_LAST_MOD:
1492         if (c1->lm > c2->lm) {
1493             return 1;
1494         }
1495         else if (c1->lm < c2->lm) {
1496             return -1;
1497         }
1498         break;
1499     case K_SIZE:
1500         if (c1->size > c2->size) {
1501             return 1;
1502         }
1503         else if (c1->size < c2->size) {
1504             return -1;
1505         }
1506         break;
1507     case K_DESC:
1508         if (c1->version_sort)
1509             result = ap_strnatcmp(c1->desc ? c1->desc : "", c2->desc ? c2->desc : "");
1510         else
1511             result = strcmp(c1->desc ? c1->desc : "", c2->desc ? c2->desc : "");
1512         if (result) {
1513             return result;
1514         }
1515         break;
1516     }
1517     if (c1->version_sort)
1518         return ap_strnatcmp(c1->name, c2->name);
1519     else
1520         return strcmp(c1->name, c2->name);
1521 }
1522
1523
1524 static int index_directory(request_rec *r,
1525                            autoindex_config_rec *autoindex_conf)
1526 {
1527     char *title_name = ap_escape_html(r->pool, r->uri);
1528     char *title_endp;
1529     char *name = r->filename;
1530
1531     ap_dir_t *d;
1532     ap_status_t status;
1533     int num_ent = 0, x;
1534     struct ent *head, *p;
1535     struct ent **ar = NULL;
1536     const char *qstring;
1537     int autoindex_opts = autoindex_conf->opts;
1538     char keyid;
1539     char direction;
1540
1541     if ((status = ap_opendir(&d, name, r->pool)) != APR_SUCCESS) {
1542         ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
1543                     "Can't open directory for index: %s", r->filename);
1544         return HTTP_FORBIDDEN;
1545     }
1546
1547     r->content_type = "text/html";
1548
1549     ap_send_http_header(r);
1550
1551     if (r->header_only) {
1552         ap_closedir(d);
1553         return 0;
1554     }
1555
1556     /* Spew HTML preamble */
1557
1558     title_endp = title_name + strlen(title_name) - 1;
1559
1560     while (title_endp > title_name && *title_endp == '/') {
1561         *title_endp-- = '\0';
1562     }
1563
1564     emit_head(r, find_header(autoindex_conf, r),
1565               autoindex_opts & SUPPRESS_PREAMBLE, title_name);
1566
1567     /*
1568      * Figure out what sort of indexing (if any) we're supposed to use.
1569      *
1570      * If no QUERY_STRING was specified or column sorting has been
1571      * explicitly disabled, we use the default specified by the
1572      * IndexOrderDefault directive (if there is one); otherwise,
1573      * we fall back to ascending by name.
1574      */
1575     qstring = r->args;
1576     if ((autoindex_opts & SUPPRESS_COLSORT)
1577         || ((qstring == NULL) || (*qstring == '\0'))) {
1578         qstring = autoindex_conf->default_order;
1579     }
1580     /*
1581      * If there is no specific ordering defined for this directory,
1582      * default to ascending by filename.
1583      */
1584     if ((qstring == NULL) || (*qstring == '\0')) {
1585         keyid = K_NAME;
1586         direction = D_ASCENDING;
1587     }
1588     else {
1589         keyid = *qstring;
1590         ap_getword(r->pool, &qstring, '=');
1591         if (qstring != '\0') {
1592             direction = *qstring;
1593         }
1594         else {
1595             direction = D_ASCENDING;
1596         }
1597     }
1598
1599     /* 
1600      * Since we don't know how many dir. entries there are, put them into a 
1601      * linked list and then arrayificate them so qsort can use them. 
1602      */
1603     head = NULL;
1604     while (ap_readdir(d) == APR_SUCCESS) {
1605         char *d_name;
1606         ap_get_dir_filename(&d_name, d);
1607         p = make_autoindex_entry(d_name, autoindex_opts,
1608                                  autoindex_conf, r, keyid, direction);
1609         if (p != NULL) {
1610             p->next = head;
1611             head = p;
1612             num_ent++;
1613         }
1614     }
1615     if (num_ent > 0) {
1616         ar = (struct ent **) ap_palloc(r->pool,
1617                                        num_ent * sizeof(struct ent *));
1618         p = head;
1619         x = 0;
1620         while (p) {
1621             ar[x++] = p;
1622             p = p->next;
1623         }
1624
1625         qsort((void *) ar, num_ent, sizeof(struct ent *),
1626               (int (*)(const void *, const void *)) dsortf);
1627     }
1628     output_directories(ar, num_ent, autoindex_conf, r, autoindex_opts, keyid,
1629                        direction);
1630     ap_closedir(d);
1631
1632     if (autoindex_opts & FANCY_INDEXING) {
1633         ap_rputs("<HR>\n", r);
1634     }
1635     emit_tail(r, find_readme(autoindex_conf, r),
1636               autoindex_opts & SUPPRESS_PREAMBLE);
1637
1638     return 0;
1639 }
1640
1641 /* The formal handler... */
1642
1643 static int handle_autoindex(request_rec *r)
1644 {
1645     autoindex_config_rec *d;
1646     int allow_opts = ap_allow_options(r);
1647
1648     d = (autoindex_config_rec *) ap_get_module_config(r->per_dir_config,
1649                                                       &autoindex_module);
1650
1651     r->allowed |= (1 << M_GET);
1652     if (r->method_number != M_GET) {
1653         return DECLINED;
1654     }
1655
1656     /* OK, nothing easy.  Trot out the heavy artillery... */
1657
1658     if (allow_opts & OPT_INDEXES) {
1659         /* KLUDGE --- make the sub_req lookups happen in the right directory.
1660          * Fixing this in the sub_req_lookup functions themselves is difficult,
1661          * and would probably break virtual includes...
1662          */
1663
1664         if (r->filename[strlen(r->filename) - 1] != '/') {
1665             r->filename = ap_pstrcat(r->pool, r->filename, "/", NULL);
1666         }
1667         return index_directory(r, d);
1668     }
1669     else {
1670         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1671                      "Directory index forbidden by rule: %s", r->filename);
1672         return HTTP_FORBIDDEN;
1673     }
1674 }
1675
1676
1677 static const handler_rec autoindex_handlers[] =
1678 {
1679     {DIR_MAGIC_TYPE, handle_autoindex},
1680     {NULL}
1681 };
1682
1683 module MODULE_VAR_EXPORT autoindex_module =
1684 {
1685     STANDARD20_MODULE_STUFF,
1686     create_autoindex_config,    /* dir config creater */
1687     merge_autoindex_configs,    /* dir merger --- default is to override */
1688     NULL,                       /* server config */
1689     NULL,                       /* merge server config */
1690     autoindex_cmds,             /* command ap_table_t */
1691     autoindex_handlers,         /* handlers */
1692     NULL                        /* register hooks */
1693 };