1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
60 * mod_autoindex.c: Handles the on-the-fly html index generation
65 * Adapted to Apache by rst.
68 #include "ap_config.h"
70 #include "http_config.h"
71 #include "http_core.h"
72 #include "http_request.h"
73 #include "http_protocol.h"
75 #include "http_main.h"
76 #include "util_script.h"
77 #include "apr_fnmatch.h"
82 module MODULE_VAR_EXPORT autoindex_module;
84 /****************************************************************
86 * Handling configuration directives...
91 #define FRONT_MATTER 1
94 #define FANCY_INDEXING 1 /* Indexing options */
95 #define ICONS_ARE_LINKS 2
96 #define SCAN_HTML_TITLES 4
97 #define SUPPRESS_LAST_MOD 8
98 #define SUPPRESS_SIZE 16
99 #define SUPPRESS_DESC 32
100 #define SUPPRESS_PREAMBLE 64
101 #define SUPPRESS_COLSORT 128
102 #define NO_OPTIONS 256
112 * Define keys for sorting.
114 #define K_NAME 'N' /* Sort by file name (default) */
115 #define K_LAST_MOD 'M' /* Last modification date */
116 #define K_SIZE 'S' /* Size (absolute, not as displayed) */
117 #define K_DESC 'D' /* Description */
119 #define D_ASCENDING 'A'
120 #define D_DESCENDING 'D'
123 * These are the dimensions of the default icons supplied with Apache.
125 #define DEFAULT_ICON_WIDTH 20
126 #define DEFAULT_ICON_HEIGHT 22
129 * Other default dimensions.
131 #define DEFAULT_NAME_WIDTH 23
140 typedef struct ai_desc_t {
147 typedef struct autoindex_config_struct {
151 int incremented_opts;
152 int decremented_opts;
159 ap_array_header_t *icon_list;
160 ap_array_header_t *alt_list;
161 ap_array_header_t *desc_list;
162 ap_array_header_t *ign_list;
163 ap_array_header_t *hdr_list;
164 ap_array_header_t *rdme_list;
166 } autoindex_config_rec;
168 static char c_by_encoding, c_by_type, c_by_path;
170 #define BY_ENCODING &c_by_encoding
171 #define BY_TYPE &c_by_type
172 #define BY_PATH &c_by_path
175 * Return true if the specified string refers to the parent directory (i.e.,
176 * matches ".." or "../"). Hopefully this one call is significantly less
177 * expensive than multiple strcmp() calls.
179 static ap_inline int is_parent(const char *name)
182 * Now, IFF the first two bytes are dots, and the third byte is either
183 * EOS (\0) or a slash followed by EOS, we have a match.
185 if (((name[0] == '.') && (name[1] == '.'))
186 && ((name[2] == '\0')
187 || ((name[2] == '/') && (name[3] == '\0')))) {
194 * This routine puts the standard HTML header at the top of the index page.
195 * We include the DOCTYPE because we may be using features therefrom (i.e.,
196 * HEIGHT and WIDTH attributes on the icons if we're FancyIndexing).
198 static void emit_preamble(request_rec *r, char *title)
200 ap_rvputs(r, DOCTYPE_HTML_3_2,
201 "<HTML>\n <HEAD>\n <TITLE>Index of ", title,
202 "</TITLE>\n </HEAD>\n <BODY>\n", NULL);
205 static void push_item(ap_array_header_t *arr, char *type, char *to, char *path,
208 struct item *p = (struct item *) ap_push_array(arr);
218 p->data = data ? ap_pstrdup(arr->cont, data) : NULL;
219 p->apply_path = ap_pstrcat(arr->cont, path, "*", NULL);
221 if ((type == BY_PATH) && (!ap_is_matchexp(to))) {
222 p->apply_to = ap_pstrcat(arr->cont, "*", to, NULL);
225 p->apply_to = ap_pstrdup(arr->cont, to);
232 static const char *add_alt(cmd_parms *cmd, void *d, char *alt, char *to)
234 if (cmd->info == BY_PATH) {
235 if (!strcmp(to, "**DIRECTORY**")) {
236 to = "^^DIRECTORY^^";
239 if (cmd->info == BY_ENCODING) {
243 push_item(((autoindex_config_rec *) d)->alt_list, cmd->info, to,
248 static const char *add_icon(cmd_parms *cmd, void *d, char *icon, char *to)
250 char *iconbak = ap_pstrdup(cmd->pool, icon);
252 if (icon[0] == '(') {
254 char *cl = strchr(iconbak, ')');
257 return "missing closing paren";
259 alt = ap_getword_nc(cmd->pool, &iconbak, ',');
260 *cl = '\0'; /* Lose closing paren */
261 add_alt(cmd, d, &alt[1], to);
263 if (cmd->info == BY_PATH) {
264 if (!strcmp(to, "**DIRECTORY**")) {
265 to = "^^DIRECTORY^^";
268 if (cmd->info == BY_ENCODING) {
272 push_item(((autoindex_config_rec *) d)->icon_list, cmd->info, to,
278 * Add description text for a filename pattern. If the pattern has
279 * wildcards already (or we need to add them), add leading and
280 * trailing wildcards to it to ensure substring processing. If the
281 * pattern contains a '/' anywhere, force wildcard matching mode,
282 * add a slash to the prefix so that "bar/bletch" won't be matched
283 * by "foobar/bletch", and make a note that there's a delimiter;
284 * the matching routine simplifies to just the actual filename
285 * whenever it can. This allows definitions in parent directories
286 * to be made for files in subordinate ones using relative paths.
290 * Absent a strcasestr() function, we have to force wildcards on
291 * systems for which "AAA" and "aaa" mean the same file.
293 #ifdef CASE_BLIND_FILESYSTEM
294 #define WILDCARDS_REQUIRED 1
296 #define WILDCARDS_REQUIRED 0
299 static const char *add_desc(cmd_parms *cmd, void *d, char *desc, char *to)
301 autoindex_config_rec *dcfg = (autoindex_config_rec *) d;
302 ai_desc_t *desc_entry;
305 desc_entry = (ai_desc_t *) ap_push_array(dcfg->desc_list);
306 desc_entry->full_path = (strchr(to, '/') == NULL) ? 0 : 1;
307 desc_entry->wildcards = (WILDCARDS_REQUIRED
308 || desc_entry->full_path
309 || ap_is_fnmatch(to));
310 if (desc_entry->wildcards) {
311 prefix = desc_entry->full_path ? "*/" : "*";
312 desc_entry->pattern = ap_pstrcat(dcfg->desc_list->cont,
313 prefix, to, "*", NULL);
316 desc_entry->pattern = ap_pstrdup(dcfg->desc_list->cont, to);
318 desc_entry->description = ap_pstrdup(dcfg->desc_list->cont, desc);
322 static const char *add_ignore(cmd_parms *cmd, void *d, char *ext)
324 push_item(((autoindex_config_rec *) d)->ign_list, 0, ext, cmd->path, NULL);
328 static const char *add_header(cmd_parms *cmd, void *d, char *name)
330 push_item(((autoindex_config_rec *) d)->hdr_list, 0, NULL, cmd->path,
335 static const char *add_readme(cmd_parms *cmd, void *d, char *name)
337 push_item(((autoindex_config_rec *) d)->rdme_list, 0, NULL, cmd->path,
342 /* A legacy directive, FancyIndexing is superseded by the IndexOptions
343 * keyword. But for compatibility..
345 static const char *fancy_indexing(cmd_parms *cmd, void *d, int arg)
349 autoindex_config_rec *cfg;
351 cfg = (autoindex_config_rec *) d;
353 if (curopts & NO_OPTIONS) {
354 return "FancyIndexing directive conflicts with existing "
357 newopts = (arg ? (curopts | FANCY_INDEXING) : (curopts & ~FANCY_INDEXING));
362 static const char *add_opts(cmd_parms *cmd, void *d, const char *optstr)
369 autoindex_config_rec *d_cfg = (autoindex_config_rec *) d;
372 opts_add = d_cfg->incremented_opts;
373 opts_remove = d_cfg->decremented_opts;
377 w = ap_getword_conf(cmd->pool, &optstr);
378 if ((*w == '+') || (*w == '-')) {
384 if (!strcasecmp(w, "FancyIndexing")) {
385 option = FANCY_INDEXING;
387 else if (!strcasecmp(w, "IconsAreLinks")) {
388 option = ICONS_ARE_LINKS;
390 else if (!strcasecmp(w, "ScanHTMLTitles")) {
391 option = SCAN_HTML_TITLES;
393 else if (!strcasecmp(w, "SuppressLastModified")) {
394 option = SUPPRESS_LAST_MOD;
396 else if (!strcasecmp(w, "SuppressSize")) {
397 option = SUPPRESS_SIZE;
399 else if (!strcasecmp(w, "SuppressDescription")) {
400 option = SUPPRESS_DESC;
402 else if (!strcasecmp(w, "SuppressHTMLPreamble")) {
403 option = SUPPRESS_PREAMBLE;
405 else if (!strcasecmp(w, "SuppressColumnSorting")) {
406 option = SUPPRESS_COLSORT;
408 else if (!strcasecmp(w, "None")) {
409 if (action != '\0') {
410 return "Cannot combine '+' or '-' with 'None' keyword";
416 else if (!strcasecmp(w, "IconWidth")) {
418 d_cfg->icon_width = DEFAULT_ICON_WIDTH;
421 d_cfg->icon_width = 0;
424 else if (!strncasecmp(w, "IconWidth=", 10)) {
426 return "Cannot combine '-' with IconWidth=n";
428 d_cfg->icon_width = atoi(&w[10]);
430 else if (!strcasecmp(w, "IconHeight")) {
432 d_cfg->icon_height = DEFAULT_ICON_HEIGHT;
435 d_cfg->icon_height = 0;
438 else if (!strncasecmp(w, "IconHeight=", 11)) {
440 return "Cannot combine '-' with IconHeight=n";
442 d_cfg->icon_height = atoi(&w[11]);
444 else if (!strcasecmp(w, "NameWidth")) {
446 return "NameWidth with no value may only appear as "
449 d_cfg->name_width = DEFAULT_NAME_WIDTH;
450 d_cfg->name_adjust = K_NOADJUST;
452 else if (!strncasecmp(w, "NameWidth=", 10)) {
454 return "Cannot combine '-' with NameWidth=n";
457 d_cfg->name_adjust = K_ADJUST;
460 int width = atoi(&w[10]);
463 return "NameWidth value must be greater than 5";
465 d_cfg->name_width = width;
466 d_cfg->name_adjust = K_NOADJUST;
470 return "Invalid directory indexing option";
472 if (action == '\0') {
477 else if (action == '+') {
479 opts_remove &= ~option;
482 opts_remove |= option;
486 if ((opts & NO_OPTIONS) && (opts & ~NO_OPTIONS)) {
487 return "Cannot combine other IndexOptions keywords with 'None'";
489 d_cfg->incremented_opts = opts_add;
490 d_cfg->decremented_opts = opts_remove;
495 static const char *set_default_order(cmd_parms *cmd, void *m, char *direction,
499 autoindex_config_rec *d_cfg = (autoindex_config_rec *) m;
501 ap_cpystrn(temp, "k=d", sizeof(temp));
502 if (!strcasecmp(direction, "Ascending")) {
503 temp[2] = D_ASCENDING;
505 else if (!strcasecmp(direction, "Descending")) {
506 temp[2] = D_DESCENDING;
509 return "First keyword must be 'Ascending' or 'Descending'";
512 if (!strcasecmp(key, "Name")) {
515 else if (!strcasecmp(key, "Date")) {
516 temp[0] = K_LAST_MOD;
518 else if (!strcasecmp(key, "Size")) {
521 else if (!strcasecmp(key, "Description")) {
525 return "Second keyword must be 'Name', 'Date', 'Size', or "
529 if (d_cfg->default_order == NULL) {
530 d_cfg->default_order = ap_palloc(cmd->pool, 4);
531 d_cfg->default_order[3] = '\0';
533 ap_cpystrn(d_cfg->default_order, temp, sizeof(temp));
537 #define DIR_CMD_PERMS OR_INDEXES
539 static const command_rec autoindex_cmds[] =
541 {"AddIcon", add_icon, BY_PATH, DIR_CMD_PERMS, ITERATE2,
542 "an icon URL followed by one or more filenames"},
543 {"AddIconByType", add_icon, BY_TYPE, DIR_CMD_PERMS, ITERATE2,
544 "an icon URL followed by one or more MIME types"},
545 {"AddIconByEncoding", add_icon, BY_ENCODING, DIR_CMD_PERMS, ITERATE2,
546 "an icon URL followed by one or more content encodings"},
547 {"AddAlt", add_alt, BY_PATH, DIR_CMD_PERMS, ITERATE2,
548 "alternate descriptive text followed by one or more filenames"},
549 {"AddAltByType", add_alt, BY_TYPE, DIR_CMD_PERMS, ITERATE2,
550 "alternate descriptive text followed by one or more MIME types"},
551 {"AddAltByEncoding", add_alt, BY_ENCODING, DIR_CMD_PERMS, ITERATE2,
552 "alternate descriptive text followed by one or more content encodings"},
553 {"IndexOptions", add_opts, NULL, DIR_CMD_PERMS, RAW_ARGS,
554 "one or more index options"},
555 {"IndexOrderDefault", set_default_order, NULL, DIR_CMD_PERMS, TAKE2,
556 "{Ascending,Descending} {Name,Size,Description,Date}"},
557 {"IndexIgnore", add_ignore, NULL, DIR_CMD_PERMS, ITERATE,
558 "one or more file extensions"},
559 {"AddDescription", add_desc, BY_PATH, DIR_CMD_PERMS, ITERATE2,
560 "Descriptive text followed by one or more filenames"},
561 {"HeaderName", add_header, NULL, DIR_CMD_PERMS, TAKE1, "a filename"},
562 {"ReadmeName", add_readme, NULL, DIR_CMD_PERMS, TAKE1, "a filename"},
563 {"FancyIndexing", fancy_indexing, NULL, DIR_CMD_PERMS, FLAG,
564 "Limited to 'on' or 'off' (superseded by IndexOptions FancyIndexing)"},
565 {"DefaultIcon", ap_set_string_slot,
566 (void *) XtOffsetOf(autoindex_config_rec, default_icon),
567 DIR_CMD_PERMS, TAKE1, "an icon URL"},
571 static void *create_autoindex_config(ap_context_t *p, char *dummy)
573 autoindex_config_rec *new =
574 (autoindex_config_rec *) ap_pcalloc(p, sizeof(autoindex_config_rec));
577 new->icon_height = 0;
578 new->name_width = DEFAULT_NAME_WIDTH;
579 new->name_adjust = K_UNSET;
580 new->icon_list = ap_make_array(p, 4, sizeof(struct item));
581 new->alt_list = ap_make_array(p, 4, sizeof(struct item));
582 new->desc_list = ap_make_array(p, 4, sizeof(ai_desc_t));
583 new->ign_list = ap_make_array(p, 4, sizeof(struct item));
584 new->hdr_list = ap_make_array(p, 4, sizeof(struct item));
585 new->rdme_list = ap_make_array(p, 4, sizeof(struct item));
587 new->incremented_opts = 0;
588 new->decremented_opts = 0;
589 new->default_order = NULL;
594 static void *merge_autoindex_configs(ap_context_t *p, void *basev, void *addv)
596 autoindex_config_rec *new;
597 autoindex_config_rec *base = (autoindex_config_rec *) basev;
598 autoindex_config_rec *add = (autoindex_config_rec *) addv;
600 new = (autoindex_config_rec *) ap_pcalloc(p, sizeof(autoindex_config_rec));
601 new->default_icon = add->default_icon ? add->default_icon
602 : base->default_icon;
603 new->icon_height = add->icon_height ? add->icon_height : base->icon_height;
604 new->icon_width = add->icon_width ? add->icon_width : base->icon_width;
606 new->alt_list = ap_append_arrays(p, add->alt_list, base->alt_list);
607 new->ign_list = ap_append_arrays(p, add->ign_list, base->ign_list);
608 new->hdr_list = ap_append_arrays(p, add->hdr_list, base->hdr_list);
609 new->desc_list = ap_append_arrays(p, add->desc_list, base->desc_list);
610 new->icon_list = ap_append_arrays(p, add->icon_list, base->icon_list);
611 new->rdme_list = ap_append_arrays(p, add->rdme_list, base->rdme_list);
612 if (add->opts & NO_OPTIONS) {
614 * If the current directory says 'no options' then we also
615 * clear any incremental mods from being inheritable further down.
617 new->opts = NO_OPTIONS;
618 new->incremented_opts = 0;
619 new->decremented_opts = 0;
623 * If there were any nonincremental options selected for
624 * this directory, they dominate and we don't inherit *anything.*
625 * Contrariwise, we *do* inherit if the only settings here are
628 if (add->opts == 0) {
629 new->incremented_opts = (base->incremented_opts
630 | add->incremented_opts)
631 & ~add->decremented_opts;
632 new->decremented_opts = (base->decremented_opts
633 | add->decremented_opts);
635 * We may have incremental settings, so make sure we don't
636 * inadvertently inherit an IndexOptions None from above.
638 new->opts = (base->opts & ~NO_OPTIONS);
642 * There are local nonincremental settings, which clear
643 * all inheritance from above. They *are* the new base settings.
645 new->opts = add->opts;;
648 * We're guaranteed that there'll be no overlap between
649 * the add-options and the remove-options.
651 new->opts |= new->incremented_opts;
652 new->opts &= ~new->decremented_opts;
655 * Inherit the NameWidth settings if there aren't any specific to
656 * the new location; otherwise we'll end up using the defaults set in the
657 * config-rec creation routine.
659 if (add->name_adjust == K_UNSET) {
660 new->name_width = base->name_width;
661 new->name_adjust = base->name_adjust;
664 new->name_width = add->name_width;
665 new->name_adjust = add->name_adjust;
668 new->default_order = (add->default_order != NULL)
669 ? add->default_order : base->default_order;
673 /****************************************************************
675 * Looking things up in config entries...
678 /* Structure used to hold entries when we're actually building an index */
692 static char *find_item(request_rec *r, ap_array_header_t *list, int path_only)
694 const char *content_type = ap_field_noparam(r->pool, r->content_type);
695 const char *content_encoding = r->content_encoding;
696 char *path = r->filename;
698 struct item *items = (struct item *) list->elts;
701 for (i = 0; i < list->nelts; ++i) {
702 struct item *p = &items[i];
704 /* Special cased for ^^DIRECTORY^^ and ^^BLANKICON^^ */
705 if ((path[0] == '^') || (!ap_strcmp_match(path, p->apply_path))) {
706 if (!*(p->apply_to)) {
709 else if (p->type == BY_PATH || path[0] == '^') {
710 if (!ap_strcmp_match(path, p->apply_to)) {
714 else if (!path_only) {
715 if (!content_encoding) {
716 if (p->type == BY_TYPE) {
718 && !ap_strcasecmp_match(content_type,
725 if (p->type == BY_ENCODING) {
726 if (!ap_strcasecmp_match(content_encoding,
738 #define find_icon(d,p,t) find_item(p,d->icon_list,t)
739 #define find_alt(d,p,t) find_item(p,d->alt_list,t)
740 #define find_header(d,p) find_item(p,d->hdr_list,0)
741 #define find_readme(d,p) find_item(p,d->rdme_list,0)
743 static char *find_default_icon(autoindex_config_rec *d, char *bogus_name)
747 /* Bleah. I tried to clean up find_item, and it lead to this bit
748 * of ugliness. Note that the fields initialized are precisely
749 * those that find_item looks at...
752 r.filename = bogus_name;
753 r.content_type = r.content_encoding = NULL;
755 return find_item(&r, d->icon_list, 1);
759 * Look through the list of pattern/description pairs and return the first one
760 * if any) that matches the filename in the request. If multiple patterns
761 * match, only the first one is used; since the order in the array is the
762 * same as the order in which directives were processed, earlier matching
763 * directives will dominate.
766 #ifdef CASE_BLIND_FILESYSTEM
767 #define MATCH_FLAGS FNM_CASE_BLIND
769 #define MATCH_FLAGS 0
772 static char *find_desc(autoindex_config_rec *dcfg, request_rec *r)
775 ai_desc_t *list = (ai_desc_t *) dcfg->desc_list->elts;
776 const char *filename_full = r->filename;
777 const char *filename_only;
778 const char *filename;
781 * If the filename includes a path, extract just the name itself
782 * for the simple matches.
784 if ((filename_only = strrchr(filename_full, '/')) == NULL) {
785 filename_only = filename_full;
790 for (i = 0; i < dcfg->desc_list->nelts; ++i) {
791 ai_desc_t *tuple = &list[i];
795 * Only use the full-path filename if the pattern contains '/'s.
797 filename = (tuple->full_path) ? filename_full : filename_only;
799 * Make the comparison using the cheapest method; only do
800 * wildcard checking if we must.
802 if (tuple->wildcards) {
803 found = (ap_fnmatch(tuple->pattern, filename, MATCH_FLAGS) == 0);
806 found = (strstr(filename, tuple->pattern) != NULL);
809 return tuple->description;
815 static int ignore_entry(autoindex_config_rec *d, char *path)
817 ap_array_header_t *list = d->ign_list;
818 struct item *items = (struct item *) list->elts;
822 if ((tt = strrchr(path, '/')) == NULL) {
829 for (i = 0; i < list->nelts; ++i) {
830 struct item *p = &items[i];
833 if ((ap = strrchr(p->apply_to, '/')) == NULL) {
840 #ifndef CASE_BLIND_FILESYSTEM
841 if (!ap_strcmp_match(path, p->apply_path)
842 && !ap_strcmp_match(tt, ap)) {
845 #else /* !CASE_BLIND_FILESYSTEM */
847 * On some platforms, the match must be case-blind. This is really
848 * a factor of the filesystem involved, but we can't detect that
849 * reliably - so we have to granularise at the OS level.
851 if (!ap_strcasecmp_match(path, p->apply_path)
852 && !ap_strcasecmp_match(tt, ap)) {
855 #endif /* !CASE_BLIND_FILESYSTEM */
860 /*****************************************************************
862 * Actually generating output
866 * Elements of the emitted document:
868 * Emitted unless SUPPRESS_PREAMBLE is set AND ap_run_sub_req
869 * succeeds for the (content_type == text/html) header file.
871 * Emitted if found (and able).
873 * Emitted if a header file is NOT emitted.
877 * Emitted if FANCY_INDEXING is set.
879 * Emitted if found (and able).
881 * Emitted if ServerSignature is not Off AND a readme file
884 * Emitted unless SUPPRESS_PREAMBLE is set AND ap_run_sub_req
885 * succeeds for the (content_type == text/html) readme file.
890 * emit a plain text file
892 static void do_emit_plain(request_rec *r, ap_file_t *f)
894 char buf[IOBUFSIZE + 1];
899 ap_rputs("<PRE>\n", r);
902 n = sizeof(char) * IOBUFSIZE;
903 stat = ap_read(f, buf, &n);
905 while (stat != APR_SUCCESS && stat == EINTR);
906 if (n == -1 || n == 0) {
912 for (i = c; i < n; i++) {
913 if (buf[i] == '<' || buf[i] == '>' || buf[i] == '&') {
919 ap_rputs(&buf[c], r);
923 else if (ch == '>') {
926 else if (ch == '&') {
927 ap_rputs("&", r);
932 ap_rputs("</PRE>\n", r);
936 * Handle the preamble through the H1 tag line, inclusive. Locate
937 * the file with a subrequests. Process text/html documents by actually
938 * running the subrequest; text/xxx documents get copied verbatim,
939 * and any other content type is ignored. This means that a non-text
940 * document (such as HEADER.gif) might get multiviewed as the result
941 * instead of a text document, meaning nothing will be displayed, but
944 static void emit_head(request_rec *r, char *header_fname, int suppress_amble,
948 request_rec *rr = NULL;
953 * If there's a header file, send a subrequest to look for it. If it's
954 * found and a text file, handle it -- otherwise fall through and
955 * pretend there's nothing there.
957 if ((header_fname != NULL)
958 && (rr = ap_sub_req_lookup_uri(header_fname, r))
959 && (rr->status == HTTP_OK)
960 && (rr->filename != NULL)
961 && rr->finfo.filetype == APR_REG) {
963 * Check for the two specific cases we allow: text/html and
964 * text/anything-else. The former is allowed to be processed for
967 if (rr->content_type != NULL) {
968 if (!strcasecmp(ap_field_noparam(r->pool, rr->content_type),
970 /* Hope everything will work... */
974 if (! suppress_amble) {
975 emit_preamble(r, title);
978 * If there's a problem running the subrequest, display the
979 * preamble if we didn't do it before -- the header file
980 * didn't get displayed.
982 if (ap_run_sub_req(rr) != OK) {
984 emit_amble = suppress_amble;
988 else if (!strncasecmp("text/", rr->content_type, 5)) {
990 * If we can open the file, prefix it with the preamble
991 * regardless; since we'll be sending a <PRE> block around
992 * the file's contents, any HTML header it had won't end up
995 if (ap_open(&f, rr->filename, APR_READ | APR_BUFFERED,
996 APR_OS_DEFAULT, r->pool) == APR_SUCCESS) {
997 emit_preamble(r, title);
1008 emit_preamble(r, title);
1011 ap_rvputs(r, "<H1>Index of ", title, "</H1>\n", NULL);
1014 ap_destroy_sub_req(rr);
1020 * Handle the Readme file through the postamble, inclusive. Locate
1021 * the file with a subrequests. Process text/html documents by actually
1022 * running the subrequest; text/xxx documents get copied verbatim,
1023 * and any other content type is ignored. This means that a non-text
1024 * document (such as FOOTER.gif) might get multiviewed as the result
1025 * instead of a text document, meaning nothing will be displayed, but
1028 static void emit_tail(request_rec *r, char *readme_fname, int suppress_amble)
1030 ap_file_t *f = NULL;
1031 request_rec *rr = NULL;
1032 int suppress_post = 0;
1033 int suppress_sig = 0;
1036 * If there's a readme file, send a subrequest to look for it. If it's
1037 * found and a text file, handle it -- otherwise fall through and
1038 * pretend there's nothing there.
1040 if ((readme_fname != NULL)
1041 && (rr = ap_sub_req_lookup_uri(readme_fname, r))
1042 && (rr->status == HTTP_OK)
1043 && (rr->filename != NULL)
1044 && rr->finfo.filetype == APR_REG) {
1046 * Check for the two specific cases we allow: text/html and
1047 * text/anything-else. The former is allowed to be processed for
1050 if (rr->content_type != NULL) {
1051 if (!strcasecmp(ap_field_noparam(r->pool, rr->content_type),
1053 if (ap_run_sub_req(rr) == OK) {
1056 suppress_post = suppress_amble;
1059 else if (!strncasecmp("text/", rr->content_type, 5)) {
1061 * If we can open the file, suppress the signature.
1063 if (ap_open(&f, rr->filename, APR_READ | APR_BUFFERED,
1064 APR_OS_DEFAULT, r->pool) == APR_SUCCESS) {
1065 do_emit_plain(r, f);
1073 if (!suppress_sig) {
1074 ap_rputs(ap_psignature("", r), r);
1076 if (!suppress_post) {
1077 ap_rputs("</BODY></HTML>\n", r);
1080 ap_destroy_sub_req(rr);
1085 static char *find_title(request_rec *r)
1087 char titlebuf[MAX_STRING_LEN], *find = "<TITLE>";
1088 ap_file_t *thefile = NULL;
1092 if (r->status != HTTP_OK) {
1095 if ((r->content_type != NULL)
1096 && (!strcasecmp(ap_field_noparam(r->pool, r->content_type),
1098 || !strcmp(r->content_type, INCLUDES_MAGIC_TYPE))
1099 && !r->content_encoding) {
1100 if (ap_open(&thefile, r->filename, APR_READ | APR_BUFFERED,
1101 APR_OS_DEFAULT, r->pool) != APR_SUCCESS) {
1104 n = sizeof(char) * (MAX_STRING_LEN - 1);
1105 ap_read(thefile, titlebuf, &n);
1111 for (x = 0, p = 0; titlebuf[x]; x++) {
1112 if (ap_toupper(titlebuf[x]) == find[p]) {
1114 if ((p = ap_ind(&titlebuf[++x], '<')) != -1) {
1115 titlebuf[x + p] = '\0';
1117 /* Scan for line breaks for Tanmoy's secretary */
1118 for (y = x; titlebuf[y]; y++) {
1119 if ((titlebuf[y] == CR) || (titlebuf[y] == LF)) {
1129 return ap_pstrdup(r->pool, &titlebuf[x]);
1141 static struct ent *make_autoindex_entry(char *name, int autoindex_opts,
1142 autoindex_config_rec *d,
1143 request_rec *r, char keyid,
1148 if ((name[0] == '.') && (!name[1])) {
1152 if (ignore_entry(d, ap_make_full_path(r->pool, r->filename, name))) {
1156 p = (struct ent *) ap_pcalloc(r->pool, sizeof(struct ent));
1157 p->name = ap_pstrdup(r->pool, name);
1163 p->key = ap_toupper(keyid);
1164 p->ascending = (ap_toupper(direction) == D_ASCENDING);
1166 if (autoindex_opts & FANCY_INDEXING) {
1167 request_rec *rr = ap_sub_req_lookup_file(name, r);
1169 if (rr->finfo.protection != 0) {
1170 p->lm = rr->finfo.mtime;
1171 if (rr->finfo.filetype == APR_DIR) {
1172 if (!(p->icon = find_icon(d, rr, 1))) {
1173 p->icon = find_default_icon(d, "^^DIRECTORY^^");
1175 if (!(p->alt = find_alt(d, rr, 1))) {
1179 p->name = ap_pstrcat(r->pool, name, "/", NULL);
1182 p->icon = find_icon(d, rr, 0);
1183 p->alt = find_alt(d, rr, 0);
1184 p->size = rr->finfo.size;
1188 p->desc = find_desc(d, rr);
1190 if ((!p->desc) && (autoindex_opts & SCAN_HTML_TITLES)) {
1191 p->desc = ap_pstrdup(r->pool, find_title(rr));
1194 ap_destroy_sub_req(rr);
1197 * We don't need to take any special action for the file size key. If
1198 * we did, it would go here.
1200 if (keyid == K_LAST_MOD) {
1208 static char *terminate_description(autoindex_config_rec *d, char *desc,
1214 if (autoindex_opts & SUPPRESS_LAST_MOD) {
1217 if (autoindex_opts & SUPPRESS_SIZE) {
1221 for (x = 0; desc[x] && (maxsize > 0 || desc[x]=='<'); x++) {
1222 if (desc[x] == '<') {
1223 while (desc[x] != '>') {
1231 else if (desc[x] == '&') {
1232 /* entities like ä count as one character */
1234 for ( ; desc[x] != ';'; ++x) {
1235 if (desc[x] == '\0') {
1245 if (!maxsize && desc[x] != '\0') {
1246 desc[x - 1] = '>'; /* Grump. */
1247 desc[x] = '\0'; /* Double Grump! */
1253 * Emit the anchor for the specified field. If a field is the key for the
1254 * current request, the link changes its meaning to reverse the order when
1255 * selected again. Non-active fields always start in ascending order.
1257 static void emit_link(request_rec *r, char *anchor, char fname, char curkey,
1258 char curdirection, int nosort)
1268 reverse = ((curkey == fname) && (curdirection == D_ASCENDING));
1269 qvalue[3] = reverse ? D_DESCENDING : D_ASCENDING;
1270 ap_rvputs(r, "<A HREF=\"", qvalue, "\">", anchor, "</A>", NULL);
1273 ap_rputs(anchor, r);
1277 static void output_directories(struct ent **ar, int n,
1278 autoindex_config_rec *d, request_rec *r,
1279 int autoindex_opts, char keyid, char direction)
1283 char *name = r->uri;
1285 int static_columns = (autoindex_opts & SUPPRESS_COLSORT);
1286 ap_context_t *scratch;
1291 ap_create_context(&scratch, r->pool);
1292 if (name[0] == '\0') {
1296 name_width = d->name_width;
1297 if (d->name_adjust == K_ADJUST) {
1298 for (x = 0; x < n; x++) {
1299 int t = strlen(ar[x]->name);
1300 if (t > name_width) {
1305 name_scratch = ap_palloc(r->pool, name_width + 1);
1306 pad_scratch = ap_palloc(r->pool, name_width + 1);
1307 memset(pad_scratch, ' ', name_width);
1308 pad_scratch[name_width] = '\0';
1310 if (autoindex_opts & FANCY_INDEXING) {
1311 ap_rputs("<PRE>", r);
1312 if ((tp = find_default_icon(d, "^^BLANKICON^^"))) {
1313 ap_rvputs(r, "<IMG SRC=\"", ap_escape_html(scratch, tp),
1314 "\" ALT=\" \"", NULL);
1315 if (d->icon_width && d->icon_height) {
1319 " HEIGHT=\"%d\" WIDTH=\"%d\"",
1326 emit_link(r, "Name", K_NAME, keyid, direction, static_columns);
1327 ap_rputs(pad_scratch + 4, r);
1329 * Emit the guaranteed-at-least-one-space-between-columns byte.
1332 if (!(autoindex_opts & SUPPRESS_LAST_MOD)) {
1333 emit_link(r, "Last modified", K_LAST_MOD, keyid, direction,
1337 if (!(autoindex_opts & SUPPRESS_SIZE)) {
1338 emit_link(r, "Size", K_SIZE, keyid, direction, static_columns);
1341 if (!(autoindex_opts & SUPPRESS_DESC)) {
1342 emit_link(r, "Description", K_DESC, keyid, direction,
1345 ap_rputs("\n<HR>\n", r);
1348 ap_rputs("<UL>", r);
1351 for (x = 0; x < n; x++) {
1352 char *anchor, *t, *t2;
1355 ap_clear_pool(scratch);
1357 if (is_parent(ar[x]->name)) {
1358 t = ap_make_full_path(scratch, name, "../");
1363 t2 = "Parent Directory";
1364 anchor = ap_escape_html(scratch, ap_os_escape_path(scratch, t, 0));
1369 anchor = ap_escape_html(scratch, ap_os_escape_path(scratch, t, 0));
1372 if (autoindex_opts & FANCY_INDEXING) {
1373 if (autoindex_opts & ICONS_ARE_LINKS) {
1374 ap_rvputs(r, "<A HREF=\"", anchor, "\">", NULL);
1376 if ((ar[x]->icon) || d->default_icon) {
1377 ap_rvputs(r, "<IMG SRC=\"",
1378 ap_escape_html(scratch,
1379 ar[x]->icon ? ar[x]->icon
1381 "\" ALT=\"[", (ar[x]->alt ? ar[x]->alt : " "),
1383 if (d->icon_width && d->icon_height) {
1384 ap_rprintf(r, " HEIGHT=\"%d\" WIDTH=\"%d\"",
1385 d->icon_height, d->icon_width);
1389 if (autoindex_opts & ICONS_ARE_LINKS) {
1390 ap_rputs("</A>", r);
1393 nwidth = strlen(t2);
1394 if (nwidth > name_width) {
1395 memcpy(name_scratch, t2, name_width - 3);
1396 name_scratch[name_width - 3] = '.';
1397 name_scratch[name_width - 2] = '.';
1398 name_scratch[name_width - 1] = '>';
1399 name_scratch[name_width] = 0;
1401 nwidth = name_width;
1403 ap_rvputs(r, " <A HREF=\"", anchor, "\">",
1404 ap_escape_html(scratch, t2), "</A>", pad_scratch + nwidth,
1407 * The blank before the storm.. er, before the next field.
1410 if (!(autoindex_opts & SUPPRESS_LAST_MOD)) {
1411 if (ar[x]->lm != -1) {
1412 char time_str[MAX_STRING_LEN];
1413 ap_exploded_time_t ts;
1414 ap_explode_localtime(&ts, ar[x]->lm);
1415 ap_strftime(time_str, &rv, MAX_STRING_LEN,
1416 "%d-%b-%Y %H:%M ", &ts);
1417 ap_rputs(time_str, r);
1420 /*Length="22-Feb-1998 23:42 " (see 4 lines above) */
1424 if (!(autoindex_opts & SUPPRESS_SIZE)) {
1425 ap_send_size(ar[x]->size, r);
1428 if (!(autoindex_opts & SUPPRESS_DESC)) {
1430 ap_rputs(terminate_description(d, ar[x]->desc,
1431 autoindex_opts), r);
1436 ap_rvputs(r, "<LI><A HREF=\"", anchor, "\"> ", t2,
1441 if (autoindex_opts & FANCY_INDEXING) {
1442 ap_rputs("</PRE>", r);
1445 ap_rputs("</UL>", r);
1450 * Compare two file entries according to the sort criteria. The return
1451 * is essentially a signum function value.
1454 static int dsortf(struct ent **e1, struct ent **e2)
1461 * First, see if either of the entries is for the parent directory.
1462 * If so, that *always* sorts lower than anything else.
1464 if (is_parent((*e1)->name)) {
1467 if (is_parent((*e2)->name)) {
1471 * All of our comparisons will be of the c1 entry against the c2 one,
1472 * so assign them appropriately to take care of the ordering.
1474 if ((*e1)->ascending) {
1484 if (c1->lm > c2->lm) {
1487 else if (c1->lm < c2->lm) {
1492 if (c1->size > c2->size) {
1495 else if (c1->size < c2->size) {
1500 result = strcmp(c1->desc ? c1->desc : "", c2->desc ? c2->desc : "");
1506 return strcmp(c1->name, c2->name);
1510 static int index_directory(request_rec *r,
1511 autoindex_config_rec *autoindex_conf)
1513 char *title_name = ap_escape_html(r->pool, r->uri);
1515 char *name = r->filename;
1520 struct ent *head, *p;
1521 struct ent **ar = NULL;
1522 const char *qstring;
1523 int autoindex_opts = autoindex_conf->opts;
1527 if ((status = ap_opendir(&d, name, r->pool)) != APR_SUCCESS) {
1528 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
1529 "Can't open directory for index: %s", r->filename);
1530 return HTTP_FORBIDDEN;
1533 r->content_type = "text/html";
1535 ap_send_http_header(r);
1537 if (r->header_only) {
1542 /* Spew HTML preamble */
1544 title_endp = title_name + strlen(title_name) - 1;
1546 while (title_endp > title_name && *title_endp == '/') {
1547 *title_endp-- = '\0';
1550 emit_head(r, find_header(autoindex_conf, r),
1551 autoindex_opts & SUPPRESS_PREAMBLE, title_name);
1554 * Figure out what sort of indexing (if any) we're supposed to use.
1556 * If no QUERY_STRING was specified or column sorting has been
1557 * explicitly disabled, we use the default specified by the
1558 * IndexOrderDefault directive (if there is one); otherwise,
1559 * we fall back to ascending by name.
1562 if ((autoindex_opts & SUPPRESS_COLSORT)
1563 || ((qstring == NULL) || (*qstring == '\0'))) {
1564 qstring = autoindex_conf->default_order;
1567 * If there is no specific ordering defined for this directory,
1568 * default to ascending by filename.
1570 if ((qstring == NULL) || (*qstring == '\0')) {
1572 direction = D_ASCENDING;
1576 ap_getword(r->pool, &qstring, '=');
1577 if (qstring != '\0') {
1578 direction = *qstring;
1581 direction = D_ASCENDING;
1586 * Since we don't know how many dir. entries there are, put them into a
1587 * linked list and then arrayificate them so qsort can use them.
1590 while (ap_readdir(d) == APR_SUCCESS) {
1592 ap_get_dir_filename(&d_name, d);
1593 p = make_autoindex_entry(d_name, autoindex_opts,
1594 autoindex_conf, r, keyid, direction);
1602 ar = (struct ent **) ap_palloc(r->pool,
1603 num_ent * sizeof(struct ent *));
1611 qsort((void *) ar, num_ent, sizeof(struct ent *),
1612 (int (*)(const void *, const void *)) dsortf);
1614 output_directories(ar, num_ent, autoindex_conf, r, autoindex_opts, keyid,
1618 if (autoindex_opts & FANCY_INDEXING) {
1619 ap_rputs("<HR>\n", r);
1621 emit_tail(r, find_readme(autoindex_conf, r),
1622 autoindex_opts & SUPPRESS_PREAMBLE);
1627 /* The formal handler... */
1629 static int handle_autoindex(request_rec *r)
1631 autoindex_config_rec *d;
1632 int allow_opts = ap_allow_options(r);
1634 d = (autoindex_config_rec *) ap_get_module_config(r->per_dir_config,
1637 r->allowed |= (1 << M_GET);
1638 if (r->method_number != M_GET) {
1642 /* OK, nothing easy. Trot out the heavy artillery... */
1644 if (allow_opts & OPT_INDEXES) {
1645 /* KLUDGE --- make the sub_req lookups happen in the right directory.
1646 * Fixing this in the sub_req_lookup functions themselves is difficult,
1647 * and would probably break virtual includes...
1650 if (r->filename[strlen(r->filename) - 1] != '/') {
1651 r->filename = ap_pstrcat(r->pool, r->filename, "/", NULL);
1653 return index_directory(r, d);
1656 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1657 "Directory index forbidden by rule: %s", r->filename);
1658 return HTTP_FORBIDDEN;
1663 static const handler_rec autoindex_handlers[] =
1665 {DIR_MAGIC_TYPE, handle_autoindex},
1669 module MODULE_VAR_EXPORT autoindex_module =
1671 STANDARD20_MODULE_STUFF,
1672 create_autoindex_config, /* dir config creater */
1673 merge_autoindex_configs, /* dir merger --- default is to override */
1674 NULL, /* server config */
1675 NULL, /* merge server config */
1676 autoindex_cmds, /* command ap_table_t */
1677 autoindex_handlers, /* handlers */
1678 NULL /* register hooks */