Coverage Report

Created: 2023-06-07 06:38

/src/httpd/server/request.c
Line
Count
Source (jump to first uncovered line)
1
/* Licensed to the Apache Software Foundation (ASF) under one or more
2
 * contributor license agreements.  See the NOTICE file distributed with
3
 * this work for additional information regarding copyright ownership.
4
 * The ASF licenses this file to You under the Apache License, Version 2.0
5
 * (the "License"); you may not use this file except in compliance with
6
 * the License.  You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
17
/*
18
 * @file  request.c
19
 * @brief functions to get and process requests
20
 *
21
 * @author Rob McCool 3/21/93
22
 *
23
 * Thoroughly revamped by rst for Apache.  NB this file reads
24
 * best from the bottom up.
25
 *
26
 */
27
28
#include "apr_strings.h"
29
#include "apr_file_io.h"
30
#include "apr_fnmatch.h"
31
32
#define APR_WANT_STRFUNC
33
#include "apr_want.h"
34
35
#include "ap_config.h"
36
#include "ap_provider.h"
37
#include "httpd.h"
38
#include "http_config.h"
39
#include "http_request.h"
40
#include "http_core.h"
41
#include "http_protocol.h"
42
#include "http_log.h"
43
#include "http_main.h"
44
#include "util_filter.h"
45
#include "util_charset.h"
46
#include "util_script.h"
47
#include "ap_expr.h"
48
#include "mod_request.h"
49
50
#include "mod_core.h"
51
#include "mod_auth.h"
52
53
#if APR_HAVE_STDARG_H
54
#include <stdarg.h>
55
#endif
56
57
/* we know core's module_index is 0 */
58
#undef APLOG_MODULE_INDEX
59
#define APLOG_MODULE_INDEX AP_CORE_MODULE_INDEX
60
61
APR_HOOK_STRUCT(
62
    APR_HOOK_LINK(pre_translate_name)
63
    APR_HOOK_LINK(translate_name)
64
    APR_HOOK_LINK(map_to_storage)
65
    APR_HOOK_LINK(check_user_id)
66
    APR_HOOK_LINK(fixups)
67
    APR_HOOK_LINK(type_checker)
68
    APR_HOOK_LINK(access_checker)
69
    APR_HOOK_LINK(access_checker_ex)
70
    APR_HOOK_LINK(auth_checker)
71
    APR_HOOK_LINK(insert_filter)
72
    APR_HOOK_LINK(create_request)
73
    APR_HOOK_LINK(post_perdir_config)
74
    APR_HOOK_LINK(dirwalk_stat)
75
    APR_HOOK_LINK(force_authn)
76
    APR_HOOK_LINK(token_checker)
77
)
78
79
AP_IMPLEMENT_HOOK_RUN_FIRST(int,pre_translate_name,
80
                            (request_rec *r), (r), DECLINED)
81
AP_IMPLEMENT_HOOK_RUN_FIRST(int,translate_name,
82
                            (request_rec *r), (r), DECLINED)
83
AP_IMPLEMENT_HOOK_RUN_FIRST(int,map_to_storage,
84
                            (request_rec *r), (r), DECLINED)
85
AP_IMPLEMENT_HOOK_RUN_FIRST(int,check_user_id,
86
                            (request_rec *r), (r), DECLINED)
87
AP_IMPLEMENT_HOOK_RUN_ALL(int,fixups,
88
                          (request_rec *r), (r), OK, DECLINED)
89
AP_IMPLEMENT_HOOK_RUN_FIRST(int,type_checker,
90
                            (request_rec *r), (r), DECLINED)
91
AP_IMPLEMENT_HOOK_RUN_ALL(int,access_checker,
92
                          (request_rec *r), (r), OK, DECLINED)
93
AP_IMPLEMENT_HOOK_RUN_FIRST(int,access_checker_ex,
94
                          (request_rec *r), (r), DECLINED)
95
AP_IMPLEMENT_HOOK_RUN_FIRST(int,auth_checker,
96
                            (request_rec *r), (r), DECLINED)
97
AP_IMPLEMENT_HOOK_VOID(insert_filter, (request_rec *r), (r))
98
AP_IMPLEMENT_HOOK_RUN_ALL(int, create_request,
99
                          (request_rec *r), (r), OK, DECLINED)
100
AP_IMPLEMENT_HOOK_RUN_ALL(int, post_perdir_config,
101
                          (request_rec *r), (r), OK, DECLINED)
102
AP_IMPLEMENT_HOOK_RUN_FIRST(apr_status_t,dirwalk_stat,
103
                            (apr_finfo_t *finfo, request_rec *r, apr_int32_t wanted),
104
                            (finfo, r, wanted), AP_DECLINED)
105
AP_IMPLEMENT_HOOK_RUN_FIRST(int,force_authn,
106
                            (request_rec *r), (r), DECLINED)
107
AP_IMPLEMENT_HOOK_RUN_FIRST(int,token_checker,
108
                            (request_rec *r), (r), DECLINED)
109
110
static int auth_internal_per_conf = 0;
111
static int auth_internal_per_conf_hooks = 0;
112
static int auth_internal_per_conf_providers = 0;
113
114
115
static int decl_die(int status, const char *phase, request_rec *r)
116
0
{
117
0
    if (status == DECLINED) {
118
0
        ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(00025)
119
0
                      "configuration error:  couldn't %s: %s", phase, r->uri);
120
0
        return HTTP_INTERNAL_SERVER_ERROR;
121
0
    }
122
0
    else {
123
0
        ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
124
0
                      "auth phase '%s' gave status %d: %s", phase,
125
0
                      status, r->uri);
126
0
        return status;
127
0
    }
128
0
}
129
130
AP_DECLARE(int) ap_some_authn_required(request_rec *r)
131
0
{
132
0
    int access_status;
133
0
    char *olduser = r->user;
134
0
    int rv = FALSE;
135
136
0
    switch (ap_satisfies(r)) {
137
0
    case SATISFY_ALL:
138
0
    case SATISFY_NOSPEC:
139
0
        if ((access_status = ap_run_access_checker(r)) != OK) {
140
0
            break;
141
0
        }
142
143
0
        access_status = ap_run_access_checker_ex(r);
144
0
        if (access_status == DECLINED) {
145
0
            rv = TRUE;
146
0
        }
147
148
0
        break;
149
0
    case SATISFY_ANY:
150
0
        if ((access_status = ap_run_access_checker(r)) == OK) {
151
0
            break;
152
0
        }
153
154
0
        access_status = ap_run_access_checker_ex(r);
155
0
        if (access_status == DECLINED) {
156
0
            rv = TRUE;
157
0
        }
158
159
0
        break;
160
0
    }
161
162
0
    r->user = olduser;
163
0
    return rv;
164
0
}
165
166
static int walk_location_and_if(request_rec *r)
167
0
{
168
0
    int access_status;
169
170
0
    if ((access_status = ap_location_walk(r))) {
171
0
        return access_status;
172
0
    }
173
0
    if ((access_status = ap_if_walk(r))) {
174
0
        return access_status;
175
0
    }
176
177
    /* Don't set per-dir loglevel if LogLevelOverride is set */
178
0
    if (!r->connection->log) {
179
0
        core_dir_config *d = ap_get_core_module_config(r->per_dir_config);
180
0
        if (d->log)
181
0
            r->log = d->log;
182
0
    }
183
184
0
    return OK;
185
0
}
186
187
/* This is the master logic for processing requests.  Do NOT duplicate
188
 * this logic elsewhere, or the security model will be broken by future
189
 * API changes.  Each phase must be individually optimized to pick up
190
 * redundant/duplicate calls by subrequests, and redirects.
191
 */
192
AP_DECLARE(int) ap_process_request_internal(request_rec *r)
193
0
{
194
0
    int access_status = DECLINED;
195
0
    int file_req = (r->main && r->filename);
196
0
    core_server_config *sconf =
197
0
        ap_get_core_module_config(r->server->module_config);
198
0
    unsigned int normalize_flags;
199
200
0
    normalize_flags = AP_NORMALIZE_NOT_ABOVE_ROOT;
201
0
    if (sconf->merge_slashes != AP_CORE_CONFIG_OFF) { 
202
0
        normalize_flags |= AP_NORMALIZE_MERGE_SLASHES;
203
0
    }
204
0
    if (file_req) {
205
        /* File subrequests can have a relative path. */
206
0
        normalize_flags |= AP_NORMALIZE_ALLOW_RELATIVE;
207
0
    }
208
209
0
    if (r->parsed_uri.path) {
210
        /* Normalize: remove /./ and shrink /../ segments, plus
211
         * decode unreserved chars (first time only to avoid
212
         * double decoding after ap_unescape_url() below).
213
         */
214
0
        if (!ap_normalize_path(r->parsed_uri.path,
215
0
                               normalize_flags |
216
0
                               AP_NORMALIZE_DECODE_UNRESERVED)) {
217
0
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(10244)
218
0
                          "invalid URI path (%s)", r->unparsed_uri);
219
0
            return HTTP_BAD_REQUEST;
220
0
        }
221
0
    }
222
223
    /* All file subrequests are a huge pain... they cannot bubble through the
224
     * next several steps.  Only file subrequests are allowed an empty uri,
225
     * otherwise let (pre_)translate_name kill the request.
226
     */
227
0
    if (!file_req) {
228
0
        ap_conf_vector_t *per_dir_config = r->per_dir_config;
229
230
0
        if ((access_status = walk_location_and_if(r))) {
231
0
            return access_status;
232
0
        }
233
234
        /* Let pre_translate_name hooks work with non-decoded URIs, and
235
         * eventually prevent further URI transformations (return DONE).
236
         */
237
0
        access_status = ap_run_pre_translate_name(r);
238
0
        if (ap_is_HTTP_ERROR(access_status)) {
239
0
            return access_status;
240
0
        }
241
242
        /* Throw away pre_trans only merging */
243
0
        r->per_dir_config = per_dir_config;
244
0
    }
245
246
    /* Ignore URL unescaping for translated URIs already */
247
0
    if (access_status != DONE && r->parsed_uri.path) {
248
0
        core_dir_config *d = ap_get_core_module_config(r->per_dir_config);
249
        /* Unreserved chars were already decoded by ap_normalize_path() */
250
0
        unsigned int unescape_flags = AP_UNESCAPE_URL_KEEP_UNRESERVED;
251
0
        if (!d->allow_encoded_slashes) {
252
0
            unescape_flags |= AP_UNESCAPE_URL_FORBID_SLASHES;
253
0
        }
254
0
        else if (!d->decode_encoded_slashes) {
255
0
            unescape_flags |= AP_UNESCAPE_URL_KEEP_SLASHES;
256
0
        }
257
0
        access_status = ap_unescape_url_ex(r->parsed_uri.path, unescape_flags);
258
0
        if (access_status) {
259
0
            if (access_status == HTTP_NOT_FOUND) {
260
0
                if (! d->allow_encoded_slashes) {
261
0
                    ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00026)
262
0
                                  "found %%2f (encoded '/') in URI path (%s), "
263
0
                                  "returning 404", r->unparsed_uri);
264
0
                }
265
0
            }
266
0
            return access_status;
267
0
        }
268
269
0
        if (d->allow_encoded_slashes && d->decode_encoded_slashes) {
270
            /* Decoding slashes might have created new // or /./ or /../
271
             * segments (e.g. "/.%2F/"), so re-normalize.
272
             */
273
0
            ap_normalize_path(r->parsed_uri.path, normalize_flags);
274
0
        }
275
0
    }
276
277
    /* Same, translate_name is not suited for file subrequests */
278
0
    if (!file_req) {
279
0
        if ((access_status = walk_location_and_if(r))) {
280
0
            return access_status;
281
0
        }
282
283
0
        if ((access_status = ap_run_translate_name(r))) {
284
0
            return decl_die(access_status, "translate", r);
285
0
        }
286
0
    }
287
288
    /* Reset to the server default config prior to running map_to_storage
289
     */
290
0
    r->per_dir_config = r->server->lookup_defaults;
291
292
0
    if ((access_status = ap_run_map_to_storage(r))) {
293
        /* This request wasn't in storage (e.g. TRACE) */
294
0
        return access_status;
295
0
    }
296
297
    /* Rerun the location walk, which overrides any map_to_storage config.
298
     */
299
0
    if ((access_status = walk_location_and_if(r))) {
300
0
        return access_status;
301
0
    }
302
303
0
    if ((access_status = ap_run_post_perdir_config(r))) {
304
0
        return access_status;
305
0
    }
306
307
    /* Only on the main request! */
308
0
    if (r->main == NULL) {
309
0
        if ((access_status = ap_run_header_parser(r))) {
310
0
            return access_status;
311
0
        }
312
0
    }
313
314
    /* Skip authn/authz if the parent or prior request passed the authn/authz,
315
     * and that configuration didn't change (this requires optimized _walk()
316
     * functions in map_to_storage that use the same merge results given
317
     * identical input.)  If the config changes, we must re-auth.
318
     */
319
0
    if (r->prev && (r->prev->per_dir_config == r->per_dir_config)) {
320
0
        r->user = r->prev->user;
321
0
        r->ap_auth_type = r->prev->ap_auth_type;
322
0
    }
323
0
    else if (r->main && (r->main->per_dir_config == r->per_dir_config)) {
324
0
        r->user = r->main->user;
325
0
        r->ap_auth_type = r->main->ap_auth_type;
326
0
    }
327
0
    else {
328
        /* A module using a confusing API (ap_get_basic_auth_pw) caused
329
        ** r->user to be filled out prior to check_authn hook. We treat
330
        ** it is inadvertent.
331
        */
332
0
        if (r->user && apr_table_get(r->notes, AP_GET_BASIC_AUTH_PW_NOTE)) { 
333
0
            r->user = NULL;
334
0
        }
335
336
0
        switch (ap_satisfies(r)) {
337
0
        case SATISFY_ALL:
338
0
        case SATISFY_NOSPEC:
339
0
            if ((access_status = ap_run_token_checker(r)) != OK &&
340
0
                access_status != DECLINED) {
341
0
                return decl_die(access_status,
342
0
                                "check token (with Satisfy All)", r);
343
0
            }
344
345
0
            if ((access_status = ap_run_access_checker(r)) != OK) {
346
0
                return decl_die(access_status,
347
0
                                "check access (with Satisfy All)", r);
348
0
            }
349
350
0
            access_status = ap_run_access_checker_ex(r);
351
0
            if (access_status == DECLINED
352
0
                || (access_status == OK && ap_run_force_authn(r) == OK)) {
353
0
                if ((access_status = ap_run_check_user_id(r)) != OK) {
354
0
                    return decl_die(access_status, "check user", r);
355
0
                }
356
0
                if (r->user == NULL) {
357
                    /* don't let buggy authn module crash us in authz */
358
0
                    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00027)
359
0
                                  "No authentication done but request not "
360
0
                                  "allowed without authentication for %s. "
361
0
                                  "Authentication not configured?",
362
0
                                  r->uri);
363
0
                    access_status = HTTP_INTERNAL_SERVER_ERROR;
364
0
                    return decl_die(access_status, "check user", r);
365
0
                }
366
0
                if ((access_status = ap_run_auth_checker(r)) != OK) {
367
0
                    return decl_die(access_status, "check authorization", r);
368
0
                }
369
0
            }
370
0
            else if (access_status == OK) {
371
0
                ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
372
0
                              "request authorized without authentication by "
373
0
                              "access_checker_ex hook: %s", r->uri);
374
0
            }
375
0
            else {
376
0
                return decl_die(access_status, "check access", r);
377
0
            }
378
0
            break;
379
0
        case SATISFY_ANY:
380
0
            if ((access_status = ap_run_token_checker(r)) == OK) {
381
0
                ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
382
0
                              "request authorized bypassing access_checker by "
383
0
                              "token_checker hook and 'Satisfy any': %s",
384
0
                              r->uri);
385
0
                break;
386
0
            }
387
388
0
            if ((access_status = ap_run_access_checker(r)) == OK) {
389
0
                ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
390
0
                              "request authorized without authentication by "
391
0
                              "access_checker hook and 'Satisfy any': %s",
392
0
                              r->uri);
393
0
                break;
394
0
            }
395
396
0
            access_status = ap_run_access_checker_ex(r);
397
0
            if (access_status == DECLINED
398
0
                || (access_status == OK && ap_run_force_authn(r) == OK)) {
399
0
                if ((access_status = ap_run_check_user_id(r)) != OK) {
400
0
                    return decl_die(access_status, "check user", r);
401
0
                }
402
0
                if (r->user == NULL) {
403
                    /* don't let buggy authn module crash us in authz */
404
0
                    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00028)
405
0
                                  "No authentication done but request not "
406
0
                                  "allowed without authentication for %s. "
407
0
                                  "Authentication not configured?",
408
0
                                  r->uri);
409
0
                    access_status = HTTP_INTERNAL_SERVER_ERROR;
410
0
                    return decl_die(access_status, "check user", r);
411
0
                }
412
0
                if ((access_status = ap_run_auth_checker(r)) != OK) {
413
0
                    return decl_die(access_status, "check authorization", r);
414
0
                }
415
0
            }
416
0
            else if (access_status == OK) {
417
0
                ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
418
0
                              "request authorized without authentication by "
419
0
                              "access_checker_ex hook: %s", r->uri);
420
0
            }
421
0
            else {
422
0
                return decl_die(access_status, "check access", r);
423
0
            }
424
0
            break;
425
0
        }
426
0
    }
427
    /* XXX Must make certain the ap_run_type_checker short circuits mime
428
     * in mod-proxy for r->proxyreq && r->parsed_uri.scheme
429
     *                              && !strcmp(r->parsed_uri.scheme, "http")
430
     */
431
0
    if ((access_status = ap_run_type_checker(r)) != OK) {
432
0
        return decl_die(access_status, "find types", r);
433
0
    }
434
435
0
    if ((access_status = ap_run_fixups(r)) != OK) {
436
0
        ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "fixups hook gave %d: %s",
437
0
                      access_status, r->uri);
438
0
        return access_status;
439
0
    }
440
441
0
    return OK;
442
0
}
443
444
445
/* Useful caching structures to repeat _walk/merge sequences as required
446
 * when a subrequest or redirect reuses substantially the same config.
447
 *
448
 * Directive order in the httpd.conf file and its Includes significantly
449
 * impact this optimization.  Grouping common blocks at the front of the
450
 * config that are less likely to change between a request and
451
 * its subrequests, or between a request and its redirects reduced
452
 * the work of these functions significantly.
453
 */
454
455
typedef struct walk_walked_t {
456
    ap_conf_vector_t *matched; /* A dir_conf sections we matched */
457
    ap_conf_vector_t *merged;  /* The dir_conf merged result */
458
} walk_walked_t;
459
460
typedef struct walk_cache_t {
461
    const char         *cached;          /* The identifier we matched */
462
    ap_conf_vector_t  **dir_conf_tested; /* The sections we matched against */
463
    ap_conf_vector_t   *dir_conf_merged; /* Base per_dir_config */
464
    ap_conf_vector_t   *per_dir_result;  /* per_dir_config += walked result */
465
    apr_array_header_t *walked;          /* The list of walk_walked_t results */
466
    struct walk_cache_t *prev; /* Prev cache of same call in this (sub)req */
467
    int count; /* Number of prev invocations of same call in this (sub)req */
468
} walk_cache_t;
469
470
static walk_cache_t *prep_walk_cache(apr_size_t t, request_rec *r)
471
0
{
472
0
    void **note, **inherit_note;
473
0
    walk_cache_t *cache, *prev_cache, *copy_cache;
474
0
    int count;
475
476
    /* Find the most relevant, recent walk cache to work from and provide
477
     * a copy the caller is allowed to munge.  In the case of a sub-request
478
     * or internal redirect, this is the cache corresponding to the equivalent
479
     * invocation of the same function call in the "parent" request, if such
480
     * a cache exists.  Otherwise it is the walk cache of the previous
481
     * invocation of the same function call in the current request, if
482
     * that exists; if not, then create a new walk cache.
483
     */
484
0
    note = ap_get_request_note(r, t);
485
0
    AP_DEBUG_ASSERT(note != NULL);
486
487
0
    copy_cache = prev_cache = *note;
488
0
    count = prev_cache ? (prev_cache->count + 1) : 0;
489
490
0
    if ((r->prev
491
0
         && (inherit_note = ap_get_request_note(r->prev, t))
492
0
         && *inherit_note)
493
0
        || (r->main
494
0
            && (inherit_note = ap_get_request_note(r->main, t))
495
0
            && *inherit_note)) {
496
0
        walk_cache_t *inherit_cache = *inherit_note;
497
498
0
        while (inherit_cache->count > count) {
499
0
            inherit_cache = inherit_cache->prev;
500
0
        }
501
0
        if (inherit_cache->count == count) {
502
0
            copy_cache = inherit_cache;
503
0
        }
504
0
    }
505
506
0
    if (copy_cache) {
507
0
        cache = apr_pmemdup(r->pool, copy_cache, sizeof(*cache));
508
0
        cache->walked = apr_array_copy(r->pool, cache->walked);
509
0
        cache->prev = prev_cache;
510
0
        cache->count = count;
511
0
    }
512
0
    else {
513
0
        cache = apr_pcalloc(r->pool, sizeof(*cache));
514
0
        cache->walked = apr_array_make(r->pool, 4, sizeof(walk_walked_t));
515
0
    }
516
517
0
    *note = cache;
518
519
0
    return cache;
520
0
}
521
522
/*****************************************************************
523
 *
524
 * Getting and checking directory configuration.  Also checks the
525
 * FollowSymlinks and FollowSymOwner stuff, since this is really the
526
 * only place that can happen (barring a new mid_dir_walk callout).
527
 *
528
 * We can't do it as an access_checker module function which gets
529
 * called with the final per_dir_config, since we could have a directory
530
 * with FollowSymLinks disabled, which contains a symlink to another
531
 * with a .htaccess file which turns FollowSymLinks back on --- and
532
 * access in such a case must be denied.  So, whatever it is that
533
 * checks FollowSymLinks needs to know the state of the options as
534
 * they change, all the way down.
535
 */
536
537
538
/*
539
 * resolve_symlink must _always_ be called on an APR_LNK file type!
540
 * It will resolve the actual target file type, modification date, etc,
541
 * and provide any processing required for symlink evaluation.
542
 * Path must already be cleaned, no trailing slash, no multi-slashes,
543
 * and don't call this on the root!
544
 *
545
 * Simply, the number of times we deref a symlink are minimal compared
546
 * to the number of times we had an extra lstat() since we 'weren't sure'.
547
 *
548
 * To optimize, we stat() anything when given (opts & OPT_SYM_LINKS), otherwise
549
 * we start off with an lstat().  Every lstat() must be dereferenced in case
550
 * it points at a 'nasty' - we must always rerun check_safe_file (or similar.)
551
 */
552
static int resolve_symlink(char *d, apr_finfo_t *lfi, int opts, apr_pool_t *p)
553
0
{
554
0
    apr_finfo_t fi;
555
0
    const char *savename;
556
557
0
    if (!(opts & (OPT_SYM_OWNER | OPT_SYM_LINKS))) {
558
0
        return HTTP_FORBIDDEN;
559
0
    }
560
561
    /* Save the name from the valid bits. */
562
0
    savename = (lfi->valid & APR_FINFO_NAME) ? lfi->name : NULL;
563
564
    /* if OPT_SYM_OWNER is unset, we only need to check target accessible */
565
0
    if (!(opts & OPT_SYM_OWNER)) {
566
0
        if (apr_stat(&fi, d, lfi->valid & ~(APR_FINFO_NAME | APR_FINFO_LINK), p)
567
0
            != APR_SUCCESS)
568
0
        {
569
0
            return HTTP_FORBIDDEN;
570
0
        }
571
572
        /* Give back the target */
573
0
        memcpy(lfi, &fi, sizeof(fi));
574
0
        if (savename) {
575
0
            lfi->name = savename;
576
0
            lfi->valid |= APR_FINFO_NAME;
577
0
        }
578
579
0
        return OK;
580
0
    }
581
582
    /* OPT_SYM_OWNER only works if we can get the owner of
583
     * both the file and symlink.  First fill in a missing
584
     * owner of the symlink, then get the info of the target.
585
     */
586
0
    if (!(lfi->valid & APR_FINFO_OWNER)) {
587
0
        if (apr_stat(lfi, d, lfi->valid | APR_FINFO_LINK | APR_FINFO_OWNER, p)
588
0
            != APR_SUCCESS)
589
0
        {
590
0
            return HTTP_FORBIDDEN;
591
0
        }
592
0
    }
593
594
0
    if (apr_stat(&fi, d, lfi->valid & ~(APR_FINFO_NAME), p) != APR_SUCCESS) {
595
0
        return HTTP_FORBIDDEN;
596
0
    }
597
598
0
    if (apr_uid_compare(fi.user, lfi->user) != APR_SUCCESS) {
599
0
        return HTTP_FORBIDDEN;
600
0
    }
601
602
    /* Give back the target */
603
0
    memcpy(lfi, &fi, sizeof(fi));
604
0
    if (savename) {
605
0
        lfi->name = savename;
606
0
        lfi->valid |= APR_FINFO_NAME;
607
0
    }
608
609
0
    return OK;
610
0
}
611
612
613
/*
614
 * As we walk the directory configuration, the merged config won't
615
 * be 'rooted' to a specific vhost until the very end of the merge.
616
 *
617
 * We need a very fast mini-merge to a real, vhost-rooted merge
618
 * of core.opts and core.override, the only options tested within
619
 * directory_walk itself.
620
 *
621
 * See core.c::merge_core_dir_configs() for explanation.
622
 */
623
624
typedef struct core_opts_t {
625
        allow_options_t opts;
626
        allow_options_t add;
627
        allow_options_t remove;
628
        overrides_t override;
629
        overrides_t override_opts;
630
        apr_table_t *override_list;
631
} core_opts_t;
632
633
static void core_opts_merge(const ap_conf_vector_t *sec, core_opts_t *opts)
634
0
{
635
0
    core_dir_config *this_dir = ap_get_core_module_config(sec);
636
637
0
    if (!this_dir) {
638
0
        return;
639
0
    }
640
641
0
    if (this_dir->opts & OPT_UNSET) {
642
0
        opts->add = (opts->add & ~this_dir->opts_remove)
643
0
                   | this_dir->opts_add;
644
0
        opts->remove = (opts->remove & ~this_dir->opts_add)
645
0
                      | this_dir->opts_remove;
646
0
        opts->opts = (opts->opts & ~opts->remove) | opts->add;
647
0
    }
648
0
    else {
649
0
        opts->opts = this_dir->opts;
650
0
        opts->add = this_dir->opts_add;
651
0
        opts->remove = this_dir->opts_remove;
652
0
    }
653
654
0
    if (!(this_dir->override & OR_UNSET)) {
655
0
        opts->override = this_dir->override;
656
0
        opts->override_opts = this_dir->override_opts;
657
0
    }
658
659
0
    if (this_dir->override_list != NULL) {
660
0
        opts->override_list = this_dir->override_list;
661
0
    }
662
0
}
663
664
665
/*****************************************************************
666
 *
667
 * Getting and checking directory configuration.  Also checks the
668
 * FollowSymlinks and FollowSymOwner stuff, since this is really the
669
 * only place that can happen (barring a new mid_dir_walk callout).
670
 *
671
 * We can't do it as an access_checker module function which gets
672
 * called with the final per_dir_config, since we could have a directory
673
 * with FollowSymLinks disabled, which contains a symlink to another
674
 * with a .htaccess file which turns FollowSymLinks back on --- and
675
 * access in such a case must be denied.  So, whatever it is that
676
 * checks FollowSymLinks needs to know the state of the options as
677
 * they change, all the way down.
678
 */
679
680
AP_DECLARE(int) ap_directory_walk(request_rec *r)
681
0
{
682
0
    ap_conf_vector_t *now_merged = NULL;
683
0
    core_server_config *sconf =
684
0
        ap_get_core_module_config(r->server->module_config);
685
0
    ap_conf_vector_t **sec_ent = (ap_conf_vector_t **) sconf->sec_dir->elts;
686
0
    int num_sec = sconf->sec_dir->nelts;
687
0
    walk_cache_t *cache;
688
0
    char *entry_dir;
689
0
    apr_status_t rv;
690
0
    int cached;
691
692
    /* XXX: Better (faster) tests needed!!!
693
     *
694
     * "OK" as a response to a real problem is not _OK_, but to allow broken
695
     * modules to proceed, we will permit the not-a-path filename to pass the
696
     * following two tests.  This behavior may be revoked in future versions
697
     * of Apache.  We still must catch it later if it's heading for the core
698
     * handler.  Leave INFO notes here for module debugging.
699
     */
700
0
    if (r->filename == NULL) {
701
0
        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00029)
702
0
                      "Module bug?  Request filename is missing for URI %s",
703
0
                      r->uri);
704
0
        return OK;
705
0
    }
706
707
    /* Canonicalize the file path without resolving filename case or aliases
708
     * so we can begin by checking the cache for a recent directory walk.
709
     * This call will ensure we have an absolute path in the same pass.
710
     */
711
0
    if ((rv = apr_filepath_merge(&entry_dir, NULL, r->filename,
712
0
                                 APR_FILEPATH_NOTRELATIVE, r->pool))
713
0
                  != APR_SUCCESS) {
714
0
        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00030)
715
0
                      "Module bug?  Request filename path %s is invalid or "
716
0
                      "or not absolute for uri %s",
717
0
                      r->filename, r->uri);
718
0
        return OK;
719
0
    }
720
721
    /* XXX Notice that this forces path_info to be canonical.  That might
722
     * not be desired by all apps.  However, some of those same apps likely
723
     * have significant security holes.
724
     */
725
0
    r->filename = entry_dir;
726
727
0
    cache = prep_walk_cache(AP_NOTE_DIRECTORY_WALK, r);
728
0
    cached = (cache->cached != NULL);
729
730
    /* If this is not a dirent subrequest with a preconstructed
731
     * r->finfo value, then we can simply stat the filename to
732
     * save burning mega-cycles with unneeded stats - if this is
733
     * an exact file match.  We don't care about failure... we
734
     * will stat by component failing this meager attempt.
735
     *
736
     * It would be nice to distinguish APR_ENOENT from other
737
     * types of failure, such as APR_ENOTDIR.  We can do something
738
     * with APR_ENOENT, knowing that the path is good.
739
     */
740
0
    if (r->finfo.filetype == APR_NOFILE || r->finfo.filetype == APR_LNK) {
741
0
        rv = ap_run_dirwalk_stat(&r->finfo, r, APR_FINFO_MIN);
742
743
        /* some OSs will return APR_SUCCESS/APR_REG if we stat
744
         * a regular file but we have '/' at the end of the name;
745
         *
746
         * other OSs will return APR_ENOTDIR for that situation;
747
         *
748
         * handle it the same everywhere by simulating a failure
749
         * if it looks like a directory but really isn't
750
         *
751
         * Also reset if the stat failed, just for safety.
752
         */
753
0
        if ((rv != APR_SUCCESS) ||
754
0
            (r->finfo.filetype != APR_NOFILE &&
755
0
             (r->finfo.filetype != APR_DIR) &&
756
0
             (r->filename[strlen(r->filename) - 1] == '/'))) {
757
0
             r->finfo.filetype = APR_NOFILE; /* forget what we learned */
758
0
        }
759
0
    }
760
761
0
    if (r->finfo.filetype == APR_REG) {
762
0
        entry_dir = ap_make_dirstr_parent(r->pool, entry_dir);
763
0
    }
764
0
    else if (r->filename[strlen(r->filename) - 1] != '/') {
765
0
        entry_dir = apr_pstrcat(r->pool, r->filename, "/", NULL);
766
0
    }
767
768
    /* If we have a file already matches the path of r->filename,
769
     * and the vhost's list of directory sections hasn't changed,
770
     * we can skip rewalking the directory_walk entries.
771
     */
772
0
    if (cached
773
0
        && ((r->finfo.filetype == APR_REG)
774
0
            || ((r->finfo.filetype == APR_DIR)
775
0
                && (!r->path_info || !*r->path_info)))
776
0
        && (cache->dir_conf_tested == sec_ent)
777
0
        && (strcmp(entry_dir, cache->cached) == 0)) {
778
0
        int familiar = 0;
779
780
        /* Well this looks really familiar!  If our end-result (per_dir_result)
781
         * didn't change, we have absolutely nothing to do :)
782
         * Otherwise (as is the case with most dir_merged/file_merged requests)
783
         * we must merge our dir_conf_merged onto this new r->per_dir_config.
784
         */
785
0
        if (r->per_dir_config == cache->per_dir_result) {
786
0
            familiar = 1;
787
0
        }
788
789
0
        if (r->per_dir_config == cache->dir_conf_merged) {
790
0
            r->per_dir_config = cache->per_dir_result;
791
0
            familiar = 1;
792
0
        }
793
794
0
        if (familiar) {
795
0
            apr_finfo_t thisinfo;
796
0
            int res;
797
0
            allow_options_t opts;
798
0
            core_dir_config *this_dir;
799
800
0
            this_dir = ap_get_core_module_config(r->per_dir_config);
801
0
            opts = this_dir->opts;
802
            /*
803
             * If Symlinks are allowed in general we do not need the following
804
             * check.
805
             */
806
0
            if (!(opts & OPT_SYM_LINKS)) {
807
0
                rv = ap_run_dirwalk_stat(&thisinfo, r,
808
0
                                         APR_FINFO_MIN | APR_FINFO_NAME | APR_FINFO_LINK);
809
                /*
810
                 * APR_INCOMPLETE is as fine as result as APR_SUCCESS as we
811
                 * have added APR_FINFO_NAME to the wanted parameter of
812
                 * apr_stat above. On Unix platforms this means that apr_stat
813
                 * is always going to return APR_INCOMPLETE in the case that
814
                 * the call to the native stat / lstat did not fail.
815
                 */
816
0
                if ((rv != APR_INCOMPLETE) && (rv != APR_SUCCESS)) {
817
                    /*
818
                     * This should never happen, because we did a stat on the
819
                     * same file, resolving a possible symlink several lines
820
                     * above. Therefore do not make a detailed analysis of rv
821
                     * in this case for the reason of the failure, just bail out
822
                     * with a HTTP_FORBIDDEN in case we hit a race condition
823
                     * here.
824
                     */
825
0
                    ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(00031)
826
0
                                  "access to %s failed; stat of '%s' failed.",
827
0
                                  r->uri, r->filename);
828
0
                    return r->status = HTTP_FORBIDDEN;
829
0
                }
830
0
                if (thisinfo.filetype == APR_LNK) {
831
                    /* Is this a possibly acceptable symlink? */
832
0
                    if ((res = resolve_symlink(r->filename, &thisinfo,
833
0
                                               opts, r->pool)) != OK) {
834
0
                        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00032)
835
0
                                      "Symbolic link not allowed "
836
0
                                      "or link target not accessible: %s",
837
0
                                      r->filename);
838
0
                        return r->status = res;
839
0
                    }
840
0
                }
841
0
            }
842
0
            return OK;
843
0
        }
844
845
0
        if (cache->walked->nelts) {
846
0
            now_merged = ((walk_walked_t*)cache->walked->elts)
847
0
                [cache->walked->nelts - 1].merged;
848
0
        }
849
0
    }
850
0
    else {
851
        /* We start now_merged from NULL since we want to build
852
         * a locations list that can be merged to any vhost.
853
         */
854
0
        int sec_idx;
855
0
        int matches = cache->walked->nelts;
856
0
        int cached_matches = matches;
857
0
        walk_walked_t *last_walk = (walk_walked_t*)cache->walked->elts;
858
0
        core_dir_config *this_dir;
859
0
        core_opts_t opts;
860
0
        apr_finfo_t thisinfo;
861
0
        char *save_path_info;
862
0
        apr_size_t buflen;
863
0
        char *buf;
864
0
        unsigned int seg, startseg;
865
0
        apr_pool_t *rxpool = NULL;
866
867
        /* Invariant: from the first time filename_len is set until
868
         * it goes out of scope, filename_len==strlen(r->filename)
869
         */
870
0
        apr_size_t filename_len;
871
#ifdef CASE_BLIND_FILESYSTEM
872
        apr_size_t canonical_len;
873
#endif
874
875
0
        cached &= auth_internal_per_conf;
876
877
        /*
878
         * We must play our own mini-merge game here, for the few
879
         * running dir_config values we care about within dir_walk.
880
         * We didn't start the merge from r->per_dir_config, so we
881
         * accumulate opts and override as we merge, from the globals.
882
         */
883
0
        this_dir = ap_get_core_module_config(r->per_dir_config);
884
0
        opts.opts = this_dir->opts;
885
0
        opts.add = this_dir->opts_add;
886
0
        opts.remove = this_dir->opts_remove;
887
0
        opts.override = this_dir->override;
888
0
        opts.override_opts = this_dir->override_opts;
889
0
        opts.override_list = this_dir->override_list;
890
891
        /* Set aside path_info to merge back onto path_info later.
892
         * If r->filename is a directory, we must remerge the path_info,
893
         * before we continue!  [Directories cannot, by definition, have
894
         * path info.  Either the next segment is not-found, or a file.]
895
         *
896
         * r->path_info tracks the unconsumed source path.
897
         * r->filename  tracks the path as we process it
898
         */
899
0
        if ((r->finfo.filetype == APR_DIR) && r->path_info && *r->path_info)
900
0
        {
901
0
            if ((rv = apr_filepath_merge(&r->path_info, r->filename,
902
0
                                         r->path_info,
903
0
                                         APR_FILEPATH_NOTABOVEROOT, r->pool))
904
0
                != APR_SUCCESS) {
905
0
                ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(00033)
906
0
                              "dir_walk error, path_info %s is not relative "
907
0
                              "to the filename path %s for uri %s",
908
0
                              r->path_info, r->filename, r->uri);
909
0
                return HTTP_INTERNAL_SERVER_ERROR;
910
0
            }
911
912
0
            save_path_info = NULL;
913
0
        }
914
0
        else {
915
0
            save_path_info = r->path_info;
916
0
            r->path_info = r->filename;
917
0
        }
918
919
#ifdef CASE_BLIND_FILESYSTEM
920
921
        canonical_len = 0;
922
        while (r->canonical_filename && r->canonical_filename[canonical_len]
923
               && (r->canonical_filename[canonical_len]
924
                   == r->path_info[canonical_len])) {
925
             ++canonical_len;
926
        }
927
928
        while (canonical_len
929
               && ((r->canonical_filename[canonical_len - 1] != '/'
930
                   && r->canonical_filename[canonical_len - 1])
931
                   || (r->path_info[canonical_len - 1] != '/'
932
                       && r->path_info[canonical_len - 1]))) {
933
            --canonical_len;
934
        }
935
936
        /*
937
         * Now build r->filename component by component, starting
938
         * with the root (on Unix, simply "/").  We will make a huge
939
         * assumption here for efficiency, that any canonical path
940
         * already given included a canonical root.
941
         */
942
        rv = apr_filepath_root((const char **)&r->filename,
943
                               (const char **)&r->path_info,
944
                               canonical_len ? 0 : APR_FILEPATH_TRUENAME,
945
                               r->pool);
946
        filename_len = strlen(r->filename);
947
948
        /*
949
         * Bad assumption above?  If the root's length is longer
950
         * than the canonical length, then it cannot be trusted as
951
         * a truename.  So try again, this time more seriously.
952
         */
953
        if ((rv == APR_SUCCESS) && canonical_len
954
            && (filename_len > canonical_len)) {
955
            rv = apr_filepath_root((const char **)&r->filename,
956
                                   (const char **)&r->path_info,
957
                                   APR_FILEPATH_TRUENAME, r->pool);
958
            filename_len = strlen(r->filename);
959
            canonical_len = 0;
960
        }
961
962
#else /* ndef CASE_BLIND_FILESYSTEM, really this simple for Unix today; */
963
964
0
        rv = apr_filepath_root((const char **)&r->filename,
965
0
                               (const char **)&r->path_info,
966
0
                               0, r->pool);
967
0
        filename_len = strlen(r->filename);
968
969
0
#endif
970
971
0
        if (rv != APR_SUCCESS) {
972
0
            ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(00034)
973
0
                          "dir_walk error, could not determine the root "
974
0
                          "path of filename %s%s for uri %s",
975
0
                          r->filename, r->path_info, r->uri);
976
0
            return HTTP_INTERNAL_SERVER_ERROR;
977
0
        }
978
979
        /* Working space for terminating null and an extra / is required.
980
         */
981
0
        buflen = filename_len + strlen(r->path_info) + 2;
982
0
        buf = apr_palloc(r->pool, buflen);
983
0
        memcpy(buf, r->filename, filename_len + 1);
984
0
        r->filename = buf;
985
0
        thisinfo.valid = APR_FINFO_TYPE;
986
0
        thisinfo.filetype = APR_DIR; /* It's the root, of course it's a dir */
987
988
        /*
989
         * seg keeps track of which segment we've copied.
990
         * sec_idx keeps track of which section we're on, since sections are
991
         *     ordered by number of segments. See core_reorder_directories
992
         * startseg tells us how many segments describe the root path
993
         *     e.g. the complete path "//host/foo/" to a UNC share (4)
994
         */
995
0
        startseg = seg = ap_count_dirs(r->filename);
996
0
        sec_idx = 0;
997
998
        /*
999
         * Go down the directory hierarchy.  Where we have to check for
1000
         * symlinks, do so.  Where a .htaccess file has permission to
1001
         * override anything, try to find one.
1002
         */
1003
0
        do {
1004
0
            int res;
1005
0
            char *seg_name;
1006
0
            char *delim;
1007
0
            int temp_slash=0;
1008
1009
            /* We have no trailing slash, but we sure would appreciate one.
1010
             * However, we don't want to append a / our first time through.
1011
             */
1012
0
            if ((seg > startseg) && r->filename[filename_len-1] != '/') {
1013
0
                r->filename[filename_len++] = '/';
1014
0
                r->filename[filename_len] = 0;
1015
0
                temp_slash=1;
1016
0
            }
1017
1018
            /* Begin *this* level by looking for matching <Directory> sections
1019
             * from the server config.
1020
             */
1021
0
            for (; sec_idx < num_sec; ++sec_idx) {
1022
1023
0
                ap_conf_vector_t *entry_config = sec_ent[sec_idx];
1024
0
                core_dir_config *entry_core;
1025
0
                entry_core = ap_get_core_module_config(entry_config);
1026
1027
                /* No more possible matches for this many segments?
1028
                 * We are done when we find relative/regex/longer components.
1029
                 */
1030
0
                if (entry_core->r || entry_core->d_components > seg) {
1031
0
                    break;
1032
0
                }
1033
1034
                /* We will never skip '0' element components, e.g. plain old
1035
                 * <Directory >, and <Directory "/"> are classified as zero
1036
                 * so that Win32/Netware/OS2 etc all pick them up.
1037
                 * Otherwise, skip over the mismatches.
1038
                 */
1039
0
                if (entry_core->d_components
1040
0
                    && ((entry_core->d_components < seg)
1041
0
                     || (entry_core->d_is_fnmatch
1042
0
                         ? (apr_fnmatch(entry_core->d, r->filename,
1043
0
                                        APR_FNM_PATHNAME) != APR_SUCCESS)
1044
0
                         : (strcmp(r->filename, entry_core->d) != 0)))) {
1045
0
                    continue;
1046
0
                }
1047
1048
                /* If we haven't continue'd above, we have a match.
1049
                 *
1050
                 * Calculate our full-context core opts & override.
1051
                 */
1052
0
                core_opts_merge(sec_ent[sec_idx], &opts);
1053
1054
                /* If we merged this same section last time, reuse it
1055
                 */
1056
0
                if (matches) {
1057
0
                    if (last_walk->matched == sec_ent[sec_idx]) {
1058
0
                        now_merged = last_walk->merged;
1059
0
                        ++last_walk;
1060
0
                        --matches;
1061
0
                        continue;
1062
0
                    }
1063
1064
                    /* We fell out of sync.  This is our own copy of walked,
1065
                     * so truncate the remaining matches and reset remaining.
1066
                     */
1067
0
                    cache->walked->nelts -= matches;
1068
0
                    matches = 0;
1069
0
                    cached = 0;
1070
0
                }
1071
1072
0
                if (now_merged) {
1073
0
                    now_merged = ap_merge_per_dir_configs(r->pool,
1074
0
                                                          now_merged,
1075
0
                                                          sec_ent[sec_idx]);
1076
0
                }
1077
0
                else {
1078
0
                    now_merged = sec_ent[sec_idx];
1079
0
                }
1080
1081
0
                last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1082
0
                last_walk->matched = sec_ent[sec_idx];
1083
0
                last_walk->merged = now_merged;
1084
0
            }
1085
1086
            /* If .htaccess files are enabled, check for one, provided we
1087
             * have reached a real path.
1088
             */
1089
0
            do {  /* Not really a loop, just a break'able code block */
1090
1091
0
                ap_conf_vector_t *htaccess_conf = NULL;
1092
1093
                /* No htaccess in an incomplete root path,
1094
                 * nor if it's disabled
1095
                 */
1096
0
                if (seg < startseg || (!opts.override 
1097
0
                    && apr_is_empty_table(opts.override_list)
1098
0
                    )) {
1099
0
                    break;
1100
0
                }
1101
1102
1103
0
                res = ap_parse_htaccess(&htaccess_conf, r, opts.override,
1104
0
                                        opts.override_opts, opts.override_list,
1105
0
                                        r->filename, sconf->access_name);
1106
0
                if (res) {
1107
0
                    return res;
1108
0
                }
1109
1110
0
                if (!htaccess_conf) {
1111
0
                    break;
1112
0
                }
1113
1114
                /* If we are still here, we found our htaccess.
1115
                 *
1116
                 * Calculate our full-context core opts & override.
1117
                 */
1118
0
                core_opts_merge(htaccess_conf, &opts);
1119
1120
                /* If we merged this same htaccess last time, reuse it...
1121
                 * this wouldn't work except that we cache the htaccess
1122
                 * sections for the lifetime of the request, so we match
1123
                 * the same conf.  Good planning (no, pure luck ;)
1124
                 */
1125
0
                if (matches) {
1126
0
                    if (last_walk->matched == htaccess_conf) {
1127
0
                        now_merged = last_walk->merged;
1128
0
                        ++last_walk;
1129
0
                        --matches;
1130
0
                        break;
1131
0
                    }
1132
1133
                    /* We fell out of sync.  This is our own copy of walked,
1134
                     * so truncate the remaining matches and reset
1135
                     * remaining.
1136
                     */
1137
0
                    cache->walked->nelts -= matches;
1138
0
                    matches = 0;
1139
0
                    cached = 0;
1140
0
                }
1141
1142
0
                if (now_merged) {
1143
0
                    now_merged = ap_merge_per_dir_configs(r->pool,
1144
0
                                                          now_merged,
1145
0
                                                          htaccess_conf);
1146
0
                }
1147
0
                else {
1148
0
                    now_merged = htaccess_conf;
1149
0
                }
1150
1151
0
                last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1152
0
                last_walk->matched = htaccess_conf;
1153
0
                last_walk->merged = now_merged;
1154
1155
0
            } while (0); /* Only one htaccess, not a real loop */
1156
1157
            /* That temporary trailing slash was useful, now drop it.
1158
             */
1159
0
            if (temp_slash) {
1160
0
                r->filename[--filename_len] = '\0';
1161
0
            }
1162
1163
            /* Time for all good things to come to an end?
1164
             */
1165
0
            if (!r->path_info || !*r->path_info) {
1166
0
                break;
1167
0
            }
1168
1169
            /* Now it's time for the next segment...
1170
             * We will assume the next element is an end node, and fix it up
1171
             * below as necessary...
1172
             */
1173
1174
0
            seg_name = r->filename + filename_len;
1175
0
            delim = strchr(r->path_info + (*r->path_info == '/' ? 1 : 0), '/');
1176
0
            if (delim) {
1177
0
                apr_size_t path_info_len = delim - r->path_info;
1178
0
                *delim = '\0';
1179
0
                memcpy(seg_name, r->path_info, path_info_len + 1);
1180
0
                filename_len += path_info_len;
1181
0
                r->path_info = delim;
1182
0
                *delim = '/';
1183
0
            }
1184
0
            else {
1185
0
                apr_size_t path_info_len = strlen(r->path_info);
1186
0
                memcpy(seg_name, r->path_info, path_info_len + 1);
1187
0
                filename_len += path_info_len;
1188
0
                r->path_info += path_info_len;
1189
0
            }
1190
0
            if (*seg_name == '/')
1191
0
                ++seg_name;
1192
1193
            /* If nothing remained but a '/' string, we are finished
1194
             * XXX: NO WE ARE NOT!!!  Now process this puppy!!! */
1195
0
            if (!*seg_name) {
1196
0
                break;
1197
0
            }
1198
1199
            /* First optimization;
1200
             * If...we knew r->filename was a file, and
1201
             * if...we have strict (case-sensitive) filenames, or
1202
             *      we know the canonical_filename matches to _this_ name, and
1203
             * if...we have allowed symlinks
1204
             * skip the lstat and dummy up an APR_DIR value for thisinfo.
1205
             */
1206
0
            if (r->finfo.filetype != APR_NOFILE
1207
#ifdef CASE_BLIND_FILESYSTEM
1208
                && (filename_len <= canonical_len)
1209
#endif
1210
0
                && ((opts.opts & (OPT_SYM_OWNER | OPT_SYM_LINKS)) == OPT_SYM_LINKS))
1211
0
            {
1212
1213
0
                thisinfo.filetype = APR_DIR;
1214
0
                ++seg;
1215
0
                continue;
1216
0
            }
1217
1218
            /* We choose apr_stat with flag APR_FINFO_LINK here, rather that
1219
             * plain apr_stat, so that we capture this path object rather than
1220
             * its target.  We will replace the info with our target's info
1221
             * below.  We especially want the name of this 'link' object, not
1222
             * the name of its target, if we are fixing the filename
1223
             * case/resolving aliases.
1224
             */
1225
0
            rv = ap_run_dirwalk_stat(&thisinfo, r,
1226
0
                                     APR_FINFO_MIN | APR_FINFO_NAME | APR_FINFO_LINK);
1227
1228
0
            if (APR_STATUS_IS_ENOENT(rv)) {
1229
                /* Nothing?  That could be nice.  But our directory
1230
                 * walk is done.
1231
                 */
1232
0
                thisinfo.filetype = APR_NOFILE;
1233
0
                break;
1234
0
            }
1235
0
            else if (APR_STATUS_IS_EACCES(rv)) {
1236
0
                ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(00035)
1237
0
                              "access to %s denied (filesystem path '%s') "
1238
0
                              "because search permissions are missing on a "
1239
0
                              "component of the path", r->uri, r->filename);
1240
0
                return r->status = HTTP_FORBIDDEN;
1241
0
            }
1242
0
            else if ((rv != APR_SUCCESS && rv != APR_INCOMPLETE)
1243
0
                     || !(thisinfo.valid & APR_FINFO_TYPE)) {
1244
                /* If we hit ENOTDIR, we must have over-optimized, deny
1245
                 * rather than assume not found.
1246
                 */
1247
0
                ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(00036)
1248
0
                              "access to %s failed (filesystem path '%s')", 
1249
0
                              r->uri, r->filename);
1250
0
                return r->status = HTTP_FORBIDDEN;
1251
0
            }
1252
1253
            /* Fix up the path now if we have a name, and they don't agree
1254
             */
1255
0
            if ((thisinfo.valid & APR_FINFO_NAME)
1256
0
                && strcmp(seg_name, thisinfo.name)) {
1257
                /* TODO: provide users an option that an internal/external
1258
                 * redirect is required here?  We need to walk the URI and
1259
                 * filename in tandem to properly correlate these.
1260
                 */
1261
0
                strcpy(seg_name, thisinfo.name);
1262
0
                filename_len = strlen(r->filename);
1263
0
            }
1264
1265
0
            if (thisinfo.filetype == APR_LNK) {
1266
                /* Is this a possibly acceptable symlink?
1267
                 */
1268
0
                if ((res = resolve_symlink(r->filename, &thisinfo,
1269
0
                                           opts.opts, r->pool)) != OK) {
1270
0
                    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00037)
1271
0
                                  "Symbolic link not allowed "
1272
0
                                  "or link target not accessible: %s",
1273
0
                                  r->filename);
1274
0
                    return r->status = res;
1275
0
                }
1276
0
            }
1277
1278
            /* Ok, we are done with the link's info, test the real target
1279
             */
1280
0
            if (thisinfo.filetype == APR_REG ||
1281
0
                thisinfo.filetype == APR_NOFILE) {
1282
                /* That was fun, nothing left for us here
1283
                 */
1284
0
                break;
1285
0
            }
1286
0
            else if (thisinfo.filetype != APR_DIR) {
1287
0
                ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00038)
1288
0
                              "Forbidden: %s doesn't point to "
1289
0
                              "a file or directory",
1290
0
                              r->filename);
1291
0
                return r->status = HTTP_FORBIDDEN;
1292
0
            }
1293
1294
0
            ++seg;
1295
0
        } while (thisinfo.filetype == APR_DIR);
1296
1297
        /* If we have _not_ optimized, this is the time to recover
1298
         * the final stat result.
1299
         */
1300
0
        if (r->finfo.filetype == APR_NOFILE || r->finfo.filetype == APR_LNK) {
1301
0
            r->finfo = thisinfo;
1302
0
        }
1303
1304
        /* Now splice the saved path_info back onto any new path_info
1305
         */
1306
0
        if (save_path_info) {
1307
0
            if (r->path_info && *r->path_info) {
1308
0
                r->path_info = ap_make_full_path(r->pool, r->path_info,
1309
0
                                                 save_path_info);
1310
0
            }
1311
0
            else {
1312
0
                r->path_info = save_path_info;
1313
0
            }
1314
0
        }
1315
1316
        /*
1317
         * Now we'll deal with the regexes, note we pick up sec_idx
1318
         * where we left off (we gave up after we hit entry_core->r)
1319
         */
1320
0
        for (; sec_idx < num_sec; ++sec_idx) {
1321
1322
0
            int nmatch = 0;
1323
0
            int i;
1324
0
            ap_regmatch_t *pmatch = NULL;
1325
1326
0
            core_dir_config *entry_core;
1327
0
            entry_core = ap_get_core_module_config(sec_ent[sec_idx]);
1328
1329
0
            if (!entry_core->r) {
1330
0
                continue;
1331
0
            }
1332
1333
0
            if (entry_core->refs && entry_core->refs->nelts) {
1334
0
                if (!rxpool) {
1335
0
                    apr_pool_create(&rxpool, r->pool);
1336
0
                    apr_pool_tag(rxpool, "directory_walk_rxpool");
1337
0
                }
1338
0
                nmatch = entry_core->refs->nelts;
1339
0
                pmatch = apr_palloc(rxpool, nmatch*sizeof(ap_regmatch_t));
1340
0
            }
1341
1342
0
            if (ap_regexec(entry_core->r, r->filename, nmatch, pmatch, 0)) {
1343
0
                continue;
1344
0
            }
1345
1346
0
            for (i = 0; i < nmatch; i++) {
1347
0
                if (pmatch[i].rm_so >= 0 && pmatch[i].rm_eo >= 0 &&
1348
0
                    ((const char **)entry_core->refs->elts)[i]) {
1349
0
                    apr_table_setn(r->subprocess_env, 
1350
0
                                   ((const char **)entry_core->refs->elts)[i],
1351
0
                                   apr_pstrndup(r->pool,
1352
0
                                   r->filename + pmatch[i].rm_so,
1353
0
                                   pmatch[i].rm_eo - pmatch[i].rm_so));
1354
0
                }
1355
0
            }
1356
1357
            /* If we haven't already continue'd above, we have a match.
1358
             *
1359
             * Calculate our full-context core opts & override.
1360
             */
1361
0
            core_opts_merge(sec_ent[sec_idx], &opts);
1362
1363
            /* If we merged this same section last time, reuse it
1364
             */
1365
0
            if (matches) {
1366
0
                if (last_walk->matched == sec_ent[sec_idx]) {
1367
0
                    now_merged = last_walk->merged;
1368
0
                    ++last_walk;
1369
0
                    --matches;
1370
0
                    continue;
1371
0
                }
1372
1373
                /* We fell out of sync.  This is our own copy of walked,
1374
                 * so truncate the remaining matches and reset remaining.
1375
                 */
1376
0
                cache->walked->nelts -= matches;
1377
0
                matches = 0;
1378
0
                cached = 0;
1379
0
            }
1380
1381
0
            if (now_merged) {
1382
0
                now_merged = ap_merge_per_dir_configs(r->pool,
1383
0
                                                      now_merged,
1384
0
                                                      sec_ent[sec_idx]);
1385
0
            }
1386
0
            else {
1387
0
                now_merged = sec_ent[sec_idx];
1388
0
            }
1389
1390
0
            last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1391
0
            last_walk->matched = sec_ent[sec_idx];
1392
0
            last_walk->merged = now_merged;
1393
0
        }
1394
1395
0
        if (rxpool) {
1396
0
            apr_pool_destroy(rxpool);
1397
0
        }
1398
1399
        /* Whoops - everything matched in sequence, but either the original
1400
         * walk found some additional matches (which we need to truncate), or
1401
         * this walk found some additional matches.
1402
         */
1403
0
        if (matches) {
1404
0
            cache->walked->nelts -= matches;
1405
0
            cached = 0;
1406
0
        }
1407
0
        else if (cache->walked->nelts > cached_matches) {
1408
0
            cached = 0;
1409
0
        }
1410
0
    }
1411
1412
/* It seems this shouldn't be needed anymore.  We translated the
1413
 x symlink above into a real resource, and should have died up there.
1414
 x Even if we keep this, it needs more thought (maybe an r->file_is_symlink)
1415
 x perhaps it should actually happen in file_walk, so we catch more
1416
 x obscure cases in autoindex subrequests, etc.
1417
 x
1418
 x    * Symlink permissions are determined by the parent.  If the request is
1419
 x    * for a directory then applying the symlink test here would use the
1420
 x    * permissions of the directory as opposed to its parent.  Consider a
1421
 x    * symlink pointing to a dir with a .htaccess disallowing symlinks.  If
1422
 x    * you access /symlink (or /symlink/) you would get a 403 without this
1423
 x    * APR_DIR test.  But if you accessed /symlink/index.html, for example,
1424
 x    * you would *not* get the 403.
1425
 x
1426
 x   if (r->finfo.filetype != APR_DIR
1427
 x       && (res = resolve_symlink(r->filename, r->info, ap_allow_options(r),
1428
 x                                 r->pool))) {
1429
 x       ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(03295)
1430
 x                     "Symbolic link not allowed: %s", r->filename);
1431
 x       return res;
1432
 x   }
1433
 */
1434
1435
    /* Save future sub-requestors much angst in processing
1436
     * this subrequest.  If dir_walk couldn't canonicalize
1437
     * the file path, nothing can.
1438
     */
1439
0
    r->canonical_filename = r->filename;
1440
1441
0
    if (r->finfo.filetype == APR_DIR) {
1442
0
        cache->cached = apr_pstrdup(r->pool, r->filename);
1443
0
    }
1444
0
    else {
1445
0
        cache->cached = ap_make_dirstr_parent(r->pool, r->filename);
1446
0
    }
1447
1448
0
    if (cached
1449
0
        && r->per_dir_config == cache->dir_conf_merged) {
1450
0
        r->per_dir_config = cache->per_dir_result;
1451
0
        return OK;
1452
0
    }
1453
1454
0
    cache->dir_conf_tested = sec_ent;
1455
0
    cache->dir_conf_merged = r->per_dir_config;
1456
1457
    /* Merge our cache->dir_conf_merged construct with the r->per_dir_configs,
1458
     * and note the end result to (potentially) skip this step next time.
1459
     */
1460
0
    if (now_merged) {
1461
0
        r->per_dir_config = ap_merge_per_dir_configs(r->pool,
1462
0
                                                     r->per_dir_config,
1463
0
                                                     now_merged);
1464
0
    }
1465
0
    cache->per_dir_result = r->per_dir_config;
1466
1467
0
    return OK;
1468
0
}
1469
1470
1471
AP_DECLARE(int) ap_location_walk(request_rec *r)
1472
0
{
1473
0
    ap_conf_vector_t *now_merged = NULL;
1474
0
    core_server_config *sconf =
1475
0
        ap_get_core_module_config(r->server->module_config);
1476
0
    ap_conf_vector_t **sec_ent = (ap_conf_vector_t **)sconf->sec_url->elts;
1477
0
    int num_sec = sconf->sec_url->nelts;
1478
0
    walk_cache_t *cache;
1479
0
    const char *entry_uri;
1480
0
    int cached;
1481
1482
    /* No tricks here, there are no <Locations > to parse in this vhost.
1483
     * We won't destroy the cache, just in case _this_ redirect is later
1484
     * redirected again to a vhost with <Location > blocks to optimize.
1485
     */
1486
0
    if (!num_sec) {
1487
0
        return OK;
1488
0
    }
1489
1490
0
    cache = prep_walk_cache(AP_NOTE_LOCATION_WALK, r);
1491
0
    cached = (cache->cached != NULL);
1492
1493
   /*
1494
    * When merge_slashes is set to AP_CORE_CONFIG_OFF the slashes in r->uri
1495
    * have not been merged. But for Location walks we always go with merged
1496
    * slashes no matter what merge_slashes is set to.
1497
    */
1498
0
    if (sconf->merge_slashes != AP_CORE_CONFIG_OFF) {
1499
0
        entry_uri = r->uri;
1500
0
    }
1501
0
    else {
1502
0
        char *uri = apr_pstrdup(r->pool, r->uri);
1503
0
        ap_no2slash(uri);
1504
0
        entry_uri = uri;
1505
0
    }
1506
1507
    /* If we have an cache->cached location that matches r->uri,
1508
     * and the vhost's list of locations hasn't changed, we can skip
1509
     * rewalking the location_walk entries.
1510
     */
1511
0
    if (cached
1512
0
        && (cache->dir_conf_tested == sec_ent)
1513
0
        && (strcmp(entry_uri, cache->cached) == 0)) {
1514
        /* Well this looks really familiar!  If our end-result (per_dir_result)
1515
         * didn't change, we have absolutely nothing to do :)
1516
         * Otherwise (as is the case with most dir_merged/file_merged requests)
1517
         * we must merge our dir_conf_merged onto this new r->per_dir_config.
1518
         */
1519
0
        if (r->per_dir_config == cache->per_dir_result) {
1520
0
            return OK;
1521
0
        }
1522
1523
0
        if (cache->walked->nelts) {
1524
0
            now_merged = ((walk_walked_t*)cache->walked->elts)
1525
0
                                            [cache->walked->nelts - 1].merged;
1526
0
        }
1527
0
    }
1528
0
    else {
1529
        /* We start now_merged from NULL since we want to build
1530
         * a locations list that can be merged to any vhost.
1531
         */
1532
0
        int len, sec_idx;
1533
0
        int matches = cache->walked->nelts;
1534
0
        int cached_matches = matches;
1535
0
        walk_walked_t *last_walk = (walk_walked_t*)cache->walked->elts;
1536
0
        apr_pool_t *rxpool = NULL;
1537
1538
0
        cached &= auth_internal_per_conf;
1539
0
        cache->cached = apr_pstrdup(r->pool, entry_uri);
1540
1541
        /* Go through the location entries, and check for matches.
1542
         * We apply the directive sections in given order, we should
1543
         * really try them with the most general first.
1544
         */
1545
0
        for (sec_idx = 0; sec_idx < num_sec; ++sec_idx) {
1546
1547
0
            core_dir_config *entry_core;
1548
0
            entry_core = ap_get_core_module_config(sec_ent[sec_idx]);
1549
1550
            /* ### const strlen can be optimized in location config parsing */
1551
0
            len = strlen(entry_core->d);
1552
1553
            /* Test the regex, fnmatch or string as appropriate.
1554
             * If it's a strcmp, and the <Location > pattern was
1555
             * not slash terminated, then this uri must be slash
1556
             * terminated (or at the end of the string) to match.
1557
             */
1558
0
            if (entry_core->r) {
1559
1560
0
                int nmatch = 0;
1561
0
                int i;
1562
0
                ap_regmatch_t *pmatch = NULL;
1563
1564
0
                if (entry_core->refs && entry_core->refs->nelts) {
1565
0
                    if (!rxpool) {
1566
0
                        apr_pool_create(&rxpool, r->pool);
1567
0
                        apr_pool_tag(rxpool, "location_walk_rxpool");
1568
0
                    }
1569
0
                    nmatch = entry_core->refs->nelts;
1570
0
                    pmatch = apr_palloc(rxpool, nmatch*sizeof(ap_regmatch_t));
1571
0
                }
1572
1573
0
                if (ap_regexec(entry_core->r, r->uri, nmatch, pmatch, 0)) {
1574
0
                    continue;
1575
0
                }
1576
1577
0
                for (i = 0; i < nmatch; i++) {
1578
0
                    if (pmatch[i].rm_so >= 0 && pmatch[i].rm_eo >= 0 && 
1579
0
                        ((const char **)entry_core->refs->elts)[i]) {
1580
0
                        apr_table_setn(r->subprocess_env,
1581
0
                                       ((const char **)entry_core->refs->elts)[i],
1582
0
                                       apr_pstrndup(r->pool,
1583
0
                                       r->uri + pmatch[i].rm_so,
1584
0
                                       pmatch[i].rm_eo - pmatch[i].rm_so));
1585
0
                    }
1586
0
                }
1587
1588
0
            }
1589
0
            else {
1590
1591
0
                if ((entry_core->d_is_fnmatch
1592
0
                   ? apr_fnmatch(entry_core->d, cache->cached, APR_FNM_PATHNAME)
1593
0
                   : (strncmp(entry_core->d, cache->cached, len)
1594
0
                      || (len > 0
1595
0
                          && entry_core->d[len - 1] != '/'
1596
0
                          && cache->cached[len] != '/'
1597
0
                          && cache->cached[len] != '\0')))) {
1598
0
                    continue;
1599
0
                }
1600
1601
0
            }
1602
1603
            /* If we merged this same section last time, reuse it
1604
             */
1605
0
            if (matches) {
1606
0
                if (last_walk->matched == sec_ent[sec_idx]) {
1607
0
                    now_merged = last_walk->merged;
1608
0
                    ++last_walk;
1609
0
                    --matches;
1610
0
                    continue;
1611
0
                }
1612
1613
                /* We fell out of sync.  This is our own copy of walked,
1614
                 * so truncate the remaining matches and reset remaining.
1615
                 */
1616
0
                cache->walked->nelts -= matches;
1617
0
                matches = 0;
1618
0
                cached = 0;
1619
0
            }
1620
1621
0
            if (now_merged) {
1622
0
                now_merged = ap_merge_per_dir_configs(r->pool,
1623
0
                                                      now_merged,
1624
0
                                                      sec_ent[sec_idx]);
1625
0
            }
1626
0
            else {
1627
0
                now_merged = sec_ent[sec_idx];
1628
0
            }
1629
1630
0
            last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1631
0
            last_walk->matched = sec_ent[sec_idx];
1632
0
            last_walk->merged = now_merged;
1633
0
        }
1634
1635
0
        if (rxpool) {
1636
0
            apr_pool_destroy(rxpool);
1637
0
        }
1638
1639
        /* Whoops - everything matched in sequence, but either the original
1640
         * walk found some additional matches (which we need to truncate), or
1641
         * this walk found some additional matches.
1642
         */
1643
0
        if (matches) {
1644
0
            cache->walked->nelts -= matches;
1645
0
            cached = 0;
1646
0
        }
1647
0
        else if (cache->walked->nelts > cached_matches) {
1648
0
            cached = 0;
1649
0
        }
1650
0
    }
1651
1652
0
    if (cached
1653
0
        && r->per_dir_config == cache->dir_conf_merged) {
1654
0
        r->per_dir_config = cache->per_dir_result;
1655
0
        return OK;
1656
0
    }
1657
1658
0
    cache->dir_conf_tested = sec_ent;
1659
0
    cache->dir_conf_merged = r->per_dir_config;
1660
1661
    /* Merge our cache->dir_conf_merged construct with the r->per_dir_configs,
1662
     * and note the end result to (potentially) skip this step next time.
1663
     */
1664
0
    if (now_merged) {
1665
0
        r->per_dir_config = ap_merge_per_dir_configs(r->pool,
1666
0
                                                     r->per_dir_config,
1667
0
                                                     now_merged);
1668
0
    }
1669
0
    cache->per_dir_result = r->per_dir_config;
1670
1671
0
    return OK;
1672
0
}
1673
1674
AP_DECLARE(int) ap_file_walk(request_rec *r)
1675
0
{
1676
0
    ap_conf_vector_t *now_merged = NULL;
1677
0
    core_dir_config *dconf = ap_get_core_module_config(r->per_dir_config);
1678
0
    ap_conf_vector_t **sec_ent = NULL;
1679
0
    int num_sec = 0;
1680
0
    walk_cache_t *cache;
1681
0
    const char *test_file;
1682
0
    int cached;
1683
1684
0
    if (dconf->sec_file) {
1685
0
        sec_ent = (ap_conf_vector_t **)dconf->sec_file->elts;
1686
0
        num_sec = dconf->sec_file->nelts;
1687
0
    }
1688
1689
    /* To allow broken modules to proceed, we allow missing filenames to pass.
1690
     * We will catch it later if it's heading for the core handler.
1691
     * directory_walk already posted an INFO note for module debugging.
1692
     */
1693
0
    if (r->filename == NULL) {
1694
0
        return OK;
1695
0
    }
1696
1697
    /* No tricks here, there are just no <Files > to parse in this context.
1698
     * We won't destroy the cache, just in case _this_ redirect is later
1699
     * redirected again to a context containing the same or similar <Files >.
1700
     */
1701
0
    if (!num_sec) {
1702
0
        return OK;
1703
0
    }
1704
1705
0
    cache = prep_walk_cache(AP_NOTE_FILE_WALK, r);
1706
0
    cached = (cache->cached != NULL);
1707
1708
    /* Get the basename .. and copy for the cache just
1709
     * in case r->filename is munged by another module
1710
     */
1711
0
    test_file = strrchr(r->filename, '/');
1712
0
    if (test_file == NULL) {
1713
0
        test_file = apr_pstrdup(r->pool, r->filename);
1714
0
    }
1715
0
    else {
1716
0
        test_file = apr_pstrdup(r->pool, ++test_file);
1717
0
    }
1718
1719
    /* If we have an cache->cached file name that matches test_file,
1720
     * and the directory's list of file sections hasn't changed, we
1721
     * can skip rewalking the file_walk entries.
1722
     */
1723
0
    if (cached
1724
0
        && (cache->dir_conf_tested == sec_ent)
1725
0
        && (strcmp(test_file, cache->cached) == 0)) {
1726
        /* Well this looks really familiar!  If our end-result (per_dir_result)
1727
         * didn't change, we have absolutely nothing to do :)
1728
         * Otherwise (as is the case with most dir_merged requests)
1729
         * we must merge our dir_conf_merged onto this new r->per_dir_config.
1730
         */
1731
0
        if (r->per_dir_config == cache->per_dir_result) {
1732
0
            return OK;
1733
0
        }
1734
1735
0
        if (cache->walked->nelts) {
1736
0
            now_merged = ((walk_walked_t*)cache->walked->elts)
1737
0
                [cache->walked->nelts - 1].merged;
1738
0
        }
1739
0
    }
1740
0
    else {
1741
        /* We start now_merged from NULL since we want to build
1742
         * a file section list that can be merged to any dir_walk.
1743
         */
1744
0
        int sec_idx;
1745
0
        int matches = cache->walked->nelts;
1746
0
        int cached_matches = matches;
1747
0
        walk_walked_t *last_walk = (walk_walked_t*)cache->walked->elts;
1748
0
        apr_pool_t *rxpool = NULL;
1749
1750
0
        cached &= auth_internal_per_conf;
1751
0
        cache->cached = test_file;
1752
1753
        /* Go through the location entries, and check for matches.
1754
         * We apply the directive sections in given order, we should
1755
         * really try them with the most general first.
1756
         */
1757
0
        for (sec_idx = 0; sec_idx < num_sec; ++sec_idx) {
1758
0
            core_dir_config *entry_core;
1759
0
            entry_core = ap_get_core_module_config(sec_ent[sec_idx]);
1760
1761
0
            if (entry_core->r) {
1762
1763
0
                int nmatch = 0;
1764
0
                int i;
1765
0
                ap_regmatch_t *pmatch = NULL;
1766
1767
0
                if (entry_core->refs && entry_core->refs->nelts) {
1768
0
                    if (!rxpool) {
1769
0
                        apr_pool_create(&rxpool, r->pool);
1770
0
                        apr_pool_tag(rxpool, "file_walk_rxpool");
1771
0
                    }
1772
0
                    nmatch = entry_core->refs->nelts;
1773
0
                    pmatch = apr_palloc(rxpool, nmatch*sizeof(ap_regmatch_t));
1774
0
                }
1775
1776
0
                if (ap_regexec(entry_core->r, cache->cached, nmatch, pmatch, 0)) {
1777
0
                    continue;
1778
0
                }
1779
1780
0
                for (i = 0; i < nmatch; i++) {
1781
0
                    if (pmatch[i].rm_so >= 0 && pmatch[i].rm_eo >= 0 && 
1782
0
                        ((const char **)entry_core->refs->elts)[i]) {
1783
0
                        apr_table_setn(r->subprocess_env,
1784
0
                                       ((const char **)entry_core->refs->elts)[i],
1785
0
                                       apr_pstrndup(r->pool,
1786
0
                                       cache->cached + pmatch[i].rm_so,
1787
0
                                       pmatch[i].rm_eo - pmatch[i].rm_so));
1788
0
                    }
1789
0
                }
1790
1791
0
            }
1792
0
            else {
1793
0
                if ((entry_core->d_is_fnmatch
1794
0
                       ? apr_fnmatch(entry_core->d, cache->cached, APR_FNM_PATHNAME)
1795
0
                       : strcmp(entry_core->d, cache->cached))) {
1796
0
                    continue;
1797
0
                }
1798
0
            }
1799
1800
            /* If we merged this same section last time, reuse it
1801
             */
1802
0
            if (matches) {
1803
0
                if (last_walk->matched == sec_ent[sec_idx]) {
1804
0
                    now_merged = last_walk->merged;
1805
0
                    ++last_walk;
1806
0
                    --matches;
1807
0
                    continue;
1808
0
                }
1809
1810
                /* We fell out of sync.  This is our own copy of walked,
1811
                 * so truncate the remaining matches and reset remaining.
1812
                 */
1813
0
                cache->walked->nelts -= matches;
1814
0
                matches = 0;
1815
0
                cached = 0;
1816
0
            }
1817
1818
0
            if (now_merged) {
1819
0
                now_merged = ap_merge_per_dir_configs(r->pool,
1820
0
                                                      now_merged,
1821
0
                                                      sec_ent[sec_idx]);
1822
0
            }
1823
0
            else {
1824
0
                now_merged = sec_ent[sec_idx];
1825
0
            }
1826
1827
0
            last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1828
0
            last_walk->matched = sec_ent[sec_idx];
1829
0
            last_walk->merged = now_merged;
1830
0
        }
1831
1832
0
        if (rxpool) {
1833
0
            apr_pool_destroy(rxpool);
1834
0
        }
1835
1836
        /* Whoops - everything matched in sequence, but either the original
1837
         * walk found some additional matches (which we need to truncate), or
1838
         * this walk found some additional matches.
1839
         */
1840
0
        if (matches) {
1841
0
            cache->walked->nelts -= matches;
1842
0
            cached = 0;
1843
0
        }
1844
0
        else if (cache->walked->nelts > cached_matches) {
1845
0
            cached = 0;
1846
0
        }
1847
0
    }
1848
1849
0
    if (cached
1850
0
        && r->per_dir_config == cache->dir_conf_merged) {
1851
0
        r->per_dir_config = cache->per_dir_result;
1852
0
        return OK;
1853
0
    }
1854
1855
0
    cache->dir_conf_tested = sec_ent;
1856
0
    cache->dir_conf_merged = r->per_dir_config;
1857
1858
    /* Merge our cache->dir_conf_merged construct with the r->per_dir_configs,
1859
     * and note the end result to (potentially) skip this step next time.
1860
     */
1861
0
    if (now_merged) {
1862
0
        r->per_dir_config = ap_merge_per_dir_configs(r->pool,
1863
0
                                                     r->per_dir_config,
1864
0
                                                     now_merged);
1865
0
    }
1866
0
    cache->per_dir_result = r->per_dir_config;
1867
1868
0
    return OK;
1869
0
}
1870
1871
static int ap_if_walk_sub(request_rec *r, core_dir_config* dconf)
1872
0
{
1873
0
    ap_conf_vector_t *now_merged = NULL;
1874
0
    ap_conf_vector_t **sec_ent = NULL;
1875
0
    int num_sec = 0;
1876
0
    walk_cache_t *cache;
1877
0
    int cached;
1878
0
    int sec_idx;
1879
0
    int matches;
1880
0
    int cached_matches;
1881
0
    int prev_result = -1;
1882
0
    walk_walked_t *last_walk;
1883
1884
0
    if (dconf && dconf->sec_if) {
1885
0
        sec_ent = (ap_conf_vector_t **)dconf->sec_if->elts;
1886
0
        num_sec = dconf->sec_if->nelts;
1887
0
    }
1888
1889
    /* No tricks here, there are just no <If > to parse in this context.
1890
     * We won't destroy the cache, just in case _this_ redirect is later
1891
     * redirected again to a context containing the same or similar <If >.
1892
     */
1893
0
    if (!num_sec) {
1894
0
        return OK;
1895
0
    }
1896
1897
0
    cache = prep_walk_cache(AP_NOTE_IF_WALK, r);
1898
0
    cached = (cache->cached != NULL);
1899
0
    cache->cached = (void *)1;
1900
0
    matches = cache->walked->nelts;
1901
0
    cached_matches = matches;
1902
0
    last_walk = (walk_walked_t*)cache->walked->elts;
1903
1904
0
    cached &= auth_internal_per_conf;
1905
1906
    /* Go through the if entries, and check for matches  */
1907
0
    for (sec_idx = 0; sec_idx < num_sec; ++sec_idx) {
1908
0
        const char *err = NULL;
1909
0
        core_dir_config *entry_core;
1910
0
        int rc;
1911
0
        entry_core = ap_get_core_module_config(sec_ent[sec_idx]);
1912
1913
0
        AP_DEBUG_ASSERT(entry_core->condition_ifelse != 0);
1914
0
        if (entry_core->condition_ifelse & AP_CONDITION_ELSE) {
1915
0
            AP_DEBUG_ASSERT(prev_result != -1);
1916
0
            if (prev_result == 1)
1917
0
                continue;
1918
0
        }
1919
1920
0
        if (entry_core->condition_ifelse & AP_CONDITION_IF) {
1921
0
            rc = ap_expr_exec(r, entry_core->condition, &err);
1922
0
            if (rc <= 0) {
1923
0
                if (rc < 0)
1924
0
                    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00039)
1925
0
                                  "Failed to evaluate <If > condition: %s",
1926
0
                                  err);
1927
0
                prev_result = 0;
1928
0
                continue;
1929
0
            }
1930
0
            prev_result = 1;
1931
0
        }
1932
0
        else {
1933
0
            prev_result = -1;
1934
0
        }
1935
1936
        /* If we merged this same section last time, reuse it
1937
         */
1938
0
        if (matches) {
1939
0
            if (last_walk->matched == sec_ent[sec_idx]) {
1940
0
                now_merged = last_walk->merged;
1941
0
                ++last_walk;
1942
0
                --matches;
1943
0
                continue;
1944
0
            }
1945
1946
            /* We fell out of sync.  This is our own copy of walked,
1947
             * so truncate the remaining matches and reset remaining.
1948
             */
1949
0
            cache->walked->nelts -= matches;
1950
0
            matches = 0;
1951
0
            cached = 0;
1952
0
        }
1953
1954
0
        if (now_merged) {
1955
0
            now_merged = ap_merge_per_dir_configs(r->pool,
1956
0
                                                  now_merged,
1957
0
                                                  sec_ent[sec_idx]);
1958
0
        }
1959
0
        else {
1960
0
            now_merged = sec_ent[sec_idx];
1961
0
        }
1962
1963
0
        last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1964
0
        last_walk->matched = sec_ent[sec_idx];
1965
0
        last_walk->merged = now_merged;
1966
0
    }
1967
1968
    /* Everything matched in sequence, but it may be that the original
1969
     * walk found some additional matches (which we need to truncate), or
1970
     * this walk found some additional matches.
1971
     */
1972
0
    if (matches) {
1973
0
        cache->walked->nelts -= matches;
1974
0
        cached = 0;
1975
0
    }
1976
0
    else if (cache->walked->nelts > cached_matches) {
1977
0
        cached = 0;
1978
0
    }
1979
1980
0
    if (cached
1981
0
        && r->per_dir_config == cache->dir_conf_merged) {
1982
0
        r->per_dir_config = cache->per_dir_result;
1983
0
        return OK;
1984
0
    }
1985
1986
0
    cache->dir_conf_tested = sec_ent;
1987
0
    cache->dir_conf_merged = r->per_dir_config;
1988
1989
    /* Merge our cache->dir_conf_merged construct with the r->per_dir_configs,
1990
     * and note the end result to (potentially) skip this step next time.
1991
     */
1992
0
    if (now_merged) {
1993
0
        r->per_dir_config = ap_merge_per_dir_configs(r->pool,
1994
0
                                                     r->per_dir_config,
1995
0
                                                     now_merged);
1996
0
    }
1997
0
    cache->per_dir_result = r->per_dir_config;
1998
1999
0
    if (now_merged) {
2000
0
        core_dir_config *dconf_merged = ap_get_core_module_config(now_merged);
2001
2002
        /* Allow nested <If>s and their configs to get merged
2003
         * with the current one.
2004
         */
2005
0
        return ap_if_walk_sub(r, dconf_merged);
2006
0
    }
2007
2008
0
    return OK;
2009
0
}
2010
2011
AP_DECLARE(int) ap_if_walk(request_rec *r)
2012
0
{
2013
0
    core_dir_config *dconf = ap_get_core_module_config(r->per_dir_config);
2014
0
    int status = ap_if_walk_sub(r, dconf);
2015
0
    return status;
2016
0
}
2017
2018
/*****************************************************************
2019
 *
2020
 * The sub_request mechanism.
2021
 *
2022
 * Fns to look up a relative URI from, e.g., a map file or SSI document.
2023
 * These do all access checks, etc., but don't actually run the transaction
2024
 * ... use run_sub_req below for that.  Also, be sure to use destroy_sub_req
2025
 * as appropriate if you're likely to be creating more than a few of these.
2026
 * (An early Apache version didn't destroy the sub_reqs used in directory
2027
 * indexing.  The result, when indexing a directory with 800-odd files in
2028
 * it, was massively excessive storage allocation).
2029
 *
2030
 * Note more manipulation of protocol-specific vars in the request
2031
 * structure...
2032
 */
2033
2034
static request_rec *make_sub_request(const request_rec *r,
2035
                                     ap_filter_t *next_filter)
2036
0
{
2037
0
    apr_pool_t *rrp;
2038
0
    request_rec *rnew;
2039
2040
0
    apr_pool_create(&rrp, r->pool);
2041
0
    apr_pool_tag(rrp, "subrequest");
2042
0
    rnew = apr_pcalloc(rrp, sizeof(request_rec));
2043
0
    rnew->pool = rrp;
2044
2045
0
    rnew->hostname       = r->hostname;
2046
0
    rnew->request_time   = r->request_time;
2047
0
    rnew->connection     = r->connection;
2048
0
    rnew->server         = r->server;
2049
0
    rnew->log            = r->log;
2050
2051
0
    rnew->request_config = ap_create_request_config(rnew->pool);
2052
2053
    /* Start a clean config from this subrequest's vhost.  Optimization in
2054
     * Location/File/Dir walks from the parent request assure that if the
2055
     * config blocks of the subrequest match the parent request, no merges
2056
     * will actually occur (and generally a minimal number of merges are
2057
     * required, even if the parent and subrequest aren't quite identical.)
2058
     */
2059
0
    rnew->per_dir_config = r->server->lookup_defaults;
2060
2061
0
    rnew->htaccess = r->htaccess;
2062
0
    rnew->allowed_methods = ap_make_method_list(rnew->pool, 2);
2063
2064
    /* make a copy of the allowed-methods list */
2065
0
    ap_copy_method_list(rnew->allowed_methods, r->allowed_methods);
2066
2067
    /* start with the same set of output filters */
2068
0
    if (next_filter) {
2069
0
        ap_filter_t *scan = next_filter;
2070
2071
        /* while there are no input filters for a subrequest, we will
2072
         * try to insert some, so if we don't have valid data, the code
2073
         * will seg fault.
2074
         */
2075
0
        rnew->input_filters = r->input_filters;
2076
0
        rnew->proto_input_filters = r->proto_input_filters;
2077
0
        rnew->output_filters = next_filter;
2078
0
        rnew->proto_output_filters = r->proto_output_filters;
2079
0
        while (scan && (scan != r->proto_output_filters)) {
2080
0
            if (scan->frec == ap_subreq_core_filter_handle) {
2081
0
                break;
2082
0
            }
2083
0
            scan = scan->next;
2084
0
        }
2085
0
        if (!scan || scan == r->proto_output_filters) {
2086
0
            ap_add_output_filter_handle(ap_subreq_core_filter_handle,
2087
0
                    NULL, rnew, rnew->connection);
2088
0
        }
2089
0
    }
2090
0
    else {
2091
        /* If NULL - we are expecting to be internal_fast_redirect'ed
2092
         * to this subrequest - or this request will never be invoked.
2093
         * Ignore the original request filter stack entirely, and
2094
         * drill the input and output stacks back to the connection.
2095
         */
2096
0
        rnew->proto_input_filters = r->proto_input_filters;
2097
0
        rnew->proto_output_filters = r->proto_output_filters;
2098
2099
0
        rnew->input_filters = r->proto_input_filters;
2100
0
        rnew->output_filters = r->proto_output_filters;
2101
0
    }
2102
2103
0
    rnew->useragent_addr = r->useragent_addr;
2104
0
    rnew->useragent_ip = r->useragent_ip;
2105
2106
    /* no input filters for a subrequest */
2107
2108
0
    ap_set_sub_req_protocol(rnew, r);
2109
2110
    /* We have to run this after we fill in sub req vars,
2111
     * or the r->main pointer won't be setup
2112
     */
2113
0
    ap_run_create_request(rnew);
2114
2115
    /* Begin by presuming any module can make its own path_info assumptions,
2116
     * until some module interjects and changes the value.
2117
     */
2118
0
    rnew->used_path_info = AP_REQ_DEFAULT_PATH_INFO;
2119
2120
    /* Pass on the kept body (if any) into the new request. */
2121
0
    rnew->kept_body = r->kept_body;
2122
2123
0
    return rnew;
2124
0
}
2125
2126
AP_CORE_DECLARE_NONSTD(apr_status_t) ap_sub_req_output_filter(ap_filter_t *f,
2127
                                                              apr_bucket_brigade *bb)
2128
0
{
2129
0
    apr_bucket *e = APR_BRIGADE_LAST(bb);
2130
2131
0
    if (APR_BUCKET_IS_EOS(e)) {
2132
0
        apr_bucket_delete(e);
2133
0
    }
2134
2135
0
    if (!APR_BRIGADE_EMPTY(bb)) {
2136
0
        return ap_pass_brigade(f->next, bb);
2137
0
    }
2138
2139
0
    return APR_SUCCESS;
2140
0
}
2141
2142
extern APR_OPTIONAL_FN_TYPE(authz_some_auth_required) *ap__authz_ap_some_auth_required;
2143
2144
AP_DECLARE(int) ap_some_auth_required(request_rec *r)
2145
0
{
2146
    /* Is there a require line configured for the type of *this* req? */
2147
0
    if (ap__authz_ap_some_auth_required) {
2148
0
        return ap__authz_ap_some_auth_required(r);
2149
0
    }
2150
0
    else
2151
0
        return 0;
2152
0
}
2153
2154
AP_DECLARE(void) ap_clear_auth_internal(void)
2155
0
{
2156
0
    auth_internal_per_conf_hooks = 0;
2157
0
    auth_internal_per_conf_providers = 0;
2158
0
}
2159
2160
AP_DECLARE(void) ap_setup_auth_internal(apr_pool_t *ptemp)
2161
0
{
2162
0
    int total_auth_hooks = 0;
2163
0
    int total_auth_providers = 0;
2164
2165
0
    auth_internal_per_conf = 0;
2166
2167
0
    if (_hooks.link_access_checker) {
2168
0
        total_auth_hooks += _hooks.link_access_checker->nelts;
2169
0
    }
2170
0
    if (_hooks.link_access_checker_ex) {
2171
0
        total_auth_hooks += _hooks.link_access_checker_ex->nelts;
2172
0
    }
2173
0
    if (_hooks.link_check_user_id) {
2174
0
        total_auth_hooks += _hooks.link_check_user_id->nelts;
2175
0
    }
2176
0
    if (_hooks.link_auth_checker) {
2177
0
        total_auth_hooks += _hooks.link_auth_checker->nelts;
2178
0
    }
2179
2180
0
    if (total_auth_hooks > auth_internal_per_conf_hooks) {
2181
0
        return;
2182
0
    }
2183
2184
0
    total_auth_providers +=
2185
0
        ap_list_provider_names(ptemp, AUTHN_PROVIDER_GROUP,
2186
0
                               AUTHN_PROVIDER_VERSION)->nelts;
2187
0
    total_auth_providers +=
2188
0
        ap_list_provider_names(ptemp, AUTHZ_PROVIDER_GROUP,
2189
0
                               AUTHZ_PROVIDER_VERSION)->nelts;
2190
2191
0
    if (total_auth_providers > auth_internal_per_conf_providers) {
2192
0
        return;
2193
0
    }
2194
2195
0
    auth_internal_per_conf = 1;
2196
0
}
2197
2198
AP_DECLARE(apr_status_t) ap_register_auth_provider(apr_pool_t *pool,
2199
                                                   const char *provider_group,
2200
                                                   const char *provider_name,
2201
                                                   const char *provider_version,
2202
                                                   const void *provider,
2203
                                                   int type)
2204
0
{
2205
0
    if ((type & AP_AUTH_INTERNAL_MASK) == AP_AUTH_INTERNAL_PER_CONF) {
2206
0
        ++auth_internal_per_conf_providers;
2207
0
    }
2208
2209
0
    return ap_register_provider(pool, provider_group, provider_name,
2210
0
                                provider_version, provider);
2211
0
}
2212
2213
AP_DECLARE(void) ap_hook_check_access(ap_HOOK_access_checker_t *pf,
2214
                                      const char * const *aszPre,
2215
                                      const char * const *aszSucc,
2216
                                      int nOrder, int type)
2217
0
{
2218
0
    if ((type & AP_AUTH_INTERNAL_MASK) == AP_AUTH_INTERNAL_PER_CONF) {
2219
0
        ++auth_internal_per_conf_hooks;
2220
0
    }
2221
2222
0
    ap_hook_access_checker(pf, aszPre, aszSucc, nOrder);
2223
0
}
2224
2225
AP_DECLARE(void) ap_hook_check_access_ex(ap_HOOK_access_checker_ex_t *pf,
2226
                                      const char * const *aszPre,
2227
                                      const char * const *aszSucc,
2228
                                      int nOrder, int type)
2229
0
{
2230
0
    if ((type & AP_AUTH_INTERNAL_MASK) == AP_AUTH_INTERNAL_PER_CONF) {
2231
0
        ++auth_internal_per_conf_hooks;
2232
0
    }
2233
2234
0
    ap_hook_access_checker_ex(pf, aszPre, aszSucc, nOrder);
2235
0
}
2236
2237
AP_DECLARE(void) ap_hook_check_autht(ap_HOOK_check_user_id_t *pf,
2238
                                     const char * const *aszPre,
2239
                                     const char * const *aszSucc,
2240
                                     int nOrder, int type)
2241
0
{
2242
0
    if ((type & AP_AUTH_INTERNAL_MASK) == AP_AUTH_INTERNAL_PER_CONF) {
2243
0
        ++auth_internal_per_conf_hooks;
2244
0
    }
2245
2246
0
    ap_hook_token_checker(pf, aszPre, aszSucc, nOrder);
2247
0
}
2248
2249
AP_DECLARE(void) ap_hook_check_authn(ap_HOOK_check_user_id_t *pf,
2250
                                     const char * const *aszPre,
2251
                                     const char * const *aszSucc,
2252
                                     int nOrder, int type)
2253
0
{
2254
0
    if ((type & AP_AUTH_INTERNAL_MASK) == AP_AUTH_INTERNAL_PER_CONF) {
2255
0
        ++auth_internal_per_conf_hooks;
2256
0
    }
2257
2258
0
    ap_hook_check_user_id(pf, aszPre, aszSucc, nOrder);
2259
0
}
2260
2261
AP_DECLARE(void) ap_hook_check_authz(ap_HOOK_auth_checker_t *pf,
2262
                                     const char * const *aszPre,
2263
                                     const char * const *aszSucc,
2264
                                     int nOrder, int type)
2265
0
{
2266
0
    if ((type & AP_AUTH_INTERNAL_MASK) == AP_AUTH_INTERNAL_PER_CONF) {
2267
0
        ++auth_internal_per_conf_hooks;
2268
0
    }
2269
2270
0
    ap_hook_auth_checker(pf, aszPre, aszSucc, nOrder);
2271
0
}
2272
2273
AP_DECLARE(request_rec *) ap_sub_req_method_uri(const char *method,
2274
                                                const char *new_uri,
2275
                                                const request_rec *r,
2276
                                                ap_filter_t *next_filter)
2277
0
{
2278
0
    request_rec *rnew;
2279
0
    int res = DECLINED;
2280
0
    char *udir;
2281
2282
0
    rnew = make_sub_request(r, next_filter);
2283
2284
    /* would be nicer to pass "method" to ap_set_sub_req_protocol */
2285
0
    rnew->method = method;
2286
0
    rnew->method_number = ap_method_number_of(method);
2287
2288
0
    if (new_uri[0] == '/') {
2289
0
        ap_parse_uri(rnew, new_uri);
2290
0
    }
2291
0
    else {
2292
0
        udir = ap_make_dirstr_parent(rnew->pool, r->uri);
2293
0
        udir = ap_escape_uri(rnew->pool, udir);    /* re-escape it */
2294
0
        ap_parse_uri(rnew, ap_make_full_path(rnew->pool, udir, new_uri));
2295
0
    }
2296
0
    if (ap_is_HTTP_ERROR(rnew->status)) {
2297
0
        return rnew;
2298
0
    }
2299
2300
    /* We cannot return NULL without violating the API. So just turn this
2301
     * subrequest into a 500 to indicate the failure. */
2302
0
    if (ap_is_recursion_limit_exceeded(r)) {
2303
0
        rnew->status = HTTP_INTERNAL_SERVER_ERROR;
2304
0
        return rnew;
2305
0
    }
2306
2307
    /* lookup_uri
2308
     * If the content can be served by the quick_handler, we can
2309
     * safely bypass request_internal processing.
2310
     *
2311
     * If next_filter is NULL we are expecting to be
2312
     * internal_fast_redirect'ed to the subrequest, or the subrequest will
2313
     * never be invoked. We need to make sure that the quickhandler is not
2314
     * invoked by any lookups. Since an internal_fast_redirect will always
2315
     * occur too late for the quickhandler to handle the request.
2316
     */
2317
0
    if (next_filter) {
2318
0
        res = ap_run_quick_handler(rnew, 1);
2319
0
    }
2320
0
    if (res == DECLINED) {
2321
0
        res = ap_process_request_internal(rnew);
2322
0
    }
2323
0
    if (res) {
2324
0
        rnew->status = res;
2325
0
    }
2326
2327
0
    return rnew;
2328
0
}
2329
2330
AP_DECLARE(request_rec *) ap_sub_req_lookup_uri(const char *new_uri,
2331
                                                const request_rec *r,
2332
                                                ap_filter_t *next_filter)
2333
0
{
2334
0
    return ap_sub_req_method_uri("GET", new_uri, r, next_filter);
2335
0
}
2336
2337
AP_DECLARE(request_rec *) ap_sub_req_lookup_dirent(const apr_finfo_t *dirent,
2338
                                                   const request_rec *r,
2339
                                                   int subtype,
2340
                                                   ap_filter_t *next_filter)
2341
0
{
2342
0
    request_rec *rnew;
2343
0
    int res;
2344
0
    char *fdir;
2345
0
    char *udir;
2346
2347
0
    rnew = make_sub_request(r, next_filter);
2348
2349
    /* Special case: we are looking at a relative lookup in the same directory.
2350
     * This is 100% safe, since dirent->name just came from the filesystem.
2351
     */
2352
0
    if (r->path_info && *r->path_info) {
2353
        /* strip path_info off the end of the uri to keep it in sync
2354
         * with r->filename, which has already been stripped by directory_walk,
2355
         * merge the dirent->name, and then, if the caller wants us to remerge
2356
         * the original path info, do so.  Note we never fix the path_info back
2357
         * to r->filename, since dir_walk would do so (but we don't expect it
2358
         * to happen in the usual cases)
2359
         */
2360
0
        udir = apr_pstrdup(rnew->pool, r->uri);
2361
0
        udir[ap_find_path_info(udir, r->path_info)] = '\0';
2362
0
        udir = ap_make_dirstr_parent(rnew->pool, udir);
2363
2364
0
        rnew->uri = ap_make_full_path(rnew->pool, udir, dirent->name);
2365
0
        if (subtype == AP_SUBREQ_MERGE_ARGS) {
2366
0
            rnew->uri = ap_make_full_path(rnew->pool, rnew->uri, r->path_info + 1);
2367
0
            rnew->path_info = apr_pstrdup(rnew->pool, r->path_info);
2368
0
        }
2369
0
        rnew->uri = ap_escape_uri(rnew->pool, rnew->uri);
2370
0
    }
2371
0
    else {
2372
0
        udir = ap_make_dirstr_parent(rnew->pool, r->uri);
2373
0
        rnew->uri = ap_escape_uri(rnew->pool, ap_make_full_path(rnew->pool,
2374
0
                                                                udir,
2375
0
                                                                dirent->name));
2376
0
    }
2377
2378
0
    fdir = ap_make_dirstr_parent(rnew->pool, r->filename);
2379
0
    rnew->filename = ap_make_full_path(rnew->pool, fdir, dirent->name);
2380
0
    if (r->canonical_filename == r->filename) {
2381
0
        rnew->canonical_filename = rnew->filename;
2382
0
    }
2383
2384
    /* XXX This is now less relevant; we will do a full location walk
2385
     * these days for this case.  Preserve the apr_stat results, and
2386
     * perhaps we also tag that symlinks were tested and/or found for
2387
     * r->filename.
2388
     */
2389
0
    rnew->per_dir_config = r->server->lookup_defaults;
2390
2391
0
    if ((dirent->valid & APR_FINFO_MIN) != APR_FINFO_MIN) {
2392
        /*
2393
         * apr_dir_read isn't very complete on this platform, so
2394
         * we need another apr_stat (with or without APR_FINFO_LINK
2395
         * depending on whether we allow all symlinks here.)  If this
2396
         * is an APR_LNK that resolves to an APR_DIR, then we will rerun
2397
         * everything anyways... this should be safe.
2398
         */
2399
0
        apr_status_t rv;
2400
0
        if (ap_allow_options(rnew) & OPT_SYM_LINKS) {
2401
0
            if (((rv = apr_stat(&rnew->finfo, rnew->filename,
2402
0
                                APR_FINFO_MIN, rnew->pool)) != APR_SUCCESS)
2403
0
                && (rv != APR_INCOMPLETE)) {
2404
0
                rnew->finfo.filetype = APR_NOFILE;
2405
0
            }
2406
0
        }
2407
0
        else {
2408
0
            if (((rv = apr_stat(&rnew->finfo, rnew->filename,
2409
0
                                APR_FINFO_LINK | APR_FINFO_MIN,
2410
0
                                rnew->pool)) != APR_SUCCESS)
2411
0
                && (rv != APR_INCOMPLETE)) {
2412
0
                rnew->finfo.filetype = APR_NOFILE;
2413
0
            }
2414
0
        }
2415
0
    }
2416
0
    else {
2417
0
        memcpy(&rnew->finfo, dirent, sizeof(apr_finfo_t));
2418
0
    }
2419
2420
0
    if (rnew->finfo.filetype == APR_LNK) {
2421
        /*
2422
         * Resolve this symlink.  We should tie this back to dir_walk's cache
2423
         */
2424
0
        if ((res = resolve_symlink(rnew->filename, &rnew->finfo,
2425
0
                                   ap_allow_options(rnew), rnew->pool))
2426
0
            != OK) {
2427
0
            rnew->status = res;
2428
0
            return rnew;
2429
0
        }
2430
0
    }
2431
2432
0
    if (rnew->finfo.filetype == APR_DIR) {
2433
        /* ap_make_full_path and ap_escape_uri overallocated the buffers
2434
         * by one character to help us out here.
2435
         */
2436
0
        strcat(rnew->filename, "/");
2437
0
        if (!rnew->path_info || !*rnew->path_info) {
2438
0
            strcat(rnew->uri, "/");
2439
0
        }
2440
0
    }
2441
2442
    /* fill in parsed_uri values
2443
     */
2444
0
    if (r->args && *r->args && (subtype == AP_SUBREQ_MERGE_ARGS)) {
2445
0
        ap_parse_uri(rnew, apr_pstrcat(r->pool, rnew->uri, "?",
2446
0
                                       r->args, NULL));
2447
0
    }
2448
0
    else {
2449
0
        ap_parse_uri(rnew, rnew->uri);
2450
0
    }
2451
2452
    /* We cannot return NULL without violating the API. So just turn this
2453
     * subrequest into a 500. */
2454
0
    if (ap_is_recursion_limit_exceeded(r)) {
2455
0
        rnew->status = HTTP_INTERNAL_SERVER_ERROR;
2456
0
        return rnew;
2457
0
    }
2458
2459
0
    if ((res = ap_process_request_internal(rnew))) {
2460
0
        rnew->status = res;
2461
0
    }
2462
2463
0
    return rnew;
2464
0
}
2465
2466
AP_DECLARE(request_rec *) ap_sub_req_lookup_file(const char *new_file,
2467
                                                 const request_rec *r,
2468
                                                 ap_filter_t *next_filter)
2469
0
{
2470
0
    request_rec *rnew;
2471
0
    int res;
2472
0
    char *fdir;
2473
0
    apr_size_t fdirlen;
2474
2475
0
    rnew = make_sub_request(r, next_filter);
2476
2477
0
    fdir = ap_make_dirstr_parent(rnew->pool, r->filename);
2478
0
    fdirlen = strlen(fdir);
2479
2480
    /* Translate r->filename, if it was canonical, it stays canonical
2481
     */
2482
0
    if (r->canonical_filename == r->filename) {
2483
0
        rnew->canonical_filename = (char*)(1);
2484
0
    }
2485
2486
0
    if (apr_filepath_merge(&rnew->filename, fdir, new_file,
2487
0
                           APR_FILEPATH_TRUENAME, rnew->pool) != APR_SUCCESS) {
2488
0
        rnew->status = HTTP_FORBIDDEN;
2489
0
        return rnew;
2490
0
    }
2491
2492
0
    if (rnew->canonical_filename) {
2493
0
        rnew->canonical_filename = rnew->filename;
2494
0
    }
2495
2496
    /*
2497
     * Check for a special case... if there are no '/' characters in new_file
2498
     * at all, and the path was the same, then we are looking at a relative
2499
     * lookup in the same directory.  Fixup the URI to match.
2500
     */
2501
2502
0
    if (strncmp(rnew->filename, fdir, fdirlen) == 0
2503
0
        && rnew->filename[fdirlen]
2504
0
        && ap_strchr_c(rnew->filename + fdirlen, '/') == NULL) {
2505
0
        apr_status_t rv;
2506
0
        if (ap_allow_options(rnew) & OPT_SYM_LINKS) {
2507
0
            if (((rv = apr_stat(&rnew->finfo, rnew->filename,
2508
0
                                APR_FINFO_MIN, rnew->pool)) != APR_SUCCESS)
2509
0
                && (rv != APR_INCOMPLETE)) {
2510
0
                rnew->finfo.filetype = APR_NOFILE;
2511
0
            }
2512
0
        }
2513
0
        else {
2514
0
            if (((rv = apr_stat(&rnew->finfo, rnew->filename,
2515
0
                                APR_FINFO_LINK | APR_FINFO_MIN,
2516
0
                                rnew->pool)) != APR_SUCCESS)
2517
0
                && (rv != APR_INCOMPLETE)) {
2518
0
                rnew->finfo.filetype = APR_NOFILE;
2519
0
            }
2520
0
        }
2521
2522
0
        if (r->uri && *r->uri) {
2523
0
            char *udir = ap_make_dirstr_parent(rnew->pool, r->uri);
2524
0
            rnew->uri = ap_make_full_path(rnew->pool, udir,
2525
0
                                          rnew->filename + fdirlen);
2526
0
            ap_parse_uri(rnew, rnew->uri);    /* fill in parsed_uri values */
2527
0
        }
2528
0
        else {
2529
0
            ap_parse_uri(rnew, new_file);        /* fill in parsed_uri values */
2530
0
            rnew->uri = apr_pstrdup(rnew->pool, "");
2531
0
        }
2532
0
    }
2533
0
    else {
2534
        /* XXX: @@@: What should be done with the parsed_uri values?
2535
         * We would be better off stripping down to the 'common' elements
2536
         * of the path, then reassembling the URI as best as we can.
2537
         */
2538
0
        ap_parse_uri(rnew, new_file);        /* fill in parsed_uri values */
2539
        /*
2540
         * XXX: this should be set properly like it is in the same-dir case
2541
         * but it's actually sometimes to impossible to do it... because the
2542
         * file may not have a uri associated with it -djg
2543
         */
2544
0
        rnew->uri = apr_pstrdup(rnew->pool, "");
2545
0
    }
2546
2547
    /* We cannot return NULL without violating the API. So just turn this
2548
     * subrequest into a 500. */
2549
0
    if (ap_is_recursion_limit_exceeded(r)) {
2550
0
        rnew->status = HTTP_INTERNAL_SERVER_ERROR;
2551
0
        return rnew;
2552
0
    }
2553
2554
0
    if ((res = ap_process_request_internal(rnew))) {
2555
0
        rnew->status = res;
2556
0
    }
2557
2558
0
    return rnew;
2559
0
}
2560
2561
AP_DECLARE(int) ap_run_sub_req(request_rec *r)
2562
0
{
2563
0
    int retval = DECLINED;
2564
    /* Run the quick handler if the subrequest is not a dirent or file
2565
     * subrequest
2566
     */
2567
0
    if (!(r->filename && r->finfo.filetype != APR_NOFILE)) {
2568
0
        retval = ap_run_quick_handler(r, 0);
2569
0
    }
2570
0
    if (retval == DECLINED) {
2571
0
        retval = ap_invoke_handler(r);
2572
0
    }
2573
0
    if (retval == DONE) {
2574
0
        retval = OK;
2575
0
    }
2576
0
    ap_finalize_sub_req_protocol(r);
2577
0
    return retval;
2578
0
}
2579
2580
AP_DECLARE(void) ap_destroy_sub_req(request_rec *r)
2581
0
{
2582
    /* Reclaim the space */
2583
0
    apr_pool_destroy(r->pool);
2584
0
}
2585
2586
/*
2587
 * Function to set the r->mtime field to the specified value if it's later
2588
 * than what's already there.
2589
 */
2590
AP_DECLARE(void) ap_update_mtime(request_rec *r, apr_time_t dependency_mtime)
2591
0
{
2592
0
    if (r->mtime < dependency_mtime) {
2593
0
        r->mtime = dependency_mtime;
2594
0
    }
2595
0
}
2596
2597
/*
2598
 * Is it the initial main request, which we only get *once* per HTTP request?
2599
 */
2600
AP_DECLARE(int) ap_is_initial_req(request_rec *r)
2601
0
{
2602
0
    return (r->main == NULL)       /* otherwise, this is a sub-request */
2603
0
           && (r->prev == NULL);   /* otherwise, this is an internal redirect */
2604
0
}
2605