]> granicus.if.org Git - apache/blob - server/request.c
showstoppers--;
[apache] / server / request.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  * Portions of this software are based upon public domain software
55  * originally written at the National Center for Supercomputing Applications,
56  * University of Illinois, Urbana-Champaign.
57  */
58
59 /*
60  * http_request.c: functions to get and process requests
61  *
62  * Rob McCool 3/21/93
63  *
64  * Thoroughly revamped by rst for Apache.  NB this file reads
65  * best from the bottom up.
66  *
67  */
68
69 #include "apr_strings.h"
70 #include "apr_file_io.h"
71 #include "apr_fnmatch.h"
72
73 #define APR_WANT_STRFUNC
74 #include "apr_want.h"
75
76 #define CORE_PRIVATE
77 #include "ap_config.h"
78 #include "httpd.h"
79 #include "http_config.h"
80 #include "http_request.h"
81 #include "http_core.h"
82 #include "http_protocol.h"
83 #include "http_log.h"
84 #include "http_main.h"
85 #include "util_filter.h"
86 #include "util_charset.h"
87
88 #include "mod_core.h"
89
90 #if APR_HAVE_STDARG_H
91 #include <stdarg.h>
92 #endif
93
94 APR_HOOK_STRUCT(
95     APR_HOOK_LINK(translate_name)
96     APR_HOOK_LINK(map_to_storage)
97     APR_HOOK_LINK(check_user_id)
98     APR_HOOK_LINK(fixups)
99     APR_HOOK_LINK(type_checker)
100     APR_HOOK_LINK(access_checker)
101     APR_HOOK_LINK(auth_checker)
102     APR_HOOK_LINK(insert_filter)
103     APR_HOOK_LINK(create_request)
104 )
105
106 AP_IMPLEMENT_HOOK_RUN_FIRST(int,translate_name,
107                             (request_rec *r),(r),DECLINED)
108 AP_IMPLEMENT_HOOK_RUN_FIRST(int,map_to_storage,
109                             (request_rec *r),(r),DECLINED)
110 AP_IMPLEMENT_HOOK_RUN_FIRST(int,check_user_id,
111                             (request_rec *r),(r),DECLINED)
112 AP_IMPLEMENT_HOOK_RUN_ALL(int,fixups,
113                           (request_rec *r),(r),OK,DECLINED)
114 AP_IMPLEMENT_HOOK_RUN_FIRST(int,type_checker,
115                             (request_rec *r),(r),DECLINED)
116 AP_IMPLEMENT_HOOK_RUN_ALL(int,access_checker,
117                           (request_rec *r),(r),OK,DECLINED)
118 AP_IMPLEMENT_HOOK_RUN_FIRST(int,auth_checker,
119                             (request_rec *r),(r),DECLINED)
120 AP_IMPLEMENT_HOOK_VOID(insert_filter, (request_rec *r), (r))
121 AP_IMPLEMENT_HOOK_RUN_ALL(int,create_request,(request_rec *r),(r),OK,DECLINED)
122
123
124 static int decl_die(int status, char *phase, request_rec *r)
125 {
126     if (status == DECLINED) {
127         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_CRIT, 0, r,
128                       "configuration error:  couldn't %s: %s", phase, r->uri);
129         return HTTP_INTERNAL_SERVER_ERROR;
130     }
131     else {
132         return status;
133     }
134 }
135
136 /* This is the master logic for processing requests.  Do NOT duplicate
137  * this logic elsewhere, or the security model will be broken by future
138  * API changes.  Each phase must be individually optimized to pick up
139  * redundant/duplicate calls by subrequests, and redirects.
140  */
141 AP_DECLARE(int) ap_process_request_internal(request_rec *r)
142 {
143     int file_req = (r->main && r->filename);
144     int access_status;
145
146     /* Ignore embedded %2F's in path for proxy requests */
147     if (!r->proxyreq && r->parsed_uri.path) {
148         access_status = ap_unescape_url(r->parsed_uri.path);
149         if (access_status) {
150             return access_status;
151         }
152     }
153
154     ap_getparents(r->uri);     /* OK --- shrinking transformations... */
155
156     /* All file subrequests are a huge pain... they cannot bubble through the 
157      * next several steps.  Only file subrequests are allowed an empty uri, 
158      * otherwise let translate_name kill the request.
159      */
160     if (!file_req) {
161         if ((access_status = ap_location_walk(r))) {
162             return access_status;
163         }
164
165         if ((access_status = ap_run_translate_name(r))) {
166             return decl_die(access_status, "translate", r);
167         }
168     }
169
170     /* Reset to the server default config prior to running map_to_storage 
171      */
172     r->per_dir_config = r->server->lookup_defaults;
173
174     if ((access_status = ap_run_map_to_storage(r))) {
175         /* This request wasn't in storage (e.g. TRACE) */
176         return access_status;
177     }
178
179     /* Excluding file-specific requests with no 'true' URI...
180      */
181     if (!file_req) {
182         /* Rerun the location walk, which overrides any map_to_storage config.
183          */
184         if ((access_status = ap_location_walk(r))) {
185             return access_status;
186         }
187     }
188
189     /* Only on the main request! */
190     if (r->main == NULL) {
191         if ((access_status = ap_run_header_parser(r))) {
192             return access_status;
193         }
194     }
195
196     /* Skip authn/authz if the parent or prior request passed the authn/authz,
197      * and that configuration didn't change (this requires optimized _walk()
198      * functions in map_to_storage that use the same merge results given
199      * identical input.)  If the config changes, we must re-auth.
200      */
201     if (r->main && (r->main->per_dir_config == r->per_dir_config)) {
202         r->user = r->main->user;        
203         r->ap_auth_type = r->main->ap_auth_type;
204     } 
205     else if (r->prev && (r->prev->per_dir_config == r->per_dir_config)) {
206         r->user = r->prev->user;        
207         r->ap_auth_type = r->prev->ap_auth_type;
208     }
209     else {
210         switch (ap_satisfies(r)) {
211         case SATISFY_ALL:
212         case SATISFY_NOSPEC:
213             if ((access_status = ap_run_access_checker(r)) != 0) {
214                 return decl_die(access_status, "check access", r);
215             }
216             if (ap_some_auth_required(r)) {
217                 if (((access_status = ap_run_check_user_id(r)) != 0)
218                     || !ap_auth_type(r)) {
219                     return decl_die(access_status, ap_auth_type(r)
220                                   ? "check user.  No user file?"
221                                   : "perform authentication. AuthType not set!",
222                                   r);
223                 }
224                 if (((access_status = ap_run_auth_checker(r)) != 0)
225                     || !ap_auth_type(r)) {
226                     return decl_die(access_status, ap_auth_type(r)
227                                   ? "check access.  No groups file?"
228                                   : "perform authentication. AuthType not set!",
229                                    r);
230                 }
231             }
232             break;
233         case SATISFY_ANY:
234             if (((access_status = ap_run_access_checker(r)) != 0) || 
235                 !ap_auth_type(r)) {
236                 if (!ap_some_auth_required(r)) {
237                     return decl_die(access_status, ap_auth_type(r)
238                                   ? "check access"
239                                   : "perform authentication. AuthType not set!",
240                                   r);
241                 }
242                 if (((access_status = ap_run_check_user_id(r)) != 0)
243                     || !ap_auth_type(r)) {
244                     return decl_die(access_status, ap_auth_type(r)
245                                   ? "check user.  No user file?"
246                                   : "perform authentication. AuthType not set!",
247                                   r);
248                 }
249                 if (((access_status = ap_run_auth_checker(r)) != 0)
250                     || !ap_auth_type(r)) {
251                     return decl_die(access_status, ap_auth_type(r)
252                                   ? "check access.  No groups file?"
253                                   : "perform authentication. AuthType not set!",
254                                   r);
255                 }
256             }
257             break;
258         }
259     }
260     /* XXX Must make certain the ap_run_type_checker short circuits mime
261      * in mod-proxy for r->proxyreq && r->parsed_uri.scheme 
262      *                              && !strcmp(r->parsed_uri.scheme, "http")
263      */
264     if ((access_status = ap_run_type_checker(r)) != 0) {
265         return decl_die(access_status, "find types", r);
266     }
267
268     if ((access_status = ap_run_fixups(r)) != 0) {
269         return access_status;
270     }
271
272     return OK;
273 }
274
275
276 /* Useful caching structures to repeat _walk/merge sequences as required
277  * when a subrequest or redirect reuses substantially the same config.
278  *
279  * Directive order in the httpd.conf file and its Includes significantly
280  * impact this optimization.  Grouping common blocks at the front of the
281  * config that are less likely to change between a request and 
282  * its subrequests, or between a request and its redirects reduced
283  * the work of these functions significantly.
284  */
285
286 typedef struct walk_walked_t {
287     ap_conf_vector_t *matched; /* A dir_conf sections we matched */
288     ap_conf_vector_t *merged;  /* The dir_conf merged result */
289 } walk_walked_t;
290
291 typedef struct walk_cache_t {
292     const char         *cached;         /* The identifier we matched */
293     ap_conf_vector_t  **dir_conf_tested;/* The sections we matched against */
294     ap_conf_vector_t   *dir_conf_merged;/* Base per_dir_config */
295     ap_conf_vector_t   *per_dir_result; /* per_dir_config += walked result */
296     apr_array_header_t *walked;         /* The list of walk_walked_t results */
297 } walk_cache_t;
298
299 static walk_cache_t *prep_walk_cache(apr_size_t t, request_rec *r)
300 {
301     walk_cache_t *cache;
302     void **note;
303
304     /* Find the most relevant, recent entry to work from.  That would be
305      * this request (on the second call), or the parent request of a
306      * subrequest, or the prior request of an internal redirect.  Provide
307      * this _walk()er with a copy it is allowed to munge.  If there is no
308      * parent or prior cached request, then create a new walk cache.
309      */
310     note = ap_get_request_note(r, t);
311     if (!note) {
312         return NULL;
313     }
314     if (!(cache = *note)) {
315         void **inherit_note;
316         if ((r->main &&
317              ((inherit_note = ap_get_request_note(r->main, t))) &&
318              *inherit_note) ||
319             (r->prev &&
320              ((inherit_note = ap_get_request_note(r->prev, t))) &&
321              *inherit_note)) {
322             cache = apr_pmemdup(r->pool, *inherit_note,
323                                 sizeof(*cache));
324             cache->walked = apr_array_copy(r->pool, cache->walked);
325         }
326         else {
327             cache = apr_pcalloc(r->pool, sizeof(*cache));
328             cache->walked = apr_array_make(r->pool, 4, sizeof(walk_walked_t));
329         }
330         *note = cache;
331     }
332     return cache;
333 }
334
335 /*****************************************************************
336  *
337  * Getting and checking directory configuration.  Also checks the
338  * FollowSymlinks and FollowSymOwner stuff, since this is really the
339  * only place that can happen (barring a new mid_dir_walk callout).
340  *
341  * We can't do it as an access_checker module function which gets
342  * called with the final per_dir_config, since we could have a directory
343  * with FollowSymLinks disabled, which contains a symlink to another
344  * with a .htaccess file which turns FollowSymLinks back on --- and
345  * access in such a case must be denied.  So, whatever it is that
346  * checks FollowSymLinks needs to know the state of the options as
347  * they change, all the way down.
348  */
349
350 /*
351  * We don't want people able to serve up pipes, or unix sockets, or other
352  * scary things.  Note that symlink tests are performed later.
353  */
354 static int check_safe_file(request_rec *r)
355 {
356
357     if (r->finfo.filetype == 0      /* doesn't exist */
358         || r->finfo.filetype == APR_DIR
359         || r->finfo.filetype == APR_REG
360         || r->finfo.filetype == APR_LNK) {
361         return OK;
362     }
363
364     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
365                   "object is not a file, directory or symlink: %s",
366                   r->filename);
367     return HTTP_FORBIDDEN;
368 }
369
370 /*
371  * resolve_symlink must _always_ be called on an APR_LNK file type!
372  * It will resolve the actual target file type, modification date, etc, 
373  * and provide any processing required for symlink evaluation.
374  * Path must already be cleaned, no trailing slash, no multi-slashes,
375  * and don't call this on the root!
376  *
377  * Simply, the number of times we deref a symlink are minimal compared
378  * to the number of times we had an extra lstat() since we 'weren't sure'.
379  *
380  * To optimize, we stat() anything when given (opts & OPT_SYM_LINKS), otherwise
381  * we start off with an lstat().  Every lstat() must be dereferenced in case 
382  * it points at a 'nasty' - we must always rerun check_safe_file (or similar.)
383  */
384 static int resolve_symlink(char *d, apr_finfo_t *lfi, int opts, apr_pool_t *p)
385 {
386     apr_finfo_t fi;
387     int res;
388
389     if (!(opts & (OPT_SYM_OWNER | OPT_SYM_LINKS))) {
390         return HTTP_FORBIDDEN;
391     }
392
393     if (opts & OPT_SYM_LINKS) {
394         if ((res = apr_stat(&fi, d, lfi->valid, p)) != APR_SUCCESS) {
395             return HTTP_FORBIDDEN;
396         }
397
398         /* Give back the target */
399         memcpy(lfi, &fi, sizeof(fi));
400         return OK;
401     }
402
403     /* OPT_SYM_OWNER only works if we can get the owner of 
404      * both the file and symlink.  First fill in a missing
405      * owner of the symlink, then get the info of the target.
406      */
407     if (!(lfi->valid & APR_FINFO_OWNER)) {
408         if ((res = apr_lstat(&fi, d, lfi->valid | APR_FINFO_OWNER, p))
409             != APR_SUCCESS) {
410             return HTTP_FORBIDDEN;
411         }
412     }
413
414     if ((res = apr_stat(&fi, d, lfi->valid, p)) != APR_SUCCESS) {
415         return HTTP_FORBIDDEN;
416     }
417
418     if (apr_compare_users(fi.user, lfi->user) != APR_SUCCESS) {
419         return HTTP_FORBIDDEN;
420     }
421
422     /* Give back the target */
423     memcpy(lfi, &fi, sizeof(fi));
424     return OK;
425 }
426
427
428 /*****************************************************************
429  *
430  * Getting and checking directory configuration.  Also checks the
431  * FollowSymlinks and FollowSymOwner stuff, since this is really the
432  * only place that can happen (barring a new mid_dir_walk callout).
433  *
434  * We can't do it as an access_checker module function which gets
435  * called with the final per_dir_config, since we could have a directory
436  * with FollowSymLinks disabled, which contains a symlink to another
437  * with a .htaccess file which turns FollowSymLinks back on --- and
438  * access in such a case must be denied.  So, whatever it is that
439  * checks FollowSymLinks needs to know the state of the options as
440  * they change, all the way down.
441  */
442
443 AP_DECLARE(int) ap_directory_walk(request_rec *r)
444 {
445     ap_conf_vector_t *now_merged = NULL;
446     core_server_config *sconf = ap_get_module_config(r->server->module_config,
447                                                      &core_module);
448     ap_conf_vector_t **sec_ent = (ap_conf_vector_t **) sconf->sec_dir->elts;
449     int num_sec = sconf->sec_dir->nelts;
450     walk_cache_t *cache;
451     char *entry_dir;
452     apr_status_t rv;
453
454     /* XXX: Better (faster) tests needed!!!
455      *
456      * "OK" as a response to a real problem is not _OK_, but to allow broken 
457      * modules to proceed, we will permit the not-a-path filename to pass here.
458      * We must catch it later if it's heading for the core handler.  Leave an 
459      * INFO note here for module debugging.
460      */
461     if (r->filename == NULL || !ap_os_is_path_absolute(r->pool, r->filename)) {
462         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r,
463                       "Module bug?  Request filename path %s is missing "
464                       "or not absolute for uri %s", 
465                       r->filename ? r->filename : "<NULL>", r->uri);
466        return OK;
467     }
468
469     /* Canonicalize the file path without resolving filename case or aliases
470      * so we can begin by checking the cache for a recent directory walk.
471      * This call will ensure we have an absolute path in the same pass.
472      */
473     if ((rv = apr_filepath_merge(&entry_dir, NULL, r->filename, 
474                                  APR_FILEPATH_NOTRELATIVE, r->pool)) 
475                   != APR_SUCCESS) {
476         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r,
477                       "Module bug?  Request filename path %s is invalid or "
478                       "or not absolute for uri %s", 
479                       r->filename, r->uri);
480         return OK;
481     }
482
483     /* XXX Notice that this forces path_info to be canonical.  That might
484      * not be desired by all apps.  However, some of those same apps likely
485      * have significant security holes.
486      */
487     r->filename = entry_dir;
488
489     cache = prep_walk_cache(AP_NOTE_DIRECTORY_WALK, r);
490
491     /* If this is not a dirent subrequest with a preconstructed 
492      * r->finfo value, then we can simply stat the filename to
493      * save burning mega-cycles with unneeded stats - if this is
494      * an exact file match.  We don't care about failure... we
495      * will stat by component failing this meager attempt.
496      *
497      * It would be nice to distinguish APR_ENOENT from other
498      * types of failure, such as APR_ENOTDIR.  We can do something
499      * with APR_ENOENT, knowing that the path is good.
500      */
501     if (!r->finfo.filetype || r->finfo.filetype == APR_LNK) {
502         apr_stat(&r->finfo, r->filename, APR_FINFO_MIN, r->pool);
503     }
504
505     if (r->finfo.filetype == APR_REG) {
506         entry_dir = ap_make_dirstr_parent(r->pool, entry_dir);
507     }
508     else if (r->filename[strlen(r->filename) - 1] != '/') {
509         entry_dir = apr_pstrcat(r->pool, r->filename, "/", NULL);
510     }
511
512     /* If we have a file already matches the path of r->filename,
513      * and the vhost's list of directory sections hasn't changed, 
514      * we can skip rewalking the directory_walk entries.
515      */
516     if (cache->cached && ((r->finfo.filetype == APR_REG)
517                           || (r->finfo.filetype == APR_DIR))
518         && (cache->dir_conf_tested == sec_ent) 
519         && (strcmp(entry_dir, cache->cached) == 0)) {
520         /* Well this looks really familiar!  If our end-result (per_dir_result)
521          * didn't change, we have absolutely nothing to do :)  
522          * Otherwise (as is the case with most dir_merged/file_merged requests)
523          * we must merge our dir_conf_merged onto this new r->per_dir_config.
524          */
525         if (r->per_dir_config == cache->per_dir_result) {
526             return OK;
527         }
528         if (r->per_dir_config == cache->dir_conf_merged) {
529             r->per_dir_config = cache->per_dir_result;
530             return OK;
531         }
532         if (cache->walked->nelts) {
533             now_merged = ((walk_walked_t*)cache->walked->elts)
534                 [cache->walked->nelts - 1].merged;
535         }
536     }
537     else {
538         /* We start now_merged from NULL since we want to build 
539          * a locations list that can be merged to any vhost.
540          */
541         int sec_idx;
542         int matches = cache->walked->nelts;
543         walk_walked_t *last_walk = (walk_walked_t*)cache->walked->elts;
544         core_dir_config *this_dir;
545         allow_options_t opts;
546         allow_options_t opts_add;
547         allow_options_t opts_remove;
548         overrides_t override;
549
550         apr_finfo_t thisinfo;
551         char *save_path_info;
552         apr_size_t buflen;
553         char *buf;
554         unsigned int seg, startseg;
555
556         /* Invariant: from the first time filename_len is set until
557          * it goes out of scope, filename_len==strlen(r->filename)
558          */
559         apr_size_t filename_len;
560
561         /*
562          * We must play our own mimi-merge game here, for the few 
563          * running dir_config values we care about within dir_walk.
564          * We didn't start the merge from r->per_dir_config, so we
565          * accumulate opts and override as we merge, from the globals.
566          */
567         this_dir = ap_get_module_config(r->per_dir_config, &core_module);
568         opts = this_dir->opts;
569         opts_add = this_dir->opts_add;
570         opts_remove = this_dir->opts_remove;
571         override = this_dir->override;
572
573         /* Save path_info to merge back onto path_info later. If this
574          * isn't really path_info, what would it be doing here?
575          */
576         save_path_info = r->path_info;
577
578         /* Now begin to build r->filename from components, set aside the
579          * segments we have yet to work with in r->path_info (where they
580          * will stay when the current element resolves to a regular file.)
581          *
582          * r->path_info tracks the remaining source path.
583          * r->filename  tracks the path as we build it.
584          */
585         r->path_info = r->filename;
586         rv = apr_filepath_root((const char **)&r->filename,
587                                (const char **)&r->path_info,
588                                APR_FILEPATH_TRUENAME, r->pool);
589         filename_len = strlen(r->filename);
590         /* Space for terminating null and an extra / is required. */
591         buflen = filename_len + strlen(r->path_info) + 2;
592         buf = apr_palloc(r->pool, buflen);
593         memcpy(buf, r->filename, filename_len + 1);
594         r->filename = buf;
595         thisinfo.valid = APR_FINFO_TYPE;
596         thisinfo.filetype = APR_DIR; /* It's the root, of course it's a dir */
597
598         /*
599          * seg keeps track of which segment we've copied.
600          * sec_idx keeps track of which section we're on, since sections are
601          *     ordered by number of segments. See core_reorder_directories 
602          */
603         startseg = seg = ap_count_dirs(r->filename);
604         sec_idx = 0;
605
606         /*
607          * Go down the directory hierarchy.  Where we have to check for 
608          * symlinks, do so.  Where a .htaccess file has permission to 
609          * override anything, try to find one.
610          */
611         do {
612             int res;
613             char *seg_name;
614             char *delim;
615             int temp_slash=0;
616         
617             /* We have no trailing slash, but we sure would appreciate one...
618              */
619             if (sec_idx && r->filename[filename_len-1] != '/') {
620                 r->filename[filename_len++] = '/';
621                 r->filename[filename_len] = 0;
622                 temp_slash=1;
623             }
624
625             /* Begin *this* level by looking for matching <Directory> sections
626              * from the server config.
627              */
628             for (; sec_idx < num_sec; ++sec_idx) {
629
630                 ap_conf_vector_t *entry_config = sec_ent[sec_idx];
631                 core_dir_config *entry_core;
632                 entry_core = ap_get_module_config(entry_config, &core_module);
633
634                 /* No more possible matches for this many segments? 
635                  * We are done when we find relative/regex/longer components.
636                  */
637                 if (entry_core->r || entry_core->d_components > seg) {
638                     break;
639                 }
640
641                 /* We will never skip '0' element components, e.g. plain old
642                  * <Directory >, and <Directory "/"> are classified as zero 
643                  * so that Win32/Netware/OS2 etc all pick them up.
644                  * Otherwise, skip over the mismatches.
645                  */
646                 if (entry_core->d_components
647                       && (entry_core->d_is_fnmatch
648                             ? (apr_fnmatch(entry_core->d, r->filename, 
649                                            FNM_PATHNAME) != APR_SUCCESS)
650                             : (strcmp(r->filename, entry_core->d) != 0))) {
651                     continue;
652                 }
653
654                 /* If we merged this same section last time, reuse it
655                  */
656                 if (matches) {
657                     if (last_walk->matched == sec_ent[sec_idx]) {
658                         now_merged = last_walk->merged;
659                         ++last_walk;
660                         --matches;
661                         goto minimerge;
662                     }
663                     /* We fell out of sync.  This is our own copy of walked,
664                      * so truncate the remaining matches and reset remaining.
665                      */
666                     cache->walked->nelts -= matches;
667                     matches = 0;
668                 }
669
670                 if (now_merged) {
671                     now_merged = ap_merge_per_dir_configs(r->pool, 
672                                                           now_merged,
673                                                           sec_ent[sec_idx]);
674                 }
675                 else {
676                     now_merged = sec_ent[sec_idx];
677                 }
678
679                 last_walk = (walk_walked_t*)apr_array_push(cache->walked);
680                 last_walk->matched = sec_ent[sec_idx];
681                 last_walk->merged = now_merged;
682
683                 /* Do a mini-merge to our globally-based running calculations of
684                  * core_dir->override and core_dir->opts, since now_merged
685                  * never considered the global config.  Of course, if there is 
686                  * no core config at this level, continue without a thought.
687                  * See core.c::merge_core_dir_configs() for explanation.
688                  */
689 minimerge:
690                 this_dir = ap_get_module_config(sec_ent[sec_idx], &core_module);
691
692                 if (!this_dir) {
693                     continue;
694                 }
695
696                 if (this_dir->opts & OPT_UNSET) {
697                     opts_add = (opts_add & ~this_dir->opts_remove) 
698                                | this_dir->opts_add;
699                     opts_remove = (opts_remove & ~this_dir->opts_add)
700                                 | this_dir->opts_remove;
701                     opts = (opts & ~opts_remove) | opts_add;
702                 }
703                 else {
704                     opts = this_dir->opts;
705                     opts_add = this_dir->opts_add;
706                     opts_remove = this_dir->opts_remove;
707                 }
708                 if (!(this_dir->override & OR_UNSET)) {
709                     override = this_dir->override;
710                 }
711             }
712
713             /* If .htaccess files are enabled, check for one, provided we
714              * have reached a real path.
715              */
716             if (seg >= startseg && override) {
717                 ap_conf_vector_t *htaccess_conf = NULL;
718
719                 res = ap_parse_htaccess(&htaccess_conf, r, override,
720                                         apr_pstrdup(r->pool, r->filename),
721                                         sconf->access_name);
722                 if (res) {
723                     return res;
724                 }
725
726                 if (htaccess_conf) {
727
728                     /* If we merged this same htaccess last time, reuse it...
729                      * this wouldn't work except that we cache the htaccess
730                      * sections for the lifetime of the request, so we match 
731                      * the same conf.  Good planning (no, pure luck ;)
732                      */
733                     if (matches) {
734                         if (last_walk->matched == htaccess_conf) {
735                             now_merged = last_walk->merged;
736                             ++last_walk;
737                             --matches;
738                             goto minimerge2;
739                         }
740                         /* We fell out of sync.  This is our own copy of walked,
741                          * so truncate the remaining matches and reset 
742                          * remaining.
743                          */
744                         cache->walked->nelts -= matches;
745                         matches = 0;
746                     }
747
748                     if (now_merged) {
749                         now_merged = ap_merge_per_dir_configs(r->pool, 
750                                                               now_merged,
751                                                               htaccess_conf);
752                     }
753                     else {
754                         now_merged = htaccess_conf;
755                     }
756
757                     last_walk = (walk_walked_t*)apr_array_push(cache->walked);
758                     last_walk->matched = htaccess_conf;
759                     last_walk->merged = now_merged;
760
761                     /* Do a mini-merge to our globally-based running 
762                      * calculations of core_dir->override and core_dir->opts,
763                      * since now_merged never considered the global config.
764                      * Of course, if there is no core config at this level, 
765                      * continue without a thought.
766                      * See core.c::merge_core_dir_configs() for explanation.
767                      */
768 minimerge2:
769                     this_dir = ap_get_module_config(htaccess_conf,
770                                                     &core_module);
771
772                     if (this_dir) {
773                         if (this_dir->opts & OPT_UNSET) {
774                             opts_add = (opts_add & ~this_dir->opts_remove)
775                                 | this_dir->opts_add;
776                             opts_remove = (opts_remove & ~this_dir->opts_add)
777                                 | this_dir->opts_remove;
778                             opts = (opts & ~opts_remove) | opts_add;
779                         }
780                         else {
781                             opts = this_dir->opts;
782                             opts_add = this_dir->opts_add;
783                             opts_remove = this_dir->opts_remove;
784                         }
785                         if (!(this_dir->override & OR_UNSET)) {
786                             override = this_dir->override;
787                         }
788                     }
789                 }
790             }
791
792             /* That temporary trailing slash was useful, now drop it.
793              */
794             if (temp_slash) {
795                 r->filename[--filename_len] = '\0';
796             }
797
798             /* Time for all good things to come to an end?
799              */
800             if (!r->path_info || !*r->path_info) {
801                 break;
802             }
803
804             /* Now it's time for the next segment... 
805              * We will assume the next element is an end node, and fix it up
806              * below as necessary...
807              */
808         
809             seg_name = r->filename + filename_len;
810             delim = strchr(r->path_info + (*r->path_info == '/' ? 1 : 0), '/');
811             if (delim) {
812                 size_t path_info_len = delim - r->path_info;
813                 *delim = '\0';
814                 memcpy(seg_name, r->path_info, path_info_len + 1);
815                 filename_len += path_info_len;
816                 r->path_info = delim;
817                 *delim = '/';
818             }
819             else {
820                 size_t path_info_len = strlen(r->path_info);
821                 memcpy(seg_name, r->path_info, path_info_len + 1);
822                 filename_len += path_info_len;
823                 r->path_info += path_info_len;
824             }
825             if (*seg_name == '/') 
826                 ++seg_name;
827         
828             /* If nothing remained but a '/' string, we are finished
829              */
830             if (!*seg_name) {
831                 break;
832             }
833
834             /* First optimization;
835              * If...we knew r->filename was a file, and
836              * if...we have strict (case-sensitive) filenames, or
837              *      we know the canonical_filename matches to _this_ name, and
838              * if...we have allowed symlinks
839              * skip the lstat and dummy up an APR_DIR value for thisinfo.
840              */
841             if (r->finfo.filetype 
842 #ifdef CASE_BLIND_FILESYSTEM
843                 && (r->canonical_filename 
844                     && (strncmp(r->filename, 
845                                 r->canonical_filename, filename_len) == 0))
846 #endif
847                 && ((opts & (OPT_SYM_OWNER | OPT_SYM_LINKS)) == OPT_SYM_LINKS)) 
848             {
849
850                 thisinfo.filetype = APR_DIR;
851                 ++seg;
852                 continue;
853             }
854
855             /* We choose apr_lstat here, rather that apr_stat, so that we
856              * capture this path object rather than its target.  We will
857              * replace the info with our target's info below.  We especially
858              * want the name of this 'link' object, not the name of its
859              * target, if we are fixing the filename case/resolving aliases.
860              */
861             rv = apr_lstat(&thisinfo, r->filename,
862                            APR_FINFO_MIN | APR_FINFO_NAME, r->pool);
863
864             if (APR_STATUS_IS_ENOENT(rv)) {
865                 /* Nothing?  That could be nice.  But our directory
866                  * walk is done.
867                  */
868                 thisinfo.filetype = APR_NOFILE;
869                 break;
870             }
871             else if (APR_STATUS_IS_EACCES(rv)) {
872                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
873                               "access to %s denied", r->uri);
874                 return r->status = HTTP_FORBIDDEN;
875             }
876             else if ((rv != APR_SUCCESS && rv != APR_INCOMPLETE) 
877                      || !(thisinfo.valid & APR_FINFO_TYPE)) {
878                 /* If we hit ENOTDIR, we must have over-optimized, deny 
879                  * rather than assume not found.
880                  */
881                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
882                               "access to %s failed", r->uri);
883                 return r->status = HTTP_FORBIDDEN;
884             }
885
886             if ((res = check_safe_file(r))) {
887                 r->status = res;
888                 return res;
889             }
890
891             /* Fix up the path now if we have a name, and they don't agree
892              */
893             if ((thisinfo.valid & APR_FINFO_NAME) 
894                 && strcmp(seg_name, thisinfo.name)) {
895                 /* TODO: provide users an option that an internal/external
896                  * redirect is required here?  We need to walk the URI and
897                  * filename in tandem to properly correlate these.
898                  */
899                 strcpy(seg_name, thisinfo.name);
900                 filename_len = strlen(r->filename);
901             }
902
903             if (thisinfo.filetype == APR_LNK) {
904                 /* Is this a possibly acceptable symlink?
905                  */
906                 if ((res = resolve_symlink(r->filename, &thisinfo, 
907                                            opts, r->pool)) != OK) {
908                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
909                                   "Symbolic link not allowed: %s",
910                                   r->filename);
911                     return r->status = res;
912                 }
913
914                 /* Ok, we are done with the link's info, test the real target
915                  */
916                 if (thisinfo.filetype == APR_REG) {
917                     /* That was fun, nothing left for us here
918                      */
919                     break;
920                 }
921                 else if (thisinfo.filetype != APR_DIR) {
922                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
923                              "symlink doesn't point to a file or directory: %s",
924                              r->filename);
925                     return r->status = HTTP_FORBIDDEN;
926                 }
927             }
928
929             ++seg;
930         } while (thisinfo.filetype == APR_DIR);
931
932         /* If we have _not_ optimized, this is the time to recover
933          * the final stat result.
934          */
935         if (!r->finfo.filetype || r->finfo.filetype == APR_LNK) {
936             r->finfo = thisinfo;
937         }
938
939         /* Now splice the saved path_info back onto any new path_info
940          */
941         if (save_path_info) {
942             if (r->path_info && *r->path_info) {
943                 r->path_info = ap_make_full_path(r->pool, r->path_info, 
944                                                  save_path_info);
945             }
946             else {
947                 r->path_info = save_path_info;
948             }
949         }
950
951         /*
952          * Now we'll deal with the regexes, note we pick up sec_idx
953          * where we left off (we gave up after we hit entry_core->r)
954          */
955         for (; sec_idx < num_sec; ++sec_idx) {
956
957             core_dir_config *entry_core; 
958             entry_core = ap_get_module_config(sec_ent[sec_idx], &core_module);
959
960             if (!entry_core->r) {
961                 continue;
962             }
963
964             if (ap_regexec(entry_core->r, r->filename, 0, NULL, REG_NOTEOL)) {
965                 continue;
966             }
967
968             /* If we merged this same section last time, reuse it
969              */
970             if (matches) {
971                 if (last_walk->matched == sec_ent[sec_idx]) {
972                     now_merged = last_walk->merged;
973                     ++last_walk;
974                     --matches;
975                     goto minimerge;
976                 }
977                 /* We fell out of sync.  This is our own copy of walked,
978                  * so truncate the remaining matches and reset remaining.
979                  */
980                 cache->walked->nelts -= matches;
981                 matches = 0;
982             }
983
984             if (now_merged) {
985                 now_merged = ap_merge_per_dir_configs(r->pool, 
986                                                       now_merged,
987                                                       sec_ent[sec_idx]);
988             }
989             else {
990                 now_merged = sec_ent[sec_idx];
991             }
992
993             last_walk = (walk_walked_t*)apr_array_push(cache->walked);
994             last_walk->matched = sec_ent[sec_idx];
995             last_walk->merged = now_merged;
996         }
997
998         /* Whoops - everything matched in sequence, but the original walk
999          * found some additional matches.  Truncate them.
1000          */
1001         if (matches) {
1002             cache->walked->nelts -= matches;
1003         }
1004     }
1005
1006 /* It seems this shouldn't be needed anymore.  We translated the
1007  x symlink above into a real resource, and should have died up there.
1008  x Even if we keep this, it needs more thought (maybe an r->file_is_symlink)
1009  x perhaps it should actually happen in file_walk, so we catch more
1010  x obscure cases in autoindex sub requests, etc.
1011  x
1012  x    * Symlink permissions are determined by the parent.  If the request is
1013  x    * for a directory then applying the symlink test here would use the
1014  x    * permissions of the directory as opposed to its parent.  Consider a
1015  x    * symlink pointing to a dir with a .htaccess disallowing symlinks.  If
1016  x    * you access /symlink (or /symlink/) you would get a 403 without this
1017  x    * APR_DIR test.  But if you accessed /symlink/index.html, for example,
1018  x    * you would *not* get the 403.
1019  x
1020  x   if (r->finfo.filetype != APR_DIR
1021  x       && (res = resolve_symlink(r->filename, r->info, ap_allow_options(r),
1022  x                                 r->pool))) {
1023  x       ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1024  x                     "Symbolic link not allowed: %s", r->filename);
1025  x       return res;
1026  x   }
1027  */
1028
1029     if (r->finfo.filetype == APR_DIR) {
1030         cache->cached = r->filename;
1031     }
1032     else {
1033         cache->cached = ap_make_dirstr_parent(r->pool, r->filename);
1034     }
1035
1036     cache->dir_conf_tested = sec_ent;
1037     cache->dir_conf_merged = r->per_dir_config;
1038
1039     /* Merge our cache->dir_conf_merged construct with the r->per_dir_configs,
1040      * and note the end result to (potentially) skip this step next time.
1041      */
1042     if (now_merged) {
1043         r->per_dir_config = ap_merge_per_dir_configs(r->pool,
1044                                                      r->per_dir_config,
1045                                                      now_merged);
1046     }
1047     cache->per_dir_result = r->per_dir_config;
1048
1049     return OK;
1050 }
1051
1052
1053 AP_DECLARE(int) ap_location_walk(request_rec *r)
1054 {
1055     ap_conf_vector_t *now_merged = NULL;
1056     core_server_config *sconf = ap_get_module_config(r->server->module_config,
1057                                                      &core_module);
1058     ap_conf_vector_t **sec_ent = (ap_conf_vector_t **) sconf->sec_url->elts;
1059     int num_sec = sconf->sec_url->nelts;
1060     walk_cache_t *cache;
1061     const char *entry_uri;
1062
1063     cache = prep_walk_cache(AP_NOTE_LOCATION_WALK, r);
1064     
1065     /* No tricks here, there are no <Locations > to parse in this vhost.
1066      * We won't destroy the cache, just in case _this_ redirect is later
1067      * redirected again to a vhost with <Location > blocks to optimize.
1068      */
1069     if (!num_sec) {
1070         return OK;
1071     }
1072
1073     /* Location and LocationMatch differ on their behaviour w.r.t. multiple
1074      * slashes.  Location matches multiple slashes with a single slash,
1075      * LocationMatch doesn't.  An exception, for backwards brokenness is
1076      * absoluteURIs... in which case neither match multiple slashes.
1077      */
1078     if (r->uri[0] != '/') {
1079         entry_uri = r->uri;
1080     }
1081     else {
1082         char *uri = apr_pstrdup(r->pool, r->uri);
1083         ap_no2slash(uri);
1084         entry_uri = uri;
1085     }
1086
1087     /* If we have an cache->cached location that matches r->uri,
1088      * and the vhost's list of locations hasn't changed, we can skip
1089      * rewalking the location_walk entries.
1090      */
1091     if (cache->cached
1092         && (cache->dir_conf_tested == sec_ent) 
1093         && (strcmp(entry_uri, cache->cached) == 0)) {
1094         /* Well this looks really familiar!  If our end-result (per_dir_result)
1095          * didn't change, we have absolutely nothing to do :)  
1096          * Otherwise (as is the case with most dir_merged/file_merged requests)
1097          * we must merge our dir_conf_merged onto this new r->per_dir_config.
1098          */
1099         if (r->per_dir_config == cache->per_dir_result) {
1100             return OK;
1101         }
1102         if (r->per_dir_config == cache->dir_conf_merged) {
1103             r->per_dir_config = cache->per_dir_result;
1104             return OK;
1105         }
1106         if (cache->walked->nelts) {
1107             now_merged = ((walk_walked_t*)cache->walked->elts)
1108                                             [cache->walked->nelts - 1].merged;
1109         }
1110     }
1111     else {
1112         /* We start now_merged from NULL since we want to build 
1113          * a locations list that can be merged to any vhost.
1114          */
1115         int len, sec_idx;
1116         int matches = cache->walked->nelts;
1117         walk_walked_t *last_walk = (walk_walked_t*)cache->walked->elts;
1118         cache->cached = entry_uri;
1119
1120         /* Go through the location entries, and check for matches.
1121          * We apply the directive sections in given order, we should
1122          * really try them with the most general first.
1123          */
1124         for (sec_idx = 0; sec_idx < num_sec; ++sec_idx) {
1125
1126             core_dir_config *entry_core; 
1127             entry_core = ap_get_module_config(sec_ent[sec_idx], &core_module);
1128             
1129             /* ### const strlen can be optimized in location config parsing */
1130             len = strlen(entry_core->d);
1131
1132             /* Test the regex, fnmatch or string as appropriate.
1133              * If it's a strcmp, and the <Location > pattern was 
1134              * not slash terminated, then this uri must be slash
1135              * terminated (or at the end of the string) to match.
1136              */
1137             if (entry_core->r 
1138                 ? ap_regexec(entry_core->r, r->uri, 0, NULL, 0)
1139                 : (entry_core->d_is_fnmatch
1140                    ? apr_fnmatch(entry_core->d, cache->cached, FNM_PATHNAME)
1141                    : (strncmp(entry_core->d, cache->cached, len)
1142                       ||   (entry_core->d[len - 1] != '/'
1143                             && cache->cached[len] != '/' 
1144                             && cache->cached[len] != '\0')))) {
1145                 continue;
1146             }
1147
1148             /* If we merged this same section last time, reuse it
1149              */
1150             if (matches) {
1151                 if (last_walk->matched == sec_ent[sec_idx]) {
1152                     now_merged = last_walk->merged;
1153                     ++last_walk;
1154                     --matches;
1155                     continue;
1156                 }
1157                 /* We fell out of sync.  This is our own copy of walked,
1158                  * so truncate the remaining matches and reset remaining.
1159                  */
1160                 cache->walked->nelts -= matches;
1161                 matches = 0;
1162             }
1163
1164             if (now_merged) {
1165                 now_merged = ap_merge_per_dir_configs(r->pool, 
1166                                                       now_merged,
1167                                                       sec_ent[sec_idx]);
1168             }
1169             else {
1170                 now_merged = sec_ent[sec_idx];
1171             }
1172
1173             last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1174             last_walk->matched = sec_ent[sec_idx];
1175             last_walk->merged = now_merged;
1176         }
1177         /* Whoops - everything matched in sequence, but the original walk
1178          * found some additional matches.  Truncate them.
1179          */
1180         if (matches) {
1181             cache->walked->nelts -= matches;
1182         }
1183     }
1184
1185     cache->dir_conf_tested = sec_ent;
1186     cache->dir_conf_merged = r->per_dir_config;
1187
1188     /* Merge our cache->dir_conf_merged construct with the r->per_dir_configs,
1189      * and note the end result to (potentially) skip this step next time.
1190      */
1191     if (now_merged) {
1192         r->per_dir_config = ap_merge_per_dir_configs(r->pool,
1193                                                      r->per_dir_config,
1194                                                      now_merged);
1195     }
1196     cache->per_dir_result = r->per_dir_config;
1197
1198     return OK;
1199 }
1200
1201 AP_DECLARE(int) ap_file_walk(request_rec *r)
1202 {
1203     ap_conf_vector_t *now_merged = NULL;
1204     core_dir_config *dconf = ap_get_module_config(r->per_dir_config,
1205                                                   &core_module);
1206     ap_conf_vector_t **sec_ent = (ap_conf_vector_t **) dconf->sec_file->elts;
1207     int num_sec = dconf->sec_file->nelts;
1208     walk_cache_t *cache;
1209     const char *test_file;
1210
1211     /* To allow broken modules to proceed, we allow missing filenames to pass.
1212      * We will catch it later if it's heading for the core handler.  
1213      * directory_walk already posted an INFO note for module debugging.
1214      */
1215      if (r->filename == NULL) {
1216         return OK;
1217     }
1218
1219     cache = prep_walk_cache(AP_NOTE_FILE_WALK, r);
1220
1221     /* No tricks here, there are just no <Files > to parse in this context.
1222      * We won't destroy the cache, just in case _this_ redirect is later
1223      * redirected again to a context containing the same or similar <Files >.
1224      */
1225     if (!num_sec) {
1226         return OK;
1227     }
1228
1229     /* Get the basename .. and copy for the cache just 
1230      * in case r->filename is munged by another module
1231      */
1232     test_file = strrchr(r->filename, '/');
1233     if (test_file == NULL) {
1234         test_file = apr_pstrdup(r->pool, r->filename);
1235     }
1236     else {
1237         test_file = apr_pstrdup(r->pool, ++test_file);
1238     }
1239
1240     /* If we have an cache->cached file name that matches test_file,
1241      * and the directory's list of file sections hasn't changed, we 
1242      * can skip rewalking the file_walk entries.
1243      */
1244     if (cache->cached
1245         && (cache->dir_conf_tested == sec_ent) 
1246         && (strcmp(test_file, cache->cached) == 0)) {
1247         /* Well this looks really familiar!  If our end-result (per_dir_result)
1248          * didn't change, we have absolutely nothing to do :)  
1249          * Otherwise (as is the case with most dir_merged requests)
1250          * we must merge our dir_conf_merged onto this new r->per_dir_config.
1251          */
1252         if (r->per_dir_config == cache->per_dir_result) {
1253             return OK;
1254         }
1255         if (r->per_dir_config == cache->dir_conf_merged) {
1256             r->per_dir_config = cache->per_dir_result;
1257             return OK;
1258         }
1259         if (cache->walked->nelts) {
1260             now_merged = ((walk_walked_t*)cache->walked->elts)
1261                 [cache->walked->nelts - 1].merged;
1262         }
1263     }
1264     else {
1265         /* We start now_merged from NULL since we want to build 
1266          * a file section list that can be merged to any dir_walk.
1267          */
1268         int sec_idx;
1269         int matches = cache->walked->nelts;
1270         walk_walked_t *last_walk = (walk_walked_t*)cache->walked->elts;
1271         cache->cached = test_file;
1272
1273         /* Go through the location entries, and check for matches.
1274          * We apply the directive sections in given order, we should
1275          * really try them with the most general first.
1276          */
1277         for (sec_idx = 0; sec_idx < num_sec; ++sec_idx) {
1278         
1279             core_dir_config *entry_core;
1280             entry_core = ap_get_module_config(sec_ent[sec_idx], &core_module);
1281
1282             if (entry_core->r
1283                 ? ap_regexec(entry_core->r, cache->cached , 0, NULL, 0)
1284                 : (entry_core->d_is_fnmatch
1285                    ? apr_fnmatch(entry_core->d, cache->cached, FNM_PATHNAME)
1286                    : strcmp(entry_core->d, cache->cached))) {
1287                 continue;
1288             }
1289
1290             /* If we merged this same section last time, reuse it
1291              */
1292             if (matches) {
1293                 if (last_walk->matched == sec_ent[sec_idx]) {
1294                     now_merged = last_walk->merged;
1295                     ++last_walk;
1296                     --matches;
1297                     continue;
1298                 }
1299                 /* We fell out of sync.  This is our own copy of walked,
1300                  * so truncate the remaining matches and reset remaining.
1301                  */
1302                 cache->walked->nelts -= matches;
1303                 matches = 0;
1304             }
1305
1306             if (now_merged) {
1307                 now_merged = ap_merge_per_dir_configs(r->pool, 
1308                                                       now_merged,
1309                                                       sec_ent[sec_idx]);
1310             }
1311             else {
1312                 now_merged = sec_ent[sec_idx];
1313             }
1314
1315             last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1316             last_walk->matched = sec_ent[sec_idx];
1317             last_walk->merged = now_merged;
1318         }
1319         /* Whoops - everything matched in sequence, but the original walk
1320          * found some additional matches.  Truncate them.
1321          */
1322         if (matches) {
1323             cache->walked->nelts -= matches;
1324         }
1325     }
1326
1327     cache->dir_conf_tested = sec_ent;
1328     cache->dir_conf_merged = r->per_dir_config;
1329
1330     /* Merge our cache->dir_conf_merged construct with the r->per_dir_configs,
1331      * and note the end result to (potentially) skip this step next time.
1332      */
1333     if (now_merged) {
1334         r->per_dir_config = ap_merge_per_dir_configs(r->pool,
1335                                                      r->per_dir_config,
1336                                                      now_merged);
1337     }
1338     cache->per_dir_result = r->per_dir_config;
1339
1340     return OK;
1341 }
1342
1343 /*****************************************************************
1344  *
1345  * The sub_request mechanism.
1346  *
1347  * Fns to look up a relative URI from, e.g., a map file or SSI document.
1348  * These do all access checks, etc., but don't actually run the transaction
1349  * ... use run_sub_req below for that.  Also, be sure to use destroy_sub_req
1350  * as appropriate if you're likely to be creating more than a few of these.
1351  * (An early Apache version didn't destroy the sub_reqs used in directory
1352  * indexing.  The result, when indexing a directory with 800-odd files in
1353  * it, was massively excessive storage allocation).
1354  *
1355  * Note more manipulation of protocol-specific vars in the request
1356  * structure...
1357  */
1358
1359 static request_rec *make_sub_request(const request_rec *r, 
1360                                      ap_filter_t *next_filter)
1361 {
1362     apr_pool_t *rrp;
1363     request_rec *rnew;
1364     
1365     apr_pool_create(&rrp, r->pool);
1366     rnew = apr_pcalloc(rrp, sizeof(request_rec));
1367     rnew->pool = rrp;
1368
1369     rnew->hostname       = r->hostname;
1370     rnew->request_time   = r->request_time;
1371     rnew->connection     = r->connection;
1372     rnew->server         = r->server;
1373
1374     rnew->request_config = ap_create_request_config(rnew->pool);
1375
1376     /* Start a clean config from this subrequest's vhost.  Optimization in
1377      * Location/File/Dir walks from the parent request assure that if the
1378      * config blocks of the subrequest match the parent request, no merges
1379      * will actually occur (and generally a minimal number of merges are 
1380      * required, even if the parent and subrequest aren't quite identical.)
1381      */
1382     rnew->per_dir_config = r->server->lookup_defaults;
1383
1384     rnew->htaccess       = r->htaccess;
1385     rnew->allowed_methods = ap_make_method_list(rnew->pool, 2);
1386
1387     /* make a copy of the allowed-methods list */
1388     ap_copy_method_list(rnew->allowed_methods, r->allowed_methods);
1389
1390     /* start with the same set of output filters */
1391     if (next_filter) {
1392         rnew->output_filters = next_filter;
1393     }
1394     else {
1395         rnew->output_filters = r->output_filters;
1396     }
1397     ap_add_output_filter("SUBREQ_CORE", NULL, rnew, rnew->connection); 
1398
1399     /* no input filters for a subrequest */
1400
1401     ap_set_sub_req_protocol(rnew, r);
1402
1403     /* We have to run this after we fill in sub req vars, 
1404      * or the r->main pointer won't be setup
1405      */
1406     ap_run_create_request(rnew);
1407
1408     return rnew;
1409 }
1410
1411 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_sub_req_output_filter(ap_filter_t *f,
1412                                                               apr_bucket_brigade *bb)
1413 {
1414     apr_bucket *e = APR_BRIGADE_LAST(bb);
1415
1416     if (APR_BUCKET_IS_EOS(e)) {
1417         apr_bucket_delete(e);
1418     }
1419     if (!APR_BRIGADE_EMPTY(bb)) {
1420         return ap_pass_brigade(f->next, bb);
1421     }
1422     else {
1423         return APR_SUCCESS;
1424     }
1425 }
1426
1427  
1428 AP_DECLARE(int) ap_some_auth_required(request_rec *r)
1429 {
1430     /* Is there a require line configured for the type of *this* req? */
1431  
1432     const apr_array_header_t *reqs_arr = ap_requires(r);
1433     require_line *reqs;
1434     int i;
1435  
1436     if (!reqs_arr) {
1437         return 0;
1438     }
1439  
1440     reqs = (require_line *) reqs_arr->elts;
1441  
1442     for (i = 0; i < reqs_arr->nelts; ++i) {
1443         if (reqs[i].method_mask & (AP_METHOD_BIT << r->method_number)) {
1444             return 1;
1445         }
1446     }
1447  
1448     return 0;
1449
1450
1451
1452 AP_DECLARE(request_rec *) ap_sub_req_method_uri(const char *method,
1453                                                 const char *new_file,
1454                                                 const request_rec *r,
1455                                                 ap_filter_t *next_filter)
1456 {
1457     request_rec *rnew;
1458     int res;
1459     char *udir;
1460
1461     rnew = make_sub_request(r, next_filter);
1462
1463     /* would be nicer to pass "method" to ap_set_sub_req_protocol */
1464     rnew->method = method;
1465     rnew->method_number = ap_method_number_of(method);
1466
1467     if (new_file[0] == '/') {
1468         ap_parse_uri(rnew, new_file);
1469     }
1470     else {
1471         udir = ap_make_dirstr_parent(rnew->pool, r->uri);
1472         udir = ap_escape_uri(rnew->pool, udir);    /* re-escape it */
1473         ap_parse_uri(rnew, ap_make_full_path(rnew->pool, udir, new_file));
1474     }
1475
1476     if ((res = ap_process_request_internal(rnew))) {
1477         rnew->status = res;
1478     }
1479
1480     return rnew;
1481 }
1482
1483 AP_DECLARE(request_rec *) ap_sub_req_lookup_uri(const char *new_file,
1484                                                 const request_rec *r,
1485                                                 ap_filter_t *next_filter)
1486 {
1487     return ap_sub_req_method_uri("GET", new_file, r, next_filter);
1488 }
1489
1490 AP_DECLARE(request_rec *) ap_sub_req_lookup_dirent(const apr_finfo_t *dirent,
1491                                                    const request_rec *r,
1492                                                    ap_filter_t *next_filter)
1493 {
1494     request_rec *rnew;
1495     int res;
1496     char *fdir;
1497     char *udir;
1498
1499     rnew = make_sub_request(r, next_filter);
1500
1501     /* Special case: we are looking at a relative lookup in the same directory. 
1502      * This is 100% safe, since dirent->name just came from the filesystem.
1503      */
1504     udir = ap_make_dirstr_parent(rnew->pool, r->uri);
1505     rnew->uri = ap_make_full_path(rnew->pool, udir, dirent->name);
1506     fdir = ap_make_dirstr_parent(rnew->pool, r->filename);
1507     rnew->filename = ap_make_full_path(rnew->pool, fdir, dirent->name);
1508     if (r->canonical_filename == r->filename) {
1509         rnew->canonical_filename = rnew->filename;
1510     }
1511     
1512     /* XXX This is now less relevant; we will do a full location walk
1513      * these days for this case.  Preserve the apr_stat results, and 
1514      * perhaps we also tag that symlinks were tested and/or found for 
1515      * r->filename.
1516      */
1517     rnew->per_dir_config = r->server->lookup_defaults;
1518
1519     if ((dirent->valid & APR_FINFO_MIN) != APR_FINFO_MIN) {
1520         /*
1521          * apr_dir_read isn't very complete on this platform, so
1522          * we need another apr_lstat (or simply apr_stat if we allow
1523          * all symlinks here.)  If this is an APR_LNK that resolves 
1524          * to an APR_DIR, then we will rerun everything anyways... 
1525          * this should be safe.
1526          */
1527         apr_status_t rv;
1528         if (ap_allow_options(rnew) & OPT_SYM_LINKS) {
1529             if (((rv = apr_stat(&rnew->finfo, rnew->filename,
1530                                 APR_FINFO_MIN, rnew->pool)) != APR_SUCCESS)
1531                 && (rv != APR_INCOMPLETE)) {
1532                 rnew->finfo.filetype = 0;
1533             }
1534         }
1535         else {
1536             if (((rv = apr_lstat(&rnew->finfo, rnew->filename,
1537                                  APR_FINFO_MIN, rnew->pool)) != APR_SUCCESS)
1538                 && (rv != APR_INCOMPLETE)) {
1539                 rnew->finfo.filetype = 0;
1540             }
1541         }
1542     }
1543     else {
1544         memcpy(&rnew->finfo, dirent, sizeof(apr_finfo_t));
1545     }
1546
1547     if (rnew->finfo.filetype == APR_LNK) {
1548         /*
1549          * Resolve this symlink.  We should tie this back to dir_walk's cache
1550          */
1551         if ((res = resolve_symlink(rnew->filename, &rnew->finfo, 
1552                                    ap_allow_options(rnew), rnew->pool))
1553             != OK) {
1554             rnew->status = res;
1555             return rnew;
1556         }
1557     }
1558
1559     if (rnew->finfo.filetype == APR_DIR) {
1560         /* ### Would be real nice if apr_make_full_path overallocated 
1561          * the buffer by one character instead of a complete copy.
1562          */
1563         rnew->filename = apr_pstrcat(rnew->pool, rnew->filename, "/", NULL);
1564         rnew->uri = apr_pstrcat(rnew->pool, rnew->uri, "/", NULL);
1565         if (r->canonical_filename == r->filename) {
1566             rnew->canonical_filename = rnew->filename;
1567         }
1568     }
1569
1570     ap_parse_uri(rnew, rnew->uri);    /* fill in parsed_uri values */
1571
1572     if ((res = ap_process_request_internal(rnew))) {
1573         rnew->status = res;
1574     }
1575
1576     return rnew;
1577 }
1578
1579 AP_DECLARE(request_rec *) ap_sub_req_lookup_file(const char *new_file,
1580                                                  const request_rec *r,
1581                                                  ap_filter_t *next_filter)
1582 {
1583     request_rec *rnew;
1584     int res;
1585     char *fdir;
1586     apr_size_t fdirlen;
1587
1588     rnew = make_sub_request(r, next_filter);
1589
1590     fdir = ap_make_dirstr_parent(rnew->pool, r->filename);
1591     fdirlen = strlen(fdir);
1592
1593     /* Translate r->filename, if it was canonical, it stays canonical
1594      */
1595     if (r->canonical_filename == r->filename) {
1596         rnew->canonical_filename = (char*)(1);
1597     }
1598     if (apr_filepath_merge(&rnew->filename, fdir, new_file,
1599                            APR_FILEPATH_TRUENAME, rnew->pool) != APR_SUCCESS) {
1600         rnew->status = HTTP_FORBIDDEN;
1601         return rnew;
1602     }
1603     if (rnew->canonical_filename) {
1604         rnew->canonical_filename = rnew->filename;
1605     }
1606
1607     /*
1608      * Check for a special case... if there are no '/' characters in new_file
1609      * at all, and the path was the same, then we are looking at a relative 
1610      * lookup in the same directory.  Fixup the URI to match.
1611      */
1612
1613     if (strncmp(rnew->filename, fdir, fdirlen) == 0
1614         && rnew->filename[fdirlen] 
1615         && ap_strchr_c(rnew->filename + fdirlen, '/') == NULL) {
1616         apr_status_t rv;
1617         if (ap_allow_options(rnew) & OPT_SYM_LINKS) {
1618             if (((rv = apr_stat(&rnew->finfo, rnew->filename,
1619                                 APR_FINFO_MIN, rnew->pool)) != APR_SUCCESS)
1620                 && (rv != APR_INCOMPLETE)) {
1621                 rnew->finfo.filetype = 0;
1622             }
1623         }
1624         else {
1625             if (((rv = apr_lstat(&rnew->finfo, rnew->filename,
1626                                  APR_FINFO_MIN, rnew->pool)) != APR_SUCCESS)
1627                 && (rv != APR_INCOMPLETE)) {
1628                 rnew->finfo.filetype = 0;
1629             }
1630         }
1631
1632         if (r->uri && *r->uri) {
1633             char *udir = ap_make_dirstr_parent(rnew->pool, r->uri);
1634             rnew->uri = ap_make_full_path(rnew->pool, udir,
1635                                           rnew->filename + fdirlen);
1636             ap_parse_uri(rnew, rnew->uri);    /* fill in parsed_uri values */
1637         }
1638         else {
1639             ap_parse_uri(rnew, new_file);        /* fill in parsed_uri values */
1640             rnew->uri = apr_pstrdup(rnew->pool, "");
1641         }
1642     }
1643     else {
1644         /* XXX: @@@: What should be done with the parsed_uri values?
1645          * We would be better off stripping down to the 'common' elements
1646          * of the path, then reassembling the URI as best as we can.
1647          */
1648         ap_parse_uri(rnew, new_file);        /* fill in parsed_uri values */
1649         /*
1650          * XXX: this should be set properly like it is in the same-dir case
1651          * but it's actually sometimes to impossible to do it... because the
1652          * file may not have a uri associated with it -djg
1653          */
1654         rnew->uri = apr_pstrdup(rnew->pool, "");
1655     }
1656
1657     if ((res = ap_process_request_internal(rnew))) {
1658         rnew->status = res;
1659     }
1660
1661     return rnew;
1662 }
1663
1664 AP_DECLARE(int) ap_run_sub_req(request_rec *r)
1665 {
1666     int retval;
1667
1668     retval = ap_invoke_handler(r);
1669     ap_finalize_sub_req_protocol(r);
1670     return retval;
1671 }
1672
1673 AP_DECLARE(void) ap_destroy_sub_req(request_rec *r)
1674 {
1675     /* Reclaim the space */
1676     apr_pool_destroy(r->pool);
1677 }
1678
1679 /*
1680  * Function to set the r->mtime field to the specified value if it's later
1681  * than what's already there.
1682  */
1683 AP_DECLARE(void) ap_update_mtime(request_rec *r, apr_time_t dependency_mtime)
1684 {
1685     if (r->mtime < dependency_mtime) {
1686         r->mtime = dependency_mtime;
1687     }
1688 }
1689
1690 /*
1691  * Is it the initial main request, which we only get *once* per HTTP request?
1692  */
1693 AP_DECLARE(int) ap_is_initial_req(request_rec *r)
1694 {
1695     return
1696         (r->main == NULL)       /* otherwise, this is a sub-request */
1697         &&
1698         (r->prev == NULL);      /* otherwise, this is an internal redirect */
1699
1700