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