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