hostid.c 2.2 KB

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