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