/src/sudo/lib/util/gethostname.c
Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | * SPDX-License-Identifier: ISC |
3 | | * |
4 | | * Copyright (c) 2015, 2025 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 <stdlib.h> |
27 | | #include <unistd.h> |
28 | | |
29 | | #include <sudo_compat.h> |
30 | | #include <sudo_util.h> |
31 | | |
32 | | /* |
33 | | * Return a malloc()ed copy of the system hostname, or NULL if |
34 | | * malloc() or gethostname() fails. |
35 | | */ |
36 | | char * |
37 | | sudo_gethostname_v1(void) |
38 | 0 | { |
39 | 0 | const size_t host_name_max = sudo_host_name_max(); |
40 | 0 | char *hname = malloc(host_name_max + 1); |
41 | 0 | if (hname != NULL) { |
42 | 0 | if (gethostname(hname, host_name_max + 1) == 0 && *hname != '\0') { |
43 | | /* Old gethostname() may not NUL-terminate if there is no room. */ |
44 | 0 | hname[host_name_max] = '\0'; |
45 | 0 | } else { |
46 | 0 | free(hname); |
47 | 0 | hname = NULL; |
48 | 0 | } |
49 | 0 | } |
50 | 0 | return hname; |
51 | 0 | } |
52 | | |
53 | | size_t |
54 | | sudo_host_name_max_v1(void) |
55 | 0 | { |
56 | 0 | static size_t maxval; |
57 | |
|
58 | 0 | if (maxval == 0) { |
59 | 0 | long lval; |
60 | |
|
61 | 0 | #ifdef _SC_HOST_NAME_MAX |
62 | 0 | lval = sysconf(_SC_HOST_NAME_MAX); |
63 | 0 | if (lval <= 0) |
64 | 0 | #endif |
65 | 0 | lval = 255; /* POSIX and historic BSD */ |
66 | 0 | maxval = (size_t)lval; |
67 | 0 | } |
68 | |
|
69 | 0 | return maxval; |
70 | 0 | } |