1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *  * Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *  * Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in
12  *    the documentation and/or other materials provided with the
13  *    distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <arpa/inet.h> // For ntohl(3).
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <stdint.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 
36 #include "private/CachedProperty.h"
37 
38 extern "C" void tzset_unlocked(void);
39 extern "C" void __bionic_get_system_tz(char* buf, size_t n);
40 extern "C" int __bionic_open_tzdata(const char*, int32_t*);
41 
42 extern "C" void tzsetlcl(char const*);
43 
__bionic_get_system_tz(char * buf,size_t n)44 void __bionic_get_system_tz(char* buf, size_t n) {
45   static CachedProperty persist_sys_timezone("persist.sys.timezone");
46   const char* name = persist_sys_timezone.Get();
47 
48   // If the system property is not set, perhaps because this is called
49   // before the default value has been set (the recovery image being a
50   // classic example), fall back to GMT.
51   if (name == nullptr) name = "GMT";
52 
53   strlcpy(buf, name, n);
54 
55   if (!strcmp(buf, "GMT")) {
56     // Typically we'll set the system property to an Olson ID, but
57     // java.util.TimeZone also supports the "GMT+xxxx" style, and at
58     // least historically (see http://b/25463955) some Android-based set
59     // top boxes would get the timezone from the TV network in this format
60     // and use it directly in the system property. This caused trouble
61     // for native code because POSIX and Java disagree about the sign in
62     // a timezone string. For POSIX, "GMT+3" means "3 hours west/behind",
63     // but for Java it means "3 hours east/ahead". Since (a) Java is the
64     // one that matches human expectations and (b) this system property is
65     // used directly by Java, we flip the sign here to translate from Java
66     // to POSIX. We only need to worry about the "GMT+xxxx" case because
67     // the expectation is that these are valid java.util.TimeZone ids,
68     // not general POSIX custom timezone specifications (which is why this
69     // code only applies to the system property, and not to the environment
70     // variable).
71     char sign = buf[3];
72     if (sign == '-' || sign == '+') {
73       buf[3] = (sign == '-') ? '+' : '-';
74     }
75   }
76 }
77 
tzset_unlocked()78 void tzset_unlocked() {
79   // The TZ environment variable is meant to override the system-wide setting.
80   const char* name = getenv("TZ");
81   char buf[PROP_VALUE_MAX];
82 
83   // If that's not set, look at the "persist.sys.timezone" system property.
84   if (name == nullptr) {
85     __bionic_get_system_tz(buf, sizeof(buf));
86     name = buf;
87   }
88 
89   tzsetlcl(name);
90 }
91 
92 #if !defined(__ANDROID__)
make_path(const char * path_prefix_variable,const char * path_suffix)93 static char* make_path(const char* path_prefix_variable,
94                        const char* path_suffix) {
95   const char* path_prefix = getenv(path_prefix_variable);
96   if (path_prefix == nullptr) {
97     fprintf(stderr, "%s: %s not set!\n", __FUNCTION__, path_prefix_variable);
98     abort();
99   }
100   char* path;
101   if (asprintf(&path, "%s/%s", path_prefix, path_suffix) == -1) {
102     fprintf(stderr, "%s: couldn't allocate \"%s/%s\"\n", __FUNCTION__, path_prefix, path_suffix);
103     abort();
104   }
105   return path;
106 }
107 #endif
108 
109 // byte[12] tzdata_version  -- "tzdata2012f\0"
110 // int index_offset
111 // int data_offset
112 // int final_offset
113 struct bionic_tzdata_header_t {
114   char tzdata_version[12];
115   int32_t index_offset;
116   int32_t data_offset;
117   int32_t final_offset;
118 };
119 static constexpr size_t NAME_LENGTH = 40;
120 struct index_entry_t {
121   char buf[NAME_LENGTH];
122   int32_t start;
123   int32_t length;
124   int32_t unused; // Was raw GMT offset; always 0 since tzdata2014f (L).
125 };
126 
127 // Returns -2 for a soft failure (where the caller should try another file),
128 // -1 for a hard failure (where the caller should give up), and >= 0 is a
129 // file descriptor whose offset points to the data for the given olson id in
130 // the given file (and *entry_length is the size of the data).
__bionic_open_tzdata_path(const char * path,const char * olson_id,int32_t * entry_length)131 static int __bionic_open_tzdata_path(const char* path,
132                                      const char* olson_id,
133                                      int32_t* entry_length) {
134   int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
135   if (fd == -1) {
136     // We don't log here, because this is quite common --- current devices
137     // aren't expected to have the old APK tzdata, for example.
138     return -2;
139   }
140 
141   bionic_tzdata_header_t header = {};
142   ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, &header, sizeof(header)));
143   if (bytes_read != sizeof(header)) {
144     fprintf(stderr, "%s: could not read header of \"%s\": %s\n",
145             __FUNCTION__, path, (bytes_read == -1) ? strerror(errno) : "short read");
146     close(fd);
147     return -2;
148   }
149 
150   if (strncmp(header.tzdata_version, "tzdata", 6) != 0 || header.tzdata_version[11] != 0) {
151     fprintf(stderr, "%s: bad magic in \"%s\": \"%.6s\"\n", __FUNCTION__, path, header.tzdata_version);
152     close(fd);
153     return -2;
154   }
155 
156   if (TEMP_FAILURE_RETRY(lseek(fd, ntohl(header.index_offset), SEEK_SET)) == -1) {
157     fprintf(stderr, "%s: couldn't seek to index in \"%s\": %s\n", __FUNCTION__, path, strerror(errno));
158     close(fd);
159     return -2;
160   }
161 
162   if (ntohl(header.index_offset) > ntohl(header.data_offset)) {
163     fprintf(stderr, "%s: invalid data and index offsets in \"%s\": %u %u\n",
164             __FUNCTION__, path, ntohl(header.data_offset), ntohl(header.index_offset));
165     close(fd);
166     return -2;
167   }
168   const size_t index_size = ntohl(header.data_offset) - ntohl(header.index_offset);
169   if ((index_size % sizeof(index_entry_t)) != 0) {
170     fprintf(stderr, "%s: invalid index size in \"%s\": %zd\n", __FUNCTION__, path, index_size);
171     close(fd);
172     return -2;
173   }
174 
175   char* index = reinterpret_cast<char*>(malloc(index_size));
176   if (index == nullptr) {
177     fprintf(stderr, "%s: couldn't allocate %zd-byte index for \"%s\"\n", __FUNCTION__, index_size, path);
178     close(fd);
179     return -2;
180   }
181   if (TEMP_FAILURE_RETRY(read(fd, index, index_size)) != static_cast<ssize_t>(index_size)) {
182     fprintf(stderr, "%s: could not read index of \"%s\": %s\n",
183             __FUNCTION__, path, (bytes_read == -1) ? strerror(errno) : "short read");
184     free(index);
185     close(fd);
186     return -2;
187   }
188 
189   off_t specific_zone_offset = -1;
190   size_t id_count = index_size / sizeof(index_entry_t);
191   index_entry_t* entry = reinterpret_cast<index_entry_t*>(index);
192   for (size_t i = 0; i < id_count; ++i) {
193     char this_id[NAME_LENGTH + 1];
194     memcpy(this_id, entry->buf, NAME_LENGTH);
195     this_id[NAME_LENGTH] = '\0';
196 
197     if (strcmp(this_id, olson_id) == 0) {
198       specific_zone_offset = ntohl(entry->start) + ntohl(header.data_offset);
199       *entry_length = ntohl(entry->length);
200       break;
201     }
202 
203     ++entry;
204   }
205   free(index);
206 
207   if (specific_zone_offset == -1) {
208     // We found a valid tzdata file, but didn't find the requested id in it.
209     // Give up now, and don't try fallback tzdata files. We don't log here
210     // because for all we know the given olson id was nonsense.
211     close(fd);
212     // This file descriptor (-1) is passed to localtime.c. In invalid fd case
213     // upstream passes errno value around methods and having 0 there will
214     // indicate that timezone was found and read successfully and localtime's
215     // internal state was properly initialized (which wasn't as we couldn't find
216     // requested timezone in the tzdata file).
217     // If we reached this point errno is unlikely to be touched. It is only
218     // close(fd) which can do it, but that is very unlikely to happen. And
219     // even if it happens we can't extract any useful insights from it.
220     // We are overriding it to ENOENT as it matches upstream expectations -
221     // timezone is absent in the tzdata file == there is no TZif file in
222     // /usr/share/zoneinfo.
223     errno = ENOENT;
224     return -1;
225   }
226 
227   if (TEMP_FAILURE_RETRY(lseek(fd, specific_zone_offset, SEEK_SET)) == -1) {
228     fprintf(stderr, "%s: could not seek to %ld in \"%s\": %s\n",
229             __FUNCTION__, specific_zone_offset, path, strerror(errno));
230     close(fd);
231     return -2;
232   }
233 
234   return fd;
235 }
236 
__bionic_open_tzdata(const char * olson_id,int32_t * entry_length)237 int __bionic_open_tzdata(const char* olson_id, int32_t* entry_length) {
238   int fd;
239 
240   // Try the two locations for the tzdata file in a strict order:
241   // 1: The timezone data module which contains the main copy. This is the
242   //    common case for current devices.
243   // 2: The ultimate fallback: the non-updatable copy in /system.
244 
245 #if defined(__ANDROID__)
246   // On Android devices, bionic has to work even if exec takes place without
247   // environment variables set. So, all paths are hardcoded here.
248   fd = __bionic_open_tzdata_path("/apex/com.android.tzdata/etc/tz/tzdata",
249                                  olson_id, entry_length);
250   if (fd >= -1) return fd;
251 
252   fd = __bionic_open_tzdata_path("/system/usr/share/zoneinfo/tzdata",
253                                  olson_id, entry_length);
254   if (fd >= -1) return fd;
255 #else
256   // On the host, we don't expect the hard-coded locations above to exist, and
257   // we're not worried about security so we trust $ANDROID_TZDATA_ROOT, and
258   // $ANDROID_ROOT to point us in the right direction instead.
259 
260   char* path = make_path("ANDROID_TZDATA_ROOT", "/etc/tz/tzdata");
261   fd = __bionic_open_tzdata_path(path, olson_id, entry_length);
262   free(path);
263   if (fd >= -1) return fd;
264 
265   path = make_path("ANDROID_ROOT", "/usr/share/zoneinfo/tzdata");
266   fd = __bionic_open_tzdata_path(path, olson_id, entry_length);
267   free(path);
268   if (fd >= -1) return fd;
269 #endif
270 
271   // Not finding any tzdata is more serious that not finding a specific zone,
272   // and worth logging.
273   if (fd == -2) {
274     // The first thing that 'recovery' does is try to format the current time. It doesn't have
275     // any tzdata available, so we must not abort here --- doing so breaks the recovery image!
276     fprintf(stderr, "%s: couldn't find any tzdata when looking for %s!\n", __FUNCTION__, olson_id);
277   }
278 
279   // Otherwise we were successful.
280   return fd;
281 }
282