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