Coverage Report

Created: 2024-04-25 06:03

/src/ntpsec/libntp/strl_obsd.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Why use strlcpy()/strlcat() instead of standard strncpy()/strncat()?
3
 * To reduce likelihood of bugs and avoid wasteful zero fills.  See:
4
 * http://www.gratisoft.us/todd/papers/strlcpy.html
5
 */
6
7
/*
8
 * Copyright Todd C. Miller <Todd.Miller@courtesan.com>
9
 * Copyright the NTPsec project contributors
10
 * SPDX-License-Identifier: ISC
11
 */
12
13
#include "config.h"   /* + marks local changes */
14
#include <sys/types.h>
15
#include <string.h>
16
17
#include "ntp_stdlib.h"   /* + strlcpy, strlcat prototypes */
18
19
#ifndef HAVE_STRLCPY    /* + */
20
/*
21
 * Copy src to string dst of size siz.  At most siz-1 characters
22
 * will be copied.  Always NUL terminates (unless siz == 0).
23
 * Returns strlen(src); if retval >= siz, truncation occurred.
24
 */
25
size_t
26
strlcpy(char *dst, const char *src, size_t siz)
27
0
{
28
0
  char *d = dst;
29
0
  const char *s = src;
30
0
  size_t n = siz;
31
32
  /* Copy as many bytes as will fit */
33
0
  if (n != 0) {
34
0
    while (--n != 0) {
35
0
      if ((*d++ = *s++) == '\0') {
36
0
        break;
37
0
      }
38
0
    }
39
0
  }
40
41
  /* Not enough room in dst, add NUL and traverse rest of src */
42
0
  if (n == 0) {
43
0
    if (siz != 0) {
44
0
      *d = '\0';    /* NUL-terminate dst */
45
0
    }
46
0
    while (*s++) {
47
0
      ;
48
0
    }
49
0
  }
50
51
0
  return((size_t)(s - src - 1));  /* count does not include NUL */
52
0
}
53
#endif        /* + */
54
55
56
/* #include <sys/types.h> */  /* + */
57
/* #include <string.h> */ /* + */
58
59
#ifndef HAVE_STRLCAT    /* + */
60
/*
61
 * Appends src to string dst of size siz (unlike strncat, siz is the
62
 * full size of dst, not space left).  At most siz-1 characters
63
 * will be copied.  Always NUL terminates (unless siz <= strlen(dst)).
64
 * Returns strlen(src) + MIN(siz, strlen(initial dst)).
65
 * If retval >= siz, truncation occurred.
66
 */
67
size_t
68
strlcat(char *dst, const char *src, size_t siz)
69
0
{
70
0
  char *d = dst;
71
0
  const char *s = src;
72
0
  size_t n = siz;
73
0
  size_t dlen;
74
75
  /* Find the end of dst and adjust bytes left but don't go past end */
76
0
  while (n-- != 0 && *d != '\0') {
77
0
    d++;
78
0
  }
79
0
  dlen = (size_t)(d - dst);
80
0
  n = siz - dlen;
81
82
0
  if (n == 0) {
83
0
    return(dlen + strlen(s));
84
0
  }
85
0
  while (*s != '\0') {
86
0
    if (n != 1) {
87
0
      *d++ = *s;
88
0
      n--;
89
0
    }
90
0
    s++;
91
0
  }
92
0
  *d = '\0';
93
94
0
  return(dlen + (size_t)(s - src)); /* count does not include NUL */
95
0
}
96
#endif        /* + */