/src/dovecot/src/lib/hostpid.c
Line | Count | Source (jump to first uncovered line) |
1 | | /* Copyright (c) 2002-2018 Dovecot authors, see the included COPYING file */ |
2 | | |
3 | | #include "lib.h" |
4 | | #include "hostpid.h" |
5 | | |
6 | | #include <unistd.h> |
7 | | #include <netdb.h> |
8 | | |
9 | 1 | #define HOSTNAME_DISALLOWED_CHARS "/\r\n\t" |
10 | | |
11 | | const char *my_hostname = NULL; |
12 | | const char *my_pid = NULL; |
13 | | |
14 | | static char *my_hostname_dup = NULL; |
15 | | static char *my_domain = NULL; |
16 | | |
17 | | void hostpid_init(void) |
18 | 1 | { |
19 | 1 | static char pid[MAX_INT_STRLEN]; |
20 | 1 | char hostname[256]; |
21 | 1 | const char *value; |
22 | | |
23 | | /* allow calling hostpid_init() multiple times to reset hostname */ |
24 | 1 | i_free_and_null(my_hostname_dup); |
25 | 1 | i_free_and_null(my_domain); |
26 | | |
27 | 1 | value = getenv(MY_HOSTNAME_ENV); |
28 | 1 | if (value == NULL) { |
29 | 1 | if (gethostname(hostname, sizeof(hostname)-1) < 0) |
30 | 0 | i_fatal("gethostname() failed: %m"); |
31 | 1 | hostname[sizeof(hostname)-1] = '\0'; |
32 | 1 | value = hostname; |
33 | 1 | } |
34 | | |
35 | 1 | if (value[0] == '\0' || |
36 | 1 | strcspn(value, HOSTNAME_DISALLOWED_CHARS) != strlen(value)) |
37 | 0 | i_fatal("Invalid system hostname: '%s'", value); |
38 | 1 | my_hostname_dup = i_strdup(value); |
39 | 1 | my_hostname = my_hostname_dup; |
40 | | |
41 | 1 | i_snprintf(pid, sizeof(pid), "%lld", (long long)getpid()); |
42 | 1 | my_pid = pid; |
43 | 1 | } |
44 | | |
45 | | void hostpid_deinit(void) |
46 | 0 | { |
47 | 0 | i_free(my_hostname_dup); |
48 | 0 | i_free(my_domain); |
49 | 0 | } |
50 | | |
51 | | const char *my_hostdomain(void) |
52 | 0 | { |
53 | 0 | struct hostent *hent; |
54 | 0 | const char *name; |
55 | |
|
56 | 0 | if (my_domain == NULL) { |
57 | 0 | name = getenv(MY_HOSTDOMAIN_ENV); |
58 | 0 | if (name == NULL) { |
59 | 0 | hent = gethostbyname(my_hostname); |
60 | 0 | name = hent != NULL ? hent->h_name : NULL; |
61 | 0 | if (name == NULL) { |
62 | | /* failed, use just the hostname */ |
63 | 0 | name = my_hostname; |
64 | 0 | } |
65 | 0 | } |
66 | 0 | my_domain = i_strdup(name); |
67 | 0 | } |
68 | 0 | return my_domain; |
69 | 0 | } |