InstalldNativeService.cpp revision eca1bff0ce7709830816418107c8f444afdd33f5
1/* 2** Copyright 2008, 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 "InstalldNativeService.h" 18 19#include <errno.h> 20#include <inttypes.h> 21#include <fstream> 22#include <fts.h> 23#include <regex> 24#include <stdlib.h> 25#include <string.h> 26#include <sys/capability.h> 27#include <sys/file.h> 28#include <sys/resource.h> 29#include <sys/quota.h> 30#include <sys/stat.h> 31#include <sys/statvfs.h> 32#include <sys/types.h> 33#include <sys/wait.h> 34#include <sys/xattr.h> 35#include <unistd.h> 36 37#include <android-base/logging.h> 38#include <android-base/stringprintf.h> 39#include <android-base/strings.h> 40#include <android-base/unique_fd.h> 41#include <cutils/fs.h> 42#include <cutils/properties.h> 43#include <cutils/sched_policy.h> 44#include <log/log.h> // TODO: Move everything to base/logging. 45#include <logwrap/logwrap.h> 46#include <private/android_filesystem_config.h> 47#include <selinux/android.h> 48#include <system/thread_defs.h> 49 50#include "dexopt.h" 51#include "globals.h" 52#include "installd_deps.h" 53#include "otapreopt_utils.h" 54#include "utils.h" 55 56#include "MatchExtensionGen.h" 57 58#ifndef LOG_TAG 59#define LOG_TAG "installd" 60#endif 61 62using android::base::StringPrintf; 63 64namespace android { 65namespace installd { 66 67static constexpr const char* kCpPath = "/system/bin/cp"; 68static constexpr const char* kXattrDefault = "user.default"; 69 70static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M 71 72static constexpr const char* PKG_LIB_POSTFIX = "/lib"; 73static constexpr const char* CACHE_DIR_POSTFIX = "/cache"; 74static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache"; 75 76static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/"; 77static constexpr const char* IDMAP_SUFFIX = "@idmap"; 78 79// NOTE: keep in sync with StorageManager 80static constexpr int FLAG_STORAGE_DE = 1 << 0; 81static constexpr int FLAG_STORAGE_CE = 1 << 1; 82 83// NOTE: keep in sync with Installer 84static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8; 85static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9; 86static constexpr int FLAG_USE_QUOTA = 1 << 12; 87 88namespace { 89 90constexpr const char* kDump = "android.permission.DUMP"; 91 92static binder::Status ok() { 93 return binder::Status::ok(); 94} 95 96static binder::Status exception(uint32_t code, const std::string& msg) { 97 return binder::Status::fromExceptionCode(code, String8(msg.c_str())); 98} 99 100static binder::Status error() { 101 return binder::Status::fromServiceSpecificError(errno); 102} 103 104static binder::Status error(const std::string& msg) { 105 PLOG(ERROR) << msg; 106 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str())); 107} 108 109static binder::Status error(uint32_t code, const std::string& msg) { 110 LOG(ERROR) << msg << " (" << code << ")"; 111 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str())); 112} 113 114binder::Status checkPermission(const char* permission) { 115 pid_t pid; 116 uid_t uid; 117 118 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid), 119 reinterpret_cast<int32_t*>(&uid))) { 120 return ok(); 121 } else { 122 return exception(binder::Status::EX_SECURITY, 123 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission)); 124 } 125} 126 127binder::Status checkUid(uid_t expectedUid) { 128 uid_t uid = IPCThreadState::self()->getCallingUid(); 129 if (uid == expectedUid || uid == AID_ROOT) { 130 return ok(); 131 } else { 132 return exception(binder::Status::EX_SECURITY, 133 StringPrintf("UID %d is not expected UID %d", uid, expectedUid)); 134 } 135} 136 137binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) { 138 if (!uuid || is_valid_filename(*uuid)) { 139 return ok(); 140 } else { 141 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, 142 StringPrintf("UUID %s is malformed", uuid->c_str())); 143 } 144} 145 146binder::Status checkArgumentPackageName(const std::string& packageName) { 147 if (is_valid_package_name(packageName.c_str())) { 148 return ok(); 149 } else { 150 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, 151 StringPrintf("Package name %s is malformed", packageName.c_str())); 152 } 153} 154 155#define ENFORCE_UID(uid) { \ 156 binder::Status status = checkUid((uid)); \ 157 if (!status.isOk()) { \ 158 return status; \ 159 } \ 160} 161 162#define CHECK_ARGUMENT_UUID(uuid) { \ 163 binder::Status status = checkArgumentUuid((uuid)); \ 164 if (!status.isOk()) { \ 165 return status; \ 166 } \ 167} 168 169#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \ 170 binder::Status status = \ 171 checkArgumentPackageName((packageName)); \ 172 if (!status.isOk()) { \ 173 return status; \ 174 } \ 175} 176 177} // namespace 178 179status_t InstalldNativeService::start() { 180 IPCThreadState::self()->disableBackgroundScheduling(true); 181 status_t ret = BinderService<InstalldNativeService>::publish(); 182 if (ret != android::OK) { 183 return ret; 184 } 185 sp<ProcessState> ps(ProcessState::self()); 186 ps->startThreadPool(); 187 ps->giveThreadPoolName(); 188 return android::OK; 189} 190 191status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) { 192 const binder::Status dump_permission = checkPermission(kDump); 193 if (!dump_permission.isOk()) { 194 const String8 msg(dump_permission.toString8()); 195 write(fd, msg.string(), msg.size()); 196 return PERMISSION_DENIED; 197 } 198 199 std::string msg = "installd is happy\n"; 200 write(fd, msg.c_str(), strlen(msg.c_str())); 201 return NO_ERROR; 202} 203 204/** 205 * Perform restorecon of the given path, but only perform recursive restorecon 206 * if the label of that top-level file actually changed. This can save us 207 * significant time by avoiding no-op traversals of large filesystem trees. 208 */ 209static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid, 210 bool existing) { 211 int res = 0; 212 char* before = nullptr; 213 char* after = nullptr; 214 215 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by 216 // libselinux. Not needed here. 217 218 if (lgetfilecon(path.c_str(), &before) < 0) { 219 PLOG(ERROR) << "Failed before getfilecon for " << path; 220 goto fail; 221 } 222 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) { 223 PLOG(ERROR) << "Failed top-level restorecon for " << path; 224 goto fail; 225 } 226 if (lgetfilecon(path.c_str(), &after) < 0) { 227 PLOG(ERROR) << "Failed after getfilecon for " << path; 228 goto fail; 229 } 230 231 // If the initial top-level restorecon above changed the label, then go 232 // back and restorecon everything recursively 233 if (strcmp(before, after)) { 234 if (existing) { 235 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at " 236 << path << "; running recursive restorecon"; 237 } 238 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 239 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) { 240 PLOG(ERROR) << "Failed recursive restorecon for " << path; 241 goto fail; 242 } 243 } 244 245 goto done; 246fail: 247 res = -1; 248done: 249 free(before); 250 free(after); 251 return res; 252} 253 254static int restorecon_app_data_lazy(const std::string& parent, const char* name, 255 const std::string& seInfo, uid_t uid, bool existing) { 256 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid, 257 existing); 258} 259 260static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) { 261 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) { 262 PLOG(ERROR) << "Failed to prepare " << path; 263 return -1; 264 } 265 return 0; 266} 267 268/** 269 * Prepare an app cache directory, which offers to fix-up the GID and 270 * directory mode flags during a platform upgrade. 271 */ 272static int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode, 273 uid_t uid, gid_t gid) { 274 auto path = StringPrintf("%s/%s", parent.c_str(), name); 275 struct stat st; 276 if (stat(path.c_str(), &st) != 0) { 277 if (errno == ENOENT) { 278 // This is fine, just create it 279 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) { 280 PLOG(ERROR) << "Failed to prepare " << path; 281 return -1; 282 } else { 283 return 0; 284 } 285 } else { 286 PLOG(ERROR) << "Failed to stat " << path; 287 return -1; 288 } 289 } 290 291 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID); 292 if (st.st_uid != uid) { 293 // Mismatched UID is real trouble; we can't recover 294 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid 295 << " but expected " << uid; 296 return -1; 297 } else if (st.st_gid == gid && actual_mode == target_mode) { 298 // Everything looks good! 299 return 0; 300 } 301 302 // Directory is owned correctly, but GID or mode mismatch means it's 303 // probably a platform upgrade so we need to fix them 304 FTS *fts; 305 FTSENT *p; 306 char *argv[] = { (char*) path.c_str(), nullptr }; 307 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) { 308 PLOG(ERROR) << "Failed to fts_open " << path; 309 return -1; 310 } 311 while ((p = fts_read(fts)) != NULL) { 312 switch (p->fts_info) { 313 case FTS_DP: 314 if (chmod(p->fts_accpath, target_mode) != 0) { 315 PLOG(WARNING) << "Failed to chmod " << p->fts_path; 316 } 317 // Intentional fall through to also set GID 318 case FTS_F: 319 if (chown(p->fts_accpath, -1, gid) != 0) { 320 PLOG(WARNING) << "Failed to chown " << p->fts_path; 321 } 322 break; 323 case FTS_SL: 324 case FTS_SLNONE: 325 if (lchown(p->fts_accpath, -1, gid) != 0) { 326 PLOG(WARNING) << "Failed to chown " << p->fts_path; 327 } 328 break; 329 } 330 } 331 fts_close(fts); 332 return 0; 333} 334 335binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid, 336 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId, 337 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) { 338 ENFORCE_UID(AID_SYSTEM); 339 CHECK_ARGUMENT_UUID(uuid); 340 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 341 342 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 343 const char* pkgname = packageName.c_str(); 344 345 // Assume invalid inode unless filled in below 346 if (_aidl_return != nullptr) *_aidl_return = -1; 347 348 int32_t uid = multiuser_get_uid(userId, appId); 349 int32_t cacheGid = multiuser_get_cache_gid(userId, appId); 350 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751; 351 352 // If UID doesn't have a specific cache GID, use UID value 353 if (cacheGid == -1) { 354 cacheGid = uid; 355 } 356 357 if (flags & FLAG_STORAGE_CE) { 358 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname); 359 bool existing = (access(path.c_str(), F_OK) == 0); 360 361 if (prepare_app_dir(path, targetMode, uid) || 362 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) || 363 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) { 364 return error("Failed to prepare " + path); 365 } 366 367 // Consider restorecon over contents if label changed 368 if (restorecon_app_data_lazy(path, seInfo, uid, existing) || 369 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) || 370 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) { 371 return error("Failed to restorecon " + path); 372 } 373 374 // Remember inode numbers of cache directories so that we can clear 375 // contents while CE storage is locked 376 if (write_path_inode(path, "cache", kXattrInodeCache) || 377 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) { 378 return error("Failed to write_path_inode for " + path); 379 } 380 381 // And return the CE inode of the top-level data directory so we can 382 // clear contents while CE storage is locked 383 if ((_aidl_return != nullptr) 384 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) { 385 return error("Failed to get_path_inode for " + path); 386 } 387 } 388 if (flags & FLAG_STORAGE_DE) { 389 auto path = create_data_user_de_package_path(uuid_, userId, pkgname); 390 bool existing = (access(path.c_str(), F_OK) == 0); 391 392 if (prepare_app_dir(path, targetMode, uid) || 393 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) || 394 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) { 395 return error("Failed to prepare " + path); 396 } 397 398 // Consider restorecon over contents if label changed 399 if (restorecon_app_data_lazy(path, seInfo, uid, existing)) { 400 return error("Failed to restorecon " + path); 401 } 402 403 if (property_get_bool("dalvik.vm.usejitprofiles", false)) { 404 const std::string profile_path = create_data_user_profile_package_path(userId, pkgname); 405 // read-write-execute only for the app user. 406 if (fs_prepare_dir_strict(profile_path.c_str(), 0700, uid, uid) != 0) { 407 return error("Failed to prepare " + profile_path); 408 } 409 std::string profile_file = create_primary_profile(profile_path); 410 // read-write only for the app user. 411 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) { 412 return error("Failed to prepare " + profile_path); 413 } 414 const std::string ref_profile_path = create_data_ref_profile_package_path(pkgname); 415 // dex2oat/profman runs under the shared app gid and it needs to read/write reference 416 // profiles. 417 int shared_app_gid = multiuser_get_shared_gid(0, appId); 418 if ((shared_app_gid != -1) && fs_prepare_dir_strict( 419 ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) { 420 return error("Failed to prepare " + ref_profile_path); 421 } 422 } 423 } 424 return ok(); 425} 426 427binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid, 428 const std::string& packageName, int32_t userId, int32_t flags) { 429 ENFORCE_UID(AID_SYSTEM); 430 CHECK_ARGUMENT_UUID(uuid); 431 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 432 433 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 434 const char* pkgname = packageName.c_str(); 435 436 // This method only exists to upgrade system apps that have requested 437 // forceDeviceEncrypted, so their default storage always lives in a 438 // consistent location. This only works on non-FBE devices, since we 439 // never want to risk exposing data on a device with real CE/DE storage. 440 441 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname); 442 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname); 443 444 // If neither directory is marked as default, assume CE is default 445 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1 446 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) { 447 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) { 448 return error("Failed to mark default storage " + ce_path); 449 } 450 } 451 452 // Migrate default data location if needed 453 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path; 454 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path; 455 456 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) { 457 LOG(WARNING) << "Requested default storage " << target 458 << " is not active; migrating from " << source; 459 if (delete_dir_contents_and_dir(target) != 0) { 460 return error("Failed to delete " + target); 461 } 462 if (rename(source.c_str(), target.c_str()) != 0) { 463 return error("Failed to rename " + source + " to " + target); 464 } 465 } 466 467 return ok(); 468} 469 470 471binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) { 472 ENFORCE_UID(AID_SYSTEM); 473 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 474 475 const char* pkgname = packageName.c_str(); 476 binder::Status res = ok(); 477 if (!clear_reference_profile(pkgname)) { 478 res = error("Failed to clear reference profile for " + packageName); 479 } 480 if (!clear_current_profiles(pkgname)) { 481 res = error("Failed to clear current profiles for " + packageName); 482 } 483 return res; 484} 485 486binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid, 487 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) { 488 ENFORCE_UID(AID_SYSTEM); 489 CHECK_ARGUMENT_UUID(uuid); 490 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 491 492 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 493 const char* pkgname = packageName.c_str(); 494 495 binder::Status res = ok(); 496 if (flags & FLAG_STORAGE_CE) { 497 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode); 498 if (flags & FLAG_CLEAR_CACHE_ONLY) { 499 path = read_path_inode(path, "cache", kXattrInodeCache); 500 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) { 501 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache); 502 } 503 if (access(path.c_str(), F_OK) == 0) { 504 if (delete_dir_contents(path) != 0) { 505 res = error("Failed to delete contents of " + path); 506 } 507 } 508 } 509 if (flags & FLAG_STORAGE_DE) { 510 std::string suffix = ""; 511 bool only_cache = false; 512 if (flags & FLAG_CLEAR_CACHE_ONLY) { 513 suffix = CACHE_DIR_POSTFIX; 514 only_cache = true; 515 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) { 516 suffix = CODE_CACHE_DIR_POSTFIX; 517 only_cache = true; 518 } 519 520 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix; 521 if (access(path.c_str(), F_OK) == 0) { 522 if (delete_dir_contents(path) != 0) { 523 res = error("Failed to delete contents of " + path); 524 } 525 } 526 if (!only_cache) { 527 if (!clear_current_profile(pkgname, userId)) { 528 res = error("Failed to clear current profile for " + packageName); 529 } 530 } 531 } 532 return res; 533} 534 535static int destroy_app_reference_profile(const char *pkgname) { 536 return delete_dir_contents_and_dir( 537 create_data_ref_profile_package_path(pkgname), 538 /*ignore_if_missing*/ true); 539} 540 541static int destroy_app_current_profiles(const char *pkgname, userid_t userid) { 542 return delete_dir_contents_and_dir( 543 create_data_user_profile_package_path(userid, pkgname), 544 /*ignore_if_missing*/ true); 545} 546 547binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) { 548 ENFORCE_UID(AID_SYSTEM); 549 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 550 551 const char* pkgname = packageName.c_str(); 552 binder::Status res = ok(); 553 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr); 554 for (auto user : users) { 555 if (destroy_app_current_profiles(pkgname, user) != 0) { 556 res = error("Failed to destroy current profiles for " + packageName); 557 } 558 } 559 if (destroy_app_reference_profile(pkgname) != 0) { 560 res = error("Failed to destroy reference profile for " + packageName); 561 } 562 return res; 563} 564 565binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid, 566 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) { 567 ENFORCE_UID(AID_SYSTEM); 568 CHECK_ARGUMENT_UUID(uuid); 569 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 570 571 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 572 const char* pkgname = packageName.c_str(); 573 574 binder::Status res = ok(); 575 if (flags & FLAG_STORAGE_CE) { 576 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode); 577 if (delete_dir_contents_and_dir(path) != 0) { 578 res = error("Failed to delete " + path); 579 } 580 } 581 if (flags & FLAG_STORAGE_DE) { 582 auto path = create_data_user_de_package_path(uuid_, userId, pkgname); 583 if (delete_dir_contents_and_dir(path) != 0) { 584 res = error("Failed to delete " + path); 585 } 586 destroy_app_current_profiles(pkgname, userId); 587 // TODO(calin): If the package is still installed by other users it's probably 588 // beneficial to keep the reference profile around. 589 // Verify if it's ok to do that. 590 destroy_app_reference_profile(pkgname); 591 } 592 return res; 593} 594 595binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid, 596 const std::unique_ptr<std::string>& toUuid, const std::string& packageName, 597 const std::string& dataAppName, int32_t appId, const std::string& seInfo, 598 int32_t targetSdkVersion) { 599 ENFORCE_UID(AID_SYSTEM); 600 CHECK_ARGUMENT_UUID(fromUuid); 601 CHECK_ARGUMENT_UUID(toUuid); 602 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 603 604 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr; 605 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr; 606 const char* package_name = packageName.c_str(); 607 const char* data_app_name = dataAppName.c_str(); 608 609 binder::Status res = ok(); 610 std::vector<userid_t> users = get_known_users(from_uuid); 611 612 // Copy app 613 { 614 auto from = create_data_app_package_path(from_uuid, data_app_name); 615 auto to = create_data_app_package_path(to_uuid, data_app_name); 616 auto to_parent = create_data_app_path(to_uuid); 617 618 char *argv[] = { 619 (char*) kCpPath, 620 (char*) "-F", /* delete any existing destination file first (--remove-destination) */ 621 (char*) "-p", /* preserve timestamps, ownership, and permissions */ 622 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */ 623 (char*) "-P", /* Do not follow symlinks [default] */ 624 (char*) "-d", /* don't dereference symlinks */ 625 (char*) from.c_str(), 626 (char*) to_parent.c_str() 627 }; 628 629 LOG(DEBUG) << "Copying " << from << " to " << to; 630 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true); 631 if (rc != 0) { 632 res = error(rc, "Failed copying " + from + " to " + to); 633 goto fail; 634 } 635 636 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) { 637 res = error("Failed to restorecon " + to); 638 goto fail; 639 } 640 } 641 642 // Copy private data for all known users 643 for (auto user : users) { 644 645 // Data source may not exist for all users; that's okay 646 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name); 647 if (access(from_ce.c_str(), F_OK) != 0) { 648 LOG(INFO) << "Missing source " << from_ce; 649 continue; 650 } 651 652 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId, 653 seInfo, targetSdkVersion, nullptr).isOk()) { 654 res = error("Failed to create package target"); 655 goto fail; 656 } 657 658 char *argv[] = { 659 (char*) kCpPath, 660 (char*) "-F", /* delete any existing destination file first (--remove-destination) */ 661 (char*) "-p", /* preserve timestamps, ownership, and permissions */ 662 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */ 663 (char*) "-P", /* Do not follow symlinks [default] */ 664 (char*) "-d", /* don't dereference symlinks */ 665 nullptr, 666 nullptr 667 }; 668 669 { 670 auto from = create_data_user_de_package_path(from_uuid, user, package_name); 671 auto to = create_data_user_de_path(to_uuid, user); 672 argv[6] = (char*) from.c_str(); 673 argv[7] = (char*) to.c_str(); 674 675 LOG(DEBUG) << "Copying " << from << " to " << to; 676 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true); 677 if (rc != 0) { 678 res = error(rc, "Failed copying " + from + " to " + to); 679 goto fail; 680 } 681 } 682 { 683 auto from = create_data_user_ce_package_path(from_uuid, user, package_name); 684 auto to = create_data_user_ce_path(to_uuid, user); 685 argv[6] = (char*) from.c_str(); 686 argv[7] = (char*) to.c_str(); 687 688 LOG(DEBUG) << "Copying " << from << " to " << to; 689 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true); 690 if (rc != 0) { 691 res = error(rc, "Failed copying " + from + " to " + to); 692 goto fail; 693 } 694 } 695 696 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, 697 appId, seInfo).isOk()) { 698 res = error("Failed to restorecon"); 699 goto fail; 700 } 701 } 702 703 // We let the framework scan the new location and persist that before 704 // deleting the data in the old location; this ordering ensures that 705 // we can recover from things like battery pulls. 706 return ok(); 707 708fail: 709 // Nuke everything we might have already copied 710 { 711 auto to = create_data_app_package_path(to_uuid, data_app_name); 712 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) { 713 LOG(WARNING) << "Failed to rollback " << to; 714 } 715 } 716 for (auto user : users) { 717 { 718 auto to = create_data_user_de_package_path(to_uuid, user, package_name); 719 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) { 720 LOG(WARNING) << "Failed to rollback " << to; 721 } 722 } 723 { 724 auto to = create_data_user_ce_package_path(to_uuid, user, package_name); 725 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) { 726 LOG(WARNING) << "Failed to rollback " << to; 727 } 728 } 729 } 730 return res; 731} 732 733binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid, 734 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) { 735 ENFORCE_UID(AID_SYSTEM); 736 CHECK_ARGUMENT_UUID(uuid); 737 738 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 739 if (flags & FLAG_STORAGE_DE) { 740 if (uuid_ == nullptr) { 741 if (ensure_config_user_dirs(userId) != 0) { 742 return error(StringPrintf("Failed to ensure dirs for %d", userId)); 743 } 744 } 745 } 746 return ok(); 747} 748 749binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid, 750 int32_t userId, int32_t flags) { 751 ENFORCE_UID(AID_SYSTEM); 752 CHECK_ARGUMENT_UUID(uuid); 753 754 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 755 binder::Status res = ok(); 756 if (flags & FLAG_STORAGE_DE) { 757 auto path = create_data_user_de_path(uuid_, userId); 758 if (delete_dir_contents_and_dir(path, true) != 0) { 759 res = error("Failed to delete " + path); 760 } 761 if (uuid_ == nullptr) { 762 path = create_data_misc_legacy_path(userId); 763 if (delete_dir_contents_and_dir(path, true) != 0) { 764 res = error("Failed to delete " + path); 765 } 766 path = create_data_user_profile_path(userId); 767 if (delete_dir_contents_and_dir(path, true) != 0) { 768 res = error("Failed to delete " + path); 769 } 770 } 771 } 772 if (flags & FLAG_STORAGE_CE) { 773 auto path = create_data_user_ce_path(uuid_, userId); 774 if (delete_dir_contents_and_dir(path, true) != 0) { 775 res = error("Failed to delete " + path); 776 } 777 path = create_data_media_path(uuid_, userId); 778 if (delete_dir_contents_and_dir(path, true) != 0) { 779 res = error("Failed to delete " + path); 780 } 781 } 782 return res; 783} 784 785/* Try to ensure free_size bytes of storage are available. 786 * Returns 0 on success. 787 * This is rather simple-minded because doing a full LRU would 788 * be potentially memory-intensive, and without atime it would 789 * also require that apps constantly modify file metadata even 790 * when just reading from the cache, which is pretty awful. 791 */ 792binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid, 793 int64_t freeStorageSize) { 794 ENFORCE_UID(AID_SYSTEM); 795 CHECK_ARGUMENT_UUID(uuid); 796 797 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 798 cache_t* cache; 799 int64_t avail; 800 801 auto data_path = create_data_path(uuid_); 802 803 avail = data_disk_free(data_path); 804 if (avail < 0) { 805 return error("Failed to determine free space for " + data_path); 806 } 807 808 ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", freeStorageSize, avail); 809 if (avail >= freeStorageSize) { 810 return ok(); 811 } 812 813 cache = start_cache_collection(); 814 815 auto users = get_known_users(uuid_); 816 for (auto user : users) { 817 add_cache_files(cache, create_data_user_ce_path(uuid_, user)); 818 add_cache_files(cache, create_data_user_de_path(uuid_, user)); 819 add_cache_files(cache, 820 StringPrintf("%s/Android/data", create_data_media_path(uuid_, user).c_str())); 821 } 822 823 clear_cache_files(data_path, cache, freeStorageSize); 824 finish_cache_collection(cache); 825 826 avail = data_disk_free(data_path); 827 if (avail >= freeStorageSize) { 828 return ok(); 829 } else { 830 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64, 831 freeStorageSize, data_path.c_str(), avail)); 832 } 833} 834 835binder::Status InstalldNativeService::rmdex(const std::string& codePath, 836 const std::string& instructionSet) { 837 ENFORCE_UID(AID_SYSTEM); 838 char dex_path[PKG_PATH_MAX]; 839 840 const char* path = codePath.c_str(); 841 const char* instruction_set = instructionSet.c_str(); 842 843 if (validate_apk_path(path) && validate_system_app_path(path)) { 844 return error("Invalid path " + codePath); 845 } 846 847 if (!create_cache_path(dex_path, path, instruction_set)) { 848 return error("Failed to create cache path for " + codePath); 849 } 850 851 ALOGV("unlink %s\n", dex_path); 852 if (unlink(dex_path) < 0) { 853 return error(StringPrintf("Failed to unlink %s", dex_path)); 854 } else { 855 return ok(); 856 } 857} 858 859struct stats { 860 int64_t codeSize; 861 int64_t dataSize; 862 int64_t cacheSize; 863}; 864 865#if MEASURE_DEBUG 866static std::string toString(std::vector<int64_t> values) { 867 std::stringstream res; 868 res << "["; 869 for (size_t i = 0; i < values.size(); i++) { 870 res << values[i]; 871 if (i < values.size() - 1) { 872 res << ","; 873 } 874 } 875 res << "]"; 876 return res.str(); 877} 878#endif 879 880static std::string findDeviceForUuid(const std::unique_ptr<std::string>& uuid) { 881 auto path = create_data_path(uuid ? uuid->c_str() : nullptr); 882 std::ifstream in("/proc/mounts"); 883 if (!in.is_open()) { 884 PLOG(ERROR) << "Failed to read mounts"; 885 return ""; 886 } 887 std::string source; 888 std::string target; 889 while (!in.eof()) { 890 std::getline(in, source, ' '); 891 std::getline(in, target, ' '); 892 if (target == path) { 893 return source; 894 } 895 // Skip to next line 896 std::getline(in, source); 897 } 898 PLOG(ERROR) << "Failed to resolve block device for " << path; 899 return ""; 900} 901 902static void collectQuotaStats(const std::string& device, int32_t userId, 903 int32_t appId, struct stats* stats, struct stats* extStats ATTRIBUTE_UNUSED) { 904 if (device.empty()) return; 905 906 struct dqblk dq; 907 908 uid_t uid = multiuser_get_uid(userId, appId); 909 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid, 910 reinterpret_cast<char*>(&dq)) != 0) { 911 if (errno != ESRCH) { 912 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid; 913 } 914 } else { 915#if MEASURE_DEBUG 916 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace; 917#endif 918 stats->dataSize += dq.dqb_curspace; 919 } 920 921 int cacheGid = multiuser_get_cache_gid(userId, appId); 922 if (cacheGid != -1) { 923 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid, 924 reinterpret_cast<char*>(&dq)) != 0) { 925 if (errno != ESRCH) { 926 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid; 927 } 928 } else { 929#if MEASURE_DEBUG 930 LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace; 931#endif 932 stats->cacheSize += dq.dqb_curspace; 933 } 934 } 935 936 int sharedGid = multiuser_get_shared_app_gid(uid); 937 if (sharedGid != -1) { 938 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid, 939 reinterpret_cast<char*>(&dq)) != 0) { 940 if (errno != ESRCH) { 941 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid; 942 } 943 } else { 944#if MEASURE_DEBUG 945 LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace; 946#endif 947 stats->codeSize += dq.dqb_curspace; 948 } 949 } 950 951#if MEASURE_EXTERNAL 952 // TODO: measure using external GIDs 953#endif 954} 955 956static void collectQuotaStats(const std::unique_ptr<std::string>& uuid, int32_t userId, 957 int32_t appId, struct stats* stats, struct stats* extStats) { 958 collectQuotaStats(findDeviceForUuid(uuid), userId, appId, stats, extStats); 959} 960 961static void collectManualStats(const std::string& path, struct stats* stats) { 962 DIR *d; 963 int dfd; 964 struct dirent *de; 965 struct stat s; 966 967 d = opendir(path.c_str()); 968 if (d == nullptr) { 969 if (errno != ENOENT) { 970 PLOG(WARNING) << "Failed to open " << path; 971 } 972 return; 973 } 974 dfd = dirfd(d); 975 while ((de = readdir(d))) { 976 const char *name = de->d_name; 977 978 int64_t size = 0; 979 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) { 980 size = s.st_blocks * 512; 981 } 982 983 if (de->d_type == DT_DIR) { 984 if (!strcmp(name, ".")) { 985 // Don't recurse, but still count node size 986 } else if (!strcmp(name, "..")) { 987 // Don't recurse or count node size 988 continue; 989 } else { 990 // Measure all children nodes 991 size = 0; 992 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size); 993 } 994 995 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) { 996 stats->cacheSize += size; 997 } 998 } 999 1000 // Legacy symlink isn't owned by app 1001 if (de->d_type == DT_LNK && !strcmp(name, "lib")) { 1002 continue; 1003 } 1004 1005 // Everything found inside is considered data 1006 stats->dataSize += size; 1007 } 1008 closedir(d); 1009} 1010 1011static void collectManualStatsForUser(const std::string& path, struct stats* stats, 1012 bool exclude_apps = false) { 1013 DIR *d; 1014 int dfd; 1015 struct dirent *de; 1016 struct stat s; 1017 1018 d = opendir(path.c_str()); 1019 if (d == nullptr) { 1020 if (errno != ENOENT) { 1021 PLOG(WARNING) << "Failed to open " << path; 1022 } 1023 return; 1024 } 1025 dfd = dirfd(d); 1026 while ((de = readdir(d))) { 1027 if (de->d_type == DT_DIR) { 1028 const char *name = de->d_name; 1029 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) { 1030 continue; 1031 } 1032 if (!strcmp(name, ".") || !strcmp(name, "..")) { 1033 continue; 1034 } else if (exclude_apps && (s.st_uid >= AID_APP_START && s.st_uid <= AID_APP_END)) { 1035 continue; 1036 } else { 1037 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats); 1038 } 1039 } 1040 } 1041 closedir(d); 1042} 1043 1044binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid, 1045 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags, 1046 int32_t appId, const std::vector<int64_t>& ceDataInodes, 1047 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) { 1048 ENFORCE_UID(AID_SYSTEM); 1049 CHECK_ARGUMENT_UUID(uuid); 1050 for (auto packageName : packageNames) { 1051 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 1052 } 1053 1054 // When modifying this logic, always verify using tests: 1055 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize 1056 1057#if MEASURE_DEBUG 1058 LOG(INFO) << "Measuring user " << userId << " app " << appId; 1059#endif 1060 1061 // Here's a summary of the common storage locations across the platform, 1062 // and how they're each tagged: 1063 // 1064 // /data/app/com.example UID system 1065 // /data/app/com.example/oat UID system 1066 // /data/user/0/com.example UID u0_a10 GID u0_a10 1067 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache 1068 // /data/media/0/foo.txt UID u0_media_rw 1069 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image 1070 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext 1071 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache 1072 // /data/media/obb/com.example UID system 1073 1074 struct stats stats; 1075 struct stats extStats; 1076 memset(&stats, 0, sizeof(stats)); 1077 memset(&extStats, 0, sizeof(extStats)); 1078 1079 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 1080 1081 for (auto packageName : packageNames) { 1082 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str()); 1083 calculate_tree_size(obbCodePath, &extStats.codeSize); 1084 } 1085 1086 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) { 1087 for (auto codePath : codePaths) { 1088 calculate_tree_size(codePath, &stats.codeSize, -1, 1089 multiuser_get_shared_gid(userId, appId)); 1090 } 1091 1092 collectQuotaStats(uuid, userId, appId, &stats, &extStats); 1093 1094 } else { 1095 for (auto codePath : codePaths) { 1096 calculate_tree_size(codePath, &stats.codeSize); 1097 } 1098 1099 for (size_t i = 0; i < packageNames.size(); i++) { 1100 const char* pkgname = packageNames[i].c_str(); 1101 1102 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]); 1103 collectManualStats(cePath, &stats); 1104 1105 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname); 1106 collectManualStats(dePath, &stats); 1107 1108 auto userProfilePath = create_data_user_profile_package_path(userId, pkgname); 1109 calculate_tree_size(userProfilePath, &stats.dataSize); 1110 1111 auto refProfilePath = create_data_ref_profile_package_path(pkgname); 1112 calculate_tree_size(refProfilePath, &stats.codeSize); 1113 1114#if MEASURE_EXTERNAL 1115 auto extPath = create_data_media_package_path(uuid_, userId, pkgname, "data"); 1116 collectManualStats(extPath, &extStats); 1117 1118 auto mediaPath = create_data_media_package_path(uuid_, userId, pkgname, "media"); 1119 calculate_tree_size(mediaPath, &extStats.dataSize); 1120#endif 1121 } 1122 1123 int32_t sharedGid = multiuser_get_shared_gid(userId, appId); 1124 if (sharedGid != -1) { 1125 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize, 1126 sharedGid, -1); 1127 } 1128 1129 calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize, 1130 multiuser_get_uid(userId, appId), -1); 1131 } 1132 1133 std::vector<int64_t> ret; 1134 ret.push_back(stats.codeSize); 1135 ret.push_back(stats.dataSize); 1136 ret.push_back(stats.cacheSize); 1137 ret.push_back(extStats.codeSize); 1138 ret.push_back(extStats.dataSize); 1139 ret.push_back(extStats.cacheSize); 1140#if MEASURE_DEBUG 1141 LOG(DEBUG) << "Final result " << toString(ret); 1142#endif 1143 *_aidl_return = ret; 1144 return ok(); 1145} 1146 1147binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid, 1148 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds, 1149 std::vector<int64_t>* _aidl_return) { 1150 ENFORCE_UID(AID_SYSTEM); 1151 CHECK_ARGUMENT_UUID(uuid); 1152 1153 // When modifying this logic, always verify using tests: 1154 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize 1155 1156#if MEASURE_DEBUG 1157 LOG(INFO) << "Measuring user " << userId; 1158#endif 1159 1160 struct stats stats; 1161 struct stats extStats; 1162 memset(&stats, 0, sizeof(stats)); 1163 memset(&extStats, 0, sizeof(extStats)); 1164 1165 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 1166 1167 auto obbPath = create_data_path(uuid_) + "/media/obb"; 1168 calculate_tree_size(obbPath, &extStats.codeSize); 1169 1170 if (flags & FLAG_USE_QUOTA) { 1171 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true); 1172 1173 auto cePath = create_data_user_ce_path(uuid_, userId); 1174 collectManualStatsForUser(cePath, &stats, true); 1175 1176 auto dePath = create_data_user_de_path(uuid_, userId); 1177 collectManualStatsForUser(dePath, &stats, true); 1178 1179 auto userProfilePath = create_data_user_profile_path(userId); 1180 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true); 1181 1182 auto refProfilePath = create_data_ref_profile_path(); 1183 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true); 1184 1185#if MEASURE_EXTERNAL 1186 // TODO: measure external storage paths 1187#endif 1188 1189 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize, 1190 -1, -1, true); 1191 1192 calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize, 1193 -1, -1, true); 1194 1195 auto device = findDeviceForUuid(uuid); 1196 for (auto appId : appIds) { 1197 if (appId >= AID_APP_START) { 1198 collectQuotaStats(device, userId, appId, &stats, &extStats); 1199#if MEASURE_DEBUG 1200 // Sleep to make sure we don't lose logs 1201 usleep(1); 1202#endif 1203 } 1204 } 1205 } else { 1206 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize); 1207 1208 auto cePath = create_data_user_ce_path(uuid_, userId); 1209 collectManualStatsForUser(cePath, &stats); 1210 1211 auto dePath = create_data_user_de_path(uuid_, userId); 1212 collectManualStatsForUser(dePath, &stats); 1213 1214 auto userProfilePath = create_data_user_profile_path(userId); 1215 calculate_tree_size(userProfilePath, &stats.dataSize); 1216 1217 auto refProfilePath = create_data_ref_profile_path(); 1218 calculate_tree_size(refProfilePath, &stats.codeSize); 1219 1220#if MEASURE_EXTERNAL 1221 // TODO: measure external storage paths 1222#endif 1223 1224 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize); 1225 1226 calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize); 1227 } 1228 1229 std::vector<int64_t> ret; 1230 ret.push_back(stats.codeSize); 1231 ret.push_back(stats.dataSize); 1232 ret.push_back(stats.cacheSize); 1233 ret.push_back(extStats.codeSize); 1234 ret.push_back(extStats.dataSize); 1235 ret.push_back(extStats.cacheSize); 1236#if MEASURE_DEBUG 1237 LOG(DEBUG) << "Final result " << toString(ret); 1238#endif 1239 *_aidl_return = ret; 1240 return ok(); 1241} 1242 1243binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid, 1244 int32_t userId, int32_t flags, std::vector<int64_t>* _aidl_return) { 1245 ENFORCE_UID(AID_SYSTEM); 1246 CHECK_ARGUMENT_UUID(uuid); 1247 1248 // When modifying this logic, always verify using tests: 1249 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize 1250 1251#if MEASURE_DEBUG 1252 LOG(INFO) << "Measuring external " << userId; 1253#endif 1254 1255 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 1256 1257 int64_t totalSize = 0; 1258 int64_t audioSize = 0; 1259 int64_t videoSize = 0; 1260 int64_t imageSize = 0; 1261 1262 if (flags & FLAG_USE_QUOTA) { 1263 struct dqblk dq; 1264 1265 auto device = findDeviceForUuid(uuid); 1266 1267 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW); 1268 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid, 1269 reinterpret_cast<char*>(&dq)) != 0) { 1270 if (errno != ESRCH) { 1271 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid; 1272 } 1273 } else { 1274#if MEASURE_DEBUG 1275 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace; 1276#endif 1277 totalSize = dq.dqb_curspace; 1278 } 1279 1280 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO); 1281 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid, 1282 reinterpret_cast<char*>(&dq)) == 0) { 1283#if MEASURE_DEBUG 1284 LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace; 1285#endif 1286 audioSize = dq.dqb_curspace; 1287 } 1288 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO); 1289 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid, 1290 reinterpret_cast<char*>(&dq)) == 0) { 1291#if MEASURE_DEBUG 1292 LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace; 1293#endif 1294 videoSize = dq.dqb_curspace; 1295 } 1296 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE); 1297 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid, 1298 reinterpret_cast<char*>(&dq)) == 0) { 1299#if MEASURE_DEBUG 1300 LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace; 1301#endif 1302 imageSize = dq.dqb_curspace; 1303 } 1304 } else { 1305 FTS *fts; 1306 FTSENT *p; 1307 auto path = create_data_media_path(uuid_, userId); 1308 char *argv[] = { (char*) path.c_str(), nullptr }; 1309 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) { 1310 return error("Failed to fts_open " + path); 1311 } 1312 while ((p = fts_read(fts)) != NULL) { 1313 char* ext; 1314 int64_t size = (p->fts_statp->st_blocks * 512); 1315 switch (p->fts_info) { 1316 case FTS_F: 1317 // Only categorize files not belonging to apps 1318 if (p->fts_statp->st_gid < AID_APP_START) { 1319 ext = strrchr(p->fts_name, '.'); 1320 if (ext != nullptr) { 1321 switch (MatchExtension(++ext)) { 1322 case AID_MEDIA_AUDIO: audioSize += size; break; 1323 case AID_MEDIA_VIDEO: videoSize += size; break; 1324 case AID_MEDIA_IMAGE: imageSize += size; break; 1325 } 1326 } 1327 } 1328 // Fall through to always count against total 1329 case FTS_D: 1330 case FTS_DEFAULT: 1331 case FTS_SL: 1332 case FTS_SLNONE: 1333 totalSize += size; 1334 break; 1335 } 1336 } 1337 fts_close(fts); 1338 } 1339 1340 std::vector<int64_t> ret; 1341 ret.push_back(totalSize); 1342 ret.push_back(audioSize); 1343 ret.push_back(videoSize); 1344 ret.push_back(imageSize); 1345#if MEASURE_DEBUG 1346 LOG(DEBUG) << "Final result " << toString(ret); 1347#endif 1348 *_aidl_return = ret; 1349 return ok(); 1350} 1351 1352// Dumps the contents of a profile file, using pkgname's dex files for pretty 1353// printing the result. 1354binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName, 1355 const std::string& codePaths, bool* _aidl_return) { 1356 ENFORCE_UID(AID_SYSTEM); 1357 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 1358 1359 const char* pkgname = packageName.c_str(); 1360 const char* code_paths = codePaths.c_str(); 1361 1362 *_aidl_return = dump_profiles(uid, pkgname, code_paths); 1363 return ok(); 1364} 1365 1366// TODO: Consider returning error codes. 1367binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName, 1368 bool* _aidl_return) { 1369 ENFORCE_UID(AID_SYSTEM); 1370 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 1371 1372 const char* pkgname = packageName.c_str(); 1373 *_aidl_return = analyse_profiles(uid, pkgname); 1374 return ok(); 1375} 1376 1377binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid, 1378 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet, 1379 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags, 1380 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid, 1381 const std::unique_ptr<std::string>& sharedLibraries) { 1382 ENFORCE_UID(AID_SYSTEM); 1383 CHECK_ARGUMENT_UUID(uuid); 1384 if (packageName && *packageName != "*") { 1385 CHECK_ARGUMENT_PACKAGE_NAME(*packageName); 1386 } 1387 1388 const char* apk_path = apkPath.c_str(); 1389 const char* pkgname = packageName ? packageName->c_str() : "*"; 1390 const char* instruction_set = instructionSet.c_str(); 1391 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr; 1392 const char* compiler_filter = compilerFilter.c_str(); 1393 const char* volume_uuid = uuid ? uuid->c_str() : nullptr; 1394 const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr; 1395 1396 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded, 1397 oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries); 1398 return res ? error(res, "Failed to dexopt") : ok(); 1399} 1400 1401binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) { 1402 ENFORCE_UID(AID_SYSTEM); 1403 const char* instruction_set = instructionSet.c_str(); 1404 1405 char boot_marker_path[PKG_PATH_MAX]; 1406 sprintf(boot_marker_path, 1407 "%s/%s/%s/.booting", 1408 android_data_dir.path, 1409 DALVIK_CACHE, 1410 instruction_set); 1411 1412 ALOGV("mark_boot_complete : %s", boot_marker_path); 1413 if (unlink(boot_marker_path) != 0) { 1414 return error(StringPrintf("Failed to unlink %s", boot_marker_path)); 1415 } 1416 return ok(); 1417} 1418 1419void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid, 1420 struct stat* statbuf) 1421{ 1422 while (path[basepos] != 0) { 1423 if (path[basepos] == '/') { 1424 path[basepos] = 0; 1425 if (lstat(path, statbuf) < 0) { 1426 ALOGV("Making directory: %s\n", path); 1427 if (mkdir(path, mode) == 0) { 1428 chown(path, uid, gid); 1429 } else { 1430 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno)); 1431 } 1432 } 1433 path[basepos] = '/'; 1434 basepos++; 1435 } 1436 basepos++; 1437 } 1438} 1439 1440binder::Status InstalldNativeService::linkNativeLibraryDirectory( 1441 const std::unique_ptr<std::string>& uuid, const std::string& packageName, 1442 const std::string& nativeLibPath32, int32_t userId) { 1443 ENFORCE_UID(AID_SYSTEM); 1444 CHECK_ARGUMENT_UUID(uuid); 1445 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 1446 1447 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 1448 const char* pkgname = packageName.c_str(); 1449 const char* asecLibDir = nativeLibPath32.c_str(); 1450 struct stat s, libStat; 1451 binder::Status res = ok(); 1452 1453 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname); 1454 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX; 1455 1456 const char* pkgdir = _pkgdir.c_str(); 1457 const char* libsymlink = _libsymlink.c_str(); 1458 1459 if (stat(pkgdir, &s) < 0) { 1460 return error("Failed to stat " + _pkgdir); 1461 } 1462 1463 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) { 1464 return error("Failed to chown " + _pkgdir); 1465 } 1466 1467 if (chmod(pkgdir, 0700) < 0) { 1468 res = error("Failed to chmod " + _pkgdir); 1469 goto out; 1470 } 1471 1472 if (lstat(libsymlink, &libStat) < 0) { 1473 if (errno != ENOENT) { 1474 res = error("Failed to stat " + _libsymlink); 1475 goto out; 1476 } 1477 } else { 1478 if (S_ISDIR(libStat.st_mode)) { 1479 if (delete_dir_contents(libsymlink, 1, NULL) < 0) { 1480 res = error("Failed to delete " + _libsymlink); 1481 goto out; 1482 } 1483 } else if (S_ISLNK(libStat.st_mode)) { 1484 if (unlink(libsymlink) < 0) { 1485 res = error("Failed to unlink " + _libsymlink); 1486 goto out; 1487 } 1488 } 1489 } 1490 1491 if (symlink(asecLibDir, libsymlink) < 0) { 1492 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32); 1493 goto out; 1494 } 1495 1496out: 1497 if (chmod(pkgdir, s.st_mode) < 0) { 1498 auto msg = "Failed to cleanup chmod " + _pkgdir; 1499 if (res.isOk()) { 1500 res = error(msg); 1501 } else { 1502 PLOG(ERROR) << msg; 1503 } 1504 } 1505 1506 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) { 1507 auto msg = "Failed to cleanup chown " + _pkgdir; 1508 if (res.isOk()) { 1509 res = error(msg); 1510 } else { 1511 PLOG(ERROR) << msg; 1512 } 1513 } 1514 1515 return res; 1516} 1517 1518static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd) 1519{ 1520 static const char *IDMAP_BIN = "/system/bin/idmap"; 1521 static const size_t MAX_INT_LEN = 32; 1522 char idmap_str[MAX_INT_LEN]; 1523 1524 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd); 1525 1526 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL); 1527 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno)); 1528} 1529 1530// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix) 1531// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap 1532static int flatten_path(const char *prefix, const char *suffix, 1533 const char *overlay_path, char *idmap_path, size_t N) 1534{ 1535 if (overlay_path == NULL || idmap_path == NULL) { 1536 return -1; 1537 } 1538 const size_t len_overlay_path = strlen(overlay_path); 1539 // will access overlay_path + 1 further below; requires absolute path 1540 if (len_overlay_path < 2 || *overlay_path != '/') { 1541 return -1; 1542 } 1543 const size_t len_idmap_root = strlen(prefix); 1544 const size_t len_suffix = strlen(suffix); 1545 if (SIZE_MAX - len_idmap_root < len_overlay_path || 1546 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) { 1547 // additions below would cause overflow 1548 return -1; 1549 } 1550 if (N < len_idmap_root + len_overlay_path + len_suffix) { 1551 return -1; 1552 } 1553 memset(idmap_path, 0, N); 1554 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix); 1555 char *ch = idmap_path + len_idmap_root; 1556 while (*ch != '\0') { 1557 if (*ch == '/') { 1558 *ch = '@'; 1559 } 1560 ++ch; 1561 } 1562 return 0; 1563} 1564 1565binder::Status InstalldNativeService::idmap(const std::string& targetApkPath, 1566 const std::string& overlayApkPath, int32_t uid) { 1567 ENFORCE_UID(AID_SYSTEM); 1568 const char* target_apk = targetApkPath.c_str(); 1569 const char* overlay_apk = overlayApkPath.c_str(); 1570 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid); 1571 1572 int idmap_fd = -1; 1573 char idmap_path[PATH_MAX]; 1574 1575 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk, 1576 idmap_path, sizeof(idmap_path)) == -1) { 1577 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk); 1578 goto fail; 1579 } 1580 1581 unlink(idmap_path); 1582 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644); 1583 if (idmap_fd < 0) { 1584 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno)); 1585 goto fail; 1586 } 1587 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) { 1588 ALOGE("idmap cannot chown '%s'\n", idmap_path); 1589 goto fail; 1590 } 1591 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) { 1592 ALOGE("idmap cannot chmod '%s'\n", idmap_path); 1593 goto fail; 1594 } 1595 1596 pid_t pid; 1597 pid = fork(); 1598 if (pid == 0) { 1599 /* child -- drop privileges before continuing */ 1600 if (setgid(uid) != 0) { 1601 ALOGE("setgid(%d) failed during idmap\n", uid); 1602 exit(1); 1603 } 1604 if (setuid(uid) != 0) { 1605 ALOGE("setuid(%d) failed during idmap\n", uid); 1606 exit(1); 1607 } 1608 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) { 1609 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno)); 1610 exit(1); 1611 } 1612 1613 run_idmap(target_apk, overlay_apk, idmap_fd); 1614 exit(1); /* only if exec call to idmap failed */ 1615 } else { 1616 int status = wait_child(pid); 1617 if (status != 0) { 1618 ALOGE("idmap failed, status=0x%04x\n", status); 1619 goto fail; 1620 } 1621 } 1622 1623 close(idmap_fd); 1624 return ok(); 1625fail: 1626 if (idmap_fd >= 0) { 1627 close(idmap_fd); 1628 unlink(idmap_path); 1629 } 1630 return error(); 1631} 1632 1633binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid, 1634 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId, 1635 const std::string& seInfo) { 1636 ENFORCE_UID(AID_SYSTEM); 1637 CHECK_ARGUMENT_UUID(uuid); 1638 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 1639 1640 binder::Status res = ok(); 1641 1642 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here. 1643 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE; 1644 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 1645 const char* pkgName = packageName.c_str(); 1646 const char* seinfo = seInfo.c_str(); 1647 1648 uid_t uid = multiuser_get_uid(userId, appId); 1649 if (flags & FLAG_STORAGE_CE) { 1650 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName); 1651 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) { 1652 res = error("restorecon failed for " + path); 1653 } 1654 } 1655 if (flags & FLAG_STORAGE_DE) { 1656 auto path = create_data_user_de_package_path(uuid_, userId, pkgName); 1657 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) { 1658 res = error("restorecon failed for " + path); 1659 } 1660 } 1661 return res; 1662} 1663 1664binder::Status InstalldNativeService::createOatDir(const std::string& oatDir, 1665 const std::string& instructionSet) { 1666 ENFORCE_UID(AID_SYSTEM); 1667 const char* oat_dir = oatDir.c_str(); 1668 const char* instruction_set = instructionSet.c_str(); 1669 char oat_instr_dir[PKG_PATH_MAX]; 1670 1671 if (validate_apk_path(oat_dir)) { 1672 return error("Invalid path " + oatDir); 1673 } 1674 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) { 1675 return error("Failed to prepare " + oatDir); 1676 } 1677 if (selinux_android_restorecon(oat_dir, 0)) { 1678 return error("Failed to restorecon " + oatDir); 1679 } 1680 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set); 1681 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) { 1682 return error(StringPrintf("Failed to prepare %s", oat_instr_dir)); 1683 } 1684 return ok(); 1685} 1686 1687binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) { 1688 ENFORCE_UID(AID_SYSTEM); 1689 if (validate_apk_path(packageDir.c_str())) { 1690 return error("Invalid path " + packageDir); 1691 } 1692 if (delete_dir_contents_and_dir(packageDir) != 0) { 1693 return error("Failed to delete " + packageDir); 1694 } 1695 return ok(); 1696} 1697 1698binder::Status InstalldNativeService::linkFile(const std::string& relativePath, 1699 const std::string& fromBase, const std::string& toBase) { 1700 ENFORCE_UID(AID_SYSTEM); 1701 const char* relative_path = relativePath.c_str(); 1702 const char* from_base = fromBase.c_str(); 1703 const char* to_base = toBase.c_str(); 1704 char from_path[PKG_PATH_MAX]; 1705 char to_path[PKG_PATH_MAX]; 1706 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path); 1707 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path); 1708 1709 if (validate_apk_path_subdirs(from_path)) { 1710 return error(StringPrintf("Invalid from path %s", from_path)); 1711 } 1712 1713 if (validate_apk_path_subdirs(to_path)) { 1714 return error(StringPrintf("Invalid to path %s", to_path)); 1715 } 1716 1717 if (link(from_path, to_path) < 0) { 1718 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path)); 1719 } 1720 1721 return ok(); 1722} 1723 1724binder::Status InstalldNativeService::moveAb(const std::string& apkPath, 1725 const std::string& instructionSet, const std::string& outputPath) { 1726 ENFORCE_UID(AID_SYSTEM); 1727 1728 const char* apk_path = apkPath.c_str(); 1729 const char* instruction_set = instructionSet.c_str(); 1730 const char* oat_dir = outputPath.c_str(); 1731 1732 bool success = move_ab(apk_path, instruction_set, oat_dir); 1733 return success ? ok() : error(); 1734} 1735 1736binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath, 1737 const std::string& instructionSet, const std::string& outputPath) { 1738 ENFORCE_UID(AID_SYSTEM); 1739 1740 const char* apk_path = apkPath.c_str(); 1741 const char* instruction_set = instructionSet.c_str(); 1742 const char* oat_dir = outputPath.c_str(); 1743 1744 bool res = delete_odex(apk_path, instruction_set, oat_dir); 1745 return res ? ok() : error(); 1746} 1747 1748} // namespace installd 1749} // namespace android 1750