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