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