1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "PublicVolume.h"
18 
19 #include "AppFuseUtil.h"
20 #include "Utils.h"
21 #include "VolumeManager.h"
22 #include "fs/Exfat.h"
23 #include "fs/Vfat.h"
24 
25 #include <android-base/logging.h>
26 #include <android-base/properties.h>
27 #include <android-base/stringprintf.h>
28 #include <cutils/fs.h>
29 #include <private/android_filesystem_config.h>
30 #include <utils/Timers.h>
31 
32 #include <fcntl.h>
33 #include <stdlib.h>
34 #include <sys/mount.h>
35 #include <sys/stat.h>
36 #include <sys/sysmacros.h>
37 #include <sys/types.h>
38 #include <sys/wait.h>
39 
40 using android::base::GetBoolProperty;
41 using android::base::StringPrintf;
42 
43 namespace android {
44 namespace vold {
45 
46 static const char* kSdcardFsPath = "/system/bin/sdcard";
47 
48 static const char* kAsecPath = "/mnt/secure/asec";
49 
PublicVolume(dev_t device)50 PublicVolume::PublicVolume(dev_t device) : VolumeBase(Type::kPublic), mDevice(device) {
51     setId(StringPrintf("public:%u,%u", major(device), minor(device)));
52     mDevPath = StringPrintf("/dev/block/vold/%s", getId().c_str());
53     mFuseMounted = false;
54     mUseSdcardFs = IsSdcardfsUsed();
55 }
56 
~PublicVolume()57 PublicVolume::~PublicVolume() {}
58 
readMetadata()59 status_t PublicVolume::readMetadata() {
60     status_t res = ReadMetadataUntrusted(mDevPath, &mFsType, &mFsUuid, &mFsLabel);
61 
62     auto listener = getListener();
63     if (listener) listener->onVolumeMetadataChanged(getId(), mFsType, mFsUuid, mFsLabel);
64 
65     return res;
66 }
67 
initAsecStage()68 status_t PublicVolume::initAsecStage() {
69     std::string legacyPath(mRawPath + "/android_secure");
70     std::string securePath(mRawPath + "/.android_secure");
71 
72     // Recover legacy secure path
73     if (!access(legacyPath.c_str(), R_OK | X_OK) && access(securePath.c_str(), R_OK | X_OK)) {
74         if (rename(legacyPath.c_str(), securePath.c_str())) {
75             PLOG(WARNING) << getId() << " failed to rename legacy ASEC dir";
76         }
77     }
78 
79     if (TEMP_FAILURE_RETRY(mkdir(securePath.c_str(), 0700))) {
80         if (errno != EEXIST) {
81             PLOG(WARNING) << getId() << " creating ASEC stage failed";
82             return -errno;
83         }
84     }
85 
86     BindMount(securePath, kAsecPath);
87 
88     return OK;
89 }
90 
doCreate()91 status_t PublicVolume::doCreate() {
92     return CreateDeviceNode(mDevPath, mDevice);
93 }
94 
doDestroy()95 status_t PublicVolume::doDestroy() {
96     return DestroyDeviceNode(mDevPath);
97 }
98 
doMount()99 status_t PublicVolume::doMount() {
100     bool isVisible = isVisibleForWrite();
101     readMetadata();
102 
103     if (mFsType == "vfat" && vfat::IsSupported()) {
104         if (vfat::Check(mDevPath)) {
105             LOG(ERROR) << getId() << " failed filesystem check";
106             return -EIO;
107         }
108     } else if (mFsType == "exfat" && exfat::IsSupported()) {
109         if (exfat::Check(mDevPath)) {
110             LOG(ERROR) << getId() << " failed filesystem check";
111             return -EIO;
112         }
113     } else {
114         LOG(ERROR) << getId() << " unsupported filesystem " << mFsType;
115         return -EIO;
116     }
117 
118     // Use UUID as stable name, if available
119     std::string stableName = getId();
120     if (!mFsUuid.empty()) {
121         stableName = mFsUuid;
122     }
123 
124     mRawPath = StringPrintf("/mnt/media_rw/%s", stableName.c_str());
125 
126     mSdcardFsDefault = StringPrintf("/mnt/runtime/default/%s", stableName.c_str());
127     mSdcardFsRead = StringPrintf("/mnt/runtime/read/%s", stableName.c_str());
128     mSdcardFsWrite = StringPrintf("/mnt/runtime/write/%s", stableName.c_str());
129     mSdcardFsFull = StringPrintf("/mnt/runtime/full/%s", stableName.c_str());
130 
131     setInternalPath(mRawPath);
132     if (isVisible) {
133         setPath(StringPrintf("/storage/%s", stableName.c_str()));
134     } else {
135         setPath(mRawPath);
136     }
137 
138     if (fs_prepare_dir(mRawPath.c_str(), 0700, AID_ROOT, AID_ROOT)) {
139         PLOG(ERROR) << getId() << " failed to create mount points";
140         return -errno;
141     }
142 
143     if (mFsType == "vfat") {
144         if (vfat::Mount(mDevPath, mRawPath, false, false, false, AID_ROOT,
145                         (isVisible ? AID_MEDIA_RW : AID_EXTERNAL_STORAGE), 0007, true)) {
146             PLOG(ERROR) << getId() << " failed to mount " << mDevPath;
147             return -EIO;
148         }
149     } else if (mFsType == "exfat") {
150         if (exfat::Mount(mDevPath, mRawPath, AID_ROOT,
151                          (isVisible ? AID_MEDIA_RW : AID_EXTERNAL_STORAGE), 0007)) {
152             PLOG(ERROR) << getId() << " failed to mount " << mDevPath;
153             return -EIO;
154         }
155     }
156 
157     if (getMountFlags() & MountFlags::kPrimary) {
158         initAsecStage();
159     }
160 
161     if (!isVisible) {
162         // Not visible to apps, so no need to spin up sdcardfs or FUSE
163         return OK;
164     }
165 
166     if (mUseSdcardFs) {
167         if (fs_prepare_dir(mSdcardFsDefault.c_str(), 0700, AID_ROOT, AID_ROOT) ||
168             fs_prepare_dir(mSdcardFsRead.c_str(), 0700, AID_ROOT, AID_ROOT) ||
169             fs_prepare_dir(mSdcardFsWrite.c_str(), 0700, AID_ROOT, AID_ROOT) ||
170             fs_prepare_dir(mSdcardFsFull.c_str(), 0700, AID_ROOT, AID_ROOT)) {
171             PLOG(ERROR) << getId() << " failed to create sdcardfs mount points";
172             return -errno;
173         }
174 
175         dev_t before = GetDevice(mSdcardFsFull);
176 
177         int sdcardFsPid;
178         if (!(sdcardFsPid = fork())) {
179             if (getMountFlags() & MountFlags::kPrimary) {
180                 // clang-format off
181                 if (execl(kSdcardFsPath, kSdcardFsPath,
182                         "-u", "1023", // AID_MEDIA_RW
183                         "-g", "1023", // AID_MEDIA_RW
184                         "-U", std::to_string(getMountUserId()).c_str(),
185                         "-w",
186                         mRawPath.c_str(),
187                         stableName.c_str(),
188                         NULL)) {
189                     // clang-format on
190                     PLOG(ERROR) << "Failed to exec";
191                 }
192             } else {
193                 // clang-format off
194                 if (execl(kSdcardFsPath, kSdcardFsPath,
195                         "-u", "1023", // AID_MEDIA_RW
196                         "-g", "1023", // AID_MEDIA_RW
197                         "-U", std::to_string(getMountUserId()).c_str(),
198                         mRawPath.c_str(),
199                         stableName.c_str(),
200                         NULL)) {
201                     // clang-format on
202                     PLOG(ERROR) << "Failed to exec";
203                 }
204             }
205 
206             LOG(ERROR) << "sdcardfs exiting";
207             _exit(1);
208         }
209 
210         if (sdcardFsPid == -1) {
211             PLOG(ERROR) << getId() << " failed to fork";
212             return -errno;
213         }
214 
215         nsecs_t start = systemTime(SYSTEM_TIME_BOOTTIME);
216         while (before == GetDevice(mSdcardFsFull)) {
217             LOG(DEBUG) << "Waiting for sdcardfs to spin up...";
218             usleep(50000);  // 50ms
219 
220             nsecs_t now = systemTime(SYSTEM_TIME_BOOTTIME);
221             if (nanoseconds_to_milliseconds(now - start) > 5000) {
222                 LOG(WARNING) << "Timed out while waiting for sdcardfs to spin up";
223                 return -ETIMEDOUT;
224             }
225         }
226         /* sdcardfs will have exited already. The filesystem will still be running */
227         TEMP_FAILURE_RETRY(waitpid(sdcardFsPid, nullptr, 0));
228     }
229 
230     // We need to mount FUSE *after* sdcardfs, since the FUSE daemon may depend
231     // on sdcardfs being up.
232     LOG(INFO) << "Mounting public fuse volume";
233     android::base::unique_fd fd;
234     int user_id = getMountUserId();
235     int result = MountUserFuse(user_id, getInternalPath(), stableName, &fd);
236 
237     if (result != 0) {
238         LOG(ERROR) << "Failed to mount public fuse volume";
239         doUnmount();
240         return -result;
241     }
242 
243     mFuseMounted = true;
244     auto callback = getMountCallback();
245     if (callback) {
246         bool is_ready = false;
247         callback->onVolumeChecking(std::move(fd), getPath(), getInternalPath(), &is_ready);
248         if (!is_ready) {
249             LOG(ERROR) << "Failed to complete public volume mount";
250             doUnmount();
251             return -EIO;
252         }
253     }
254 
255     ConfigureReadAheadForFuse(GetFuseMountPathForUser(user_id, stableName), 256u);
256 
257     // See comment in model/EmulatedVolume.cpp
258     ConfigureMaxDirtyRatioForFuse(GetFuseMountPathForUser(user_id, stableName), 40u);
259 
260     auto vol_manager = VolumeManager::Instance();
261     // Create bind mounts for all running users
262     for (userid_t started_user : vol_manager->getStartedUsers()) {
263         userid_t mountUserId = getMountUserId();
264         if (started_user == mountUserId) {
265             // No need to bind mount for the user that owns the mount
266             continue;
267         }
268         if (mountUserId != VolumeManager::Instance()->getSharedStorageUser(started_user)) {
269             // No need to bind if the user does not share storage with the mount owner
270             continue;
271         }
272         auto bindMountStatus = bindMountForUser(started_user);
273         if (bindMountStatus != OK) {
274             LOG(ERROR) << "Bind Mounting Public Volume: " << stableName
275                        << " for user: " << started_user << "Failed. Error: " << bindMountStatus;
276         }
277     }
278     return OK;
279 }
280 
bindMountForUser(userid_t user_id)281 status_t PublicVolume::bindMountForUser(userid_t user_id) {
282     userid_t mountUserId = getMountUserId();
283     std::string stableName = getId();
284     if (!mFsUuid.empty()) {
285         stableName = mFsUuid;
286     }
287 
288     LOG(INFO) << "Bind Mounting Public Volume for user: " << user_id
289               << ".Mount owner: " << mountUserId;
290     auto sourcePath = GetFuseMountPathForUser(mountUserId, stableName);
291     auto destPath = GetFuseMountPathForUser(user_id, stableName);
292     PrepareDir(destPath, 0770, AID_ROOT, AID_MEDIA_RW);
293     auto mountRes = BindMount(sourcePath, destPath);
294     LOG(INFO) << "Mount status: " << mountRes;
295 
296     return mountRes;
297 }
298 
doUnmount()299 status_t PublicVolume::doUnmount() {
300     // Unmount the storage before we kill the FUSE process. If we kill
301     // the FUSE process first, most file system operations will return
302     // ENOTCONN until the unmount completes. This is an exotic and unusual
303     // error code and might cause broken behaviour in applications.
304     KillProcessesUsingPath(getPath());
305 
306     if (mFuseMounted) {
307         // Use UUID as stable name, if available
308         std::string stableName = getId();
309         if (!mFsUuid.empty()) {
310             stableName = mFsUuid;
311         }
312 
313         // Unmount bind mounts for running users
314         auto vol_manager = VolumeManager::Instance();
315         int user_id = getMountUserId();
316         for (int started_user : vol_manager->getStartedUsers()) {
317             if (started_user == user_id) {
318                 // No need to remove bind mount for the user that owns the mount
319                 continue;
320             }
321             LOG(INFO) << "Removing Public Volume Bind Mount for: " << started_user;
322             auto mountPath = GetFuseMountPathForUser(started_user, stableName);
323             ForceUnmount(mountPath);
324             rmdir(mountPath.c_str());
325         }
326 
327         if (UnmountUserFuse(getMountUserId(), getInternalPath(), stableName) != OK) {
328             PLOG(INFO) << "UnmountUserFuse failed on public fuse volume";
329             return -errno;
330         }
331 
332         mFuseMounted = false;
333     }
334 
335     ForceUnmount(kAsecPath);
336 
337     if (mUseSdcardFs) {
338         ForceUnmount(mSdcardFsDefault);
339         ForceUnmount(mSdcardFsRead);
340         ForceUnmount(mSdcardFsWrite);
341         ForceUnmount(mSdcardFsFull);
342 
343         rmdir(mSdcardFsDefault.c_str());
344         rmdir(mSdcardFsRead.c_str());
345         rmdir(mSdcardFsWrite.c_str());
346         rmdir(mSdcardFsFull.c_str());
347 
348         mSdcardFsDefault.clear();
349         mSdcardFsRead.clear();
350         mSdcardFsWrite.clear();
351         mSdcardFsFull.clear();
352     }
353 
354     if (ForceUnmount(mRawPath) != 0){
355         umount2(mRawPath.c_str(),MNT_DETACH);
356         PLOG(INFO) << "use umount lazy if force unmount fail";
357     }
358     if(rmdir(mRawPath.c_str()) != 0) {
359         PLOG(INFO) << "rmdir mRawPath=" << mRawPath << " fail";
360         KillProcessesUsingPath(getPath());
361     }
362     mRawPath.clear();
363 
364     return OK;
365 }
366 
doFormat(const std::string & fsType)367 status_t PublicVolume::doFormat(const std::string& fsType) {
368     bool isVfatSup = vfat::IsSupported();
369     bool isExfatSup = exfat::IsSupported();
370     status_t res = OK;
371 
372     enum { NONE, VFAT, EXFAT } fsPick = NONE;
373 
374     // Resolve auto requests
375     if (fsType == "auto" && isVfatSup && isExfatSup) {
376         uint64_t size = 0;
377 
378         res = GetBlockDevSize(mDevPath, &size);
379         if (res != OK) {
380             LOG(ERROR) << "Couldn't get device size " << mDevPath;
381             return res;
382         }
383 
384         // If both vfat & exfat are supported use exfat for SDXC (>~32GiB) cards
385         if (size > 32896LL * 1024 * 1024) {
386             fsPick = EXFAT;
387         } else {
388             fsPick = VFAT;
389         }
390     } else if (fsType == "auto" && isExfatSup) {
391         fsPick = EXFAT;
392     } else if (fsType == "auto" && isVfatSup) {
393         fsPick = VFAT;
394     }
395 
396     // Resolve explicit requests
397     if (fsType == "vfat" && isVfatSup) {
398         fsPick = VFAT;
399     } else if (fsType == "exfat" && isExfatSup) {
400         fsPick = EXFAT;
401     }
402 
403     if (WipeBlockDevice(mDevPath) != OK) {
404         LOG(WARNING) << getId() << " failed to wipe";
405     }
406 
407     if (fsPick == VFAT) {
408         res = vfat::Format(mDevPath, 0);
409     } else if (fsPick == EXFAT) {
410         res = exfat::Format(mDevPath);
411     } else {
412         LOG(ERROR) << "Unsupported filesystem " << fsType;
413         return -EINVAL;
414     }
415 
416     if (res != OK) {
417         LOG(ERROR) << getId() << " failed to format";
418         res = -errno;
419     }
420 
421     return res;
422 }
423 
424 }  // namespace vold
425 }  // namespace android
426