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