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 ACQUIRE_LOCK;
260
261 return translate(VolumeManager::Instance()->forgetPartition(partGuid, fsUuid));
262 }
263
mount(const std::string & volId,int32_t mountFlags,int32_t mountUserId,const android::sp<android::os::IVoldMountCallback> & callback)264 binder::Status VoldNativeService::mount(
265 const std::string& volId, int32_t mountFlags, int32_t mountUserId,
266 const android::sp<android::os::IVoldMountCallback>& callback) {
267 ENFORCE_SYSTEM_OR_ROOT;
268 CHECK_ARGUMENT_ID(volId);
269 ACQUIRE_LOCK;
270
271 auto vol = VolumeManager::Instance()->findVolume(volId);
272 if (vol == nullptr) {
273 return error("Failed to find volume " + volId);
274 }
275
276 vol->setMountFlags(mountFlags);
277 vol->setMountUserId(mountUserId);
278
279 vol->setMountCallback(callback);
280 int res = vol->mount();
281 vol->setMountCallback(nullptr);
282
283 if (res != OK) {
284 return translate(res);
285 }
286
287 return translate(OK);
288 }
289
unmount(const std::string & volId)290 binder::Status VoldNativeService::unmount(const std::string& volId) {
291 ENFORCE_SYSTEM_OR_ROOT;
292 CHECK_ARGUMENT_ID(volId);
293 ACQUIRE_LOCK;
294
295 auto vol = VolumeManager::Instance()->findVolume(volId);
296 if (vol == nullptr) {
297 return error("Failed to find volume " + volId);
298 }
299 return translate(vol->unmount());
300 }
301
format(const std::string & volId,const std::string & fsType)302 binder::Status VoldNativeService::format(const std::string& volId, const std::string& fsType) {
303 ENFORCE_SYSTEM_OR_ROOT;
304 CHECK_ARGUMENT_ID(volId);
305 ACQUIRE_LOCK;
306
307 auto vol = VolumeManager::Instance()->findVolume(volId);
308 if (vol == nullptr) {
309 return error("Failed to find volume " + volId);
310 }
311 return translate(vol->format(fsType));
312 }
313
pathForVolId(const std::string & volId,std::string * path)314 static binder::Status pathForVolId(const std::string& volId, std::string* path) {
315 if (volId == "private" || volId == "null") {
316 *path = "/data";
317 } else {
318 auto vol = VolumeManager::Instance()->findVolume(volId);
319 if (vol == nullptr) {
320 return error("Failed to find volume " + volId);
321 }
322 if (vol->getType() != VolumeBase::Type::kPrivate) {
323 return error("Volume " + volId + " not private");
324 }
325 if (vol->getState() != VolumeBase::State::kMounted) {
326 return error("Volume " + volId + " not mounted");
327 }
328 *path = vol->getPath();
329 if (path->empty()) {
330 return error("Volume " + volId + " missing path");
331 }
332 }
333 return Ok();
334 }
335
benchmark(const std::string & volId,const android::sp<android::os::IVoldTaskListener> & listener)336 binder::Status VoldNativeService::benchmark(
337 const std::string& volId, const android::sp<android::os::IVoldTaskListener>& listener) {
338 ENFORCE_SYSTEM_OR_ROOT;
339 CHECK_ARGUMENT_ID(volId);
340 ACQUIRE_LOCK;
341
342 std::string path;
343 auto status = pathForVolId(volId, &path);
344 if (!status.isOk()) return status;
345
346 std::thread([=]() { android::vold::Benchmark(path, listener); }).detach();
347 return Ok();
348 }
349
moveStorage(const std::string & fromVolId,const std::string & toVolId,const android::sp<android::os::IVoldTaskListener> & listener)350 binder::Status VoldNativeService::moveStorage(
351 const std::string& fromVolId, const std::string& toVolId,
352 const android::sp<android::os::IVoldTaskListener>& listener) {
353 ENFORCE_SYSTEM_OR_ROOT;
354 CHECK_ARGUMENT_ID(fromVolId);
355 CHECK_ARGUMENT_ID(toVolId);
356 ACQUIRE_LOCK;
357
358 auto fromVol = VolumeManager::Instance()->findVolume(fromVolId);
359 auto toVol = VolumeManager::Instance()->findVolume(toVolId);
360 if (fromVol == nullptr) {
361 return error("Failed to find volume " + fromVolId);
362 } else if (toVol == nullptr) {
363 return error("Failed to find volume " + toVolId);
364 }
365
366 std::thread([=]() { android::vold::MoveStorage(fromVol, toVol, listener); }).detach();
367 return Ok();
368 }
369
remountUid(int32_t uid,int32_t remountMode)370 binder::Status VoldNativeService::remountUid(int32_t uid, int32_t remountMode) {
371 ENFORCE_SYSTEM_OR_ROOT;
372 ACQUIRE_LOCK;
373
374 return translate(VolumeManager::Instance()->remountUid(uid, remountMode));
375 }
376
remountAppStorageDirs(int uid,int pid,const std::vector<std::string> & packageNames)377 binder::Status VoldNativeService::remountAppStorageDirs(int uid, int pid,
378 const std::vector<std::string>& packageNames) {
379 ENFORCE_SYSTEM_OR_ROOT;
380 ACQUIRE_LOCK;
381
382 return translate(VolumeManager::Instance()->handleAppStorageDirs(uid, pid,
383 false /* doUnmount */, packageNames));
384 }
385
unmountAppStorageDirs(int uid,int pid,const std::vector<std::string> & packageNames)386 binder::Status VoldNativeService::unmountAppStorageDirs(int uid, int pid,
387 const std::vector<std::string>& packageNames) {
388 ENFORCE_SYSTEM_OR_ROOT;
389 ACQUIRE_LOCK;
390
391 return translate(VolumeManager::Instance()->handleAppStorageDirs(uid, pid,
392 true /* doUnmount */, packageNames));
393 }
394
setupAppDir(const std::string & path,int32_t appUid)395 binder::Status VoldNativeService::setupAppDir(const std::string& path, int32_t appUid) {
396 ENFORCE_SYSTEM_OR_ROOT;
397 CHECK_ARGUMENT_PATH(path);
398 ACQUIRE_LOCK;
399
400 return translate(VolumeManager::Instance()->setupAppDir(path, appUid));
401 }
402
ensureAppDirsCreated(const std::vector<std::string> & paths,int32_t appUid)403 binder::Status VoldNativeService::ensureAppDirsCreated(const std::vector<std::string>& paths,
404 int32_t appUid) {
405 ENFORCE_SYSTEM_OR_ROOT;
406 ACQUIRE_LOCK;
407
408 return translate(VolumeManager::Instance()->ensureAppDirsCreated(paths, appUid));
409 }
410
fixupAppDir(const std::string & path,int32_t appUid)411 binder::Status VoldNativeService::fixupAppDir(const std::string& path, int32_t appUid) {
412 ENFORCE_SYSTEM_OR_ROOT;
413 CHECK_ARGUMENT_PATH(path);
414 ACQUIRE_LOCK;
415
416 return translate(VolumeManager::Instance()->fixupAppDir(path, appUid));
417 }
418
createObb(const std::string & sourcePath,int32_t ownerGid,std::string * _aidl_return)419 binder::Status VoldNativeService::createObb(const std::string& sourcePath, int32_t ownerGid,
420 std::string* _aidl_return) {
421 ENFORCE_SYSTEM_OR_ROOT;
422 CHECK_ARGUMENT_PATH(sourcePath);
423 ACQUIRE_LOCK;
424
425 return translate(VolumeManager::Instance()->createObb(sourcePath, ownerGid, _aidl_return));
426 }
427
destroyObb(const std::string & volId)428 binder::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
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)436 binder::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
destroyStubVolume(const std::string & volId)454 binder::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
fstrim(int32_t fstrimFlags,const android::sp<android::os::IVoldTaskListener> & listener)462 binder::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
runIdleMaint(bool needGC,const android::sp<android::os::IVoldTaskListener> & listener)471 binder::Status VoldNativeService::runIdleMaint(
472 bool needGC, const android::sp<android::os::IVoldTaskListener>& listener) {
473 ENFORCE_SYSTEM_OR_ROOT;
474 ACQUIRE_LOCK;
475
476 std::thread([=]() { android::vold::RunIdleMaint(needGC, listener); }).detach();
477 return Ok();
478 }
479
abortIdleMaint(const android::sp<android::os::IVoldTaskListener> & listener)480 binder::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
getStorageLifeTime(int32_t * _aidl_return)489 binder::Status VoldNativeService::getStorageLifeTime(int32_t* _aidl_return) {
490 ENFORCE_SYSTEM_OR_ROOT;
491 ACQUIRE_LOCK;
492
493 *_aidl_return = GetStorageLifeTime();
494 return Ok();
495 }
496
setGCUrgentPace(int32_t neededSegments,int32_t minSegmentThreshold,float dirtyReclaimRate,float reclaimWeight,int32_t gcPeriod,int32_t minGCSleepTime,int32_t targetDirtyRatio)497 binder::Status VoldNativeService::setGCUrgentPace(int32_t neededSegments,
498 int32_t minSegmentThreshold,
499 float dirtyReclaimRate, float reclaimWeight,
500 int32_t gcPeriod, int32_t minGCSleepTime,
501 int32_t targetDirtyRatio) {
502 ENFORCE_SYSTEM_OR_ROOT;
503 ACQUIRE_LOCK;
504
505 SetGCUrgentPace(neededSegments, minSegmentThreshold, dirtyReclaimRate, reclaimWeight, gcPeriod,
506 minGCSleepTime, targetDirtyRatio);
507 return Ok();
508 }
509
refreshLatestWrite()510 binder::Status VoldNativeService::refreshLatestWrite() {
511 ENFORCE_SYSTEM_OR_ROOT;
512 ACQUIRE_LOCK;
513
514 RefreshLatestWrite();
515 return Ok();
516 }
517
getWriteAmount(int32_t * _aidl_return)518 binder::Status VoldNativeService::getWriteAmount(int32_t* _aidl_return) {
519 ENFORCE_SYSTEM_OR_ROOT;
520 ACQUIRE_LOCK;
521
522 *_aidl_return = GetWriteAmount();
523 return Ok();
524 }
525
mountAppFuse(int32_t uid,int32_t mountId,android::base::unique_fd * _aidl_return)526 binder::Status VoldNativeService::mountAppFuse(int32_t uid, int32_t mountId,
527 android::base::unique_fd* _aidl_return) {
528 ENFORCE_SYSTEM_OR_ROOT;
529 ACQUIRE_LOCK;
530
531 return translate(VolumeManager::Instance()->mountAppFuse(uid, mountId, _aidl_return));
532 }
533
unmountAppFuse(int32_t uid,int32_t mountId)534 binder::Status VoldNativeService::unmountAppFuse(int32_t uid, int32_t mountId) {
535 ENFORCE_SYSTEM_OR_ROOT;
536 ACQUIRE_LOCK;
537
538 return translate(VolumeManager::Instance()->unmountAppFuse(uid, mountId));
539 }
540
openAppFuseFile(int32_t uid,int32_t mountId,int32_t fileId,int32_t flags,android::base::unique_fd * _aidl_return)541 binder::Status VoldNativeService::openAppFuseFile(int32_t uid, int32_t mountId, int32_t fileId,
542 int32_t flags,
543 android::base::unique_fd* _aidl_return) {
544 ENFORCE_SYSTEM_OR_ROOT;
545 ACQUIRE_LOCK;
546
547 int fd = VolumeManager::Instance()->openAppFuseFile(uid, mountId, fileId, flags);
548 if (fd == -1) {
549 return error("Failed to open AppFuse file for uid: " + std::to_string(uid) +
550 " mountId: " + std::to_string(mountId) + " fileId: " + std::to_string(fileId) +
551 " flags: " + std::to_string(flags));
552 }
553
554 *_aidl_return = android::base::unique_fd(fd);
555 return Ok();
556 }
557
fbeEnable()558 binder::Status VoldNativeService::fbeEnable() {
559 ENFORCE_SYSTEM_OR_ROOT;
560 ACQUIRE_CRYPT_LOCK;
561
562 return translateBool(fscrypt_initialize_systemwide_keys());
563 }
564
initUser0()565 binder::Status VoldNativeService::initUser0() {
566 ENFORCE_SYSTEM_OR_ROOT;
567 ACQUIRE_CRYPT_LOCK;
568
569 return translateBool(fscrypt_init_user0());
570 }
571
mountFstab(const std::string & blkDevice,const std::string & mountPoint,const std::string & zonedDevice)572 binder::Status VoldNativeService::mountFstab(const std::string& blkDevice,
573 const std::string& mountPoint,
574 const std::string& zonedDevice) {
575 ENFORCE_SYSTEM_OR_ROOT;
576 ACQUIRE_LOCK;
577
578 return translateBool(fscrypt_mount_metadata_encrypted(blkDevice, mountPoint, false, false,
579 "null", zonedDevice));
580 }
581
encryptFstab(const std::string & blkDevice,const std::string & mountPoint,bool shouldFormat,const std::string & fsType,const std::string & zonedDevice)582 binder::Status VoldNativeService::encryptFstab(const std::string& blkDevice,
583 const std::string& mountPoint, bool shouldFormat,
584 const std::string& fsType,
585 const std::string& zonedDevice) {
586 ENFORCE_SYSTEM_OR_ROOT;
587 ACQUIRE_LOCK;
588
589 return translateBool(fscrypt_mount_metadata_encrypted(blkDevice, mountPoint, true, shouldFormat,
590 fsType, zonedDevice));
591 }
592
setStorageBindingSeed(const std::vector<uint8_t> & seed)593 binder::Status VoldNativeService::setStorageBindingSeed(const std::vector<uint8_t>& seed) {
594 ENFORCE_SYSTEM_OR_ROOT;
595 ACQUIRE_CRYPT_LOCK;
596
597 return translateBool(setKeyStorageBindingSeed(seed));
598 }
599
createUserKey(int32_t userId,int32_t userSerial,bool ephemeral)600 binder::Status VoldNativeService::createUserKey(int32_t userId, int32_t userSerial,
601 bool ephemeral) {
602 ENFORCE_SYSTEM_OR_ROOT;
603 ACQUIRE_CRYPT_LOCK;
604
605 return translateBool(fscrypt_vold_create_user_key(userId, userSerial, ephemeral));
606 }
607
destroyUserKey(int32_t userId)608 binder::Status VoldNativeService::destroyUserKey(int32_t userId) {
609 ENFORCE_SYSTEM_OR_ROOT;
610 ACQUIRE_CRYPT_LOCK;
611
612 return translateBool(fscrypt_destroy_user_key(userId));
613 }
614
setUserKeyProtection(int32_t userId,const std::string & secret)615 binder::Status VoldNativeService::setUserKeyProtection(int32_t userId, const std::string& secret) {
616 ENFORCE_SYSTEM_OR_ROOT;
617 ACQUIRE_CRYPT_LOCK;
618
619 return translateBool(fscrypt_set_user_key_protection(userId, secret));
620 }
621
getUnlockedUsers(std::vector<int> * _aidl_return)622 binder::Status VoldNativeService::getUnlockedUsers(std::vector<int>* _aidl_return) {
623 ENFORCE_SYSTEM_OR_ROOT;
624 ACQUIRE_CRYPT_LOCK;
625
626 *_aidl_return = fscrypt_get_unlocked_users();
627 return Ok();
628 }
629
unlockUserKey(int32_t userId,int32_t userSerial,const std::string & secret)630 binder::Status VoldNativeService::unlockUserKey(int32_t userId, int32_t userSerial,
631 const std::string& secret) {
632 ENFORCE_SYSTEM_OR_ROOT;
633 ACQUIRE_CRYPT_LOCK;
634
635 return translateBool(fscrypt_unlock_user_key(userId, userSerial, secret));
636 }
637
lockUserKey(int32_t userId)638 binder::Status VoldNativeService::lockUserKey(int32_t userId) {
639 ENFORCE_SYSTEM_OR_ROOT;
640 ACQUIRE_CRYPT_LOCK;
641
642 return translateBool(fscrypt_lock_user_key(userId));
643 }
644
prepareUserStorage(const std::optional<std::string> & uuid,int32_t userId,int32_t userSerial,int32_t flags)645 binder::Status VoldNativeService::prepareUserStorage(const std::optional<std::string>& uuid,
646 int32_t userId, int32_t userSerial,
647 int32_t flags) {
648 ENFORCE_SYSTEM_OR_ROOT;
649 std::string empty_string = "";
650 auto uuid_ = uuid ? *uuid : empty_string;
651 CHECK_ARGUMENT_HEX(uuid_);
652
653 ACQUIRE_CRYPT_LOCK;
654 return translateBool(fscrypt_prepare_user_storage(uuid_, userId, userSerial, flags));
655 }
656
destroyUserStorage(const std::optional<std::string> & uuid,int32_t userId,int32_t flags)657 binder::Status VoldNativeService::destroyUserStorage(const std::optional<std::string>& uuid,
658 int32_t userId, int32_t flags) {
659 ENFORCE_SYSTEM_OR_ROOT;
660 std::string empty_string = "";
661 auto uuid_ = uuid ? *uuid : empty_string;
662 CHECK_ARGUMENT_HEX(uuid_);
663
664 ACQUIRE_CRYPT_LOCK;
665 return translateBool(fscrypt_destroy_user_storage(uuid_, userId, flags));
666 }
667
prepareSandboxForApp(const std::string & packageName,int32_t appId,const std::string & sandboxId,int32_t userId)668 binder::Status VoldNativeService::prepareSandboxForApp(const std::string& packageName,
669 int32_t appId, const std::string& sandboxId,
670 int32_t userId) {
671 return Ok();
672 }
673
destroySandboxForApp(const std::string & packageName,const std::string & sandboxId,int32_t userId)674 binder::Status VoldNativeService::destroySandboxForApp(const std::string& packageName,
675 const std::string& sandboxId,
676 int32_t userId) {
677 return Ok();
678 }
679
startCheckpoint(int32_t retry)680 binder::Status VoldNativeService::startCheckpoint(int32_t retry) {
681 ENFORCE_SYSTEM_OR_ROOT;
682 ACQUIRE_LOCK;
683
684 return cp_startCheckpoint(retry);
685 }
686
needsRollback(bool * _aidl_return)687 binder::Status VoldNativeService::needsRollback(bool* _aidl_return) {
688 ENFORCE_SYSTEM_OR_ROOT;
689 ACQUIRE_LOCK;
690
691 *_aidl_return = cp_needsRollback();
692 return Ok();
693 }
694
needsCheckpoint(bool * _aidl_return)695 binder::Status VoldNativeService::needsCheckpoint(bool* _aidl_return) {
696 ENFORCE_SYSTEM_OR_ROOT;
697 ACQUIRE_LOCK;
698
699 *_aidl_return = cp_needsCheckpoint();
700 return Ok();
701 }
702
isCheckpointing(bool * _aidl_return)703 binder::Status VoldNativeService::isCheckpointing(bool* _aidl_return) {
704 ENFORCE_SYSTEM_OR_ROOT;
705 ACQUIRE_LOCK;
706
707 *_aidl_return = cp_isCheckpointing();
708 return Ok();
709 }
710
commitChanges()711 binder::Status VoldNativeService::commitChanges() {
712 ENFORCE_SYSTEM_OR_ROOT;
713 ACQUIRE_LOCK;
714
715 return cp_commitChanges();
716 }
717
prepareCheckpoint()718 binder::Status VoldNativeService::prepareCheckpoint() {
719 ENFORCE_SYSTEM_OR_ROOT;
720 ACQUIRE_LOCK;
721
722 return cp_prepareCheckpoint();
723 }
724
restoreCheckpoint(const std::string & mountPoint)725 binder::Status VoldNativeService::restoreCheckpoint(const std::string& mountPoint) {
726 ENFORCE_SYSTEM_OR_ROOT;
727 CHECK_ARGUMENT_PATH(mountPoint);
728 ACQUIRE_LOCK;
729
730 return cp_restoreCheckpoint(mountPoint);
731 }
732
restoreCheckpointPart(const std::string & mountPoint,int count)733 binder::Status VoldNativeService::restoreCheckpointPart(const std::string& mountPoint, int count) {
734 ENFORCE_SYSTEM_OR_ROOT;
735 CHECK_ARGUMENT_PATH(mountPoint);
736 ACQUIRE_LOCK;
737
738 return cp_restoreCheckpoint(mountPoint, count);
739 }
740
markBootAttempt()741 binder::Status VoldNativeService::markBootAttempt() {
742 ENFORCE_SYSTEM_OR_ROOT;
743 ACQUIRE_LOCK;
744
745 return cp_markBootAttempt();
746 }
747
abortChanges(const std::string & message,bool retry)748 binder::Status VoldNativeService::abortChanges(const std::string& message, bool retry) {
749 ENFORCE_SYSTEM_OR_ROOT;
750 ACQUIRE_LOCK;
751
752 cp_abortChanges(message, retry);
753 return Ok();
754 }
755
supportsCheckpoint(bool * _aidl_return)756 binder::Status VoldNativeService::supportsCheckpoint(bool* _aidl_return) {
757 ENFORCE_SYSTEM_OR_ROOT;
758 ACQUIRE_LOCK;
759
760 return cp_supportsCheckpoint(*_aidl_return);
761 }
762
supportsBlockCheckpoint(bool * _aidl_return)763 binder::Status VoldNativeService::supportsBlockCheckpoint(bool* _aidl_return) {
764 ENFORCE_SYSTEM_OR_ROOT;
765 ACQUIRE_LOCK;
766
767 return cp_supportsBlockCheckpoint(*_aidl_return);
768 }
769
supportsFileCheckpoint(bool * _aidl_return)770 binder::Status VoldNativeService::supportsFileCheckpoint(bool* _aidl_return) {
771 ENFORCE_SYSTEM_OR_ROOT;
772 ACQUIRE_LOCK;
773
774 return cp_supportsFileCheckpoint(*_aidl_return);
775 }
776
resetCheckpoint()777 binder::Status VoldNativeService::resetCheckpoint() {
778 ENFORCE_SYSTEM_OR_ROOT;
779 ACQUIRE_LOCK;
780
781 cp_resetCheckpoint();
782 return Ok();
783 }
784
initializeIncFs()785 static void initializeIncFs() {
786 // Obtaining IncFS features triggers initialization of IncFS.
787 incfs::features();
788 }
789
earlyBootEnded()790 binder::Status VoldNativeService::earlyBootEnded() {
791 ENFORCE_SYSTEM_OR_ROOT;
792 ACQUIRE_LOCK;
793
794 initializeIncFs();
795 Keystore::earlyBootEnded();
796 return Ok();
797 }
798
incFsEnabled(bool * _aidl_return)799 binder::Status VoldNativeService::incFsEnabled(bool* _aidl_return) {
800 ENFORCE_SYSTEM_OR_ROOT;
801
802 *_aidl_return = incfs::enabled();
803 return Ok();
804 }
805
mountIncFs(const std::string & backingPath,const std::string & targetDir,int32_t flags,const std::string & sysfsName,::android::os::incremental::IncrementalFileSystemControlParcel * _aidl_return)806 binder::Status VoldNativeService::mountIncFs(
807 const std::string& backingPath, const std::string& targetDir, int32_t flags,
808 const std::string& sysfsName,
809 ::android::os::incremental::IncrementalFileSystemControlParcel* _aidl_return) {
810 ENFORCE_SYSTEM_OR_ROOT;
811 if (auto status = CheckIncrementalPath(IncrementalPathKind::MountTarget, targetDir);
812 !status.isOk()) {
813 return status;
814 }
815 if (auto status = CheckIncrementalPath(IncrementalPathKind::MountSource, backingPath);
816 !status.isOk()) {
817 return status;
818 }
819
820 auto [backingFd, backingSymlink] = OpenDirInProcfs(backingPath);
821 if (!backingFd.ok()) {
822 return translate(-errno);
823 }
824 auto [targetFd, targetSymlink] = OpenDirInProcfs(targetDir);
825 if (!targetFd.ok()) {
826 return translate(-errno);
827 }
828
829 auto control = incfs::mount(backingSymlink, targetSymlink,
830 {.flags = IncFsMountFlags(flags),
831 // Mount with read timeouts.
832 .defaultReadTimeoutMs = INCFS_DEFAULT_READ_TIMEOUT_MS,
833 // Mount with read logs disabled.
834 .readLogBufferPages = 0,
835 .sysfsName = sysfsName.c_str()});
836 if (!control) {
837 return translate(-errno);
838 }
839 auto fds = control.releaseFds();
840 using android::base::unique_fd;
841 _aidl_return->cmd.reset(unique_fd(fds[CMD].release()));
842 _aidl_return->pendingReads.reset(unique_fd(fds[PENDING_READS].release()));
843 _aidl_return->log.reset(unique_fd(fds[LOGS].release()));
844 if (fds[BLOCKS_WRITTEN].ok()) {
845 _aidl_return->blocksWritten.emplace(unique_fd(fds[BLOCKS_WRITTEN].release()));
846 }
847 return Ok();
848 }
849
unmountIncFs(const std::string & dir)850 binder::Status VoldNativeService::unmountIncFs(const std::string& dir) {
851 ENFORCE_SYSTEM_OR_ROOT;
852 if (auto status = CheckIncrementalPath(IncrementalPathKind::Any, dir); !status.isOk()) {
853 return status;
854 }
855
856 auto [fd, symLink] = OpenDirInProcfs(dir);
857 if (!fd.ok()) {
858 return translate(-errno);
859 }
860 return translate(incfs::unmount(symLink));
861 }
862
setIncFsMountOptions(const::android::os::incremental::IncrementalFileSystemControlParcel & control,bool enableReadLogs,bool enableReadTimeouts,const std::string & sysfsName)863 binder::Status VoldNativeService::setIncFsMountOptions(
864 const ::android::os::incremental::IncrementalFileSystemControlParcel& control,
865 bool enableReadLogs, bool enableReadTimeouts, const std::string& sysfsName) {
866 ENFORCE_SYSTEM_OR_ROOT;
867
868 auto incfsControl =
869 incfs::createControl(control.cmd.get(), control.pendingReads.get(), control.log.get(),
870 control.blocksWritten ? control.blocksWritten->get() : -1);
871 auto cleanupFunc = [](auto incfsControl) {
872 for (auto& fd : incfsControl->releaseFds()) {
873 (void)fd.release();
874 }
875 };
876 auto cleanup =
877 std::unique_ptr<incfs::Control, decltype(cleanupFunc)>(&incfsControl, cleanupFunc);
878
879 constexpr auto minReadLogBufferPages = INCFS_DEFAULT_PAGE_READ_BUFFER_PAGES;
880 constexpr auto maxReadLogBufferPages = 8 * INCFS_DEFAULT_PAGE_READ_BUFFER_PAGES;
881 auto options = incfs::MountOptions{
882 .defaultReadTimeoutMs =
883 enableReadTimeouts ? INCFS_DEFAULT_READ_TIMEOUT_MS : kIncFsReadNoTimeoutMs,
884 .readLogBufferPages = enableReadLogs ? maxReadLogBufferPages : 0,
885 .sysfsName = sysfsName.c_str()};
886
887 for (;;) {
888 const auto error = incfs::setOptions(incfsControl, options);
889 if (!error) {
890 return Ok();
891 }
892 if (!enableReadLogs || error != -ENOMEM) {
893 return binder::Status::fromServiceSpecificError(error);
894 }
895 // In case of memory allocation error retry with a smaller buffer.
896 options.readLogBufferPages /= 2;
897 if (options.readLogBufferPages < minReadLogBufferPages) {
898 return binder::Status::fromServiceSpecificError(error);
899 }
900 }
901 // unreachable, but makes the compiler happy
902 return Ok();
903 }
904
bindMount(const std::string & sourceDir,const std::string & targetDir)905 binder::Status VoldNativeService::bindMount(const std::string& sourceDir,
906 const std::string& targetDir) {
907 ENFORCE_SYSTEM_OR_ROOT;
908 if (auto status = CheckIncrementalPath(IncrementalPathKind::Any, sourceDir); !status.isOk()) {
909 return status;
910 }
911 if (auto status = CheckIncrementalPath(IncrementalPathKind::Bind, targetDir); !status.isOk()) {
912 return status;
913 }
914
915 auto [sourceFd, sourceSymlink] = OpenDirInProcfs(sourceDir);
916 if (!sourceFd.ok()) {
917 return translate(-errno);
918 }
919 auto [targetFd, targetSymlink] = OpenDirInProcfs(targetDir);
920 if (!targetFd.ok()) {
921 return translate(-errno);
922 }
923 return translate(incfs::bindMount(sourceSymlink, targetSymlink));
924 }
925
destroyDsuMetadataKey(const std::string & dsuSlot)926 binder::Status VoldNativeService::destroyDsuMetadataKey(const std::string& dsuSlot) {
927 ENFORCE_SYSTEM_OR_ROOT;
928 ACQUIRE_LOCK;
929
930 return translateBool(destroy_dsu_metadata_key(dsuSlot));
931 }
932
getStorageSize(int64_t * storageSize)933 binder::Status VoldNativeService::getStorageSize(int64_t* storageSize) {
934 ENFORCE_SYSTEM_OR_ROOT;
935 return translate(GetStorageSize(storageSize));
936 }
937
938 } // namespace vold
939 } // namespace android
940