1 /* 2 * Copyright (C) 2009 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 "updater/install.h" 18 19 #include <ctype.h> 20 #include <errno.h> 21 #include <fcntl.h> 22 #include <ftw.h> 23 #include <inttypes.h> 24 #include <stdarg.h> 25 #include <stdio.h> 26 #include <stdlib.h> 27 #include <string.h> 28 #include <sys/capability.h> 29 #include <sys/mount.h> 30 #include <sys/stat.h> 31 #include <sys/types.h> 32 #include <sys/wait.h> 33 #include <sys/xattr.h> 34 #include <time.h> 35 #include <unistd.h> 36 #include <utime.h> 37 38 #include <memory> 39 #include <string> 40 #include <vector> 41 42 #include <android-base/file.h> 43 #include <android-base/logging.h> 44 #include <android-base/parsedouble.h> 45 #include <android-base/parseint.h> 46 #include <android-base/properties.h> 47 #include <android-base/stringprintf.h> 48 #include <android-base/strings.h> 49 #include <applypatch/applypatch.h> 50 #include <bootloader_message/bootloader_message.h> 51 #include <cutils/android_reboot.h> 52 #include <ext4_utils/make_ext4fs.h> 53 #include <ext4_utils/wipe.h> 54 #include <openssl/sha.h> 55 #include <selinux/label.h> 56 #include <selinux/selinux.h> 57 #include <ziparchive/zip_archive.h> 58 59 #include "edify/expr.h" 60 #include "error_code.h" 61 #include "mounts.h" 62 #include "ota_io.h" 63 #include "otautil/DirUtil.h" 64 #include "print_sha1.h" 65 #include "tune2fs.h" 66 #include "updater/updater.h" 67 68 // Send over the buffer to recovery though the command pipe. 69 static void uiPrint(State* state, const std::string& buffer) { 70 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie); 71 72 // "line1\nline2\n" will be split into 3 tokens: "line1", "line2" and "". 73 // So skip sending empty strings to UI. 74 std::vector<std::string> lines = android::base::Split(buffer, "\n"); 75 for (auto& line : lines) { 76 if (!line.empty()) { 77 fprintf(ui->cmd_pipe, "ui_print %s\n", line.c_str()); 78 } 79 } 80 81 // On the updater side, we need to dump the contents to stderr (which has 82 // been redirected to the log file). Because the recovery will only print 83 // the contents to screen when processing pipe command ui_print. 84 LOG(INFO) << buffer; 85 } 86 87 void uiPrintf(State* _Nonnull state, const char* _Nonnull format, ...) { 88 std::string error_msg; 89 90 va_list ap; 91 va_start(ap, format); 92 android::base::StringAppendV(&error_msg, format, ap); 93 va_end(ap); 94 95 uiPrint(state, error_msg); 96 } 97 98 static bool is_dir(const std::string& dirpath) { 99 struct stat st; 100 return stat(dirpath.c_str(), &st) == 0 && S_ISDIR(st.st_mode); 101 } 102 103 // Create all parent directories of name, if necessary. 104 static bool make_parents(const std::string& name) { 105 size_t prev_end = 0; 106 while (prev_end < name.size()) { 107 size_t next_end = name.find('/', prev_end + 1); 108 if (next_end == std::string::npos) { 109 break; 110 } 111 std::string dir_path = name.substr(0, next_end); 112 if (!is_dir(dir_path)) { 113 int result = mkdir(dir_path.c_str(), 0700); 114 if (result != 0) { 115 PLOG(ERROR) << "failed to mkdir " << dir_path << " when make parents for " << name; 116 return false; 117 } 118 119 LOG(INFO) << "created [" << dir_path << "]"; 120 } 121 prev_end = next_end; 122 } 123 return true; 124 } 125 126 // mount(fs_type, partition_type, location, mount_point) 127 // mount(fs_type, partition_type, location, mount_point, mount_options) 128 129 // fs_type="ext4" partition_type="EMMC" location=device 130 Value* MountFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 131 if (argv.size() != 4 && argv.size() != 5) { 132 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 4-5 args, got %zu", name, 133 argv.size()); 134 } 135 136 std::vector<std::string> args; 137 if (!ReadArgs(state, argv, &args)) { 138 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); 139 } 140 const std::string& fs_type = args[0]; 141 const std::string& partition_type = args[1]; 142 const std::string& location = args[2]; 143 const std::string& mount_point = args[3]; 144 std::string mount_options; 145 146 if (argv.size() == 5) { 147 mount_options = args[4]; 148 } 149 150 if (fs_type.empty()) { 151 return ErrorAbort(state, kArgsParsingFailure, "fs_type argument to %s() can't be empty", name); 152 } 153 if (partition_type.empty()) { 154 return ErrorAbort(state, kArgsParsingFailure, "partition_type argument to %s() can't be empty", 155 name); 156 } 157 if (location.empty()) { 158 return ErrorAbort(state, kArgsParsingFailure, "location argument to %s() can't be empty", name); 159 } 160 if (mount_point.empty()) { 161 return ErrorAbort(state, kArgsParsingFailure, "mount_point argument to %s() can't be empty", 162 name); 163 } 164 165 { 166 char* secontext = nullptr; 167 168 if (sehandle) { 169 selabel_lookup(sehandle, &secontext, mount_point.c_str(), 0755); 170 setfscreatecon(secontext); 171 } 172 173 mkdir(mount_point.c_str(), 0755); 174 175 if (secontext) { 176 freecon(secontext); 177 setfscreatecon(nullptr); 178 } 179 } 180 181 if (mount(location.c_str(), mount_point.c_str(), fs_type.c_str(), 182 MS_NOATIME | MS_NODEV | MS_NODIRATIME, mount_options.c_str()) < 0) { 183 uiPrintf(state, "%s: Failed to mount %s at %s: %s", name, location.c_str(), mount_point.c_str(), 184 strerror(errno)); 185 return StringValue(""); 186 } 187 188 return StringValue(mount_point); 189 } 190 191 // is_mounted(mount_point) 192 Value* IsMountedFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 193 if (argv.size() != 1) { 194 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 arg, got %zu", name, argv.size()); 195 } 196 197 std::vector<std::string> args; 198 if (!ReadArgs(state, argv, &args)) { 199 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); 200 } 201 const std::string& mount_point = args[0]; 202 if (mount_point.empty()) { 203 return ErrorAbort(state, kArgsParsingFailure, 204 "mount_point argument to unmount() can't be empty"); 205 } 206 207 scan_mounted_volumes(); 208 MountedVolume* vol = find_mounted_volume_by_mount_point(mount_point.c_str()); 209 if (vol == nullptr) { 210 return StringValue(""); 211 } 212 213 return StringValue(mount_point); 214 } 215 216 Value* UnmountFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 217 if (argv.size() != 1) { 218 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 arg, got %zu", name, argv.size()); 219 } 220 std::vector<std::string> args; 221 if (!ReadArgs(state, argv, &args)) { 222 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); 223 } 224 const std::string& mount_point = args[0]; 225 if (mount_point.empty()) { 226 return ErrorAbort(state, kArgsParsingFailure, 227 "mount_point argument to unmount() can't be empty"); 228 } 229 230 scan_mounted_volumes(); 231 MountedVolume* vol = find_mounted_volume_by_mount_point(mount_point.c_str()); 232 if (vol == nullptr) { 233 uiPrintf(state, "Failed to unmount %s: No such volume", mount_point.c_str()); 234 return nullptr; 235 } else { 236 int ret = unmount_mounted_volume(vol); 237 if (ret != 0) { 238 uiPrintf(state, "Failed to unmount %s: %s", mount_point.c_str(), strerror(errno)); 239 } 240 } 241 242 return StringValue(mount_point); 243 } 244 245 static int exec_cmd(const char* path, char* const argv[]) { 246 pid_t child; 247 if ((child = vfork()) == 0) { 248 execv(path, argv); 249 _exit(EXIT_FAILURE); 250 } 251 252 int status; 253 waitpid(child, &status, 0); 254 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { 255 LOG(ERROR) << path << " failed with status " << WEXITSTATUS(status); 256 } 257 return WEXITSTATUS(status); 258 } 259 260 // format(fs_type, partition_type, location, fs_size, mount_point) 261 // 262 // fs_type="ext4" partition_type="EMMC" location=device fs_size=<bytes> mount_point=<location> 263 // fs_type="f2fs" partition_type="EMMC" location=device fs_size=<bytes> mount_point=<location> 264 // if fs_size == 0, then make fs uses the entire partition. 265 // if fs_size > 0, that is the size to use 266 // if fs_size < 0, then reserve that many bytes at the end of the partition (not for "f2fs") 267 Value* FormatFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 268 if (argv.size() != 5) { 269 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 5 args, got %zu", name, 270 argv.size()); 271 } 272 273 std::vector<std::string> args; 274 if (!ReadArgs(state, argv, &args)) { 275 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); 276 } 277 const std::string& fs_type = args[0]; 278 const std::string& partition_type = args[1]; 279 const std::string& location = args[2]; 280 const std::string& fs_size = args[3]; 281 const std::string& mount_point = args[4]; 282 283 if (fs_type.empty()) { 284 return ErrorAbort(state, kArgsParsingFailure, "fs_type argument to %s() can't be empty", name); 285 } 286 if (partition_type.empty()) { 287 return ErrorAbort(state, kArgsParsingFailure, "partition_type argument to %s() can't be empty", 288 name); 289 } 290 if (location.empty()) { 291 return ErrorAbort(state, kArgsParsingFailure, "location argument to %s() can't be empty", name); 292 } 293 if (mount_point.empty()) { 294 return ErrorAbort(state, kArgsParsingFailure, "mount_point argument to %s() can't be empty", 295 name); 296 } 297 298 int64_t size; 299 if (!android::base::ParseInt(fs_size, &size)) { 300 return ErrorAbort(state, kArgsParsingFailure, "%s: failed to parse int in %s\n", name, 301 fs_size.c_str()); 302 } 303 304 if (fs_type == "ext4") { 305 const char* mke2fs_argv[] = { "/sbin/mke2fs_static", "-t", "ext4", "-b", "4096", 306 location.c_str(), nullptr, nullptr }; 307 std::string size_str; 308 if (size != 0) { 309 size_str = std::to_string(size / 4096LL); 310 mke2fs_argv[6] = size_str.c_str(); 311 } 312 313 int status = exec_cmd(mke2fs_argv[0], const_cast<char**>(mke2fs_argv)); 314 if (status != 0) { 315 LOG(WARNING) << name << ": mke2fs failed (" << status << ") on " << location 316 << ", falling back to make_ext4fs"; 317 status = make_ext4fs(location.c_str(), size, mount_point.c_str(), sehandle); 318 if (status != 0) { 319 LOG(ERROR) << name << ": make_ext4fs failed (" << status << ") on " << location; 320 return StringValue(""); 321 } 322 return StringValue(location); 323 } 324 325 const char* e2fsdroid_argv[] = { "/sbin/e2fsdroid_static", "-e", "-a", mount_point.c_str(), 326 location.c_str(), nullptr }; 327 status = exec_cmd(e2fsdroid_argv[0], const_cast<char**>(e2fsdroid_argv)); 328 if (status != 0) { 329 LOG(ERROR) << name << ": e2fsdroid failed (" << status << ") on " << location; 330 return StringValue(""); 331 } 332 return StringValue(location); 333 } else if (fs_type == "f2fs") { 334 if (size < 0) { 335 LOG(ERROR) << name << ": fs_size can't be negative for f2fs: " << fs_size; 336 return StringValue(""); 337 } 338 std::string num_sectors = std::to_string(size / 512); 339 340 const char* f2fs_path = "/sbin/mkfs.f2fs"; 341 const char* f2fs_argv[] = { 342 "mkfs.f2fs", "-t", "-d1", location.c_str(), (size < 512) ? nullptr : num_sectors.c_str(), 343 nullptr 344 }; 345 int status = exec_cmd(f2fs_path, const_cast<char**>(f2fs_argv)); 346 if (status != 0) { 347 LOG(ERROR) << name << ": mkfs.f2fs failed (" << status << ") on " << location; 348 return StringValue(""); 349 } 350 return StringValue(location); 351 } else { 352 LOG(ERROR) << name << ": unsupported fs_type \"" << fs_type << "\" partition_type \"" 353 << partition_type << "\""; 354 } 355 356 return nullptr; 357 } 358 359 Value* ShowProgressFn(const char* name, State* state, 360 const std::vector<std::unique_ptr<Expr>>& argv) { 361 if (argv.size() != 2) { 362 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 2 args, got %zu", name, 363 argv.size()); 364 } 365 366 std::vector<std::string> args; 367 if (!ReadArgs(state, argv, &args)) { 368 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); 369 } 370 const std::string& frac_str = args[0]; 371 const std::string& sec_str = args[1]; 372 373 double frac; 374 if (!android::base::ParseDouble(frac_str.c_str(), &frac)) { 375 return ErrorAbort(state, kArgsParsingFailure, "%s: failed to parse double in %s\n", name, 376 frac_str.c_str()); 377 } 378 int sec; 379 if (!android::base::ParseInt(sec_str.c_str(), &sec)) { 380 return ErrorAbort(state, kArgsParsingFailure, "%s: failed to parse int in %s\n", name, 381 sec_str.c_str()); 382 } 383 384 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie); 385 fprintf(ui->cmd_pipe, "progress %f %d\n", frac, sec); 386 387 return StringValue(frac_str); 388 } 389 390 Value* SetProgressFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 391 if (argv.size() != 1) { 392 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 arg, got %zu", name, argv.size()); 393 } 394 395 std::vector<std::string> args; 396 if (!ReadArgs(state, argv, &args)) { 397 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); 398 } 399 const std::string& frac_str = args[0]; 400 401 double frac; 402 if (!android::base::ParseDouble(frac_str.c_str(), &frac)) { 403 return ErrorAbort(state, kArgsParsingFailure, "%s: failed to parse double in %s\n", name, 404 frac_str.c_str()); 405 } 406 407 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie); 408 fprintf(ui->cmd_pipe, "set_progress %f\n", frac); 409 410 return StringValue(frac_str); 411 } 412 413 // package_extract_file(package_file[, dest_file]) 414 // Extracts a single package_file from the update package and writes it to dest_file, 415 // overwriting existing files if necessary. Without the dest_file argument, returns the 416 // contents of the package file as a binary blob. 417 Value* PackageExtractFileFn(const char* name, State* state, 418 const std::vector<std::unique_ptr<Expr>>& argv) { 419 if (argv.size() < 1 || argv.size() > 2) { 420 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 or 2 args, got %zu", name, 421 argv.size()); 422 } 423 424 if (argv.size() == 2) { 425 // The two-argument version extracts to a file. 426 427 std::vector<std::string> args; 428 if (!ReadArgs(state, argv, &args)) { 429 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse %zu args", name, 430 argv.size()); 431 } 432 const std::string& zip_path = args[0]; 433 const std::string& dest_path = args[1]; 434 435 ZipArchiveHandle za = static_cast<UpdaterInfo*>(state->cookie)->package_zip; 436 ZipString zip_string_path(zip_path.c_str()); 437 ZipEntry entry; 438 if (FindEntry(za, zip_string_path, &entry) != 0) { 439 LOG(ERROR) << name << ": no " << zip_path << " in package"; 440 return StringValue(""); 441 } 442 443 unique_fd fd(TEMP_FAILURE_RETRY( 444 ota_open(dest_path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR))); 445 if (fd == -1) { 446 PLOG(ERROR) << name << ": can't open " << dest_path << " for write"; 447 return StringValue(""); 448 } 449 450 bool success = true; 451 int32_t ret = ExtractEntryToFile(za, &entry, fd); 452 if (ret != 0) { 453 LOG(ERROR) << name << ": Failed to extract entry \"" << zip_path << "\" (" 454 << entry.uncompressed_length << " bytes) to \"" << dest_path 455 << "\": " << ErrorCodeString(ret); 456 success = false; 457 } 458 if (ota_fsync(fd) == -1) { 459 PLOG(ERROR) << "fsync of \"" << dest_path << "\" failed"; 460 success = false; 461 } 462 if (ota_close(fd) == -1) { 463 PLOG(ERROR) << "close of \"" << dest_path << "\" failed"; 464 success = false; 465 } 466 467 return StringValue(success ? "t" : ""); 468 } else { 469 // The one-argument version returns the contents of the file as the result. 470 471 std::vector<std::string> args; 472 if (!ReadArgs(state, argv, &args)) { 473 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse %zu args", name, 474 argv.size()); 475 } 476 const std::string& zip_path = args[0]; 477 478 ZipArchiveHandle za = static_cast<UpdaterInfo*>(state->cookie)->package_zip; 479 ZipString zip_string_path(zip_path.c_str()); 480 ZipEntry entry; 481 if (FindEntry(za, zip_string_path, &entry) != 0) { 482 return ErrorAbort(state, kPackageExtractFileFailure, "%s(): no %s in package", name, 483 zip_path.c_str()); 484 } 485 486 std::string buffer; 487 buffer.resize(entry.uncompressed_length); 488 489 int32_t ret = ExtractToMemory(za, &entry, reinterpret_cast<uint8_t*>(&buffer[0]), buffer.size()); 490 if (ret != 0) { 491 return ErrorAbort(state, kPackageExtractFileFailure, 492 "%s: Failed to extract entry \"%s\" (%zu bytes) to memory: %s", name, 493 zip_path.c_str(), buffer.size(), ErrorCodeString(ret)); 494 } 495 496 return new Value(VAL_BLOB, buffer); 497 } 498 } 499 500 Value* GetPropFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 501 if (argv.size() != 1) { 502 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 arg, got %zu", name, argv.size()); 503 } 504 std::string key; 505 if (!Evaluate(state, argv[0], &key)) { 506 return nullptr; 507 } 508 std::string value = android::base::GetProperty(key, ""); 509 510 return StringValue(value); 511 } 512 513 // file_getprop(file, key) 514 // 515 // interprets 'file' as a getprop-style file (key=value pairs, one 516 // per line. # comment lines, blank lines, lines without '=' ignored), 517 // and returns the value for 'key' (or "" if it isn't defined). 518 Value* FileGetPropFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 519 if (argv.size() != 2) { 520 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 2 args, got %zu", name, 521 argv.size()); 522 } 523 524 std::vector<std::string> args; 525 if (!ReadArgs(state, argv, &args)) { 526 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); 527 } 528 const std::string& filename = args[0]; 529 const std::string& key = args[1]; 530 531 struct stat st; 532 if (stat(filename.c_str(), &st) < 0) { 533 return ErrorAbort(state, kFileGetPropFailure, "%s: failed to stat \"%s\": %s", name, 534 filename.c_str(), strerror(errno)); 535 } 536 537 constexpr off_t MAX_FILE_GETPROP_SIZE = 65536; 538 if (st.st_size > MAX_FILE_GETPROP_SIZE) { 539 return ErrorAbort(state, kFileGetPropFailure, "%s too large for %s (max %lld)", 540 filename.c_str(), name, static_cast<long long>(MAX_FILE_GETPROP_SIZE)); 541 } 542 543 std::string buffer(st.st_size, '\0'); 544 unique_file f(ota_fopen(filename.c_str(), "rb")); 545 if (f == nullptr) { 546 return ErrorAbort(state, kFileOpenFailure, "%s: failed to open %s: %s", name, filename.c_str(), 547 strerror(errno)); 548 } 549 550 if (ota_fread(&buffer[0], 1, st.st_size, f.get()) != static_cast<size_t>(st.st_size)) { 551 ErrorAbort(state, kFreadFailure, "%s: failed to read %zu bytes from %s", name, 552 static_cast<size_t>(st.st_size), filename.c_str()); 553 return nullptr; 554 } 555 556 ota_fclose(f); 557 558 std::vector<std::string> lines = android::base::Split(buffer, "\n"); 559 for (size_t i = 0; i < lines.size(); i++) { 560 std::string line = android::base::Trim(lines[i]); 561 562 // comment or blank line: skip to next line 563 if (line.empty() || line[0] == '#') { 564 continue; 565 } 566 size_t equal_pos = line.find('='); 567 if (equal_pos == std::string::npos) { 568 continue; 569 } 570 571 // trim whitespace between key and '=' 572 std::string str = android::base::Trim(line.substr(0, equal_pos)); 573 574 // not the key we're looking for 575 if (key != str) continue; 576 577 return StringValue(android::base::Trim(line.substr(equal_pos + 1))); 578 } 579 580 return StringValue(""); 581 } 582 583 // apply_patch_space(bytes) 584 Value* ApplyPatchSpaceFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 585 if (argv.size() != 1) { 586 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 args, got %zu", name, 587 argv.size()); 588 } 589 std::vector<std::string> args; 590 if (!ReadArgs(state, argv, &args)) { 591 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); 592 } 593 const std::string& bytes_str = args[0]; 594 595 size_t bytes; 596 if (!android::base::ParseUint(bytes_str.c_str(), &bytes)) { 597 return ErrorAbort(state, kArgsParsingFailure, "%s(): can't parse \"%s\" as byte count\n\n", 598 name, bytes_str.c_str()); 599 } 600 601 return StringValue(CacheSizeCheck(bytes) ? "" : "t"); 602 } 603 604 // apply_patch(src_file, tgt_file, tgt_sha1, tgt_size, patch1_sha1, patch1_blob, [...]) 605 // Applies a binary patch to the src_file to produce the tgt_file. If the desired target is the 606 // same as the source, pass "-" for tgt_file. tgt_sha1 and tgt_size are the expected final SHA1 607 // hash and size of the target file. The remaining arguments must come in pairs: a SHA1 hash (a 608 // 40-character hex string) and a blob. The blob is the patch to be applied when the source 609 // file's current contents have the given SHA1. 610 // 611 // The patching is done in a safe manner that guarantees the target file either has the desired 612 // SHA1 hash and size, or it is untouched -- it will not be left in an unrecoverable intermediate 613 // state. If the process is interrupted during patching, the target file may be in an intermediate 614 // state; a copy exists in the cache partition so restarting the update can successfully update 615 // the file. 616 Value* ApplyPatchFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 617 if (argv.size() < 6 || (argv.size() % 2) == 1) { 618 return ErrorAbort(state, kArgsParsingFailure, "%s(): expected at least 6 args and an " 619 "even number, got %zu", name, argv.size()); 620 } 621 622 std::vector<std::string> args; 623 if (!ReadArgs(state, argv, &args, 0, 4)) { 624 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); 625 } 626 const std::string& source_filename = args[0]; 627 const std::string& target_filename = args[1]; 628 const std::string& target_sha1 = args[2]; 629 const std::string& target_size_str = args[3]; 630 631 size_t target_size; 632 if (!android::base::ParseUint(target_size_str.c_str(), &target_size)) { 633 return ErrorAbort(state, kArgsParsingFailure, "%s(): can't parse \"%s\" as byte count", 634 name, target_size_str.c_str()); 635 } 636 637 int patchcount = (argv.size()-4) / 2; 638 std::vector<std::unique_ptr<Value>> arg_values; 639 if (!ReadValueArgs(state, argv, &arg_values, 4, argv.size() - 4)) { 640 return nullptr; 641 } 642 643 for (int i = 0; i < patchcount; ++i) { 644 if (arg_values[i * 2]->type != VAL_STRING) { 645 return ErrorAbort(state, kArgsParsingFailure, "%s(): sha-1 #%d is not string", name, 646 i * 2); 647 } 648 if (arg_values[i * 2 + 1]->type != VAL_BLOB) { 649 return ErrorAbort(state, kArgsParsingFailure, "%s(): patch #%d is not blob", name, 650 i * 2 + 1); 651 } 652 } 653 654 std::vector<std::string> patch_sha_str; 655 std::vector<std::unique_ptr<Value>> patches; 656 for (int i = 0; i < patchcount; ++i) { 657 patch_sha_str.push_back(arg_values[i * 2]->data); 658 patches.push_back(std::move(arg_values[i * 2 + 1])); 659 } 660 661 int result = applypatch(source_filename.c_str(), target_filename.c_str(), 662 target_sha1.c_str(), target_size, 663 patch_sha_str, patches, nullptr); 664 665 return StringValue(result == 0 ? "t" : ""); 666 } 667 668 // apply_patch_check(filename, [sha1, ...]) 669 // Returns true if the contents of filename or the temporary copy in the cache partition (if 670 // present) have a SHA-1 checksum equal to one of the given sha1 values. sha1 values are 671 // specified as 40 hex digits. This function differs from sha1_check(read_file(filename), 672 // sha1 [, ...]) in that it knows to check the cache partition copy, so apply_patch_check() will 673 // succeed even if the file was corrupted by an interrupted apply_patch() update. 674 Value* ApplyPatchCheckFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 675 if (argv.size() < 1) { 676 return ErrorAbort(state, kArgsParsingFailure, "%s(): expected at least 1 arg, got %zu", name, 677 argv.size()); 678 } 679 680 std::vector<std::string> args; 681 if (!ReadArgs(state, argv, &args, 0, 1)) { 682 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); 683 } 684 const std::string& filename = args[0]; 685 686 std::vector<std::string> sha1s; 687 if (argv.size() > 1 && !ReadArgs(state, argv, &sha1s, 1, argv.size() - 1)) { 688 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); 689 } 690 int result = applypatch_check(filename.c_str(), sha1s); 691 692 return StringValue(result == 0 ? "t" : ""); 693 } 694 695 // This is the updater side handler for ui_print() in edify script. Contents will be sent over to 696 // the recovery side for on-screen display. 697 Value* UIPrintFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 698 std::vector<std::string> args; 699 if (!ReadArgs(state, argv, &args)) { 700 return ErrorAbort(state, kArgsParsingFailure, "%s(): Failed to parse the argument(s)", name); 701 } 702 703 std::string buffer = android::base::Join(args, ""); 704 uiPrint(state, buffer); 705 return StringValue(buffer); 706 } 707 708 Value* WipeCacheFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 709 if (!argv.empty()) { 710 return ErrorAbort(state, kArgsParsingFailure, "%s() expects no args, got %zu", name, 711 argv.size()); 712 } 713 fprintf(static_cast<UpdaterInfo*>(state->cookie)->cmd_pipe, "wipe_cache\n"); 714 return StringValue("t"); 715 } 716 717 Value* RunProgramFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 718 if (argv.size() < 1) { 719 return ErrorAbort(state, kArgsParsingFailure, "%s() expects at least 1 arg", name); 720 } 721 722 std::vector<std::string> args; 723 if (!ReadArgs(state, argv, &args)) { 724 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); 725 } 726 727 char* args2[argv.size() + 1]; 728 for (size_t i = 0; i < argv.size(); i++) { 729 args2[i] = &args[i][0]; 730 } 731 args2[argv.size()] = nullptr; 732 733 LOG(INFO) << "about to run program [" << args2[0] << "] with " << argv.size() << " args"; 734 735 pid_t child = fork(); 736 if (child == 0) { 737 execv(args2[0], args2); 738 PLOG(ERROR) << "run_program: execv failed"; 739 _exit(EXIT_FAILURE); 740 } 741 742 int status; 743 waitpid(child, &status, 0); 744 if (WIFEXITED(status)) { 745 if (WEXITSTATUS(status) != 0) { 746 LOG(ERROR) << "run_program: child exited with status " << WEXITSTATUS(status); 747 } 748 } else if (WIFSIGNALED(status)) { 749 LOG(ERROR) << "run_program: child terminated by signal " << WTERMSIG(status); 750 } 751 752 return StringValue(std::to_string(status)); 753 } 754 755 // sha1_check(data) 756 // to return the sha1 of the data (given in the format returned by 757 // read_file). 758 // 759 // sha1_check(data, sha1_hex, [sha1_hex, ...]) 760 // returns the sha1 of the file if it matches any of the hex 761 // strings passed, or "" if it does not equal any of them. 762 // 763 Value* Sha1CheckFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 764 if (argv.size() < 1) { 765 return ErrorAbort(state, kArgsParsingFailure, "%s() expects at least 1 arg", name); 766 } 767 768 std::vector<std::unique_ptr<Value>> args; 769 if (!ReadValueArgs(state, argv, &args)) { 770 return nullptr; 771 } 772 773 if (args[0]->type == VAL_INVALID) { 774 return StringValue(""); 775 } 776 uint8_t digest[SHA_DIGEST_LENGTH]; 777 SHA1(reinterpret_cast<const uint8_t*>(args[0]->data.c_str()), args[0]->data.size(), digest); 778 779 if (argv.size() == 1) { 780 return StringValue(print_sha1(digest)); 781 } 782 783 for (size_t i = 1; i < argv.size(); ++i) { 784 uint8_t arg_digest[SHA_DIGEST_LENGTH]; 785 if (args[i]->type != VAL_STRING) { 786 LOG(ERROR) << name << "(): arg " << i << " is not a string; skipping"; 787 } else if (ParseSha1(args[i]->data.c_str(), arg_digest) != 0) { 788 // Warn about bad args and skip them. 789 LOG(ERROR) << name << "(): error parsing \"" << args[i]->data << "\" as sha-1; skipping"; 790 } else if (memcmp(digest, arg_digest, SHA_DIGEST_LENGTH) == 0) { 791 // Found a match. 792 return args[i].release(); 793 } 794 } 795 796 // Didn't match any of the hex strings; return false. 797 return StringValue(""); 798 } 799 800 // Read a local file and return its contents (the Value* returned 801 // is actually a FileContents*). 802 Value* ReadFileFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 803 if (argv.size() != 1) { 804 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 arg, got %zu", name, argv.size()); 805 } 806 807 std::vector<std::string> args; 808 if (!ReadArgs(state, argv, &args)) { 809 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); 810 } 811 const std::string& filename = args[0]; 812 813 Value* v = new Value(VAL_INVALID, ""); 814 815 FileContents fc; 816 if (LoadFileContents(filename.c_str(), &fc) == 0) { 817 v->type = VAL_BLOB; 818 v->data = std::string(fc.data.begin(), fc.data.end()); 819 } 820 return v; 821 } 822 823 // write_value(value, filename) 824 // Writes 'value' to 'filename'. 825 // Example: write_value("960000", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq") 826 Value* WriteValueFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 827 if (argv.size() != 2) { 828 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 2 args, got %zu", name, 829 argv.size()); 830 } 831 832 std::vector<std::string> args; 833 if (!ReadArgs(state, argv, &args)) { 834 return ErrorAbort(state, kArgsParsingFailure, "%s(): Failed to parse the argument(s)", name); 835 } 836 837 const std::string& filename = args[1]; 838 if (filename.empty()) { 839 return ErrorAbort(state, kArgsParsingFailure, "%s(): Filename cannot be empty", name); 840 } 841 842 const std::string& value = args[0]; 843 if (!android::base::WriteStringToFile(value, filename)) { 844 PLOG(ERROR) << name << ": Failed to write to \"" << filename << "\""; 845 return StringValue(""); 846 } else { 847 return StringValue("t"); 848 } 849 } 850 851 // Immediately reboot the device. Recovery is not finished normally, 852 // so if you reboot into recovery it will re-start applying the 853 // current package (because nothing has cleared the copy of the 854 // arguments stored in the BCB). 855 // 856 // The argument is the partition name passed to the android reboot 857 // property. It can be "recovery" to boot from the recovery 858 // partition, or "" (empty string) to boot from the regular boot 859 // partition. 860 Value* RebootNowFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 861 if (argv.size() != 2) { 862 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 2 args, got %zu", name, 863 argv.size()); 864 } 865 866 std::vector<std::string> args; 867 if (!ReadArgs(state, argv, &args)) { 868 return ErrorAbort(state, kArgsParsingFailure, "%s(): Failed to parse the argument(s)", name); 869 } 870 const std::string& filename = args[0]; 871 const std::string& property = args[1]; 872 873 // Zero out the 'command' field of the bootloader message. Leave the rest intact. 874 bootloader_message boot; 875 std::string err; 876 if (!read_bootloader_message_from(&boot, filename, &err)) { 877 LOG(ERROR) << name << "(): Failed to read from \"" << filename << "\": " << err; 878 return StringValue(""); 879 } 880 memset(boot.command, 0, sizeof(boot.command)); 881 if (!write_bootloader_message_to(boot, filename, &err)) { 882 LOG(ERROR) << name << "(): Failed to write to \"" << filename << "\": " << err; 883 return StringValue(""); 884 } 885 886 std::string reboot_cmd = "reboot," + property; 887 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) { 888 reboot_cmd += ",quiescent"; 889 } 890 android::base::SetProperty(ANDROID_RB_PROPERTY, reboot_cmd); 891 892 sleep(5); 893 return ErrorAbort(state, kRebootFailure, "%s() failed to reboot", name); 894 } 895 896 // Store a string value somewhere that future invocations of recovery 897 // can access it. This value is called the "stage" and can be used to 898 // drive packages that need to do reboots in the middle of 899 // installation and keep track of where they are in the multi-stage 900 // install. 901 // 902 // The first argument is the block device for the misc partition 903 // ("/misc" in the fstab), which is where this value is stored. The 904 // second argument is the string to store; it should not exceed 31 905 // bytes. 906 Value* SetStageFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 907 if (argv.size() != 2) { 908 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 2 args, got %zu", name, 909 argv.size()); 910 } 911 912 std::vector<std::string> args; 913 if (!ReadArgs(state, argv, &args)) { 914 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); 915 } 916 const std::string& filename = args[0]; 917 const std::string& stagestr = args[1]; 918 919 // Store this value in the misc partition, immediately after the 920 // bootloader message that the main recovery uses to save its 921 // arguments in case of the device restarting midway through 922 // package installation. 923 bootloader_message boot; 924 std::string err; 925 if (!read_bootloader_message_from(&boot, filename, &err)) { 926 LOG(ERROR) << name << "(): Failed to read from \"" << filename << "\": " << err; 927 return StringValue(""); 928 } 929 strlcpy(boot.stage, stagestr.c_str(), sizeof(boot.stage)); 930 if (!write_bootloader_message_to(boot, filename, &err)) { 931 LOG(ERROR) << name << "(): Failed to write to \"" << filename << "\": " << err; 932 return StringValue(""); 933 } 934 935 return StringValue(filename); 936 } 937 938 // Return the value most recently saved with SetStageFn. The argument 939 // is the block device for the misc partition. 940 Value* GetStageFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 941 if (argv.size() != 1) { 942 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 arg, got %zu", name, argv.size()); 943 } 944 945 std::vector<std::string> args; 946 if (!ReadArgs(state, argv, &args)) { 947 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); 948 } 949 const std::string& filename = args[0]; 950 951 bootloader_message boot; 952 std::string err; 953 if (!read_bootloader_message_from(&boot, filename, &err)) { 954 LOG(ERROR) << name << "(): Failed to read from \"" << filename << "\": " << err; 955 return StringValue(""); 956 } 957 958 return StringValue(boot.stage); 959 } 960 961 Value* WipeBlockDeviceFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 962 if (argv.size() != 2) { 963 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 2 args, got %zu", name, 964 argv.size()); 965 } 966 967 std::vector<std::string> args; 968 if (!ReadArgs(state, argv, &args)) { 969 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); 970 } 971 const std::string& filename = args[0]; 972 const std::string& len_str = args[1]; 973 974 size_t len; 975 if (!android::base::ParseUint(len_str.c_str(), &len)) { 976 return nullptr; 977 } 978 unique_fd fd(ota_open(filename.c_str(), O_WRONLY, 0644)); 979 // The wipe_block_device function in ext4_utils returns 0 on success and 1 980 // for failure. 981 int status = wipe_block_device(fd, len); 982 return StringValue((status == 0) ? "t" : ""); 983 } 984 985 Value* EnableRebootFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 986 if (!argv.empty()) { 987 return ErrorAbort(state, kArgsParsingFailure, "%s() expects no args, got %zu", name, 988 argv.size()); 989 } 990 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie); 991 fprintf(ui->cmd_pipe, "enable_reboot\n"); 992 return StringValue("t"); 993 } 994 995 Value* Tune2FsFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) { 996 if (argv.empty()) { 997 return ErrorAbort(state, kArgsParsingFailure, "%s() expects args, got %zu", name, argv.size()); 998 } 999 1000 std::vector<std::string> args; 1001 if (!ReadArgs(state, argv, &args)) { 1002 return ErrorAbort(state, kArgsParsingFailure, "%s() could not read args", name); 1003 } 1004 1005 char* args2[argv.size() + 1]; 1006 // Tune2fs expects the program name as its args[0] 1007 args2[0] = const_cast<char*>(name); 1008 if (args2[0] == nullptr) { 1009 return nullptr; 1010 } 1011 for (size_t i = 0; i < argv.size(); ++i) { 1012 args2[i + 1] = &args[i][0]; 1013 } 1014 1015 // tune2fs changes the file system parameters on an ext2 file system; it 1016 // returns 0 on success. 1017 int result = tune2fs_main(argv.size() + 1, args2); 1018 if (result != 0) { 1019 return ErrorAbort(state, kTune2FsFailure, "%s() returned error code %d", name, result); 1020 } 1021 return StringValue("t"); 1022 } 1023 1024 void RegisterInstallFunctions() { 1025 RegisterFunction("mount", MountFn); 1026 RegisterFunction("is_mounted", IsMountedFn); 1027 RegisterFunction("unmount", UnmountFn); 1028 RegisterFunction("format", FormatFn); 1029 RegisterFunction("show_progress", ShowProgressFn); 1030 RegisterFunction("set_progress", SetProgressFn); 1031 RegisterFunction("package_extract_file", PackageExtractFileFn); 1032 1033 RegisterFunction("getprop", GetPropFn); 1034 RegisterFunction("file_getprop", FileGetPropFn); 1035 1036 RegisterFunction("apply_patch", ApplyPatchFn); 1037 RegisterFunction("apply_patch_check", ApplyPatchCheckFn); 1038 RegisterFunction("apply_patch_space", ApplyPatchSpaceFn); 1039 1040 RegisterFunction("wipe_block_device", WipeBlockDeviceFn); 1041 1042 RegisterFunction("read_file", ReadFileFn); 1043 RegisterFunction("sha1_check", Sha1CheckFn); 1044 RegisterFunction("write_value", WriteValueFn); 1045 1046 RegisterFunction("wipe_cache", WipeCacheFn); 1047 1048 RegisterFunction("ui_print", UIPrintFn); 1049 1050 RegisterFunction("run_program", RunProgramFn); 1051 1052 RegisterFunction("reboot_now", RebootNowFn); 1053 RegisterFunction("get_stage", GetStageFn); 1054 RegisterFunction("set_stage", SetStageFn); 1055 1056 RegisterFunction("enable_reboot", EnableRebootFn); 1057 RegisterFunction("tune2fs", Tune2FsFn); 1058 } 1059