1/*
2 * Copyright (C) 2017 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#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
18
19#include "VoldNativeService.h"
20
21#include <android-base/logging.h>
22#include <android-base/stringprintf.h>
23#include <android-base/strings.h>
24#include <fs_mgr.h>
25#include <fscrypt/fscrypt.h>
26#include <private/android_filesystem_config.h>
27#include <utils/Trace.h>
28
29#include <fstream>
30#include <thread>
31
32#include "Benchmark.h"
33#include "CheckEncryption.h"
34#include "Checkpoint.h"
35#include "FsCrypt.h"
36#include "IdleMaint.h"
37#include "MetadataCrypt.h"
38#include "MoveStorage.h"
39#include "Process.h"
40#include "VoldNativeServiceValidation.h"
41#include "VoldUtil.h"
42#include "VolumeManager.h"
43#include "cryptfs.h"
44#include "incfs.h"
45
46using android::base::StringPrintf;
47using std::endl;
48using namespace std::literals;
49
50namespace android {
51namespace vold {
52
53namespace {
54
55constexpr const char* kDump = "android.permission.DUMP";
56
57static binder::Status error(const std::string& msg) {
58    PLOG(ERROR) << msg;
59    return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
60}
61
62static binder::Status translate(int status) {
63    if (status == 0) {
64        return binder::Status::ok();
65    } else {
66        return binder::Status::fromServiceSpecificError(status);
67    }
68}
69
70static binder::Status translateBool(bool status) {
71    if (status) {
72        return binder::Status::ok();
73    } else {
74        return binder::Status::fromServiceSpecificError(status);
75    }
76}
77
78#define ENFORCE_SYSTEM_OR_ROOT                              \
79    {                                                       \
80        binder::Status status = CheckUidOrRoot(AID_SYSTEM); \
81        if (!status.isOk()) {                               \
82            return status;                                  \
83        }                                                   \
84    }
85
86#define CHECK_ARGUMENT_ID(id)                          \
87    {                                                  \
88        binder::Status status = CheckArgumentId((id)); \
89        if (!status.isOk()) {                          \
90            return status;                             \
91        }                                              \
92    }
93
94#define CHECK_ARGUMENT_PATH(path)                          \
95    {                                                      \
96        binder::Status status = CheckArgumentPath((path)); \
97        if (!status.isOk()) {                              \
98            return status;                                 \
99        }                                                  \
100    }
101
102#define CHECK_ARGUMENT_HEX(hex)                          \
103    {                                                    \
104        binder::Status status = CheckArgumentHex((hex)); \
105        if (!status.isOk()) {                            \
106            return status;                               \
107        }                                                \
108    }
109
110#define ACQUIRE_LOCK                                                        \
111    std::lock_guard<std::mutex> lock(VolumeManager::Instance()->getLock()); \
112    ATRACE_CALL();
113
114#define ACQUIRE_CRYPT_LOCK                                                       \
115    std::lock_guard<std::mutex> lock(VolumeManager::Instance()->getCryptLock()); \
116    ATRACE_CALL();
117
118}  // namespace
119
120status_t VoldNativeService::start() {
121    IPCThreadState::self()->disableBackgroundScheduling(true);
122    status_t ret = BinderService<VoldNativeService>::publish();
123    if (ret != android::OK) {
124        return ret;
125    }
126    sp<ProcessState> ps(ProcessState::self());
127    ps->startThreadPool();
128    ps->giveThreadPoolName();
129    return android::OK;
130}
131
132status_t VoldNativeService::dump(int fd, const Vector<String16>& /* args */) {
133    auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
134    const binder::Status dump_permission = CheckPermission(kDump);
135    if (!dump_permission.isOk()) {
136        out << dump_permission.toString8() << endl;
137        return PERMISSION_DENIED;
138    }
139
140    ACQUIRE_LOCK;
141    out << "vold is happy!" << endl;
142    return NO_ERROR;
143}
144
145binder::Status VoldNativeService::setListener(
146        const android::sp<android::os::IVoldListener>& listener) {
147    ENFORCE_SYSTEM_OR_ROOT;
148    ACQUIRE_LOCK;
149
150    VolumeManager::Instance()->setListener(listener);
151    return Ok();
152}
153
154binder::Status VoldNativeService::monitor() {
155    ENFORCE_SYSTEM_OR_ROOT;
156
157    // Simply acquire/release each lock for watchdog
158    { ACQUIRE_LOCK; }
159    { ACQUIRE_CRYPT_LOCK; }
160
161    return Ok();
162}
163
164binder::Status VoldNativeService::reset() {
165    ENFORCE_SYSTEM_OR_ROOT;
166    ACQUIRE_LOCK;
167
168    return translate(VolumeManager::Instance()->reset());
169}
170
171binder::Status VoldNativeService::shutdown() {
172    ENFORCE_SYSTEM_OR_ROOT;
173    ACQUIRE_LOCK;
174
175    return translate(VolumeManager::Instance()->shutdown());
176}
177
178binder::Status VoldNativeService::abortFuse() {
179    ENFORCE_SYSTEM_OR_ROOT;
180    ACQUIRE_LOCK;
181
182    return translate(VolumeManager::Instance()->abortFuse());
183}
184
185binder::Status VoldNativeService::onUserAdded(int32_t userId, int32_t userSerial) {
186    ENFORCE_SYSTEM_OR_ROOT;
187    ACQUIRE_LOCK;
188
189    return translate(VolumeManager::Instance()->onUserAdded(userId, userSerial));
190}
191
192binder::Status VoldNativeService::onUserRemoved(int32_t userId) {
193    ENFORCE_SYSTEM_OR_ROOT;
194    ACQUIRE_LOCK;
195
196    return translate(VolumeManager::Instance()->onUserRemoved(userId));
197}
198
199binder::Status VoldNativeService::onUserStarted(int32_t userId) {
200    ENFORCE_SYSTEM_OR_ROOT;
201    ACQUIRE_LOCK;
202
203    return translate(VolumeManager::Instance()->onUserStarted(userId));
204}
205
206binder::Status VoldNativeService::onUserStopped(int32_t userId) {
207    ENFORCE_SYSTEM_OR_ROOT;
208    ACQUIRE_LOCK;
209
210    return translate(VolumeManager::Instance()->onUserStopped(userId));
211}
212
213binder::Status VoldNativeService::addAppIds(const std::vector<std::string>& packageNames,
214                                            const std::vector<int32_t>& appIds) {
215    return Ok();
216}
217
218binder::Status VoldNativeService::addSandboxIds(const std::vector<int32_t>& appIds,
219                                                const std::vector<std::string>& sandboxIds) {
220    return Ok();
221}
222
223binder::Status VoldNativeService::onSecureKeyguardStateChanged(bool isShowing) {
224    ENFORCE_SYSTEM_OR_ROOT;
225    ACQUIRE_LOCK;
226
227    return translate(VolumeManager::Instance()->onSecureKeyguardStateChanged(isShowing));
228}
229
230binder::Status VoldNativeService::partition(const std::string& diskId, int32_t partitionType,
231                                            int32_t ratio) {
232    ENFORCE_SYSTEM_OR_ROOT;
233    CHECK_ARGUMENT_ID(diskId);
234    ACQUIRE_LOCK;
235
236    auto disk = VolumeManager::Instance()->findDisk(diskId);
237    if (disk == nullptr) {
238        return error("Failed to find disk " + diskId);
239    }
240    switch (partitionType) {
241        case PARTITION_TYPE_PUBLIC:
242            return translate(disk->partitionPublic());
243        case PARTITION_TYPE_PRIVATE:
244            return translate(disk->partitionPrivate());
245        case PARTITION_TYPE_MIXED:
246            return translate(disk->partitionMixed(ratio));
247        default:
248            return error("Unknown type " + std::to_string(partitionType));
249    }
250}
251
252binder::Status VoldNativeService::forgetPartition(const std::string& partGuid,
253                                                  const std::string& fsUuid) {
254    ENFORCE_SYSTEM_OR_ROOT;
255    CHECK_ARGUMENT_HEX(partGuid);
256    CHECK_ARGUMENT_HEX(fsUuid);
257    ACQUIRE_LOCK;
258
259    return translate(VolumeManager::Instance()->forgetPartition(partGuid, fsUuid));
260}
261
262binder::Status VoldNativeService::mount(
263        const std::string& volId, int32_t mountFlags, int32_t mountUserId,
264        const android::sp<android::os::IVoldMountCallback>& callback) {
265    ENFORCE_SYSTEM_OR_ROOT;
266    CHECK_ARGUMENT_ID(volId);
267    ACQUIRE_LOCK;
268
269    auto vol = VolumeManager::Instance()->findVolume(volId);
270    if (vol == nullptr) {
271        return error("Failed to find volume " + volId);
272    }
273
274    vol->setMountFlags(mountFlags);
275    vol->setMountUserId(mountUserId);
276
277    vol->setMountCallback(callback);
278    int res = vol->mount();
279    vol->setMountCallback(nullptr);
280
281    if (res != OK) {
282        return translate(res);
283    }
284
285    if ((mountFlags & MOUNT_FLAG_PRIMARY) != 0) {
286        res = VolumeManager::Instance()->setPrimary(vol);
287        if (res != OK) {
288            return translate(res);
289        }
290    }
291    return translate(OK);
292}
293
294binder::Status VoldNativeService::unmount(const std::string& volId) {
295    ENFORCE_SYSTEM_OR_ROOT;
296    CHECK_ARGUMENT_ID(volId);
297    ACQUIRE_LOCK;
298
299    auto vol = VolumeManager::Instance()->findVolume(volId);
300    if (vol == nullptr) {
301        return error("Failed to find volume " + volId);
302    }
303    return translate(vol->unmount());
304}
305
306binder::Status VoldNativeService::format(const std::string& volId, const std::string& fsType) {
307    ENFORCE_SYSTEM_OR_ROOT;
308    CHECK_ARGUMENT_ID(volId);
309    ACQUIRE_LOCK;
310
311    auto vol = VolumeManager::Instance()->findVolume(volId);
312    if (vol == nullptr) {
313        return error("Failed to find volume " + volId);
314    }
315    return translate(vol->format(fsType));
316}
317
318static binder::Status pathForVolId(const std::string& volId, std::string* path) {
319    if (volId == "private" || volId == "null") {
320        *path = "/data";
321    } else {
322        auto vol = VolumeManager::Instance()->findVolume(volId);
323        if (vol == nullptr) {
324            return error("Failed to find volume " + volId);
325        }
326        if (vol->getType() != VolumeBase::Type::kPrivate) {
327            return error("Volume " + volId + " not private");
328        }
329        if (vol->getState() != VolumeBase::State::kMounted) {
330            return error("Volume " + volId + " not mounted");
331        }
332        *path = vol->getPath();
333        if (path->empty()) {
334            return error("Volume " + volId + " missing path");
335        }
336    }
337    return Ok();
338}
339
340binder::Status VoldNativeService::benchmark(
341        const std::string& volId, const android::sp<android::os::IVoldTaskListener>& listener) {
342    ENFORCE_SYSTEM_OR_ROOT;
343    CHECK_ARGUMENT_ID(volId);
344    ACQUIRE_LOCK;
345
346    std::string path;
347    auto status = pathForVolId(volId, &path);
348    if (!status.isOk()) return status;
349
350    std::thread([=]() { android::vold::Benchmark(path, listener); }).detach();
351    return Ok();
352}
353
354binder::Status VoldNativeService::checkEncryption(const std::string& volId) {
355    ENFORCE_SYSTEM_OR_ROOT;
356    CHECK_ARGUMENT_ID(volId);
357    ACQUIRE_LOCK;
358
359    std::string path;
360    auto status = pathForVolId(volId, &path);
361    if (!status.isOk()) return status;
362    return translate(android::vold::CheckEncryption(path));
363}
364
365binder::Status VoldNativeService::moveStorage(
366        const std::string& fromVolId, const std::string& toVolId,
367        const android::sp<android::os::IVoldTaskListener>& listener) {
368    ENFORCE_SYSTEM_OR_ROOT;
369    CHECK_ARGUMENT_ID(fromVolId);
370    CHECK_ARGUMENT_ID(toVolId);
371    ACQUIRE_LOCK;
372
373    auto fromVol = VolumeManager::Instance()->findVolume(fromVolId);
374    auto toVol = VolumeManager::Instance()->findVolume(toVolId);
375    if (fromVol == nullptr) {
376        return error("Failed to find volume " + fromVolId);
377    } else if (toVol == nullptr) {
378        return error("Failed to find volume " + toVolId);
379    }
380
381    std::thread([=]() { android::vold::MoveStorage(fromVol, toVol, listener); }).detach();
382    return Ok();
383}
384
385binder::Status VoldNativeService::remountUid(int32_t uid, int32_t remountMode) {
386    ENFORCE_SYSTEM_OR_ROOT;
387    ACQUIRE_LOCK;
388
389    return translate(VolumeManager::Instance()->remountUid(uid, remountMode));
390}
391
392binder::Status VoldNativeService::remountAppStorageDirs(int uid, int pid,
393        const std::vector<std::string>& packageNames) {
394    ENFORCE_SYSTEM_OR_ROOT;
395    ACQUIRE_LOCK;
396
397    return translate(VolumeManager::Instance()->remountAppStorageDirs(uid, pid, packageNames));
398}
399
400binder::Status VoldNativeService::setupAppDir(const std::string& path, int32_t appUid) {
401    ENFORCE_SYSTEM_OR_ROOT;
402    CHECK_ARGUMENT_PATH(path);
403    ACQUIRE_LOCK;
404
405    return translate(VolumeManager::Instance()->setupAppDir(path, appUid));
406}
407
408binder::Status VoldNativeService::fixupAppDir(const std::string& path, int32_t appUid) {
409    ENFORCE_SYSTEM_OR_ROOT;
410    CHECK_ARGUMENT_PATH(path);
411    ACQUIRE_LOCK;
412
413    return translate(VolumeManager::Instance()->fixupAppDir(path, appUid));
414}
415
416binder::Status VoldNativeService::createObb(const std::string& sourcePath,
417                                            const std::string& sourceKey, int32_t ownerGid,
418                                            std::string* _aidl_return) {
419    ENFORCE_SYSTEM_OR_ROOT;
420    CHECK_ARGUMENT_PATH(sourcePath);
421    CHECK_ARGUMENT_HEX(sourceKey);
422    ACQUIRE_LOCK;
423
424    return translate(
425            VolumeManager::Instance()->createObb(sourcePath, sourceKey, ownerGid, _aidl_return));
426}
427
428binder::Status VoldNativeService::destroyObb(const std::string& volId) {
429    ENFORCE_SYSTEM_OR_ROOT;
430    CHECK_ARGUMENT_ID(volId);
431    ACQUIRE_LOCK;
432
433    return translate(VolumeManager::Instance()->destroyObb(volId));
434}
435
436binder::Status VoldNativeService::createStubVolume(const std::string& sourcePath,
437                                                   const std::string& mountPath,
438                                                   const std::string& fsType,
439                                                   const std::string& fsUuid,
440                                                   const std::string& fsLabel, int32_t flags,
441                                                   std::string* _aidl_return) {
442    ENFORCE_SYSTEM_OR_ROOT;
443    CHECK_ARGUMENT_PATH(sourcePath);
444    CHECK_ARGUMENT_PATH(mountPath);
445    CHECK_ARGUMENT_HEX(fsUuid);
446    // Label limitation seems to be different between fs (including allowed characters), so checking
447    // is quite meaningless.
448    ACQUIRE_LOCK;
449
450    return translate(VolumeManager::Instance()->createStubVolume(
451            sourcePath, mountPath, fsType, fsUuid, fsLabel, flags, _aidl_return));
452}
453
454binder::Status VoldNativeService::destroyStubVolume(const std::string& volId) {
455    ENFORCE_SYSTEM_OR_ROOT;
456    CHECK_ARGUMENT_ID(volId);
457    ACQUIRE_LOCK;
458
459    return translate(VolumeManager::Instance()->destroyStubVolume(volId));
460}
461
462binder::Status VoldNativeService::fstrim(
463        int32_t fstrimFlags, const android::sp<android::os::IVoldTaskListener>& listener) {
464    ENFORCE_SYSTEM_OR_ROOT;
465    ACQUIRE_LOCK;
466
467    std::thread([=]() { android::vold::Trim(listener); }).detach();
468    return Ok();
469}
470
471binder::Status VoldNativeService::runIdleMaint(
472        const android::sp<android::os::IVoldTaskListener>& listener) {
473    ENFORCE_SYSTEM_OR_ROOT;
474    ACQUIRE_LOCK;
475
476    std::thread([=]() { android::vold::RunIdleMaint(listener); }).detach();
477    return Ok();
478}
479
480binder::Status VoldNativeService::abortIdleMaint(
481        const android::sp<android::os::IVoldTaskListener>& listener) {
482    ENFORCE_SYSTEM_OR_ROOT;
483    ACQUIRE_LOCK;
484
485    std::thread([=]() { android::vold::AbortIdleMaint(listener); }).detach();
486    return Ok();
487}
488
489binder::Status VoldNativeService::mountAppFuse(int32_t uid, int32_t mountId,
490                                               android::base::unique_fd* _aidl_return) {
491    ENFORCE_SYSTEM_OR_ROOT;
492    ACQUIRE_LOCK;
493
494    return translate(VolumeManager::Instance()->mountAppFuse(uid, mountId, _aidl_return));
495}
496
497binder::Status VoldNativeService::unmountAppFuse(int32_t uid, int32_t mountId) {
498    ENFORCE_SYSTEM_OR_ROOT;
499    ACQUIRE_LOCK;
500
501    return translate(VolumeManager::Instance()->unmountAppFuse(uid, mountId));
502}
503
504binder::Status VoldNativeService::openAppFuseFile(int32_t uid, int32_t mountId, int32_t fileId,
505                                                  int32_t flags,
506                                                  android::base::unique_fd* _aidl_return) {
507    ENFORCE_SYSTEM_OR_ROOT;
508    ACQUIRE_LOCK;
509
510    int fd = VolumeManager::Instance()->openAppFuseFile(uid, mountId, fileId, flags);
511    if (fd == -1) {
512        return error("Failed to open AppFuse file for uid: " + std::to_string(uid) +
513                     " mountId: " + std::to_string(mountId) + " fileId: " + std::to_string(fileId) +
514                     " flags: " + std::to_string(flags));
515    }
516
517    *_aidl_return = android::base::unique_fd(fd);
518    return Ok();
519}
520
521binder::Status VoldNativeService::fdeCheckPassword(const std::string& password) {
522    ENFORCE_SYSTEM_OR_ROOT;
523    ACQUIRE_CRYPT_LOCK;
524
525    return translate(cryptfs_check_passwd(password.c_str()));
526}
527
528binder::Status VoldNativeService::fdeRestart() {
529    ENFORCE_SYSTEM_OR_ROOT;
530    ACQUIRE_CRYPT_LOCK;
531
532    // Spawn as thread so init can issue commands back to vold without
533    // causing deadlock, usually as a result of prep_data_fs.
534    std::thread(&cryptfs_restart).detach();
535    return Ok();
536}
537
538binder::Status VoldNativeService::fdeComplete(int32_t* _aidl_return) {
539    ENFORCE_SYSTEM_OR_ROOT;
540    ACQUIRE_CRYPT_LOCK;
541
542    *_aidl_return = cryptfs_crypto_complete();
543    return Ok();
544}
545
546static int fdeEnableInternal(int32_t passwordType, const std::string& password,
547                             int32_t encryptionFlags) {
548    bool noUi = (encryptionFlags & VoldNativeService::ENCRYPTION_FLAG_NO_UI) != 0;
549
550    for (int tries = 0; tries < 2; ++tries) {
551        int rc;
552        if (passwordType == VoldNativeService::PASSWORD_TYPE_DEFAULT) {
553            rc = cryptfs_enable_default(noUi);
554        } else {
555            rc = cryptfs_enable(passwordType, password.c_str(), noUi);
556        }
557
558        if (rc == 0) {
559            return 0;
560        } else if (tries == 0) {
561            KillProcessesWithOpenFiles(DATA_MNT_POINT, SIGKILL);
562        }
563    }
564
565    return -1;
566}
567
568binder::Status VoldNativeService::fdeEnable(int32_t passwordType, const std::string& password,
569                                            int32_t encryptionFlags) {
570    ENFORCE_SYSTEM_OR_ROOT;
571    ACQUIRE_CRYPT_LOCK;
572
573    LOG(DEBUG) << "fdeEnable(" << passwordType << ", *, " << encryptionFlags << ")";
574    if (fscrypt_is_native()) {
575        LOG(ERROR) << "fscrypt_is_native, fdeEnable invalid";
576        return error("fscrypt_is_native, fdeEnable invalid");
577    }
578    LOG(DEBUG) << "!fscrypt_is_native, spawning fdeEnableInternal";
579
580    // Spawn as thread so init can issue commands back to vold without
581    // causing deadlock, usually as a result of prep_data_fs.
582    std::thread(&fdeEnableInternal, passwordType, password, encryptionFlags).detach();
583    return Ok();
584}
585
586binder::Status VoldNativeService::fdeChangePassword(int32_t passwordType,
587                                                    const std::string& password) {
588    ENFORCE_SYSTEM_OR_ROOT;
589    ACQUIRE_CRYPT_LOCK;
590
591    return translate(cryptfs_changepw(passwordType, password.c_str()));
592}
593
594binder::Status VoldNativeService::fdeVerifyPassword(const std::string& password) {
595    ENFORCE_SYSTEM_OR_ROOT;
596    ACQUIRE_CRYPT_LOCK;
597
598    return translate(cryptfs_verify_passwd(password.c_str()));
599}
600
601binder::Status VoldNativeService::fdeGetField(const std::string& key, std::string* _aidl_return) {
602    ENFORCE_SYSTEM_OR_ROOT;
603    ACQUIRE_CRYPT_LOCK;
604
605    char buf[PROPERTY_VALUE_MAX];
606    if (cryptfs_getfield(key.c_str(), buf, sizeof(buf)) != CRYPTO_GETFIELD_OK) {
607        return error(StringPrintf("Failed to read field %s", key.c_str()));
608    } else {
609        *_aidl_return = buf;
610        return Ok();
611    }
612}
613
614binder::Status VoldNativeService::fdeSetField(const std::string& key, const std::string& value) {
615    ENFORCE_SYSTEM_OR_ROOT;
616    ACQUIRE_CRYPT_LOCK;
617
618    return translate(cryptfs_setfield(key.c_str(), value.c_str()));
619}
620
621binder::Status VoldNativeService::fdeGetPasswordType(int32_t* _aidl_return) {
622    ENFORCE_SYSTEM_OR_ROOT;
623    ACQUIRE_CRYPT_LOCK;
624
625    *_aidl_return = cryptfs_get_password_type();
626    return Ok();
627}
628
629binder::Status VoldNativeService::fdeGetPassword(std::string* _aidl_return) {
630    ENFORCE_SYSTEM_OR_ROOT;
631    ACQUIRE_CRYPT_LOCK;
632
633    const char* res = cryptfs_get_password();
634    if (res != nullptr) {
635        *_aidl_return = res;
636    }
637    return Ok();
638}
639
640binder::Status VoldNativeService::fdeClearPassword() {
641    ENFORCE_SYSTEM_OR_ROOT;
642    ACQUIRE_CRYPT_LOCK;
643
644    cryptfs_clear_password();
645    return Ok();
646}
647
648binder::Status VoldNativeService::fbeEnable() {
649    ENFORCE_SYSTEM_OR_ROOT;
650    ACQUIRE_CRYPT_LOCK;
651
652    return translateBool(fscrypt_initialize_systemwide_keys());
653}
654
655binder::Status VoldNativeService::mountDefaultEncrypted() {
656    ENFORCE_SYSTEM_OR_ROOT;
657    ACQUIRE_CRYPT_LOCK;
658
659    if (!fscrypt_is_native()) {
660        // Spawn as thread so init can issue commands back to vold without
661        // causing deadlock, usually as a result of prep_data_fs.
662        std::thread(&cryptfs_mount_default_encrypted).detach();
663    }
664    return Ok();
665}
666
667binder::Status VoldNativeService::initUser0() {
668    ENFORCE_SYSTEM_OR_ROOT;
669    ACQUIRE_CRYPT_LOCK;
670
671    return translateBool(fscrypt_init_user0());
672}
673
674binder::Status VoldNativeService::isConvertibleToFbe(bool* _aidl_return) {
675    ENFORCE_SYSTEM_OR_ROOT;
676    ACQUIRE_CRYPT_LOCK;
677
678    *_aidl_return = cryptfs_isConvertibleToFBE() != 0;
679    return Ok();
680}
681
682binder::Status VoldNativeService::mountFstab(const std::string& blkDevice,
683                                             const std::string& mountPoint) {
684    ENFORCE_SYSTEM_OR_ROOT;
685    ACQUIRE_LOCK;
686
687    return translateBool(fscrypt_mount_metadata_encrypted(blkDevice, mountPoint, false));
688}
689
690binder::Status VoldNativeService::encryptFstab(const std::string& blkDevice,
691                                               const std::string& mountPoint) {
692    ENFORCE_SYSTEM_OR_ROOT;
693    ACQUIRE_LOCK;
694
695    return translateBool(fscrypt_mount_metadata_encrypted(blkDevice, mountPoint, true));
696}
697
698binder::Status VoldNativeService::createUserKey(int32_t userId, int32_t userSerial,
699                                                bool ephemeral) {
700    ENFORCE_SYSTEM_OR_ROOT;
701    ACQUIRE_CRYPT_LOCK;
702
703    return translateBool(fscrypt_vold_create_user_key(userId, userSerial, ephemeral));
704}
705
706binder::Status VoldNativeService::destroyUserKey(int32_t userId) {
707    ENFORCE_SYSTEM_OR_ROOT;
708    ACQUIRE_CRYPT_LOCK;
709
710    return translateBool(fscrypt_destroy_user_key(userId));
711}
712
713binder::Status VoldNativeService::addUserKeyAuth(int32_t userId, int32_t userSerial,
714                                                 const std::string& token,
715                                                 const std::string& secret) {
716    ENFORCE_SYSTEM_OR_ROOT;
717    ACQUIRE_CRYPT_LOCK;
718
719    return translateBool(fscrypt_add_user_key_auth(userId, userSerial, token, secret));
720}
721
722binder::Status VoldNativeService::clearUserKeyAuth(int32_t userId, int32_t userSerial,
723                                                   const std::string& token,
724                                                   const std::string& secret) {
725    ENFORCE_SYSTEM_OR_ROOT;
726    ACQUIRE_CRYPT_LOCK;
727
728    return translateBool(fscrypt_clear_user_key_auth(userId, userSerial, token, secret));
729}
730
731binder::Status VoldNativeService::fixateNewestUserKeyAuth(int32_t userId) {
732    ENFORCE_SYSTEM_OR_ROOT;
733    ACQUIRE_CRYPT_LOCK;
734
735    return translateBool(fscrypt_fixate_newest_user_key_auth(userId));
736}
737
738binder::Status VoldNativeService::unlockUserKey(int32_t userId, int32_t userSerial,
739                                                const std::string& token,
740                                                const std::string& secret) {
741    ENFORCE_SYSTEM_OR_ROOT;
742    ACQUIRE_CRYPT_LOCK;
743
744    return translateBool(fscrypt_unlock_user_key(userId, userSerial, token, secret));
745}
746
747binder::Status VoldNativeService::lockUserKey(int32_t userId) {
748    ENFORCE_SYSTEM_OR_ROOT;
749    ACQUIRE_CRYPT_LOCK;
750
751    return translateBool(fscrypt_lock_user_key(userId));
752}
753
754binder::Status VoldNativeService::prepareUserStorage(const std::unique_ptr<std::string>& uuid,
755                                                     int32_t userId, int32_t userSerial,
756                                                     int32_t flags) {
757    ENFORCE_SYSTEM_OR_ROOT;
758    std::string empty_string = "";
759    auto uuid_ = uuid ? *uuid : empty_string;
760    CHECK_ARGUMENT_HEX(uuid_);
761
762    ACQUIRE_CRYPT_LOCK;
763    return translateBool(fscrypt_prepare_user_storage(uuid_, userId, userSerial, flags));
764}
765
766binder::Status VoldNativeService::destroyUserStorage(const std::unique_ptr<std::string>& uuid,
767                                                     int32_t userId, int32_t flags) {
768    ENFORCE_SYSTEM_OR_ROOT;
769    std::string empty_string = "";
770    auto uuid_ = uuid ? *uuid : empty_string;
771    CHECK_ARGUMENT_HEX(uuid_);
772
773    ACQUIRE_CRYPT_LOCK;
774    return translateBool(fscrypt_destroy_user_storage(uuid_, userId, flags));
775}
776
777binder::Status VoldNativeService::prepareSandboxForApp(const std::string& packageName,
778                                                       int32_t appId, const std::string& sandboxId,
779                                                       int32_t userId) {
780    return Ok();
781}
782
783binder::Status VoldNativeService::destroySandboxForApp(const std::string& packageName,
784                                                       const std::string& sandboxId,
785                                                       int32_t userId) {
786    return Ok();
787}
788
789binder::Status VoldNativeService::startCheckpoint(int32_t retry) {
790    ENFORCE_SYSTEM_OR_ROOT;
791    ACQUIRE_LOCK;
792
793    return cp_startCheckpoint(retry);
794}
795
796binder::Status VoldNativeService::needsRollback(bool* _aidl_return) {
797    ENFORCE_SYSTEM_OR_ROOT;
798    ACQUIRE_LOCK;
799
800    *_aidl_return = cp_needsRollback();
801    return Ok();
802}
803
804binder::Status VoldNativeService::needsCheckpoint(bool* _aidl_return) {
805    ENFORCE_SYSTEM_OR_ROOT;
806    ACQUIRE_LOCK;
807
808    *_aidl_return = cp_needsCheckpoint();
809    return Ok();
810}
811
812binder::Status VoldNativeService::isCheckpointing(bool* _aidl_return) {
813    ENFORCE_SYSTEM_OR_ROOT;
814    ACQUIRE_LOCK;
815
816    *_aidl_return = cp_isCheckpointing();
817    return Ok();
818}
819
820binder::Status VoldNativeService::commitChanges() {
821    ENFORCE_SYSTEM_OR_ROOT;
822    ACQUIRE_LOCK;
823
824    return cp_commitChanges();
825}
826
827binder::Status VoldNativeService::prepareCheckpoint() {
828    ENFORCE_SYSTEM_OR_ROOT;
829    ACQUIRE_LOCK;
830
831    return cp_prepareCheckpoint();
832}
833
834binder::Status VoldNativeService::restoreCheckpoint(const std::string& mountPoint) {
835    ENFORCE_SYSTEM_OR_ROOT;
836    CHECK_ARGUMENT_PATH(mountPoint);
837    ACQUIRE_LOCK;
838
839    return cp_restoreCheckpoint(mountPoint);
840}
841
842binder::Status VoldNativeService::restoreCheckpointPart(const std::string& mountPoint, int count) {
843    ENFORCE_SYSTEM_OR_ROOT;
844    CHECK_ARGUMENT_PATH(mountPoint);
845    ACQUIRE_LOCK;
846
847    return cp_restoreCheckpoint(mountPoint, count);
848}
849
850binder::Status VoldNativeService::markBootAttempt() {
851    ENFORCE_SYSTEM_OR_ROOT;
852    ACQUIRE_LOCK;
853
854    return cp_markBootAttempt();
855}
856
857binder::Status VoldNativeService::abortChanges(const std::string& message, bool retry) {
858    ENFORCE_SYSTEM_OR_ROOT;
859    ACQUIRE_LOCK;
860
861    cp_abortChanges(message, retry);
862    return Ok();
863}
864
865binder::Status VoldNativeService::supportsCheckpoint(bool* _aidl_return) {
866    ENFORCE_SYSTEM_OR_ROOT;
867    ACQUIRE_LOCK;
868
869    return cp_supportsCheckpoint(*_aidl_return);
870}
871
872binder::Status VoldNativeService::supportsBlockCheckpoint(bool* _aidl_return) {
873    ENFORCE_SYSTEM_OR_ROOT;
874    ACQUIRE_LOCK;
875
876    return cp_supportsBlockCheckpoint(*_aidl_return);
877}
878
879binder::Status VoldNativeService::supportsFileCheckpoint(bool* _aidl_return) {
880    ENFORCE_SYSTEM_OR_ROOT;
881    ACQUIRE_LOCK;
882
883    return cp_supportsFileCheckpoint(*_aidl_return);
884}
885
886binder::Status VoldNativeService::resetCheckpoint() {
887    ENFORCE_SYSTEM_OR_ROOT;
888    ACQUIRE_LOCK;
889
890    cp_resetCheckpoint();
891    return Ok();
892}
893
894binder::Status VoldNativeService::incFsEnabled(bool* _aidl_return) {
895    ENFORCE_SYSTEM_OR_ROOT;
896
897    *_aidl_return = incfs::enabled();
898    return Ok();
899}
900
901binder::Status VoldNativeService::mountIncFs(
902        const std::string& backingPath, const std::string& targetDir, int32_t flags,
903        ::android::os::incremental::IncrementalFileSystemControlParcel* _aidl_return) {
904    ENFORCE_SYSTEM_OR_ROOT;
905    CHECK_ARGUMENT_PATH(backingPath);
906    CHECK_ARGUMENT_PATH(targetDir);
907
908    auto control = incfs::mount(backingPath, targetDir,
909                                {.flags = IncFsMountFlags(flags),
910                                 .defaultReadTimeoutMs = INCFS_DEFAULT_READ_TIMEOUT_MS,
911                                 // Mount with read logs disabled.
912                                 .readLogBufferPages = 0});
913    if (!control) {
914        return translate(-errno);
915    }
916    auto fds = control.releaseFds();
917    using android::base::unique_fd;
918    _aidl_return->cmd.reset(unique_fd(fds[CMD].release()));
919    _aidl_return->pendingReads.reset(unique_fd(fds[PENDING_READS].release()));
920    _aidl_return->log.reset(unique_fd(fds[LOGS].release()));
921    return Ok();
922}
923
924binder::Status VoldNativeService::unmountIncFs(const std::string& dir) {
925    ENFORCE_SYSTEM_OR_ROOT;
926    CHECK_ARGUMENT_PATH(dir);
927
928    return translate(incfs::unmount(dir));
929}
930
931binder::Status VoldNativeService::setIncFsMountOptions(
932        const ::android::os::incremental::IncrementalFileSystemControlParcel& control,
933        bool enableReadLogs) {
934    ENFORCE_SYSTEM_OR_ROOT;
935
936    auto incfsControl =
937            incfs::createControl(control.cmd.get(), control.pendingReads.get(), control.log.get());
938    auto cleanupFunc = [](auto incfsControl) {
939        for (auto& fd : incfsControl->releaseFds()) {
940            (void)fd.release();
941        }
942    };
943    auto cleanup =
944            std::unique_ptr<incfs::Control, decltype(cleanupFunc)>(&incfsControl, cleanupFunc);
945    if (auto error = incfs::setOptions(
946                incfsControl,
947                {.defaultReadTimeoutMs = INCFS_DEFAULT_READ_TIMEOUT_MS,
948                 .readLogBufferPages = enableReadLogs ? INCFS_DEFAULT_PAGE_READ_BUFFER_PAGES : 0});
949        error < 0) {
950        return binder::Status::fromServiceSpecificError(error);
951    }
952
953    return Ok();
954}
955
956binder::Status VoldNativeService::bindMount(const std::string& sourceDir,
957                                            const std::string& targetDir) {
958    ENFORCE_SYSTEM_OR_ROOT;
959    CHECK_ARGUMENT_PATH(sourceDir);
960    CHECK_ARGUMENT_PATH(targetDir);
961
962    return translate(incfs::bindMount(sourceDir, targetDir));
963}
964
965}  // namespace vold
966}  // namespace android
967