hostid.c 2.2 KB

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