Coverage Report

Created: 2026-12-01 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/httpd/srclib/apr/strings/apr_strings.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
 * Copyright (c) 1990, 1993
18
 *  The Regents of the University of California.  All rights reserved.
19
 *
20
 * Redistribution and use in source and binary forms, with or without
21
 * modification, are permitted provided that the following conditions
22
 * are met:
23
 * 1. Redistributions of source code must retain the above copyright
24
 *    notice, this list of conditions and the following disclaimer.
25
 * 2. Redistributions in binary form must reproduce the above copyright
26
 *    notice, this list of conditions and the following disclaimer in the
27
 *    documentation and/or other materials provided with the distribution.
28
 * 3. All advertising materials mentioning features or use of this software
29
 *    must display the following acknowledgement:
30
 *  This product includes software developed by the University of
31
 *  California, Berkeley and its contributors.
32
 * 4. Neither the name of the University nor the names of its contributors
33
 *    may be used to endorse or promote products derived from this software
34
 *    without specific prior written permission.
35
 *
36
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
37
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
39
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
40
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
41
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
42
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
44
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
45
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46
 * SUCH DAMAGE.
47
 */
48
49
#include "apr.h"
50
#include "apr_strings.h"
51
#include "apr_general.h"
52
#include "apr_private.h"
53
#include "apr_lib.h"
54
#define APR_WANT_STDIO
55
#define APR_WANT_STRFUNC
56
#include "apr_want.h"
57
58
#ifdef HAVE_STDDEF_H
59
#include <stddef.h> /* NULL */
60
#endif
61
#ifdef HAVE_LIMITS_H
62
#include <limits.h> /* INT_MAX */
63
#endif
64
65
#ifdef HAVE_STDLIB_H
66
#include <stdlib.h> /* strtol and strtoll */
67
#endif
68
69
/** this is used to cache lengths in apr_pstrcat */
70
16.0k
#define MAX_SAVED_LENGTHS  6
71
72
APR_DECLARE(char *) apr_pstrdup(apr_pool_t *a, const char *s)
73
34.5k
{
74
34.5k
    char *res;
75
34.5k
    apr_size_t len;
76
77
34.5k
    if (s == NULL) {
78
0
        return NULL;
79
0
    }
80
34.5k
    len = strlen(s) + 1;
81
34.5k
    res = apr_pmemdup(a, s, len);
82
34.5k
    return res;
83
34.5k
}
84
85
APR_DECLARE(char *) apr_pstrndup(apr_pool_t *a, const char *s, apr_size_t n)
86
423
{
87
423
    char *res;
88
423
    const char *end;
89
90
423
    if (s == NULL) {
91
0
        return NULL;
92
0
    }
93
423
    end = memchr(s, '\0', n);
94
423
    if (end != NULL)
95
0
        n = end - s;
96
423
    res = apr_palloc(a, n + 1);
97
423
    memcpy(res, s, n);
98
423
    res[n] = '\0';
99
423
    return res;
100
423
}
101
102
APR_DECLARE(char *) apr_pstrmemdup(apr_pool_t *a, const char *s, apr_size_t n)
103
7.90k
{
104
7.90k
    char *res;
105
106
7.90k
    if (s == NULL) {
107
0
        return NULL;
108
0
    }
109
7.90k
    res = apr_palloc(a, n + 1);
110
7.90k
    memcpy(res, s, n);
111
7.90k
    res[n] = '\0';
112
7.90k
    return res;
113
7.90k
}
114
115
APR_DECLARE(void *) apr_pmemdup(apr_pool_t *a, const void *m, apr_size_t n)
116
61.1k
{
117
61.1k
    void *res;
118
119
61.1k
    if (m == NULL)
120
0
  return NULL;
121
61.1k
    res = apr_palloc(a, n);
122
61.1k
    memcpy(res, m, n);
123
61.1k
    return res;
124
61.1k
}
125
126
APR_DECLARE_NONSTD(char *) apr_pstrcat(apr_pool_t *a, ...)
127
1.69k
{
128
1.69k
    char *cp, *argp, *res;
129
1.69k
    apr_size_t saved_lengths[MAX_SAVED_LENGTHS];
130
1.69k
    int nargs = 0;
131
132
    /* Pass one --- find length of required string */
133
134
1.69k
    apr_size_t len = 0;
135
1.69k
    va_list adummy;
136
137
1.69k
    va_start(adummy, a);
138
139
9.71k
    while ((cp = va_arg(adummy, char *)) != NULL) {
140
8.02k
        apr_size_t cplen = strlen(cp);
141
8.02k
        if (nargs < MAX_SAVED_LENGTHS) {
142
7.68k
            saved_lengths[nargs++] = cplen;
143
7.68k
        }
144
8.02k
        len += cplen;
145
8.02k
    }
146
147
1.69k
    va_end(adummy);
148
149
    /* Allocate the required string */
150
151
1.69k
    res = (char *) apr_palloc(a, len + 1);
152
1.69k
    cp = res;
153
154
    /* Pass two --- copy the argument strings into the result space */
155
156
1.69k
    va_start(adummy, a);
157
158
1.69k
    nargs = 0;
159
9.71k
    while ((argp = va_arg(adummy, char *)) != NULL) {
160
8.02k
        if (nargs < MAX_SAVED_LENGTHS) {
161
7.68k
            len = saved_lengths[nargs++];
162
7.68k
        }
163
337
        else {
164
337
            len = strlen(argp);
165
337
        }
166
167
8.02k
        memcpy(cp, argp, len);
168
8.02k
        cp += len;
169
8.02k
    }
170
171
1.69k
    va_end(adummy);
172
173
    /* Return the result string */
174
175
1.69k
    *cp = '\0';
176
177
1.69k
    return res;
178
1.69k
}
179
180
APR_DECLARE(char *) apr_pstrcatv(apr_pool_t *a, const struct iovec *vec,
181
                                 apr_size_t nvec, apr_size_t *nbytes)
182
0
{
183
0
    apr_size_t i;
184
0
    apr_size_t len;
185
0
    const struct iovec *src;
186
0
    char *res;
187
0
    char *dst;
188
189
    /* Pass one --- find length of required string */
190
0
    len = 0;
191
0
    src = vec;
192
0
    for (i = nvec; i; i--) {
193
0
        len += src->iov_len;
194
0
        src++;
195
0
    }
196
0
    if (nbytes) {
197
0
        *nbytes = len;
198
0
    }
199
200
    /* Allocate the required string */
201
0
    res = (char *) apr_palloc(a, len + 1);
202
203
    /* Pass two --- copy the argument strings into the result space */
204
0
    src = vec;
205
0
    dst = res;
206
0
    for (i = nvec; i; i--) {
207
0
        memcpy(dst, src->iov_base, src->iov_len);
208
0
        dst += src->iov_len;
209
0
        src++;
210
0
    }
211
212
    /* Return the result string */
213
0
    *dst = '\0';
214
215
0
    return res;
216
0
}
217
218
#if defined(HAVE_WEAK_SYMBOLS)
219
void apr__memzero_explicit(void *buffer, apr_size_t size);
220
221
__attribute__ ((weak))
222
void apr__memzero_explicit(void *buffer, apr_size_t size)
223
0
{
224
0
    memset(buffer, 0, size);
225
0
}
226
#endif
227
228
APR_DECLARE(apr_status_t) apr_memzero_explicit(void *buffer, apr_size_t size)
229
0
{
230
#if defined(WIN32)
231
    SecureZeroMemory(buffer, size);
232
#elif defined(HAVE_EXPLICIT_BZERO)
233
    explicit_bzero(buffer, size);
234
#elif defined(HAVE_MEMSET_S)
235
    if (size) {
236
        return memset_s(buffer, (rsize_t)size, 0, (rsize_t)size);
237
    }
238
#elif defined(HAVE_WEAK_SYMBOLS)
239
    apr__memzero_explicit(buffer, size);
240
#else
241
    apr_size_t i;
242
    volatile unsigned char *volatile ptr = buffer;
243
    for (i = 0; i < size; ++i) {
244
        ptr[i] = 0;
245
    }
246
#endif
247
0
    return APR_SUCCESS;
248
0
}
249
250
/* A volatile variable which is always zero but allows to block the compiler
251
 * from optimizing or eliding code using it. Volatile forces the compiler to
252
 * emit a memory load for which no value can be assumed, so for instance an
253
 * add/sub/xor/or with "optblocker" is a noop that will hide the result to
254
 * the optimizer.
255
 */
256
static volatile const apr_uint32_t optblocker;
257
258
/* Return whether x is not zero, with no branching controlled by x.
259
 *
260
 * Taken from the cryptoint library (public domain) by D. J. Bernstein,
261
 * which provides timing attacks safe integer operations/primitives.
262
 * Code:
263
 *   https://lib.mceliece.org/libmceliece-20250507/cryptoint/crypto_uint32.h
264
 * Paper:
265
 *   https://cr.yp.to/papers/cryptoint-20250424.pdf
266
 */
267
static APR_INLINE_ALWAYS int test_nonzero_timingsafe(apr_uint32_t x)
268
0
{
269
0
    x |= -x; /* sets the most significant bit unless x == 0 */
270
271
    /* shift bit 31 (MSB) to bit 0 */
272
0
    x >>= 32-6;      /* keep 6 bits */
273
0
    x += optblocker; /* lose the optimizer */
274
0
    x >>= 5;         /* keep the (original) MSB only */
275
276
    /* x is now 0 or 1 */
277
0
    return x & INT_MAX;
278
0
}
279
280
APR_DECLARE(int) apr_memeq_timingsafe(const void *buf1, const void *buf2,
281
                                      apr_size_t n)
282
0
{
283
0
    apr_uint32_t diff = 0;
284
0
    volatile apr_size_t count = n; /* prevent loop unrolling */
285
0
    apr_size_t i = 0;
286
287
0
    for (; i < count; ++i) {
288
0
        const unsigned char c1 = ((volatile const unsigned char *)buf1)[i];
289
0
        const unsigned char c2 = ((volatile const unsigned char *)buf2)[i];
290
291
0
        diff |= c1 ^ c2; /* sets diff to non-zero whenever c1 != c2 */
292
0
    }
293
294
    /* (diff == 0) <=> (diff != 0) ^ 1 */
295
0
    return test_nonzero_timingsafe(diff) ^ 1;
296
0
}
297
298
APR_DECLARE(int) apr_streq_timingsafe(const char *sec1, const char *str2)
299
0
{
300
0
    apr_uint32_t diff = 0;
301
0
    apr_size_t i1 = 0, i2 = 0;
302
303
0
    for (;; ++i2) {
304
0
        const unsigned char c1 = ((volatile const unsigned char *)sec1)[i1];
305
0
        const unsigned char c2 = ((volatile const unsigned char *)str2)[i2];
306
307
0
        diff |= c1 ^ c2; /* sets diff to non-zero whenever c1 != c2 */
308
309
        /* Not a shortest/longest match because an attacker would usually know
310
         * one of the strings and could then determine the length of the other.
311
         * So assume only sec1 and its length are secret and stop the loop at
312
         * the end of str2. If sec1 is shorter than str2 the loop will continue
313
         * by comparing the rest of str2 with the trailing NUL byte of sec1.
314
         * In any case since the diff above is computed up to and including a
315
         * NUL byte, only the same content and length will raise match.
316
         */
317
0
        if (!c2) {
318
0
            break;
319
0
        }
320
321
        /* Don't go above sec1's NUL byte */
322
0
        i1 += test_nonzero_timingsafe(c1);
323
0
    }
324
325
    /* (diff == 0) <=> (diff != 0) ^ 1 */
326
0
    return test_nonzero_timingsafe(diff) ^ 1;
327
0
}
328
329
APR_DECLARE(int) apr_strneq_timingsafe(const char *sec1, const char *str2,
330
                                       apr_size_t n)
331
0
{
332
0
    apr_uint32_t diff = 0;
333
0
    volatile apr_size_t count = n; /* prevent loop unrolling */
334
0
    apr_size_t i1 = 0, i2 = 0;
335
336
0
    for (; i2 < count; ++i2) {
337
0
        const unsigned char c1 = ((volatile const unsigned char *)sec1)[i1];
338
0
        const unsigned char c2 = ((volatile const unsigned char *)str2)[i2];
339
340
0
        diff |= c1 ^ c2; /* sets diff to non-zero whenever c1 != c2 */
341
342
        /* Not a shortest/longest match because an attacker would usually know
343
         * one of the strings and could then determine the length of the other.
344
         * So assume only sec1 and its length are secret and stop the loop at
345
         * the end of str2. If sec1 is shorter than str2 the loop will continue
346
         * by comparing the rest of str2 with the trailing NUL byte of sec1.
347
         * In any case since the diff above is computed up to and including a
348
         * NUL byte, only the same content and length will raise match.
349
         */
350
0
        if (!c2) {
351
0
            break;
352
0
        }
353
354
        /* Don't go above sec1's NUL byte */
355
0
        i1 += test_nonzero_timingsafe(c1);
356
0
    }
357
358
    /* (diff == 0) <=> (diff != 0) ^ 1 */
359
0
    return test_nonzero_timingsafe(diff) ^ 1;
360
0
}
361
362
#if (!APR_HAVE_MEMCHR)
363
void *memchr(const void *s, int c, size_t n)
364
{
365
    const char *cp;
366
367
    for (cp = s; n > 0; n--, cp++) {
368
        if (*cp == c)
369
            return (char *) cp; /* Casting away the const here */
370
    }
371
372
    return NULL;
373
}
374
#endif
375
376
#ifndef INT64_MAX
377
#define INT64_MAX  APR_INT64_C(0x7fffffffffffffff)
378
#endif
379
#ifndef INT64_MIN
380
#define INT64_MIN (-APR_INT64_C(0x7fffffffffffffff) - APR_INT64_C(1))
381
#endif
382
383
APR_DECLARE(apr_status_t) apr_strtoff(apr_off_t *offset, const char *nptr,
384
                                      char **endptr, int base)
385
0
{
386
0
    errno = 0;
387
0
    *offset = APR_OFF_T_STRFN(nptr, endptr, base);
388
0
    return APR_FROM_OS_ERROR(errno);
389
0
}
390
391
APR_DECLARE(apr_int64_t) apr_strtoi64(const char *nptr, char **endptr, int base)
392
1.21k
{
393
1.21k
#ifdef APR_INT64_STRFN
394
1.21k
    errno = 0;
395
1.21k
    return APR_INT64_STRFN(nptr, endptr, base);
396
#else
397
    const char *s;
398
    apr_int64_t acc;
399
    apr_int64_t val;
400
    int neg, any;
401
    char c;
402
403
    errno = 0;
404
    /*
405
     * Skip white space and pick up leading +/- sign if any.
406
     * If base is 0, allow 0x for hex and 0 for octal, else
407
     * assume decimal; if base is already 16, allow 0x.
408
     */
409
    s = nptr;
410
    do {
411
  c = *s++;
412
    } while (apr_isspace(c));
413
    if (c == '-') {
414
  neg = 1;
415
  c = *s++;
416
    } else {
417
  neg = 0;
418
  if (c == '+')
419
      c = *s++;
420
    }
421
    if ((base == 0 || base == 16) &&
422
  c == '0' && (*s == 'x' || *s == 'X')) {
423
      c = s[1];
424
      s += 2;
425
      base = 16;
426
    }
427
    if (base == 0)
428
  base = c == '0' ? 8 : 10;
429
    acc = any = 0;
430
    if (base < 2 || base > 36) {
431
  errno = EINVAL;
432
        if (endptr != NULL)
433
      *endptr = (char *)(any ? s - 1 : nptr);
434
        return acc;
435
    }
436
437
    /* The classic bsd implementation requires div/mod operators
438
     * to compute a cutoff.  Benchmarking proves that is very, very
439
     * evil to some 32 bit processors.  Instead, look for underflow
440
     * in both the mult and add/sub operation.  Unlike the bsd impl,
441
     * we also work strictly in a signed int64 word as we haven't
442
     * implemented the unsigned type in win32.
443
     *
444
     * Set 'any' if any `digits' consumed; make it negative to indicate
445
     * overflow.
446
     */
447
    val = 0;
448
    for ( ; ; c = *s++) {
449
        if (c >= '0' && c <= '9')
450
      c -= '0';
451
#if (('Z' - 'A') == 25)
452
  else if (c >= 'A' && c <= 'Z')
453
      c -= 'A' - 10;
454
  else if (c >= 'a' && c <= 'z')
455
      c -= 'a' - 10;
456
#elif APR_CHARSET_EBCDIC
457
  else if (c >= 'A' && c <= 'I')
458
      c -= 'A' - 10;
459
  else if (c >= 'J' && c <= 'R')
460
      c -= 'J' - 19;
461
  else if (c >= 'S' && c <= 'Z')
462
      c -= 'S' - 28;
463
  else if (c >= 'a' && c <= 'i')
464
      c -= 'a' - 10;
465
  else if (c >= 'j' && c <= 'r')
466
      c -= 'j' - 19;
467
  else if (c >= 's' && c <= 'z')
468
      c -= 'z' - 28;
469
#else
470
#error "CANNOT COMPILE apr_strtoi64(), only ASCII and EBCDIC supported"
471
#endif
472
  else
473
      break;
474
  if (c >= base)
475
      break;
476
  val *= base;
477
        if ( (any < 0)  /* already noted an over/under flow - short circuit */
478
           || (neg && (val > acc || (val -= c) > acc)) /* underflow */
479
           || (!neg && (val < acc || (val += c) < acc))) {       /* overflow */
480
            any = -1; /* once noted, over/underflows never go away */
481
#ifdef APR_STRTOI64_OVERFLOW_IS_BAD_CHAR
482
            break;
483
#endif
484
        } else {
485
            acc = val;
486
      any = 1;
487
        }
488
    }
489
490
    if (any < 0) {
491
  acc = neg ? INT64_MIN : INT64_MAX;
492
  errno = ERANGE;
493
    } else if (!any) {
494
  errno = EINVAL;
495
    }
496
    if (endptr != NULL)
497
  *endptr = (char *)(any ? s - 1 : nptr);
498
    return (acc);
499
#endif
500
1.21k
}
501
502
APR_DECLARE(apr_int64_t) apr_atoi64(const char *buf)
503
0
{
504
0
    return apr_strtoi64(buf, NULL, 10);
505
0
}
506
507
APR_DECLARE(char *) apr_itoa(apr_pool_t *p, int n)
508
0
{
509
0
    const int BUFFER_SIZE = sizeof(int) * 3 + 2;
510
0
    char *buf = apr_palloc(p, BUFFER_SIZE);
511
0
    char *start = buf + BUFFER_SIZE - 1;
512
0
    unsigned int un;
513
0
    int negative;
514
0
    if (n < 0) {
515
0
  negative = 1;
516
0
  un = -n;
517
0
    }
518
0
    else {
519
0
  negative = 0;
520
0
        un = n;
521
0
    }
522
0
    *start = 0;
523
0
    do {
524
0
  *--start = '0' + (un % 10);
525
0
  un /= 10;
526
0
    } while (un);
527
0
    if (negative) {
528
0
  *--start = '-';
529
0
    }
530
0
    return start;
531
0
}
532
533
APR_DECLARE(char *) apr_ltoa(apr_pool_t *p, long n)
534
0
{
535
0
    const int BUFFER_SIZE = sizeof(long) * 3 + 2;
536
0
    char *buf = apr_palloc(p, BUFFER_SIZE);
537
0
    char *start = buf + BUFFER_SIZE - 1;
538
0
    int negative;
539
0
    unsigned int un;
540
0
    if (n < 0) {
541
0
  negative = 1;
542
0
  un = -n;
543
0
    }
544
0
    else {
545
0
  negative = 0;
546
0
        un = n;
547
0
    }
548
0
    *start = 0;
549
0
    do {
550
0
  *--start = (char)('0' + (un % 10));
551
0
  un /= 10;
552
0
    } while (un);
553
0
    if (negative) {
554
0
  *--start = '-';
555
0
    }
556
0
    return start;
557
0
}
558
559
APR_DECLARE(char *) apr_off_t_toa(apr_pool_t *p, apr_off_t n)
560
0
{
561
0
    const int BUFFER_SIZE = sizeof(apr_off_t) * 3 + 2;
562
0
    char *buf = apr_palloc(p, BUFFER_SIZE);
563
0
    char *start = buf + BUFFER_SIZE - 1;
564
0
    int negative;
565
0
    if (n < 0) {
566
0
  negative = 1;
567
0
  n = -n;
568
0
    }
569
0
    else {
570
0
  negative = 0;
571
0
    }
572
0
    *start = 0;
573
0
    do {
574
0
  *--start = '0' + (char)(n % 10);
575
0
  n /= 10;
576
0
    } while (n);
577
0
    if (negative) {
578
0
  *--start = '-';
579
0
    }
580
0
    return start;
581
0
}
582
583
APR_DECLARE(char *) apr_strfsize(apr_off_t size, char *buf)
584
0
{
585
0
    const char ord[] = "KMGTPE";
586
0
    const char *o = ord;
587
0
    int remain;
588
589
0
    if (size < 0) {
590
0
        return strcpy(buf, "  - ");
591
0
    }
592
0
    if (size < 973) {
593
0
        if (apr_snprintf(buf, 5, "%3d ", (int) size) < 0)
594
0
            return strcpy(buf, "****");
595
0
        return buf;
596
0
    }
597
0
    do {
598
0
        remain = (int)(size & 1023);
599
0
        size >>= 10;
600
0
        if (size >= 973) {
601
0
            ++o;
602
0
            continue;
603
0
        }
604
0
        if (size < 9 || (size == 9 && remain < 973)) {
605
0
            if ((remain = ((remain * 5) + 256) / 512) >= 10)
606
0
                ++size, remain = 0;
607
0
            if (apr_snprintf(buf, 5, "%d.%d%c", (int) size, remain, *o) < 0)
608
0
                return strcpy(buf, "****");
609
0
            return buf;
610
0
        }
611
0
        if (remain >= 512)
612
0
            ++size;
613
0
        if (apr_snprintf(buf, 5, "%3d%c", (int) size, *o) < 0)
614
0
            return strcpy(buf, "****");
615
0
        return buf;
616
0
    } while (1);
617
0
}
618