lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame^] | 1 | /* vi: set sw=4 ts=4: */ |
| 2 | /* |
| 3 | * Copyright (C) 2000-2006 Erik Andersen <andersen@uclibc.org> |
| 4 | * |
| 5 | * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball. |
| 6 | */ |
| 7 | |
| 8 | #define __FORCE_GLIBC |
| 9 | #include <features.h> |
| 10 | #include <errno.h> |
| 11 | #include <unistd.h> |
| 12 | #include <sys/types.h> |
| 13 | #include <fcntl.h> |
| 14 | #include <stdlib.h> |
| 15 | #include <string.h> |
| 16 | #include <netdb.h> |
| 17 | #include <not-cancel.h> |
| 18 | |
| 19 | #define HOSTID "/etc/hostid" |
| 20 | |
| 21 | #ifdef __USE_BSD |
| 22 | int sethostid(long int new_id) |
| 23 | { |
| 24 | int fd; |
| 25 | int ret; |
| 26 | |
| 27 | if (geteuid() || getuid()) |
| 28 | return __set_errno(EPERM); |
| 29 | fd = open_not_cancel(HOSTID, O_CREAT|O_WRONLY, 0644); |
| 30 | if (fd < 0) |
| 31 | return fd; |
| 32 | ret = write_not_cancel(fd, &new_id, sizeof(new_id)) == sizeof(new_id) ? 0 : -1; |
| 33 | close_not_cancel_no_status (fd); |
| 34 | return ret; |
| 35 | } |
| 36 | #endif |
| 37 | |
| 38 | #define _addr(a) (((struct sockaddr_in*)a->ai_addr)->sin_addr.s_addr) |
| 39 | long int gethostid(void) |
| 40 | { |
| 41 | char host[HOST_NAME_MAX + 1]; |
| 42 | int fd, id = 0; |
| 43 | |
| 44 | /* If hostid was already set then we can return that value. |
| 45 | * It is not an error if we cannot read this file. It is not even an |
| 46 | * error if we cannot read all the bytes, we just carry on trying... |
| 47 | */ |
| 48 | fd = open_not_cancel_2(HOSTID, O_RDONLY); |
| 49 | if (fd >= 0) { |
| 50 | int i = read_not_cancel(fd, &id, sizeof(id)); |
| 51 | close_not_cancel_no_status(fd); |
| 52 | if (i > 0) |
| 53 | return id; |
| 54 | } |
| 55 | /* Try some methods of returning a unique 32 bit id. Clearly IP |
| 56 | * numbers, if on the internet, will have a unique address. If they |
| 57 | * are not on the internet then we can return 0 which means they should |
| 58 | * really set this number via a sethostid() call. If their hostname |
| 59 | * returns the loopback number (i.e. if they have put their hostname |
| 60 | * in the /etc/hosts file with 127.0.0.1) then all such hosts will |
| 61 | * have a non-unique hostid, but it doesn't matter anyway and |
| 62 | * gethostid() will return a non zero number without the need for |
| 63 | * setting one anyway. |
| 64 | * Mitch |
| 65 | */ |
| 66 | if (gethostname(host, HOST_NAME_MAX) >= 0 && *host) { |
| 67 | struct addrinfo hints, *results, *addr; |
| 68 | memset(&hints, 0, sizeof(struct addrinfo)); |
| 69 | if (!getaddrinfo(host, NULL, &hints, &results)) { |
| 70 | for (addr = results; addr; addr = results->ai_next) { |
| 71 | /* Just so it doesn't look exactly like the |
| 72 | IP addr */ |
| 73 | id = _addr(addr) << 16 | _addr(addr) >> 16; |
| 74 | break; |
| 75 | } |
| 76 | freeaddrinfo(results); |
| 77 | } |
| 78 | } |
| 79 | return id; |
| 80 | } |