]> granicus.if.org Git - apache/blob - modules/generators/mod_autoindex.c
8d514021a5ba4b6427cbe4bd0f8eaf7a8f22f285
[apache] / modules / generators / mod_autoindex.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * mod_autoindex.c: Handles the on-the-fly html index generation
19  *
20  * Rob McCool
21  * 3/23/93
22  *
23  * Adapted to Apache by rst.
24  *
25  * Version sort added by Martin Pool <mbp@humbug.org.au>.
26  */
27
28 #include "apr_strings.h"
29 #include "apr_fnmatch.h"
30 #include "apr_strings.h"
31 #include "apr_lib.h"
32
33 #define APR_WANT_STRFUNC
34 #include "apr_want.h"
35
36 #include "ap_config.h"
37 #include "httpd.h"
38 #include "http_config.h"
39 #include "http_core.h"
40 #include "http_request.h"
41 #include "http_protocol.h"
42 #include "http_log.h"
43 #include "http_main.h"
44 #include "util_script.h"
45
46 #include "mod_core.h"
47
48 module AP_MODULE_DECLARE_DATA autoindex_module;
49
50 /****************************************************************
51  *
52  * Handling configuration directives...
53  */
54
55 #define NO_OPTIONS          (1 <<  0)  /* Indexing options */
56 #define ICONS_ARE_LINKS     (1 <<  1)
57 #define SCAN_HTML_TITLES    (1 <<  2)
58 #define SUPPRESS_ICON       (1 <<  3)
59 #define SUPPRESS_LAST_MOD   (1 <<  4)
60 #define SUPPRESS_SIZE       (1 <<  5)
61 #define SUPPRESS_DESC       (1 <<  6)
62 #define SUPPRESS_PREAMBLE   (1 <<  7)
63 #define SUPPRESS_COLSORT    (1 <<  8)
64 #define SUPPRESS_RULES      (1 <<  9)
65 #define FOLDERS_FIRST       (1 << 10)
66 #define VERSION_SORT        (1 << 11)
67 #define TRACK_MODIFIED      (1 << 12)
68 #define FANCY_INDEXING      (1 << 13)
69 #define TABLE_INDEXING      (1 << 14)
70 #define IGNORE_CLIENT       (1 << 15)
71 #define IGNORE_CASE         (1 << 16)
72 #define EMIT_XHTML          (1 << 17)
73 #define SHOW_FORBIDDEN      (1 << 18)
74
75 #define K_NOADJUST 0
76 #define K_ADJUST 1
77 #define K_UNSET 2
78
79 /*
80  * Define keys for sorting.
81  */
82 #define K_NAME 'N'              /* Sort by file name (default) */
83 #define K_LAST_MOD 'M'          /* Last modification date */
84 #define K_SIZE 'S'              /* Size (absolute, not as displayed) */
85 #define K_DESC 'D'              /* Description */
86 #define K_VALID "NMSD"          /* String containing _all_ valid K_ opts */
87
88 #define D_ASCENDING 'A'
89 #define D_DESCENDING 'D'
90 #define D_VALID "AD"            /* String containing _all_ valid D_ opts */
91
92 /*
93  * These are the dimensions of the default icons supplied with Apache.
94  */
95 #define DEFAULT_ICON_WIDTH 20
96 #define DEFAULT_ICON_HEIGHT 22
97
98 /*
99  * Other default dimensions.
100  */
101 #define DEFAULT_NAME_WIDTH 23
102 #define DEFAULT_DESC_WIDTH 23
103
104 struct item {
105     char *type;
106     char *apply_to;
107     char *apply_path;
108     char *data;
109 };
110
111 typedef struct ai_desc_t {
112     char *pattern;
113     char *description;
114     int full_path;
115     int wildcards;
116 } ai_desc_t;
117
118 typedef struct autoindex_config_struct {
119
120     char *default_icon;
121     char *style_sheet;
122     apr_int32_t opts;
123     apr_int32_t incremented_opts;
124     apr_int32_t decremented_opts;
125     int name_width;
126     int name_adjust;
127     int desc_width;
128     int desc_adjust;
129     int icon_width;
130     int icon_height;
131     char default_keyid;
132     char default_direction;
133
134     apr_array_header_t *icon_list;
135     apr_array_header_t *alt_list;
136     apr_array_header_t *desc_list;
137     apr_array_header_t *ign_list;
138     apr_array_header_t *hdr_list;
139     apr_array_header_t *rdme_list;
140
141     char *ctype;
142     char *charset;
143 } autoindex_config_rec;
144
145 static char c_by_encoding, c_by_type, c_by_path;
146
147 #define BY_ENCODING &c_by_encoding
148 #define BY_TYPE &c_by_type
149 #define BY_PATH &c_by_path
150
151 /*
152  * This routine puts the standard HTML header at the top of the index page.
153  * We include the DOCTYPE because we may be using features therefrom (i.e.,
154  * HEIGHT and WIDTH attributes on the icons if we're FancyIndexing).
155  */
156 static void emit_preamble(request_rec *r, int xhtml, const char *title)
157 {
158     autoindex_config_rec *d;
159
160     d = (autoindex_config_rec *) ap_get_module_config(r->per_dir_config,
161                                                       &autoindex_module);
162
163     ap_rvputs(r, xhtml ? DOCTYPE_XHTML_1_0T : DOCTYPE_HTML_3_2,
164               "<html>\n <head>\n  <title>Index of ", title,
165               "</title>\n", NULL);
166     if (d->style_sheet != NULL) {
167         ap_rvputs(r, "  <link rel=\"stylesheet\" href=\"", d->style_sheet,
168                 "\" type=\"text/css\"", xhtml ? " />\n" : ">\n", NULL);
169     }
170     ap_rvputs(r, " </head>\n <body>\n", NULL);
171 }
172
173 static void push_item(apr_array_header_t *arr, char *type, const char *to,
174                       const char *path, const char *data)
175 {
176     struct item *p = (struct item *) apr_array_push(arr);
177
178     if (!to) {
179         to = "";
180     }
181     if (!path) {
182         path = "";
183     }
184
185     p->type = type;
186     p->data = data ? apr_pstrdup(arr->pool, data) : NULL;
187     p->apply_path = apr_pstrcat(arr->pool, path, "*", NULL);
188
189     if ((type == BY_PATH) && (!ap_is_matchexp(to))) {
190         p->apply_to = apr_pstrcat(arr->pool, "*", to, NULL);
191     }
192     else if (to) {
193         p->apply_to = apr_pstrdup(arr->pool, to);
194     }
195     else {
196         p->apply_to = NULL;
197     }
198 }
199
200 static const char *add_alt(cmd_parms *cmd, void *d, const char *alt,
201                            const char *to)
202 {
203     if (cmd->info == BY_PATH) {
204         if (!strcmp(to, "**DIRECTORY**")) {
205             to = "^^DIRECTORY^^";
206         }
207     }
208     if (cmd->info == BY_ENCODING) {
209         char *tmp = apr_pstrdup(cmd->pool, to);
210         ap_str_tolower(tmp);
211         to = tmp;
212     }
213
214     push_item(((autoindex_config_rec *) d)->alt_list, cmd->info, to,
215               cmd->path, alt);
216     return NULL;
217 }
218
219 static const char *add_icon(cmd_parms *cmd, void *d, const char *icon,
220                             const char *to)
221 {
222     char *iconbak = apr_pstrdup(cmd->pool, icon);
223
224     if (icon[0] == '(') {
225         char *alt;
226         char *cl = strchr(iconbak, ')');
227
228         if (cl == NULL) {
229             return "missing closing paren";
230         }
231         alt = ap_getword_nc(cmd->pool, &iconbak, ',');
232         *cl = '\0';                             /* Lose closing paren */
233         add_alt(cmd, d, &alt[1], to);
234     }
235     if (cmd->info == BY_PATH) {
236         if (!strcmp(to, "**DIRECTORY**")) {
237             to = "^^DIRECTORY^^";
238         }
239     }
240     if (cmd->info == BY_ENCODING) {
241         char *tmp = apr_pstrdup(cmd->pool, to);
242         ap_str_tolower(tmp);
243         to = tmp;
244     }
245
246     push_item(((autoindex_config_rec *) d)->icon_list, cmd->info, to,
247               cmd->path, iconbak);
248     return NULL;
249 }
250
251 /*
252  * Add description text for a filename pattern.  If the pattern has
253  * wildcards already (or we need to add them), add leading and
254  * trailing wildcards to it to ensure substring processing.  If the
255  * pattern contains a '/' anywhere, force wildcard matching mode,
256  * add a slash to the prefix so that "bar/bletch" won't be matched
257  * by "foobar/bletch", and make a note that there's a delimiter;
258  * the matching routine simplifies to just the actual filename
259  * whenever it can.  This allows definitions in parent directories
260  * to be made for files in subordinate ones using relative paths.
261  */
262
263 /*
264  * Absent a strcasestr() function, we have to force wildcards on
265  * systems for which "AAA" and "aaa" mean the same file.
266  */
267 #ifdef CASE_BLIND_FILESYSTEM
268 #define WILDCARDS_REQUIRED 1
269 #else
270 #define WILDCARDS_REQUIRED 0
271 #endif
272
273 static const char *add_desc(cmd_parms *cmd, void *d, const char *desc,
274                             const char *to)
275 {
276     autoindex_config_rec *dcfg = (autoindex_config_rec *) d;
277     ai_desc_t *desc_entry;
278     char *prefix = "";
279
280     desc_entry = (ai_desc_t *) apr_array_push(dcfg->desc_list);
281     desc_entry->full_path = (ap_strchr_c(to, '/') == NULL) ? 0 : 1;
282     desc_entry->wildcards = (WILDCARDS_REQUIRED
283                              || desc_entry->full_path
284                              || apr_fnmatch_test(to));
285     if (desc_entry->wildcards) {
286         prefix = desc_entry->full_path ? "*/" : "*";
287         desc_entry->pattern = apr_pstrcat(dcfg->desc_list->pool,
288                                           prefix, to, "*", NULL);
289     }
290     else {
291         desc_entry->pattern = apr_pstrdup(dcfg->desc_list->pool, to);
292     }
293     desc_entry->description = apr_pstrdup(dcfg->desc_list->pool, desc);
294     return NULL;
295 }
296
297 static const char *add_ignore(cmd_parms *cmd, void *d, const char *ext)
298 {
299     push_item(((autoindex_config_rec *) d)->ign_list, 0, ext, cmd->path, NULL);
300     return NULL;
301 }
302
303 static const char *add_header(cmd_parms *cmd, void *d, const char *name)
304 {
305     push_item(((autoindex_config_rec *) d)->hdr_list, 0, NULL, cmd->path,
306               name);
307     return NULL;
308 }
309
310 static const char *add_readme(cmd_parms *cmd, void *d, const char *name)
311 {
312     push_item(((autoindex_config_rec *) d)->rdme_list, 0, NULL, cmd->path,
313               name);
314     return NULL;
315 }
316
317 static const char *add_opts(cmd_parms *cmd, void *d, int argc, char *const argv[])
318 {
319     int i;
320     char *w;
321     apr_int32_t opts;
322     apr_int32_t opts_add;
323     apr_int32_t opts_remove;
324     char action;
325     autoindex_config_rec *d_cfg = (autoindex_config_rec *) d;
326
327     opts = d_cfg->opts;
328     opts_add = d_cfg->incremented_opts;
329     opts_remove = d_cfg->decremented_opts;
330
331     for (i = 0; i < argc; i++) {
332         int option = 0;
333         w = argv[i];
334
335         if ((*w == '+') || (*w == '-')) {
336             action = *(w++);
337         }
338         else {
339             action = '\0';
340         }
341         if (!strcasecmp(w, "FancyIndexing")) {
342             option = FANCY_INDEXING;
343         }
344         else if (!strcasecmp(w, "FoldersFirst")) {
345             option = FOLDERS_FIRST;
346         }
347         else if (!strcasecmp(w, "HTMLTable")) {
348             option = TABLE_INDEXING;
349         }
350         else if (!strcasecmp(w, "IconsAreLinks")) {
351             option = ICONS_ARE_LINKS;
352         }
353         else if (!strcasecmp(w, "IgnoreCase")) {
354             option = IGNORE_CASE;
355         }
356         else if (!strcasecmp(w, "IgnoreClient")) {
357             option = IGNORE_CLIENT;
358         }
359         else if (!strcasecmp(w, "ScanHTMLTitles")) {
360             option = SCAN_HTML_TITLES;
361         }
362         else if (!strcasecmp(w, "SuppressColumnSorting")) {
363             option = SUPPRESS_COLSORT;
364         }
365         else if (!strcasecmp(w, "SuppressDescription")) {
366             option = SUPPRESS_DESC;
367         }
368         else if (!strcasecmp(w, "SuppressHTMLPreamble")) {
369             option = SUPPRESS_PREAMBLE;
370         }
371         else if (!strcasecmp(w, "SuppressIcon")) {
372             option = SUPPRESS_ICON;
373         }
374         else if (!strcasecmp(w, "SuppressLastModified")) {
375             option = SUPPRESS_LAST_MOD;
376         }
377         else if (!strcasecmp(w, "SuppressSize")) {
378             option = SUPPRESS_SIZE;
379         }
380         else if (!strcasecmp(w, "SuppressRules")) {
381             option = SUPPRESS_RULES;
382         }
383         else if (!strcasecmp(w, "TrackModified")) {
384             option = TRACK_MODIFIED;
385         }
386         else if (!strcasecmp(w, "VersionSort")) {
387             option = VERSION_SORT;
388         }
389         else if (!strcasecmp(w, "XHTML")) {
390             option = EMIT_XHTML;
391         }
392         else if (!strcasecmp(w, "ShowForbidden")) {
393             option = SHOW_FORBIDDEN;
394         }
395         else if (!strcasecmp(w, "None")) {
396             if (action != '\0') {
397                 return "Cannot combine '+' or '-' with 'None' keyword";
398             }
399             opts = NO_OPTIONS;
400             opts_add = 0;
401             opts_remove = 0;
402         }
403         else if (!strcasecmp(w, "IconWidth")) {
404             if (action != '-') {
405                 d_cfg->icon_width = DEFAULT_ICON_WIDTH;
406             }
407             else {
408                 d_cfg->icon_width = 0;
409             }
410         }
411         else if (!strncasecmp(w, "IconWidth=", 10)) {
412             if (action == '-') {
413                 return "Cannot combine '-' with IconWidth=n";
414             }
415             d_cfg->icon_width = atoi(&w[10]);
416         }
417         else if (!strcasecmp(w, "IconHeight")) {
418             if (action != '-') {
419                 d_cfg->icon_height = DEFAULT_ICON_HEIGHT;
420             }
421             else {
422                 d_cfg->icon_height = 0;
423             }
424         }
425         else if (!strncasecmp(w, "IconHeight=", 11)) {
426             if (action == '-') {
427                 return "Cannot combine '-' with IconHeight=n";
428             }
429             d_cfg->icon_height = atoi(&w[11]);
430         }
431         else if (!strcasecmp(w, "NameWidth")) {
432             if (action != '-') {
433                 return "NameWidth with no value may only appear as "
434                        "'-NameWidth'";
435             }
436             d_cfg->name_width = DEFAULT_NAME_WIDTH;
437             d_cfg->name_adjust = K_NOADJUST;
438         }
439         else if (!strncasecmp(w, "NameWidth=", 10)) {
440             if (action == '-') {
441                 return "Cannot combine '-' with NameWidth=n";
442             }
443             if (w[10] == '*') {
444                 d_cfg->name_adjust = K_ADJUST;
445             }
446             else {
447                 int width = atoi(&w[10]);
448
449                 if (width && (width < 5)) {
450                     return "NameWidth value must be greater than 5";
451                 }
452                 d_cfg->name_width = width;
453                 d_cfg->name_adjust = K_NOADJUST;
454             }
455         }
456         else if (!strcasecmp(w, "DescriptionWidth")) {
457             if (action != '-') {
458                 return "DescriptionWidth with no value may only appear as "
459                        "'-DescriptionWidth'";
460             }
461             d_cfg->desc_width = DEFAULT_DESC_WIDTH;
462             d_cfg->desc_adjust = K_NOADJUST;
463         }
464         else if (!strncasecmp(w, "DescriptionWidth=", 17)) {
465             if (action == '-') {
466                 return "Cannot combine '-' with DescriptionWidth=n";
467             }
468             if (w[17] == '*') {
469                 d_cfg->desc_adjust = K_ADJUST;
470             }
471             else {
472                 int width = atoi(&w[17]);
473
474                 if (width && (width < 12)) {
475                     return "DescriptionWidth value must be greater than 12";
476                 }
477                 d_cfg->desc_width = width;
478                 d_cfg->desc_adjust = K_NOADJUST;
479             }
480         }
481         else if (!strncasecmp(w, "Type=", 5)) {
482             d_cfg->ctype = apr_pstrdup(cmd->pool, &w[5]);
483         }
484         else if (!strncasecmp(w, "Charset=", 8)) {
485             d_cfg->charset = apr_pstrdup(cmd->pool, &w[8]);
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,
514                                      const char *direction, const char *key)
515 {
516     autoindex_config_rec *d_cfg = (autoindex_config_rec *) m;
517
518     if (!strcasecmp(direction, "Ascending")) {
519         d_cfg->default_direction = D_ASCENDING;
520     }
521     else if (!strcasecmp(direction, "Descending")) {
522         d_cfg->default_direction = D_DESCENDING;
523     }
524     else {
525         return "First keyword must be 'Ascending' or 'Descending'";
526     }
527
528     if (!strcasecmp(key, "Name")) {
529         d_cfg->default_keyid = K_NAME;
530     }
531     else if (!strcasecmp(key, "Date")) {
532         d_cfg->default_keyid = K_LAST_MOD;
533     }
534     else if (!strcasecmp(key, "Size")) {
535         d_cfg->default_keyid = K_SIZE;
536     }
537     else if (!strcasecmp(key, "Description")) {
538         d_cfg->default_keyid = K_DESC;
539     }
540     else {
541         return "Second keyword must be 'Name', 'Date', 'Size', or "
542                "'Description'";
543     }
544
545     return NULL;
546 }
547
548 #define DIR_CMD_PERMS OR_INDEXES
549
550 static const command_rec autoindex_cmds[] =
551 {
552     AP_INIT_ITERATE2("AddIcon", add_icon, BY_PATH, DIR_CMD_PERMS,
553                      "an icon URL followed by one or more filenames"),
554     AP_INIT_ITERATE2("AddIconByType", add_icon, BY_TYPE, DIR_CMD_PERMS,
555                      "an icon URL followed by one or more MIME types"),
556     AP_INIT_ITERATE2("AddIconByEncoding", add_icon, BY_ENCODING, DIR_CMD_PERMS,
557                      "an icon URL followed by one or more content encodings"),
558     AP_INIT_ITERATE2("AddAlt", add_alt, BY_PATH, DIR_CMD_PERMS,
559                      "alternate descriptive text followed by one or more "
560                      "filenames"),
561     AP_INIT_ITERATE2("AddAltByType", add_alt, BY_TYPE, DIR_CMD_PERMS,
562                      "alternate descriptive text followed by one or more MIME "
563                      "types"),
564     AP_INIT_ITERATE2("AddAltByEncoding", add_alt, BY_ENCODING, DIR_CMD_PERMS,
565                      "alternate descriptive text followed by one or more "
566                      "content encodings"),
567     AP_INIT_TAKE_ARGV("IndexOptions", add_opts, NULL, DIR_CMD_PERMS,
568                       "one or more index options [+|-][]"),
569     AP_INIT_TAKE2("IndexOrderDefault", set_default_order, NULL, DIR_CMD_PERMS,
570                   "{Ascending,Descending} {Name,Size,Description,Date}"),
571     AP_INIT_ITERATE("IndexIgnore", add_ignore, NULL, DIR_CMD_PERMS,
572                     "one or more file extensions"),
573     AP_INIT_ITERATE2("AddDescription", add_desc, BY_PATH, DIR_CMD_PERMS,
574                      "Descriptive text followed by one or more filenames"),
575     AP_INIT_TAKE1("HeaderName", add_header, NULL, DIR_CMD_PERMS,
576                   "a filename"),
577     AP_INIT_TAKE1("ReadmeName", add_readme, NULL, DIR_CMD_PERMS,
578                   "a filename"),
579     AP_INIT_RAW_ARGS("FancyIndexing", ap_set_deprecated, NULL, OR_ALL,
580                      "The FancyIndexing directive is no longer supported. "
581                      "Use IndexOptions FancyIndexing."),
582     AP_INIT_TAKE1("DefaultIcon", ap_set_string_slot,
583                   (void *)APR_OFFSETOF(autoindex_config_rec, default_icon),
584                   DIR_CMD_PERMS, "an icon URL"),
585     AP_INIT_TAKE1("IndexStyleSheet", ap_set_string_slot,
586                   (void *)APR_OFFSETOF(autoindex_config_rec, style_sheet),
587                   DIR_CMD_PERMS, "URL to style sheet"),
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->desc_width = DEFAULT_DESC_WIDTH;
601     new->desc_adjust = K_UNSET;
602     new->icon_list = apr_array_make(p, 4, sizeof(struct item));
603     new->alt_list = apr_array_make(p, 4, sizeof(struct item));
604     new->desc_list = apr_array_make(p, 4, sizeof(ai_desc_t));
605     new->ign_list = apr_array_make(p, 4, sizeof(struct item));
606     new->hdr_list = apr_array_make(p, 4, sizeof(struct item));
607     new->rdme_list = apr_array_make(p, 4, sizeof(struct item));
608     new->opts = 0;
609     new->incremented_opts = 0;
610     new->decremented_opts = 0;
611     new->default_keyid = '\0';
612     new->default_direction = '\0';
613
614     return (void *) new;
615 }
616
617 static void *merge_autoindex_configs(apr_pool_t *p, void *basev, void *addv)
618 {
619     autoindex_config_rec *new;
620     autoindex_config_rec *base = (autoindex_config_rec *) basev;
621     autoindex_config_rec *add = (autoindex_config_rec *) addv;
622
623     new = (autoindex_config_rec *) apr_pcalloc(p, sizeof(autoindex_config_rec));
624     new->default_icon = add->default_icon ? add->default_icon
625                                           : base->default_icon;
626     new->style_sheet = add->style_sheet ? add->style_sheet
627                                           : base->style_sheet;
628     new->icon_height = add->icon_height ? add->icon_height : base->icon_height;
629     new->icon_width = add->icon_width ? add->icon_width : base->icon_width;
630
631     new->ctype = add->ctype ? add->ctype : base->ctype;
632     new->charset = add->charset ? add->charset : base->charset;
633
634     new->alt_list = apr_array_append(p, add->alt_list, base->alt_list);
635     new->ign_list = apr_array_append(p, add->ign_list, base->ign_list);
636     new->hdr_list = apr_array_append(p, add->hdr_list, base->hdr_list);
637     new->desc_list = apr_array_append(p, add->desc_list, base->desc_list);
638     new->icon_list = apr_array_append(p, add->icon_list, base->icon_list);
639     new->rdme_list = apr_array_append(p, add->rdme_list, base->rdme_list);
640     if (add->opts & NO_OPTIONS) {
641         /*
642          * If the current directory says 'no options' then we also
643          * clear any incremental mods from being inheritable further down.
644          */
645         new->opts = NO_OPTIONS;
646         new->incremented_opts = 0;
647         new->decremented_opts = 0;
648     }
649     else {
650         /*
651          * If there were any nonincremental options selected for
652          * this directory, they dominate and we don't inherit *anything.*
653          * Contrariwise, we *do* inherit if the only settings here are
654          * incremental ones.
655          */
656         if (add->opts == 0) {
657             new->incremented_opts = (base->incremented_opts
658                                      | add->incremented_opts)
659                                     & ~add->decremented_opts;
660             new->decremented_opts = (base->decremented_opts
661                                      | add->decremented_opts);
662             /*
663              * We may have incremental settings, so make sure we don't
664              * inadvertently inherit an IndexOptions None from above.
665              */
666             new->opts = (base->opts & ~NO_OPTIONS);
667         }
668         else {
669             /*
670              * There are local nonincremental settings, which clear
671              * all inheritance from above.  They *are* the new base settings.
672              */
673             new->opts = add->opts;;
674         }
675         /*
676          * We're guaranteed that there'll be no overlap between
677          * the add-options and the remove-options.
678          */
679         new->opts |= new->incremented_opts;
680         new->opts &= ~new->decremented_opts;
681     }
682     /*
683      * Inherit the NameWidth settings if there aren't any specific to
684      * the new location; otherwise we'll end up using the defaults set in the
685      * config-rec creation routine.
686      */
687     if (add->name_adjust == K_UNSET) {
688         new->name_width = base->name_width;
689         new->name_adjust = base->name_adjust;
690     }
691     else {
692         new->name_width = add->name_width;
693         new->name_adjust = add->name_adjust;
694     }
695
696     /*
697      * Likewise for DescriptionWidth.
698      */
699     if (add->desc_adjust == K_UNSET) {
700         new->desc_width = base->desc_width;
701         new->desc_adjust = base->desc_adjust;
702     }
703     else {
704         new->desc_width = add->desc_width;
705         new->desc_adjust = add->desc_adjust;
706     }
707
708     new->default_keyid = add->default_keyid ? add->default_keyid
709                                             : base->default_keyid;
710     new->default_direction = add->default_direction ? add->default_direction
711                                                     : base->default_direction;
712     return new;
713 }
714
715 /****************************************************************
716  *
717  * Looking things up in config entries...
718  */
719
720 /* Structure used to hold entries when we're actually building an index */
721
722 struct ent {
723     char *name;
724     char *icon;
725     char *alt;
726     char *desc;
727     apr_off_t size;
728     apr_time_t lm;
729     struct ent *next;
730     int ascending, ignore_case, version_sort;
731     char key;
732     int isdir;
733 };
734
735 static char *find_item(request_rec *r, apr_array_header_t *list, int path_only)
736 {
737     const char *content_type = ap_field_noparam(r->pool, r->content_type);
738     const char *content_encoding = r->content_encoding;
739     char *path = r->filename;
740
741     struct item *items = (struct item *) list->elts;
742     int i;
743
744     for (i = 0; i < list->nelts; ++i) {
745         struct item *p = &items[i];
746
747         /* Special cased for ^^DIRECTORY^^ and ^^BLANKICON^^ */
748         if ((path[0] == '^') || (!ap_strcmp_match(path, p->apply_path))) {
749             if (!*(p->apply_to)) {
750                 return p->data;
751             }
752             else if (p->type == BY_PATH || path[0] == '^') {
753                 if (!ap_strcmp_match(path, p->apply_to)) {
754                     return p->data;
755                 }
756             }
757             else if (!path_only) {
758                 if (!content_encoding) {
759                     if (p->type == BY_TYPE) {
760                         if (content_type
761                             && !ap_strcasecmp_match(content_type,
762                                                     p->apply_to)) {
763                             return p->data;
764                         }
765                     }
766                 }
767                 else {
768                     if (p->type == BY_ENCODING) {
769                         if (!ap_strcasecmp_match(content_encoding,
770                                                  p->apply_to)) {
771                             return p->data;
772                         }
773                     }
774                 }
775             }
776         }
777     }
778     return NULL;
779 }
780
781 #define find_icon(d,p,t) find_item(p,d->icon_list,t)
782 #define find_alt(d,p,t) find_item(p,d->alt_list,t)
783 #define find_header(d,p) find_item(p,d->hdr_list,0)
784 #define find_readme(d,p) find_item(p,d->rdme_list,0)
785
786 static char *find_default_item(char *bogus_name, apr_array_header_t *list)
787 {
788     request_rec r;
789     /* Bleah.  I tried to clean up find_item, and it lead to this bit
790      * of ugliness.   Note that the fields initialized are precisely
791      * those that find_item looks at...
792      */
793     r.filename = bogus_name;
794     r.content_type = r.content_encoding = NULL;
795     return find_item(&r, list, 1);
796 }
797
798 #define find_default_icon(d,n) find_default_item(n, d->icon_list)
799 #define find_default_alt(d,n) find_default_item(n, d->alt_list)
800
801 /*
802  * Look through the list of pattern/description pairs and return the first one
803  * if any) that matches the filename in the request.  If multiple patterns
804  * match, only the first one is used; since the order in the array is the
805  * same as the order in which directives were processed, earlier matching
806  * directives will dominate.
807  */
808
809 #ifdef CASE_BLIND_FILESYSTEM
810 #define MATCH_FLAGS APR_FNM_CASE_BLIND
811 #else
812 #define MATCH_FLAGS 0
813 #endif
814
815 static char *find_desc(autoindex_config_rec *dcfg, const char *filename_full)
816 {
817     int i;
818     ai_desc_t *list = (ai_desc_t *) dcfg->desc_list->elts;
819     const char *filename_only;
820     const char *filename;
821
822     /*
823      * If the filename includes a path, extract just the name itself
824      * for the simple matches.
825      */
826     if ((filename_only = ap_strrchr_c(filename_full, '/')) == NULL) {
827         filename_only = filename_full;
828     }
829     else {
830         filename_only++;
831     }
832     for (i = 0; i < dcfg->desc_list->nelts; ++i) {
833         ai_desc_t *tuple = &list[i];
834         int found;
835
836         /*
837          * Only use the full-path filename if the pattern contains '/'s.
838          */
839         filename = (tuple->full_path) ? filename_full : filename_only;
840         /*
841          * Make the comparison using the cheapest method; only do
842          * wildcard checking if we must.
843          */
844         if (tuple->wildcards) {
845             found = (apr_fnmatch(tuple->pattern, filename, MATCH_FLAGS) == 0);
846         }
847         else {
848             found = (ap_strstr_c(filename, tuple->pattern) != NULL);
849         }
850         if (found) {
851             return tuple->description;
852         }
853     }
854     return NULL;
855 }
856
857 static int ignore_entry(autoindex_config_rec *d, char *path)
858 {
859     apr_array_header_t *list = d->ign_list;
860     struct item *items = (struct item *) list->elts;
861     char *tt;
862     int i;
863
864     if ((tt = strrchr(path, '/')) == NULL) {
865         tt = path;
866     }
867     else {
868         tt++;
869     }
870
871     for (i = 0; i < list->nelts; ++i) {
872         struct item *p = &items[i];
873         char *ap;
874
875         if ((ap = strrchr(p->apply_to, '/')) == NULL) {
876             ap = p->apply_to;
877         }
878         else {
879             ap++;
880         }
881
882 #ifndef CASE_BLIND_FILESYSTEM
883         if (!ap_strcmp_match(path, p->apply_path)
884             && !ap_strcmp_match(tt, ap)) {
885             return 1;
886         }
887 #else  /* !CASE_BLIND_FILESYSTEM */
888         /*
889          * On some platforms, the match must be case-blind.  This is really
890          * a factor of the filesystem involved, but we can't detect that
891          * reliably - so we have to granularise at the OS level.
892          */
893         if (!ap_strcasecmp_match(path, p->apply_path)
894             && !ap_strcasecmp_match(tt, ap)) {
895             return 1;
896         }
897 #endif /* !CASE_BLIND_FILESYSTEM */
898     }
899     return 0;
900 }
901
902 /*****************************************************************
903  *
904  * Actually generating output
905  */
906
907 /*
908  * Elements of the emitted document:
909  *      Preamble
910  *              Emitted unless SUPPRESS_PREAMBLE is set AND ap_run_sub_req
911  *              succeeds for the (content_type == text/html) header file.
912  *      Header file
913  *              Emitted if found (and able).
914  *      H1 tag line
915  *              Emitted if a header file is NOT emitted.
916  *      Directory stuff
917  *              Always emitted.
918  *      HR
919  *              Emitted if FANCY_INDEXING is set.
920  *      Readme file
921  *              Emitted if found (and able).
922  *      ServerSig
923  *              Emitted if ServerSignature is not Off AND a readme file
924  *              is NOT emitted.
925  *      Postamble
926  *              Emitted unless SUPPRESS_PREAMBLE is set AND ap_run_sub_req
927  *              succeeds for the (content_type == text/html) readme file.
928  */
929
930
931 /*
932  * emit a plain text file
933  */
934 static void do_emit_plain(request_rec *r, apr_file_t *f)
935 {
936     char buf[AP_IOBUFSIZE + 1];
937     int ch;
938     apr_size_t i, c, n;
939     apr_status_t rv;
940
941     ap_rputs("<pre>\n", r);
942     while (!apr_file_eof(f)) {
943         do {
944             n = sizeof(char) * AP_IOBUFSIZE;
945             rv = apr_file_read(f, buf, &n);
946         } while (APR_STATUS_IS_EINTR(rv));
947         if (n == 0 || rv != APR_SUCCESS) {
948             /* ###: better error here? */
949             break;
950         }
951         buf[n] = '\0';
952         c = 0;
953         while (c < n) {
954             for (i = c; i < n; i++) {
955                 if (buf[i] == '<' || buf[i] == '>' || buf[i] == '&') {
956                     break;
957                 }
958             }
959             ch = buf[i];
960             buf[i] = '\0';
961             ap_rputs(&buf[c], r);
962             if (ch == '<') {
963                 ap_rputs("&lt;", r);
964             }
965             else if (ch == '>') {
966                 ap_rputs("&gt;", r);
967             }
968             else if (ch == '&') {
969                 ap_rputs("&amp;", r);
970             }
971             c = i + 1;
972         }
973     }
974     ap_rputs("</pre>\n", r);
975 }
976
977 /*
978  * Handle the preamble through the H1 tag line, inclusive.  Locate
979  * the file with a subrequests.  Process text/html documents by actually
980  * running the subrequest; text/xxx documents get copied verbatim,
981  * and any other content type is ignored.  This means that a non-text
982  * document (such as HEADER.gif) might get multiviewed as the result
983  * instead of a text document, meaning nothing will be displayed, but
984  * oh well.
985  */
986 static void emit_head(request_rec *r, char *header_fname, int suppress_amble,
987                       int emit_xhtml, char *title)
988 {
989     apr_table_t *hdrs = r->headers_in;
990     apr_file_t *f = NULL;
991     request_rec *rr = NULL;
992     int emit_amble = 1;
993     int emit_H1 = 1;
994     const char *r_accept;
995     const char *r_accept_enc;
996
997     /*
998      * If there's a header file, send a subrequest to look for it.  If it's
999      * found and html do the subrequest, otherwise handle it
1000      */
1001     r_accept = apr_table_get(hdrs, "Accept");
1002     r_accept_enc = apr_table_get(hdrs, "Accept-Encoding");
1003     apr_table_setn(hdrs, "Accept", "text/html, text/plain");
1004     apr_table_unset(hdrs, "Accept-Encoding");
1005
1006
1007     if ((header_fname != NULL) && r->args) {
1008         header_fname = apr_pstrcat(r->pool, header_fname, "?", r->args, NULL);
1009     }
1010
1011     if ((header_fname != NULL)
1012         && (rr = ap_sub_req_lookup_uri(header_fname, r, r->output_filters))
1013         && (rr->status == HTTP_OK)
1014         && (rr->filename != NULL)
1015         && (rr->finfo.filetype == APR_REG)) {
1016         /*
1017          * Check for the two specific cases we allow: text/html and
1018          * text/anything-else.  The former is allowed to be processed for
1019          * SSIs.
1020          */
1021         if (rr->content_type != NULL) {
1022             if (!strcasecmp(ap_field_noparam(r->pool, rr->content_type),
1023                             "text/html")) {
1024                 ap_filter_t *f;
1025                /* Hope everything will work... */
1026                 emit_amble = 0;
1027                 emit_H1 = 0;
1028
1029                 if (! suppress_amble) {
1030                     emit_preamble(r, emit_xhtml, title);
1031                 }
1032                 /* This is a hack, but I can't find any better way to do this.
1033                  * The problem is that we have already created the sub-request,
1034                  * but we just inserted the OLD_WRITE filter, and the
1035                  * sub-request needs to pass its data through the OLD_WRITE
1036                  * filter, or things go horribly wrong (missing data, data in
1037                  * the wrong order, etc).  To fix it, if you create a
1038                  * sub-request and then insert the OLD_WRITE filter before you
1039                  * run the request, you need to make sure that the sub-request
1040                  * data goes through the OLD_WRITE filter.  Just steal this
1041                  * code.  The long-term solution is to remove the ap_r*
1042                  * functions.
1043                  */
1044                 for (f=rr->output_filters;
1045                      f->frec != ap_subreq_core_filter_handle; f = f->next);
1046                 f->next = r->output_filters;
1047
1048                 /*
1049                  * If there's a problem running the subrequest, display the
1050                  * preamble if we didn't do it before -- the header file
1051                  * didn't get displayed.
1052                  */
1053                 if (ap_run_sub_req(rr) != OK) {
1054                     /* It didn't work */
1055                     emit_amble = suppress_amble;
1056                     emit_H1 = 1;
1057                 }
1058             }
1059             else if (!strncasecmp("text/", rr->content_type, 5)) {
1060                 /*
1061                  * If we can open the file, prefix it with the preamble
1062                  * regardless; since we'll be sending a <pre> block around
1063                  * the file's contents, any HTML header it had won't end up
1064                  * where it belongs.
1065                  */
1066                 if (apr_file_open(&f, rr->filename, APR_READ,
1067                                   APR_OS_DEFAULT, r->pool) == APR_SUCCESS) {
1068                     emit_preamble(r, emit_xhtml, title);
1069                     emit_amble = 0;
1070                     do_emit_plain(r, f);
1071                     apr_file_close(f);
1072                     emit_H1 = 0;
1073                 }
1074             }
1075         }
1076     }
1077
1078     if (r_accept) {
1079         apr_table_setn(hdrs, "Accept", r_accept);
1080     }
1081     else {
1082         apr_table_unset(hdrs, "Accept");
1083     }
1084
1085     if (r_accept_enc) {
1086         apr_table_setn(hdrs, "Accept-Encoding", r_accept_enc);
1087     }
1088
1089     if (emit_amble) {
1090         emit_preamble(r, emit_xhtml, title);
1091     }
1092     if (emit_H1) {
1093         ap_rvputs(r, "<h1>Index of ", title, "</h1>\n", NULL);
1094     }
1095     if (rr != NULL) {
1096         ap_destroy_sub_req(rr);
1097     }
1098 }
1099
1100
1101 /*
1102  * Handle the Readme file through the postamble, inclusive.  Locate
1103  * the file with a subrequests.  Process text/html documents by actually
1104  * running the subrequest; text/xxx documents get copied verbatim,
1105  * and any other content type is ignored.  This means that a non-text
1106  * document (such as FOOTER.gif) might get multiviewed as the result
1107  * instead of a text document, meaning nothing will be displayed, but
1108  * oh well.
1109  */
1110 static void emit_tail(request_rec *r, char *readme_fname, int suppress_amble)
1111 {
1112     apr_file_t *f = NULL;
1113     request_rec *rr = NULL;
1114     int suppress_post = 0;
1115     int suppress_sig = 0;
1116
1117     /*
1118      * If there's a readme file, send a subrequest to look for it.  If it's
1119      * found and a text file, handle it -- otherwise fall through and
1120      * pretend there's nothing there.
1121      */
1122     if ((readme_fname != NULL)
1123         && (rr = ap_sub_req_lookup_uri(readme_fname, r, r->output_filters))
1124         && (rr->status == HTTP_OK)
1125         && (rr->filename != NULL)
1126         && rr->finfo.filetype == APR_REG) {
1127         /*
1128          * Check for the two specific cases we allow: text/html and
1129          * text/anything-else.  The former is allowed to be processed for
1130          * SSIs.
1131          */
1132         if (rr->content_type != NULL) {
1133             if (!strcasecmp(ap_field_noparam(r->pool, rr->content_type),
1134                             "text/html")) {
1135                 ap_filter_t *f;
1136                 for (f=rr->output_filters;
1137                      f->frec != ap_subreq_core_filter_handle; f = f->next);
1138                 f->next = r->output_filters;
1139
1140
1141                 if (ap_run_sub_req(rr) == OK) {
1142                     /* worked... */
1143                     suppress_sig = 1;
1144                     suppress_post = suppress_amble;
1145                 }
1146             }
1147             else if (!strncasecmp("text/", rr->content_type, 5)) {
1148                 /*
1149                  * If we can open the file, suppress the signature.
1150                  */
1151                 if (apr_file_open(&f, rr->filename, APR_READ,
1152                                   APR_OS_DEFAULT, r->pool) == APR_SUCCESS) {
1153                     do_emit_plain(r, f);
1154                     apr_file_close(f);
1155                     suppress_sig = 1;
1156                 }
1157             }
1158         }
1159     }
1160
1161     if (!suppress_sig) {
1162         ap_rputs(ap_psignature("", r), r);
1163     }
1164     if (!suppress_post) {
1165         ap_rputs("</body></html>\n", r);
1166     }
1167     if (rr != NULL) {
1168         ap_destroy_sub_req(rr);
1169     }
1170 }
1171
1172
1173 static char *find_title(request_rec *r)
1174 {
1175     char titlebuf[MAX_STRING_LEN], *find = "<title>";
1176     apr_file_t *thefile = NULL;
1177     int x, y, p;
1178     apr_size_t n;
1179
1180     if (r->status != HTTP_OK) {
1181         return NULL;
1182     }
1183     if ((r->content_type != NULL)
1184         && (!strcasecmp(ap_field_noparam(r->pool, r->content_type),
1185                         "text/html")
1186             || !strcmp(r->content_type, INCLUDES_MAGIC_TYPE))
1187         && !r->content_encoding) {
1188         if (apr_file_open(&thefile, r->filename, APR_READ,
1189                           APR_OS_DEFAULT, r->pool) != APR_SUCCESS) {
1190             return NULL;
1191         }
1192         n = sizeof(char) * (MAX_STRING_LEN - 1);
1193         apr_file_read(thefile, titlebuf, &n);
1194         if (n <= 0) {
1195             apr_file_close(thefile);
1196             return NULL;
1197         }
1198         titlebuf[n] = '\0';
1199         for (x = 0, p = 0; titlebuf[x]; x++) {
1200             if (apr_tolower(titlebuf[x]) == find[p]) {
1201                 if (!find[++p]) {
1202                     if ((p = ap_ind(&titlebuf[++x], '<')) != -1) {
1203                         titlebuf[x + p] = '\0';
1204                     }
1205                     /* Scan for line breaks for Tanmoy's secretary */
1206                     for (y = x; titlebuf[y]; y++) {
1207                         if ((titlebuf[y] == CR) || (titlebuf[y] == LF)) {
1208                             if (y == x) {
1209                                 x++;
1210                             }
1211                             else {
1212                                 titlebuf[y] = ' ';
1213                             }
1214                         }
1215                     }
1216                     apr_file_close(thefile);
1217                     return apr_pstrdup(r->pool, &titlebuf[x]);
1218                 }
1219             }
1220             else {
1221                 p = 0;
1222             }
1223         }
1224         apr_file_close(thefile);
1225     }
1226     return NULL;
1227 }
1228
1229 static struct ent *make_parent_entry(apr_int32_t autoindex_opts,
1230                                      autoindex_config_rec *d,
1231                                      request_rec *r, char keyid,
1232                                      char direction)
1233 {
1234     struct ent *p = (struct ent *) apr_pcalloc(r->pool, sizeof(struct ent));
1235     char *testpath;
1236     /*
1237      * p->name is now the true parent URI.
1238      * testpath is a crafted lie, so that the syntax '/some/..'
1239      * (or simply '..')be used to describe 'up' from '/some/'
1240      * when processeing IndexIgnore, and Icon|Alt|Desc configs.
1241      */
1242
1243     /* The output has always been to the parent.  Don't make ourself
1244      * our own parent (worthless cyclical reference).
1245      */
1246     if (!(p->name = ap_make_full_path(r->pool, r->uri, "../"))) {
1247         return (NULL);
1248     }
1249     ap_getparents(p->name);
1250     if (!*p->name) {
1251         return (NULL);
1252     }
1253
1254     /* IndexIgnore has always compared "/thispath/.." */
1255     testpath = ap_make_full_path(r->pool, r->filename, "..");
1256     if (ignore_entry(d, testpath)) {
1257         return (NULL);
1258     }
1259
1260     p->size = -1;
1261     p->lm = -1;
1262     p->key = apr_toupper(keyid);
1263     p->ascending = (apr_toupper(direction) == D_ASCENDING);
1264     p->version_sort = autoindex_opts & VERSION_SORT;
1265     if (autoindex_opts & FANCY_INDEXING) {
1266         if (!(p->icon = find_default_icon(d, testpath))) {
1267             p->icon = find_default_icon(d, "^^DIRECTORY^^");
1268         }
1269         if (!(p->alt = find_default_alt(d, testpath))) {
1270             if (!(p->alt = find_default_alt(d, "^^DIRECTORY^^"))) {
1271                 p->alt = "DIR";
1272             }
1273         }
1274         p->desc = find_desc(d, testpath);
1275     }
1276     return p;
1277 }
1278
1279 static struct ent *make_autoindex_entry(const apr_finfo_t *dirent,
1280                                         int autoindex_opts,
1281                                         autoindex_config_rec *d,
1282                                         request_rec *r, char keyid,
1283                                         char direction,
1284                                         const char *pattern)
1285 {
1286     request_rec *rr;
1287     struct ent *p;
1288     int show_forbidden = 0;
1289
1290     /* Dot is ignored, Parent is handled by make_parent_entry() */
1291     if ((dirent->name[0] == '.') && (!dirent->name[1]
1292         || ((dirent->name[1] == '.') && !dirent->name[2])))
1293         return (NULL);
1294
1295     /*
1296      * On some platforms, the match must be case-blind.  This is really
1297      * a factor of the filesystem involved, but we can't detect that
1298      * reliably - so we have to granularise at the OS level.
1299      */
1300     if (pattern && (apr_fnmatch(pattern, dirent->name,
1301                                 APR_FNM_NOESCAPE | APR_FNM_PERIOD
1302 #ifdef CASE_BLIND_FILESYSTEM
1303                                 | APR_FNM_CASE_BLIND
1304 #endif
1305                                 )
1306                     != APR_SUCCESS)) {
1307         return (NULL);
1308     }
1309
1310     if (ignore_entry(d, ap_make_full_path(r->pool,
1311                                           r->filename, dirent->name))) {
1312         return (NULL);
1313     }
1314
1315     if (!(rr = ap_sub_req_lookup_dirent(dirent, r, AP_SUBREQ_NO_ARGS, NULL))) {
1316         return (NULL);
1317     }
1318
1319     if((autoindex_opts & SHOW_FORBIDDEN)
1320         && (rr->status == HTTP_UNAUTHORIZED || rr->status == HTTP_FORBIDDEN)) {
1321         show_forbidden = 1;
1322     }
1323
1324     if ((rr->finfo.filetype != APR_DIR && rr->finfo.filetype != APR_REG)
1325         || !(rr->status == OK || ap_is_HTTP_SUCCESS(rr->status)
1326                               || ap_is_HTTP_REDIRECT(rr->status)
1327                               || show_forbidden == 1)) {
1328         ap_destroy_sub_req(rr);
1329         return (NULL);
1330     }
1331
1332     p = (struct ent *) apr_pcalloc(r->pool, sizeof(struct ent));
1333     if (dirent->filetype == APR_DIR) {
1334         p->name = apr_pstrcat(r->pool, dirent->name, "/", NULL);
1335     }
1336     else {
1337         p->name = apr_pstrdup(r->pool, dirent->name);
1338     }
1339     p->size = -1;
1340     p->icon = NULL;
1341     p->alt = NULL;
1342     p->desc = NULL;
1343     p->lm = -1;
1344     p->isdir = 0;
1345     p->key = apr_toupper(keyid);
1346     p->ascending = (apr_toupper(direction) == D_ASCENDING);
1347     p->version_sort = !!(autoindex_opts & VERSION_SORT);
1348     p->ignore_case = !!(autoindex_opts & IGNORE_CASE);
1349
1350     if (autoindex_opts & (FANCY_INDEXING | TABLE_INDEXING)) {
1351         p->lm = rr->finfo.mtime;
1352         if (dirent->filetype == APR_DIR) {
1353             if (autoindex_opts & FOLDERS_FIRST) {
1354                 p->isdir = 1;
1355             }
1356             rr->filename = ap_make_dirstr_parent (rr->pool, rr->filename);
1357
1358             /* omit the trailing slash (1.3 compat) */
1359             rr->filename[strlen(rr->filename) - 1] = '\0';
1360
1361             if (!(p->icon = find_icon(d, rr, 1))) {
1362                 p->icon = find_default_icon(d, "^^DIRECTORY^^");
1363             }
1364             if (!(p->alt = find_alt(d, rr, 1))) {
1365                 if (!(p->alt = find_default_alt(d, "^^DIRECTORY^^"))) {
1366                     p->alt = "DIR";
1367                 }
1368             }
1369         }
1370         else {
1371             p->icon = find_icon(d, rr, 0);
1372             p->alt = find_alt(d, rr, 0);
1373             p->size = rr->finfo.size;
1374         }
1375
1376         p->desc = find_desc(d, rr->filename);
1377
1378         if ((!p->desc) && (autoindex_opts & SCAN_HTML_TITLES)) {
1379             p->desc = apr_pstrdup(r->pool, find_title(rr));
1380         }
1381     }
1382     ap_destroy_sub_req(rr);
1383     /*
1384      * We don't need to take any special action for the file size key.
1385      * If we did, it would go here.
1386      */
1387     if (keyid == K_LAST_MOD) {
1388         if (p->lm < 0) {
1389             p->lm = 0;
1390         }
1391     }
1392     return (p);
1393 }
1394
1395 static char *terminate_description(autoindex_config_rec *d, char *desc,
1396                                    apr_int32_t autoindex_opts, int desc_width)
1397 {
1398     int maxsize = desc_width;
1399     register int x;
1400
1401     /*
1402      * If there's no DescriptionWidth in effect, default to the old
1403      * behaviour of adjusting the description size depending upon
1404      * what else is being displayed.  Otherwise, stick with the
1405      * setting.
1406      */
1407     if (d->desc_adjust == K_UNSET) {
1408         if (autoindex_opts & SUPPRESS_ICON) {
1409             maxsize += 6;
1410         }
1411         if (autoindex_opts & SUPPRESS_LAST_MOD) {
1412             maxsize += 19;
1413         }
1414         if (autoindex_opts & SUPPRESS_SIZE) {
1415             maxsize += 7;
1416         }
1417     }
1418     for (x = 0; desc[x] && ((maxsize > 0) || (desc[x] == '<')); x++) {
1419         if (desc[x] == '<') {
1420             while (desc[x] != '>') {
1421                 if (!desc[x]) {
1422                     maxsize = 0;
1423                     break;
1424                 }
1425                 ++x;
1426             }
1427         }
1428         else if (desc[x] == '&') {
1429             /* entities like &auml; count as one character */
1430             --maxsize;
1431             for ( ; desc[x] != ';'; ++x) {
1432                 if (desc[x] == '\0') {
1433                      maxsize = 0;
1434                      break;
1435                 }
1436             }
1437         }
1438         else {
1439             --maxsize;
1440         }
1441     }
1442     if (!maxsize && desc[x] != '\0') {
1443         desc[x - 1] = '>';      /* Grump. */
1444         desc[x] = '\0';         /* Double Grump! */
1445     }
1446     return desc;
1447 }
1448
1449 /*
1450  * Emit the anchor for the specified field.  If a field is the key for the
1451  * current request, the link changes its meaning to reverse the order when
1452  * selected again.  Non-active fields always start in ascending order.
1453  */
1454 static void emit_link(request_rec *r, const char *anchor, char column,
1455                       char curkey, char curdirection,
1456                       const char *colargs, int nosort)
1457 {
1458     if (!nosort) {
1459         char qvalue[9];
1460
1461         qvalue[0] = '?';
1462         qvalue[1] = 'C';
1463         qvalue[2] = '=';
1464         qvalue[3] = column;
1465         qvalue[4] = ';';
1466         qvalue[5] = 'O';
1467         qvalue[6] = '=';
1468                     /* reverse? */
1469         qvalue[7] = ((curkey == column) && (curdirection == D_ASCENDING))
1470                       ? D_DESCENDING : D_ASCENDING;
1471         qvalue[8] = '\0';
1472         ap_rvputs(r, "<a href=\"", qvalue, colargs ? colargs : "",
1473                      "\">", anchor, "</a>", NULL);
1474     }
1475     else {
1476         ap_rputs(anchor, r);
1477     }
1478 }
1479
1480 static void output_directories(struct ent **ar, int n,
1481                                autoindex_config_rec *d, request_rec *r,
1482                                apr_int32_t autoindex_opts, char keyid,
1483                                char direction, const char *colargs)
1484 {
1485     int x;
1486     apr_size_t rv;
1487     char *name = r->uri;
1488     char *tp;
1489     int static_columns = !!(autoindex_opts & SUPPRESS_COLSORT);
1490     apr_pool_t *scratch;
1491     int name_width;
1492     int desc_width;
1493     char *name_scratch;
1494     char *pad_scratch;
1495     char *breakrow = "";
1496
1497     apr_pool_create(&scratch, r->pool);
1498     if (name[0] == '\0') {
1499         name = "/";
1500     }
1501
1502     name_width = d->name_width;
1503     desc_width = d->desc_width;
1504
1505     if ((autoindex_opts & (FANCY_INDEXING | TABLE_INDEXING))
1506                         == FANCY_INDEXING) {
1507         if (d->name_adjust == K_ADJUST) {
1508             for (x = 0; x < n; x++) {
1509                 int t = strlen(ar[x]->name);
1510                 if (t > name_width) {
1511                     name_width = t;
1512                 }
1513             }
1514         }
1515
1516         if (d->desc_adjust == K_ADJUST) {
1517             for (x = 0; x < n; x++) {
1518                 if (ar[x]->desc != NULL) {
1519                     int t = strlen(ar[x]->desc);
1520                     if (t > desc_width) {
1521                         desc_width = t;
1522                     }
1523                 }
1524             }
1525         }
1526     }
1527     name_scratch = apr_palloc(r->pool, name_width + 1);
1528     pad_scratch = apr_palloc(r->pool, name_width + 1);
1529     memset(pad_scratch, ' ', name_width);
1530     pad_scratch[name_width] = '\0';
1531
1532     if (autoindex_opts & TABLE_INDEXING) {
1533         int cols = 1;
1534         ap_rputs("<table><tr>", r);
1535         if (!(autoindex_opts & SUPPRESS_ICON)) {
1536             ap_rputs("<th>", r);
1537             if ((tp = find_default_icon(d, "^^BLANKICON^^"))) {
1538                 ap_rvputs(r, "<img src=\"", ap_escape_html(scratch, tp),
1539                              "\" alt=\"[ICO]\"", NULL);
1540                 if (d->icon_width) {
1541                     ap_rprintf(r, " width=\"%d\"", d->icon_width);
1542                 }
1543                 if (d->icon_height) {
1544                     ap_rprintf(r, " height=\"%d\"", d->icon_height);
1545                 }
1546
1547                 if (autoindex_opts & EMIT_XHTML) {
1548                     ap_rputs(" /", r);
1549                 }
1550                 ap_rputs("></th>", r);
1551             }
1552             else {
1553                 ap_rputs("&nbsp;</th>", r);
1554             }
1555
1556             ++cols;
1557         }
1558         ap_rputs("<th>", r);
1559         emit_link(r, "Name", K_NAME, keyid, direction,
1560                   colargs, static_columns);
1561         if (!(autoindex_opts & SUPPRESS_LAST_MOD)) {
1562             ap_rputs("</th><th>", r);
1563             emit_link(r, "Last modified", K_LAST_MOD, keyid, direction,
1564                       colargs, static_columns);
1565             ++cols;
1566         }
1567         if (!(autoindex_opts & SUPPRESS_SIZE)) {
1568             ap_rputs("</th><th>", r);
1569             emit_link(r, "Size", K_SIZE, keyid, direction,
1570                       colargs, static_columns);
1571             ++cols;
1572         }
1573         if (!(autoindex_opts & SUPPRESS_DESC)) {
1574             ap_rputs("</th><th>", r);
1575             emit_link(r, "Description", K_DESC, keyid, direction,
1576                       colargs, static_columns);
1577             ++cols;
1578         }
1579         if (!(autoindex_opts & SUPPRESS_RULES)) {
1580             breakrow = apr_psprintf(r->pool,
1581                                     "<tr><th colspan=\"%d\">"
1582                                     "<hr%s></th></tr>\n", cols,
1583                                     (autoindex_opts & EMIT_XHTML) ? " /" : "");
1584         }
1585         ap_rvputs(r, "</th></tr>", breakrow, NULL);
1586     }
1587     else if (autoindex_opts & FANCY_INDEXING) {
1588         ap_rputs("<pre>", r);
1589         if (!(autoindex_opts & SUPPRESS_ICON)) {
1590             if ((tp = find_default_icon(d, "^^BLANKICON^^"))) {
1591                 ap_rvputs(r, "<img src=\"", ap_escape_html(scratch, tp),
1592                              "\" alt=\"Icon \"", NULL);
1593                 if (d->icon_width) {
1594                     ap_rprintf(r, " width=\"%d\"", d->icon_width);
1595                 }
1596                 if (d->icon_height) {
1597                     ap_rprintf(r, " height=\"%d\"", d->icon_height);
1598                 }
1599
1600                 if (autoindex_opts & EMIT_XHTML) {
1601                     ap_rputs(" /", r);
1602                 }
1603                 ap_rputs("> ", r);
1604             }
1605             else {
1606                 ap_rputs("      ", r);
1607             }
1608         }
1609         emit_link(r, "Name", K_NAME, keyid, direction,
1610                   colargs, static_columns);
1611         ap_rputs(pad_scratch + 4, r);
1612         /*
1613          * Emit the guaranteed-at-least-one-space-between-columns byte.
1614          */
1615         ap_rputs(" ", r);
1616         if (!(autoindex_opts & SUPPRESS_LAST_MOD)) {
1617             emit_link(r, "Last modified", K_LAST_MOD, keyid, direction,
1618                       colargs, static_columns);
1619             ap_rputs("      ", r);
1620         }
1621         if (!(autoindex_opts & SUPPRESS_SIZE)) {
1622             emit_link(r, "Size", K_SIZE, keyid, direction,
1623                       colargs, static_columns);
1624             ap_rputs("  ", r);
1625         }
1626         if (!(autoindex_opts & SUPPRESS_DESC)) {
1627             emit_link(r, "Description", K_DESC, keyid, direction,
1628                       colargs, static_columns);
1629         }
1630         if (!(autoindex_opts & SUPPRESS_RULES)) {
1631             ap_rputs("<hr", r);
1632             if (autoindex_opts & EMIT_XHTML) {
1633                 ap_rputs(" /", r);
1634             }
1635             ap_rputs(">", r);
1636         }
1637         else {
1638             ap_rputc('\n', r);
1639         }
1640     }
1641     else {
1642         ap_rputs("<ul>", r);
1643     }
1644
1645     for (x = 0; x < n; x++) {
1646         char *anchor, *t, *t2;
1647         int nwidth;
1648
1649         apr_pool_clear(scratch);
1650
1651         t = ar[x]->name;
1652         anchor = ap_escape_html(scratch, ap_os_escape_path(scratch, t, 0));
1653
1654         if (!x && t[0] == '/') {
1655             t2 = "Parent Directory";
1656         }
1657         else {
1658             t2 = t;
1659         }
1660
1661         if (autoindex_opts & TABLE_INDEXING) {
1662             ap_rputs("<tr>", r);
1663             if (!(autoindex_opts & SUPPRESS_ICON)) {
1664                 ap_rputs("<td valign=\"top\">", r);
1665                 if (autoindex_opts & ICONS_ARE_LINKS) {
1666                     ap_rvputs(r, "<a href=\"", anchor, "\">", NULL);
1667                 }
1668                 if ((ar[x]->icon) || d->default_icon) {
1669                     ap_rvputs(r, "<img src=\"",
1670                               ap_escape_html(scratch,
1671                                              ar[x]->icon ? ar[x]->icon
1672                                                          : d->default_icon),
1673                               "\" alt=\"[", (ar[x]->alt ? ar[x]->alt : "   "),
1674                               "]\"", NULL);
1675                     if (d->icon_width) {
1676                         ap_rprintf(r, " width=\"%d\"", d->icon_width);
1677                     }
1678                     if (d->icon_height) {
1679                         ap_rprintf(r, " height=\"%d\"", d->icon_height);
1680                     }
1681
1682                     if (autoindex_opts & EMIT_XHTML) {
1683                         ap_rputs(" /", r);
1684                     }
1685                     ap_rputs(">", r);
1686                 }
1687                 else {
1688                     ap_rputs("&nbsp;", r);
1689                 }
1690                 if (autoindex_opts & ICONS_ARE_LINKS) {
1691                     ap_rputs("</a></td>", r);
1692                 }
1693                 else {
1694                     ap_rputs("</td>", r);
1695                 }
1696             }
1697             if (d->name_adjust == K_ADJUST) {
1698                 ap_rvputs(r, "<td><a href=\"", anchor, "\">",
1699                           ap_escape_html(scratch, t2), "</a>", NULL);
1700             }
1701             else {
1702                 nwidth = strlen(t2);
1703                 if (nwidth > name_width) {
1704                   memcpy(name_scratch, t2, name_width - 3);
1705                   name_scratch[name_width - 3] = '.';
1706                   name_scratch[name_width - 2] = '.';
1707                   name_scratch[name_width - 1] = '>';
1708                   name_scratch[name_width] = 0;
1709                   t2 = name_scratch;
1710                   nwidth = name_width;
1711                 }
1712                 ap_rvputs(r, "<td><a href=\"", anchor, "\">",
1713                           ap_escape_html(scratch, t2),
1714                           "</a>", pad_scratch + nwidth, NULL);
1715             }
1716             if (!(autoindex_opts & SUPPRESS_LAST_MOD)) {
1717                 if (ar[x]->lm != -1) {
1718                     char time_str[MAX_STRING_LEN];
1719                     apr_time_exp_t ts;
1720                     apr_time_exp_lt(&ts, ar[x]->lm);
1721                     apr_strftime(time_str, &rv, MAX_STRING_LEN,
1722                                  "</td><td align=\"right\">%d-%b-%Y %H:%M  ",
1723                                  &ts);
1724                     ap_rputs(time_str, r);
1725                 }
1726                 else {
1727                     ap_rputs("</td><td>&nbsp;", r);
1728                 }
1729             }
1730             if (!(autoindex_opts & SUPPRESS_SIZE)) {
1731                 char buf[5];
1732                 ap_rvputs(r, "</td><td align=\"right\">",
1733                           apr_strfsize(ar[x]->size, buf), NULL);
1734             }
1735             if (!(autoindex_opts & SUPPRESS_DESC)) {
1736                 if (ar[x]->desc) {
1737                     if (d->desc_adjust == K_ADJUST) {
1738                         ap_rvputs(r, "</td><td>", ar[x]->desc, NULL);
1739                     }
1740                     else {
1741                         ap_rvputs(r, "</td><td>",
1742                                   terminate_description(d, ar[x]->desc,
1743                                                         autoindex_opts,
1744                                                         desc_width), NULL);
1745                     }
1746                 }
1747             }
1748             else {
1749                 ap_rputs("</td><td>&nbsp;", r);
1750             }
1751             ap_rputs("</td></tr>\n", r);
1752         }
1753         else if (autoindex_opts & FANCY_INDEXING) {
1754             if (!(autoindex_opts & SUPPRESS_ICON)) {
1755                 if (autoindex_opts & ICONS_ARE_LINKS) {
1756                     ap_rvputs(r, "<a href=\"", anchor, "\">", NULL);
1757                 }
1758                 if ((ar[x]->icon) || d->default_icon) {
1759                     ap_rvputs(r, "<img src=\"",
1760                               ap_escape_html(scratch,
1761                                              ar[x]->icon ? ar[x]->icon
1762                                                          : d->default_icon),
1763                               "\" alt=\"[", (ar[x]->alt ? ar[x]->alt : "   "),
1764                               "]\"", NULL);
1765                     if (d->icon_width) {
1766                         ap_rprintf(r, " width=\"%d\"", d->icon_width);
1767                     }
1768                     if (d->icon_height) {
1769                         ap_rprintf(r, " height=\"%d\"", d->icon_height);
1770                     }
1771
1772                     if (autoindex_opts & EMIT_XHTML) {
1773                         ap_rputs(" /", r);
1774                     }
1775                     ap_rputs(">", r);
1776                 }
1777                 else {
1778                     ap_rputs("     ", r);
1779                 }
1780                 if (autoindex_opts & ICONS_ARE_LINKS) {
1781                     ap_rputs("</a> ", r);
1782                 }
1783                 else {
1784                     ap_rputc(' ', r);
1785                 }
1786             }
1787             nwidth = strlen(t2);
1788             if (nwidth > name_width) {
1789                 memcpy(name_scratch, t2, name_width - 3);
1790                 name_scratch[name_width - 3] = '.';
1791                 name_scratch[name_width - 2] = '.';
1792                 name_scratch[name_width - 1] = '>';
1793                 name_scratch[name_width] = 0;
1794                 t2 = name_scratch;
1795                 nwidth = name_width;
1796             }
1797             ap_rvputs(r, "<a href=\"", anchor, "\">",
1798                       ap_escape_html(scratch, t2),
1799                       "</a>", pad_scratch + nwidth, NULL);
1800             /*
1801              * The blank before the storm.. er, before the next field.
1802              */
1803             ap_rputs(" ", r);
1804             if (!(autoindex_opts & SUPPRESS_LAST_MOD)) {
1805                 if (ar[x]->lm != -1) {
1806                     char time_str[MAX_STRING_LEN];
1807                     apr_time_exp_t ts;
1808                     apr_time_exp_lt(&ts, ar[x]->lm);
1809                     apr_strftime(time_str, &rv, MAX_STRING_LEN,
1810                                 "%d-%b-%Y %H:%M  ", &ts);
1811                     ap_rputs(time_str, r);
1812                 }
1813                 else {
1814                     /*Length="22-Feb-1998 23:42  " (see 4 lines above) */
1815                     ap_rputs("                   ", r);
1816                 }
1817             }
1818             if (!(autoindex_opts & SUPPRESS_SIZE)) {
1819                 char buf[5];
1820                 ap_rputs(apr_strfsize(ar[x]->size, buf), r);
1821                 ap_rputs("  ", r);
1822             }
1823             if (!(autoindex_opts & SUPPRESS_DESC)) {
1824                 if (ar[x]->desc) {
1825                     ap_rputs(terminate_description(d, ar[x]->desc,
1826                                                    autoindex_opts,
1827                                                    desc_width), r);
1828                 }
1829             }
1830             ap_rputc('\n', r);
1831         }
1832         else {
1833             ap_rvputs(r, "<li><a href=\"", anchor, "\"> ",
1834                       ap_escape_html(scratch, t2),
1835                       "</a></li>\n", NULL);
1836         }
1837     }
1838     if (autoindex_opts & TABLE_INDEXING) {
1839         ap_rvputs(r, breakrow, "</table>\n", NULL);
1840     }
1841     else if (autoindex_opts & FANCY_INDEXING) {
1842         if (!(autoindex_opts & SUPPRESS_RULES)) {
1843             ap_rputs("<hr", r);
1844             if (autoindex_opts & EMIT_XHTML) {
1845                 ap_rputs(" /", r);
1846             }
1847             ap_rputs("></pre>\n", r);
1848         }
1849         else {
1850             ap_rputs("</pre>\n", r);
1851         }
1852     }
1853     else {
1854         ap_rputs("</ul>\n", r);
1855     }
1856 }
1857
1858 /*
1859  * Compare two file entries according to the sort criteria.  The return
1860  * is essentially a signum function value.
1861  */
1862
1863 static int dsortf(struct ent **e1, struct ent **e2)
1864 {
1865     struct ent *c1;
1866     struct ent *c2;
1867     int result = 0;
1868
1869     /*
1870      * First, see if either of the entries is for the parent directory.
1871      * If so, that *always* sorts lower than anything else.
1872      */
1873     if ((*e1)->name[0] == '/') {
1874         return -1;
1875     }
1876     if ((*e2)->name[0] == '/') {
1877         return 1;
1878     }
1879     /*
1880      * Now see if one's a directory and one isn't, if we're set
1881      * isdir for FOLDERS_FIRST.
1882      */
1883     if ((*e1)->isdir != (*e2)->isdir) {
1884         return (*e1)->isdir ? -1 : 1;
1885     }
1886     /*
1887      * All of our comparisons will be of the c1 entry against the c2 one,
1888      * so assign them appropriately to take care of the ordering.
1889      */
1890     if ((*e1)->ascending) {
1891         c1 = *e1;
1892         c2 = *e2;
1893     }
1894     else {
1895         c1 = *e2;
1896         c2 = *e1;
1897     }
1898
1899     switch (c1->key) {
1900     case K_LAST_MOD:
1901         if (c1->lm > c2->lm) {
1902             return 1;
1903         }
1904         else if (c1->lm < c2->lm) {
1905             return -1;
1906         }
1907         break;
1908     case K_SIZE:
1909         if (c1->size > c2->size) {
1910             return 1;
1911         }
1912         else if (c1->size < c2->size) {
1913             return -1;
1914         }
1915         break;
1916     case K_DESC:
1917         if (c1->version_sort) {
1918             result = apr_strnatcmp(c1->desc ? c1->desc : "",
1919                                    c2->desc ? c2->desc : "");
1920         }
1921         else {
1922             result = strcmp(c1->desc ? c1->desc : "",
1923                             c2->desc ? c2->desc : "");
1924         }
1925         if (result) {
1926             return result;
1927         }
1928         break;
1929     }
1930
1931     /* names may identical when treated case-insensitively,
1932      * so always fall back on strcmp() flavors to put entries
1933      * in deterministic order.  This means that 'ABC' and 'abc'
1934      * will always appear in the same order, rather than
1935      * variably between 'ABC abc' and 'abc ABC' order.
1936      */
1937
1938     if (c1->version_sort) {
1939         if (c1->ignore_case) {
1940             result = apr_strnatcasecmp (c1->name, c2->name);
1941         }
1942         if (!result) {
1943             result = apr_strnatcmp(c1->name, c2->name);
1944         }
1945     }
1946
1947     /* The names may be identical in respects other other than
1948      * filename case when strnatcmp is used above, so fall back
1949      * to strcmp on conflicts so that fn1.01.zzz and fn1.1.zzz
1950      * are also sorted in a deterministic order.
1951      */
1952
1953     if (!result && c1->ignore_case) {
1954         result = strcasecmp (c1->name, c2->name);
1955     }
1956
1957     if (!result) {
1958         result = strcmp (c1->name, c2->name);
1959     }
1960
1961     return result;
1962 }
1963
1964
1965 static int index_directory(request_rec *r,
1966                            autoindex_config_rec *autoindex_conf)
1967 {
1968     char *title_name = ap_escape_html(r->pool, r->uri);
1969     char *title_endp;
1970     char *name = r->filename;
1971     char *pstring = NULL;
1972     apr_finfo_t dirent;
1973     apr_dir_t *thedir;
1974     apr_status_t status;
1975     int num_ent = 0, x;
1976     struct ent *head, *p;
1977     struct ent **ar = NULL;
1978     const char *qstring;
1979     apr_int32_t autoindex_opts = autoindex_conf->opts;
1980     char keyid;
1981     char direction;
1982     char *colargs;
1983     char *fullpath;
1984     apr_size_t dirpathlen;
1985     char *ctype = "text/html";
1986     char *charset;
1987
1988     if ((status = apr_dir_open(&thedir, name, r->pool)) != APR_SUCCESS) {
1989         ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
1990                       "Can't open directory for index: %s", r->filename);
1991         return HTTP_FORBIDDEN;
1992     }
1993
1994     if (autoindex_conf->ctype) {
1995         ctype = autoindex_conf->ctype;
1996     }
1997     if (autoindex_conf->charset) {
1998         charset = autoindex_conf->charset;
1999     }
2000     else {
2001 #if APR_HAS_UNICODE_FS
2002         charset = "UTF-8";
2003 #else
2004         charset = "ISO-8859-1";
2005 #endif
2006     }
2007     if (*charset) {
2008         ap_set_content_type(r, apr_pstrcat(r->pool, ctype, ";charset=",
2009                             charset, NULL));
2010     }
2011     else {
2012         ap_set_content_type(r, ctype);
2013     }
2014
2015     if (autoindex_opts & TRACK_MODIFIED) {
2016         ap_update_mtime(r, r->finfo.mtime);
2017         ap_set_last_modified(r);
2018         ap_set_etag(r);
2019     }
2020     if (r->header_only) {
2021         apr_dir_close(thedir);
2022         return 0;
2023     }
2024
2025     /*
2026      * If there is no specific ordering defined for this directory,
2027      * default to ascending by filename.
2028      */
2029     keyid = autoindex_conf->default_keyid
2030                 ? autoindex_conf->default_keyid : K_NAME;
2031     direction = autoindex_conf->default_direction
2032                 ? autoindex_conf->default_direction : D_ASCENDING;
2033
2034     /*
2035      * Figure out what sort of indexing (if any) we're supposed to use.
2036      *
2037      * If no QUERY_STRING was specified or client query strings have been
2038      * explicitly disabled.
2039      * If we are ignoring the client, suppress column sorting as well.
2040      */
2041     if (autoindex_opts & IGNORE_CLIENT) {
2042         qstring = NULL;
2043         autoindex_opts |= SUPPRESS_COLSORT;
2044         colargs = "";
2045     }
2046     else {
2047         char fval[5], vval[5], *ppre = "", *epattern = "";
2048         fval[0] = '\0'; vval[0] = '\0';
2049         qstring = r->args;
2050
2051         while (qstring && *qstring) {
2052
2053             /* C= First Sort key Column (N, M, S, D) */
2054             if (   qstring[0] == 'C' && qstring[1] == '='
2055                 && qstring[2] && strchr(K_VALID, qstring[2])
2056                 && (   qstring[3] == '&' || qstring[3] == ';'
2057                     || !qstring[3])) {
2058                 keyid = qstring[2];
2059                 qstring += qstring[3] ? 4 : 3;
2060             }
2061
2062             /* O= Sort order (A, D) */
2063             else if (   qstring[0] == 'O' && qstring[1] == '='
2064                      && (   (qstring[2] == D_ASCENDING)
2065                          || (qstring[2] == D_DESCENDING))
2066                      && (   qstring[3] == '&' || qstring[3] == ';'
2067                          || !qstring[3])) {
2068                 direction = qstring[2];
2069                 qstring += qstring[3] ? 4 : 3;
2070             }
2071
2072             /* F= Output Format (0 plain, 1 fancy (pre), 2 table) */
2073             else if (   qstring[0] == 'F' && qstring[1] == '='
2074                      && qstring[2] && strchr("012", qstring[2])
2075                      && (   qstring[3] == '&' || qstring[3] == ';'
2076                          || !qstring[3])) {
2077                 if (qstring[2] == '0') {
2078                     autoindex_opts &= ~(FANCY_INDEXING | TABLE_INDEXING);
2079                 }
2080                 else if (qstring[2] == '1') {
2081                     autoindex_opts = (autoindex_opts | FANCY_INDEXING)
2082                         & ~TABLE_INDEXING;
2083                 }
2084                 else if (qstring[2] == '2') {
2085                     autoindex_opts |= FANCY_INDEXING | TABLE_INDEXING;
2086                 }
2087                 strcpy(fval, ";F= ");
2088                 fval[3] = qstring[2];
2089                 qstring += qstring[3] ? 4 : 3;
2090             }
2091
2092             /* V= Version sort (0, 1) */
2093             else if (   qstring[0] == 'V' && qstring[1] == '='
2094                      && (qstring[2] == '0' || qstring[2] == '1')
2095                      && (   qstring[3] == '&' || qstring[3] == ';'
2096                          || !qstring[3])) {
2097                 if (qstring[2] == '0') {
2098                     autoindex_opts &= ~VERSION_SORT;
2099                 }
2100                 else if (qstring[2] == '1') {
2101                     autoindex_opts |= VERSION_SORT;
2102                 }
2103                 strcpy(vval, ";V= ");
2104                 vval[3] = qstring[2];
2105                 qstring += qstring[3] ? 4 : 3;
2106             }
2107
2108             /* P= wildcard pattern (*.foo) */
2109             else if (qstring[0] == 'P' && qstring[1] == '=') {
2110                 const char *eos = qstring += 2; /* for efficiency */
2111
2112                 while (*eos && *eos != '&' && *eos != ';') {
2113                     ++eos;
2114                 }
2115
2116                 if (eos == qstring) {
2117                     pstring = NULL;
2118                 }
2119                 else {
2120                     pstring = apr_pstrndup(r->pool, qstring, eos - qstring);
2121                     if (ap_unescape_url(pstring) != OK) {
2122                         /* ignore the pattern, if it's bad. */
2123                         pstring = NULL;
2124                     }
2125                     else {
2126                         ppre = ";P=";
2127                         /* be correct */
2128                         epattern = ap_escape_uri(r->pool, pstring);
2129                     }
2130                 }
2131
2132                 if (*eos && *++eos) {
2133                     qstring = eos;
2134                 }
2135                 else {
2136                     qstring = NULL;
2137                 }
2138             }
2139
2140             /* Syntax error?  Ignore the remainder! */
2141             else {
2142                 qstring = NULL;
2143             }
2144         }
2145         colargs = apr_pstrcat(r->pool, fval, vval, ppre, epattern, NULL);
2146     }
2147
2148     /* Spew HTML preamble */
2149     title_endp = title_name + strlen(title_name) - 1;
2150
2151     while (title_endp > title_name && *title_endp == '/') {
2152         *title_endp-- = '\0';
2153     }
2154
2155     emit_head(r, find_header(autoindex_conf, r),
2156               autoindex_opts & SUPPRESS_PREAMBLE,
2157               autoindex_opts & EMIT_XHTML, title_name);
2158
2159     /*
2160      * Since we don't know how many dir. entries there are, put them into a
2161      * linked list and then arrayificate them so qsort can use them.
2162      */
2163     head = NULL;
2164     p = make_parent_entry(autoindex_opts, autoindex_conf, r, keyid, direction);
2165     if (p != NULL) {
2166         p->next = head;
2167         head = p;
2168         num_ent++;
2169     }
2170     fullpath = apr_palloc(r->pool, APR_PATH_MAX);
2171     dirpathlen = strlen(name);
2172     memcpy(fullpath, name, dirpathlen);
2173
2174     do {
2175         status = apr_dir_read(&dirent, APR_FINFO_MIN | APR_FINFO_NAME, thedir);
2176         if (APR_STATUS_IS_INCOMPLETE(status)) {
2177             continue; /* ignore un-stat()able files */
2178         }
2179         else if (status != APR_SUCCESS) {
2180             break;
2181         }
2182
2183         /* We want to explode symlinks here. */
2184         if (dirent.filetype == APR_LNK) {
2185             const char *savename;
2186             apr_finfo_t fi;
2187             /* We *must* have FNAME. */
2188             savename = dirent.name;
2189             apr_cpystrn(fullpath + dirpathlen, dirent.name,
2190                         APR_PATH_MAX - dirpathlen);
2191             status = apr_stat(&fi, fullpath,
2192                               dirent.valid & ~(APR_FINFO_NAME), r->pool);
2193             if (status != APR_SUCCESS) {
2194                 /* Something bad happened, skip this file. */
2195                 continue;
2196             }
2197             memcpy(&dirent, &fi, sizeof(fi));
2198             dirent.name = savename;
2199             dirent.valid |= APR_FINFO_NAME;
2200         }
2201         p = make_autoindex_entry(&dirent, autoindex_opts, autoindex_conf, r,
2202                                  keyid, direction, pstring);
2203         if (p != NULL) {
2204             p->next = head;
2205             head = p;
2206             num_ent++;
2207         }
2208     } while (1);
2209
2210     if (num_ent > 0) {
2211         ar = (struct ent **) apr_palloc(r->pool,
2212                                         num_ent * sizeof(struct ent *));
2213         p = head;
2214         x = 0;
2215         while (p) {
2216             ar[x++] = p;
2217             p = p->next;
2218         }
2219
2220         qsort((void *) ar, num_ent, sizeof(struct ent *),
2221               (int (*)(const void *, const void *)) dsortf);
2222     }
2223     output_directories(ar, num_ent, autoindex_conf, r, autoindex_opts,
2224                        keyid, direction, colargs);
2225     apr_dir_close(thedir);
2226
2227     emit_tail(r, find_readme(autoindex_conf, r),
2228               autoindex_opts & SUPPRESS_PREAMBLE);
2229
2230     return 0;
2231 }
2232
2233 /* The formal handler... */
2234
2235 static int handle_autoindex(request_rec *r)
2236 {
2237     autoindex_config_rec *d;
2238     int allow_opts;
2239
2240     if(strcmp(r->handler,DIR_MAGIC_TYPE)) {
2241         return DECLINED;
2242     }
2243
2244     allow_opts = ap_allow_options(r);
2245
2246     d = (autoindex_config_rec *) ap_get_module_config(r->per_dir_config,
2247                                                       &autoindex_module);
2248
2249     r->allowed |= (AP_METHOD_BIT << M_GET);
2250     if (r->method_number != M_GET) {
2251         return DECLINED;
2252     }
2253
2254     /* OK, nothing easy.  Trot out the heavy artillery... */
2255
2256     if (allow_opts & OPT_INDEXES) {
2257         int errstatus;
2258
2259         if ((errstatus = ap_discard_request_body(r)) != OK) {
2260             return errstatus;
2261         }
2262
2263         /* KLUDGE --- make the sub_req lookups happen in the right directory.
2264          * Fixing this in the sub_req_lookup functions themselves is difficult,
2265          * and would probably break virtual includes...
2266          */
2267
2268         if (r->filename[strlen(r->filename) - 1] != '/') {
2269             r->filename = apr_pstrcat(r->pool, r->filename, "/", NULL);
2270         }
2271         return index_directory(r, d);
2272     }
2273     else {
2274         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
2275                       "Directory index forbidden by "
2276                       "Options directive: %s", r->filename);
2277         return HTTP_FORBIDDEN;
2278     }
2279 }
2280
2281 static void register_hooks(apr_pool_t *p)
2282 {
2283     ap_hook_handler(handle_autoindex,NULL,NULL,APR_HOOK_MIDDLE);
2284 }
2285
2286 module AP_MODULE_DECLARE_DATA autoindex_module =
2287 {
2288     STANDARD20_MODULE_STUFF,
2289     create_autoindex_config,    /* dir config creater */
2290     merge_autoindex_configs,    /* dir merger --- default is to override */
2291     NULL,                       /* server config */
2292     NULL,                       /* merge server config */
2293     autoindex_cmds,             /* command apr_table_t */
2294     register_hooks              /* register hooks */
2295 };