util.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /**
  2. * nmrpflash - Netgear Unbrick Utility
  3. * Copyright (C) 2016 Joseph Lehner <joseph.c.lehner@gmail.com>
  4. *
  5. * nmrpflash is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * nmrpflash is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with nmrpflash. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. #include <stdio.h>
  20. #include <errno.h>
  21. #include <time.h>
  22. #include <math.h>
  23. #include "nmrpd.h"
  24. #ifdef NMRPFLASH_OSX
  25. #include <mach/mach_time.h>
  26. #endif
  27. volatile sig_atomic_t g_interrupted = 0;
  28. int verbosity = 0;
  29. long long millis()
  30. {
  31. #ifndef NMRPFLASH_WINDOWS
  32. struct timespec ts;
  33. clock_gettime(CLOCK_MONOTONIC, &ts);
  34. return ts.tv_sec * 1000 + ((ts.tv_nsec + 500000) / 1000000);
  35. #else
  36. return GetTickCount();
  37. #endif
  38. }
  39. time_t time_monotonic()
  40. {
  41. return millis() / 1000;
  42. }
  43. char *lltostr(long long ll, int base)
  44. {
  45. static char buf[32];
  46. snprintf(buf, sizeof(buf) - 1, (base == 16 ? "%llx" : (base == 8 ? "%llo" : "%lld")), ll);
  47. return buf;
  48. }
  49. const char *mac_to_str(uint8_t *mac)
  50. {
  51. static char buf[18];
  52. snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x",
  53. mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  54. return buf;
  55. }
  56. uint32_t bitcount(uint32_t n)
  57. {
  58. uint32_t c;
  59. for (c = 0; n; ++c) {
  60. n &= n - 1;
  61. }
  62. return c;
  63. }
  64. uint32_t netmask(uint32_t count)
  65. {
  66. return htonl(count <= 32 ? 0xffffffff << (32 - count) : 0);
  67. }
  68. int select_fd(int fd, unsigned timeout)
  69. {
  70. struct timeval tv;
  71. int status;
  72. fd_set fds;
  73. FD_ZERO(&fds);
  74. FD_SET(fd, &fds);
  75. tv.tv_sec = timeout / 1000;
  76. tv.tv_usec = 1000 * (timeout % 1000);
  77. status = select(fd + 1, &fds, NULL, NULL, &tv);
  78. if (status < 0) {
  79. sock_perror("select");
  80. }
  81. return status;
  82. }
  83. void xperror(const char *msg)
  84. {
  85. if (errno != EINTR) {
  86. perror(msg);
  87. } else {
  88. printf("\n");
  89. }
  90. }