Mike Frysinger | 6b160e4 | 2008-02-15 02:27:19 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Common RTC functions |
| 3 | */ |
| 4 | |
| 5 | #include "libbb.h" |
| 6 | #include "rtc_.h" |
| 7 | |
| 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 | |
| 14 | int rtc_adjtime_is_utc(void) |
| 15 | { |
| 16 | int utc = 0; |
| 17 | FILE *f = fopen(ADJTIME_PATH, "r"); |
| 18 | |
| 19 | if (f) { |
| 20 | RESERVE_CONFIG_BUFFER(buffer, 128); |
| 21 | |
| 22 | while (fgets(buffer, sizeof(buffer), f)) { |
| 23 | int len = strlen(buffer); |
| 24 | |
| 25 | while (len && isspace(buffer[len - 1])) |
| 26 | len--; |
| 27 | |
| 28 | buffer[len] = 0; |
| 29 | |
| 30 | if (strncmp(buffer, "UTC", 3) == 0) { |
| 31 | utc = 1; |
| 32 | break; |
| 33 | } |
| 34 | } |
| 35 | fclose(f); |
| 36 | |
| 37 | RELEASE_CONFIG_BUFFER(buffer); |
| 38 | } |
| 39 | |
| 40 | return utc; |
| 41 | } |
| 42 | |
Mike Frysinger | 977bc6a | 2008-02-15 07:19:03 +0000 | [diff] [blame^] | 43 | int rtc_xopen(const char **default_rtc, int flags) |
Mike Frysinger | 6b160e4 | 2008-02-15 02:27:19 +0000 | [diff] [blame] | 44 | { |
| 45 | int rtc; |
| 46 | |
Mike Frysinger | 977bc6a | 2008-02-15 07:19:03 +0000 | [diff] [blame^] | 47 | if (!*default_rtc) { |
| 48 | *default_rtc = "/dev/rtc"; |
| 49 | rtc = open(*default_rtc, flags); |
Mike Frysinger | 6b160e4 | 2008-02-15 02:27:19 +0000 | [diff] [blame] | 50 | if (rtc >= 0) |
| 51 | return rtc; |
Mike Frysinger | 977bc6a | 2008-02-15 07:19:03 +0000 | [diff] [blame^] | 52 | *default_rtc = "/dev/rtc0"; |
| 53 | rtc = open(*default_rtc, flags); |
Mike Frysinger | 6b160e4 | 2008-02-15 02:27:19 +0000 | [diff] [blame] | 54 | if (rtc >= 0) |
| 55 | return rtc; |
Mike Frysinger | 977bc6a | 2008-02-15 07:19:03 +0000 | [diff] [blame^] | 56 | *default_rtc = "/dev/misc/rtc"; |
Mike Frysinger | 6b160e4 | 2008-02-15 02:27:19 +0000 | [diff] [blame] | 57 | } |
| 58 | |
Mike Frysinger | 977bc6a | 2008-02-15 07:19:03 +0000 | [diff] [blame^] | 59 | return xopen(*default_rtc, flags); |
Mike Frysinger | 6b160e4 | 2008-02-15 02:27:19 +0000 | [diff] [blame] | 60 | } |
| 61 | |
| 62 | time_t rtc_read_time(int fd, int utc) |
| 63 | { |
| 64 | struct tm tm; |
| 65 | char *oldtz = 0; |
| 66 | time_t t = 0; |
| 67 | |
| 68 | memset(&tm, 0, sizeof(struct tm)); |
| 69 | xioctl(fd, RTC_RD_TIME, &tm); |
| 70 | tm.tm_isdst = -1; /* not known */ |
| 71 | |
| 72 | if (utc) { |
| 73 | oldtz = getenv("TZ"); |
| 74 | putenv((char*)"TZ=UTC0"); |
| 75 | tzset(); |
| 76 | } |
| 77 | |
| 78 | t = mktime(&tm); |
| 79 | |
| 80 | if (utc) { |
| 81 | unsetenv("TZ"); |
| 82 | if (oldtz) |
| 83 | putenv(oldtz - 3); |
| 84 | tzset(); |
| 85 | } |
| 86 | |
| 87 | return t; |
| 88 | } |