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