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