hostid.c 2.2 KB

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