/src/sudo/plugins/sudoers/strvec_join.c
Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | * SPDX-License-Identifier: ISC |
3 | | * |
4 | | * Copyright (c) 2021 Todd C. Miller <Todd.Miller@sudo.ws> |
5 | | * |
6 | | * Permission to use, copy, modify, and distribute this software for any |
7 | | * purpose with or without fee is hereby granted, provided that the above |
8 | | * copyright notice and this permission notice appear in all copies. |
9 | | * |
10 | | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |
11 | | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
12 | | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |
13 | | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
14 | | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
15 | | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |
16 | | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
17 | | */ |
18 | | |
19 | | /* |
20 | | * This is an open source non-commercial project. Dear PVS-Studio, please check it. |
21 | | * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com |
22 | | */ |
23 | | |
24 | | #include <config.h> |
25 | | |
26 | | #include <stdio.h> |
27 | | #include <stdlib.h> |
28 | | #include <string.h> |
29 | | |
30 | | #include <sudoers.h> |
31 | | |
32 | | #ifdef HAVE_STRLCPY |
33 | | # define cpy_default strlcpy |
34 | | #else |
35 | 640 | # define cpy_default sudo_strlcpy |
36 | | #endif |
37 | | |
38 | | /* |
39 | | * Join a NULL-terminated array of strings using the specified separator |
40 | | * char. If non-NULL, the copy function must have strlcpy-like semantics. |
41 | | */ |
42 | | char * |
43 | | strvec_join(char *const argv[], char sep, size_t (*cpy)(char * restrict, const char * restrict, size_t)) |
44 | 1.05k | { |
45 | 1.05k | char *dst, *result = NULL; |
46 | 1.05k | char *const *av; |
47 | 1.05k | size_t n, size = 0; |
48 | 1.05k | debug_decl(strvec_join, SUDOERS_DEBUG_UTIL); |
49 | | |
50 | 3.63M | for (av = argv; *av != NULL; av++) |
51 | 3.63M | size += strlen(*av) + 1; |
52 | 1.05k | if (size == 0 || (result = malloc(size)) == NULL) { |
53 | 0 | sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory")); |
54 | 0 | debug_return_ptr(NULL); |
55 | 0 | } |
56 | | |
57 | 1.05k | if (cpy == NULL) |
58 | 640 | cpy = cpy_default; |
59 | 3.63M | for (dst = result, av = argv; *av != NULL; av++) { |
60 | 3.63M | n = cpy(dst, *av, size); |
61 | 3.63M | if (n >= size) { |
62 | 0 | sudo_warnx(U_("internal error, %s overflow"), __func__); |
63 | 0 | free(result); |
64 | 0 | debug_return_ptr(NULL); |
65 | 0 | } |
66 | 3.63M | dst += n; |
67 | 3.63M | size -= n; |
68 | 3.63M | *dst++ = sep; |
69 | 3.63M | size--; |
70 | 3.63M | } |
71 | 1.05k | dst[-1] = '\0'; |
72 | | |
73 | 1.05k | debug_return_str(result); |
74 | 1.05k | } |