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