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#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
20
21#include <errno.h>
22#include <inttypes.h>
23#include <fstream>
24#include <fts.h>
25#include <regex>
26#include <stdlib.h>
27#include <string.h>
28#include <sys/capability.h>
29#include <sys/file.h>
30#include <sys/resource.h>
31#include <sys/quota.h>
32#include <sys/stat.h>
33#include <sys/statvfs.h>
34#include <sys/types.h>
35#include <sys/wait.h>
36#include <sys/xattr.h>
37#include <unistd.h>
38
39#include <android-base/logging.h>
40#include <android-base/stringprintf.h>
41#include <android-base/strings.h>
42#include <android-base/unique_fd.h>
43#include <cutils/fs.h>
44#include <cutils/properties.h>
45#include <cutils/sched_policy.h>
46#include <log/log.h>               // TODO: Move everything to base/logging.
47#include <logwrap/logwrap.h>
48#include <private/android_filesystem_config.h>
49#include <selinux/android.h>
50#include <system/thread_defs.h>
51#include <utils/Trace.h>
52
53#include "dexopt.h"
54#include "globals.h"
55#include "installd_deps.h"
56#include "otapreopt_utils.h"
57#include "utils.h"
58
59#include "CacheTracker.h"
60#include "MatchExtensionGen.h"
61
62#ifndef LOG_TAG
63#define LOG_TAG "installd"
64#endif
65
66using android::base::StringPrintf;
67using std::endl;
68
69namespace android {
70namespace installd {
71
72static constexpr const char* kCpPath = "/system/bin/cp";
73static constexpr const char* kXattrDefault = "user.default";
74
75static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
76
77static constexpr const char* PKG_LIB_POSTFIX = "/lib";
78static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
79static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
80
81static constexpr const char *kIdMapPath = "/system/bin/idmap";
82static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
83static constexpr const char* IDMAP_SUFFIX = "@idmap";
84
85// NOTE: keep in sync with Installer
86static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
87static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
88static constexpr int FLAG_USE_QUOTA = 1 << 12;
89static constexpr int FLAG_FREE_CACHE_V2 = 1 << 13;
90static constexpr int FLAG_FREE_CACHE_V2_DEFY_QUOTA = 1 << 14;
91static constexpr int FLAG_FREE_CACHE_NOOP = 1 << 15;
92static constexpr int FLAG_FORCE = 1 << 16;
93
94namespace {
95
96constexpr const char* kDump = "android.permission.DUMP";
97
98static binder::Status ok() {
99    return binder::Status::ok();
100}
101
102static binder::Status exception(uint32_t code, const std::string& msg) {
103    return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
104}
105
106static binder::Status error() {
107    return binder::Status::fromServiceSpecificError(errno);
108}
109
110static binder::Status error(const std::string& msg) {
111    PLOG(ERROR) << msg;
112    return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
113}
114
115static binder::Status error(uint32_t code, const std::string& msg) {
116    LOG(ERROR) << msg << " (" << code << ")";
117    return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
118}
119
120binder::Status checkPermission(const char* permission) {
121    pid_t pid;
122    uid_t uid;
123
124    if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
125            reinterpret_cast<int32_t*>(&uid))) {
126        return ok();
127    } else {
128        return exception(binder::Status::EX_SECURITY,
129                StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
130    }
131}
132
133binder::Status checkUid(uid_t expectedUid) {
134    uid_t uid = IPCThreadState::self()->getCallingUid();
135    if (uid == expectedUid || uid == AID_ROOT) {
136        return ok();
137    } else {
138        return exception(binder::Status::EX_SECURITY,
139                StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
140    }
141}
142
143binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
144    if (!uuid || is_valid_filename(*uuid)) {
145        return ok();
146    } else {
147        return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
148                StringPrintf("UUID %s is malformed", uuid->c_str()));
149    }
150}
151
152binder::Status checkArgumentPackageName(const std::string& packageName) {
153    if (is_valid_package_name(packageName.c_str())) {
154        return ok();
155    } else {
156        return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
157                StringPrintf("Package name %s is malformed", packageName.c_str()));
158    }
159}
160
161#define ENFORCE_UID(uid) {                                  \
162    binder::Status status = checkUid((uid));                \
163    if (!status.isOk()) {                                   \
164        return status;                                      \
165    }                                                       \
166}
167
168#define CHECK_ARGUMENT_UUID(uuid) {                         \
169    binder::Status status = checkArgumentUuid((uuid));      \
170    if (!status.isOk()) {                                   \
171        return status;                                      \
172    }                                                       \
173}
174
175#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) {          \
176    binder::Status status =                                 \
177            checkArgumentPackageName((packageName));        \
178    if (!status.isOk()) {                                   \
179        return status;                                      \
180    }                                                       \
181}
182
183}  // namespace
184
185status_t InstalldNativeService::start() {
186    IPCThreadState::self()->disableBackgroundScheduling(true);
187    status_t ret = BinderService<InstalldNativeService>::publish();
188    if (ret != android::OK) {
189        return ret;
190    }
191    sp<ProcessState> ps(ProcessState::self());
192    ps->startThreadPool();
193    ps->giveThreadPoolName();
194    return android::OK;
195}
196
197status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
198    auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
199    const binder::Status dump_permission = checkPermission(kDump);
200    if (!dump_permission.isOk()) {
201        out << dump_permission.toString8() << endl;
202        return PERMISSION_DENIED;
203    }
204    std::lock_guard<std::recursive_mutex> lock(mLock);
205
206    out << "installd is happy!" << endl;
207
208    {
209        std::lock_guard<std::recursive_mutex> lock(mMountsLock);
210        out << endl << "Storage mounts:" << endl;
211        for (const auto& n : mStorageMounts) {
212            out << "    " << n.first << " = " << n.second << endl;
213        }
214
215        out << endl << "Quota reverse mounts:" << endl;
216        for (const auto& n : mQuotaReverseMounts) {
217            out << "    " << n.first << " = " << n.second << endl;
218        }
219    }
220
221    {
222        std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
223        out << endl << "Per-UID cache quotas:" << endl;
224        for (const auto& n : mCacheQuotas) {
225            out << "    " << n.first << " = " << n.second << endl;
226        }
227    }
228
229    out << endl;
230    out.flush();
231
232    return NO_ERROR;
233}
234
235/**
236 * Perform restorecon of the given path, but only perform recursive restorecon
237 * if the label of that top-level file actually changed.  This can save us
238 * significant time by avoiding no-op traversals of large filesystem trees.
239 */
240static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
241        bool existing) {
242    int res = 0;
243    char* before = nullptr;
244    char* after = nullptr;
245
246    // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
247    // libselinux. Not needed here.
248
249    if (lgetfilecon(path.c_str(), &before) < 0) {
250        PLOG(ERROR) << "Failed before getfilecon for " << path;
251        goto fail;
252    }
253    if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
254        PLOG(ERROR) << "Failed top-level restorecon for " << path;
255        goto fail;
256    }
257    if (lgetfilecon(path.c_str(), &after) < 0) {
258        PLOG(ERROR) << "Failed after getfilecon for " << path;
259        goto fail;
260    }
261
262    // If the initial top-level restorecon above changed the label, then go
263    // back and restorecon everything recursively
264    if (strcmp(before, after)) {
265        if (existing) {
266            LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
267                    << path << "; running recursive restorecon";
268        }
269        if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
270                SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
271            PLOG(ERROR) << "Failed recursive restorecon for " << path;
272            goto fail;
273        }
274    }
275
276    goto done;
277fail:
278    res = -1;
279done:
280    free(before);
281    free(after);
282    return res;
283}
284
285static int restorecon_app_data_lazy(const std::string& parent, const char* name,
286        const std::string& seInfo, uid_t uid, bool existing) {
287    return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
288            existing);
289}
290
291static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
292    if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
293        PLOG(ERROR) << "Failed to prepare " << path;
294        return -1;
295    }
296    return 0;
297}
298
299/**
300 * Ensure that we have a hard-limit quota to protect against abusive apps;
301 * they should never use more than 90% of blocks or 50% of inodes.
302 */
303static int prepare_app_quota(const std::unique_ptr<std::string>& uuid, const std::string& device,
304        uid_t uid) {
305    if (device.empty()) return 0;
306
307    struct dqblk dq;
308    if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
309            reinterpret_cast<char*>(&dq)) != 0) {
310        PLOG(WARNING) << "Failed to find quota for " << uid;
311        return -1;
312    }
313
314    if ((dq.dqb_bhardlimit == 0) || (dq.dqb_ihardlimit == 0)) {
315        auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
316        struct statvfs stat;
317        if (statvfs(path.c_str(), &stat) != 0) {
318            PLOG(WARNING) << "Failed to statvfs " << path;
319            return -1;
320        }
321
322        dq.dqb_valid = QIF_LIMITS;
323        dq.dqb_bhardlimit = (((stat.f_blocks * stat.f_frsize) / 10) * 9) / QIF_DQBLKSIZE;
324        dq.dqb_ihardlimit = (stat.f_files / 2);
325        if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), device.c_str(), uid,
326                reinterpret_cast<char*>(&dq)) != 0) {
327            PLOG(WARNING) << "Failed to set hard quota for " << uid;
328            return -1;
329        } else {
330            LOG(DEBUG) << "Applied hard quotas for " << uid;
331            return 0;
332        }
333    } else {
334        // Hard quota already set; assume it's reasonable
335        return 0;
336    }
337}
338
339binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
340        const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
341        const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
342    ENFORCE_UID(AID_SYSTEM);
343    CHECK_ARGUMENT_UUID(uuid);
344    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
345    std::lock_guard<std::recursive_mutex> lock(mLock);
346
347    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
348    const char* pkgname = packageName.c_str();
349
350    // Assume invalid inode unless filled in below
351    if (_aidl_return != nullptr) *_aidl_return = -1;
352
353    int32_t uid = multiuser_get_uid(userId, appId);
354    int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
355    mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
356
357    // If UID doesn't have a specific cache GID, use UID value
358    if (cacheGid == -1) {
359        cacheGid = uid;
360    }
361
362    if (flags & FLAG_STORAGE_CE) {
363        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
364        bool existing = (access(path.c_str(), F_OK) == 0);
365
366        if (prepare_app_dir(path, targetMode, uid) ||
367                prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
368                prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
369            return error("Failed to prepare " + path);
370        }
371
372        // Consider restorecon over contents if label changed
373        if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
374                restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
375                restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
376            return error("Failed to restorecon " + path);
377        }
378
379        // Remember inode numbers of cache directories so that we can clear
380        // contents while CE storage is locked
381        if (write_path_inode(path, "cache", kXattrInodeCache) ||
382                write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
383            return error("Failed to write_path_inode for " + path);
384        }
385
386        // And return the CE inode of the top-level data directory so we can
387        // clear contents while CE storage is locked
388        if ((_aidl_return != nullptr)
389                && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
390            return error("Failed to get_path_inode for " + path);
391        }
392    }
393    if (flags & FLAG_STORAGE_DE) {
394        auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
395        bool existing = (access(path.c_str(), F_OK) == 0);
396
397        if (prepare_app_dir(path, targetMode, uid) ||
398                prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
399                prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
400            return error("Failed to prepare " + path);
401        }
402
403        // Consider restorecon over contents if label changed
404        if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
405                restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
406                restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
407            return error("Failed to restorecon " + path);
408        }
409
410        if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid), uid)) {
411            return error("Failed to set hard quota " + path);
412        }
413
414        if (property_get_bool("dalvik.vm.usejitprofiles", false)) {
415            const std::string profile_dir =
416                    create_primary_current_profile_package_dir_path(userId, pkgname);
417            // read-write-execute only for the app user.
418            if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
419                return error("Failed to prepare " + profile_dir);
420            }
421            const std::string profile_file = create_current_profile_path(userId, pkgname,
422                    /*is_secondary_dex*/false);
423            // read-write only for the app user.
424            if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
425                return error("Failed to prepare " + profile_file);
426            }
427            const std::string ref_profile_path =
428                    create_primary_reference_profile_package_dir_path(pkgname);
429            // dex2oat/profman runs under the shared app gid and it needs to read/write reference
430            // profiles.
431            int shared_app_gid = multiuser_get_shared_gid(0, appId);
432            if ((shared_app_gid != -1) && fs_prepare_dir_strict(
433                    ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
434                return error("Failed to prepare " + ref_profile_path);
435            }
436        }
437    }
438    return ok();
439}
440
441binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
442        const std::string& packageName, int32_t userId, int32_t flags) {
443    ENFORCE_UID(AID_SYSTEM);
444    CHECK_ARGUMENT_UUID(uuid);
445    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
446    std::lock_guard<std::recursive_mutex> lock(mLock);
447
448    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
449    const char* pkgname = packageName.c_str();
450
451    // This method only exists to upgrade system apps that have requested
452    // forceDeviceEncrypted, so their default storage always lives in a
453    // consistent location.  This only works on non-FBE devices, since we
454    // never want to risk exposing data on a device with real CE/DE storage.
455
456    auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
457    auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
458
459    // If neither directory is marked as default, assume CE is default
460    if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
461            && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
462        if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
463            return error("Failed to mark default storage " + ce_path);
464        }
465    }
466
467    // Migrate default data location if needed
468    auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
469    auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
470
471    if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
472        LOG(WARNING) << "Requested default storage " << target
473                << " is not active; migrating from " << source;
474        if (delete_dir_contents_and_dir(target) != 0) {
475            return error("Failed to delete " + target);
476        }
477        if (rename(source.c_str(), target.c_str()) != 0) {
478            return error("Failed to rename " + source + " to " + target);
479        }
480    }
481
482    return ok();
483}
484
485
486binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
487    ENFORCE_UID(AID_SYSTEM);
488    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
489    std::lock_guard<std::recursive_mutex> lock(mLock);
490
491    binder::Status res = ok();
492    if (!clear_primary_reference_profile(packageName)) {
493        res = error("Failed to clear reference profile for " + packageName);
494    }
495    if (!clear_primary_current_profiles(packageName)) {
496        res = error("Failed to clear current profiles for " + packageName);
497    }
498    return res;
499}
500
501binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
502        const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
503    ENFORCE_UID(AID_SYSTEM);
504    CHECK_ARGUMENT_UUID(uuid);
505    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
506    std::lock_guard<std::recursive_mutex> lock(mLock);
507
508    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
509    const char* pkgname = packageName.c_str();
510
511    binder::Status res = ok();
512    if (flags & FLAG_STORAGE_CE) {
513        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
514        if (flags & FLAG_CLEAR_CACHE_ONLY) {
515            path = read_path_inode(path, "cache", kXattrInodeCache);
516        } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
517            path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
518        }
519        if (access(path.c_str(), F_OK) == 0) {
520            if (delete_dir_contents(path) != 0) {
521                res = error("Failed to delete contents of " + path);
522            }
523        }
524    }
525    if (flags & FLAG_STORAGE_DE) {
526        std::string suffix = "";
527        bool only_cache = false;
528        if (flags & FLAG_CLEAR_CACHE_ONLY) {
529            suffix = CACHE_DIR_POSTFIX;
530            only_cache = true;
531        } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
532            suffix = CODE_CACHE_DIR_POSTFIX;
533            only_cache = true;
534        }
535
536        auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
537        if (access(path.c_str(), F_OK) == 0) {
538            if (delete_dir_contents(path) != 0) {
539                res = error("Failed to delete contents of " + path);
540            }
541        }
542        if (!only_cache) {
543            if (!clear_primary_current_profile(packageName, userId)) {
544                res = error("Failed to clear current profile for " + packageName);
545            }
546        }
547    }
548    return res;
549}
550
551static int destroy_app_reference_profile(const std::string& pkgname) {
552    return delete_dir_contents_and_dir(
553        create_primary_reference_profile_package_dir_path(pkgname),
554        /*ignore_if_missing*/ true);
555}
556
557static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
558    return delete_dir_contents_and_dir(
559        create_primary_current_profile_package_dir_path(userid, pkgname),
560        /*ignore_if_missing*/ true);
561}
562
563binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
564    ENFORCE_UID(AID_SYSTEM);
565    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
566    std::lock_guard<std::recursive_mutex> lock(mLock);
567
568    binder::Status res = ok();
569    std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
570    for (auto user : users) {
571        if (destroy_app_current_profiles(packageName, user) != 0) {
572            res = error("Failed to destroy current profiles for " + packageName);
573        }
574    }
575    if (destroy_app_reference_profile(packageName) != 0) {
576        res = error("Failed to destroy reference profile for " + packageName);
577    }
578    return res;
579}
580
581binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
582        const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
583    ENFORCE_UID(AID_SYSTEM);
584    CHECK_ARGUMENT_UUID(uuid);
585    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
586    std::lock_guard<std::recursive_mutex> lock(mLock);
587
588    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
589    const char* pkgname = packageName.c_str();
590
591    binder::Status res = ok();
592    if (flags & FLAG_STORAGE_CE) {
593        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
594        if (delete_dir_contents_and_dir(path) != 0) {
595            res = error("Failed to delete " + path);
596        }
597    }
598    if (flags & FLAG_STORAGE_DE) {
599        auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
600        if (delete_dir_contents_and_dir(path) != 0) {
601            res = error("Failed to delete " + path);
602        }
603        destroy_app_current_profiles(packageName, userId);
604        // TODO(calin): If the package is still installed by other users it's probably
605        // beneficial to keep the reference profile around.
606        // Verify if it's ok to do that.
607        destroy_app_reference_profile(packageName);
608    }
609    return res;
610}
611
612static gid_t get_cache_gid(uid_t uid) {
613    int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
614    return (gid != -1) ? gid : uid;
615}
616
617binder::Status InstalldNativeService::fixupAppData(const std::unique_ptr<std::string>& uuid,
618        int32_t flags) {
619    ENFORCE_UID(AID_SYSTEM);
620    CHECK_ARGUMENT_UUID(uuid);
621    std::lock_guard<std::recursive_mutex> lock(mLock);
622
623    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
624    for (auto user : get_known_users(uuid_)) {
625        ATRACE_BEGIN("fixup user");
626        FTS* fts;
627        FTSENT* p;
628        auto ce_path = create_data_user_ce_path(uuid_, user);
629        auto de_path = create_data_user_de_path(uuid_, user);
630        char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(), nullptr };
631        if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
632            return error("Failed to fts_open");
633        }
634        while ((p = fts_read(fts)) != nullptr) {
635            if (p->fts_info == FTS_D && p->fts_level == 1) {
636                // Track down inodes of cache directories
637                uint64_t raw = 0;
638                ino_t inode_cache = 0;
639                ino_t inode_code_cache = 0;
640                if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
641                    inode_cache = raw;
642                }
643                if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
644                    inode_code_cache = raw;
645                }
646
647                // Figure out expected GID of each child
648                FTSENT* child = fts_children(fts, 0);
649                while (child != nullptr) {
650                    if ((child->fts_statp->st_ino == inode_cache)
651                            || (child->fts_statp->st_ino == inode_code_cache)
652                            || !strcmp(child->fts_name, "cache")
653                            || !strcmp(child->fts_name, "code_cache")) {
654                        child->fts_number = get_cache_gid(p->fts_statp->st_uid);
655                    } else {
656                        child->fts_number = p->fts_statp->st_uid;
657                    }
658                    child = child->fts_link;
659                }
660            } else if (p->fts_level >= 2) {
661                if (p->fts_level > 2) {
662                    // Inherit GID from parent once we're deeper into tree
663                    p->fts_number = p->fts_parent->fts_number;
664                }
665
666                uid_t uid = p->fts_parent->fts_statp->st_uid;
667                gid_t cache_gid = get_cache_gid(uid);
668                gid_t expected = p->fts_number;
669                gid_t actual = p->fts_statp->st_gid;
670                if (actual == expected) {
671#if FIXUP_DEBUG
672                    LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
673#endif
674                    if (!(flags & FLAG_FORCE)) {
675                        fts_set(fts, p, FTS_SKIP);
676                    }
677                } else if ((actual == uid) || (actual == cache_gid)) {
678                    // Only consider fixing up when current GID belongs to app
679                    if (p->fts_info != FTS_D) {
680                        LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
681                                << " instead of " << expected;
682                    }
683                    switch (p->fts_info) {
684                    case FTS_DP:
685                        // If we're moving towards cache GID, we need to set S_ISGID
686                        if (expected == cache_gid) {
687                            if (chmod(p->fts_path, 02771) != 0) {
688                                PLOG(WARNING) << "Failed to chmod " << p->fts_path;
689                            }
690                        }
691                        // Intentional fall through to also set GID
692                    case FTS_F:
693                        if (chown(p->fts_path, -1, expected) != 0) {
694                            PLOG(WARNING) << "Failed to chown " << p->fts_path;
695                        }
696                        break;
697                    case FTS_SL:
698                    case FTS_SLNONE:
699                        if (lchown(p->fts_path, -1, expected) != 0) {
700                            PLOG(WARNING) << "Failed to chown " << p->fts_path;
701                        }
702                        break;
703                    }
704                } else {
705                    // Ignore all other GID transitions, since they're kinda shady
706                    LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
707                            << " instead of " << expected;
708                }
709            }
710        }
711        fts_close(fts);
712        ATRACE_END();
713    }
714    return ok();
715}
716
717binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
718        const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
719        const std::string& dataAppName, int32_t appId, const std::string& seInfo,
720        int32_t targetSdkVersion) {
721    ENFORCE_UID(AID_SYSTEM);
722    CHECK_ARGUMENT_UUID(fromUuid);
723    CHECK_ARGUMENT_UUID(toUuid);
724    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
725    std::lock_guard<std::recursive_mutex> lock(mLock);
726
727    const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
728    const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
729    const char* package_name = packageName.c_str();
730    const char* data_app_name = dataAppName.c_str();
731
732    binder::Status res = ok();
733    std::vector<userid_t> users = get_known_users(from_uuid);
734
735    // Copy app
736    {
737        auto from = create_data_app_package_path(from_uuid, data_app_name);
738        auto to = create_data_app_package_path(to_uuid, data_app_name);
739        auto to_parent = create_data_app_path(to_uuid);
740
741        char *argv[] = {
742            (char*) kCpPath,
743            (char*) "-F", /* delete any existing destination file first (--remove-destination) */
744            (char*) "-p", /* preserve timestamps, ownership, and permissions */
745            (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
746            (char*) "-P", /* Do not follow symlinks [default] */
747            (char*) "-d", /* don't dereference symlinks */
748            (char*) from.c_str(),
749            (char*) to_parent.c_str()
750        };
751
752        LOG(DEBUG) << "Copying " << from << " to " << to;
753        int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
754        if (rc != 0) {
755            res = error(rc, "Failed copying " + from + " to " + to);
756            goto fail;
757        }
758
759        if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
760            res = error("Failed to restorecon " + to);
761            goto fail;
762        }
763    }
764
765    // Copy private data for all known users
766    for (auto user : users) {
767
768        // Data source may not exist for all users; that's okay
769        auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
770        if (access(from_ce.c_str(), F_OK) != 0) {
771            LOG(INFO) << "Missing source " << from_ce;
772            continue;
773        }
774
775        if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
776                seInfo, targetSdkVersion, nullptr).isOk()) {
777            res = error("Failed to create package target");
778            goto fail;
779        }
780
781        char *argv[] = {
782            (char*) kCpPath,
783            (char*) "-F", /* delete any existing destination file first (--remove-destination) */
784            (char*) "-p", /* preserve timestamps, ownership, and permissions */
785            (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
786            (char*) "-P", /* Do not follow symlinks [default] */
787            (char*) "-d", /* don't dereference symlinks */
788            nullptr,
789            nullptr
790        };
791
792        {
793            auto from = create_data_user_de_package_path(from_uuid, user, package_name);
794            auto to = create_data_user_de_path(to_uuid, user);
795            argv[6] = (char*) from.c_str();
796            argv[7] = (char*) to.c_str();
797
798            LOG(DEBUG) << "Copying " << from << " to " << to;
799            int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
800            if (rc != 0) {
801                res = error(rc, "Failed copying " + from + " to " + to);
802                goto fail;
803            }
804        }
805        {
806            auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
807            auto to = create_data_user_ce_path(to_uuid, user);
808            argv[6] = (char*) from.c_str();
809            argv[7] = (char*) to.c_str();
810
811            LOG(DEBUG) << "Copying " << from << " to " << to;
812            int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
813            if (rc != 0) {
814                res = error(rc, "Failed copying " + from + " to " + to);
815                goto fail;
816            }
817        }
818
819        if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
820                appId, seInfo).isOk()) {
821            res = error("Failed to restorecon");
822            goto fail;
823        }
824    }
825
826    // We let the framework scan the new location and persist that before
827    // deleting the data in the old location; this ordering ensures that
828    // we can recover from things like battery pulls.
829    return ok();
830
831fail:
832    // Nuke everything we might have already copied
833    {
834        auto to = create_data_app_package_path(to_uuid, data_app_name);
835        if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
836            LOG(WARNING) << "Failed to rollback " << to;
837        }
838    }
839    for (auto user : users) {
840        {
841            auto to = create_data_user_de_package_path(to_uuid, user, package_name);
842            if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
843                LOG(WARNING) << "Failed to rollback " << to;
844            }
845        }
846        {
847            auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
848            if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
849                LOG(WARNING) << "Failed to rollback " << to;
850            }
851        }
852    }
853    return res;
854}
855
856binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
857        int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
858    ENFORCE_UID(AID_SYSTEM);
859    CHECK_ARGUMENT_UUID(uuid);
860    std::lock_guard<std::recursive_mutex> lock(mLock);
861
862    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
863    if (flags & FLAG_STORAGE_DE) {
864        if (uuid_ == nullptr) {
865            if (ensure_config_user_dirs(userId) != 0) {
866                return error(StringPrintf("Failed to ensure dirs for %d", userId));
867            }
868        }
869    }
870
871    // Data under /data/media doesn't have an app, but we still want
872    // to limit it to prevent abuse.
873    if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid),
874            multiuser_get_uid(userId, AID_MEDIA_RW))) {
875        return error("Failed to set hard quota for media_rw");
876    }
877
878    return ok();
879}
880
881binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
882        int32_t userId, int32_t flags) {
883    ENFORCE_UID(AID_SYSTEM);
884    CHECK_ARGUMENT_UUID(uuid);
885    std::lock_guard<std::recursive_mutex> lock(mLock);
886
887    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
888    binder::Status res = ok();
889    if (flags & FLAG_STORAGE_DE) {
890        auto path = create_data_user_de_path(uuid_, userId);
891        if (delete_dir_contents_and_dir(path, true) != 0) {
892            res = error("Failed to delete " + path);
893        }
894        if (uuid_ == nullptr) {
895            path = create_data_misc_legacy_path(userId);
896            if (delete_dir_contents_and_dir(path, true) != 0) {
897                res = error("Failed to delete " + path);
898            }
899            path = create_primary_cur_profile_dir_path(userId);
900            if (delete_dir_contents_and_dir(path, true) != 0) {
901                res = error("Failed to delete " + path);
902            }
903        }
904    }
905    if (flags & FLAG_STORAGE_CE) {
906        auto path = create_data_user_ce_path(uuid_, userId);
907        if (delete_dir_contents_and_dir(path, true) != 0) {
908            res = error("Failed to delete " + path);
909        }
910        path = findDataMediaPath(uuid, userId);
911        if (delete_dir_contents_and_dir(path, true) != 0) {
912            res = error("Failed to delete " + path);
913        }
914    }
915    return res;
916}
917
918binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
919        int64_t targetFreeBytes, int64_t cacheReservedBytes, int32_t flags) {
920    ENFORCE_UID(AID_SYSTEM);
921    CHECK_ARGUMENT_UUID(uuid);
922    std::lock_guard<std::recursive_mutex> lock(mLock);
923
924    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
925    auto data_path = create_data_path(uuid_);
926    auto device = findQuotaDeviceForUuid(uuid);
927    auto noop = (flags & FLAG_FREE_CACHE_NOOP);
928
929    int64_t free = data_disk_free(data_path);
930    if (free < 0) {
931        return error("Failed to determine free space for " + data_path);
932    }
933
934    int64_t cleared = 0;
935    int64_t needed = targetFreeBytes - free;
936    LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
937            << targetFreeBytes << "; needed " << needed;
938
939    if (free >= targetFreeBytes) {
940        return ok();
941    }
942
943    if (flags & FLAG_FREE_CACHE_V2) {
944        // This new cache strategy fairly removes files from UIDs by deleting
945        // files from the UIDs which are most over their allocated quota
946
947        // 1. Create trackers for every known UID
948        ATRACE_BEGIN("create");
949        std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
950        for (auto user : get_known_users(uuid_)) {
951            FTS *fts;
952            FTSENT *p;
953            auto ce_path = create_data_user_ce_path(uuid_, user);
954            auto de_path = create_data_user_de_path(uuid_, user);
955            auto media_path = findDataMediaPath(uuid, user) + "/Android/data/";
956            char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(),
957                    (char*) media_path.c_str(), nullptr };
958            if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
959                return error("Failed to fts_open");
960            }
961            while ((p = fts_read(fts)) != NULL) {
962                if (p->fts_info == FTS_D && p->fts_level == 1) {
963                    uid_t uid = p->fts_statp->st_uid;
964                    if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
965                        uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
966                                + AID_APP_START;
967                    }
968                    auto search = trackers.find(uid);
969                    if (search != trackers.end()) {
970                        search->second->addDataPath(p->fts_path);
971                    } else {
972                        auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
973                                multiuser_get_user_id(uid), multiuser_get_app_id(uid), device));
974                        tracker->addDataPath(p->fts_path);
975                        {
976                            std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
977                            tracker->cacheQuota = mCacheQuotas[uid];
978                        }
979                        if (tracker->cacheQuota == 0) {
980#if MEASURE_DEBUG
981                            LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
982#endif
983                            tracker->cacheQuota = 67108864;
984                        }
985                        trackers[uid] = tracker;
986                    }
987                    fts_set(fts, p, FTS_SKIP);
988                }
989            }
990            fts_close(fts);
991        }
992        ATRACE_END();
993
994        // 2. Populate tracker stats and insert into priority queue
995        ATRACE_BEGIN("populate");
996        int64_t cacheTotal = 0;
997        auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
998            return (left->getCacheRatio() < right->getCacheRatio());
999        };
1000        std::priority_queue<std::shared_ptr<CacheTracker>,
1001                std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
1002        for (const auto& it : trackers) {
1003            it.second->loadStats();
1004            queue.push(it.second);
1005            cacheTotal += it.second->cacheUsed;
1006        }
1007        ATRACE_END();
1008
1009        // 3. Bounce across the queue, freeing items from whichever tracker is
1010        // the most over their assigned quota
1011        ATRACE_BEGIN("bounce");
1012        std::shared_ptr<CacheTracker> active;
1013        while (active || !queue.empty()) {
1014            // Only look at apps under quota when explicitly requested
1015            if (active && (active->getCacheRatio() < 10000)
1016                    && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
1017                LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
1018                        << " isn't over quota, and defy not requested";
1019                break;
1020            }
1021
1022            // Only keep clearing when we haven't pushed into reserved area
1023            if (cacheReservedBytes > 0 && cleared >= (cacheTotal - cacheReservedBytes)) {
1024                LOG(DEBUG) << "Refusing to clear cached data in reserved space";
1025                break;
1026            }
1027
1028            // Find the best tracker to work with; this might involve swapping
1029            // if the active tracker is no longer the most over quota
1030            bool nextBetter = active && !queue.empty()
1031                    && active->getCacheRatio() < queue.top()->getCacheRatio();
1032            if (!active || nextBetter) {
1033                if (active) {
1034                    // Current tracker still has items, so we'll consider it
1035                    // again later once it bubbles up to surface
1036                    queue.push(active);
1037                }
1038                active = queue.top(); queue.pop();
1039                active->ensureItems();
1040                continue;
1041            }
1042
1043            // If no items remain, go find another tracker
1044            if (active->items.empty()) {
1045                active = nullptr;
1046                continue;
1047            } else {
1048                auto item = active->items.back();
1049                active->items.pop_back();
1050
1051                LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
1052                if (!noop) {
1053                    item->purge();
1054                }
1055                active->cacheUsed -= item->size;
1056                needed -= item->size;
1057                cleared += item->size;
1058            }
1059
1060            // Verify that we're actually done before bailing, since sneaky
1061            // apps might be using hardlinks
1062            if (needed <= 0) {
1063                free = data_disk_free(data_path);
1064                needed = targetFreeBytes - free;
1065                if (needed <= 0) {
1066                    break;
1067                } else {
1068                    LOG(WARNING) << "Expected to be done but still need " << needed;
1069                }
1070            }
1071        }
1072        ATRACE_END();
1073
1074    } else {
1075        return error("Legacy cache logic no longer supported");
1076    }
1077
1078    free = data_disk_free(data_path);
1079    if (free >= targetFreeBytes) {
1080        return ok();
1081    } else {
1082        return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
1083                targetFreeBytes, data_path.c_str(), free));
1084    }
1085}
1086
1087binder::Status InstalldNativeService::rmdex(const std::string& codePath,
1088        const std::string& instructionSet) {
1089    ENFORCE_UID(AID_SYSTEM);
1090    std::lock_guard<std::recursive_mutex> lock(mLock);
1091
1092    char dex_path[PKG_PATH_MAX];
1093
1094    const char* path = codePath.c_str();
1095    const char* instruction_set = instructionSet.c_str();
1096
1097    if (validate_apk_path(path) && validate_system_app_path(path)) {
1098        return error("Invalid path " + codePath);
1099    }
1100
1101    if (!create_cache_path(dex_path, path, instruction_set)) {
1102        return error("Failed to create cache path for " + codePath);
1103    }
1104
1105    ALOGV("unlink %s\n", dex_path);
1106    if (unlink(dex_path) < 0) {
1107        // It's ok if we don't have a dalvik cache path. Report error only when the path exists
1108        // but could not be unlinked.
1109        if (errno != ENOENT) {
1110            return error(StringPrintf("Failed to unlink %s", dex_path));
1111        }
1112    }
1113    return ok();
1114}
1115
1116struct stats {
1117    int64_t codeSize;
1118    int64_t dataSize;
1119    int64_t cacheSize;
1120};
1121
1122#if MEASURE_DEBUG
1123static std::string toString(std::vector<int64_t> values) {
1124    std::stringstream res;
1125    res << "[";
1126    for (size_t i = 0; i < values.size(); i++) {
1127        res << values[i];
1128        if (i < values.size() - 1) {
1129            res << ",";
1130        }
1131    }
1132    res << "]";
1133    return res.str();
1134}
1135#endif
1136
1137static void collectQuotaStats(const std::string& device, int32_t userId,
1138        int32_t appId, struct stats* stats, struct stats* extStats) {
1139    if (device.empty()) return;
1140
1141    struct dqblk dq;
1142
1143    if (stats != nullptr) {
1144        uid_t uid = multiuser_get_uid(userId, appId);
1145        if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1146                reinterpret_cast<char*>(&dq)) != 0) {
1147            if (errno != ESRCH) {
1148                PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1149            }
1150        } else {
1151#if MEASURE_DEBUG
1152            LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1153#endif
1154            stats->dataSize += dq.dqb_curspace;
1155        }
1156
1157        int cacheGid = multiuser_get_cache_gid(userId, appId);
1158        if (cacheGid != -1) {
1159            if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
1160                    reinterpret_cast<char*>(&dq)) != 0) {
1161                if (errno != ESRCH) {
1162                    PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
1163                }
1164            } else {
1165#if MEASURE_DEBUG
1166                LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
1167#endif
1168                stats->cacheSize += dq.dqb_curspace;
1169            }
1170        }
1171
1172        int sharedGid = multiuser_get_shared_gid(0, appId);
1173        if (sharedGid != -1) {
1174            if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
1175                    reinterpret_cast<char*>(&dq)) != 0) {
1176                if (errno != ESRCH) {
1177                    PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
1178                }
1179            } else {
1180#if MEASURE_DEBUG
1181                LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
1182#endif
1183                stats->codeSize += dq.dqb_curspace;
1184            }
1185        }
1186    }
1187
1188    if (extStats != nullptr) {
1189        int extGid = multiuser_get_ext_gid(userId, appId);
1190        if (extGid != -1) {
1191            if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extGid,
1192                    reinterpret_cast<char*>(&dq)) != 0) {
1193                if (errno != ESRCH) {
1194                    PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extGid;
1195                }
1196            } else {
1197#if MEASURE_DEBUG
1198                LOG(DEBUG) << "quotactl() for GID " << extGid << " " << dq.dqb_curspace;
1199#endif
1200                extStats->dataSize += dq.dqb_curspace;
1201            }
1202        }
1203
1204        int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1205        if (extCacheGid != -1) {
1206            if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extCacheGid,
1207                    reinterpret_cast<char*>(&dq)) != 0) {
1208                if (errno != ESRCH) {
1209                    PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extCacheGid;
1210                }
1211            } else {
1212#if MEASURE_DEBUG
1213                LOG(DEBUG) << "quotactl() for GID " << extCacheGid << " " << dq.dqb_curspace;
1214#endif
1215                extStats->dataSize += dq.dqb_curspace;
1216                extStats->cacheSize += dq.dqb_curspace;
1217            }
1218        }
1219    }
1220}
1221
1222static void collectManualStats(const std::string& path, struct stats* stats) {
1223    DIR *d;
1224    int dfd;
1225    struct dirent *de;
1226    struct stat s;
1227
1228    d = opendir(path.c_str());
1229    if (d == nullptr) {
1230        if (errno != ENOENT) {
1231            PLOG(WARNING) << "Failed to open " << path;
1232        }
1233        return;
1234    }
1235    dfd = dirfd(d);
1236    while ((de = readdir(d))) {
1237        const char *name = de->d_name;
1238
1239        int64_t size = 0;
1240        if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
1241            size = s.st_blocks * 512;
1242        }
1243
1244        if (de->d_type == DT_DIR) {
1245            if (!strcmp(name, ".")) {
1246                // Don't recurse, but still count node size
1247            } else if (!strcmp(name, "..")) {
1248                // Don't recurse or count node size
1249                continue;
1250            } else {
1251                // Measure all children nodes
1252                size = 0;
1253                calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
1254            }
1255
1256            if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1257                stats->cacheSize += size;
1258            }
1259        }
1260
1261        // Legacy symlink isn't owned by app
1262        if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1263            continue;
1264        }
1265
1266        // Everything found inside is considered data
1267        stats->dataSize += size;
1268    }
1269    closedir(d);
1270}
1271
1272static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1273        bool exclude_apps = false) {
1274    DIR *d;
1275    int dfd;
1276    struct dirent *de;
1277    struct stat s;
1278
1279    d = opendir(path.c_str());
1280    if (d == nullptr) {
1281        if (errno != ENOENT) {
1282            PLOG(WARNING) << "Failed to open " << path;
1283        }
1284        return;
1285    }
1286    dfd = dirfd(d);
1287    while ((de = readdir(d))) {
1288        if (de->d_type == DT_DIR) {
1289            const char *name = de->d_name;
1290            if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1291                continue;
1292            }
1293            int32_t user_uid = multiuser_get_app_id(s.st_uid);
1294            if (!strcmp(name, ".") || !strcmp(name, "..")) {
1295                continue;
1296            } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
1297                continue;
1298            } else {
1299                collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1300            }
1301        }
1302    }
1303    closedir(d);
1304}
1305
1306static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1307    FTS *fts;
1308    FTSENT *p;
1309    char *argv[] = { (char*) path.c_str(), nullptr };
1310    if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
1311        PLOG(ERROR) << "Failed to fts_open " << path;
1312        return;
1313    }
1314    while ((p = fts_read(fts)) != NULL) {
1315        p->fts_number = p->fts_parent->fts_number;
1316        switch (p->fts_info) {
1317        case FTS_D:
1318            if (p->fts_level == 4
1319                    && !strcmp(p->fts_name, "cache")
1320                    && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1321                    && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1322                p->fts_number = 1;
1323            }
1324            // Fall through to count the directory
1325        case FTS_DEFAULT:
1326        case FTS_F:
1327        case FTS_SL:
1328        case FTS_SLNONE:
1329            int64_t size = (p->fts_statp->st_blocks * 512);
1330            if (p->fts_number == 1) {
1331                stats->cacheSize += size;
1332            }
1333            stats->dataSize += size;
1334            break;
1335        }
1336    }
1337    fts_close(fts);
1338}
1339
1340binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
1341        const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1342        int32_t appId, const std::vector<int64_t>& ceDataInodes,
1343        const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
1344    ENFORCE_UID(AID_SYSTEM);
1345    CHECK_ARGUMENT_UUID(uuid);
1346    for (auto packageName : packageNames) {
1347        CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1348    }
1349    // NOTE: Locking is relaxed on this method, since it's limited to
1350    // read-only measurements without mutation.
1351
1352    // When modifying this logic, always verify using tests:
1353    // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1354
1355#if MEASURE_DEBUG
1356    LOG(INFO) << "Measuring user " << userId << " app " << appId;
1357#endif
1358
1359    // Here's a summary of the common storage locations across the platform,
1360    // and how they're each tagged:
1361    //
1362    // /data/app/com.example                           UID system
1363    // /data/app/com.example/oat                       UID system
1364    // /data/user/0/com.example                        UID u0_a10      GID u0_a10
1365    // /data/user/0/com.example/cache                  UID u0_a10      GID u0_a10_cache
1366    // /data/media/0/foo.txt                           UID u0_media_rw
1367    // /data/media/0/bar.jpg                           UID u0_media_rw GID u0_media_image
1368    // /data/media/0/Android/data/com.example          UID u0_media_rw GID u0_a10_ext
1369    // /data/media/0/Android/data/com.example/cache    UID u0_media_rw GID u0_a10_ext_cache
1370    // /data/media/obb/com.example                     UID system
1371
1372    struct stats stats;
1373    struct stats extStats;
1374    memset(&stats, 0, sizeof(stats));
1375    memset(&extStats, 0, sizeof(extStats));
1376
1377    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1378
1379    auto device = findQuotaDeviceForUuid(uuid);
1380    if (device.empty()) {
1381        flags &= ~FLAG_USE_QUOTA;
1382    }
1383
1384    ATRACE_BEGIN("obb");
1385    for (auto packageName : packageNames) {
1386        auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1387        calculate_tree_size(obbCodePath, &extStats.codeSize);
1388    }
1389    ATRACE_END();
1390
1391    if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
1392        ATRACE_BEGIN("code");
1393        for (auto codePath : codePaths) {
1394            calculate_tree_size(codePath, &stats.codeSize, -1,
1395                    multiuser_get_shared_gid(0, appId));
1396        }
1397        ATRACE_END();
1398
1399        ATRACE_BEGIN("quota");
1400        collectQuotaStats(device, userId, appId, &stats, &extStats);
1401        ATRACE_END();
1402    } else {
1403        ATRACE_BEGIN("code");
1404        for (auto codePath : codePaths) {
1405            calculate_tree_size(codePath, &stats.codeSize);
1406        }
1407        ATRACE_END();
1408
1409        for (size_t i = 0; i < packageNames.size(); i++) {
1410            const char* pkgname = packageNames[i].c_str();
1411
1412            ATRACE_BEGIN("data");
1413            auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1414            collectManualStats(cePath, &stats);
1415            auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1416            collectManualStats(dePath, &stats);
1417            ATRACE_END();
1418
1419            if (!uuid) {
1420                ATRACE_BEGIN("profiles");
1421                calculate_tree_size(
1422                        create_primary_current_profile_package_dir_path(userId, pkgname),
1423                        &stats.dataSize);
1424                calculate_tree_size(
1425                        create_primary_reference_profile_package_dir_path(pkgname),
1426                        &stats.codeSize);
1427                ATRACE_END();
1428            }
1429
1430            ATRACE_BEGIN("external");
1431            auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
1432            collectManualStats(extPath, &extStats);
1433            auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
1434            calculate_tree_size(mediaPath, &extStats.dataSize);
1435            ATRACE_END();
1436        }
1437
1438        if (!uuid) {
1439            ATRACE_BEGIN("dalvik");
1440            int32_t sharedGid = multiuser_get_shared_gid(0, appId);
1441            if (sharedGid != -1) {
1442                calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1443                        sharedGid, -1);
1444            }
1445            ATRACE_END();
1446        }
1447    }
1448
1449    std::vector<int64_t> ret;
1450    ret.push_back(stats.codeSize);
1451    ret.push_back(stats.dataSize);
1452    ret.push_back(stats.cacheSize);
1453    ret.push_back(extStats.codeSize);
1454    ret.push_back(extStats.dataSize);
1455    ret.push_back(extStats.cacheSize);
1456#if MEASURE_DEBUG
1457    LOG(DEBUG) << "Final result " << toString(ret);
1458#endif
1459    *_aidl_return = ret;
1460    return ok();
1461}
1462
1463binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1464        int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1465        std::vector<int64_t>* _aidl_return) {
1466    ENFORCE_UID(AID_SYSTEM);
1467    CHECK_ARGUMENT_UUID(uuid);
1468    // NOTE: Locking is relaxed on this method, since it's limited to
1469    // read-only measurements without mutation.
1470
1471    // When modifying this logic, always verify using tests:
1472    // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1473
1474#if MEASURE_DEBUG
1475    LOG(INFO) << "Measuring user " << userId;
1476#endif
1477
1478    struct stats stats;
1479    struct stats extStats;
1480    memset(&stats, 0, sizeof(stats));
1481    memset(&extStats, 0, sizeof(extStats));
1482
1483    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1484
1485    auto device = findQuotaDeviceForUuid(uuid);
1486    if (device.empty()) {
1487        flags &= ~FLAG_USE_QUOTA;
1488    }
1489
1490    if (flags & FLAG_USE_QUOTA) {
1491        struct dqblk dq;
1492
1493        ATRACE_BEGIN("obb");
1494        if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1495                reinterpret_cast<char*>(&dq)) != 0) {
1496            if (errno != ESRCH) {
1497                PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << AID_MEDIA_OBB;
1498            }
1499        } else {
1500#if MEASURE_DEBUG
1501            LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1502#endif
1503            extStats.codeSize += dq.dqb_curspace;
1504        }
1505        ATRACE_END();
1506
1507        ATRACE_BEGIN("code");
1508        calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
1509        ATRACE_END();
1510
1511        ATRACE_BEGIN("data");
1512        auto cePath = create_data_user_ce_path(uuid_, userId);
1513        collectManualStatsForUser(cePath, &stats, true);
1514        auto dePath = create_data_user_de_path(uuid_, userId);
1515        collectManualStatsForUser(dePath, &stats, true);
1516        ATRACE_END();
1517
1518        if (!uuid) {
1519            ATRACE_BEGIN("profile");
1520            auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1521            calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1522            auto refProfilePath = create_primary_ref_profile_dir_path();
1523            calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1524            ATRACE_END();
1525        }
1526
1527        ATRACE_BEGIN("external");
1528        uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1529        if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1530                reinterpret_cast<char*>(&dq)) != 0) {
1531            if (errno != ESRCH) {
1532                PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1533            }
1534        } else {
1535#if MEASURE_DEBUG
1536            LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1537#endif
1538            extStats.dataSize += dq.dqb_curspace;
1539        }
1540        ATRACE_END();
1541
1542        if (!uuid) {
1543            ATRACE_BEGIN("dalvik");
1544            calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1545                    -1, -1, true);
1546            calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1547                    -1, -1, true);
1548            ATRACE_END();
1549        }
1550
1551        ATRACE_BEGIN("quota");
1552        int64_t dataSize = extStats.dataSize;
1553        for (auto appId : appIds) {
1554            if (appId >= AID_APP_START) {
1555                collectQuotaStats(device, userId, appId, &stats, &extStats);
1556
1557#if MEASURE_DEBUG
1558                // Sleep to make sure we don't lose logs
1559                usleep(1);
1560#endif
1561            }
1562        }
1563        extStats.dataSize = dataSize;
1564        ATRACE_END();
1565    } else {
1566        ATRACE_BEGIN("obb");
1567        auto obbPath = create_data_path(uuid_) + "/media/obb";
1568        calculate_tree_size(obbPath, &extStats.codeSize);
1569        ATRACE_END();
1570
1571        ATRACE_BEGIN("code");
1572        calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
1573        ATRACE_END();
1574
1575        ATRACE_BEGIN("data");
1576        auto cePath = create_data_user_ce_path(uuid_, userId);
1577        collectManualStatsForUser(cePath, &stats);
1578        auto dePath = create_data_user_de_path(uuid_, userId);
1579        collectManualStatsForUser(dePath, &stats);
1580        ATRACE_END();
1581
1582        if (!uuid) {
1583            ATRACE_BEGIN("profile");
1584            auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1585            calculate_tree_size(userProfilePath, &stats.dataSize);
1586            auto refProfilePath = create_primary_ref_profile_dir_path();
1587            calculate_tree_size(refProfilePath, &stats.codeSize);
1588            ATRACE_END();
1589        }
1590
1591        ATRACE_BEGIN("external");
1592        auto dataMediaPath = create_data_media_path(uuid_, userId);
1593        collectManualExternalStatsForUser(dataMediaPath, &extStats);
1594#if MEASURE_DEBUG
1595        LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1596                << extStats.cacheSize;
1597#endif
1598        ATRACE_END();
1599
1600        if (!uuid) {
1601            ATRACE_BEGIN("dalvik");
1602            calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1603            calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
1604            ATRACE_END();
1605        }
1606    }
1607
1608    std::vector<int64_t> ret;
1609    ret.push_back(stats.codeSize);
1610    ret.push_back(stats.dataSize);
1611    ret.push_back(stats.cacheSize);
1612    ret.push_back(extStats.codeSize);
1613    ret.push_back(extStats.dataSize);
1614    ret.push_back(extStats.cacheSize);
1615#if MEASURE_DEBUG
1616    LOG(DEBUG) << "Final result " << toString(ret);
1617#endif
1618    *_aidl_return = ret;
1619    return ok();
1620}
1621
1622binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
1623        int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1624        std::vector<int64_t>* _aidl_return) {
1625    ENFORCE_UID(AID_SYSTEM);
1626    CHECK_ARGUMENT_UUID(uuid);
1627    // NOTE: Locking is relaxed on this method, since it's limited to
1628    // read-only measurements without mutation.
1629
1630    // When modifying this logic, always verify using tests:
1631    // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1632
1633#if MEASURE_DEBUG
1634    LOG(INFO) << "Measuring external " << userId;
1635#endif
1636
1637    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1638
1639    int64_t totalSize = 0;
1640    int64_t audioSize = 0;
1641    int64_t videoSize = 0;
1642    int64_t imageSize = 0;
1643    int64_t appSize = 0;
1644
1645    auto device = findQuotaDeviceForUuid(uuid);
1646    if (device.empty()) {
1647        flags &= ~FLAG_USE_QUOTA;
1648    }
1649
1650    if (flags & FLAG_USE_QUOTA) {
1651        struct dqblk dq;
1652
1653        ATRACE_BEGIN("quota");
1654        uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1655        if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1656                reinterpret_cast<char*>(&dq)) != 0) {
1657            if (errno != ESRCH) {
1658                PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1659            }
1660        } else {
1661#if MEASURE_DEBUG
1662            LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1663#endif
1664            totalSize = dq.dqb_curspace;
1665        }
1666
1667        gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1668        if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1669                reinterpret_cast<char*>(&dq)) == 0) {
1670#if MEASURE_DEBUG
1671            LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
1672#endif
1673            audioSize = dq.dqb_curspace;
1674        }
1675        gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1676        if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1677                reinterpret_cast<char*>(&dq)) == 0) {
1678#if MEASURE_DEBUG
1679            LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
1680#endif
1681            videoSize = dq.dqb_curspace;
1682        }
1683        gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1684        if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1685                reinterpret_cast<char*>(&dq)) == 0) {
1686#if MEASURE_DEBUG
1687            LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
1688#endif
1689            imageSize = dq.dqb_curspace;
1690        }
1691        ATRACE_END();
1692
1693        ATRACE_BEGIN("apps");
1694        struct stats extStats;
1695        memset(&extStats, 0, sizeof(extStats));
1696        for (auto appId : appIds) {
1697            if (appId >= AID_APP_START) {
1698                collectQuotaStats(device, userId, appId, nullptr, &extStats);
1699            }
1700        }
1701        appSize = extStats.dataSize;
1702        ATRACE_END();
1703    } else {
1704        ATRACE_BEGIN("manual");
1705        FTS *fts;
1706        FTSENT *p;
1707        auto path = create_data_media_path(uuid_, userId);
1708        char *argv[] = { (char*) path.c_str(), nullptr };
1709        if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
1710            return error("Failed to fts_open " + path);
1711        }
1712        while ((p = fts_read(fts)) != NULL) {
1713            char* ext;
1714            int64_t size = (p->fts_statp->st_blocks * 512);
1715            switch (p->fts_info) {
1716            case FTS_F:
1717                // Only categorize files not belonging to apps
1718                if (p->fts_parent->fts_number == 0) {
1719                    ext = strrchr(p->fts_name, '.');
1720                    if (ext != nullptr) {
1721                        switch (MatchExtension(++ext)) {
1722                        case AID_MEDIA_AUDIO: audioSize += size; break;
1723                        case AID_MEDIA_VIDEO: videoSize += size; break;
1724                        case AID_MEDIA_IMAGE: imageSize += size; break;
1725                        }
1726                    }
1727                }
1728                // Fall through to always count against total
1729            case FTS_D:
1730                // Ignore data belonging to specific apps
1731                p->fts_number = p->fts_parent->fts_number;
1732                if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
1733                    p->fts_number = 1;
1734                }
1735            case FTS_DEFAULT:
1736            case FTS_SL:
1737            case FTS_SLNONE:
1738                if (p->fts_parent->fts_number == 1) {
1739                    appSize += size;
1740                }
1741                totalSize += size;
1742                break;
1743            }
1744        }
1745        fts_close(fts);
1746        ATRACE_END();
1747    }
1748
1749    std::vector<int64_t> ret;
1750    ret.push_back(totalSize);
1751    ret.push_back(audioSize);
1752    ret.push_back(videoSize);
1753    ret.push_back(imageSize);
1754    ret.push_back(appSize);
1755#if MEASURE_DEBUG
1756    LOG(DEBUG) << "Final result " << toString(ret);
1757#endif
1758    *_aidl_return = ret;
1759    return ok();
1760}
1761
1762binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
1763        int32_t userId, int32_t appId, int64_t cacheQuota) {
1764    ENFORCE_UID(AID_SYSTEM);
1765    CHECK_ARGUMENT_UUID(uuid);
1766    std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
1767
1768    int32_t uid = multiuser_get_uid(userId, appId);
1769    mCacheQuotas[uid] = cacheQuota;
1770
1771    return ok();
1772}
1773
1774// Dumps the contents of a profile file, using pkgname's dex files for pretty
1775// printing the result.
1776binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1777        const std::string& codePaths, bool* _aidl_return) {
1778    ENFORCE_UID(AID_SYSTEM);
1779    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1780    std::lock_guard<std::recursive_mutex> lock(mLock);
1781
1782    const char* pkgname = packageName.c_str();
1783    const char* code_paths = codePaths.c_str();
1784
1785    *_aidl_return = dump_profiles(uid, pkgname, code_paths);
1786    return ok();
1787}
1788
1789// TODO: Consider returning error codes.
1790binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
1791        bool* _aidl_return) {
1792    ENFORCE_UID(AID_SYSTEM);
1793    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1794    std::lock_guard<std::recursive_mutex> lock(mLock);
1795
1796    *_aidl_return = analyze_primary_profiles(uid, packageName);
1797    return ok();
1798}
1799
1800binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1801        const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1802        int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1803        const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
1804        const std::unique_ptr<std::string>& sharedLibraries,
1805        const std::unique_ptr<std::string>& seInfo) {
1806    ENFORCE_UID(AID_SYSTEM);
1807    CHECK_ARGUMENT_UUID(uuid);
1808    if (packageName && *packageName != "*") {
1809        CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1810    }
1811    std::lock_guard<std::recursive_mutex> lock(mLock);
1812
1813    const char* apk_path = apkPath.c_str();
1814    const char* pkgname = packageName ? packageName->c_str() : "*";
1815    const char* instruction_set = instructionSet.c_str();
1816    const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1817    const char* compiler_filter = compilerFilter.c_str();
1818    const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
1819    const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
1820    const char* se_info = seInfo ? seInfo->c_str() : nullptr;
1821    int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
1822            oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries, se_info);
1823    return res ? error(res, "Failed to dexopt") : ok();
1824}
1825
1826binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1827    ENFORCE_UID(AID_SYSTEM);
1828    std::lock_guard<std::recursive_mutex> lock(mLock);
1829
1830    const char* instruction_set = instructionSet.c_str();
1831
1832    char boot_marker_path[PKG_PATH_MAX];
1833    sprintf(boot_marker_path,
1834          "%s/%s/%s/.booting",
1835          android_data_dir.path,
1836          DALVIK_CACHE,
1837          instruction_set);
1838
1839    ALOGV("mark_boot_complete : %s", boot_marker_path);
1840    if (unlink(boot_marker_path) != 0) {
1841        return error(StringPrintf("Failed to unlink %s", boot_marker_path));
1842    }
1843    return ok();
1844}
1845
1846void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1847        struct stat* statbuf)
1848{
1849    while (path[basepos] != 0) {
1850        if (path[basepos] == '/') {
1851            path[basepos] = 0;
1852            if (lstat(path, statbuf) < 0) {
1853                ALOGV("Making directory: %s\n", path);
1854                if (mkdir(path, mode) == 0) {
1855                    chown(path, uid, gid);
1856                } else {
1857                    ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1858                }
1859            }
1860            path[basepos] = '/';
1861            basepos++;
1862        }
1863        basepos++;
1864    }
1865}
1866
1867binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1868        const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1869        const std::string& nativeLibPath32, int32_t userId) {
1870    ENFORCE_UID(AID_SYSTEM);
1871    CHECK_ARGUMENT_UUID(uuid);
1872    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1873    std::lock_guard<std::recursive_mutex> lock(mLock);
1874
1875    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1876    const char* pkgname = packageName.c_str();
1877    const char* asecLibDir = nativeLibPath32.c_str();
1878    struct stat s, libStat;
1879    binder::Status res = ok();
1880
1881    auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1882    auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
1883
1884    const char* pkgdir = _pkgdir.c_str();
1885    const char* libsymlink = _libsymlink.c_str();
1886
1887    if (stat(pkgdir, &s) < 0) {
1888        return error("Failed to stat " + _pkgdir);
1889    }
1890
1891    if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
1892        return error("Failed to chown " + _pkgdir);
1893    }
1894
1895    if (chmod(pkgdir, 0700) < 0) {
1896        res = error("Failed to chmod " + _pkgdir);
1897        goto out;
1898    }
1899
1900    if (lstat(libsymlink, &libStat) < 0) {
1901        if (errno != ENOENT) {
1902            res = error("Failed to stat " + _libsymlink);
1903            goto out;
1904        }
1905    } else {
1906        if (S_ISDIR(libStat.st_mode)) {
1907            if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
1908                res = error("Failed to delete " + _libsymlink);
1909                goto out;
1910            }
1911        } else if (S_ISLNK(libStat.st_mode)) {
1912            if (unlink(libsymlink) < 0) {
1913                res = error("Failed to unlink " + _libsymlink);
1914                goto out;
1915            }
1916        }
1917    }
1918
1919    if (symlink(asecLibDir, libsymlink) < 0) {
1920        res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
1921        goto out;
1922    }
1923
1924out:
1925    if (chmod(pkgdir, s.st_mode) < 0) {
1926        auto msg = "Failed to cleanup chmod " + _pkgdir;
1927        if (res.isOk()) {
1928            res = error(msg);
1929        } else {
1930            PLOG(ERROR) << msg;
1931        }
1932    }
1933
1934    if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
1935        auto msg = "Failed to cleanup chown " + _pkgdir;
1936        if (res.isOk()) {
1937            res = error(msg);
1938        } else {
1939            PLOG(ERROR) << msg;
1940        }
1941    }
1942
1943    return res;
1944}
1945
1946static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1947{
1948    execl(kIdMapPath, kIdMapPath, "--fd", target_apk, overlay_apk,
1949            StringPrintf("%d", idmap_fd).c_str(), (char*)NULL);
1950    PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
1951}
1952
1953static void run_verify_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1954{
1955    execl(kIdMapPath, kIdMapPath, "--verify", target_apk, overlay_apk,
1956            StringPrintf("%d", idmap_fd).c_str(), (char*)NULL);
1957    PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
1958}
1959
1960static bool delete_stale_idmap(const char* target_apk, const char* overlay_apk,
1961        const char* idmap_path, int32_t uid) {
1962    int idmap_fd = open(idmap_path, O_RDWR);
1963    if (idmap_fd < 0) {
1964        PLOG(ERROR) << "idmap open failed: " << idmap_path;
1965        unlink(idmap_path);
1966        return true;
1967    }
1968
1969    pid_t pid;
1970    pid = fork();
1971    if (pid == 0) {
1972        /* child -- drop privileges before continuing */
1973        if (setgid(uid) != 0) {
1974            LOG(ERROR) << "setgid(" << uid << ") failed during idmap";
1975            exit(1);
1976        }
1977        if (setuid(uid) != 0) {
1978            LOG(ERROR) << "setuid(" << uid << ") failed during idmap";
1979            exit(1);
1980        }
1981        if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
1982            PLOG(ERROR) << "flock(" << idmap_path << ") failed during idmap";
1983            exit(1);
1984        }
1985
1986        run_verify_idmap(target_apk, overlay_apk, idmap_fd);
1987        exit(1); /* only if exec call to deleting stale idmap failed */
1988    } else {
1989        int status = wait_child(pid);
1990        close(idmap_fd);
1991
1992        if (status != 0) {
1993            // Failed on verifying if idmap is made from target_apk and overlay_apk.
1994            LOG(DEBUG) << "delete stale idmap: " << idmap_path;
1995            unlink(idmap_path);
1996            return true;
1997        }
1998    }
1999    return false;
2000}
2001
2002// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
2003// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
2004static int flatten_path(const char *prefix, const char *suffix,
2005        const char *overlay_path, char *idmap_path, size_t N)
2006{
2007    if (overlay_path == NULL || idmap_path == NULL) {
2008        return -1;
2009    }
2010    const size_t len_overlay_path = strlen(overlay_path);
2011    // will access overlay_path + 1 further below; requires absolute path
2012    if (len_overlay_path < 2 || *overlay_path != '/') {
2013        return -1;
2014    }
2015    const size_t len_idmap_root = strlen(prefix);
2016    const size_t len_suffix = strlen(suffix);
2017    if (SIZE_MAX - len_idmap_root < len_overlay_path ||
2018            SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
2019        // additions below would cause overflow
2020        return -1;
2021    }
2022    if (N < len_idmap_root + len_overlay_path + len_suffix) {
2023        return -1;
2024    }
2025    memset(idmap_path, 0, N);
2026    snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
2027    char *ch = idmap_path + len_idmap_root;
2028    while (*ch != '\0') {
2029        if (*ch == '/') {
2030            *ch = '@';
2031        }
2032        ++ch;
2033    }
2034    return 0;
2035}
2036
2037binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
2038        const std::string& overlayApkPath, int32_t uid) {
2039    ENFORCE_UID(AID_SYSTEM);
2040    std::lock_guard<std::recursive_mutex> lock(mLock);
2041
2042    const char* target_apk = targetApkPath.c_str();
2043    const char* overlay_apk = overlayApkPath.c_str();
2044    ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
2045
2046    int idmap_fd = -1;
2047    char idmap_path[PATH_MAX];
2048    struct stat idmap_stat;
2049    bool outdated = false;
2050
2051    if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2052                idmap_path, sizeof(idmap_path)) == -1) {
2053        ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2054        goto fail;
2055    }
2056
2057    if (stat(idmap_path, &idmap_stat) < 0) {
2058        outdated = true;
2059    } else {
2060        outdated = delete_stale_idmap(target_apk, overlay_apk, idmap_path, uid);
2061    }
2062
2063    if (outdated) {
2064        idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
2065    } else {
2066        idmap_fd = open(idmap_path, O_RDWR);
2067    }
2068
2069    if (idmap_fd < 0) {
2070        ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
2071        goto fail;
2072    }
2073    if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
2074        ALOGE("idmap cannot chown '%s'\n", idmap_path);
2075        goto fail;
2076    }
2077    if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
2078        ALOGE("idmap cannot chmod '%s'\n", idmap_path);
2079        goto fail;
2080    }
2081
2082    if (!outdated) {
2083        close(idmap_fd);
2084        return ok();
2085    }
2086
2087    pid_t pid;
2088    pid = fork();
2089    if (pid == 0) {
2090        /* child -- drop privileges before continuing */
2091        if (setgid(uid) != 0) {
2092            ALOGE("setgid(%d) failed during idmap\n", uid);
2093            exit(1);
2094        }
2095        if (setuid(uid) != 0) {
2096            ALOGE("setuid(%d) failed during idmap\n", uid);
2097            exit(1);
2098        }
2099        if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2100            ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
2101            exit(1);
2102        }
2103
2104        run_idmap(target_apk, overlay_apk, idmap_fd);
2105        exit(1); /* only if exec call to idmap failed */
2106    } else {
2107        int status = wait_child(pid);
2108        if (status != 0) {
2109            ALOGE("idmap failed, status=0x%04x\n", status);
2110            goto fail;
2111        }
2112    }
2113
2114    close(idmap_fd);
2115    return ok();
2116fail:
2117    if (idmap_fd >= 0) {
2118        close(idmap_fd);
2119        unlink(idmap_path);
2120    }
2121    return error();
2122}
2123
2124binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
2125    const char* overlay_apk = overlayApkPath.c_str();
2126    char idmap_path[PATH_MAX];
2127
2128    if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2129                idmap_path, sizeof(idmap_path)) == -1) {
2130        ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2131        return error();
2132    }
2133    if (unlink(idmap_path) < 0) {
2134        ALOGE("couldn't unlink idmap file %s\n", idmap_path);
2135        return error();
2136    }
2137    return ok();
2138}
2139
2140binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2141        const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2142        const std::string& seInfo) {
2143    ENFORCE_UID(AID_SYSTEM);
2144    CHECK_ARGUMENT_UUID(uuid);
2145    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2146    std::lock_guard<std::recursive_mutex> lock(mLock);
2147
2148    binder::Status res = ok();
2149
2150    // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
2151    unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
2152    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2153    const char* pkgName = packageName.c_str();
2154    const char* seinfo = seInfo.c_str();
2155
2156    uid_t uid = multiuser_get_uid(userId, appId);
2157    if (flags & FLAG_STORAGE_CE) {
2158        auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
2159        if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
2160            res = error("restorecon failed for " + path);
2161        }
2162    }
2163    if (flags & FLAG_STORAGE_DE) {
2164        auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
2165        if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
2166            res = error("restorecon failed for " + path);
2167        }
2168    }
2169    return res;
2170}
2171
2172binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2173        const std::string& instructionSet) {
2174    ENFORCE_UID(AID_SYSTEM);
2175    std::lock_guard<std::recursive_mutex> lock(mLock);
2176
2177    const char* oat_dir = oatDir.c_str();
2178    const char* instruction_set = instructionSet.c_str();
2179    char oat_instr_dir[PKG_PATH_MAX];
2180
2181    if (validate_apk_path(oat_dir)) {
2182        return error("Invalid path " + oatDir);
2183    }
2184    if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
2185        return error("Failed to prepare " + oatDir);
2186    }
2187    if (selinux_android_restorecon(oat_dir, 0)) {
2188        return error("Failed to restorecon " + oatDir);
2189    }
2190    snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
2191    if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
2192        return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
2193    }
2194    return ok();
2195}
2196
2197binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2198    ENFORCE_UID(AID_SYSTEM);
2199    std::lock_guard<std::recursive_mutex> lock(mLock);
2200
2201    if (validate_apk_path(packageDir.c_str())) {
2202        return error("Invalid path " + packageDir);
2203    }
2204    if (delete_dir_contents_and_dir(packageDir) != 0) {
2205        return error("Failed to delete " + packageDir);
2206    }
2207    return ok();
2208}
2209
2210binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2211        const std::string& fromBase, const std::string& toBase) {
2212    ENFORCE_UID(AID_SYSTEM);
2213    std::lock_guard<std::recursive_mutex> lock(mLock);
2214
2215    const char* relative_path = relativePath.c_str();
2216    const char* from_base = fromBase.c_str();
2217    const char* to_base = toBase.c_str();
2218    char from_path[PKG_PATH_MAX];
2219    char to_path[PKG_PATH_MAX];
2220    snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2221    snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2222
2223    if (validate_apk_path_subdirs(from_path)) {
2224        return error(StringPrintf("Invalid from path %s", from_path));
2225    }
2226
2227    if (validate_apk_path_subdirs(to_path)) {
2228        return error(StringPrintf("Invalid to path %s", to_path));
2229    }
2230
2231    if (link(from_path, to_path) < 0) {
2232        return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
2233    }
2234
2235    return ok();
2236}
2237
2238binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2239        const std::string& instructionSet, const std::string& outputPath) {
2240    ENFORCE_UID(AID_SYSTEM);
2241    std::lock_guard<std::recursive_mutex> lock(mLock);
2242
2243    const char* apk_path = apkPath.c_str();
2244    const char* instruction_set = instructionSet.c_str();
2245    const char* oat_dir = outputPath.c_str();
2246
2247    bool success = move_ab(apk_path, instruction_set, oat_dir);
2248    return success ? ok() : error();
2249}
2250
2251binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
2252        const std::string& instructionSet, const std::unique_ptr<std::string>& outputPath) {
2253    ENFORCE_UID(AID_SYSTEM);
2254    std::lock_guard<std::recursive_mutex> lock(mLock);
2255
2256    const char* apk_path = apkPath.c_str();
2257    const char* instruction_set = instructionSet.c_str();
2258    const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
2259
2260    bool res = delete_odex(apk_path, instruction_set, oat_dir);
2261    return res ? ok() : error();
2262}
2263
2264binder::Status InstalldNativeService::reconcileSecondaryDexFile(
2265        const std::string& dexPath, const std::string& packageName, int32_t uid,
2266        const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
2267        int32_t storage_flag, bool* _aidl_return) {
2268    ENFORCE_UID(AID_SYSTEM);
2269    CHECK_ARGUMENT_UUID(volumeUuid);
2270    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2271
2272    std::lock_guard<std::recursive_mutex> lock(mLock);
2273    bool result = android::installd::reconcile_secondary_dex_file(
2274            dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
2275    return result ? ok() : error();
2276}
2277
2278binder::Status InstalldNativeService::invalidateMounts() {
2279    ENFORCE_UID(AID_SYSTEM);
2280    std::lock_guard<std::recursive_mutex> lock(mMountsLock);
2281
2282    mStorageMounts.clear();
2283    mQuotaReverseMounts.clear();
2284
2285    std::ifstream in("/proc/mounts");
2286    if (!in.is_open()) {
2287        return error("Failed to read mounts");
2288    }
2289
2290    std::string source;
2291    std::string target;
2292    std::string ignored;
2293    while (!in.eof()) {
2294        std::getline(in, source, ' ');
2295        std::getline(in, target, ' ');
2296        std::getline(in, ignored);
2297
2298#if !BYPASS_SDCARDFS
2299        if (target.compare(0, 21, "/mnt/runtime/default/") == 0) {
2300            LOG(DEBUG) << "Found storage mount " << source << " at " << target;
2301            mStorageMounts[source] = target;
2302        }
2303#endif
2304
2305#if !BYPASS_QUOTA
2306        if (source.compare(0, 11, "/dev/block/") == 0) {
2307            struct dqblk dq;
2308            if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), source.c_str(), 0,
2309                    reinterpret_cast<char*>(&dq)) == 0) {
2310                LOG(DEBUG) << "Found quota mount " << source << " at " << target;
2311                mQuotaReverseMounts[target] = source;
2312
2313                // ext4 only enables DQUOT_USAGE_ENABLED by default, so we
2314                // need to kick it again to enable DQUOT_LIMITS_ENABLED.
2315                if (quotactl(QCMD(Q_QUOTAON, USRQUOTA), source.c_str(), QFMT_VFS_V1, nullptr) != 0
2316                        && errno != EBUSY) {
2317                    PLOG(ERROR) << "Failed to enable USRQUOTA on " << source;
2318                }
2319                if (quotactl(QCMD(Q_QUOTAON, GRPQUOTA), source.c_str(), QFMT_VFS_V1, nullptr) != 0
2320                        && errno != EBUSY) {
2321                    PLOG(ERROR) << "Failed to enable GRPQUOTA on " << source;
2322                }
2323            }
2324        }
2325#endif
2326    }
2327    return ok();
2328}
2329
2330std::string InstalldNativeService::findDataMediaPath(
2331        const std::unique_ptr<std::string>& uuid, userid_t userid) {
2332    std::lock_guard<std::recursive_mutex> lock(mMountsLock);
2333    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2334    auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
2335    auto resolved = mStorageMounts[path];
2336    if (resolved.empty()) {
2337        LOG(WARNING) << "Failed to find storage mount for " << path;
2338        resolved = path;
2339    }
2340    return StringPrintf("%s/%u", resolved.c_str(), userid);
2341}
2342
2343std::string InstalldNativeService::findQuotaDeviceForUuid(
2344        const std::unique_ptr<std::string>& uuid) {
2345    std::lock_guard<std::recursive_mutex> lock(mMountsLock);
2346    auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
2347    return mQuotaReverseMounts[path];
2348}
2349
2350binder::Status InstalldNativeService::isQuotaSupported(
2351        const std::unique_ptr<std::string>& volumeUuid, bool* _aidl_return) {
2352    *_aidl_return = !findQuotaDeviceForUuid(volumeUuid).empty();
2353    return ok();
2354}
2355
2356}  // namespace installd
2357}  // namespace android
2358