]> granicus.if.org Git - apache/blob - server/request.c
Update the copyright year in all .c, .h and .xml files
[apache] / server / request.c
1 /* Copyright 2001-2006 The Apache Software Foundation or its licensors, as
2  * applicable.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * 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         /* Well this looks really familiar!  If our end-result (per_dir_result)
528          * didn't change, we have absolutely nothing to do :)
529          * Otherwise (as is the case with most dir_merged/file_merged requests)
530          * we must merge our dir_conf_merged onto this new r->per_dir_config.
531          */
532         if (r->per_dir_config == cache->per_dir_result) {
533             return OK;
534         }
535
536         if (r->per_dir_config == cache->dir_conf_merged) {
537             r->per_dir_config = cache->per_dir_result;
538             return OK;
539         }
540
541         if (cache->walked->nelts) {
542             now_merged = ((walk_walked_t*)cache->walked->elts)
543                 [cache->walked->nelts - 1].merged;
544         }
545     }
546     else {
547         /* We start now_merged from NULL since we want to build
548          * a locations list that can be merged to any vhost.
549          */
550         int sec_idx;
551         int matches = cache->walked->nelts;
552         walk_walked_t *last_walk = (walk_walked_t*)cache->walked->elts;
553         core_dir_config *this_dir;
554         core_opts_t opts;
555         apr_finfo_t thisinfo;
556         char *save_path_info;
557         apr_size_t buflen;
558         char *buf;
559         unsigned int seg, startseg;
560
561         /* Invariant: from the first time filename_len is set until
562          * it goes out of scope, filename_len==strlen(r->filename)
563          */
564         apr_size_t filename_len;
565 #ifdef CASE_BLIND_FILESYSTEM
566         apr_size_t canonical_len;
567 #endif
568
569         /*
570          * We must play our own mini-merge game here, for the few
571          * running dir_config values we care about within dir_walk.
572          * We didn't start the merge from r->per_dir_config, so we
573          * accumulate opts and override as we merge, from the globals.
574          */
575         this_dir = ap_get_module_config(r->per_dir_config, &core_module);
576         opts.opts = this_dir->opts;
577         opts.add = this_dir->opts_add;
578         opts.remove = this_dir->opts_remove;
579         opts.override = this_dir->override;
580
581         /* Set aside path_info to merge back onto path_info later.
582          * If r->filename is a directory, we must remerge the path_info,
583          * before we continue!  [Directories cannot, by defintion, have
584          * path info.  Either the next segment is not-found, or a file.]
585          *
586          * r->path_info tracks the unconsumed source path.
587          * r->filename  tracks the path as we process it
588          */
589         if ((r->finfo.filetype == APR_DIR) && r->path_info && *r->path_info)
590         {
591             if ((rv = apr_filepath_merge(&r->path_info, r->filename,
592                                          r->path_info,
593                                          APR_FILEPATH_NOTABOVEROOT, r->pool))
594                 != APR_SUCCESS) {
595                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
596                               "dir_walk error, path_info %s is not relative "
597                               "to the filename path %s for uri %s",
598                               r->path_info, r->filename, r->uri);
599                 return HTTP_INTERNAL_SERVER_ERROR;
600             }
601
602             save_path_info = NULL;
603         }
604         else {
605             save_path_info = r->path_info;
606             r->path_info = r->filename;
607         }
608
609 #ifdef CASE_BLIND_FILESYSTEM
610
611         canonical_len = 0;
612         while (r->canonical_filename && r->canonical_filename[canonical_len]
613                && (r->canonical_filename[canonical_len]
614                    == r->path_info[canonical_len])) {
615              ++canonical_len;
616         }
617
618         while (canonical_len
619                && ((r->canonical_filename[canonical_len - 1] != '/'
620                    && r->canonical_filename[canonical_len - 1])
621                    || (r->path_info[canonical_len - 1] != '/'
622                        && r->path_info[canonical_len - 1]))) {
623             --canonical_len;
624         }
625
626         /*
627          * Now build r->filename component by component, starting
628          * with the root (on Unix, simply "/").  We will make a huge
629          * assumption here for efficiency, that any canonical path
630          * already given included a canonical root.
631          */
632         rv = apr_filepath_root((const char **)&r->filename,
633                                (const char **)&r->path_info,
634                                canonical_len ? 0 : APR_FILEPATH_TRUENAME,
635                                r->pool);
636         filename_len = strlen(r->filename);
637
638         /*
639          * Bad assumption above?  If the root's length is longer
640          * than the canonical length, then it cannot be trusted as
641          * a truename.  So try again, this time more seriously.
642          */
643         if ((rv == APR_SUCCESS) && canonical_len
644             && (filename_len > canonical_len)) {
645             rv = apr_filepath_root((const char **)&r->filename,
646                                    (const char **)&r->path_info,
647                                    APR_FILEPATH_TRUENAME, r->pool);
648             filename_len = strlen(r->filename);
649             canonical_len = 0;
650         }
651
652 #else /* ndef CASE_BLIND_FILESYSTEM, really this simple for Unix today; */
653
654         rv = apr_filepath_root((const char **)&r->filename,
655                                (const char **)&r->path_info,
656                                0, r->pool);
657         filename_len = strlen(r->filename);
658
659 #endif
660
661         if (rv != APR_SUCCESS) {
662             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
663                           "dir_walk error, could not determine the root "
664                           "path of filename %s%s for uri %s",
665                           r->filename, r->path_info, r->uri);
666             return HTTP_INTERNAL_SERVER_ERROR;
667         }
668
669         /* Working space for terminating null and an extra / is required.
670          */
671         buflen = filename_len + strlen(r->path_info) + 2;
672         buf = apr_palloc(r->pool, buflen);
673         memcpy(buf, r->filename, filename_len + 1);
674         r->filename = buf;
675         thisinfo.valid = APR_FINFO_TYPE;
676         thisinfo.filetype = APR_DIR; /* It's the root, of course it's a dir */
677
678         /*
679          * seg keeps track of which segment we've copied.
680          * sec_idx keeps track of which section we're on, since sections are
681          *     ordered by number of segments. See core_reorder_directories
682          * startseg tells us how many segments describe the root path
683          *     e.g. the complete path "//host/foo/" to a UNC share (4)
684          */
685         startseg = seg = ap_count_dirs(r->filename);
686         sec_idx = 0;
687
688         /*
689          * Go down the directory hierarchy.  Where we have to check for
690          * symlinks, do so.  Where a .htaccess file has permission to
691          * override anything, try to find one.
692          */
693         do {
694             int res;
695             char *seg_name;
696             char *delim;
697             int temp_slash=0;
698
699             /* We have no trailing slash, but we sure would appreciate one.
700              * However, we don't want to append a / our first time through.
701              */
702             if ((seg > startseg) && r->filename[filename_len-1] != '/') {
703                 r->filename[filename_len++] = '/';
704                 r->filename[filename_len] = 0;
705                 temp_slash=1;
706             }
707
708             /* Begin *this* level by looking for matching <Directory> sections
709              * from the server config.
710              */
711             for (; sec_idx < num_sec; ++sec_idx) {
712
713                 ap_conf_vector_t *entry_config = sec_ent[sec_idx];
714                 core_dir_config *entry_core;
715                 entry_core = ap_get_module_config(entry_config, &core_module);
716
717                 /* No more possible matches for this many segments?
718                  * We are done when we find relative/regex/longer components.
719                  */
720                 if (entry_core->r || entry_core->d_components > seg) {
721                     break;
722                 }
723
724                 /* We will never skip '0' element components, e.g. plain old
725                  * <Directory >, and <Directory "/"> are classified as zero
726                  * so that Win32/Netware/OS2 etc all pick them up.
727                  * Otherwise, skip over the mismatches.
728                  */
729                 if (entry_core->d_components
730                     && ((entry_core->d_components < seg)
731                      || (entry_core->d_is_fnmatch
732                          ? (apr_fnmatch(entry_core->d, r->filename,
733                                         APR_FNM_PATHNAME) != APR_SUCCESS)
734                          : (strcmp(r->filename, entry_core->d) != 0)))) {
735                     continue;
736                 }
737
738                 /* If we haven't continue'd above, we have a match.
739                  *
740                  * Calculate our full-context core opts & override.
741                  */
742                 core_opts_merge(sec_ent[sec_idx], &opts);
743
744                 /* If we merged this same section last time, reuse it
745                  */
746                 if (matches) {
747                     if (last_walk->matched == sec_ent[sec_idx]) {
748                         now_merged = last_walk->merged;
749                         ++last_walk;
750                         --matches;
751                         continue;
752                     }
753
754                     /* We fell out of sync.  This is our own copy of walked,
755                      * so truncate the remaining matches and reset remaining.
756                      */
757                     cache->walked->nelts -= matches;
758                     matches = 0;
759                 }
760
761                 if (now_merged) {
762                     now_merged = ap_merge_per_dir_configs(r->pool,
763                                                           now_merged,
764                                                           sec_ent[sec_idx]);
765                 }
766                 else {
767                     now_merged = sec_ent[sec_idx];
768                 }
769
770                 last_walk = (walk_walked_t*)apr_array_push(cache->walked);
771                 last_walk->matched = sec_ent[sec_idx];
772                 last_walk->merged = now_merged;
773             }
774
775             /* If .htaccess files are enabled, check for one, provided we
776              * have reached a real path.
777              */
778             do {  /* Not really a loop, just a break'able code block */
779
780                 ap_conf_vector_t *htaccess_conf = NULL;
781
782                 /* No htaccess in an incomplete root path,
783                  * nor if it's disabled
784                  */
785                 if (seg < startseg || !opts.override) {
786                     break;
787                 }
788
789                 res = ap_parse_htaccess(&htaccess_conf, r, opts.override,
790                                         opts.override_opts,
791                                         apr_pstrdup(r->pool, r->filename),
792                                         sconf->access_name);
793                 if (res) {
794                     return res;
795                 }
796
797                 if (!htaccess_conf) {
798                     break;
799                 }
800
801                 /* If we are still here, we found our htaccess.
802                  *
803                  * Calculate our full-context core opts & override.
804                  */
805                 core_opts_merge(htaccess_conf, &opts);
806
807                 /* If we merged this same htaccess last time, reuse it...
808                  * this wouldn't work except that we cache the htaccess
809                  * sections for the lifetime of the request, so we match
810                  * the same conf.  Good planning (no, pure luck ;)
811                  */
812                 if (matches) {
813                     if (last_walk->matched == htaccess_conf) {
814                         now_merged = last_walk->merged;
815                         ++last_walk;
816                         --matches;
817                         break;
818                     }
819
820                     /* We fell out of sync.  This is our own copy of walked,
821                      * so truncate the remaining matches and reset
822                      * remaining.
823                      */
824                     cache->walked->nelts -= matches;
825                     matches = 0;
826                 }
827
828                 if (now_merged) {
829                     now_merged = ap_merge_per_dir_configs(r->pool,
830                                                           now_merged,
831                                                           htaccess_conf);
832                 }
833                 else {
834                     now_merged = htaccess_conf;
835                 }
836
837                 last_walk = (walk_walked_t*)apr_array_push(cache->walked);
838                 last_walk->matched = htaccess_conf;
839                 last_walk->merged = now_merged;
840
841             } while (0); /* Only one htaccess, not a real loop */
842
843             /* That temporary trailing slash was useful, now drop it.
844              */
845             if (temp_slash) {
846                 r->filename[--filename_len] = '\0';
847             }
848
849             /* Time for all good things to come to an end?
850              */
851             if (!r->path_info || !*r->path_info) {
852                 break;
853             }
854
855             /* Now it's time for the next segment...
856              * We will assume the next element is an end node, and fix it up
857              * below as necessary...
858              */
859
860             seg_name = r->filename + filename_len;
861             delim = strchr(r->path_info + (*r->path_info == '/' ? 1 : 0), '/');
862             if (delim) {
863                 size_t path_info_len = delim - r->path_info;
864                 *delim = '\0';
865                 memcpy(seg_name, r->path_info, path_info_len + 1);
866                 filename_len += path_info_len;
867                 r->path_info = delim;
868                 *delim = '/';
869             }
870             else {
871                 size_t path_info_len = strlen(r->path_info);
872                 memcpy(seg_name, r->path_info, path_info_len + 1);
873                 filename_len += path_info_len;
874                 r->path_info += path_info_len;
875             }
876             if (*seg_name == '/')
877                 ++seg_name;
878
879             /* If nothing remained but a '/' string, we are finished
880              * XXX: NO WE ARE NOT!!!  Now process this puppy!!! */
881             if (!*seg_name) {
882                 break;
883             }
884
885             /* First optimization;
886              * If...we knew r->filename was a file, and
887              * if...we have strict (case-sensitive) filenames, or
888              *      we know the canonical_filename matches to _this_ name, and
889              * if...we have allowed symlinks
890              * skip the lstat and dummy up an APR_DIR value for thisinfo.
891              */
892             if (r->finfo.filetype
893 #ifdef CASE_BLIND_FILESYSTEM
894                 && (filename_len <= canonical_len)
895 #endif
896                 && ((opts.opts & (OPT_SYM_OWNER | OPT_SYM_LINKS)) == OPT_SYM_LINKS))
897             {
898
899                 thisinfo.filetype = APR_DIR;
900                 ++seg;
901                 continue;
902             }
903
904             /* We choose apr_stat with flag APR_FINFO_LINK here, rather that
905              * plain apr_stat, so that we capture this path object rather than
906              * its target.  We will replace the info with our target's info
907              * below.  We especially want the name of this 'link' object, not
908              * the name of its target, if we are fixing the filename
909              * case/resolving aliases.
910              */
911             rv = apr_stat(&thisinfo, r->filename,
912                           APR_FINFO_MIN | APR_FINFO_NAME | APR_FINFO_LINK,
913                           r->pool);
914
915             if (APR_STATUS_IS_ENOENT(rv)) {
916                 /* Nothing?  That could be nice.  But our directory
917                  * walk is done.
918                  */
919                 thisinfo.filetype = APR_NOFILE;
920                 break;
921             }
922             else if (APR_STATUS_IS_EACCES(rv)) {
923                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
924                               "access to %s denied", r->uri);
925                 return r->status = HTTP_FORBIDDEN;
926             }
927             else if ((rv != APR_SUCCESS && rv != APR_INCOMPLETE)
928                      || !(thisinfo.valid & APR_FINFO_TYPE)) {
929                 /* If we hit ENOTDIR, we must have over-optimized, deny
930                  * rather than assume not found.
931                  */
932                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
933                               "access to %s failed", r->uri);
934                 return r->status = HTTP_FORBIDDEN;
935             }
936
937             /* Fix up the path now if we have a name, and they don't agree
938              */
939             if ((thisinfo.valid & APR_FINFO_NAME)
940                 && strcmp(seg_name, thisinfo.name)) {
941                 /* TODO: provide users an option that an internal/external
942                  * redirect is required here?  We need to walk the URI and
943                  * filename in tandem to properly correlate these.
944                  */
945                 strcpy(seg_name, thisinfo.name);
946                 filename_len = strlen(r->filename);
947             }
948
949             if (thisinfo.filetype == APR_LNK) {
950                 /* Is this a possibly acceptable symlink?
951                  */
952                 if ((res = resolve_symlink(r->filename, &thisinfo,
953                                            opts.opts, r->pool)) != OK) {
954                     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
955                                   "Symbolic link not allowed "
956                                   "or link target not accessible: %s",
957                                   r->filename);
958                     return r->status = res;
959                 }
960             }
961
962             /* Ok, we are done with the link's info, test the real target
963              */
964             if (thisinfo.filetype == APR_REG ||
965                 thisinfo.filetype == APR_NOFILE) {
966                 /* That was fun, nothing left for us here
967                  */
968                 break;
969             }
970             else if (thisinfo.filetype != APR_DIR) {
971                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
972                               "Forbidden: %s doesn't point to "
973                               "a file or directory",
974                               r->filename);
975                 return r->status = HTTP_FORBIDDEN;
976             }
977
978             ++seg;
979         } while (thisinfo.filetype == APR_DIR);
980
981         /* If we have _not_ optimized, this is the time to recover
982          * the final stat result.
983          */
984         if (!r->finfo.filetype || r->finfo.filetype == APR_LNK) {
985             r->finfo = thisinfo;
986         }
987
988         /* Now splice the saved path_info back onto any new path_info
989          */
990         if (save_path_info) {
991             if (r->path_info && *r->path_info) {
992                 r->path_info = ap_make_full_path(r->pool, r->path_info,
993                                                  save_path_info);
994             }
995             else {
996                 r->path_info = save_path_info;
997             }
998         }
999
1000         /*
1001          * Now we'll deal with the regexes, note we pick up sec_idx
1002          * where we left off (we gave up after we hit entry_core->r)
1003          */
1004         for (; sec_idx < num_sec; ++sec_idx) {
1005
1006             core_dir_config *entry_core;
1007             entry_core = ap_get_module_config(sec_ent[sec_idx], &core_module);
1008
1009             if (!entry_core->r) {
1010                 continue;
1011             }
1012
1013             if (ap_regexec(entry_core->r, r->filename, 0, NULL, AP_REG_NOTEOL)) {
1014                 continue;
1015             }
1016
1017             /* If we haven't already continue'd above, we have a match.
1018              *
1019              * Calculate our full-context core opts & override.
1020              */
1021             core_opts_merge(sec_ent[sec_idx], &opts);
1022
1023             /* If we merged this same section last time, reuse it
1024              */
1025             if (matches) {
1026                 if (last_walk->matched == sec_ent[sec_idx]) {
1027                     now_merged = last_walk->merged;
1028                     ++last_walk;
1029                     --matches;
1030                     continue;
1031                 }
1032
1033                 /* We fell out of sync.  This is our own copy of walked,
1034                  * so truncate the remaining matches and reset remaining.
1035                  */
1036                 cache->walked->nelts -= matches;
1037                 matches = 0;
1038             }
1039
1040             if (now_merged) {
1041                 now_merged = ap_merge_per_dir_configs(r->pool,
1042                                                       now_merged,
1043                                                       sec_ent[sec_idx]);
1044             }
1045             else {
1046                 now_merged = sec_ent[sec_idx];
1047             }
1048
1049             last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1050             last_walk->matched = sec_ent[sec_idx];
1051             last_walk->merged = now_merged;
1052         }
1053
1054         /* Whoops - everything matched in sequence, but the original walk
1055          * found some additional matches.  Truncate them.
1056          */
1057         if (matches) {
1058             cache->walked->nelts -= matches;
1059         }
1060     }
1061
1062 /* It seems this shouldn't be needed anymore.  We translated the
1063  x symlink above into a real resource, and should have died up there.
1064  x Even if we keep this, it needs more thought (maybe an r->file_is_symlink)
1065  x perhaps it should actually happen in file_walk, so we catch more
1066  x obscure cases in autoindex subrequests, etc.
1067  x
1068  x    * Symlink permissions are determined by the parent.  If the request is
1069  x    * for a directory then applying the symlink test here would use the
1070  x    * permissions of the directory as opposed to its parent.  Consider a
1071  x    * symlink pointing to a dir with a .htaccess disallowing symlinks.  If
1072  x    * you access /symlink (or /symlink/) you would get a 403 without this
1073  x    * APR_DIR test.  But if you accessed /symlink/index.html, for example,
1074  x    * you would *not* get the 403.
1075  x
1076  x   if (r->finfo.filetype != APR_DIR
1077  x       && (res = resolve_symlink(r->filename, r->info, ap_allow_options(r),
1078  x                                 r->pool))) {
1079  x       ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1080  x                     "Symbolic link not allowed: %s", r->filename);
1081  x       return res;
1082  x   }
1083  */
1084
1085     /* Save future sub-requestors much angst in processing
1086      * this subrequest.  If dir_walk couldn't canonicalize
1087      * the file path, nothing can.
1088      */
1089     r->canonical_filename = r->filename;
1090
1091     if (r->finfo.filetype == APR_DIR) {
1092         cache->cached = r->filename;
1093     }
1094     else {
1095         cache->cached = ap_make_dirstr_parent(r->pool, r->filename);
1096     }
1097
1098     cache->dir_conf_tested = sec_ent;
1099     cache->dir_conf_merged = r->per_dir_config;
1100
1101     /* Merge our cache->dir_conf_merged construct with the r->per_dir_configs,
1102      * and note the end result to (potentially) skip this step next time.
1103      */
1104     if (now_merged) {
1105         r->per_dir_config = ap_merge_per_dir_configs(r->pool,
1106                                                      r->per_dir_config,
1107                                                      now_merged);
1108     }
1109     cache->per_dir_result = r->per_dir_config;
1110
1111     return OK;
1112 }
1113
1114
1115 AP_DECLARE(int) ap_location_walk(request_rec *r)
1116 {
1117     ap_conf_vector_t *now_merged = NULL;
1118     core_server_config *sconf = ap_get_module_config(r->server->module_config,
1119                                                      &core_module);
1120     ap_conf_vector_t **sec_ent = (ap_conf_vector_t **)sconf->sec_url->elts;
1121     int num_sec = sconf->sec_url->nelts;
1122     walk_cache_t *cache;
1123     const char *entry_uri;
1124
1125     /* No tricks here, there are no <Locations > to parse in this vhost.
1126      * We won't destroy the cache, just in case _this_ redirect is later
1127      * redirected again to a vhost with <Location > blocks to optimize.
1128      */
1129     if (!num_sec) {
1130         return OK;
1131     }
1132
1133     cache = prep_walk_cache(AP_NOTE_LOCATION_WALK, r);
1134
1135     /* Location and LocationMatch differ on their behaviour w.r.t. multiple
1136      * slashes.  Location matches multiple slashes with a single slash,
1137      * LocationMatch doesn't.  An exception, for backwards brokenness is
1138      * absoluteURIs... in which case neither match multiple slashes.
1139      */
1140     if (r->uri[0] != '/') {
1141         entry_uri = r->uri;
1142     }
1143     else {
1144         char *uri = apr_pstrdup(r->pool, r->uri);
1145         ap_no2slash(uri);
1146         entry_uri = uri;
1147     }
1148
1149     /* If we have an cache->cached location that matches r->uri,
1150      * and the vhost's list of locations hasn't changed, we can skip
1151      * rewalking the location_walk entries.
1152      */
1153     if (cache->cached
1154         && (cache->dir_conf_tested == sec_ent)
1155         && (strcmp(entry_uri, cache->cached) == 0)) {
1156         /* Well this looks really familiar!  If our end-result (per_dir_result)
1157          * didn't change, we have absolutely nothing to do :)
1158          * Otherwise (as is the case with most dir_merged/file_merged requests)
1159          * we must merge our dir_conf_merged onto this new r->per_dir_config.
1160          */
1161         if (r->per_dir_config == cache->per_dir_result) {
1162             return OK;
1163         }
1164
1165         if (r->per_dir_config == cache->dir_conf_merged) {
1166             r->per_dir_config = cache->per_dir_result;
1167             return OK;
1168         }
1169
1170         if (cache->walked->nelts) {
1171             now_merged = ((walk_walked_t*)cache->walked->elts)
1172                                             [cache->walked->nelts - 1].merged;
1173         }
1174     }
1175     else {
1176         /* We start now_merged from NULL since we want to build
1177          * a locations list that can be merged to any vhost.
1178          */
1179         int len, sec_idx;
1180         int matches = cache->walked->nelts;
1181         walk_walked_t *last_walk = (walk_walked_t*)cache->walked->elts;
1182         cache->cached = entry_uri;
1183
1184         /* Go through the location entries, and check for matches.
1185          * We apply the directive sections in given order, we should
1186          * really try them with the most general first.
1187          */
1188         for (sec_idx = 0; sec_idx < num_sec; ++sec_idx) {
1189
1190             core_dir_config *entry_core;
1191             entry_core = ap_get_module_config(sec_ent[sec_idx], &core_module);
1192
1193             /* ### const strlen can be optimized in location config parsing */
1194             len = strlen(entry_core->d);
1195
1196             /* Test the regex, fnmatch or string as appropriate.
1197              * If it's a strcmp, and the <Location > pattern was
1198              * not slash terminated, then this uri must be slash
1199              * terminated (or at the end of the string) to match.
1200              */
1201             if (entry_core->r
1202                 ? ap_regexec(entry_core->r, r->uri, 0, NULL, 0)
1203                 : (entry_core->d_is_fnmatch
1204                    ? apr_fnmatch(entry_core->d, cache->cached, APR_FNM_PATHNAME)
1205                    : (strncmp(entry_core->d, cache->cached, len)
1206                       || (entry_core->d[len - 1] != '/'
1207                           && cache->cached[len] != '/'
1208                           && cache->cached[len] != '\0')))) {
1209                 continue;
1210             }
1211
1212             /* If we merged this same section last time, reuse it
1213              */
1214             if (matches) {
1215                 if (last_walk->matched == sec_ent[sec_idx]) {
1216                     now_merged = last_walk->merged;
1217                     ++last_walk;
1218                     --matches;
1219                     continue;
1220                 }
1221
1222                 /* We fell out of sync.  This is our own copy of walked,
1223                  * so truncate the remaining matches and reset remaining.
1224                  */
1225                 cache->walked->nelts -= matches;
1226                 matches = 0;
1227             }
1228
1229             if (now_merged) {
1230                 now_merged = ap_merge_per_dir_configs(r->pool,
1231                                                       now_merged,
1232                                                       sec_ent[sec_idx]);
1233             }
1234             else {
1235                 now_merged = sec_ent[sec_idx];
1236             }
1237
1238             last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1239             last_walk->matched = sec_ent[sec_idx];
1240             last_walk->merged = now_merged;
1241         }
1242
1243         /* Whoops - everything matched in sequence, but the original walk
1244          * found some additional matches.  Truncate them.
1245          */
1246         if (matches) {
1247             cache->walked->nelts -= matches;
1248         }
1249     }
1250
1251     cache->dir_conf_tested = sec_ent;
1252     cache->dir_conf_merged = r->per_dir_config;
1253
1254     /* Merge our cache->dir_conf_merged construct with the r->per_dir_configs,
1255      * and note the end result to (potentially) skip this step next time.
1256      */
1257     if (now_merged) {
1258         r->per_dir_config = ap_merge_per_dir_configs(r->pool,
1259                                                      r->per_dir_config,
1260                                                      now_merged);
1261     }
1262     cache->per_dir_result = r->per_dir_config;
1263
1264     return OK;
1265 }
1266
1267 AP_DECLARE(int) ap_file_walk(request_rec *r)
1268 {
1269     ap_conf_vector_t *now_merged = NULL;
1270     core_dir_config *dconf = ap_get_module_config(r->per_dir_config,
1271                                                   &core_module);
1272     ap_conf_vector_t **sec_ent = (ap_conf_vector_t **)dconf->sec_file->elts;
1273     int num_sec = dconf->sec_file->nelts;
1274     walk_cache_t *cache;
1275     const char *test_file;
1276
1277     /* To allow broken modules to proceed, we allow missing filenames to pass.
1278      * We will catch it later if it's heading for the core handler.
1279      * directory_walk already posted an INFO note for module debugging.
1280      */
1281     if (r->filename == NULL) {
1282         return OK;
1283     }
1284
1285     cache = prep_walk_cache(AP_NOTE_FILE_WALK, r);
1286
1287     /* No tricks here, there are just no <Files > to parse in this context.
1288      * We won't destroy the cache, just in case _this_ redirect is later
1289      * redirected again to a context containing the same or similar <Files >.
1290      */
1291     if (!num_sec) {
1292         return OK;
1293     }
1294
1295     /* Get the basename .. and copy for the cache just
1296      * in case r->filename is munged by another module
1297      */
1298     test_file = strrchr(r->filename, '/');
1299     if (test_file == NULL) {
1300         test_file = apr_pstrdup(r->pool, r->filename);
1301     }
1302     else {
1303         test_file = apr_pstrdup(r->pool, ++test_file);
1304     }
1305
1306     /* If we have an cache->cached file name that matches test_file,
1307      * and the directory's list of file sections hasn't changed, we
1308      * can skip rewalking the file_walk entries.
1309      */
1310     if (cache->cached
1311         && (cache->dir_conf_tested == sec_ent)
1312         && (strcmp(test_file, cache->cached) == 0)) {
1313         /* Well this looks really familiar!  If our end-result (per_dir_result)
1314          * didn't change, we have absolutely nothing to do :)
1315          * Otherwise (as is the case with most dir_merged requests)
1316          * we must merge our dir_conf_merged onto this new r->per_dir_config.
1317          */
1318         if (r->per_dir_config == cache->per_dir_result) {
1319             return OK;
1320         }
1321
1322         if (r->per_dir_config == cache->dir_conf_merged) {
1323             r->per_dir_config = cache->per_dir_result;
1324             return OK;
1325         }
1326
1327         if (cache->walked->nelts) {
1328             now_merged = ((walk_walked_t*)cache->walked->elts)
1329                 [cache->walked->nelts - 1].merged;
1330         }
1331     }
1332     else {
1333         /* We start now_merged from NULL since we want to build
1334          * a file section list that can be merged to any dir_walk.
1335          */
1336         int sec_idx;
1337         int matches = cache->walked->nelts;
1338         walk_walked_t *last_walk = (walk_walked_t*)cache->walked->elts;
1339         cache->cached = test_file;
1340
1341         /* Go through the location entries, and check for matches.
1342          * We apply the directive sections in given order, we should
1343          * really try them with the most general first.
1344          */
1345         for (sec_idx = 0; sec_idx < num_sec; ++sec_idx) {
1346
1347             core_dir_config *entry_core;
1348             entry_core = ap_get_module_config(sec_ent[sec_idx], &core_module);
1349
1350             if (entry_core->r
1351                 ? ap_regexec(entry_core->r, cache->cached , 0, NULL, 0)
1352                 : (entry_core->d_is_fnmatch
1353                    ? apr_fnmatch(entry_core->d, cache->cached, APR_FNM_PATHNAME)
1354                    : strcmp(entry_core->d, cache->cached))) {
1355                 continue;
1356             }
1357
1358             /* If we merged this same section last time, reuse it
1359              */
1360             if (matches) {
1361                 if (last_walk->matched == sec_ent[sec_idx]) {
1362                     now_merged = last_walk->merged;
1363                     ++last_walk;
1364                     --matches;
1365                     continue;
1366                 }
1367
1368                 /* We fell out of sync.  This is our own copy of walked,
1369                  * so truncate the remaining matches and reset remaining.
1370                  */
1371                 cache->walked->nelts -= matches;
1372                 matches = 0;
1373             }
1374
1375             if (now_merged) {
1376                 now_merged = ap_merge_per_dir_configs(r->pool,
1377                                                       now_merged,
1378                                                       sec_ent[sec_idx]);
1379             }
1380             else {
1381                 now_merged = sec_ent[sec_idx];
1382             }
1383
1384             last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1385             last_walk->matched = sec_ent[sec_idx];
1386             last_walk->merged = now_merged;
1387         }
1388
1389         /* Whoops - everything matched in sequence, but the original walk
1390          * found some additional matches.  Truncate them.
1391          */
1392         if (matches) {
1393             cache->walked->nelts -= matches;
1394         }
1395     }
1396
1397     cache->dir_conf_tested = sec_ent;
1398     cache->dir_conf_merged = r->per_dir_config;
1399
1400     /* Merge our cache->dir_conf_merged construct with the r->per_dir_configs,
1401      * and note the end result to (potentially) skip this step next time.
1402      */
1403     if (now_merged) {
1404         r->per_dir_config = ap_merge_per_dir_configs(r->pool,
1405                                                      r->per_dir_config,
1406                                                      now_merged);
1407     }
1408     cache->per_dir_result = r->per_dir_config;
1409
1410     return OK;
1411 }
1412
1413 /*****************************************************************
1414  *
1415  * The sub_request mechanism.
1416  *
1417  * Fns to look up a relative URI from, e.g., a map file or SSI document.
1418  * These do all access checks, etc., but don't actually run the transaction
1419  * ... use run_sub_req below for that.  Also, be sure to use destroy_sub_req
1420  * as appropriate if you're likely to be creating more than a few of these.
1421  * (An early Apache version didn't destroy the sub_reqs used in directory
1422  * indexing.  The result, when indexing a directory with 800-odd files in
1423  * it, was massively excessive storage allocation).
1424  *
1425  * Note more manipulation of protocol-specific vars in the request
1426  * structure...
1427  */
1428
1429 static request_rec *make_sub_request(const request_rec *r,
1430                                      ap_filter_t *next_filter)
1431 {
1432     apr_pool_t *rrp;
1433     request_rec *rnew;
1434
1435     apr_pool_create(&rrp, r->pool);
1436     apr_pool_tag(rrp, "subrequest");
1437     rnew = apr_pcalloc(rrp, sizeof(request_rec));
1438     rnew->pool = rrp;
1439
1440     rnew->hostname       = r->hostname;
1441     rnew->request_time   = r->request_time;
1442     rnew->connection     = r->connection;
1443     rnew->server         = r->server;
1444
1445     rnew->request_config = ap_create_request_config(rnew->pool);
1446
1447     /* Start a clean config from this subrequest's vhost.  Optimization in
1448      * Location/File/Dir walks from the parent request assure that if the
1449      * config blocks of the subrequest match the parent request, no merges
1450      * will actually occur (and generally a minimal number of merges are
1451      * required, even if the parent and subrequest aren't quite identical.)
1452      */
1453     rnew->per_dir_config = r->server->lookup_defaults;
1454
1455     rnew->htaccess = r->htaccess;
1456     rnew->allowed_methods = ap_make_method_list(rnew->pool, 2);
1457
1458     /* make a copy of the allowed-methods list */
1459     ap_copy_method_list(rnew->allowed_methods, r->allowed_methods);
1460
1461     /* start with the same set of output filters */
1462     if (next_filter) {
1463         /* while there are no input filters for a subrequest, we will
1464          * try to insert some, so if we don't have valid data, the code
1465          * will seg fault.
1466          */
1467         rnew->input_filters = r->input_filters;
1468         rnew->proto_input_filters = r->proto_input_filters;
1469         rnew->output_filters = next_filter;
1470         rnew->proto_output_filters = r->proto_output_filters;
1471         ap_add_output_filter_handle(ap_subreq_core_filter_handle,
1472                                     NULL, rnew, rnew->connection);
1473     }
1474     else {
1475         /* If NULL - we are expecting to be internal_fast_redirect'ed
1476          * to this subrequest - or this request will never be invoked.
1477          * Ignore the original request filter stack entirely, and
1478          * drill the input and output stacks back to the connection.
1479          */
1480         rnew->proto_input_filters = r->proto_input_filters;
1481         rnew->proto_output_filters = r->proto_output_filters;
1482
1483         rnew->input_filters = r->proto_input_filters;
1484         rnew->output_filters = r->proto_output_filters;
1485     }
1486
1487     /* no input filters for a subrequest */
1488
1489     ap_set_sub_req_protocol(rnew, r);
1490
1491     /* We have to run this after we fill in sub req vars,
1492      * or the r->main pointer won't be setup
1493      */
1494     ap_run_create_request(rnew);
1495
1496     /* Begin by presuming any module can make its own path_info assumptions,
1497      * until some module interjects and changes the value.
1498      */
1499     rnew->used_path_info = AP_REQ_DEFAULT_PATH_INFO;
1500
1501     return rnew;
1502 }
1503
1504 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_sub_req_output_filter(ap_filter_t *f,
1505                                                               apr_bucket_brigade *bb)
1506 {
1507     apr_bucket *e = APR_BRIGADE_LAST(bb);
1508
1509     if (APR_BUCKET_IS_EOS(e)) {
1510         apr_bucket_delete(e);
1511     }
1512
1513     if (!APR_BRIGADE_EMPTY(bb)) {
1514         return ap_pass_brigade(f->next, bb);
1515     }
1516
1517     return APR_SUCCESS;
1518 }
1519
1520 extern APR_OPTIONAL_FN_TYPE(authz_some_auth_required) *authz_ap_some_auth_required;
1521
1522 AP_DECLARE(int) ap_some_auth_required(request_rec *r)
1523 {
1524     /* Is there a require line configured for the type of *this* req? */
1525     if (authz_ap_some_auth_required) {
1526         return authz_ap_some_auth_required(r);
1527     }
1528     else
1529         return 0;
1530 }
1531
1532
1533 AP_DECLARE(request_rec *) ap_sub_req_method_uri(const char *method,
1534                                                 const char *new_uri,
1535                                                 const request_rec *r,
1536                                                 ap_filter_t *next_filter)
1537 {
1538     request_rec *rnew;
1539     /* Initialise res, to avoid a gcc warning */
1540     int res = HTTP_INTERNAL_SERVER_ERROR;
1541     char *udir;
1542
1543     rnew = make_sub_request(r, next_filter);
1544
1545     /* would be nicer to pass "method" to ap_set_sub_req_protocol */
1546     rnew->method = method;
1547     rnew->method_number = ap_method_number_of(method);
1548
1549     if (new_uri[0] == '/') {
1550         ap_parse_uri(rnew, new_uri);
1551     }
1552     else {
1553         udir = ap_make_dirstr_parent(rnew->pool, r->uri);
1554         udir = ap_escape_uri(rnew->pool, udir);    /* re-escape it */
1555         ap_parse_uri(rnew, ap_make_full_path(rnew->pool, udir, new_uri));
1556     }
1557
1558     /* We cannot return NULL without violating the API. So just turn this
1559      * subrequest into a 500 to indicate the failure. */
1560     if (ap_is_recursion_limit_exceeded(r)) {
1561         rnew->status = HTTP_INTERNAL_SERVER_ERROR;
1562         return rnew;
1563     }
1564
1565     /* lookup_uri
1566      * If the content can be served by the quick_handler, we can
1567      * safely bypass request_internal processing.
1568      *
1569      * If next_filter is NULL we are expecting to be
1570      * internal_fast_redirect'ed to the subrequest, or the subrequest will
1571      * never be invoked. We need to make sure that the quickhandler is not
1572      * invoked by any lookups. Since an internal_fast_redirect will always
1573      * occur too late for the quickhandler to handle the request.
1574      */
1575     if (next_filter) {
1576         res = ap_run_quick_handler(rnew, 1);
1577     }
1578
1579     if (next_filter == NULL || res != OK) {
1580         if ((res = ap_process_request_internal(rnew))) {
1581             rnew->status = res;
1582         }
1583     }
1584
1585     return rnew;
1586 }
1587
1588 AP_DECLARE(request_rec *) ap_sub_req_lookup_uri(const char *new_uri,
1589                                                 const request_rec *r,
1590                                                 ap_filter_t *next_filter)
1591 {
1592     return ap_sub_req_method_uri("GET", new_uri, r, next_filter);
1593 }
1594
1595 AP_DECLARE(request_rec *) ap_sub_req_lookup_dirent(const apr_finfo_t *dirent,
1596                                                    const request_rec *r,
1597                                                    int subtype,
1598                                                    ap_filter_t *next_filter)
1599 {
1600     request_rec *rnew;
1601     int res;
1602     char *fdir;
1603     char *udir;
1604
1605     rnew = make_sub_request(r, next_filter);
1606
1607     /* Special case: we are looking at a relative lookup in the same directory.
1608      * This is 100% safe, since dirent->name just came from the filesystem.
1609      */
1610     if (r->path_info && *r->path_info) {
1611         /* strip path_info off the end of the uri to keep it in sync
1612          * with r->filename, which has already been stripped by directory_walk,
1613          * merge the dirent->name, and then, if the caller wants us to remerge
1614          * the original path info, do so.  Note we never fix the path_info back
1615          * to r->filename, since dir_walk would do so (but we don't expect it
1616          * to happen in the usual cases)
1617          */
1618         udir = apr_pstrdup(rnew->pool, r->uri);
1619         udir[ap_find_path_info(udir, r->path_info)] = '\0';
1620         udir = ap_make_dirstr_parent(rnew->pool, udir);
1621
1622         rnew->uri = ap_make_full_path(rnew->pool, udir, dirent->name);
1623         if (subtype == AP_SUBREQ_MERGE_ARGS) {
1624             rnew->uri = ap_make_full_path(rnew->pool, rnew->uri, r->path_info + 1);
1625             rnew->path_info = apr_pstrdup(rnew->pool, r->path_info);
1626         }
1627         rnew->uri = ap_escape_uri(rnew->pool, rnew->uri);
1628     }
1629     else {
1630         udir = ap_make_dirstr_parent(rnew->pool, r->uri);
1631         rnew->uri = ap_escape_uri(rnew->pool, ap_make_full_path(rnew->pool,
1632                                                                 udir,
1633                                                                 dirent->name));
1634     }
1635
1636     fdir = ap_make_dirstr_parent(rnew->pool, r->filename);
1637     rnew->filename = ap_make_full_path(rnew->pool, fdir, dirent->name);
1638     if (r->canonical_filename == r->filename) {
1639         rnew->canonical_filename = rnew->filename;
1640     }
1641
1642     /* XXX This is now less relevant; we will do a full location walk
1643      * these days for this case.  Preserve the apr_stat results, and
1644      * perhaps we also tag that symlinks were tested and/or found for
1645      * r->filename.
1646      */
1647     rnew->per_dir_config = r->server->lookup_defaults;
1648
1649     if ((dirent->valid & APR_FINFO_MIN) != APR_FINFO_MIN) {
1650         /*
1651          * apr_dir_read isn't very complete on this platform, so
1652          * we need another apr_stat (with or without APR_FINFO_LINK
1653          * depending on whether we allow all symlinks here.)  If this
1654          * is an APR_LNK that resolves to an APR_DIR, then we will rerun
1655          * everything anyways... this should be safe.
1656          */
1657         apr_status_t rv;
1658         if (ap_allow_options(rnew) & OPT_SYM_LINKS) {
1659             if (((rv = apr_stat(&rnew->finfo, rnew->filename,
1660                                 APR_FINFO_MIN, rnew->pool)) != APR_SUCCESS)
1661                 && (rv != APR_INCOMPLETE)) {
1662                 rnew->finfo.filetype = 0;
1663             }
1664         }
1665         else {
1666             if (((rv = apr_stat(&rnew->finfo, rnew->filename,
1667                                 APR_FINFO_LINK | APR_FINFO_MIN,
1668                                 rnew->pool)) != APR_SUCCESS)
1669                 && (rv != APR_INCOMPLETE)) {
1670                 rnew->finfo.filetype = 0;
1671             }
1672         }
1673     }
1674     else {
1675         memcpy(&rnew->finfo, dirent, sizeof(apr_finfo_t));
1676     }
1677
1678     if (rnew->finfo.filetype == APR_LNK) {
1679         /*
1680          * Resolve this symlink.  We should tie this back to dir_walk's cache
1681          */
1682         if ((res = resolve_symlink(rnew->filename, &rnew->finfo,
1683                                    ap_allow_options(rnew), rnew->pool))
1684             != OK) {
1685             rnew->status = res;
1686             return rnew;
1687         }
1688     }
1689
1690     if (rnew->finfo.filetype == APR_DIR) {
1691         /* ap_make_full_path overallocated the buffers
1692          * by one character to help us out here.
1693          */
1694         strcpy(rnew->filename + strlen(rnew->filename), "/");
1695         if (!rnew->path_info || !*rnew->path_info) {
1696             strcpy(rnew->uri  + strlen(rnew->uri ), "/");
1697         }
1698     }
1699
1700     /* fill in parsed_uri values
1701      */
1702     if (r->args && *r->args && (subtype == AP_SUBREQ_MERGE_ARGS)) {
1703         ap_parse_uri(rnew, apr_pstrcat(r->pool, rnew->uri, "?",
1704                                        r->args, NULL));
1705     }
1706     else {
1707         ap_parse_uri(rnew, rnew->uri);
1708     }
1709
1710     /* We cannot return NULL without violating the API. So just turn this
1711      * subrequest into a 500. */
1712     if (ap_is_recursion_limit_exceeded(r)) {
1713         rnew->status = HTTP_INTERNAL_SERVER_ERROR;
1714         return rnew;
1715     }
1716
1717     if ((res = ap_process_request_internal(rnew))) {
1718         rnew->status = res;
1719     }
1720
1721     return rnew;
1722 }
1723
1724 AP_DECLARE(request_rec *) ap_sub_req_lookup_file(const char *new_file,
1725                                                  const request_rec *r,
1726                                                  ap_filter_t *next_filter)
1727 {
1728     request_rec *rnew;
1729     int res;
1730     char *fdir;
1731     apr_size_t fdirlen;
1732
1733     rnew = make_sub_request(r, next_filter);
1734
1735     fdir = ap_make_dirstr_parent(rnew->pool, r->filename);
1736     fdirlen = strlen(fdir);
1737
1738     /* Translate r->filename, if it was canonical, it stays canonical
1739      */
1740     if (r->canonical_filename == r->filename) {
1741         rnew->canonical_filename = (char*)(1);
1742     }
1743
1744     if (apr_filepath_merge(&rnew->filename, fdir, new_file,
1745                            APR_FILEPATH_TRUENAME, rnew->pool) != APR_SUCCESS) {
1746         rnew->status = HTTP_FORBIDDEN;
1747         return rnew;
1748     }
1749
1750     if (rnew->canonical_filename) {
1751         rnew->canonical_filename = rnew->filename;
1752     }
1753
1754     /*
1755      * Check for a special case... if there are no '/' characters in new_file
1756      * at all, and the path was the same, then we are looking at a relative
1757      * lookup in the same directory.  Fixup the URI to match.
1758      */
1759
1760     if (strncmp(rnew->filename, fdir, fdirlen) == 0
1761         && rnew->filename[fdirlen]
1762         && ap_strchr_c(rnew->filename + fdirlen, '/') == NULL) {
1763         apr_status_t rv;
1764         if (ap_allow_options(rnew) & OPT_SYM_LINKS) {
1765             if (((rv = apr_stat(&rnew->finfo, rnew->filename,
1766                                 APR_FINFO_MIN, rnew->pool)) != APR_SUCCESS)
1767                 && (rv != APR_INCOMPLETE)) {
1768                 rnew->finfo.filetype = 0;
1769             }
1770         }
1771         else {
1772             if (((rv = apr_stat(&rnew->finfo, rnew->filename,
1773                                 APR_FINFO_LINK | APR_FINFO_MIN,
1774                                 rnew->pool)) != APR_SUCCESS)
1775                 && (rv != APR_INCOMPLETE)) {
1776                 rnew->finfo.filetype = 0;
1777             }
1778         }
1779
1780         if (r->uri && *r->uri) {
1781             char *udir = ap_make_dirstr_parent(rnew->pool, r->uri);
1782             rnew->uri = ap_make_full_path(rnew->pool, udir,
1783                                           rnew->filename + fdirlen);
1784             ap_parse_uri(rnew, rnew->uri);    /* fill in parsed_uri values */
1785         }
1786         else {
1787             ap_parse_uri(rnew, new_file);        /* fill in parsed_uri values */
1788             rnew->uri = apr_pstrdup(rnew->pool, "");
1789         }
1790     }
1791     else {
1792         /* XXX: @@@: What should be done with the parsed_uri values?
1793          * We would be better off stripping down to the 'common' elements
1794          * of the path, then reassembling the URI as best as we can.
1795          */
1796         ap_parse_uri(rnew, new_file);        /* fill in parsed_uri values */
1797         /*
1798          * XXX: this should be set properly like it is in the same-dir case
1799          * but it's actually sometimes to impossible to do it... because the
1800          * file may not have a uri associated with it -djg
1801          */
1802         rnew->uri = apr_pstrdup(rnew->pool, "");
1803     }
1804
1805     /* We cannot return NULL without violating the API. So just turn this
1806      * subrequest into a 500. */
1807     if (ap_is_recursion_limit_exceeded(r)) {
1808         rnew->status = HTTP_INTERNAL_SERVER_ERROR;
1809         return rnew;
1810     }
1811
1812     if ((res = ap_process_request_internal(rnew))) {
1813         rnew->status = res;
1814     }
1815
1816     return rnew;
1817 }
1818
1819 AP_DECLARE(int) ap_run_sub_req(request_rec *r)
1820 {
1821     int retval = DECLINED;
1822     /* Run the quick handler if the subrequest is not a dirent or file
1823      * subrequest
1824      */
1825     if (!(r->filename && r->finfo.filetype)) {
1826         retval = ap_run_quick_handler(r, 0);
1827     }
1828     if (retval != OK) {
1829         retval = ap_invoke_handler(r);
1830         if (retval == DONE) {
1831             retval = OK;
1832         }
1833     }
1834     ap_finalize_sub_req_protocol(r);
1835     return retval;
1836 }
1837
1838 AP_DECLARE(void) ap_destroy_sub_req(request_rec *r)
1839 {
1840     /* Reclaim the space */
1841     apr_pool_destroy(r->pool);
1842 }
1843
1844 /*
1845  * Function to set the r->mtime field to the specified value if it's later
1846  * than what's already there.
1847  */
1848 AP_DECLARE(void) ap_update_mtime(request_rec *r, apr_time_t dependency_mtime)
1849 {
1850     if (r->mtime < dependency_mtime) {
1851         r->mtime = dependency_mtime;
1852     }
1853 }
1854
1855 /*
1856  * Is it the initial main request, which we only get *once* per HTTP request?
1857  */
1858 AP_DECLARE(int) ap_is_initial_req(request_rec *r)
1859 {
1860     return (r->main == NULL)       /* otherwise, this is a sub-request */
1861            && (r->prev == NULL);   /* otherwise, this is an internal redirect */
1862 }