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