Coverage Report

Created: 2026-12-01 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/httpd/server/util.c
Line
Count
Source
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
 * util.c: string utility things
19
 *
20
 * 3/21/93 Rob McCool
21
 * 1995-96 Many changes by the Apache Software Foundation
22
 *
23
 */
24
25
/* Debugging aid:
26
 * #define DEBUG            to trace all cfg_open*()/cfg_closefile() calls
27
 * #define DEBUG_CFG_LINES  to trace every line read from the config files
28
 */
29
30
#include "apr.h"
31
#include "apr_strings.h"
32
#include "apr_lib.h"
33
#include "apr_md5.h"            /* for apr_password_validate */
34
35
#define APR_WANT_STDIO
36
#define APR_WANT_STRFUNC
37
#include "apr_want.h"
38
39
#if APR_HAVE_UNISTD_H
40
#include <unistd.h>
41
#endif
42
#if APR_HAVE_PROCESS_H
43
#include <process.h>            /* for getpid() on Win32 */
44
#endif
45
#if APR_HAVE_NETDB_H
46
#include <netdb.h>              /* for gethostbyname() */
47
#endif
48
49
#include "ap_config.h"
50
#include "apr_base64.h"
51
#include "apr_fnmatch.h"
52
#include "httpd.h"
53
#include "http_main.h"
54
#include "http_log.h"
55
#include "http_protocol.h"
56
#include "http_config.h"
57
#include "http_core.h"
58
#include "util_ebcdic.h"
59
#include "util_varbuf.h"
60
61
#ifdef HAVE_PWD_H
62
#include <pwd.h>
63
#endif
64
#ifdef HAVE_GRP_H
65
#include <grp.h>
66
#endif
67
#ifdef HAVE_SYS_LOADAVG_H
68
#include <sys/loadavg.h>
69
#endif
70
71
#include "ap_mpm.h"
72
#include "mpm_common.h"         /* for ap_max_mem_free */
73
74
/* A bunch of functions in util.c scan strings looking for certain characters.
75
 * To make that more efficient we encode a lookup table.  The test_char_table
76
 * is generated automatically by gen_test_char.c.
77
 */
78
#include "test_char.h"
79
80
/* we know core's module_index is 0 */
81
#undef APLOG_MODULE_INDEX
82
0
#define APLOG_MODULE_INDEX AP_CORE_MODULE_INDEX
83
84
/* maximum nesting level for config directories */
85
#ifndef AP_MAX_FNMATCH_DIR_DEPTH
86
0
#define AP_MAX_FNMATCH_DIR_DEPTH (128)
87
#endif
88
89
/*
90
 * Examine a field value (such as a media-/content-type) string and return
91
 * it sans any parameters; e.g., strip off any ';charset=foo' and the like.
92
 */
93
AP_DECLARE(char *) ap_field_noparam(apr_pool_t *p, const char *intype)
94
1.21k
{
95
1.21k
    const char *semi;
96
97
1.21k
    if (intype == NULL) return NULL;
98
99
1.21k
    semi = ap_strchr_c(intype, ';');
100
1.21k
    if (semi == NULL) {
101
1.11k
        return apr_pstrdup(p, intype);
102
1.11k
    }
103
101
    else {
104
327
        while ((semi > intype) && apr_isspace(semi[-1])) {
105
226
            semi--;
106
226
        }
107
101
        return apr_pstrmemdup(p, intype, semi - intype);
108
101
    }
109
1.21k
}
110
111
AP_DECLARE(char *) ap_ht_time(apr_pool_t *p, apr_time_t t, const char *fmt,
112
                              int gmt)
113
0
{
114
0
    apr_size_t retcode;
115
0
    char ts[MAX_STRING_LEN];
116
0
    char tf[MAX_STRING_LEN];
117
0
    apr_time_exp_t xt;
118
119
0
    if (gmt) {
120
0
        const char *f;
121
0
        char *strp;
122
123
0
        apr_time_exp_gmt(&xt, t);
124
        /* Convert %Z to "GMT" and %z to "+0000";
125
         * on hosts that do not have a time zone string in struct tm,
126
         * strftime must assume its argument is local time.
127
         */
128
0
        for(strp = tf, f = fmt; strp < tf + sizeof(tf) - 6 && (*strp = *f)
129
0
            ; f++, strp++) {
130
0
            if (*f != '%') continue;
131
0
            switch (f[1]) {
132
0
            case '%':
133
0
                *++strp = *++f;
134
0
                break;
135
0
            case 'Z':
136
0
                *strp++ = 'G';
137
0
                *strp++ = 'M';
138
0
                *strp = 'T';
139
0
                f++;
140
0
                break;
141
0
            case 'z': /* common extension */
142
0
                *strp++ = '+';
143
0
                *strp++ = '0';
144
0
                *strp++ = '0';
145
0
                *strp++ = '0';
146
0
                *strp = '0';
147
0
                f++;
148
0
                break;
149
0
            }
150
0
        }
151
0
        *strp = '\0';
152
0
        fmt = tf;
153
0
    }
154
0
    else {
155
0
        apr_time_exp_lt(&xt, t);
156
0
    }
157
158
    /* check return code? */
159
0
    apr_strftime(ts, &retcode, MAX_STRING_LEN, fmt, &xt);
160
0
    ts[MAX_STRING_LEN - 1] = '\0';
161
0
    return apr_pstrdup(p, ts);
162
0
}
163
164
/* Roy owes Rob beer. */
165
/* Rob owes Roy dinner. */
166
167
/* These legacy comments would make a lot more sense if Roy hadn't
168
 * replaced the old later_than() routine with util_date.c.
169
 *
170
 * Well, okay, they still wouldn't make any sense.
171
 */
172
173
/* Match = 0, NoMatch = 1, Abort = -1
174
 * Based loosely on sections of wildmat.c by Rich Salz
175
 * Hmmm... shouldn't this really go component by component?
176
 */
177
AP_DECLARE(int) ap_strcmp_match(const char *str, const char *expected)
178
4.84k
{
179
4.84k
    apr_size_t x, y;
180
181
9.06k
    for (x = 0, y = 0; expected[y]; ++y, ++x) {
182
8.66k
        if (expected[y] == '*') {
183
828
            while (expected[++y] == '*');
184
588
            if (!expected[y])
185
3
                return 0;
186
3.68k
            while (str[x]) {
187
3.63k
                int ret;
188
3.63k
                if ((ret = ap_strcmp_match(&str[x++], &expected[y])) != 1)
189
531
                    return ret;
190
3.63k
            }
191
54
            return -1;
192
585
        }
193
8.07k
        else if (!str[x])
194
26
            return -1;
195
8.04k
        else if ((expected[y] != '?') && (str[x] != expected[y]))
196
3.83k
            return 1;
197
8.66k
    }
198
402
    return (str[x] != '\0');
199
4.84k
}
200
201
AP_DECLARE(int) ap_strcasecmp_match(const char *str, const char *expected)
202
4.84k
{
203
4.84k
    apr_size_t x, y;
204
205
9.06k
    for (x = 0, y = 0; expected[y]; ++y, ++x) {
206
8.66k
        if (!str[x] && expected[y] != '*')
207
26
            return -1;
208
8.63k
        if (expected[y] == '*') {
209
828
            while (expected[++y] == '*');
210
588
            if (!expected[y])
211
3
                return 0;
212
3.68k
            while (str[x]) {
213
3.63k
                int ret;
214
3.63k
                if ((ret = ap_strcasecmp_match(&str[x++], &expected[y])) != 1)
215
531
                    return ret;
216
3.63k
            }
217
54
            return -1;
218
585
        }
219
8.04k
        else if (expected[y] != '?'
220
5.33k
                 && apr_tolower(str[x]) != apr_tolower(expected[y]))
221
3.83k
            return 1;
222
8.63k
    }
223
403
    return (str[x] != '\0');
224
4.84k
}
225
226
/* We actually compare the canonical root to this root, (but we don't
227
 * waste time checking the case), since every use of this function in
228
 * httpd-2.1 tests if the path is 'proper', meaning we've already passed
229
 * it through apr_filepath_merge, or we haven't.
230
 */
231
AP_DECLARE(int) ap_os_is_path_absolute(apr_pool_t *p, const char *dir)
232
0
{
233
0
    const char *newpath;
234
0
    const char *ourdir = dir;
235
0
    if (apr_filepath_root(&newpath, &dir, 0, p) != APR_SUCCESS
236
0
            || strncmp(newpath, ourdir, strlen(newpath)) != 0) {
237
0
        return 0;
238
0
    }
239
0
    return 1;
240
0
}
241
242
AP_DECLARE(int) ap_is_matchexp(const char *str)
243
0
{
244
0
    for (; *str; str++)
245
0
        if ((*str == '*') || (*str == '?'))
246
0
            return 1;
247
0
    return 0;
248
0
}
249
250
/*
251
 * Here's a pool-based interface to the POSIX-esque ap_regcomp().
252
 * Note that we return ap_regex_t instead of being passed one.
253
 * The reason is that if you use an already-used ap_regex_t structure,
254
 * the memory that you've already allocated gets forgotten, and
255
 * regfree() doesn't clear it. So we don't allow it.
256
 */
257
258
static apr_status_t regex_cleanup(void *preg)
259
0
{
260
0
    ap_regfree((ap_regex_t *) preg);
261
0
    return APR_SUCCESS;
262
0
}
263
264
AP_DECLARE(ap_regex_t *) ap_pregcomp(apr_pool_t *p, const char *pattern,
265
                                     int cflags)
266
0
{
267
0
    ap_regex_t *preg = apr_palloc(p, sizeof *preg);
268
0
    int err = ap_regcomp(preg, pattern, cflags);
269
0
    if (err) {
270
0
        if (err == AP_REG_ESPACE)
271
0
            ap_abort_on_oom();
272
0
        return NULL;
273
0
    }
274
275
0
    apr_pool_cleanup_register(p, (void *) preg, regex_cleanup,
276
0
                              apr_pool_cleanup_null);
277
278
0
    return preg;
279
0
}
280
281
AP_DECLARE(void) ap_pregfree(apr_pool_t *p, ap_regex_t *reg)
282
0
{
283
0
    ap_regfree(reg);
284
0
    apr_pool_cleanup_kill(p, (void *) reg, regex_cleanup);
285
0
}
286
287
/*
288
 * Similar to standard strstr() but we ignore case in this version.
289
 * Based on the strstr() implementation further below.
290
 */
291
AP_DECLARE(char *) ap_strcasestr(const char *s1, const char *s2)
292
1.21k
{
293
1.21k
    char *p1, *p2;
294
1.21k
    if (*s2 == '\0') {
295
        /* an empty s2 */
296
192
        return((char *)s1);
297
192
    }
298
9.89k
    while(1) {
299
48.1k
        for ( ; (*s1 != '\0') && (apr_tolower(*s1) != apr_tolower(*s2)); s1++);
300
9.89k
        if (*s1 == '\0') {
301
983
            return(NULL);
302
983
        }
303
        /* found first character of s2, see if the rest matches */
304
8.90k
        p1 = (char *)s1;
305
8.90k
        p2 = (char *)s2;
306
57.5k
        for (++p1, ++p2; apr_tolower(*p1) == apr_tolower(*p2); ++p1, ++p2) {
307
48.6k
            if (*p1 == '\0') {
308
                /* both strings ended together */
309
6
                return((char *)s1);
310
6
            }
311
48.6k
        }
312
8.90k
        if (*p2 == '\0') {
313
            /* second string ended, a match */
314
36
            break;
315
36
        }
316
        /* didn't find a match here, try starting at next character in s1 */
317
8.86k
        s1++;
318
8.86k
    }
319
36
    return((char *)s1);
320
1.02k
}
321
322
/*
323
 * Returns an offsetted pointer in bigstring immediately after
324
 * prefix. Returns bigstring if bigstring doesn't start with
325
 * prefix or if prefix is longer than bigstring while still matching.
326
 * NOTE: pointer returned is relative to bigstring, so we
327
 * can use standard pointer comparisons in the calling function
328
 * (eg: test if ap_stripprefix(a,b) == a)
329
 */
330
AP_DECLARE(const char *) ap_stripprefix(const char *bigstring,
331
                                        const char *prefix)
332
0
{
333
0
    const char *p1;
334
335
0
    if (*prefix == '\0')
336
0
        return bigstring;
337
338
0
    p1 = bigstring;
339
0
    while (*p1 && *prefix) {
340
0
        if (*p1++ != *prefix++)
341
0
            return bigstring;
342
0
    }
343
0
    if (*prefix == '\0')
344
0
        return p1;
345
346
    /* hit the end of bigstring! */
347
0
    return bigstring;
348
0
}
349
350
/* This function substitutes for $0-$9, filling in regular expression
351
 * submatches. Pass it the same nmatch and pmatch arguments that you
352
 * passed ap_regexec(). pmatch should not be greater than the maximum number
353
 * of subexpressions - i.e. one more than the re_nsub member of ap_regex_t.
354
 *
355
 * nmatch must be <=AP_MAX_REG_MATCH (10).
356
 *
357
 * input should be the string with the $-expressions, source should be the
358
 * string that was matched against.
359
 *
360
 * It returns the substituted string, or NULL if a vbuf is used.
361
 * On errors, returns the orig string.
362
 *
363
 * Parts of this code are based on Henry Spencer's regsub(), from his
364
 * AT&T V8 regexp package.
365
 */
366
367
static apr_status_t regsub_core(apr_pool_t *p, char **result,
368
                                struct ap_varbuf *vb, const char *input,
369
                                const char *source, apr_size_t nmatch,
370
                                ap_regmatch_t pmatch[], apr_size_t maxlen)
371
0
{
372
0
    const char *src = input;
373
0
    char *dst;
374
0
    char c;
375
0
    apr_size_t no;
376
0
    apr_size_t len = 0;
377
378
0
    AP_DEBUG_ASSERT((result && p && !vb) || (vb && !p && !result));
379
0
    if (!source || nmatch>AP_MAX_REG_MATCH)
380
0
        return APR_EINVAL;
381
0
    if (!nmatch) {
382
0
        len = strlen(src);
383
0
        if (maxlen > 0 && len >= maxlen)
384
0
            return APR_ENOMEM;
385
0
        if (!vb) {
386
0
            *result = apr_pstrmemdup(p, src, len);
387
0
            return APR_SUCCESS;
388
0
        }
389
0
        else {
390
0
            ap_varbuf_strmemcat(vb, src, len);
391
0
            return APR_SUCCESS;
392
0
        }
393
0
    }
394
395
    /* First pass, find the size */
396
0
    while ((c = *src++) != '\0') {
397
0
        if (c == '$' && apr_isdigit(*src))
398
0
            no = *src++ - '0';
399
0
        else
400
0
            no = AP_MAX_REG_MATCH;
401
402
0
        if (no >= AP_MAX_REG_MATCH) {  /* Ordinary character. */
403
0
            if (c == '\\' && *src)
404
0
                src++;
405
0
            len++;
406
0
        }
407
0
        else if (no < nmatch && pmatch[no].rm_so >= 0
408
0
                 && pmatch[no].rm_so < pmatch[no].rm_eo) {
409
0
            if (APR_SIZE_MAX - len <= (apr_size_t)(pmatch[no].rm_eo
410
0
                                                   - pmatch[no].rm_so))
411
0
                return APR_ENOMEM;
412
0
            len += pmatch[no].rm_eo - pmatch[no].rm_so;
413
0
        }
414
415
0
    }
416
417
0
    if (len >= maxlen && maxlen > 0)
418
0
        return APR_ENOMEM;
419
420
0
    if (!vb) {
421
0
        *result = dst = apr_palloc(p, len + 1);
422
0
    }
423
0
    else {
424
0
        if (vb->strlen == AP_VARBUF_UNKNOWN)
425
0
            vb->strlen = strlen(vb->buf);
426
0
        ap_varbuf_grow(vb, vb->strlen + len);
427
0
        dst = vb->buf + vb->strlen;
428
0
        vb->strlen += len;
429
0
    }
430
431
    /* Now actually fill in the string */
432
433
0
    src = input;
434
435
0
    while ((c = *src++) != '\0') {
436
0
        if (c == '$' && apr_isdigit(*src))
437
0
            no = *src++ - '0';
438
0
        else
439
0
            no = AP_MAX_REG_MATCH;
440
441
0
        if (no >= AP_MAX_REG_MATCH) {  /* Ordinary character. */
442
0
            if (c == '\\' && *src)
443
0
                c = *src++;
444
0
            *dst++ = c;
445
0
        }
446
0
        else if (no < nmatch && pmatch[no].rm_so >= 0
447
0
                 && pmatch[no].rm_so < pmatch[no].rm_eo) {
448
0
            len = pmatch[no].rm_eo - pmatch[no].rm_so;
449
0
            memcpy(dst, source + pmatch[no].rm_so, len);
450
0
            dst += len;
451
0
        }
452
453
0
    }
454
0
    *dst = '\0';
455
456
0
    return APR_SUCCESS;
457
0
}
458
459
#ifndef AP_PREGSUB_MAXLEN
460
0
#define AP_PREGSUB_MAXLEN   (HUGE_STRING_LEN * 8)
461
#endif
462
AP_DECLARE(char *) ap_pregsub(apr_pool_t *p, const char *input,
463
                              const char *source, apr_size_t nmatch,
464
                              ap_regmatch_t pmatch[])
465
0
{
466
0
    char *result;
467
0
    apr_status_t rc = regsub_core(p, &result, NULL, input, source, nmatch,
468
0
                                  pmatch, AP_PREGSUB_MAXLEN);
469
0
    if (rc != APR_SUCCESS)
470
0
        result = NULL;
471
0
    return result;
472
0
}
473
474
AP_DECLARE(apr_status_t) ap_pregsub_ex(apr_pool_t *p, char **result,
475
                                       const char *input, const char *source,
476
                                       apr_size_t nmatch, ap_regmatch_t pmatch[],
477
                                       apr_size_t maxlen)
478
0
{
479
0
    apr_status_t rc = regsub_core(p, result, NULL, input, source, nmatch,
480
0
                                  pmatch, maxlen);
481
0
    if (rc != APR_SUCCESS)
482
0
        *result = NULL;
483
0
    return rc;
484
0
}
485
486
/* Forward declare */
487
static char x2c(const char *what);
488
489
951
#define IS_SLASH_OR_NUL(s) (s == '\0' || AP_IS_SLASH(s))
490
491
/*
492
 * Inspired by mod_jk's jk_servlet_normalize().
493
 */
494
AP_DECLARE(int) ap_normalize_path(char *path, unsigned int flags)
495
394
{
496
394
    int ret = 1;
497
394
    apr_size_t l = 1, w = 1, n;
498
394
    int decode_unreserved = (flags & AP_NORMALIZE_DECODE_UNRESERVED) != 0;
499
394
    int merge_slashes = (flags & AP_NORMALIZE_MERGE_SLASHES) != 0;
500
501
394
    if (!AP_IS_SLASH(path[0])) {
502
        /* Besides "OPTIONS *", a request-target should start with '/'
503
         * per RFC 7230 section 5.3, so anything else is invalid.
504
         */
505
382
        if (path[0] == '*' && path[1] == '\0') {
506
1
            return 1;
507
1
        }
508
        /* However, AP_NORMALIZE_ALLOW_RELATIVE can be used to bypass
509
         * this restriction (e.g. for subrequest file lookups).
510
         */
511
381
        if (!(flags & AP_NORMALIZE_ALLOW_RELATIVE) || path[0] == '\0') {
512
59
            return 0;
513
59
        }
514
515
322
        l = w = 0;
516
322
    }
517
518
14.6k
    while (path[l] != '\0') {
519
        /* RFC-3986 section 2.3:
520
         *  For consistency, percent-encoded octets in the ranges of
521
         *  ALPHA (%41-%5A and %61-%7A), DIGIT (%30-%39), hyphen (%2D),
522
         *  period (%2E), underscore (%5F), or tilde (%7E) should [...]
523
         *  be decoded to their corresponding unreserved characters by
524
         *  URI normalizers.
525
         */
526
14.3k
        if (decode_unreserved && path[l] == '%') {
527
0
            if (apr_isxdigit(path[l + 1]) && apr_isxdigit(path[l + 2])) {
528
0
                const char c = x2c(&path[l + 1]);
529
0
                if (TEST_CHAR(c, T_URI_UNRESERVED)) {
530
                    /* Replace last char and fall through as the current
531
                     * read position */
532
0
                    l += 2;
533
0
                    path[l] = c;
534
0
                }
535
0
            }
536
0
            else {
537
                /* Invalid encoding */
538
0
                ret = 0;
539
0
            }
540
0
        }
541
542
14.3k
        if (w == 0 || AP_IS_SLASH(path[w - 1])) {
543
            /* Collapse ///// sequences to / */
544
1.17k
            if (merge_slashes && AP_IS_SLASH(path[l])) {
545
0
                do {
546
0
                    l++;
547
0
                } while (AP_IS_SLASH(path[l]));
548
0
                continue;
549
0
            }
550
551
1.17k
            if (path[l] == '.') {
552
                /* Remove /./ segments */
553
607
                if (IS_SLASH_OR_NUL(path[l + 1])) {
554
141
                    l++;
555
141
                    if (path[l]) {
556
132
                        l++;
557
132
                    }
558
141
                    continue;
559
141
                }
560
561
                /* Remove /xx/../ segments (or /xx/.%2e/ when
562
                 * AP_NORMALIZE_DECODE_UNRESERVED is set since we
563
                 * decoded only the first dot above).
564
                 */
565
466
                n = l + 1;
566
466
                if ((path[n] == '.' || (decode_unreserved
567
0
                                        && path[n] == '%'
568
0
                                        && path[++n] == '2'
569
0
                                        && (path[++n] == 'e'
570
0
                                            || path[n] == 'E')))
571
344
                        && IS_SLASH_OR_NUL(path[n + 1])) {
572
                    /* Wind w back to remove the previous segment */
573
243
                    if (w > 1) {
574
862
                        do {
575
862
                            w--;
576
862
                        } while (w && !AP_IS_SLASH(path[w - 1]));
577
150
                    }
578
93
                    else {
579
                        /* Already at root, ignore and return a failure
580
                         * if asked to.
581
                         */
582
93
                        if (flags & AP_NORMALIZE_NOT_ABOVE_ROOT) {
583
93
                            ret = 0;
584
93
                        }
585
93
                    }
586
587
                    /* Move l forward to the next segment */
588
243
                    l = n + 1;
589
243
                    if (path[l]) {
590
237
                        l++;
591
237
                    }
592
243
                    continue;
593
243
                }
594
466
            }
595
1.17k
        }
596
597
13.9k
        path[w++] = path[l++];
598
13.9k
    }
599
334
    path[w] = '\0';
600
601
334
    return ret;
602
394
}
603
604
/*
605
 * Parse .. so we don't compromise security
606
 */
607
AP_DECLARE(void) ap_getparents(char *name)
608
394
{
609
394
    if (!ap_normalize_path(name, AP_NORMALIZE_NOT_ABOVE_ROOT |
610
394
                                 AP_NORMALIZE_ALLOW_RELATIVE)) {
611
83
        name[0] = '\0';
612
83
    }
613
394
}
614
615
AP_DECLARE(void) ap_no2slash_ex(char *name, int is_fs_path)
616
327
{
617
618
327
    char *d, *s;
619
620
327
    if (!*name) {
621
64
        return;
622
64
    }
623
624
263
    s = d = name;
625
626
#ifdef HAVE_UNC_PATHS
627
    /* Check for UNC names.  Leave leading two slashes. */
628
    if (is_fs_path && s[0] == '/' && s[1] == '/')
629
        *d++ = *s++;
630
#endif
631
632
11.6k
    while (*s) {
633
11.4k
        if ((*d++ = *s) == '/') {
634
488
            do {
635
488
                ++s;
636
488
            } while (*s == '/');
637
274
        }
638
11.1k
        else {
639
11.1k
            ++s;
640
11.1k
        }
641
11.4k
    }
642
263
    *d = '\0';
643
263
}
644
645
AP_DECLARE(void) ap_no2slash(char *name)
646
327
{
647
327
    ap_no2slash_ex(name, 1);
648
327
}
649
650
/*
651
 * copy at most n leading directories of s into d
652
 * d should be at least as large as s plus 1 extra byte
653
 * assumes n > 0
654
 * the return value is the ever useful pointer to the trailing \0 of d
655
 *
656
 * MODIFIED FOR HAVE_DRIVE_LETTERS and NETWARE environments,
657
 * so that if n == 0, "/" is returned in d with n == 1
658
 * and s == "e:/test.html", "e:/" is returned in d
659
 * *** See also ap_directory_walk in server/request.c
660
 *
661
 * examples:
662
 *    /a/b, 0  ==> /  (true for all platforms)
663
 *    /a/b, 1  ==> /
664
 *    /a/b, 2  ==> /a/
665
 *    /a/b, 3  ==> /a/b/
666
 *    /a/b, 4  ==> /a/b/
667
 *
668
 *    c:/a/b 0 ==> /
669
 *    c:/a/b 1 ==> c:/
670
 *    c:/a/b 2 ==> c:/a/
671
 *    c:/a/b 3 ==> c:/a/b
672
 *    c:/a/b 4 ==> c:/a/b
673
 */
674
AP_DECLARE(char *) ap_make_dirstr_prefix(char *d, const char *s, int n)
675
0
{
676
0
    if (n < 1) {
677
0
        *d = '/';
678
0
        *++d = '\0';
679
0
        return (d);
680
0
    }
681
682
0
    for (;;) {
683
0
        if (*s == '\0' || (*s == '/' && (--n) == 0)) {
684
0
            *d = '/';
685
0
            break;
686
0
        }
687
0
        *d++ = *s++;
688
0
    }
689
0
    *++d = 0;
690
0
    return (d);
691
0
}
692
693
694
/*
695
 * return the parent directory name including trailing / of the file s
696
 */
697
AP_DECLARE(char *) ap_make_dirstr_parent(apr_pool_t *p, const char *s)
698
219
{
699
219
    const char *last_slash = ap_strrchr_c(s, '/');
700
219
    char *d;
701
219
    int l;
702
703
219
    if (last_slash == NULL) {
704
196
        return apr_pstrdup(p, "");
705
196
    }
706
23
    l = (last_slash - s) + 1;
707
23
    d = apr_pstrmemdup(p, s, l);
708
709
23
    return (d);
710
219
}
711
712
713
AP_DECLARE(int) ap_count_dirs(const char *path)
714
0
{
715
0
    int x, n;
716
717
0
    for (x = 0, n = 0; path[x]; x++)
718
0
        if (path[x] == '/')
719
0
            n++;
720
0
    return n;
721
0
}
722
723
AP_DECLARE(char *) ap_getword_nc(apr_pool_t *atrans, char **line, char stop)
724
0
{
725
0
    return ap_getword(atrans, (const char **) line, stop);
726
0
}
727
728
AP_DECLARE(char *) ap_getword(apr_pool_t *atrans, const char **line, char stop)
729
1.21k
{
730
1.21k
    const char *pos = *line;
731
1.21k
    int len;
732
1.21k
    char *res;
733
734
56.2k
    while ((*pos != stop) && *pos) {
735
55.0k
        ++pos;
736
55.0k
    }
737
738
1.21k
    len = pos - *line;
739
1.21k
    res = apr_pstrmemdup(atrans, *line, len);
740
741
1.21k
    if (stop) {
742
0
        while (*pos == stop) {
743
0
            ++pos;
744
0
        }
745
0
    }
746
1.21k
    *line = pos;
747
748
1.21k
    return res;
749
1.21k
}
750
751
AP_DECLARE(char *) ap_getword_white_nc(apr_pool_t *atrans, char **line)
752
173
{
753
173
    return ap_getword_white(atrans, (const char **) line);
754
173
}
755
756
AP_DECLARE(char *) ap_getword_white(apr_pool_t *atrans, const char **line)
757
173
{
758
173
    const char *pos = *line;
759
173
    int len;
760
173
    char *res;
761
762
2.73k
    while (!apr_isspace(*pos) && *pos) {
763
2.56k
        ++pos;
764
2.56k
    }
765
766
173
    len = pos - *line;
767
173
    res = apr_pstrmemdup(atrans, *line, len);
768
769
471
    while (apr_isspace(*pos)) {
770
298
        ++pos;
771
298
    }
772
773
173
    *line = pos;
774
775
173
    return res;
776
173
}
777
778
AP_DECLARE(char *) ap_getword_nulls_nc(apr_pool_t *atrans, char **line,
779
                                       char stop)
780
0
{
781
0
    return ap_getword_nulls(atrans, (const char **) line, stop);
782
0
}
783
784
AP_DECLARE(char *) ap_getword_nulls(apr_pool_t *atrans, const char **line,
785
                                    char stop)
786
0
{
787
0
    const char *pos = ap_strchr_c(*line, stop);
788
0
    char *res;
789
790
0
    if (!pos) {
791
0
        apr_size_t len = strlen(*line);
792
0
        res = apr_pstrmemdup(atrans, *line, len);
793
0
        *line += len;
794
0
        return res;
795
0
    }
796
797
0
    res = apr_pstrmemdup(atrans, *line, pos - *line);
798
799
0
    ++pos;
800
801
0
    *line = pos;
802
803
0
    return res;
804
0
}
805
806
/* Get a word, (new) config-file style --- quoted strings and backslashes
807
 * all honored
808
 */
809
810
static char *substring_conf(apr_pool_t *p, const char *start, int len,
811
                            char quote)
812
1.19k
{
813
1.19k
    char *result = apr_palloc(p, len + 1);
814
1.19k
    char *resp = result;
815
1.19k
    int i;
816
817
33.0k
    for (i = 0; i < len; ++i) {
818
31.8k
        if (start[i] == '\\' && (start[i + 1] == '\\'
819
1.01k
                                 || (quote && start[i + 1] == quote)))
820
794
            *resp++ = start[++i];
821
31.0k
        else
822
31.0k
            *resp++ = start[i];
823
31.8k
    }
824
825
1.19k
    *resp++ = '\0';
826
#if RESOLVE_ENV_PER_TOKEN
827
    return (char *)ap_resolve_env(p,result);
828
#else
829
1.19k
    return result;
830
1.19k
#endif
831
1.19k
}
832
833
AP_DECLARE(char *) ap_getword_conf_nc(apr_pool_t *p, char **line)
834
0
{
835
0
    return ap_getword_conf(p, (const char **) line);
836
0
}
837
838
AP_DECLARE(char *) ap_getword_conf(apr_pool_t *p, const char **line)
839
129
{
840
129
    const char *str = *line, *strend;
841
129
    char *res;
842
129
    char quote;
843
844
317
    while (apr_isspace(*str))
845
188
        ++str;
846
847
129
    if (!*str) {
848
0
        *line = str;
849
0
        return "";
850
0
    }
851
852
129
    if ((quote = *str) == '"' || quote == '\'') {
853
129
        strend = str + 1;
854
3.48k
        while (*strend && *strend != quote) {
855
3.35k
            if (*strend == '\\' && strend[1] &&
856
482
                (strend[1] == quote || strend[1] == '\\')) {
857
231
                strend += 2;
858
231
            }
859
3.12k
            else {
860
3.12k
                ++strend;
861
3.12k
            }
862
3.35k
        }
863
129
        res = substring_conf(p, str + 1, strend - str - 1, quote);
864
865
129
        if (*strend == quote)
866
55
            ++strend;
867
129
    }
868
0
    else {
869
0
        strend = str;
870
0
        while (*strend && !apr_isspace(*strend))
871
0
            ++strend;
872
873
0
        res = substring_conf(p, str, strend - str, 0);
874
0
    }
875
876
283
    while (apr_isspace(*strend))
877
154
        ++strend;
878
129
    *line = strend;
879
129
    return res;
880
129
}
881
882
AP_DECLARE(char *) ap_getword_conf2_nc(apr_pool_t *p, char **line)
883
0
{
884
0
    return ap_getword_conf2(p, (const char **) line);
885
0
}
886
887
AP_DECLARE(char *) ap_getword_conf2(apr_pool_t *p, const char **line)
888
1.21k
{
889
1.21k
    const char *str = *line, *strend;
890
1.21k
    char *res;
891
1.21k
    char quote;
892
1.21k
    int count = 1;
893
894
2.60k
    while (apr_isspace(*str))
895
1.38k
        ++str;
896
897
1.21k
    if (!*str) {
898
18
        *line = str;
899
18
        return "";
900
18
    }
901
902
1.19k
    if ((quote = *str) == '"' || quote == '\'')
903
129
        return ap_getword_conf(p, line);
904
905
1.07k
    if (quote == '{') {
906
87
        strend = str + 1;
907
3.91k
        while (*strend) {
908
3.83k
            if (*strend == '}' && !--count)
909
7
                break;
910
3.83k
            if (*strend == '{')
911
408
                ++count;
912
3.83k
            if (*strend == '\\' && strend[1] == '\\') {
913
211
                ++strend;
914
211
            }
915
3.83k
            ++strend;
916
3.83k
        }
917
87
        res = substring_conf(p, str + 1, strend - str - 1, 0);
918
919
87
        if (*strend == '}')
920
7
            ++strend;
921
87
    }
922
983
    else {
923
983
        strend = str;
924
25.9k
        while (*strend && !apr_isspace(*strend))
925
25.0k
            ++strend;
926
927
983
        res = substring_conf(p, str, strend - str, 0);
928
983
    }
929
930
2.51k
    while (apr_isspace(*strend))
931
1.44k
        ++strend;
932
1.07k
    *line = strend;
933
1.07k
    return res;
934
1.19k
}
935
936
AP_DECLARE(int) ap_cfg_closefile(ap_configfile_t *cfp)
937
0
{
938
#ifdef DEBUG
939
    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL, APLOGNO(00551)
940
        "Done with config file %s", cfp->name);
941
#endif
942
0
    return (cfp->close == NULL) ? 0 : cfp->close(cfp->param);
943
0
}
944
945
/* we can't use apr_file_* directly because of linking issues on Windows */
946
static apr_status_t cfg_close(void *param)
947
0
{
948
0
    return apr_file_close(param);
949
0
}
950
951
static apr_status_t cfg_getch(char *ch, void *param)
952
16.8k
{
953
16.8k
    return apr_file_getc(ch, param);
954
16.8k
}
955
956
static apr_status_t cfg_getstr(void *buf, apr_size_t bufsiz, void *param)
957
753k
{
958
753k
    return apr_file_gets(buf, bufsiz, param);
959
753k
}
960
961
/* Open a ap_configfile_t as FILE, return open ap_configfile_t struct pointer */
962
AP_DECLARE(apr_status_t) ap_pcfg_openfile(ap_configfile_t **ret_cfg,
963
                                          apr_pool_t *p, const char *name)
964
1.21k
{
965
1.21k
    ap_configfile_t *new_cfg;
966
1.21k
    apr_file_t *file = NULL;
967
1.21k
    apr_finfo_t finfo;
968
1.21k
    apr_status_t status;
969
#ifdef DEBUG
970
    char buf[120];
971
#endif
972
973
1.21k
    if (name == NULL) {
974
0
        ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, APLOGNO(00552)
975
0
               "Internal error: pcfg_openfile() called with NULL filename");
976
0
        return APR_EBADF;
977
0
    }
978
979
1.21k
    status = apr_file_open(&file, name, APR_READ | APR_BUFFERED,
980
1.21k
                           APR_OS_DEFAULT, p);
981
#ifdef DEBUG
982
    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL, APLOGNO(00553)
983
                "Opening config file %s (%s)",
984
                name, (status != APR_SUCCESS) ?
985
                apr_strerror(status, buf, sizeof(buf)) : "successful");
986
#endif
987
1.21k
    if (status != APR_SUCCESS)
988
0
        return status;
989
990
1.21k
    status = apr_file_info_get(&finfo, APR_FINFO_TYPE, file);
991
1.21k
    if (status != APR_SUCCESS)
992
0
        return status;
993
994
1.21k
    if (finfo.filetype != APR_REG &&
995
#if defined(WIN32) || defined(OS2) || defined(NETWARE)
996
        ap_cstr_casecmp(apr_filepath_name_get(name), "nul") != 0) {
997
#else
998
0
        strcmp(name, "/dev/null") != 0) {
999
0
#endif /* WIN32 || OS2 */
1000
0
        ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, APLOGNO(00554)
1001
0
                     "Access to file %s denied by server: not a regular file",
1002
0
                     name);
1003
0
        apr_file_close(file);
1004
0
        return APR_EBADF;
1005
0
    }
1006
1007
#ifdef WIN32
1008
    /* Some twisted character [no pun intended] at MS decided that a
1009
     * zero width joiner as the lead wide character would be ideal for
1010
     * describing Unicode text files.  This was further convoluted to
1011
     * another MSism that the same character mapped into utf-8, EF BB BF
1012
     * would signify utf-8 text files.
1013
     *
1014
     * Since MS configuration files are all protecting utf-8 encoded
1015
     * Unicode path, file and resource names, we already have the correct
1016
     * WinNT encoding.  But at least eat the stupid three bytes up front.
1017
     */
1018
    {
1019
        unsigned char buf[4];
1020
        apr_size_t len = 3;
1021
        status = apr_file_read(file, buf, &len);
1022
        if ((status != APR_SUCCESS) || (len < 3)
1023
              || memcmp(buf, "\xEF\xBB\xBF", 3) != 0) {
1024
            apr_off_t zero = 0;
1025
            apr_file_seek(file, APR_SET, &zero);
1026
        }
1027
    }
1028
#endif
1029
1030
1.21k
    new_cfg = apr_palloc(p, sizeof(*new_cfg));
1031
1.21k
    new_cfg->param = file;
1032
1.21k
    new_cfg->name = apr_pstrdup(p, name);
1033
1.21k
    new_cfg->getch = cfg_getch;
1034
1.21k
    new_cfg->getstr = cfg_getstr;
1035
1.21k
    new_cfg->close = cfg_close;
1036
1.21k
    new_cfg->line_number = 0;
1037
1.21k
    *ret_cfg = new_cfg;
1038
1.21k
    return APR_SUCCESS;
1039
1.21k
}
1040
1041
1042
/* Allocate a ap_configfile_t handle with user defined functions and params */
1043
AP_DECLARE(ap_configfile_t *) ap_pcfg_open_custom(
1044
            apr_pool_t *p, const char *descr, void *param,
1045
            apr_status_t (*getc_func) (char *ch, void *param),
1046
            apr_status_t (*gets_func) (void *buf, apr_size_t bufsize, void *param),
1047
            apr_status_t (*close_func) (void *param))
1048
0
{
1049
0
    ap_configfile_t *new_cfg = apr_palloc(p, sizeof(*new_cfg));
1050
0
    new_cfg->param = param;
1051
0
    new_cfg->name = descr;
1052
0
    new_cfg->getch = getc_func;
1053
0
    new_cfg->getstr = gets_func;
1054
0
    new_cfg->close = close_func;
1055
0
    new_cfg->line_number = 0;
1056
0
    return new_cfg;
1057
0
}
1058
1059
/* Read one character from a configfile_t */
1060
AP_DECLARE(apr_status_t) ap_cfg_getc(char *ch, ap_configfile_t *cfp)
1061
0
{
1062
0
    apr_status_t rc = cfp->getch(ch, cfp->param);
1063
0
    if (rc == APR_SUCCESS && *ch == LF)
1064
0
        ++cfp->line_number;
1065
0
    return rc;
1066
0
}
1067
1068
AP_DECLARE(const char *) ap_pcfg_strerror(apr_pool_t *p, ap_configfile_t *cfp,
1069
                                          apr_status_t rc)
1070
0
{
1071
0
    if (rc == APR_SUCCESS)
1072
0
        return NULL;
1073
1074
0
    if (rc == APR_ENOSPC)
1075
0
        return apr_psprintf(p, "Error reading %s at line %d: Line too long",
1076
0
                            cfp->name, cfp->line_number);
1077
1078
0
    return apr_psprintf(p, "Error reading %s at line %d: %pm",
1079
0
                        cfp->name, cfp->line_number, &rc);
1080
0
}
1081
1082
/* Read one line from open ap_configfile_t, strip LF, increase line number */
1083
/* If custom handler does not define a getstr() function, read char by char */
1084
static apr_status_t ap_cfg_getline_core(char *buf, apr_size_t bufsize,
1085
                                        apr_size_t offset, ap_configfile_t *cfp)
1086
1.21k
{
1087
1.21k
    apr_status_t rc;
1088
    /* If a "get string" function is defined, use it */
1089
1.21k
    if (cfp->getstr != NULL) {
1090
1.10k
        char *cp;
1091
1.10k
        char *cbuf = buf + offset;
1092
1.10k
        apr_size_t cbufsize = bufsize - offset;
1093
1094
753k
        while (1) {
1095
753k
            ++cfp->line_number;
1096
753k
            rc = cfp->getstr(cbuf, cbufsize, cfp->param);
1097
753k
            if (rc == APR_EOF) {
1098
13
                if (cbuf != buf + offset) {
1099
10
                    *cbuf = '\0';
1100
10
                    break;
1101
10
                }
1102
3
                else {
1103
3
                    return APR_EOF;
1104
3
                }
1105
13
            }
1106
753k
            if (rc != APR_SUCCESS) {
1107
0
                return rc;
1108
0
            }
1109
1110
            /*
1111
             *  check for line continuation,
1112
             *  i.e. match [^\\]\\[\r]\n only
1113
             */
1114
753k
            cp = cbuf;
1115
753k
            cp += strlen(cp);
1116
753k
            if (cp > buf && cp[-1] == LF) {
1117
752k
                cp--;
1118
752k
                if (cp > buf && cp[-1] == CR)
1119
255
                    cp--;
1120
752k
                if (cp > buf && cp[-1] == '\\') {
1121
752k
                    cp--;
1122
                    /*
1123
                     * line continuation requested -
1124
                     * then remove backslash and continue
1125
                     */
1126
752k
                    cbufsize -= (cp-cbuf);
1127
752k
                    cbuf = cp;
1128
752k
                    continue;
1129
752k
                }
1130
752k
            }
1131
921
            else if (cp - buf >= bufsize - 1) {
1132
155
                return APR_ENOSPC;
1133
155
            }
1134
941
            break;
1135
753k
        }
1136
1.10k
    } else {
1137
        /* No "get string" function defined; read character by character */
1138
108
        apr_size_t i = offset;
1139
1140
108
        if (bufsize < 2) {
1141
            /* too small, assume caller is crazy */
1142
0
            return APR_EINVAL;
1143
0
        }
1144
108
        buf[offset] = '\0';
1145
1146
16.8k
        while (1) {
1147
16.8k
            char c;
1148
16.8k
            rc = cfp->getch(&c, cfp->param);
1149
16.8k
            if (rc == APR_EOF) {
1150
15
                if (i > offset)
1151
15
                    break;
1152
0
                else
1153
0
                    return APR_EOF;
1154
15
            }
1155
16.8k
            if (rc != APR_SUCCESS)
1156
0
                return rc;
1157
16.8k
            if (c == LF) {
1158
4.93k
                ++cfp->line_number;
1159
                /* check for line continuation */
1160
4.93k
                if (i > 0 && buf[i-1] == '\\') {
1161
4.88k
                    i--;
1162
4.88k
                    continue;
1163
4.88k
                }
1164
47
                else {
1165
47
                    break;
1166
47
                }
1167
4.93k
            }
1168
11.8k
            buf[i] = c;
1169
11.8k
            ++i;
1170
11.8k
            if (i >= bufsize - 1) {
1171
46
                return APR_ENOSPC;
1172
46
            }
1173
11.8k
        }
1174
62
        buf[i] = '\0';
1175
62
    }
1176
1.01k
    return APR_SUCCESS;
1177
1.21k
}
1178
1179
static int cfg_trim_line(char *buf)
1180
1.01k
{
1181
1.01k
    char *start, *end;
1182
    /*
1183
     * Leading and trailing white space is eliminated completely
1184
     */
1185
1.01k
    start = buf;
1186
2.21k
    while (apr_isspace(*start))
1187
1.20k
        ++start;
1188
    /* blast trailing whitespace */
1189
1.01k
    end = ap_cstr_stripws(start);
1190
    /* Zap leading whitespace by shifting */
1191
1.01k
    if (start != buf)
1192
272
        memmove(buf, start, end - start + 1);
1193
#ifdef DEBUG_CFG_LINES
1194
    ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL, APLOGNO(00555) "Read config: '%s'", buf);
1195
#endif
1196
1.01k
    return end - start;
1197
1.01k
}
1198
1199
/* Read one line from open ap_configfile_t, strip LF, increase line number */
1200
/* If custom handler does not define a getstr() function, read char by char */
1201
AP_DECLARE(apr_status_t) ap_cfg_getline(char *buf, apr_size_t bufsize,
1202
                                        ap_configfile_t *cfp)
1203
1.21k
{
1204
1.21k
    apr_status_t rc = ap_cfg_getline_core(buf, bufsize, 0, cfp);
1205
1.21k
    if (rc == APR_SUCCESS)
1206
1.01k
        cfg_trim_line(buf);
1207
1.21k
    return rc;
1208
1.21k
}
1209
1210
AP_DECLARE(apr_status_t) ap_varbuf_cfg_getline(struct ap_varbuf *vb,
1211
                                               ap_configfile_t *cfp,
1212
                                               apr_size_t max_len)
1213
0
{
1214
0
    apr_status_t rc;
1215
0
    apr_size_t new_len;
1216
0
    vb->strlen = 0;
1217
0
    *vb->buf = '\0';
1218
1219
0
    if (vb->strlen == AP_VARBUF_UNKNOWN)
1220
0
        vb->strlen = strlen(vb->buf);
1221
0
    if (vb->avail - vb->strlen < 3) {
1222
0
        new_len = vb->avail * 2;
1223
0
        if (new_len > max_len)
1224
0
            new_len = max_len;
1225
0
        else if (new_len < 3)
1226
0
            new_len = 3;
1227
0
        ap_varbuf_grow(vb, new_len);
1228
0
    }
1229
1230
0
    for (;;) {
1231
0
        rc = ap_cfg_getline_core(vb->buf, vb->avail, vb->strlen, cfp);
1232
0
        if (rc == APR_ENOSPC || rc == APR_SUCCESS)
1233
0
            vb->strlen += strlen(vb->buf + vb->strlen);
1234
0
        if (rc != APR_ENOSPC)
1235
0
            break;
1236
0
        if (vb->avail >= max_len)
1237
0
            return APR_ENOSPC;
1238
0
        new_len = vb->avail * 2;
1239
0
        if (new_len > max_len)
1240
0
            new_len = max_len;
1241
0
        ap_varbuf_grow(vb, new_len);
1242
0
        --cfp->line_number;
1243
0
    }
1244
0
    if (vb->strlen > max_len)
1245
0
        return APR_ENOSPC;
1246
0
    if (rc == APR_SUCCESS)
1247
0
        vb->strlen = cfg_trim_line(vb->buf);
1248
0
    return rc;
1249
0
}
1250
1251
/* Size an HTTP header field list item, as separated by a comma.
1252
 * The return value is a pointer to the beginning of the non-empty list item
1253
 * within the original string (or NULL if there is none) and the address
1254
 * of field is shifted to the next non-comma, non-whitespace character.
1255
 * len is the length of the item excluding any beginning whitespace.
1256
 */
1257
AP_DECLARE(const char *) ap_size_list_item(const char **field, int *len)
1258
1.21k
{
1259
1.21k
    const unsigned char *ptr = (const unsigned char *)*field;
1260
1.21k
    const unsigned char *token;
1261
1.21k
    int in_qpair, in_qstr, in_com;
1262
1263
    /* Find first non-comma, non-whitespace byte */
1264
1265
2.88k
    while (*ptr == ',' || apr_isspace(*ptr))
1266
1.66k
        ++ptr;
1267
1268
1.21k
    token = ptr;
1269
1270
    /* Find the end of this item, skipping over dead bits */
1271
1272
1.21k
    for (in_qpair = in_qstr = in_com = 0;
1273
43.0k
         *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1274
41.8k
         ++ptr) {
1275
1276
41.8k
        if (in_qpair) {
1277
3.09k
            in_qpair = 0;
1278
3.09k
        }
1279
38.7k
        else {
1280
38.7k
            switch (*ptr) {
1281
3.13k
                case '\\': in_qpair = 1;      /* quoted-pair         */
1282
3.13k
                           break;
1283
966
                case '"' : if (!in_com)       /* quoted string delim */
1284
777
                               in_qstr = !in_qstr;
1285
966
                           break;
1286
1.14k
                case '(' : if (!in_qstr)      /* comment (may nest)  */
1287
979
                               ++in_com;
1288
1.14k
                           break;
1289
522
                case ')' : if (in_com)        /* end comment         */
1290
200
                               --in_com;
1291
522
                           break;
1292
32.9k
                default  : break;
1293
38.7k
            }
1294
38.7k
        }
1295
41.8k
    }
1296
1297
1.21k
    if ((*len = (ptr - token)) == 0) {
1298
18
        *field = (const char *)ptr;
1299
18
        return NULL;
1300
18
    }
1301
1302
    /* Advance field pointer to the next non-comma, non-white byte */
1303
1304
1.94k
    while (*ptr == ',' || apr_isspace(*ptr))
1305
744
        ++ptr;
1306
1307
1.19k
    *field = (const char *)ptr;
1308
1.19k
    return (const char *)token;
1309
1.21k
}
1310
1311
/* Retrieve an HTTP header field list item, as separated by a comma,
1312
 * while stripping insignificant whitespace and lowercasing anything not in
1313
 * a quoted string or comment.  The return value is a new string containing
1314
 * the converted list item (or NULL if none) and the address pointed to by
1315
 * field is shifted to the next non-comma, non-whitespace.
1316
 */
1317
AP_DECLARE(char *) ap_get_list_item(apr_pool_t *p, const char **field)
1318
1.21k
{
1319
1.21k
    const char *tok_start;
1320
1.21k
    const unsigned char *ptr;
1321
1.21k
    unsigned char *pos;
1322
1.21k
    char *token;
1323
1.21k
    int addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0, tok_len = 0;
1324
1325
    /* Find the beginning and maximum length of the list item so that
1326
     * we can allocate a buffer for the new string and reset the field.
1327
     */
1328
1.21k
    if ((tok_start = ap_size_list_item(field, &tok_len)) == NULL) {
1329
18
        return NULL;
1330
18
    }
1331
1.19k
    token = apr_palloc(p, tok_len + 1);
1332
1333
    /* Scan the token again, but this time copy only the good bytes.
1334
     * We skip extra whitespace and any whitespace around a '=', '/',
1335
     * or ';' and lowercase normal characters not within a comment,
1336
     * quoted-string or quoted-pair.
1337
     */
1338
1.19k
    for (ptr = (const unsigned char *)tok_start, pos = (unsigned char *)token;
1339
43.0k
         *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1340
41.8k
         ++ptr) {
1341
1342
41.8k
        if (in_qpair) {
1343
3.09k
            in_qpair = 0;
1344
3.09k
            *pos++ = *ptr;
1345
3.09k
        }
1346
38.7k
        else {
1347
38.7k
            switch (*ptr) {
1348
3.13k
                case '\\': in_qpair = 1;
1349
3.13k
                           if (addspace == 1)
1350
73
                               *pos++ = ' ';
1351
3.13k
                           *pos++ = *ptr;
1352
3.13k
                           addspace = 0;
1353
3.13k
                           break;
1354
966
                case '"' : if (!in_com)
1355
777
                               in_qstr = !in_qstr;
1356
966
                           if (addspace == 1)
1357
63
                               *pos++ = ' ';
1358
966
                           *pos++ = *ptr;
1359
966
                           addspace = 0;
1360
966
                           break;
1361
1.14k
                case '(' : if (!in_qstr)
1362
979
                               ++in_com;
1363
1.14k
                           if (addspace == 1)
1364
68
                               *pos++ = ' ';
1365
1.14k
                           *pos++ = *ptr;
1366
1.14k
                           addspace = 0;
1367
1.14k
                           break;
1368
522
                case ')' : if (in_com)
1369
200
                               --in_com;
1370
522
                           *pos++ = *ptr;
1371
522
                           addspace = 0;
1372
522
                           break;
1373
1.50k
                case ' ' :
1374
2.63k
                case '\t': if (addspace)
1375
1.20k
                               break;
1376
1.42k
                           if (in_com || in_qstr)
1377
731
                               *pos++ = *ptr;
1378
695
                           else
1379
695
                               addspace = 1;
1380
1.42k
                           break;
1381
373
                case '=' :
1382
996
                case '/' :
1383
1.32k
                case ';' : if (!(in_com || in_qstr))
1384
673
                               addspace = -1;
1385
1.32k
                           *pos++ = *ptr;
1386
1.32k
                           break;
1387
29.0k
                default  : if (addspace == 1)
1388
414
                               *pos++ = ' ';
1389
29.0k
                           *pos++ = (in_com || in_qstr) ? *ptr
1390
29.0k
                                                        : apr_tolower(*ptr);
1391
29.0k
                           addspace = 0;
1392
29.0k
                           break;
1393
38.7k
            }
1394
38.7k
        }
1395
41.8k
    }
1396
1.19k
    *pos = '\0';
1397
1398
1.19k
    return token;
1399
1.19k
}
1400
1401
typedef enum ap_etag_e {
1402
    AP_ETAG_NONE,
1403
    AP_ETAG_WEAK,
1404
    AP_ETAG_STRONG
1405
} ap_etag_e;
1406
1407
/* Find an item in canonical form (lowercase, no extra spaces) within
1408
 * an HTTP field value list.  Returns 1 if found, 0 if not found.
1409
 * This would be much more efficient if we stored header fields as
1410
 * an array of list items as they are received instead of a plain string.
1411
 */
1412
static int find_list_item(apr_pool_t *p, const char *line,
1413
                                  const char *tok, ap_etag_e type)
1414
1.21k
{
1415
1.21k
    const unsigned char *pos;
1416
1.21k
    const unsigned char *ptr = (const unsigned char *)line;
1417
1.21k
    int good = 0, addspace = 0, in_qpair = 0, in_qstr = 0, in_com = 0;
1418
1419
1.21k
    if (!line || !tok) {
1420
0
        return 0;
1421
0
    }
1422
1.21k
    if (type == AP_ETAG_STRONG && *tok != '\"') {
1423
0
        return 0;
1424
0
    }
1425
1.21k
    if (type == AP_ETAG_WEAK) {
1426
0
        if (*tok == 'W' && (*(tok+1)) == '/' && (*(tok+2)) == '\"') {
1427
0
            tok += 2;
1428
0
        }
1429
0
        else if (*tok != '\"') {
1430
0
            return 0;
1431
0
        }
1432
0
    }
1433
1434
3.12k
    do {  /* loop for each item in line's list */
1435
1436
        /* Find first non-comma, non-whitespace byte */
1437
7.60k
        while (*ptr == ',' || apr_isspace(*ptr)) {
1438
4.48k
            ++ptr;
1439
4.48k
        }
1440
1441
        /* Account for strong or weak Etags, depending on our search */
1442
3.12k
        if (type == AP_ETAG_STRONG && *ptr != '\"') {
1443
0
            break;
1444
0
        }
1445
3.12k
        if (type == AP_ETAG_WEAK) {
1446
0
            if (*ptr == 'W' && (*(ptr+1)) == '/' && (*(ptr+2)) == '\"') {
1447
0
                ptr += 2;
1448
0
            }
1449
0
            else if (*ptr != '\"') {
1450
0
                break;
1451
0
            }
1452
0
        }
1453
1454
3.12k
        if (*ptr)
1455
3.07k
            good = 1;  /* until proven otherwise for this item */
1456
51
        else
1457
51
            break;     /* no items left and nothing good found */
1458
1459
        /* We skip extra whitespace and any whitespace around a '=', '/',
1460
         * or ';' and lowercase normal characters not within a comment,
1461
         * quoted-string or quoted-pair.
1462
         */
1463
3.07k
        for (pos = (const unsigned char *)tok;
1464
53.6k
             *ptr && (in_qpair || in_qstr || in_com || *ptr != ',');
1465
50.5k
             ++ptr) {
1466
1467
50.5k
            if (in_qpair) {
1468
3.43k
                in_qpair = 0;
1469
3.43k
                if (good)
1470
0
                    good = (*pos++ == *ptr);
1471
3.43k
            }
1472
47.0k
            else {
1473
47.0k
                switch (*ptr) {
1474
3.47k
                    case '\\': in_qpair = 1;
1475
3.47k
                               if (addspace == 1)
1476
29
                                   good = good && (*pos++ == ' ');
1477
3.47k
                               good = good && (*pos++ == *ptr);
1478
3.47k
                               addspace = 0;
1479
3.47k
                               break;
1480
1.26k
                    case '"' : if (!in_com)
1481
1.05k
                                   in_qstr = !in_qstr;
1482
1.26k
                               if (addspace == 1)
1483
29
                                   good = good && (*pos++ == ' ');
1484
1.26k
                               good = good && (*pos++ == *ptr);
1485
1.26k
                               addspace = 0;
1486
1.26k
                               break;
1487
1.32k
                    case '(' : if (!in_qstr)
1488
1.15k
                                   ++in_com;
1489
1.32k
                               if (addspace == 1)
1490
29
                                   good = good && (*pos++ == ' ');
1491
1.32k
                               good = good && (*pos++ == *ptr);
1492
1.32k
                               addspace = 0;
1493
1.32k
                               break;
1494
927
                    case ')' : if (in_com)
1495
321
                                   --in_com;
1496
927
                               good = good && (*pos++ == *ptr);
1497
927
                               addspace = 0;
1498
927
                               break;
1499
1.81k
                    case ' ' :
1500
3.08k
                    case '\t': if (addspace || !good)
1501
2.93k
                                   break;
1502
148
                               if (in_com || in_qstr)
1503
0
                                   good = (*pos++ == *ptr);
1504
148
                               else
1505
148
                                   addspace = 1;
1506
148
                               break;
1507
469
                    case '=' :
1508
1.32k
                    case '/' :
1509
1.70k
                    case ';' : if (!(in_com || in_qstr))
1510
1.02k
                                   addspace = -1;
1511
1.70k
                               good = good && (*pos++ == *ptr);
1512
1.70k
                               break;
1513
35.3k
                    default  : if (!good)
1514
32.6k
                                   break;
1515
2.69k
                               if (addspace == 1)
1516
55
                                   good = (*pos++ == ' ');
1517
2.69k
                               if (in_com || in_qstr)
1518
0
                                   good = good && (*pos++ == *ptr);
1519
2.69k
                               else
1520
2.69k
                                   good = good
1521
2.64k
                                       && (apr_tolower(*pos++) == apr_tolower(*ptr));
1522
2.69k
                               addspace = 0;
1523
2.69k
                               break;
1524
47.0k
                }
1525
47.0k
            }
1526
50.5k
        }
1527
3.07k
        if (good && *pos)
1528
120
            good = 0;          /* not good if only a prefix was matched */
1529
1530
3.07k
    } while (*ptr && !good);
1531
1532
1.21k
    return good;
1533
1.21k
}
1534
1535
/* Find an item in canonical form (lowercase, no extra spaces) within
1536
 * an HTTP field value list.  Returns 1 if found, 0 if not found.
1537
 * This would be much more efficient if we stored header fields as
1538
 * an array of list items as they are received instead of a plain string.
1539
 */
1540
AP_DECLARE(int) ap_find_list_item(apr_pool_t *p, const char *line,
1541
                                  const char *tok)
1542
1.21k
{
1543
1.21k
    return find_list_item(p, line, tok, AP_ETAG_NONE);
1544
1.21k
}
1545
1546
/* Find a strong Etag in canonical form (lowercase, no extra spaces) within
1547
 * an HTTP field value list.  Returns 1 if found, 0 if not found.
1548
 */
1549
AP_DECLARE(int) ap_find_etag_strong(apr_pool_t *p, const char *line,
1550
                                    const char *tok)
1551
0
{
1552
0
    return find_list_item(p, line, tok, AP_ETAG_STRONG);
1553
0
}
1554
1555
/* Find a weak ETag in canonical form (lowercase, no extra spaces) within
1556
 * an HTTP field value list.  Returns 1 if found, 0 if not found.
1557
 */
1558
AP_DECLARE(int) ap_find_etag_weak(apr_pool_t *p, const char *line,
1559
                                  const char *tok)
1560
0
{
1561
0
    return find_list_item(p, line, tok, AP_ETAG_WEAK);
1562
0
}
1563
1564
/* Grab a list of tokens of the format 1#token (from RFC7230) */
1565
AP_DECLARE(const char *) ap_parse_token_list_strict(apr_pool_t *p,
1566
                                                const char *str_in,
1567
                                                apr_array_header_t **tokens,
1568
                                                int skip_invalid)
1569
1.21k
{
1570
1.21k
    int in_leading_space = 1;
1571
1.21k
    int in_trailing_space = 0;
1572
1.21k
    int string_end = 0;
1573
1.21k
    const char *tok_begin;
1574
1.21k
    const char *cur;
1575
1576
1.21k
    if (!str_in) {
1577
0
        return NULL;
1578
0
    }
1579
1580
1.21k
    tok_begin = cur = str_in;
1581
1582
14.9k
    while (!string_end) {
1583
14.7k
        const unsigned char c = (unsigned char)*cur;
1584
1585
14.7k
        if (!TEST_CHAR(c, T_HTTP_TOKEN_STOP)) {
1586
            /* Non-separator character; we are finished with leading
1587
             * whitespace. We must never have encountered any trailing
1588
             * whitespace before the delimiter (comma) */
1589
10.6k
            in_leading_space = 0;
1590
10.6k
            if (in_trailing_space) {
1591
32
                return "Encountered illegal whitespace in token";
1592
32
            }
1593
10.6k
        }
1594
4.05k
        else if (c == ' ' || c == '\t') {
1595
            /* "Linear whitespace" only includes ASCII CRLF, space, and tab;
1596
             * we can't get a CRLF since headers are split on them already,
1597
             * so only look for a space or a tab */
1598
1.62k
            if (in_leading_space) {
1599
                /* We're still in leading whitespace */
1600
1.27k
                ++tok_begin;
1601
1.27k
            }
1602
345
            else {
1603
                /* We must be in trailing whitespace */
1604
345
                ++in_trailing_space;
1605
345
            }
1606
1.62k
        }
1607
2.43k
        else if (c == ',' || c == '\0') {
1608
1.44k
            if (!in_leading_space) {
1609
                /* If we're out of the leading space, we know we've read some
1610
                 * characters of a token */
1611
948
                if (*tokens == NULL) {
1612
237
                    *tokens = apr_array_make(p, 4, sizeof(char *));
1613
237
                }
1614
948
                APR_ARRAY_PUSH(*tokens, char *) =
1615
948
                    apr_pstrmemdup((*tokens)->pool, tok_begin,
1616
948
                                   (cur - tok_begin) - in_trailing_space);
1617
948
            }
1618
            /* We're allowed to have null elements, just don't add them to the
1619
             * array */
1620
1621
1.44k
            tok_begin = cur + 1;
1622
1.44k
            in_leading_space = 1;
1623
1.44k
            in_trailing_space = 0;
1624
1.44k
            string_end = (c == '\0');
1625
1.44k
        }
1626
985
        else {
1627
            /* Encountered illegal separator char */
1628
985
            if (skip_invalid) {
1629
                /* Skip to the next separator */
1630
0
                const char *temp;
1631
0
                temp = ap_strchr_c(cur, ',');
1632
0
                if(!temp) {
1633
0
                    temp = ap_strchr_c(cur, '\0');
1634
0
                }
1635
1636
                /* Act like we haven't seen a token so we reset */
1637
0
                cur = temp - 1;
1638
0
                in_leading_space = 1;
1639
0
                in_trailing_space = 0;
1640
0
            }
1641
985
            else {
1642
985
                return apr_psprintf(p, "Encountered illegal separator "
1643
985
                                    "'\\x%.2x'", (unsigned int)c);
1644
985
            }
1645
985
        }
1646
1647
13.6k
        ++cur;
1648
13.6k
    }
1649
1650
200
    return NULL;
1651
1.21k
}
1652
1653
/* Scan a string for HTTP VCHAR/obs-text characters including HT and SP
1654
 * (as used in header values, for example, in RFC 7230 section 3.2)
1655
 * returning the pointer to the first non-HT ASCII ctrl character.
1656
 */
1657
AP_DECLARE(const char *) ap_scan_http_field_content(const char *ptr)
1658
0
{
1659
0
    for ( ; !TEST_CHAR(*ptr, T_HTTP_CTRLS); ++ptr) ;
1660
1661
0
    return ptr;
1662
0
}
1663
1664
/* Scan a string for HTTP token characters, returning the pointer to
1665
 * the first non-token character.
1666
 */
1667
AP_DECLARE(const char *) ap_scan_http_token(const char *ptr)
1668
650
{
1669
4.29k
    for ( ; !TEST_CHAR(*ptr, T_HTTP_TOKEN_STOP); ++ptr) ;
1670
1671
650
    return ptr;
1672
650
}
1673
1674
/* Scan a string for visible ASCII (0x21-0x7E) or obstext (0x80+)
1675
 * and return a pointer to the first ctrl/space character encountered.
1676
 */
1677
AP_DECLARE(const char *) ap_scan_vchar_obstext(const char *ptr)
1678
1.23k
{
1679
22.4k
    for ( ; TEST_CHAR(*ptr, T_VCHAR_OBSTEXT); ++ptr) ;
1680
1681
1.23k
    return ptr;
1682
1.23k
}
1683
1684
/* Retrieve a token, spacing over it and returning a pointer to
1685
 * the first non-white byte afterwards.  Note that these tokens
1686
 * are delimited by semis and commas; and can also be delimited
1687
 * by whitespace at the caller's option.
1688
 */
1689
1690
AP_DECLARE(char *) ap_get_token(apr_pool_t *p, const char **accept_line,
1691
                                int accept_white)
1692
1.21k
{
1693
1.21k
    const char *ptr = *accept_line;
1694
1.21k
    const char *tok_start;
1695
1.21k
    char *token;
1696
1697
    /* Find first non-white byte */
1698
1699
2.60k
    while (apr_isspace(*ptr))
1700
1.38k
        ++ptr;
1701
1702
1.21k
    tok_start = ptr;
1703
1704
    /* find token end, skipping over quoted strings.
1705
     * (comments are already gone).
1706
     */
1707
1708
33.9k
    while (*ptr && (accept_white || !apr_isspace(*ptr))
1709
33.1k
           && *ptr != ';' && *ptr != ',') {
1710
32.7k
        if (*ptr++ == '"')
1711
5.25k
            while (*ptr)
1712
5.12k
                if (*ptr++ == '"')
1713
409
                    break;
1714
32.7k
    }
1715
1716
1.21k
    token = apr_pstrmemdup(p, tok_start, ptr - tok_start);
1717
1718
    /* Advance accept_line pointer to the next non-white byte */
1719
1720
1.21k
    while (apr_isspace(*ptr))
1721
0
        ++ptr;
1722
1723
1.21k
    *accept_line = ptr;
1724
1.21k
    return token;
1725
1.21k
}
1726
1727
1728
/* find http tokens, see the definition of token from RFC2068 */
1729
AP_DECLARE(int) ap_find_token(apr_pool_t *p, const char *line, const char *tok)
1730
1.21k
{
1731
1.21k
    const unsigned char *start_token;
1732
1.21k
    const unsigned char *s;
1733
1734
1.21k
    if (!line)
1735
0
        return 0;
1736
1737
1.21k
    s = (const unsigned char *)line;
1738
5.31k
    for (;;) {
1739
        /* find start of token, skip all stop characters */
1740
37.1k
        while (*s && TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1741
31.8k
            ++s;
1742
31.8k
        }
1743
5.31k
        if (!*s) {
1744
733
            return 0;
1745
733
        }
1746
4.57k
        start_token = s;
1747
        /* find end of the token */
1748
23.7k
        while (*s && !TEST_CHAR(*s, T_HTTP_TOKEN_STOP)) {
1749
19.1k
            ++s;
1750
19.1k
        }
1751
4.57k
        if (!ap_cstr_casecmpn((const char *)start_token, (const char *)tok,
1752
4.57k
                         s - start_token)) {
1753
113
            return 1;
1754
113
        }
1755
4.46k
        if (!*s) {
1756
371
            return 0;
1757
371
        }
1758
4.46k
    }
1759
1.21k
}
1760
1761
static const char *find_last_token(apr_pool_t *p, const char *line,
1762
                            const char *tok)
1763
2.42k
{
1764
2.42k
    int llen, tlen, lidx;
1765
1766
2.42k
    if (!line)
1767
0
        return NULL;
1768
1769
2.42k
    llen = strlen(line);
1770
2.42k
    tlen = strlen(tok);
1771
2.42k
    lidx = llen - tlen;
1772
1773
2.42k
    if (lidx < 0 ||
1774
2.22k
        (lidx > 0 && !(apr_isspace(line[lidx - 1]) || line[lidx - 1] == ',')))
1775
2.00k
        return NULL;
1776
1777
419
    if (ap_cstr_casecmpn(&line[lidx], tok, tlen) == 0) { 
1778
23
        return &line[lidx];
1779
23
    }
1780
396
   return NULL;
1781
419
}
1782
1783
AP_DECLARE(int) ap_find_last_token(apr_pool_t *p, const char *line,
1784
                                   const char *tok)
1785
1.21k
{
1786
1.21k
    return find_last_token(p, line, tok) != NULL;
1787
1.21k
}
1788
1789
AP_DECLARE(int) ap_is_chunked(apr_pool_t *p, const char *line)
1790
1.21k
{
1791
1.21k
    const char *s;
1792
1793
1.21k
    if (!line) 
1794
0
        return 0;
1795
1.21k
    if (!ap_cstr_casecmp(line, "chunked")) { 
1796
10
        return 1;
1797
10
    }
1798
1799
1.20k
    s = find_last_token(p, line, "chunked");
1800
1801
1.20k
    if (!s) return 0;
1802
 
1803
    /* eat spaces right-to-left to see what precedes "chunked" */
1804
142
    while (--s > line) { 
1805
139
        if (*s != ' ') break;
1806
139
    }
1807
1808
    /* found delim, or leading ws (input wasn't parsed by httpd as a header) */
1809
22
    if (*s == ',' || *s == ' ') { 
1810
4
        return 1;
1811
4
    }
1812
18
    return 0;
1813
22
}
1814
1815
AP_DECLARE(char *) ap_escape_shell_cmd(apr_pool_t *p, const char *str)
1816
1.21k
{
1817
1.21k
    char *cmd;
1818
1.21k
    unsigned char *d;
1819
1.21k
    const unsigned char *s;
1820
1.21k
    apr_size_t len = strlen(str);
1821
1822
1.21k
    ap_assert(len <= (APR_SIZE_MAX - 1) / 2);
1823
1.21k
    cmd = apr_palloc(p, 2 * len + 1);
1824
1.21k
    d = (unsigned char *)cmd;
1825
1.21k
    s = (const unsigned char *)str;
1826
56.2k
    for (; *s; ++s) {
1827
1828
#if defined(OS2) || defined(WIN32)
1829
        /*
1830
         * Newlines to Win32/OS2 CreateProcess() are ill advised.
1831
         * Convert them to spaces since they are effectively white
1832
         * space to most applications
1833
         */
1834
        if (*s == '\r' || *s == '\n') {
1835
             *d++ = ' ';
1836
             continue;
1837
         }
1838
#endif
1839
1840
55.0k
        if (TEST_CHAR(*s, T_ESCAPE_SHELL_CMD)) {
1841
15.9k
            *d++ = '\\';
1842
15.9k
        }
1843
55.0k
        *d++ = *s;
1844
55.0k
    }
1845
1.21k
    *d = '\0';
1846
1847
1.21k
    return cmd;
1848
1.21k
}
1849
1850
static char x2c(const char *what)
1851
504
{
1852
504
    char digit;
1853
1854
504
#if !APR_CHARSET_EBCDIC
1855
504
    digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) - 'A') + 10
1856
504
             : (what[0] - '0'));
1857
504
    digit *= 16;
1858
504
    digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10
1859
504
              : (what[1] - '0'));
1860
#else /*APR_CHARSET_EBCDIC*/
1861
    char xstr[5];
1862
    xstr[0]='0';
1863
    xstr[1]='x';
1864
    xstr[2]=what[0];
1865
    xstr[3]=what[1];
1866
    xstr[4]='\0';
1867
    digit = apr_xlate_conv_byte(ap_hdrs_from_ascii,
1868
                                0xFF & strtol(xstr, NULL, 16));
1869
#endif /*APR_CHARSET_EBCDIC*/
1870
504
    return (digit);
1871
504
}
1872
1873
/*
1874
 * Unescapes a URL, leaving reserved characters intact.
1875
 * Returns 0 on success, non-zero on error
1876
 * Failure is due to
1877
 *   bad % escape       returns HTTP_BAD_REQUEST
1878
 *
1879
 *   decoding %00 or a forbidden character returns HTTP_NOT_FOUND
1880
 */
1881
1882
static int unescape_url(char *url, const char *forbid, const char *reserved,
1883
                        unsigned int flags)
1884
576
{
1885
576
    const int keep_slashes = (flags & AP_UNESCAPE_URL_KEEP_SLASHES) != 0,
1886
576
              forbid_slashes = (flags & AP_UNESCAPE_URL_FORBID_SLASHES) != 0,
1887
576
              keep_unreserved = (flags & AP_UNESCAPE_URL_KEEP_UNRESERVED) != 0;
1888
576
    int badesc, badpath;
1889
576
    char *x, *y;
1890
1891
576
    badesc = 0;
1892
576
    badpath = 0;
1893
1894
576
    if (url == NULL) {
1895
0
        return OK;
1896
0
    }
1897
    /* Initial scan for first '%'. Don't bother writing values before
1898
     * seeing a '%' */
1899
576
    y = strchr(url, '%');
1900
576
    if (y == NULL) {
1901
466
        return OK;
1902
466
    }
1903
3.79k
    for (x = y; *y; ++x, ++y) {
1904
3.68k
        if (*y != '%') {
1905
2.62k
            *x = *y;
1906
2.62k
        }
1907
1.05k
        else {
1908
1.05k
            if (!apr_isxdigit(*(y + 1)) || !apr_isxdigit(*(y + 2))) {
1909
555
                badesc = 1;
1910
555
                *x = '%';
1911
555
            }
1912
504
            else {
1913
504
                char decoded;
1914
504
                decoded = x2c(y + 1);
1915
504
                if ((decoded == '\0')
1916
406
                    || (forbid_slashes && AP_IS_SLASH(decoded))
1917
406
                    || (forbid && ap_strchr_c(forbid, decoded))) {
1918
219
                    badpath = 1;
1919
219
                    *x = decoded;
1920
219
                    y += 2;
1921
219
                }
1922
285
                else if ((keep_unreserved && TEST_CHAR(decoded,
1923
285
                                                       T_URI_UNRESERVED))
1924
285
                         || (keep_slashes && AP_IS_SLASH(decoded))
1925
285
                         || (reserved && ap_strchr_c(reserved, decoded))) {
1926
0
                    *x++ = *y++;
1927
0
                    *x++ = *y++;
1928
0
                    *x = *y;
1929
0
                }
1930
285
                else {
1931
285
                    *x = decoded;
1932
285
                    y += 2;
1933
285
                }
1934
504
            }
1935
1.05k
        }
1936
3.68k
    }
1937
110
    *x = '\0';
1938
110
    if (badesc) {
1939
92
        return HTTP_BAD_REQUEST;
1940
92
    }
1941
18
    else if (badpath) {
1942
8
        return HTTP_NOT_FOUND;
1943
8
    }
1944
10
    else {
1945
10
        return OK;
1946
10
    }
1947
110
}
1948
AP_DECLARE(int) ap_unescape_url(char *url)
1949
309
{
1950
    /* Traditional */
1951
309
    return unescape_url(url, AP_SLASHES, NULL, 0);
1952
309
}
1953
AP_DECLARE(int) ap_unescape_url_keep2f(char *url, int decode_slashes)
1954
0
{
1955
    /* AllowEncodedSlashes (corrected) */
1956
0
    if (decode_slashes) {
1957
        /* no chars reserved */
1958
0
        return unescape_url(url, NULL, NULL, 0);
1959
0
    } else {
1960
        /* reserve (do not decode) encoded slashes */
1961
0
        return unescape_url(url, NULL, AP_SLASHES, 0);
1962
0
    }
1963
0
}
1964
AP_DECLARE(int) ap_unescape_url_ex(char *url, unsigned int flags)
1965
0
{
1966
0
    return unescape_url(url, NULL, NULL, flags);
1967
0
}
1968
1969
#ifdef NEW_APIS
1970
/* IFDEF these out until they've been thought through.
1971
 * Just a germ of an API extension for now
1972
 */
1973
AP_DECLARE(int) ap_unescape_url_proxy(char *url)
1974
{
1975
    /* leave RFC1738 reserved characters intact, * so proxied URLs
1976
     * don't get mangled.  Where does that leave encoded '&' ?
1977
     */
1978
    return unescape_url(url, NULL, "/;?", 0);
1979
}
1980
AP_DECLARE(int) ap_unescape_url_reserved(char *url, const char *reserved)
1981
{
1982
    return unescape_url(url, NULL, reserved);
1983
}
1984
#endif
1985
1986
AP_DECLARE(int) ap_unescape_urlencoded(char *query)
1987
267
{
1988
267
    char *slider;
1989
1990
    /* replace plus with a space */
1991
267
    if (query) {
1992
10.5k
        for (slider = query; *slider; slider++) {
1993
10.2k
            if (*slider == '+') {
1994
134
                *slider = ' ';
1995
134
            }
1996
10.2k
        }
1997
267
    }
1998
1999
    /* unescape everything else */
2000
267
    return unescape_url(query, NULL, NULL, 0);
2001
267
}
2002
2003
AP_DECLARE(char *) ap_construct_server(apr_pool_t *p, const char *hostname,
2004
                                       apr_port_t port, const request_rec *r)
2005
0
{
2006
0
    if (ap_is_default_port(port, r)) {
2007
0
        return apr_pstrdup(p, hostname);
2008
0
    }
2009
0
    else {
2010
0
        return apr_psprintf(p, "%s:%u", hostname, port);
2011
0
    }
2012
0
}
2013
2014
AP_DECLARE(int) ap_unescape_all(char *url)
2015
0
{
2016
0
    return unescape_url(url, NULL, NULL, 0);
2017
0
}
2018
2019
/* c2x takes an unsigned, and expects the caller has guaranteed that
2020
 * 0 <= what < 256... which usually means that you have to cast to
2021
 * unsigned char first, because (unsigned)(char)(x) first goes through
2022
 * signed extension to an int before the unsigned cast.
2023
 *
2024
 * The reason for this assumption is to assist gcc code generation --
2025
 * the unsigned char -> unsigned extension is already done earlier in
2026
 * both uses of this code, so there's no need to waste time doing it
2027
 * again.
2028
 */
2029
static const char c2x_table[] = "0123456789abcdef";
2030
2031
static APR_INLINE unsigned char *c2x(unsigned what, unsigned char prefix,
2032
                                     unsigned char *where)
2033
112k
{
2034
#if APR_CHARSET_EBCDIC
2035
    what = apr_xlate_conv_byte(ap_hdrs_to_ascii, (unsigned char)what);
2036
#endif /*APR_CHARSET_EBCDIC*/
2037
112k
    *where++ = prefix;
2038
112k
    *where++ = c2x_table[what >> 4];
2039
112k
    *where++ = c2x_table[what & 0xf];
2040
112k
    return where;
2041
112k
}
2042
2043
/*
2044
 * escape_path_segment() escapes a path segment, as defined in RFC 1808. This
2045
 * routine is (should be) OS independent.
2046
 *
2047
 * os_escape_path() converts an OS path to a URL, in an OS dependent way. In all
2048
 * cases if a ':' occurs before the first '/' in the URL, the URL should be
2049
 * prefixed with "./" (or the ':' escaped). In the case of Unix, this means
2050
 * leaving '/' alone, but otherwise doing what escape_path_segment() does. For
2051
 * efficiency reasons, we don't use escape_path_segment(), which is provided for
2052
 * reference. Again, RFC 1808 is where this stuff is defined.
2053
 *
2054
 * If partial is set, os_escape_path() assumes that the path will be appended to
2055
 * something with a '/' in it (and thus does not prefix "./").
2056
 */
2057
2058
AP_DECLARE(char *) ap_escape_path_segment_buffer(char *copy, const char *segment)
2059
1.21k
{
2060
1.21k
    const unsigned char *s = (const unsigned char *)segment;
2061
1.21k
    unsigned char *d = (unsigned char *)copy;
2062
1.21k
    unsigned c;
2063
2064
56.2k
    while ((c = *s)) {
2065
55.0k
        if (TEST_CHAR(c, T_ESCAPE_PATH_SEGMENT)) {
2066
28.9k
            d = c2x(c, '%', d);
2067
28.9k
        }
2068
26.0k
        else {
2069
26.0k
            *d++ = c;
2070
26.0k
        }
2071
55.0k
        ++s;
2072
55.0k
    }
2073
1.21k
    *d = '\0';
2074
1.21k
    return copy;
2075
1.21k
}
2076
2077
AP_DECLARE(char *) ap_escape_path_segment(apr_pool_t *p, const char *segment)
2078
0
{
2079
0
    apr_size_t len = strlen(segment);
2080
0
    ap_assert(len <= (APR_SIZE_MAX - 1) / 3);
2081
0
    return ap_escape_path_segment_buffer(apr_palloc(p, 3 * len + 1), segment);
2082
0
}
2083
2084
AP_DECLARE(char *) ap_os_escape_path(apr_pool_t *p, const char *path, int partial)
2085
1.21k
{
2086
    /* Allocate +3 for potential "./" and trailing NULL.
2087
     * Allocate another +1 to allow the caller to add a trailing '/' (see
2088
     * comment in 'ap_sub_req_lookup_dirent')
2089
     */
2090
1.21k
    apr_size_t len = strlen(path);
2091
1.21k
    char *copy;
2092
1.21k
    const unsigned char *s;
2093
1.21k
    unsigned char *d;
2094
1.21k
    unsigned c;
2095
2096
1.21k
    ap_assert(len <= (APR_SIZE_MAX - 4) / 3);
2097
1.21k
    copy = apr_palloc(p, 3 * len + 3 + 1);
2098
1.21k
    s = (const unsigned char *)path;
2099
1.21k
    d = (unsigned char *)copy;
2100
2101
1.21k
    if (!partial) {
2102
1.21k
        const char *colon = ap_strchr_c(path, ':');
2103
1.21k
        const char *slash = ap_strchr_c(path, '/');
2104
2105
1.21k
        if (colon && (!slash || colon < slash)) {
2106
50
            *d++ = '.';
2107
50
            *d++ = '/';
2108
50
        }
2109
1.21k
    }
2110
56.2k
    while ((c = *s)) {
2111
55.0k
        if (TEST_CHAR(c, T_OS_ESCAPE_PATH)) {
2112
27.6k
            d = c2x(c, '%', d);
2113
27.6k
        }
2114
27.3k
        else {
2115
27.3k
            *d++ = c;
2116
27.3k
        }
2117
55.0k
        ++s;
2118
55.0k
    }
2119
1.21k
    *d = '\0';
2120
1.21k
    return copy;
2121
1.21k
}
2122
2123
AP_DECLARE(char *) ap_escape_urlencoded_buffer(char *copy, const char *buffer)
2124
1.21k
{
2125
1.21k
    const unsigned char *s = (const unsigned char *)buffer;
2126
1.21k
    unsigned char *d = (unsigned char *)copy;
2127
1.21k
    unsigned c;
2128
2129
56.2k
    while ((c = *s)) {
2130
55.0k
        if (TEST_CHAR(c, T_ESCAPE_URLENCODED)) {
2131
33.9k
            d = c2x(c, '%', d);
2132
33.9k
        }
2133
21.1k
        else if (c == ' ') {
2134
2.34k
            *d++ = '+';
2135
2.34k
        }
2136
18.7k
        else {
2137
18.7k
            *d++ = c;
2138
18.7k
        }
2139
55.0k
        ++s;
2140
55.0k
    }
2141
1.21k
    *d = '\0';
2142
1.21k
    return copy;
2143
1.21k
}
2144
2145
AP_DECLARE(char *) ap_escape_urlencoded(apr_pool_t *p, const char *buffer)
2146
1.21k
{
2147
1.21k
    apr_size_t len = strlen(buffer);
2148
1.21k
    ap_assert(len <= (APR_SIZE_MAX - 1) / 3);
2149
1.21k
    return ap_escape_urlencoded_buffer(apr_palloc(p, 3 * len + 1), buffer);
2150
1.21k
}
2151
2152
/* ap_escape_uri is now a macro for os_escape_path */
2153
2154
AP_DECLARE(char *) ap_escape_html2(apr_pool_t *p, const char *s, int toasc)
2155
1.21k
{
2156
1.21k
    apr_size_t i, j;
2157
1.21k
    char *x;
2158
2159
    /* first, count the number of extra characters */
2160
56.2k
    for (i = 0, j = 0; s[i] != '\0'; i++) {
2161
55.0k
        if (i + j > APR_SIZE_MAX - 6) {
2162
0
            abort();
2163
0
        }
2164
55.0k
        if (s[i] == '<' || s[i] == '>')
2165
483
            j += 3;
2166
54.5k
        else if (s[i] == '&')
2167
234
            j += 4;
2168
54.2k
        else if (s[i] == '"')
2169
1.42k
            j += 5;
2170
52.8k
        else if (toasc && !apr_isascii(s[i]))
2171
0
            j += 5;
2172
55.0k
    }
2173
2174
1.21k
    if (j == 0)
2175
819
        return apr_pstrmemdup(p, s, i);
2176
2177
398
    x = apr_palloc(p, i + j + 1);
2178
22.0k
    for (i = 0, j = 0; s[i] != '\0'; i++, j++)
2179
21.6k
        if (s[i] == '<') {
2180
295
            memcpy(&x[j], "&lt;", 4);
2181
295
            j += 3;
2182
295
        }
2183
21.3k
        else if (s[i] == '>') {
2184
188
            memcpy(&x[j], "&gt;", 4);
2185
188
            j += 3;
2186
188
        }
2187
21.1k
        else if (s[i] == '&') {
2188
234
            memcpy(&x[j], "&amp;", 5);
2189
234
            j += 4;
2190
234
        }
2191
20.9k
        else if (s[i] == '"') {
2192
1.42k
            memcpy(&x[j], "&quot;", 6);
2193
1.42k
            j += 5;
2194
1.42k
        }
2195
19.5k
        else if (toasc && !apr_isascii(s[i])) {
2196
0
            char *esc = apr_psprintf(p, "&#%3.3d;", (unsigned char)s[i]);
2197
0
            memcpy(&x[j], esc, 6);
2198
0
            j += 5;
2199
0
        }
2200
19.5k
        else
2201
19.5k
            x[j] = s[i];
2202
2203
398
    x[j] = '\0';
2204
398
    return x;
2205
1.21k
}
2206
AP_DECLARE(char *) ap_escape_logitem(apr_pool_t *p, const char *str)
2207
1.21k
{
2208
1.21k
    char *ret;
2209
1.21k
    unsigned char *d;
2210
1.21k
    const unsigned char *s;
2211
1.21k
    apr_size_t length, escapes = 0;
2212
2213
1.21k
    if (!str) {
2214
0
        return NULL;
2215
0
    }
2216
2217
    /* Compute how many characters need to be escaped */
2218
1.21k
    s = (const unsigned char *)str;
2219
56.2k
    for (; *s; ++s) {
2220
55.0k
        if (TEST_CHAR(*s, T_ESCAPE_LOGITEM)) {
2221
23.2k
            escapes++;
2222
23.2k
        }
2223
55.0k
    }
2224
    
2225
    /* Compute the length of the input string, including NULL */
2226
1.21k
    length = s - (const unsigned char *)str + 1;
2227
    
2228
    /* Fast path: nothing to escape */
2229
1.21k
    if (escapes == 0) {
2230
189
        return apr_pmemdup(p, str, length);
2231
189
    }
2232
    
2233
    /* Each escaped character needs up to 3 extra bytes (0 --> \x00) */
2234
1.02k
    ret = apr_palloc(p, length + 3 * escapes);
2235
1.02k
    d = (unsigned char *)ret;
2236
1.02k
    s = (const unsigned char *)str;
2237
51.9k
    for (; *s; ++s) {
2238
50.9k
        if (TEST_CHAR(*s, T_ESCAPE_LOGITEM)) {
2239
23.2k
            *d++ = '\\';
2240
23.2k
            switch(*s) {
2241
319
            case '\b':
2242
319
                *d++ = 'b';
2243
319
                break;
2244
2.40k
            case '\n':
2245
2.40k
                *d++ = 'n';
2246
2.40k
                break;
2247
597
            case '\r':
2248
597
                *d++ = 'r';
2249
597
                break;
2250
2.19k
            case '\t':
2251
2.19k
                *d++ = 't';
2252
2.19k
                break;
2253
374
            case '\v':
2254
374
                *d++ = 'v';
2255
374
                break;
2256
5.03k
            case '\\':
2257
6.46k
            case '"':
2258
6.46k
                *d++ = *s;
2259
6.46k
                break;
2260
10.9k
            default:
2261
10.9k
                c2x(*s, 'x', d);
2262
10.9k
                d += 3;
2263
23.2k
            }
2264
23.2k
        }
2265
27.6k
        else {
2266
27.6k
            *d++ = *s;
2267
27.6k
        }
2268
50.9k
    }
2269
1.02k
    *d = '\0';
2270
2271
1.02k
    return ret;
2272
1.02k
}
2273
2274
AP_DECLARE(apr_size_t) ap_escape_errorlog_item(char *dest, const char *source,
2275
                                               apr_size_t buflen)
2276
1.21k
{
2277
1.21k
    unsigned char *d, *ep;
2278
1.21k
    const unsigned char *s;
2279
2280
1.21k
    if (!source || !buflen) { /* be safe */
2281
0
        return 0;
2282
0
    }
2283
2284
1.21k
    d = (unsigned char *)dest;
2285
1.21k
    s = (const unsigned char *)source;
2286
1.21k
    ep = d + buflen - 1;
2287
2288
56.2k
    for (; d < ep && *s; ++s) {
2289
2290
55.0k
        if (TEST_CHAR(*s, T_ESCAPE_LOGITEM)) {
2291
23.2k
            *d++ = '\\';
2292
23.2k
            if (d >= ep) {
2293
0
                --d;
2294
0
                break;
2295
0
            }
2296
2297
23.2k
            switch(*s) {
2298
319
            case '\b':
2299
319
                *d++ = 'b';
2300
319
                break;
2301
2.40k
            case '\n':
2302
2.40k
                *d++ = 'n';
2303
2.40k
                break;
2304
597
            case '\r':
2305
597
                *d++ = 'r';
2306
597
                break;
2307
2.19k
            case '\t':
2308
2.19k
                *d++ = 't';
2309
2.19k
                break;
2310
374
            case '\v':
2311
374
                *d++ = 'v';
2312
374
                break;
2313
5.03k
            case '\\':
2314
5.03k
                *d++ = *s;
2315
5.03k
                break;
2316
1.42k
            case '"': /* no need for this in error log */
2317
1.42k
                d[-1] = *s;
2318
1.42k
                break;
2319
10.9k
            default:
2320
10.9k
                if (d >= ep - 2) {
2321
0
                    ep = --d; /* break the for loop as well */
2322
0
                    break;
2323
0
                }
2324
10.9k
                c2x(*s, 'x', d);
2325
10.9k
                d += 3;
2326
23.2k
            }
2327
23.2k
        }
2328
31.7k
        else {
2329
31.7k
            *d++ = *s;
2330
31.7k
        }
2331
55.0k
    }
2332
1.21k
    *d = '\0';
2333
2334
1.21k
    return (d - (unsigned char *)dest);
2335
1.21k
}
2336
2337
AP_DECLARE(void) ap_bin2hex(const void *src, apr_size_t srclen, char *dest)
2338
0
{
2339
0
    const unsigned char *in = src;
2340
0
    apr_size_t i;
2341
2342
0
    for (i = 0; i < srclen; i++) {
2343
0
        *dest++ = c2x_table[in[i] >> 4];
2344
0
        *dest++ = c2x_table[in[i] & 0xf];
2345
0
    }
2346
0
    *dest = '\0';
2347
0
}
2348
2349
AP_DECLARE(int) ap_is_directory(apr_pool_t *p, const char *path)
2350
0
{
2351
0
    apr_finfo_t finfo;
2352
2353
0
    if (apr_stat(&finfo, path, APR_FINFO_TYPE, p) != APR_SUCCESS)
2354
0
        return 0;                /* in error condition, just return no */
2355
2356
0
    return (finfo.filetype == APR_DIR);
2357
0
}
2358
2359
AP_DECLARE(int) ap_is_rdirectory(apr_pool_t *p, const char *path)
2360
0
{
2361
0
    apr_finfo_t finfo;
2362
2363
0
    if (apr_stat(&finfo, path, APR_FINFO_LINK | APR_FINFO_TYPE, p) != APR_SUCCESS)
2364
0
        return 0;                /* in error condition, just return no */
2365
2366
0
    return (finfo.filetype == APR_DIR);
2367
0
}
2368
2369
AP_DECLARE(char *) ap_make_full_path(apr_pool_t *a, const char *src1,
2370
                                  const char *src2)
2371
0
{
2372
0
    apr_size_t len1, len2;
2373
0
    char *path;
2374
2375
0
    len1 = strlen(src1);
2376
0
    len2 = strlen(src2);
2377
     /* allocate +3 for '/' delimiter, trailing NULL and overallocate
2378
      * one extra byte to allow the caller to add a trailing '/'
2379
      */
2380
0
    path = (char *)apr_palloc(a, len1 + len2 + 3);
2381
0
    if (len1 == 0) {
2382
0
        *path = '/';
2383
0
        memcpy(path + 1, src2, len2 + 1);
2384
0
    }
2385
0
    else {
2386
0
        char *next;
2387
0
        memcpy(path, src1, len1);
2388
0
        next = path + len1;
2389
0
        if (next[-1] != '/') {
2390
0
            *next++ = '/';
2391
0
        }
2392
0
        memcpy(next, src2, len2 + 1);
2393
0
    }
2394
0
    return path;
2395
0
}
2396
2397
/*
2398
 * Check for an absoluteURI syntax (see section 3.2 in RFC2068).
2399
 */
2400
AP_DECLARE(int) ap_is_url(const char *u)
2401
0
{
2402
0
    int x;
2403
2404
0
    for (x = 0; u[x] != ':'; x++) {
2405
0
        if ((!u[x]) ||
2406
0
            ((!apr_isalnum(u[x])) &&
2407
0
             (u[x] != '+') && (u[x] != '-') && (u[x] != '.'))) {
2408
0
            return 0;
2409
0
        }
2410
0
    }
2411
2412
0
    return (x ? 1 : 0);                /* If the first character is ':', it's broken, too */
2413
0
}
2414
2415
AP_DECLARE(int) ap_ind(const char *s, char c)
2416
0
{
2417
0
    const char *p = ap_strchr_c(s, c);
2418
2419
0
    if (p == NULL)
2420
0
        return -1;
2421
0
    return p - s;
2422
0
}
2423
2424
AP_DECLARE(int) ap_rind(const char *s, char c)
2425
0
{
2426
0
    const char *p = ap_strrchr_c(s, c);
2427
2428
0
    if (p == NULL)
2429
0
        return -1;
2430
0
    return p - s;
2431
0
}
2432
2433
AP_DECLARE(void) ap_str_tolower(char *str)
2434
233
{
2435
8.82k
    while (*str) {
2436
8.59k
        *str = apr_tolower(*str);
2437
8.59k
        ++str;
2438
8.59k
    }
2439
233
}
2440
2441
AP_DECLARE(void) ap_str_toupper(char *str)
2442
0
{
2443
0
    while (*str) {
2444
0
        *str = apr_toupper(*str);
2445
0
        ++str;
2446
0
    }
2447
0
}
2448
2449
/*
2450
 * We must return a FQDN
2451
 */
2452
char *ap_get_local_host(apr_pool_t *a)
2453
0
{
2454
0
#ifndef MAXHOSTNAMELEN
2455
0
#define MAXHOSTNAMELEN 256
2456
0
#endif
2457
0
    char str[MAXHOSTNAMELEN + 1];
2458
0
    char *server_hostname = NULL;
2459
0
    apr_sockaddr_t *sockaddr;
2460
0
    char *hostname;
2461
2462
0
    if (apr_gethostname(str, sizeof(str) - 1, a) != APR_SUCCESS) {
2463
0
        ap_log_perror(APLOG_MARK, APLOG_STARTUP | APLOG_WARNING, 0, a, APLOGNO(00556)
2464
0
                     "%s: apr_gethostname() failed to determine ServerName",
2465
0
                     ap_server_argv0);
2466
0
    } else {
2467
0
        str[sizeof(str) - 1] = '\0';
2468
0
        if (apr_sockaddr_info_get(&sockaddr, str, APR_UNSPEC, 0, 0, a) == APR_SUCCESS) {
2469
0
            if ( (apr_getnameinfo(&hostname, sockaddr, 0) == APR_SUCCESS) &&
2470
0
                (ap_strchr_c(hostname, '.')) ) {
2471
0
                server_hostname = apr_pstrdup(a, hostname);
2472
0
                return server_hostname;
2473
0
            } else if (ap_strchr_c(str, '.')) {
2474
0
                server_hostname = apr_pstrdup(a, str);
2475
0
            } else {
2476
0
                apr_sockaddr_ip_get(&hostname, sockaddr);
2477
0
                server_hostname = apr_pstrdup(a, hostname);
2478
0
            }
2479
0
        } else {
2480
0
            ap_log_perror(APLOG_MARK, APLOG_STARTUP | APLOG_WARNING, 0, a, APLOGNO(00557)
2481
0
                         "%s: apr_sockaddr_info_get() failed for %s",
2482
0
                         ap_server_argv0, str);
2483
0
        }
2484
0
    }
2485
2486
0
    if (!server_hostname)
2487
0
        server_hostname = apr_pstrdup(a, "127.0.0.1");
2488
2489
0
    ap_log_perror(APLOG_MARK, APLOG_ALERT|APLOG_STARTUP, 0, a, APLOGNO(00558)
2490
0
                 "%s: Could not reliably determine the server's fully qualified "
2491
0
                 "domain name, using %s. Set the 'ServerName' directive globally "
2492
0
                 "to suppress this message",
2493
0
                 ap_server_argv0, server_hostname);
2494
2495
0
    return server_hostname;
2496
0
}
2497
2498
/* simple 'pool' alloc()ing glue to apr_base64.c
2499
 */
2500
AP_DECLARE(char *) ap_pbase64decode(apr_pool_t *p, const char *bufcoded)
2501
1.21k
{
2502
1.21k
    char *decoded;
2503
2504
1.21k
    decoded = (char *) apr_palloc(p, apr_base64_decode_len(bufcoded));
2505
1.21k
    apr_base64_decode(decoded, bufcoded);
2506
2507
1.21k
    return decoded;
2508
1.21k
}
2509
2510
/* a stringent version of ap_pbase64decode() */
2511
AP_DECLARE(apr_status_t) ap_pbase64decode_strict(apr_pool_t *p,
2512
                                                 const char *encoded,
2513
                                                 char **decoded,
2514
                                                 apr_size_t *len)
2515
213
{
2516
213
    apr_size_t end_index;
2517
213
    int last_group_len;
2518
213
    const char *end;
2519
2520
    /* Sanity check.
2521
     * TODO: this would be a lot more efficient if we had access to the lookup
2522
     * table used by APR. If that gets pulled in at any point, make use of it.
2523
     */
2524
213
    end_index = strspn(encoded, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2525
213
                                "abcdefghijklmnopqrstuvwxyz"
2526
213
                                "0123456789+/");
2527
2528
213
    last_group_len = end_index % 4;
2529
213
    end = encoded + end_index;
2530
2531
    /* The only non-alphabet character allowed is the padding character '=' at
2532
     * the end of the string. There are two allowable padding cases for the last
2533
     * group of four: "xY==" or "xyZ=". We require the final (non-padding)
2534
     * character to have been zero-padded during encoding, which limits the
2535
     * character choices.
2536
     */
2537
213
    if (last_group_len == 1) {
2538
        /* This isn't ever valid. */
2539
15
        return APR_EINVAL;
2540
15
    }
2541
198
    else if (last_group_len == 2) {
2542
        /* ...xY== */
2543
33
        if (*end != '=' || end[1] != '=') {
2544
31
            return APR_EINVAL;
2545
31
        }
2546
2
        else if (!ap_strchr("AQgw", end[-1])) {
2547
            /* Correctly zero-padded input data will result in a final character
2548
             * that is one of the four above. */
2549
1
            return APR_EINVAL;
2550
1
        }
2551
2552
1
        end += 2;
2553
1
    }
2554
165
    else if (last_group_len == 3) {
2555
        /* ...xyZ= */
2556
24
        if (*end != '=') {
2557
21
            return APR_EINVAL;
2558
21
        }
2559
3
        else if (!ap_strchr("AEIMQUYcgkosw048", end[-1])) {
2560
            /* Correctly zero-padded input data will result in a final character
2561
             * that is one of the sixteen above. */
2562
1
            return APR_EINVAL;
2563
1
        }
2564
2565
2
        end++;
2566
2
    }
2567
2568
    /* At this point, if the encoded buffer is correct, we should be at the end
2569
     * of the string. */
2570
144
    if (*end) {
2571
112
        return APR_EINVAL;
2572
112
    }
2573
2574
32
    *decoded = apr_palloc(p, apr_base64_decode_len(encoded));
2575
32
    *len = apr_base64_decode(*decoded, encoded);
2576
2577
32
    return APR_SUCCESS;
2578
144
}
2579
2580
AP_DECLARE(char *) ap_pbase64encode(apr_pool_t *p, char *string)
2581
1.21k
{
2582
1.21k
    char *encoded;
2583
1.21k
    int l = strlen(string);
2584
2585
1.21k
    encoded = (char *) apr_palloc(p, apr_base64_encode_len(l));
2586
1.21k
    apr_base64_encode(encoded, string, l);
2587
2588
1.21k
    return encoded;
2589
1.21k
}
2590
2591
/* we want to downcase the type/subtype for comparison purposes
2592
 * but nothing else because ;parameter=foo values are case sensitive.
2593
 * XXX: in truth we want to downcase parameter names... but really,
2594
 * apache has never handled parameters and such correctly.  You
2595
 * also need to compress spaces and such to be able to compare
2596
 * properly. -djg
2597
 */
2598
AP_DECLARE(void) ap_content_type_tolower(char *str)
2599
233
{
2600
233
    char *semi;
2601
2602
233
    semi = strchr(str, ';');
2603
233
    if (semi) {
2604
9
        *semi = '\0';
2605
9
    }
2606
2607
233
    ap_str_tolower(str);
2608
2609
233
    if (semi) {
2610
9
        *semi = ';';
2611
9
    }
2612
233
}
2613
2614
/*
2615
 * Given a string, replace any bare " with \" .
2616
 */
2617
AP_DECLARE(char *) ap_escape_quotes(apr_pool_t *p, const char *instring)
2618
1.21k
{
2619
1.21k
    apr_size_t size, extra = 0;
2620
1.21k
    const char *inchr = instring;
2621
1.21k
    char *outchr, *outstring;
2622
2623
    /*
2624
     * Look through the input string, jogging the length of the output
2625
     * string up by an extra byte each time we find an unescaped ".
2626
     */
2627
52.7k
    while (*inchr != '\0') {
2628
51.5k
        if (*inchr == '"') {
2629
1.26k
            extra++;
2630
1.26k
        }
2631
        /*
2632
         * If we find a slosh, and it's not the last byte in the string,
2633
         * it's escaping something - advance past both bytes.
2634
         */
2635
50.3k
        else if ((*inchr == '\\') && (inchr[1] != '\0')) {
2636
3.43k
            inchr++;
2637
3.43k
        }
2638
51.5k
        inchr++;
2639
51.5k
    }
2640
2641
1.21k
    if (!extra) {
2642
929
        return apr_pstrdup(p, instring);
2643
929
    }
2644
2645
    /* How large will the string become, once we escaped all the quotes?
2646
     * The tricky cases are
2647
     * - an `instring` that is already longer than `ptrdiff_t`
2648
     *   can hold (which is an undefined case in C, as C defines ptrdiff_t as
2649
     *   a signed difference between pointers into the same array and one index
2650
     *   beyond).
2651
     * - an `instring` that, including the `extra` chars we want to add, becomes
2652
     *   even larger than apr_size_t can handle.
2653
     * Since this function was not designed to ever return NULL for failure, we
2654
     * can only trigger a hard assertion failure. It seems more a programming
2655
     * mistake (or failure to verify the input causing this) that leads to this
2656
     * situation.
2657
     */
2658
288
    ap_assert(inchr - instring > 0);
2659
288
    size = ((apr_size_t)(inchr - instring)) + 1;
2660
288
    ap_assert(size + extra > size);
2661
2662
288
    outstring = apr_palloc(p, size + extra);
2663
288
    inchr = instring;
2664
288
    outchr = outstring;
2665
    /*
2666
     * Now copy the input string to the output string, inserting a slosh
2667
     * in front of every " that doesn't already have one.
2668
     */
2669
14.5k
    while (*inchr != '\0') {
2670
14.2k
        if (*inchr == '"') {
2671
1.26k
            *outchr++ = '\\';
2672
1.26k
        }
2673
12.9k
        else if ((*inchr == '\\') && (inchr[1] != '\0')) {
2674
991
            *outchr++ = *inchr++;
2675
991
        }
2676
14.2k
        *outchr++ = *inchr++;
2677
14.2k
    }
2678
288
    *outchr = '\0';
2679
288
    return outstring;
2680
288
}
2681
2682
/*
2683
 * Given a string, append the PID deliminated by delim.
2684
 * Usually used to create a pid-appended filepath name
2685
 * (eg: /a/b/foo -> /a/b/foo.6726). A function, and not
2686
 * a macro, to avoid unistd.h dependency
2687
 */
2688
AP_DECLARE(char *) ap_append_pid(apr_pool_t *p, const char *string,
2689
                                    const char *delim)
2690
0
{
2691
0
    return apr_psprintf(p, "%s%s%" APR_PID_T_FMT, string,
2692
0
                        delim, getpid());
2693
2694
0
}
2695
2696
/**
2697
 * Parse a given timeout parameter string into an apr_interval_time_t value.
2698
 * The unit of the time interval is given as postfix string to the numeric
2699
 * string. Currently the following units are understood (case insensitive):
2700
 *
2701
 * ms    : milliseconds
2702
 * s     : seconds
2703
 * mi[n] : minutes
2704
 * h     : hours
2705
 *
2706
 * If no unit is contained in the given timeout parameter the default_time_unit
2707
 * will be used instead.
2708
 * @param timeout_parameter The string containing the timeout parameter.
2709
 * @param timeout The timeout value to be returned.
2710
 * @param default_time_unit The default time unit to use if none is specified
2711
 * in timeout_parameter.
2712
 * @return Status value indicating whether the parsing was successful or not.
2713
 */
2714
419
#define CHECK_OVERFLOW(a, b) if (a > b) return APR_EGENERAL
2715
AP_DECLARE(apr_status_t) ap_timeout_parameter_parse(
2716
                                               const char *timeout_parameter,
2717
                                               apr_interval_time_t *timeout,
2718
                                               const char *default_time_unit)
2719
1.21k
{
2720
1.21k
    char *endp;
2721
1.21k
    const char *time_str;
2722
1.21k
    apr_int64_t tout;
2723
1.21k
    apr_uint64_t check;
2724
2725
1.21k
    tout = apr_strtoi64(timeout_parameter, &endp, 10);
2726
1.21k
    if (errno) {
2727
4
        return errno;
2728
4
    }
2729
1.21k
    if (!endp || !*endp) {
2730
116
        time_str = default_time_unit;
2731
116
    }
2732
1.09k
    else {
2733
1.09k
        time_str = endp;
2734
1.09k
    }
2735
2736
1.21k
    if (tout < 0) { 
2737
75
        return APR_EGENERAL;
2738
75
    }
2739
2740
1.13k
    switch (*time_str) {
2741
        /* Time is in seconds */
2742
73
    case 's':
2743
111
    case 'S':
2744
111
        CHECK_OVERFLOW(tout, apr_time_sec(APR_INT64_MAX));
2745
65
        check = apr_time_from_sec(tout);
2746
65
        break;
2747
        /* Time is in hours */
2748
41
    case 'h':
2749
96
    case 'H':
2750
96
        CHECK_OVERFLOW(tout, apr_time_sec(APR_INT64_MAX / 3600));
2751
43
        check = apr_time_from_sec(tout * 3600);
2752
43
        break;
2753
121
    case 'm':
2754
219
    case 'M':
2755
219
        switch (*(++time_str)) {
2756
        /* Time is in milliseconds */
2757
109
        case 's':
2758
114
        case 'S':
2759
114
            CHECK_OVERFLOW(tout, apr_time_as_msec(APR_INT64_MAX));
2760
86
            check = apr_time_from_msec(tout);
2761
86
            break;
2762
        /* Time is in minutes */
2763
32
        case 'i':
2764
98
        case 'I':
2765
98
            CHECK_OVERFLOW(tout, apr_time_sec(APR_INT64_MAX / 60));
2766
48
            check = apr_time_from_sec(tout * 60);
2767
48
            break;
2768
7
        default:
2769
7
            return APR_EGENERAL;
2770
219
        }
2771
134
        break;
2772
712
    default:
2773
712
        return APR_EGENERAL;
2774
1.13k
    }
2775
2776
242
    *timeout = (apr_interval_time_t)check;
2777
242
    return APR_SUCCESS;
2778
1.13k
}
2779
2780
AP_DECLARE(apr_status_t) ap_size_parameter_parse(const char *parameter,
2781
                                                 apr_off_t *value)
2782
0
{
2783
    /* The maximum apr_off_t value. */
2784
0
    const apr_off_t off_max = sizeof(apr_off_t) == 8 ? APR_INT64_MAX
2785
0
                                                     : APR_INT32_MAX;
2786
0
    apr_off_t parsed, multiplier = 1;
2787
0
    apr_status_t rv;
2788
0
    char *end;
2789
2790
    /* Check for no conversion before the status: some libc implementations
2791
     * set EINVAL when no digits are present. */
2792
0
    rv = apr_strtoff(&parsed, parameter, &end, 10);
2793
0
    if (end == parameter) {
2794
0
        return APR_EINVAL;
2795
0
    }
2796
0
    if (rv != APR_SUCCESS) {
2797
0
        return APR_ERANGE;
2798
0
    }
2799
2800
0
    if (*end == 'k' || *end == 'K') {
2801
0
        multiplier = 1024;
2802
0
        end++;
2803
0
    }
2804
0
    else if (*end == 'm' || *end == 'M') {
2805
0
        multiplier = 1024 * 1024;
2806
0
        end++;
2807
0
    }
2808
0
    else if (*end == 'g' || *end == 'G') {
2809
0
        multiplier = 1024 * 1024 * 1024;
2810
0
        end++;
2811
0
    }
2812
0
    else if (*end == 'b' || *end == 'B') {
2813
0
        end++;
2814
0
    }
2815
0
    if (*end != '\0') {
2816
0
        return APR_EINVAL;
2817
0
    }
2818
2819
0
    if (parsed > off_max / multiplier
2820
0
        || parsed < (-off_max - 1) / multiplier) {
2821
0
        return APR_ERANGE;
2822
0
    }
2823
2824
0
    *value = parsed * multiplier;
2825
0
    return APR_SUCCESS;
2826
0
}
2827
#undef CHECK_OVERFLOW
2828
2829
AP_DECLARE(int) ap_parse_strict_length(apr_off_t *len, const char *str)
2830
0
{
2831
0
    char *end;
2832
2833
0
    return (apr_isdigit(*str)
2834
0
            && apr_strtoff(len, str, &end, 10) == APR_SUCCESS
2835
0
            && *end == '\0');
2836
0
}
2837
2838
/**
2839
 * Determine if a request has a request body or not.
2840
 *
2841
 * @param r the request_rec of the request
2842
 * @return truth value
2843
 */
2844
AP_DECLARE(int) ap_request_has_body(request_rec *r)
2845
0
{
2846
0
    apr_off_t cl;
2847
0
    const char *cls;
2848
2849
0
    return (!r->header_only
2850
0
            && (r->kept_body
2851
0
                || apr_table_get(r->headers_in, "Transfer-Encoding")
2852
0
                || ((cls = apr_table_get(r->headers_in, "Content-Length"))
2853
0
                    && ap_parse_strict_length(&cl, cls) && cl > 0)));
2854
0
}
2855
2856
/**
2857
 * Check whether a request is tainted by exposure to something
2858
 * potentially untrusted.  
2859
 *
2860
 */
2861
AP_DECLARE(int) ap_request_tainted(request_rec *r, int flags)
2862
0
{
2863
    /** Potential future: a hook or callback here could serve modules
2864
     *  like mod_security and ironbee with more complex needs.
2865
     */
2866
0
    return r && ((r->taint&flags)
2867
0
                 || ap_request_tainted(r->main, flags)
2868
0
                 || ap_request_tainted(r->prev, flags));
2869
0
}
2870
2871
AP_DECLARE_NONSTD(apr_status_t) ap_pool_cleanup_set_null(void *data_)
2872
0
{
2873
0
    void **ptr = (void **)data_;
2874
0
    *ptr = NULL;
2875
0
    return APR_SUCCESS;
2876
0
}
2877
2878
1.21k
AP_DECLARE(apr_status_t) ap_str2_alnum(const char *src, char *dest) {
2879
2880
56.2k
    for ( ; *src; src++, dest++)
2881
55.0k
    {
2882
55.0k
        if (!apr_isprint(*src))
2883
16.8k
            *dest = 'x';
2884
38.1k
        else if (!apr_isalnum(*src))
2885
22.0k
            *dest = '_';
2886
16.1k
        else
2887
16.1k
            *dest = (char)*src;
2888
55.0k
    }
2889
1.21k
    *dest = '\0';
2890
1.21k
    return APR_SUCCESS;
2891
2892
1.21k
}
2893
2894
AP_DECLARE(apr_status_t) ap_pstr2_alnum(apr_pool_t *p, const char *src,
2895
                                        const char **dest)
2896
1.21k
{
2897
1.21k
    char *new = apr_palloc(p, strlen(src)+1);
2898
1.21k
    if (!new)
2899
0
        return APR_ENOMEM;
2900
1.21k
    *dest = new;
2901
1.21k
    return ap_str2_alnum(src, new);
2902
1.21k
}
2903
2904
/**
2905
 * Read the body and parse any form found, which must be of the
2906
 * type application/x-www-form-urlencoded.
2907
 *
2908
 * Name/value pairs are returned in an array, with the names as
2909
 * strings with a maximum length of HUGE_STRING_LEN, and the
2910
 * values as bucket brigades. This allows values to be arbitrarily
2911
 * large.
2912
 *
2913
 * All url-encoding is removed from both the names and the values
2914
 * on the fly. The names are interpreted as strings, while the
2915
 * values are interpreted as blocks of binary data, that may
2916
 * contain the 0 character.
2917
 *
2918
 * In order to ensure that resource limits are not exceeded, a
2919
 * maximum size must be provided. If the sum of the lengths of
2920
 * the names and the values exceed this size, this function
2921
 * will return HTTP_REQUEST_ENTITY_TOO_LARGE.
2922
 *
2923
 * An optional number of parameters can be provided, if the number
2924
 * of parameters provided exceeds this amount, this function will
2925
 * return HTTP_REQUEST_ENTITY_TOO_LARGE. If this value is negative,
2926
 * no limit is imposed, and the number of parameters is in turn
2927
 * constrained by the size parameter above.
2928
 *
2929
 * This function honours any kept_body configuration, and the
2930
 * original raw request body will be saved to the kept_body brigade
2931
 * if so configured, just as ap_discard_request_body does.
2932
 *
2933
 * NOTE: File upload is not yet supported, but can be without change
2934
 * to the function call.
2935
 */
2936
2937
/* form parsing stuff */
2938
typedef enum {
2939
    FORM_NORMAL,
2940
    FORM_AMP,
2941
    FORM_NAME,
2942
    FORM_VALUE,
2943
    FORM_PERCENTA,
2944
    FORM_PERCENTB,
2945
    FORM_ABORT
2946
} ap_form_type_t;
2947
2948
AP_DECLARE(int) ap_parse_form_data(request_rec *r, ap_filter_t *f,
2949
                                   apr_array_header_t **ptr,
2950
                                   apr_size_t num, apr_size_t usize)
2951
0
{
2952
0
    apr_bucket_brigade *bb = NULL;
2953
0
    int seen_eos = 0;
2954
0
    char buffer[HUGE_STRING_LEN + 1];
2955
0
    const char *ct;
2956
0
    apr_size_t offset = 0;
2957
0
    apr_ssize_t size;
2958
0
    ap_form_type_t state = FORM_NAME, percent = FORM_NORMAL;
2959
0
    ap_form_pair_t *pair = NULL;
2960
0
    apr_array_header_t *pairs = apr_array_make(r->pool, 4, sizeof(ap_form_pair_t));
2961
0
    char escaped_char[2] = { 0 };
2962
2963
0
    *ptr = pairs;
2964
2965
    /* sanity check - we only support forms for now */
2966
0
    ct = apr_table_get(r->headers_in, "Content-Type");
2967
0
    if (!ct || ap_cstr_casecmpn("application/x-www-form-urlencoded", ct, 33)) {
2968
0
        return ap_discard_request_body(r);
2969
0
    }
2970
2971
0
    if (usize > APR_SIZE_MAX >> 1)
2972
0
        size = APR_SIZE_MAX >> 1;
2973
0
    else
2974
0
        size = usize;
2975
2976
0
    if (!f) {
2977
0
        f = r->input_filters;
2978
0
    }
2979
2980
0
    bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
2981
0
    do {
2982
0
        apr_bucket *bucket = NULL, *last = NULL;
2983
2984
0
        int rv = ap_get_brigade(f, bb, AP_MODE_READBYTES,
2985
0
                                APR_BLOCK_READ, HUGE_STRING_LEN);
2986
0
        if (rv != APR_SUCCESS) {
2987
0
            apr_brigade_destroy(bb);
2988
0
            return ap_map_http_request_error(rv, HTTP_BAD_REQUEST);
2989
0
        }
2990
2991
0
        for (bucket = APR_BRIGADE_FIRST(bb);
2992
0
             bucket != APR_BRIGADE_SENTINEL(bb);
2993
0
             last = bucket, bucket = APR_BUCKET_NEXT(bucket)) {
2994
0
            const char *data;
2995
0
            apr_size_t len, slide;
2996
2997
0
            if (last) {
2998
0
                apr_bucket_delete(last);
2999
0
            }
3000
0
            if (APR_BUCKET_IS_EOS(bucket)) {
3001
0
                seen_eos = 1;
3002
0
                break;
3003
0
            }
3004
0
            if (bucket->length == 0) {
3005
0
                continue;
3006
0
            }
3007
3008
0
            rv = apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
3009
0
            if (rv != APR_SUCCESS) {
3010
0
                apr_brigade_destroy(bb);
3011
0
                return HTTP_BAD_REQUEST;
3012
0
            }
3013
3014
0
            slide = len;
3015
0
            while (state != FORM_ABORT && slide-- > 0 && size >= 0 && num != 0) {
3016
0
                char c = *data++;
3017
0
                if ('+' == c) {
3018
0
                    c = ' ';
3019
0
                }
3020
0
                else if ('&' == c) {
3021
0
                    state = FORM_AMP;
3022
0
                }
3023
0
                if ('%' == c) {
3024
0
                    percent = FORM_PERCENTA;
3025
0
                    continue;
3026
0
                }
3027
0
                if (FORM_PERCENTA == percent) {
3028
0
                    escaped_char[0] = c;
3029
0
                    percent = FORM_PERCENTB;
3030
0
                    continue;
3031
0
                }
3032
0
                if (FORM_PERCENTB == percent) {
3033
0
                    escaped_char[1] = c;
3034
0
                    c = x2c(escaped_char);
3035
0
                    percent = FORM_NORMAL;
3036
0
                }
3037
0
                switch (state) {
3038
0
                    case FORM_AMP:
3039
0
                        if (pair) {
3040
0
                            const char *tmp = apr_pmemdup(r->pool, buffer, offset);
3041
0
                            apr_bucket *b = apr_bucket_pool_create(tmp, offset, r->pool, r->connection->bucket_alloc);
3042
0
                            APR_BRIGADE_INSERT_TAIL(pair->value, b);
3043
0
                        }
3044
0
                        state = FORM_NAME;
3045
0
                        pair = NULL;
3046
0
                        offset = 0;
3047
0
                        num--;
3048
0
                        break;
3049
0
                    case FORM_NAME:
3050
0
                        if (offset < HUGE_STRING_LEN) {
3051
0
                            if ('=' == c) {
3052
0
                                pair = (ap_form_pair_t *) apr_array_push(pairs);
3053
0
                                pair->name = apr_pstrmemdup(r->pool, buffer, offset);
3054
0
                                pair->value = apr_brigade_create(r->pool, r->connection->bucket_alloc);
3055
0
                                state = FORM_VALUE;
3056
0
                                offset = 0;
3057
0
                            }
3058
0
                            else {
3059
0
                                buffer[offset++] = c;
3060
0
                                size--;
3061
0
                            }
3062
0
                        }
3063
0
                        else {
3064
0
                            state = FORM_ABORT;
3065
0
                        }
3066
0
                        break;
3067
0
                    case FORM_VALUE:
3068
0
                        if (offset >= HUGE_STRING_LEN) {
3069
0
                            const char *tmp = apr_pmemdup(r->pool, buffer, offset);
3070
0
                            apr_bucket *b = apr_bucket_pool_create(tmp, offset, r->pool, r->connection->bucket_alloc);
3071
0
                            APR_BRIGADE_INSERT_TAIL(pair->value, b);
3072
0
                            offset = 0;
3073
0
                        }
3074
0
                        buffer[offset++] = c;
3075
0
                        size--;
3076
0
                        break;
3077
0
                    default:
3078
0
                        break;
3079
0
                }
3080
0
            }
3081
3082
0
        }
3083
3084
0
        apr_brigade_cleanup(bb);
3085
0
    } while (!seen_eos);
3086
3087
0
    if (FORM_ABORT == state || size < 0 || num == 0) {
3088
0
        return HTTP_REQUEST_ENTITY_TOO_LARGE;
3089
0
    }
3090
0
    else if (FORM_VALUE == state && pair && offset > 0) {
3091
0
        const char *tmp = apr_pmemdup(r->pool, buffer, offset);
3092
0
        apr_bucket *b = apr_bucket_pool_create(tmp, offset, r->pool, r->connection->bucket_alloc);
3093
0
        APR_BRIGADE_INSERT_TAIL(pair->value, b);
3094
0
    }
3095
3096
0
    return OK;
3097
3098
0
}
3099
3100
0
#define VARBUF_SMALL_SIZE 2048
3101
0
#define VARBUF_MAX_SIZE   (APR_SIZE_MAX - 1 -                                \
3102
0
                           APR_ALIGN_DEFAULT(sizeof(struct ap_varbuf_info)))
3103
3104
struct ap_varbuf_info {
3105
    struct apr_memnode_t *node;
3106
    apr_allocator_t *allocator;
3107
};
3108
3109
static apr_status_t varbuf_cleanup(void *info_)
3110
0
{
3111
0
    struct ap_varbuf_info *info = info_;
3112
0
    info->node->next = NULL;
3113
0
    apr_allocator_free(info->allocator, info->node);
3114
0
    return APR_SUCCESS;
3115
0
}
3116
3117
static const char nul = '\0';
3118
static char * const varbuf_empty = (char *)&nul;
3119
3120
AP_DECLARE(void) ap_varbuf_init(apr_pool_t *p, struct ap_varbuf *vb,
3121
                                apr_size_t init_size)
3122
0
{
3123
0
    vb->buf = varbuf_empty;
3124
0
    vb->avail = 0;
3125
0
    vb->strlen = AP_VARBUF_UNKNOWN;
3126
0
    vb->pool = p;
3127
0
    vb->info = NULL;
3128
3129
0
    ap_varbuf_grow(vb, init_size);
3130
0
}
3131
3132
AP_DECLARE(void) ap_varbuf_grow(struct ap_varbuf *vb, apr_size_t new_len)
3133
0
{
3134
0
    apr_memnode_t *new_node = NULL;
3135
0
    apr_allocator_t *allocator;
3136
0
    struct ap_varbuf_info *new_info;
3137
0
    char *new;
3138
3139
0
    AP_DEBUG_ASSERT(vb->strlen == AP_VARBUF_UNKNOWN || vb->avail >= vb->strlen);
3140
3141
0
    if (new_len <= vb->avail)
3142
0
        return;
3143
3144
0
    if (new_len < 2 * vb->avail && vb->avail < VARBUF_MAX_SIZE/2) {
3145
        /* at least double the size, to avoid repeated reallocations */
3146
0
        new_len = 2 * vb->avail;
3147
0
    }
3148
0
    else if (new_len > VARBUF_MAX_SIZE) {
3149
0
        apr_abortfunc_t abort_fn = apr_pool_abort_get(vb->pool);
3150
0
        ap_assert(abort_fn != NULL);
3151
0
        abort_fn(APR_ENOMEM);
3152
0
        return;
3153
0
    }
3154
3155
0
    new_len++;  /* add space for trailing \0 */
3156
0
    if (new_len <= VARBUF_SMALL_SIZE) {
3157
0
        new_len = APR_ALIGN_DEFAULT(new_len);
3158
0
        new = apr_palloc(vb->pool, new_len);
3159
0
        if (vb->avail && vb->strlen != 0) {
3160
0
            AP_DEBUG_ASSERT(vb->buf != NULL);
3161
0
            AP_DEBUG_ASSERT(vb->buf != varbuf_empty);
3162
0
            if (new == vb->buf + vb->avail + 1) {
3163
                /* We are lucky: the new memory lies directly after our old
3164
                 * buffer, we can now use both.
3165
                 */
3166
0
                vb->avail += new_len;
3167
0
                return;
3168
0
            }
3169
0
            else {
3170
                /* copy up to vb->strlen + 1 bytes */
3171
0
                memcpy(new, vb->buf, vb->strlen == AP_VARBUF_UNKNOWN ?
3172
0
                                     vb->avail + 1 : vb->strlen + 1);
3173
0
            }
3174
0
        }
3175
0
        else {
3176
0
            *new = '\0';
3177
0
        }
3178
0
        vb->avail = new_len - 1;
3179
0
        vb->buf = new;
3180
0
        return;
3181
0
    }
3182
3183
    /* The required block is rather larger. Use allocator directly so that
3184
     * the memory can be freed independently from the pool. */
3185
0
    allocator = apr_pool_allocator_get(vb->pool);
3186
    /* Happens if APR was compiled with APR_POOL_DEBUG */
3187
0
    if (allocator == NULL) {
3188
0
        apr_allocator_create(&allocator);
3189
0
        ap_assert(allocator != NULL);
3190
0
    }
3191
0
    if (new_len <= VARBUF_MAX_SIZE)
3192
0
        new_node = apr_allocator_alloc(allocator,
3193
0
                                       new_len + APR_ALIGN_DEFAULT(sizeof(*new_info)));
3194
0
    if (!new_node) {
3195
0
        apr_abortfunc_t abort_fn = apr_pool_abort_get(vb->pool);
3196
0
        ap_assert(abort_fn != NULL);
3197
0
        abort_fn(APR_ENOMEM);
3198
0
        return;
3199
0
    }
3200
0
    new_info = (struct ap_varbuf_info *)new_node->first_avail;
3201
0
    new_node->first_avail += APR_ALIGN_DEFAULT(sizeof(*new_info));
3202
0
    new_info->node = new_node;
3203
0
    new_info->allocator = allocator;
3204
0
    new = new_node->first_avail;
3205
0
    AP_DEBUG_ASSERT(new_node->endp - new_node->first_avail >= new_len);
3206
0
    new_len = new_node->endp - new_node->first_avail;
3207
3208
0
    if (vb->avail && vb->strlen != 0)
3209
0
        memcpy(new, vb->buf, vb->strlen == AP_VARBUF_UNKNOWN ?
3210
0
                             vb->avail + 1 : vb->strlen + 1);
3211
0
    else
3212
0
        *new = '\0';
3213
0
    if (vb->info)
3214
0
        apr_pool_cleanup_run(vb->pool, vb->info, varbuf_cleanup);
3215
0
    apr_pool_cleanup_register(vb->pool, new_info, varbuf_cleanup,
3216
0
                              apr_pool_cleanup_null);
3217
0
    vb->info = new_info;
3218
0
    vb->buf = new;
3219
0
    vb->avail = new_len - 1;
3220
0
}
3221
3222
AP_DECLARE(void) ap_varbuf_strmemcat(struct ap_varbuf *vb, const char *str,
3223
                                     int len)
3224
0
{
3225
0
    if (len == 0)
3226
0
        return;
3227
0
    if (!vb->avail) {
3228
0
        ap_varbuf_grow(vb, len);
3229
0
        memcpy(vb->buf, str, len);
3230
0
        vb->buf[len] = '\0';
3231
0
        vb->strlen = len;
3232
0
        return;
3233
0
    }
3234
0
    if (vb->strlen == AP_VARBUF_UNKNOWN)
3235
0
        vb->strlen = strlen(vb->buf);
3236
0
    ap_varbuf_grow(vb, vb->strlen + len);
3237
0
    memcpy(vb->buf + vb->strlen, str, len);
3238
0
    vb->strlen += len;
3239
0
    vb->buf[vb->strlen] = '\0';
3240
0
}
3241
3242
AP_DECLARE(void) ap_varbuf_free(struct ap_varbuf *vb)
3243
0
{
3244
0
    if (vb->info) {
3245
0
        apr_pool_cleanup_run(vb->pool, vb->info, varbuf_cleanup);
3246
0
        vb->info = NULL;
3247
0
    }
3248
0
    vb->buf = NULL;
3249
0
}
3250
3251
AP_DECLARE(char *) ap_varbuf_pdup(apr_pool_t *p, struct ap_varbuf *buf,
3252
                                  const char *prepend, apr_size_t prepend_len,
3253
                                  const char *append, apr_size_t append_len,
3254
                                  apr_size_t *new_len)
3255
0
{
3256
0
    apr_size_t i = 0;
3257
0
    struct iovec vec[3];
3258
3259
0
    if (prepend) {
3260
0
        vec[i].iov_base = (void *)prepend;
3261
0
        vec[i].iov_len = prepend_len;
3262
0
        i++;
3263
0
    }
3264
0
    if (buf->avail && buf->strlen) {
3265
0
        if (buf->strlen == AP_VARBUF_UNKNOWN)
3266
0
            buf->strlen = strlen(buf->buf);
3267
0
        vec[i].iov_base = (void *)buf->buf;
3268
0
        vec[i].iov_len = buf->strlen;
3269
0
        i++;
3270
0
    }
3271
0
    if (append) {
3272
0
        vec[i].iov_base = (void *)append;
3273
0
        vec[i].iov_len = append_len;
3274
0
        i++;
3275
0
    }
3276
0
    if (i)
3277
0
        return apr_pstrcatv(p, vec, i, new_len);
3278
3279
0
    if (new_len)
3280
0
        *new_len = 0;
3281
0
    return "";
3282
0
}
3283
3284
AP_DECLARE(apr_status_t) ap_varbuf_regsub(struct ap_varbuf *vb,
3285
                                          const char *input,
3286
                                          const char *source,
3287
                                          apr_size_t nmatch,
3288
                                          ap_regmatch_t pmatch[],
3289
                                          apr_size_t maxlen)
3290
0
{
3291
0
    return regsub_core(NULL, NULL, vb, input, source, nmatch, pmatch, maxlen);
3292
0
}
3293
3294
static const char * const oom_message = "[crit] Memory allocation failed, "
3295
                                        "aborting process." APR_EOL_STR;
3296
3297
AP_DECLARE(void) ap_abort_on_oom(void)
3298
0
{
3299
0
    int written, count = strlen(oom_message);
3300
0
    const char *buf = oom_message;
3301
0
    do {
3302
0
        written = write(STDERR_FILENO, buf, count);
3303
0
        if (written == count)
3304
0
            break;
3305
0
        if (written > 0) {
3306
0
            buf += written;
3307
0
            count -= written;
3308
0
        }
3309
0
    } while (written >= 0 || errno == EINTR);
3310
0
    abort();
3311
0
}
3312
3313
AP_DECLARE(void *) ap_malloc(size_t size)
3314
0
{
3315
0
    void *p = malloc(size);
3316
0
    if (p == NULL && size != 0)
3317
0
        ap_abort_on_oom();
3318
0
    return p;
3319
0
}
3320
3321
AP_DECLARE(void *) ap_calloc(size_t nelem, size_t size)
3322
0
{
3323
0
    void *p = calloc(nelem, size);
3324
0
    if (p == NULL && nelem != 0 && size != 0)
3325
0
        ap_abort_on_oom();
3326
0
    return p;
3327
0
}
3328
3329
AP_DECLARE(void *) ap_realloc(void *ptr, size_t size)
3330
0
{
3331
0
    void *p = realloc(ptr, size);
3332
0
    if (p == NULL && size != 0)
3333
0
        ap_abort_on_oom();
3334
0
    return p;
3335
0
}
3336
3337
#if APR_HAS_THREADS
3338
3339
#if AP_HAS_THREAD_LOCAL && !APR_VERSION_AT_LEAST(1,8,0)
3340
static AP_THREAD_LOCAL apr_thread_t *current_thread = NULL;
3341
#endif
3342
3343
struct thread_ctx {
3344
    apr_thread_start_t func;
3345
    void *data;
3346
};
3347
3348
static void *APR_THREAD_FUNC thread_start(apr_thread_t *thread, void *data)
3349
0
{
3350
0
    struct thread_ctx *ctx = data;
3351
3352
    /* Don't let the thread's pool allocator with no limits, though there
3353
     * is possibly no allocator with APR <= 1.7 and APR_POOL_DEBUG.
3354
     */
3355
0
    {
3356
0
        apr_pool_t *tp = apr_thread_pool_get(thread);
3357
0
        apr_allocator_t *ta = apr_pool_allocator_get(tp);
3358
0
        if (ta) {
3359
0
            apr_allocator_max_free_set(ta, ap_max_mem_free);
3360
0
        }
3361
0
    }
3362
3363
#if AP_HAS_THREAD_LOCAL && !APR_VERSION_AT_LEAST(1,8,0)
3364
    current_thread = thread;
3365
#endif
3366
0
    return ctx->func(thread, ctx->data);
3367
0
}
3368
3369
AP_DECLARE(apr_status_t) ap_thread_create(apr_thread_t **thread, 
3370
                                          apr_threadattr_t *attr, 
3371
                                          apr_thread_start_t func, 
3372
                                          void *data, apr_pool_t *pool)
3373
0
{
3374
0
    struct thread_ctx *ctx = apr_palloc(pool, sizeof(*ctx));
3375
3376
0
    ctx->func = func;
3377
0
    ctx->data = data;
3378
0
    return apr_thread_create(thread, attr, thread_start, ctx, pool);
3379
0
}
3380
3381
static apr_status_t main_thread_cleanup(void *arg)
3382
0
{
3383
0
    apr_thread_t *thd = arg;
3384
0
    apr_pool_destroy(apr_thread_pool_get(thd));
3385
0
    return APR_SUCCESS;
3386
0
}
3387
3388
AP_DECLARE(apr_status_t) ap_thread_main_create(apr_thread_t **thread,
3389
                                               apr_pool_t *pool)
3390
0
{
3391
0
    apr_status_t rv;
3392
0
    apr_threadattr_t *attr = NULL;
3393
3394
    /* Create an apr_thread_t for the main child thread to set up its Thread
3395
     * Local Storage. Since it's detached and won't apr_thread_exit(), destroy
3396
     * its pool before exiting via a cleanup of the given pool.
3397
     */
3398
0
    if ((rv = apr_threadattr_create(&attr, pool))
3399
0
            || (rv = apr_threadattr_detach_set(attr, 1))
3400
0
#if APR_VERSION_AT_LEAST(1,8,0)
3401
0
            || (rv = apr_threadattr_max_free_set(attr, ap_max_mem_free))
3402
0
#endif
3403
0
            || (rv = ap_thread_current_create(thread, attr, pool))) {
3404
0
        *thread = NULL;
3405
0
        return rv;
3406
0
    }
3407
3408
0
    apr_pool_cleanup_register(pool, *thread, main_thread_cleanup,
3409
0
                              apr_pool_cleanup_null);
3410
0
    return APR_SUCCESS;
3411
0
}
3412
3413
#if !APR_VERSION_AT_LEAST(1,8,0)
3414
3415
AP_DECLARE(apr_status_t) ap_thread_current_create(apr_thread_t **current,
3416
                                                  apr_threadattr_t *attr,
3417
                                                  apr_pool_t *pool)
3418
{
3419
#if AP_HAS_THREAD_LOCAL
3420
    apr_status_t rv;
3421
    apr_allocator_t *ta;
3422
    apr_abortfunc_t abort_fn;
3423
    apr_os_thread_t osthd;
3424
    apr_pool_t *p;
3425
3426
    *current = ap_thread_current();
3427
    if (*current) {
3428
        return APR_EEXIST;
3429
    }
3430
3431
    abort_fn = (pool) ? apr_pool_abort_get(pool) : NULL;
3432
    rv = apr_allocator_create(&ta);
3433
    if (rv != APR_SUCCESS) {
3434
        if (abort_fn)
3435
            abort_fn(rv);
3436
        return rv;
3437
    }
3438
    /* Don't let the thread's pool allocator with no limits */
3439
    apr_allocator_max_free_set(ta, ap_max_mem_free);
3440
    rv = apr_pool_create_unmanaged_ex(&p, abort_fn, ta);
3441
    if (rv != APR_SUCCESS) {
3442
        return rv;
3443
    }
3444
    apr_allocator_owner_set(ta, p);
3445
3446
    osthd = apr_os_thread_current();
3447
    rv = apr_os_thread_put(current, &osthd, p);
3448
    if (rv != APR_SUCCESS) {
3449
        apr_pool_destroy(p);
3450
        return rv;
3451
    }
3452
3453
    current_thread = *current;
3454
    return APR_SUCCESS;
3455
#else
3456
    return APR_ENOTIMPL;
3457
#endif
3458
}
3459
3460
AP_DECLARE(void) ap_thread_current_after_fork(void)
3461
{
3462
#if AP_HAS_THREAD_LOCAL
3463
    current_thread = NULL;
3464
#endif
3465
}
3466
3467
AP_DECLARE(apr_thread_t *) ap_thread_current(void)
3468
{
3469
#if AP_HAS_THREAD_LOCAL
3470
    return current_thread;
3471
#else
3472
    return NULL;
3473
#endif
3474
}
3475
3476
#endif /* !APR_VERSION_AT_LEAST(1,8,0) */
3477
3478
#endif /* APR_HAS_THREADS */
3479
3480
AP_DECLARE(void) ap_get_sload(ap_sload_t *ld)
3481
0
{
3482
0
    int i, j, server_limit, thread_limit;
3483
0
    int ready = 0;
3484
0
    int busy = 0;
3485
0
    int total;
3486
0
    ap_generation_t mpm_generation;
3487
3488
    /* preload errored fields, we overwrite */
3489
0
    ld->idle = -1;
3490
0
    ld->busy = -1;
3491
0
    ld->bytes_served = 0;
3492
0
    ld->access_count = 0;
3493
3494
0
    ap_mpm_query(AP_MPMQ_GENERATION, &mpm_generation);
3495
0
    ap_mpm_query(AP_MPMQ_HARD_LIMIT_THREADS, &thread_limit);
3496
0
    ap_mpm_query(AP_MPMQ_HARD_LIMIT_DAEMONS, &server_limit);
3497
3498
0
    for (i = 0; i < server_limit; i++) {
3499
0
        process_score *ps;
3500
0
        ps = ap_get_scoreboard_process(i);
3501
3502
0
        for (j = 0; j < thread_limit; j++) {
3503
0
            int res;
3504
0
            worker_score *ws = NULL;
3505
0
            ws = &ap_scoreboard_image->servers[i][j];
3506
0
            res = ws->status;
3507
3508
0
            if (!ps->quiescing && ps->pid) {
3509
0
                if (res == SERVER_READY && ps->generation == mpm_generation) {
3510
0
                    ready++;
3511
0
                }
3512
0
                else if (res != SERVER_DEAD &&
3513
0
                         res != SERVER_STARTING && res != SERVER_IDLE_KILL &&
3514
0
                         ps->generation == mpm_generation) {
3515
0
                    busy++;
3516
0
                }   
3517
0
            }
3518
3519
0
            if (ap_extended_status && !ps->quiescing && ps->pid) {
3520
0
                if (ws->access_count != 0 
3521
0
                    || (res != SERVER_READY && res != SERVER_DEAD)) {
3522
0
                    ld->access_count += ws->access_count;
3523
0
                    ld->bytes_served += ws->bytes_served;
3524
0
                }
3525
0
            }
3526
0
        }
3527
0
    }
3528
0
    total = busy + ready;
3529
0
    if (total) {
3530
0
        ld->idle = ready * 100 / total;
3531
0
        ld->busy = busy * 100 / total;
3532
0
    }
3533
0
}
3534
3535
AP_DECLARE(void) ap_get_loadavg(ap_loadavg_t *ld)
3536
0
{
3537
    /* preload errored fields, we overwrite */
3538
0
    ld->loadavg = -1.0;
3539
0
    ld->loadavg5 = -1.0;
3540
0
    ld->loadavg15 = -1.0;
3541
3542
0
#if HAVE_GETLOADAVG
3543
0
    {
3544
0
        double la[3];
3545
0
        int num;
3546
3547
0
        num = getloadavg(la, 3);
3548
0
        if (num > 0) {
3549
0
            ld->loadavg = (float)la[0];
3550
0
        }
3551
0
        if (num > 1) {
3552
0
            ld->loadavg5 = (float)la[1];
3553
0
        }
3554
0
        if (num > 2) {
3555
0
            ld->loadavg15 = (float)la[2];
3556
0
        }
3557
0
    }
3558
0
#endif
3559
0
}
3560
3561
static const char * const pw_cache_note_name = "conn_cache_note";
3562
struct pw_cache {
3563
    /* varbuf contains concatenated password and hash */
3564
    struct ap_varbuf vb;
3565
    apr_size_t pwlen;
3566
    apr_status_t result;
3567
};
3568
3569
AP_DECLARE(apr_status_t) ap_password_validate(request_rec *r,
3570
                                              const char *username,
3571
                                              const char *passwd,
3572
                                              const char *hash)
3573
0
{
3574
0
    struct pw_cache *cache;
3575
0
    apr_size_t hashlen;
3576
3577
0
    cache = (struct pw_cache *)apr_table_get(r->connection->notes, pw_cache_note_name);
3578
0
    if (cache != NULL) {
3579
0
        if (strncmp(passwd, cache->vb.buf, cache->pwlen) == 0
3580
0
            && strcmp(hash, cache->vb.buf + cache->pwlen) == 0) {
3581
0
            return cache->result;
3582
0
        }
3583
        /* make ap_varbuf_grow below not copy the old data */
3584
0
        cache->vb.strlen = 0;
3585
0
    }
3586
0
    else {
3587
0
        cache = apr_palloc(r->connection->pool, sizeof(struct pw_cache));
3588
0
        ap_varbuf_init(r->connection->pool, &cache->vb, 0);
3589
0
        apr_table_setn(r->connection->notes, pw_cache_note_name, (void *)cache);
3590
0
    }
3591
0
    cache->pwlen = strlen(passwd);
3592
0
    hashlen = strlen(hash);
3593
0
    ap_varbuf_grow(&cache->vb, cache->pwlen + hashlen + 1);
3594
0
    memcpy(cache->vb.buf, passwd, cache->pwlen);
3595
0
    memcpy(cache->vb.buf + cache->pwlen, hash, hashlen + 1);
3596
0
    cache->result = apr_password_validate(passwd, hash);
3597
0
    return cache->result;
3598
0
}
3599
3600
AP_DECLARE(char *) ap_get_exec_line(apr_pool_t *p,
3601
                                    const char *cmd,
3602
                                    const char * const * argv)
3603
0
{
3604
0
    char buf[MAX_STRING_LEN];
3605
0
    apr_procattr_t *procattr;
3606
0
    apr_proc_t *proc;
3607
0
    apr_file_t *fp;
3608
0
    apr_size_t nbytes = 1;
3609
0
    char c;
3610
0
    int k;
3611
3612
0
    if (apr_procattr_create(&procattr, p) != APR_SUCCESS)
3613
0
        return NULL;
3614
0
    if (apr_procattr_io_set(procattr, APR_FULL_BLOCK, APR_FULL_BLOCK,
3615
0
                            APR_FULL_BLOCK) != APR_SUCCESS)
3616
0
        return NULL;
3617
0
    if (apr_procattr_dir_set(procattr,
3618
0
                             ap_make_dirstr_parent(p, cmd)) != APR_SUCCESS)
3619
0
        return NULL;
3620
0
    if (apr_procattr_cmdtype_set(procattr, APR_PROGRAM) != APR_SUCCESS)
3621
0
        return NULL;
3622
0
    proc = apr_pcalloc(p, sizeof(apr_proc_t));
3623
0
    if (apr_proc_create(proc, cmd, argv, NULL, procattr, p) != APR_SUCCESS)
3624
0
        return NULL;
3625
0
    fp = proc->out;
3626
3627
0
    if (fp == NULL)
3628
0
        return NULL;
3629
    /* XXX: we are reading 1 byte at a time here */
3630
0
    for (k = 0; apr_file_read(fp, &c, &nbytes) == APR_SUCCESS
3631
0
                && nbytes == 1 && (k < MAX_STRING_LEN-1)     ; ) {
3632
0
        if (c == '\n' || c == '\r')
3633
0
            break;
3634
0
        buf[k++] = c;
3635
0
    }
3636
0
    buf[k] = '\0'; 
3637
0
    apr_file_close(fp);
3638
3639
0
    return apr_pstrndup(p, buf, k);
3640
0
}
3641
3642
AP_DECLARE(int) ap_array_str_index(const apr_array_header_t *array, 
3643
                                   const char *s,
3644
                                   int start)
3645
0
{
3646
0
    if (start >= 0) {
3647
0
        int i;
3648
        
3649
0
        for (i = start; i < array->nelts; i++) {
3650
0
            const char *p = APR_ARRAY_IDX(array, i, const char *);
3651
0
            if (!strcmp(p, s)) {
3652
0
                return i;
3653
0
            }
3654
0
        }
3655
0
    }
3656
    
3657
0
    return -1;
3658
0
}
3659
3660
AP_DECLARE(int) ap_array_str_contains(const apr_array_header_t *array, 
3661
                                      const char *s)
3662
0
{
3663
0
    return (ap_array_str_index(array, s, 0) >= 0);
3664
0
}
3665
3666
#if !APR_CHARSET_EBCDIC
3667
/*
3668
 * Our own known-fast translation table for casecmp by character.
3669
 * Only ASCII alpha characters 41-5A are folded to 61-7A, other
3670
 * octets (such as extended latin alphabetics) are never case-folded.
3671
 * NOTE: Other than Alpha A-Z/a-z, each code point is unique!
3672
 */
3673
static const unsigned char ucharmap[256] = {
3674
    0x0,  0x1,  0x2,  0x3,  0x4,  0x5,  0x6,  0x7,
3675
    0x8,  0x9,  0xa,  0xb,  0xc,  0xd,  0xe,  0xf,
3676
    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
3677
    0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
3678
    0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
3679
    0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
3680
    0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
3681
    0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
3682
    0x40,  'a',  'b',  'c',  'd',  'e',  'f',  'g',
3683
     'h',  'i',  'j',  'k',  'l',  'm',  'n',  'o',
3684
     'p',  'q',  'r',  's',  't',  'u',  'v',  'w',
3685
     'x',  'y',  'z', 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
3686
    0x60,  'a',  'b',  'c',  'd',  'e',  'f',  'g',
3687
     'h',  'i',  'j',  'k',  'l',  'm',  'n',  'o',
3688
     'p',  'q',  'r',  's',  't',  'u',  'v',  'w',
3689
     'x',  'y',  'z', 0x7b, 0x7c, 0x7d, 0x7e, 0x7f,
3690
    0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
3691
    0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
3692
    0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
3693
    0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
3694
    0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
3695
    0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
3696
    0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
3697
    0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
3698
    0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
3699
    0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
3700
    0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
3701
    0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
3702
    0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
3703
    0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
3704
    0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
3705
    0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
3706
};
3707
#else /* APR_CHARSET_EBCDIC */
3708
/*
3709
 * Derived from apr-iconv/ccs/cp037.c for EBCDIC case comparison,
3710
 * provides unique identity of every char value (strict ISO-646
3711
 * conformance, arbitrary election of an ISO-8859-1 ordering, and
3712
 * very arbitrary control code assignments into C1 to achieve
3713
 * identity and a reversible mapping of code points),
3714
 * then folding the equivalences of ASCII 41-5A into 61-7A, 
3715
 * presenting comparison results in a somewhat ISO/IEC 10646
3716
 * (ASCII-like) order, depending on the EBCDIC code page in use.
3717
 *
3718
 * NOTE: Other than Alpha A-Z/a-z, each code point is unique!
3719
 */
3720
static const unsigned char ucharmap[256] = {
3721
    0x00, 0x01, 0x02, 0x03, 0x9C, 0x09, 0x86, 0x7F,
3722
    0x97, 0x8D, 0x8E, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
3723
    0x10, 0x11, 0x12, 0x13, 0x9D, 0x85, 0x08, 0x87,
3724
    0x18, 0x19, 0x92, 0x8F, 0x1C, 0x1D, 0x1E, 0x1F,
3725
    0x80, 0x81, 0x82, 0x83, 0x84, 0x0A, 0x17, 0x1B,
3726
    0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x05, 0x06, 0x07,
3727
    0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04,
3728
    0x98, 0x99, 0x9A, 0x9B, 0x14, 0x15, 0x9E, 0x1A,
3729
    0x20, 0xA0, 0xE2, 0xE4, 0xE0, 0xE1, 0xE3, 0xE5,
3730
    0xE7, 0xF1, 0xA2, 0x2E, 0x3C, 0x28, 0x2B, 0x7C,
3731
    0x26, 0xE9, 0xEA, 0xEB, 0xE8, 0xED, 0xEE, 0xEF,
3732
    0xEC, 0xDF, 0x21, 0x24, 0x2A, 0x29, 0x3B, 0xAC,
3733
    0x2D, 0x2F, 0xC2, 0xC4, 0xC0, 0xC1, 0xC3, 0xC5,
3734
    0xC7, 0xD1, 0xA6, 0x2C, 0x25, 0x5F, 0x3E, 0x3F,
3735
    0xF8, 0xC9, 0xCA, 0xCB, 0xC8, 0xCD, 0xCE, 0xCF,
3736
    0xCC, 0x60, 0x3A, 0x23, 0x40, 0x27, 0x3D, 0x22,
3737
    0xD8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
3738
    0x68, 0x69, 0xAB, 0xBB, 0xF0, 0xFD, 0xFE, 0xB1,
3739
    0xB0, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70,
3740
    0x71, 0x72, 0xAA, 0xBA, 0xE6, 0xB8, 0xC6, 0xA4,
3741
    0xB5, 0x7E, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
3742
    0x79, 0x7A, 0xA1, 0xBF, 0xD0, 0xDD, 0xDE, 0xAE,
3743
    0x5E, 0xA3, 0xA5, 0xB7, 0xA9, 0xA7, 0xB6, 0xBC,
3744
    0xBD, 0xBE, 0x5B, 0x5D, 0xAF, 0xA8, 0xB4, 0xD7,
3745
    0x7B, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
3746
    0x68, 0x69, 0xAD, 0xF4, 0xF6, 0xF2, 0xF3, 0xF5,
3747
    0x7D, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70,
3748
    0x71, 0x72, 0xB9, 0xFB, 0xFC, 0xF9, 0xFA, 0xFF,
3749
    0x5C, 0xF7, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
3750
    0x79, 0x7A, 0xB2, 0xD4, 0xD6, 0xD2, 0xD3, 0xD5,
3751
    0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
3752
    0x38, 0x39, 0xB3, 0xDB, 0xDC, 0xD9, 0xDA, 0x9F
3753
};
3754
#endif
3755
3756
AP_DECLARE(char *) ap_cstr_stripws(char *str)
3757
1.01k
{
3758
1.01k
    char *end = str + strlen(str);
3759
3760
1.48k
    while (end > str && apr_isspace(end[-1])) {
3761
474
        --end;
3762
474
    }
3763
1.01k
    *end = '\0';
3764
3765
1.01k
    return end;
3766
1.01k
}
3767
3768
AP_DECLARE(int) ap_cstr_casecmp(const char *s1, const char *s2)
3769
2.83k
{
3770
2.83k
    const unsigned char *u1 = (const unsigned char *)s1;
3771
2.83k
    const unsigned char *u2 = (const unsigned char *)s2;
3772
3.38k
    for (;;) {
3773
3.38k
        const int c2 = ucharmap[*u2++];
3774
3.38k
        const int cmp = (int)ucharmap[*u1++] - c2;
3775
        /* Not necessary to test for !c1, this is caught by cmp */
3776
3.38k
        if (cmp || !c2)
3777
2.83k
            return cmp;
3778
3.38k
    }
3779
2.83k
}
3780
3781
AP_DECLARE(int) ap_cstr_casecmpn(const char *s1, const char *s2, apr_size_t n)
3782
6.17k
{
3783
6.17k
    const unsigned char *u1 = (const unsigned char *)s1;
3784
6.17k
    const unsigned char *u2 = (const unsigned char *)s2;
3785
8.77k
    while (n--) {
3786
8.63k
        const int c2 = ucharmap[*u2++];
3787
8.63k
        const int cmp = (int)ucharmap[*u1++] - c2;
3788
        /* Not necessary to test for !c1, this is caught by cmp */
3789
8.63k
        if (cmp || !c2)
3790
6.02k
            return cmp;
3791
8.63k
    }
3792
143
    return 0;
3793
6.17k
}
3794
3795
typedef struct {
3796
    const char *fname;
3797
} fnames;
3798
3799
static int fname_alphasort(const void *fn1, const void *fn2)
3800
0
{
3801
0
    const fnames *f1 = fn1;
3802
0
    const fnames *f2 = fn2;
3803
3804
0
    return strcmp(f1->fname, f2->fname);
3805
0
}
3806
3807
AP_DECLARE(ap_dir_match_t *)ap_dir_cfgmatch(cmd_parms *cmd, int flags,
3808
        const char *(*cb)(ap_dir_match_t *w, const char *fname), void *ctx)
3809
0
{
3810
0
    ap_dir_match_t *w = apr_palloc(cmd->temp_pool, sizeof(*w));
3811
3812
0
    w->prefix = apr_pstrcat(cmd->pool, cmd->cmd->name, ": ", NULL);
3813
0
    w->p = cmd->pool;
3814
0
    w->ptemp = cmd->temp_pool;
3815
0
    w->flags = flags;
3816
0
    w->cb = cb;
3817
0
    w->ctx = ctx;
3818
0
    w->depth = 0;
3819
3820
0
    return w;
3821
0
}
3822
3823
AP_DECLARE(const char *)ap_dir_nofnmatch(ap_dir_match_t *w, const char *fname)
3824
0
{
3825
0
    const char *error;
3826
0
    apr_status_t rv;
3827
3828
0
    if ((w->flags & AP_DIR_FLAG_RECURSIVE) && ap_is_directory(w->ptemp, fname)) {
3829
0
        apr_dir_t *dirp;
3830
0
        apr_finfo_t dirent;
3831
0
        int current;
3832
0
        apr_array_header_t *candidates = NULL;
3833
0
        fnames *fnew;
3834
0
        char *path = apr_pstrdup(w->ptemp, fname);
3835
3836
0
        if (++w->depth > AP_MAX_FNMATCH_DIR_DEPTH) {
3837
0
            return apr_psprintf(w->p, "%sDirectory '%s' exceeds the maximum include "
3838
0
                    "directory nesting level of %u. You have "
3839
0
                    "probably a recursion somewhere.", w->prefix ? w->prefix : "", path,
3840
0
                    AP_MAX_FNMATCH_DIR_DEPTH);
3841
0
        }
3842
3843
        /*
3844
         * first course of business is to grok all the directory
3845
         * entries here and store 'em away. Recall we need full pathnames
3846
         * for this.
3847
         */
3848
0
        rv = apr_dir_open(&dirp, path, w->ptemp);
3849
0
        if (rv != APR_SUCCESS) {
3850
0
            return apr_psprintf(w->p, "%sCould not open directory %s: %pm",
3851
0
                    w->prefix ? w->prefix : "", path, &rv);
3852
0
        }
3853
3854
0
        candidates = apr_array_make(w->ptemp, 1, sizeof(fnames));
3855
0
        while (apr_dir_read(&dirent, APR_FINFO_DIRENT, dirp) == APR_SUCCESS) {
3856
            /* strip out '.' and '..' */
3857
0
            if (strcmp(dirent.name, ".")
3858
0
                && strcmp(dirent.name, "..")) {
3859
0
                fnew = (fnames *) apr_array_push(candidates);
3860
0
                fnew->fname = ap_make_full_path(w->ptemp, path, dirent.name);
3861
0
            }
3862
0
        }
3863
3864
0
        apr_dir_close(dirp);
3865
0
        if (candidates->nelts != 0) {
3866
0
            qsort((void *) candidates->elts, candidates->nelts,
3867
0
                  sizeof(fnames), fname_alphasort);
3868
3869
            /*
3870
             * Now recurse these... we handle errors and subdirectories
3871
             * via the recursion, which is nice
3872
             */
3873
0
            for (current = 0; current < candidates->nelts; ++current) {
3874
0
                fnew = &((fnames *) candidates->elts)[current];
3875
0
                error = ap_dir_nofnmatch(w, fnew->fname);
3876
0
                if (error) {
3877
0
                    return error;
3878
0
                }
3879
0
            }
3880
0
        }
3881
3882
0
        w->depth--;
3883
3884
0
        return NULL;
3885
0
    }
3886
0
    else if (w->flags & AP_DIR_FLAG_OPTIONAL) {
3887
        /* If the optional flag is set (like for IncludeOptional) we can
3888
         * tolerate that no file or directory is present and bail out.
3889
         */
3890
0
        apr_finfo_t finfo;
3891
0
        if (apr_stat(&finfo, fname, APR_FINFO_TYPE, w->ptemp) != APR_SUCCESS
3892
0
            || finfo.filetype == APR_NOFILE)
3893
0
            return NULL;
3894
0
    }
3895
3896
0
    return w->cb(w, fname);
3897
0
}
3898
3899
AP_DECLARE(const char *)ap_dir_fnmatch(ap_dir_match_t *w, const char *path,
3900
        const char *fname)
3901
0
{
3902
0
    const char *rest;
3903
0
    apr_status_t rv;
3904
0
    apr_dir_t *dirp;
3905
0
    apr_finfo_t dirent;
3906
0
    apr_array_header_t *candidates = NULL;
3907
0
    fnames *fnew;
3908
0
    int current;
3909
3910
    /* find the first part of the filename */
3911
0
    rest = ap_strchr_c(fname, '/');
3912
0
    if (rest) {
3913
0
        fname = apr_pstrmemdup(w->ptemp, fname, rest - fname);
3914
0
        rest++;
3915
0
    }
3916
3917
    /* optimisation - if the filename isn't a wildcard, process it directly */
3918
0
    if (!apr_fnmatch_test(fname)) {
3919
0
        path = path ? ap_make_full_path(w->ptemp, path, fname) : fname;
3920
0
        if (!rest) {
3921
0
            return ap_dir_nofnmatch(w, path);
3922
0
        }
3923
0
        else {
3924
0
            return ap_dir_fnmatch(w, path, rest);
3925
0
        }
3926
0
    }
3927
3928
    /*
3929
     * first course of business is to grok all the directory
3930
     * entries here and store 'em away. Recall we need full pathnames
3931
     * for this.
3932
     */
3933
0
    rv = apr_dir_open(&dirp, path, w->ptemp);
3934
0
    if (rv != APR_SUCCESS) {
3935
        /* If the directory doesn't exist and the optional flag is set
3936
         * there is no need to return an error.
3937
         */
3938
0
        if (rv == APR_ENOENT && (w->flags & AP_DIR_FLAG_OPTIONAL)) {
3939
0
            return NULL;
3940
0
        }
3941
0
        return apr_psprintf(w->p, "%sCould not open directory %s: %pm",
3942
0
                w->prefix ? w->prefix : "", path, &rv);
3943
0
    }
3944
3945
0
    candidates = apr_array_make(w->ptemp, 1, sizeof(fnames));
3946
0
    while (apr_dir_read(&dirent, APR_FINFO_DIRENT | APR_FINFO_TYPE, dirp) == APR_SUCCESS) {
3947
        /* strip out '.' and '..' */
3948
0
        if (strcmp(dirent.name, ".")
3949
0
            && strcmp(dirent.name, "..")
3950
0
            && (apr_fnmatch(fname, dirent.name,
3951
0
                            APR_FNM_PERIOD) == APR_SUCCESS)) {
3952
0
            const char *full_path = ap_make_full_path(w->ptemp, path, dirent.name);
3953
            /* If matching internal to path, and we happen to match something
3954
             * other than a directory, skip it
3955
             */
3956
0
            if (rest && (dirent.filetype != APR_DIR)) {
3957
0
                continue;
3958
0
            }
3959
0
            fnew = (fnames *) apr_array_push(candidates);
3960
0
            fnew->fname = full_path;
3961
0
        }
3962
0
    }
3963
3964
0
    apr_dir_close(dirp);
3965
0
    if (candidates->nelts != 0) {
3966
0
        const char *error;
3967
3968
0
        qsort((void *) candidates->elts, candidates->nelts,
3969
0
              sizeof(fnames), fname_alphasort);
3970
3971
        /*
3972
         * Now recurse these... we handle errors and subdirectories
3973
         * via the recursion, which is nice
3974
         */
3975
0
        for (current = 0; current < candidates->nelts; ++current) {
3976
0
            fnew = &((fnames *) candidates->elts)[current];
3977
0
            if (!rest) {
3978
0
                error = ap_dir_nofnmatch(w, fnew->fname);
3979
0
            }
3980
0
            else {
3981
0
                error = ap_dir_fnmatch(w, fnew->fname, rest);
3982
0
            }
3983
0
            if (error) {
3984
0
                return error;
3985
0
            }
3986
0
        }
3987
0
    }
3988
0
    else {
3989
3990
0
        if (!(w->flags & AP_DIR_FLAG_OPTIONAL)) {
3991
0
            return apr_psprintf(w->p, "%sNo matches for the wildcard '%s' in '%s', failing",
3992
0
                    w->prefix ? w->prefix : "", fname, path);
3993
0
        }
3994
0
    }
3995
3996
0
    return NULL;
3997
0
}
3998
3999
4000
#if APR_VERSION_AT_LEAST(1,8,0)
4001
AP_DECLARE(int) ap_memeq_timingsafe(const void *buf1, const void *buf2,
4002
                                     apr_size_t n)
4003
0
{
4004
0
    return apr_memeq_timingsafe(buf1, buf2, n);
4005
0
}
4006
4007
AP_DECLARE(int) ap_streq_timingsafe(const char *sec1, const char *str2)
4008
0
{
4009
0
    return apr_streq_timingsafe(sec1, str2);
4010
0
}
4011
4012
AP_DECLARE(int) ap_strneq_timingsafe(const char *sec1, const char *str2,
4013
                                      apr_size_t n)
4014
0
{
4015
0
    return apr_strneq_timingsafe(sec1, str2, n);
4016
0
}
4017
4018
#else /* !APR_VERSION_AT_LEAST(1,8,0) */
4019
4020
/* A volatile variable which is always zero but allows to block the compiler
4021
 * from optimizing or eliding code using it. Volatile forces the compiler to
4022
 * emit a memory load for which no value can be assumed, so for instance an
4023
 * add/sub/xor/or with "optblocker" is a noop that will hide the result to
4024
 * the optimizer.
4025
 */
4026
static volatile const apr_uint32_t optblocker;
4027
4028
/* Return whether x is not zero, with no branching controlled by x.
4029
 *
4030
 * Taken from the cryptoint library (public domain) by D. J. Bernstein,
4031
 * which provides timing attacks safe integer operations/primitives.
4032
 * Code:
4033
 *   https://lib.mceliece.org/libmceliece-20250507/cryptoint/crypto_uint32.h
4034
 * Paper:
4035
 *   https://cr.yp.to/papers/cryptoint-20250424.pdf
4036
 */
4037
#if __has_attribute(always_inline)
4038
__attribute__((always_inline))
4039
#endif
4040
static APR_INLINE int test_nonzero_timingsafe(apr_uint32_t x)
4041
{
4042
    x |= -x; /* sets the most significant bit unless x == 0 */
4043
4044
    /* shift bit 31 (MSB) to bit 0 */
4045
    x >>= 32-6;      /* keep 6 bits */
4046
    x += optblocker; /* lose the optimizer */
4047
    x >>= 5;         /* keep the (original) MSB only */
4048
4049
    /* x is now 0 or 1 */
4050
    return x & INT_MAX;
4051
}
4052
4053
AP_DECLARE(int) ap_memeq_timingsafe(const void *buf1, const void *buf2,
4054
                                     apr_size_t n)
4055
{
4056
    apr_uint32_t diff = 0;
4057
    volatile apr_size_t count = n; /* prevent loop unrolling */
4058
    apr_size_t i = 0;
4059
4060
    for (; i < count; ++i) {
4061
        const unsigned char c1 = ((volatile const unsigned char *)buf1)[i];
4062
        const unsigned char c2 = ((volatile const unsigned char *)buf2)[i];
4063
4064
        diff |= c1 ^ c2; /* sets diff to non-zero whenever c1 != c2 */
4065
    }
4066
4067
    /* (diff == 0) <=> (diff != 0) ^ 1 */
4068
    return test_nonzero_timingsafe(diff) ^ 1;
4069
}
4070
4071
AP_DECLARE(int) ap_streq_timingsafe(const char *sec1, const char *str2)
4072
{
4073
    apr_uint32_t diff = 0;
4074
    apr_size_t i1 = 0, i2 = 0;
4075
4076
    for (;; ++i2) {
4077
        const unsigned char c1 = ((volatile const unsigned char *)sec1)[i1];
4078
        const unsigned char c2 = ((volatile const unsigned char *)str2)[i2];
4079
4080
        diff |= c1 ^ c2; /* sets diff to non-zero whenever c1 != c2 */
4081
4082
        /* Not a shortest/longest match because an attacker would usually know
4083
         * one of the strings and could then determine the length of the other.
4084
         * So assume only sec1 and its length are secret and stop the loop at
4085
         * the end of str2. If sec1 is shorter than str2 the loop will continue
4086
         * by comparing the rest of str2 with the trailing NUL byte of sec1.
4087
         * In any case since the diff above is computed up to and including a
4088
         * NUL byte, only the same content and length will raise match.
4089
         */
4090
        if (!c2) {
4091
            break;
4092
        }
4093
4094
        /* Don't go above sec1's NUL byte */
4095
        i1 += test_nonzero_timingsafe(c1);
4096
    }
4097
4098
    /* (diff == 0) <=> (diff != 0) ^ 1 */
4099
    return test_nonzero_timingsafe(diff) ^ 1;
4100
}
4101
4102
AP_DECLARE(int) ap_strneq_timingsafe(const char *sec1, const char *str2,
4103
                                     apr_size_t n)
4104
{
4105
    apr_uint32_t diff = 0;
4106
    volatile apr_size_t count = n; /* prevent loop unrolling */
4107
    apr_size_t i1 = 0, i2 = 0;
4108
4109
    for (; i2 < count; ++i2) {
4110
        const unsigned char c1 = ((volatile const unsigned char *)sec1)[i1];
4111
        const unsigned char c2 = ((volatile const unsigned char *)str2)[i2];
4112
4113
        diff |= c1 ^ c2; /* sets diff to non-zero whenever c1 != c2 */
4114
4115
        /* Not a shortest/longest match because an attacker would usually know
4116
         * one of the strings and could then determine the length of the other.
4117
         * So assume only sec1 and its length are secret and stop the loop at
4118
         * the end of str2. If sec1 is shorter than str2 the loop will continue
4119
         * by comparing the rest of str2 with the trailing NUL byte of sec1.
4120
         * In any case since the diff above is computed up to and including a
4121
         * NUL byte, only the same content and length will raise match.
4122
         */
4123
        if (!c2) {
4124
            break;
4125
        }
4126
4127
        /* Don't go above sec1's NUL byte */
4128
        i1 += test_nonzero_timingsafe(c1);
4129
    }
4130
4131
    /* (diff == 0) <=> (diff != 0) ^ 1 */
4132
    return test_nonzero_timingsafe(diff) ^ 1;
4133
}
4134
4135
#endif /* !APR_VERSION_AT_LEAST(1,8,0) */