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