]> granicus.if.org Git - sudo/blob - lib/util/strlcat.c
Add SPDX-License-Identifier to files.
[sudo] / lib / util / strlcat.c
1 /*      $OpenBSD: strlcat.c,v 1.15 2015/03/02 21:41:08 millert Exp $    */
2
3 /*
4  * SPDX-License-Identifier: ISC
5  *
6  * Copyright (c) 1998, 2003-2005, 2010-2011, 2013-2015
7  *      Todd C. Miller <Todd.Miller@sudo.ws>
8  *
9  * Permission to use, copy, modify, and distribute this software for any
10  * purpose with or without fee is hereby granted, provided that the above
11  * copyright notice and this permission notice appear in all copies.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20  */
21
22 /*
23  * This is an open source non-commercial project. Dear PVS-Studio, please check it.
24  * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
25  */
26
27 #include <config.h>
28
29 #ifndef HAVE_STRLCAT
30
31 #include <sys/types.h>
32 #include <string.h>
33
34 #include "sudo_compat.h"
35
36 /*
37  * Appends src to string dst of size dsize (unlike strncat, dsize is the
38  * full size of dst, not space left).  At most dsize-1 characters
39  * will be copied.  Always NUL terminates (unless dsize <= strlen(dst)).
40  * Returns strlen(src) + MIN(dsize, strlen(initial dst)).
41  * If retval >= dsize, truncation occurred.
42  */
43 size_t
44 sudo_strlcat(char *dst, const char *src, size_t dsize)
45 {
46         const char *odst = dst;
47         const char *osrc = src;
48         size_t n = dsize;
49         size_t dlen;
50
51         /* Find the end of dst and adjust bytes left but don't go past end. */
52         while (n-- != 0 && *dst != '\0')
53                 dst++;
54         dlen = dst - odst;
55         n = dsize - dlen;
56
57         if (n-- == 0)
58                 return(dlen + strlen(src));
59         while (*src != '\0') {
60                 if (n != 0) {
61                         *dst++ = *src;
62                         n--;
63                 }
64                 src++;
65         }
66         *dst = '\0';
67
68         return(dlen + (src - osrc));    /* count does not include NUL */
69 }
70 #endif /* HAVE_STRLCAT */