1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <ctype.h>
18 #include <errno.h>
19 #include <ftw.h>
20 #include <libgen.h>
21 #include <stdarg.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <iostream>
27 #include <memory>
28 #include <string>
29 #include <vector>
30 
31 #include "android-base/logging.h"
32 
33 // The name of the directory that holds a staged time zone update distro. If this exists it should
34 // replace the one in CURRENT_DIR_NAME.
35 // See also com.android.timezone.distro.installer.TimeZoneDistroInstaller.
36 static const char* STAGED_DIR_NAME = "/staged";
37 
38 // The name of the directory that holds the (optional) installed time zone update distro.
39 // See also com.android.timezone.distro.installer.TimeZoneDistroInstaller.
40 static const char* CURRENT_DIR_NAME = "/current";
41 
42 // The name of a file in the staged dir that indicates the staged operation is an "uninstall".
43 // See also com.android.timezone.distro.installer.TimeZoneDistroInstaller.
44 static const char* UNINSTALL_TOMBSTONE_FILE_NAME = "/STAGED_UNINSTALL_TOMBSTONE";
45 
46 // The name of the file containing the distro version information.
47 // See also com.android.timezone.distro.TimeZoneDistro / com.android.timezone.distro.DistroVersion.
48 static const char* DISTRO_VERSION_FILENAME = "/distro_version";
49 
50 // The name of the file containing the base tz data set version information.
51 // See also libcore.timezone.TzDataSetVersion.
52 static const char* BASE_VERSION_FILENAME = "/tz_version";
53 
54 // distro_version / tz_version are ASCII files consisting of at least 17 bytes in the
55 // form: AAA.BBB|CCCCC|DDD
56 // AAA.BBB is the major/minor version of the format (e.g. 004.001),
57 // CCCCC is the rules version (e.g. 2016g),
58 // DDD is the android revision for this rules version to allow for data corrections (e.g. 001),
59 // We only use the first 13 to determine suitability of format / data.
60 static const int READ_DATA_LENGTH = 13;
61 
62 // Version bytes are: AAA.BBB|CCCCC - the format version is AAA.BBB
63 // The length of the format version,  e.g. "004.001" == 7 bytes
64 static const size_t FORMAT_VERSION_LEN = 7;
65 
66 // Version bytes are: AAA.BBB|CCCCC - the format major version is AAA
67 static const size_t FORMAT_MAJOR_VERSION_LEN = 3;
68 
69 // Version bytes are: AAA.BBB|CCCCC - the format major version is AAA
70 static const size_t FORMAT_MAJOR_VERSION_IDX = 0;
71 
72 // Version bytes are: AAA.BBB|CCCCC - the format major version is AAA
73 static const size_t FORMAT_MINOR_VERSION_LEN = 3;
74 
75 // Version bytes are: AAA.BBB|CCCCC - the format minor version is BBB
76 static const size_t FORMAT_MINOR_VERSION_IDX = 4;
77 
78 // Version bytes are: AAA.BBB|CCCCC - the IANA rules version is CCCCC
79 // The length of the IANA rules version bytes, e.g. 2016a
80 static const size_t RULES_VERSION_LEN = 5;
81 
82 // Version bytes are: AAA.BBB|CCCCC - the rules version is CCCCC
83 static const size_t VERSION_RULES_IDX = 8;
84 
85 
usage()86 static void usage() {
87     std::cerr << "Usage: tzdatacheck BASE_TZ_DIR DATA_TZ_DIR\n"
88             "\n"
89             "Checks whether any timezone update distro in DATA_TZ_DIR is compatible with the\n"
90             "current Android release and better than or the same as base timezone rules in\n"
91             "BASE_TZ_DIR. If the timezone rules in BASE_TZ_DIR are a higher version than the\n"
92             "one in DATA_TZ_DIR the DATA_TZ_DIR is renamed and then deleted.\n";
93     exit(1);
94 }
95 
96 /*
97  * Opens a file and fills buffer with the first byteCount bytes from the file.
98  * If the file does not exist or cannot be opened or is too short then false is returned.
99  * If the bytes were read successfully then true is returned.
100  */
readBytes(const std::string & fileName,char * buffer,size_t byteCount)101 static bool readBytes(const std::string& fileName, char* buffer, size_t byteCount) {
102     FILE* file = fopen(fileName.c_str(), "r");
103     if (file == nullptr) {
104         if (errno != ENOENT) {
105             PLOG(WARNING) << "Error opening file " << fileName;
106         }
107         return false;
108     }
109     size_t bytesRead = fread(buffer, 1, byteCount, file);
110     fclose(file);
111     if (bytesRead != byteCount) {
112         LOG(WARNING) << fileName << " is too small. " << byteCount << " bytes required";
113         return false;
114     }
115     return true;
116 }
117 
checkDigits(const char * buffer,const size_t count,size_t * i)118 static bool checkDigits(const char* buffer, const size_t count, size_t* i) {
119     for (size_t j = 0; j < count; j++) {
120       char toCheck = buffer[(*i)++];
121       if (!isdigit(toCheck)) {
122         return false;
123       }
124     }
125     return true;
126 }
127 
checkValidVersionBytes(const char * buffer)128 static bool checkValidVersionBytes(const char* buffer) {
129     // See READ_DATA_LENGTH comments above for a description of the format.
130     size_t i = 0;
131     if (!checkDigits(buffer, 3, &i)) {
132       return false;
133     }
134     if (buffer[i++] != '.') {
135       return false;
136     }
137     if (!checkDigits(buffer, 3, &i)) {
138       return false;
139     }
140     if (buffer[i++] != '|') {
141       return false;
142     }
143     if (!checkDigits(buffer, 4, &i)) {
144       return false;
145     }
146     // Ignore the last character. It is assumed to be a letter but we don't check because it's not
147     // obvious what would happen at 'z'.
148     return true;
149 }
150 
151 /* Return the parent directory of dirName. */
getParentDir(const std::string & dirName)152 static std::string getParentDir(const std::string& dirName) {
153     char *cMutableDirName = strdup(dirName.c_str());
154     std::string parentDir = dirname(cMutableDirName);
155     free(cMutableDirName);
156     return parentDir;
157 }
158 
159 /* Deletes a single file, symlink or directory. Called from nftw(). */
deleteFn(const char * fpath,const struct stat *,int typeflag,struct FTW *)160 static int deleteFn(const char* fpath, const struct stat*, int typeflag, struct FTW*) {
161     LOG(DEBUG) << "Inspecting " << fpath;
162     switch (typeflag) {
163     case FTW_F:
164     case FTW_SL:
165         LOG(DEBUG) << "Unlinking " << fpath;
166         if (unlink(fpath)) {
167             PLOG(WARNING) << "Failed to unlink file/symlink " << fpath;
168         }
169         break;
170     case FTW_D:
171     case FTW_DP:
172         LOG(DEBUG) << "Removing dir " << fpath;
173         if (rmdir(fpath)) {
174             PLOG(WARNING) << "Failed to remove dir " << fpath;
175         }
176         break;
177     default:
178         LOG(WARNING) << "Unsupported file type " << fpath << ": " << typeflag;
179         break;
180     }
181     return 0;
182 }
183 
184 enum PathStatus { ERR, NONE, IS_DIR, IS_REG, UNKNOWN };
185 
checkPath(const std::string & path)186 static PathStatus checkPath(const std::string& path) {
187     struct stat buf;
188     if (stat(path.c_str(), &buf) != 0) {
189         if (errno != ENOENT) {
190             PLOG(WARNING) << "Unable to stat " << path;
191             return ERR;
192         }
193         return NONE;
194     }
195     return S_ISDIR(buf.st_mode) ? IS_DIR : S_ISREG(buf.st_mode) ? IS_REG : UNKNOWN;
196 }
197 
198 /*
199  * Deletes fileToDelete and returns true if it is successful. If fileToDelete is not a file or
200  * cannot be accessed this method returns false.
201  */
deleteFile(const std::string & fileToDelete)202 static bool deleteFile(const std::string& fileToDelete) {
203     // Check whether the file exists.
204     PathStatus pathStatus = checkPath(fileToDelete);
205     if (pathStatus == NONE) {
206         LOG(INFO) << "Path " << fileToDelete << " does not exist";
207         return true;
208     }
209     if (pathStatus != IS_REG) {
210         LOG(WARNING) << "Path " << fileToDelete << " failed to stat() or is not a file.";
211         return false;
212     }
213 
214     // Attempt the deletion.
215     int rc = unlink(fileToDelete.c_str());
216     if (rc != 0) {
217         PLOG(WARNING) << "unlink() failed for " << fileToDelete;
218     }
219     return rc == 0;
220 }
221 
222 /*
223  * Deletes dirToDelete and returns true if it is successful in removing or moving the directory out
224  * of the way. If dirToDelete does not exist this function does nothing and returns true. If
225  * dirToDelete is not a directory or cannot be accessed this method returns false.
226  *
227  * During deletion, this function first renames the directory to a temporary name. If the temporary
228  * directory cannot be created, or the directory cannot be renamed, false is returned. After the
229  * rename, deletion of files and subdirs beneath the directory is performed on a "best effort"
230  * basis. Symlinks beneath the directory are not followed.
231  */
deleteDir(const std::string & dirToDelete)232 static bool deleteDir(const std::string& dirToDelete) {
233     // Check whether the dir exists.
234     int pathStatus = checkPath(dirToDelete);
235     if (pathStatus == NONE) {
236         LOG(INFO) << "Path " << dirToDelete << " does not exist";
237         return true;
238     }
239     if (pathStatus != IS_DIR) {
240         LOG(WARNING) << "Path " << dirToDelete << " failed to stat() or is not a directory.";
241         return false;
242     }
243 
244     // First, rename dirToDelete.
245 
246     std::string tempDirNameTemplate = getParentDir(dirToDelete);
247     tempDirNameTemplate += "/tempXXXXXX";
248 
249     // Create an empty directory with the temporary name. For this we need a non-const char*.
250     std::vector<char> tempDirName(tempDirNameTemplate.length() + 1);
251     strcpy(&tempDirName[0], tempDirNameTemplate.c_str());
252     if (mkdtemp(&tempDirName[0]) == nullptr) {
253         PLOG(WARNING) << "Unable to create a temporary directory: " << tempDirNameTemplate;
254         return false;
255     }
256 
257     // Rename dirToDelete to tempDirName (replacing the empty tempDirName directory created above).
258     int rc = rename(dirToDelete.c_str(), &tempDirName[0]);
259     if (rc == -1) {
260         PLOG(WARNING) << "Unable to rename directory from " << dirToDelete << " to "
261                 << &tempDirName[0];
262         return false;
263     }
264 
265     // Recursively delete contents of tempDirName.
266 
267     rc = nftw(&tempDirName[0], deleteFn, 10 /* openFiles */,
268             FTW_DEPTH | FTW_MOUNT | FTW_PHYS);
269     if (rc == -1) {
270         LOG(INFO) << "Could not delete directory: " << &tempDirName[0];
271     }
272     return true;
273 }
274 
275 /*
276  * Deletes the timezone update distro directory.
277  */
deleteUpdateDistroDir(const std::string & distroDirName)278 static void deleteUpdateDistroDir(const std::string& distroDirName) {
279     LOG(INFO) << "Removing: " << distroDirName;
280     if (!deleteDir(distroDirName)) {
281         LOG(WARNING) << "Deletion of distro dir " << distroDirName << " was not successful";
282     }
283 }
284 
handleStagedUninstall(const std::string & dataStagedDirName,const std::string & dataCurrentDirName,const PathStatus dataCurrentDirStatus)285 static void handleStagedUninstall(const std::string& dataStagedDirName,
286                                   const std::string& dataCurrentDirName,
287                                   const PathStatus dataCurrentDirStatus) {
288     LOG(INFO) << "Staged operation is an uninstall.";
289 
290     // Delete the current install directory.
291     switch (dataCurrentDirStatus) {
292         case NONE:
293             // This is unexpected: No uninstall should be staged if there is nothing to
294             // uninstall. Carry on anyway.
295             LOG(WARNING) << "No current install to delete.";
296             break;
297         case IS_DIR:
298             // This is normal. Delete the current install dir.
299             if (!deleteDir(dataCurrentDirName)) {
300                 LOG(WARNING) << "Deletion of current distro " << dataCurrentDirName
301                              << " was not successful";
302                 // If this happens we don't know whether we were able to delete or not. We don't
303                 // delete the staged operation so it will be retried next boot unless overridden.
304                 return;
305             }
306             break;
307         case IS_REG:
308         default:
309             // This is unexpected: We can try to delete the unexpected file and carry on.
310             LOG(WARNING) << "Current distro dir " << dataCurrentDirName
311                          << " is not actually a directory. Attempting deletion.";
312             if (!deleteFile(dataCurrentDirName)) {
313                 LOG(WARNING) << "Could not delete " << dataCurrentDirName;
314                 return;
315             }
316             break;
317     }
318 
319     // Delete the staged uninstall dir.
320     if (!deleteDir(dataStagedDirName)) {
321         LOG(WARNING) << "Deletion of current distro " << dataCurrentDirName
322                      << " was not successful";
323         // If this happens we don't know whether we were able to delete the staged operation
324         // or not.
325         return;
326     }
327     LOG(INFO) << "Staged uninstall complete.";
328 }
329 
handleStagedInstall(const std::string & dataStagedDirName,const std::string & dataCurrentDirName,const PathStatus dataCurrentDirStatus)330 static void handleStagedInstall(const std::string& dataStagedDirName,
331                                 const std::string& dataCurrentDirName,
332                                 const PathStatus dataCurrentDirStatus) {
333     LOG(INFO) << "Staged operation is an install.";
334 
335     switch (dataCurrentDirStatus) {
336         case NONE:
337             // This is expected: This is the first install.
338             LOG(INFO) << "No current install to replace.";
339             break;
340         case IS_DIR:
341             // This is expected: We are replacing an existing install.
342             // Delete the current dir so we can replace it.
343             if (!deleteDir(dataCurrentDirName)) {
344                 LOG(WARNING) << "Deletion of current distro " << dataCurrentDirName
345                              << " was not successful";
346                 // If this happens, we cannot proceed.
347                 return;
348             }
349             break;
350         case IS_REG:
351         default:
352             // This is unexpected: We can try to delete the unexpected file and carry on.
353             LOG(WARNING) << "Current distro dir " << dataCurrentDirName
354                          << " is not actually a directory. Attempting deletion.";
355             if (!deleteFile(dataCurrentDirName)) {
356                 LOG(WARNING) << "Could not delete " << dataCurrentDirName;
357                 return;
358             }
359             break;
360     }
361 
362     // Move the staged dir so it is the new current dir, completing the install.
363     LOG(INFO) << "Moving " << dataStagedDirName << " to " << dataCurrentDirName;
364     int rc = rename(dataStagedDirName.c_str(), dataCurrentDirName.c_str());
365     if (rc == -1) {
366         PLOG(WARNING) << "Unable to rename directory from " << dataStagedDirName << " to "
367                       << &dataCurrentDirName[0];
368         return;
369     }
370 
371     LOG(INFO) << "Staged install complete.";
372 }
373 /*
374  * Process a staged operation if there is one.
375  */
processStagedOperation(const std::string & dataStagedDirName,const std::string & dataCurrentDirName)376 static void processStagedOperation(const std::string& dataStagedDirName,
377                                    const std::string& dataCurrentDirName) {
378     PathStatus dataStagedDirStatus = checkPath(dataStagedDirName);
379 
380     // Exit early for the common case.
381     if (dataStagedDirStatus == NONE) {
382         LOG(DEBUG) << "No staged time zone operation.";
383         return;
384     }
385 
386     // Check known directory names are in a good starting state.
387     if (dataStagedDirStatus != IS_DIR) {
388         LOG(WARNING) << "Staged distro dir " << dataStagedDirName
389                      << " could not be accessed or is not a directory."
390                      << " stagedDirStatus=" << dataStagedDirStatus;
391         return;
392     }
393 
394     // dataStagedDirStatus == IS_DIR.
395 
396     // Work out whether there is anything currently installed.
397     PathStatus dataCurrentDirStatus = checkPath(dataCurrentDirName);
398     if (dataCurrentDirStatus == ERR) {
399         LOG(WARNING) << "Current install dir " << dataCurrentDirName << " could not be accessed"
400                      << " dataCurrentDirStatus=" << dataCurrentDirStatus;
401         return;
402     }
403 
404     // We must perform the staged operation.
405 
406     // Check to see if the staged directory contains an uninstall or an install operation.
407     std::string uninstallTombStoneFile(dataStagedDirName);
408     uninstallTombStoneFile += UNINSTALL_TOMBSTONE_FILE_NAME;
409     int uninstallTombStoneFileStatus = checkPath(uninstallTombStoneFile);
410     if (uninstallTombStoneFileStatus != IS_REG && uninstallTombStoneFileStatus != NONE) {
411         // Error case.
412         LOG(WARNING) << "Unable to determine if the staged operation is an uninstall.";
413         return;
414     }
415     if (uninstallTombStoneFileStatus == IS_REG) {
416         handleStagedUninstall(dataStagedDirName, dataCurrentDirName, dataCurrentDirStatus);
417     } else {
418         // uninstallTombStoneFileStatus == NONE meaning this is a staged install.
419         handleStagedInstall(dataStagedDirName, dataCurrentDirName, dataCurrentDirStatus);
420     }
421 }
422 
423 /*
424  * After a platform update it is likely that the "base" timezone data found on the device will be
425  * newer than the version found in the data partition. This tool detects this case and removes the
426  * version in /data.
427  *
428  * Note: This code is related to code in com.android.server.updates.TzDataInstallReceiver. The
429  * paths for the metadata and current timezone data must match.
430  *
431  * Typically on device the two args will be:
432  *   /apex/com.google.runtime/etc/tz /data/misc/zoneinfo
433  *
434  * See usage() for usage notes.
435  */
main(int argc,char * argv[])436 int main(int argc, char* argv[]) {
437     if (argc != 3) {
438         usage();
439         return 1;
440     }
441 
442     const char* baseZoneInfoDir = argv[1];
443     const char* dataZoneInfoDir = argv[2];
444 
445     std::string dataStagedDirName(dataZoneInfoDir);
446     dataStagedDirName += STAGED_DIR_NAME;
447 
448     std::string dataCurrentDirName(dataZoneInfoDir);
449     dataCurrentDirName += CURRENT_DIR_NAME;
450 
451     // Check for an process any staged operation.
452     // If the staged operation could not be handled we still have to validate the current installed
453     // directory so we do not check for errors and do not quit early.
454     processStagedOperation(dataStagedDirName, dataCurrentDirName);
455 
456     // Check the distro directory exists. If it does not, exit quickly: nothing to do.
457     PathStatus dataCurrentDirStatus = checkPath(dataCurrentDirName);
458     if (dataCurrentDirStatus == NONE) {
459         LOG(INFO) << "timezone distro dir " << dataCurrentDirName
460                 << " does not exist. No action required.";
461         return 0;
462     }
463 
464     // If the distro directory path is not a directory or we can't stat() the path, exit with a
465     // warning: either there's a problem accessing storage or the world is not as it should be;
466     // nothing to do.
467     if (dataCurrentDirStatus != IS_DIR) {
468         LOG(WARNING) << "Current distro dir " << dataCurrentDirName
469                 << " could not be accessed or is not a directory. result=" << dataCurrentDirStatus;
470         return 2;
471     }
472 
473     // Check the installed distro version.
474     std::string distroVersionFileName(dataCurrentDirName);
475     distroVersionFileName += DISTRO_VERSION_FILENAME;
476     std::vector<char> distroVersion;
477     distroVersion.reserve(READ_DATA_LENGTH);
478     bool distroVersionReadOk =
479             readBytes(distroVersionFileName, distroVersion.data(), READ_DATA_LENGTH);
480     if (!distroVersionReadOk) {
481         LOG(WARNING) << "distro version file " << distroVersionFileName
482                 << " does not exist or is too short. Deleting distro dir.";
483         // Implies the contents of the data partition is corrupt in some way. Try to clean up.
484         deleteUpdateDistroDir(dataCurrentDirName);
485         return 3;
486     }
487 
488     if (!checkValidVersionBytes(distroVersion.data())) {
489         LOG(WARNING) << "distro version file " << distroVersionFileName
490                 << " is not valid. Deleting distro dir.";
491         // Implies the contents of the data partition is corrupt in some way. Try to clean up.
492         deleteUpdateDistroDir(dataCurrentDirName);
493         return 4;
494     }
495 
496     // Check the base tz data set version.
497     std::string baseVersionFileName(baseZoneInfoDir);
498     baseVersionFileName += BASE_VERSION_FILENAME;
499     std::vector<char> baseVersion;
500     baseVersion.reserve(READ_DATA_LENGTH);
501     bool baseVersionReadOk =
502             readBytes(baseVersionFileName, baseVersion.data(), READ_DATA_LENGTH);
503     if (!baseVersionReadOk) {
504         // Implies the contents of the system partition is corrupt in some way. Nothing we can do.
505         LOG(WARNING) << baseVersionFileName << " does not exist or could not be opened";
506         return 6;
507     }
508 
509     if (!checkValidVersionBytes(baseVersion.data())) {
510         // Implies the contents of the system partition is corrupt in some way. Nothing we can do.
511         LOG(WARNING) << baseVersionFileName << " is not valid.";
512         return 7;
513     }
514 
515     std::string actualDistroVersion = std::string(distroVersion.data(), FORMAT_VERSION_LEN);
516     std::string baseTzVersion = std::string(baseVersion.data(), FORMAT_VERSION_LEN);
517 
518     // Check the first 3 bytes of the format version: these are the major version (e.g. 001).
519     // It must match the one we support exactly to be ok.
520     if (strncmp(
521             &distroVersion[FORMAT_MAJOR_VERSION_IDX],
522             &baseTzVersion[FORMAT_MAJOR_VERSION_IDX],
523             FORMAT_MAJOR_VERSION_LEN) != 0) {
524 
525         LOG(INFO) << "distro version file " << distroVersionFileName
526                 << " major version is not the required version " << baseTzVersion
527                 << ", was \"" << actualDistroVersion << "\". Deleting distro dir.";
528         // This implies there has been an OTA and the installed distro is not compatible with a
529         // new version of Android. Remove the installed distro.
530         deleteUpdateDistroDir(dataCurrentDirName);
531         return 5;
532     }
533 
534     // Check the last 3 bytes of the format version: these are the minor version (e.g. 001).
535     // If the version in the distro is < the minor version required by this device it cannot be
536     // used.
537     if (strncmp(
538             &distroVersion[FORMAT_MINOR_VERSION_IDX],
539             &baseTzVersion[FORMAT_MINOR_VERSION_IDX],
540             FORMAT_MINOR_VERSION_LEN) < 0) {
541 
542         LOG(INFO) << "distro version file " << distroVersionFileName
543                 << " minor version is not the required version " << baseTzVersion
544                 << ", was \"" << actualDistroVersion << "\". Deleting distro dir.";
545         // This implies there has been an OTA and the installed distro is not compatible with a
546         // new version of Android. Remove the installed distro.
547         deleteUpdateDistroDir(dataCurrentDirName);
548         return 5;
549     }
550 
551     // Compare the distro rules version against the system rules version.
552     if (strncmp(
553             &baseVersion[VERSION_RULES_IDX],
554             &distroVersion[VERSION_RULES_IDX],
555             RULES_VERSION_LEN) <= 0) {
556         LOG(INFO) << "Found an installed distro but it is valid. No action taken.";
557         // Implies there is an installed update, but it is good.
558         return 0;
559     }
560 
561     // Implies there has been an OTA and the system version of the timezone rules is now newer
562     // than the version installed in /data. Remove the installed distro.
563     LOG(INFO) << "timezone distro in " << dataCurrentDirName << " is older than data in "
564             << baseVersionFileName << "; fixing...";
565 
566     deleteUpdateDistroDir(dataCurrentDirName);
567     return 0;
568 }
569