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