util.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright (C) 2014 John Crispin <blogic@openwrt.org>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU Lesser General Public License version 2.1
  6. * as published by the Free Software Foundation
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. */
  13. #include <sys/socket.h>
  14. #include <sys/ioctl.h>
  15. #include <sys/types.h>
  16. #include <sys/stat.h>
  17. #include <sys/utsname.h>
  18. #include <arpa/inet.h>
  19. #include <unistd.h>
  20. #include <stdio.h>
  21. #include <string.h>
  22. #include <errno.h>
  23. #include <fcntl.h>
  24. #include <stdlib.h>
  25. #include <signal.h>
  26. #include <libubox/uloop.h>
  27. #include <libubox/utils.h>
  28. #include "dns.h"
  29. #include "util.h"
  30. uint8_t mdns_buf[MDNS_BUF_LEN];
  31. int debug = 0;
  32. char umdns_host_label[HOSTNAME_LEN];
  33. char mdns_hostname_local[HOSTNAME_LEN + 6];
  34. uint32_t
  35. rand_time_delta(uint32_t t)
  36. {
  37. uint32_t val;
  38. int fd = open("/dev/urandom", O_RDONLY);
  39. if (!fd)
  40. return t;
  41. if (read(fd, &val, sizeof(val)) == sizeof(val)) {
  42. int range = t / 30;
  43. srand(val);
  44. val = t + (rand() % range) - (range / 2);
  45. } else {
  46. val = t;
  47. }
  48. close(fd);
  49. return val;
  50. }
  51. void get_hostname(void)
  52. {
  53. struct utsname utsname;
  54. umdns_host_label[0] = 0;
  55. mdns_hostname_local[0] = 0;
  56. if (uname(&utsname) < 0)
  57. return;
  58. snprintf(umdns_host_label, sizeof(umdns_host_label), "%s", utsname.nodename);
  59. snprintf(mdns_hostname_local, sizeof(mdns_hostname_local), "%s.local", utsname.nodename);
  60. }
  61. time_t monotonic_time(void)
  62. {
  63. struct timespec ts;
  64. clock_gettime(CLOCK_MONOTONIC, &ts);
  65. return ts.tv_sec;
  66. }