rtc.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Common RTC functions
  3. *
  4. * Licensed under GPLv2, see file LICENSE in this tarball for details.
  5. */
  6. #include "libbb.h"
  7. #include "rtc_.h"
  8. #if ENABLE_FEATURE_HWCLOCK_ADJTIME_FHS
  9. # define ADJTIME_PATH "/var/lib/hwclock/adjtime"
  10. #else
  11. # define ADJTIME_PATH "/etc/adjtime"
  12. #endif
  13. int FAST_FUNC rtc_adjtime_is_utc(void)
  14. {
  15. int utc = 0;
  16. FILE *f = fopen_for_read(ADJTIME_PATH);
  17. if (f) {
  18. RESERVE_CONFIG_BUFFER(buffer, 128);
  19. while (fgets(buffer, sizeof(buffer), f)) {
  20. int len = strlen(buffer);
  21. while (len && isspace(buffer[len - 1]))
  22. len--;
  23. buffer[len] = 0;
  24. if (strncmp(buffer, "UTC", 3) == 0) {
  25. utc = 1;
  26. break;
  27. }
  28. }
  29. fclose(f);
  30. RELEASE_CONFIG_BUFFER(buffer);
  31. }
  32. return utc;
  33. }
  34. int FAST_FUNC rtc_xopen(const char **default_rtc, int flags)
  35. {
  36. int rtc;
  37. if (!*default_rtc) {
  38. *default_rtc = "/dev/rtc";
  39. rtc = open(*default_rtc, flags);
  40. if (rtc >= 0)
  41. return rtc;
  42. *default_rtc = "/dev/rtc0";
  43. rtc = open(*default_rtc, flags);
  44. if (rtc >= 0)
  45. return rtc;
  46. *default_rtc = "/dev/misc/rtc";
  47. }
  48. return xopen(*default_rtc, flags);
  49. }
  50. time_t FAST_FUNC rtc_read_time(int fd, int utc)
  51. {
  52. struct tm tm;
  53. char *oldtz = 0;
  54. time_t t = 0;
  55. memset(&tm, 0, sizeof(struct tm));
  56. xioctl(fd, RTC_RD_TIME, &tm);
  57. tm.tm_isdst = -1; /* not known */
  58. if (utc) {
  59. oldtz = getenv("TZ");
  60. putenv((char*)"TZ=UTC0");
  61. tzset();
  62. }
  63. t = mktime(&tm);
  64. if (utc) {
  65. unsetenv("TZ");
  66. if (oldtz)
  67. putenv(oldtz - 3);
  68. tzset();
  69. }
  70. return t;
  71. }