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 #ifndef ANDROID_VOLD_UTILS_H
18 #define ANDROID_VOLD_UTILS_H
19 
20 #include "KeyBuffer.h"
21 
22 #include <android-base/macros.h>
23 #include <android-base/unique_fd.h>
24 #include <cutils/multiuser.h>
25 #include <selinux/selinux.h>
26 #include <utils/Errors.h>
27 
28 #include <chrono>
29 #include <string>
30 #include <string_view>
31 #include <vector>
32 
33 struct DIR;
34 
35 namespace android {
36 namespace vold {
37 
38 static const char* kVoldAppDataIsolationEnabled = "persist.sys.vold_app_data_isolation_enabled";
39 static const char* kExternalStorageSdcardfs = "external_storage.sdcardfs.enabled";
40 
41 static constexpr std::chrono::seconds kUntrustedFsckSleepTime(45);
42 
43 /* SELinux contexts used depending on the block device type */
44 extern char* sBlkidContext;
45 extern char* sBlkidUntrustedContext;
46 extern char* sFsckContext;
47 extern char* sFsckUntrustedContext;
48 
49 // TODO remove this with better solution, b/64143519
50 extern bool sSleepOnUnmount;
51 
52 std::string GetFuseMountPathForUser(userid_t user_id, const std::string& relative_upper_path);
53 
54 status_t CreateDeviceNode(const std::string& path, dev_t dev);
55 status_t DestroyDeviceNode(const std::string& path);
56 
57 status_t SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
58                        std::vector<gid_t> additionalGids);
59 
60 status_t AbortFuseConnections();
61 
62 int SetQuotaInherit(const std::string& path);
63 int SetQuotaProjectId(const std::string& path, long projectId);
64 /*
65  * Creates and sets up an application-specific path on external
66  * storage with the correct ACL and project ID (if needed).
67  *
68  * ONLY for use with app-specific data directories on external storage!
69  * (eg, /Android/data/com.foo, /Android/obb/com.foo, etc.)
70  */
71 int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
72                           bool fixupExisting);
73 
74 /* fs_prepare_dir wrapper that creates with SELinux context */
75 status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
76                     unsigned int attrs = 0);
77 
78 /* Really unmounts the path, killing active processes along the way */
79 status_t ForceUnmount(const std::string& path);
80 
81 /* Kills any processes using given path */
82 status_t KillProcessesUsingPath(const std::string& path);
83 
84 /* Kills any processes using given tmpfs mount prifix */
85 status_t KillProcessesWithTmpfsMountPrefix(const std::string& path);
86 
87 /* Creates bind mount from source to target */
88 status_t BindMount(const std::string& source, const std::string& target);
89 
90 /** Creates a symbolic link to target */
91 status_t Symlink(const std::string& target, const std::string& linkpath);
92 
93 /** Calls unlink(2) at linkpath */
94 status_t Unlink(const std::string& linkpath);
95 
96 /** Creates the given directory if it is not already available */
97 status_t CreateDir(const std::string& dir, mode_t mode);
98 
99 bool FindValue(const std::string& raw, const std::string& key, std::string* value);
100 
101 /* Reads filesystem metadata from device at path */
102 status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
103                       std::string* fsLabel);
104 
105 /* Reads filesystem metadata from untrusted device at path */
106 status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
107                                std::string* fsLabel);
108 
109 /* Returns either WEXITSTATUS() status, or a negative errno */
110 status_t ForkExecvp(const std::vector<std::string>& args,
111                     std::vector<std::string>* output = nullptr, char* context = nullptr);
112 status_t ForkExecvpTimeout(const std::vector<std::string>& args, std::chrono::seconds timeout,
113                            char* context = nullptr);
114 
115 pid_t ForkExecvpAsync(const std::vector<std::string>& args, char* context = nullptr);
116 
117 /* Gets block device size in bytes */
118 status_t GetBlockDevSize(int fd, uint64_t* size);
119 status_t GetBlockDevSize(const std::string& path, uint64_t* size);
120 /* Gets block device size in 512 byte sectors */
121 status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec);
122 
123 status_t ReadRandomBytes(size_t bytes, std::string& out);
124 status_t ReadRandomBytes(size_t bytes, char* buffer);
125 status_t GenerateRandomUuid(std::string& out);
126 
127 /* Converts hex string to raw bytes, ignoring [ :-] */
128 status_t HexToStr(const std::string& hex, std::string& str);
129 /* Converts raw bytes to hex string */
130 status_t StrToHex(const std::string& str, std::string& hex);
131 /* Converts raw key bytes to hex string */
132 status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex);
133 /* Normalize given hex string into consistent format */
134 status_t NormalizeHex(const std::string& in, std::string& out);
135 
136 uint64_t GetFreeBytes(const std::string& path);
137 uint64_t GetTreeBytes(const std::string& path);
138 
139 bool IsFilesystemSupported(const std::string& fsType);
140 bool IsSdcardfsUsed();
141 bool IsFuseDaemon(const pid_t pid);
142 
143 /* Wipes contents of block device at given path */
144 status_t WipeBlockDevice(const std::string& path);
145 
146 std::string BuildKeyPath(const std::string& partGuid);
147 
148 std::string BuildDataSystemLegacyPath(userid_t userid);
149 std::string BuildDataSystemCePath(userid_t userid);
150 std::string BuildDataSystemDePath(userid_t userid);
151 std::string BuildDataProfilesDePath(userid_t userid);
152 std::string BuildDataVendorCePath(userid_t userid);
153 std::string BuildDataVendorDePath(userid_t userid);
154 
155 std::string BuildDataPath(const std::string& volumeUuid);
156 std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userid);
157 std::string BuildDataMiscCePath(const std::string& volumeUuid, userid_t userid);
158 std::string BuildDataMiscDePath(const std::string& volumeUuid, userid_t userid);
159 std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userid);
160 std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userid);
161 
162 dev_t GetDevice(const std::string& path);
163 
164 bool IsSymlink(const std::string& path);
165 
166 bool IsSameFile(const std::string& path1, const std::string& path2);
167 
168 status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid);
169 
170 status_t RestoreconRecursive(const std::string& path);
171 
172 // TODO: promote to android::base
173 bool Readlinkat(int dirfd, const std::string& path, std::string* result);
174 
175 // Handles dynamic major assignment for virtio-block
176 bool IsVirtioBlkDevice(unsigned int major);
177 
178 status_t UnmountTree(const std::string& mountPoint);
179 
180 bool IsDotOrDotDot(const struct dirent& ent);
181 
182 status_t DeleteDirContentsAndDir(const std::string& pathname);
183 status_t DeleteDirContents(const std::string& pathname);
184 
185 status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout);
186 
187 bool pathExists(const std::string& path);
188 
189 bool FsyncDirectory(const std::string& dirname);
190 
191 bool FsyncParentDirectory(const std::string& path);
192 
193 bool MkdirsSync(const std::string& path, mode_t mode);
194 
195 bool writeStringToFile(const std::string& payload, const std::string& filename);
196 
197 void ConfigureMaxDirtyRatioForFuse(const std::string& fuse_mount, unsigned int max_ratio);
198 
199 void ConfigureReadAheadForFuse(const std::string& fuse_mount, size_t read_ahead_kb);
200 
201 status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
202                        const std::string& relative_upper_path, android::base::unique_fd* fuse_fd);
203 
204 status_t UnmountUserFuse(userid_t userId, const std::string& absolute_lower_path,
205                          const std::string& relative_upper_path);
206 
207 status_t PrepareAndroidDirs(const std::string& volumeRoot);
208 
209 bool IsFuseBpfEnabled();
210 
211 // Open a given directory as an FD, and return that and the corresponding procfs virtual
212 // symlink path that can be used in any API that accepts a path string. Path stays valid until
213 // the directory FD is closed.
214 //
215 // This may be useful when an API wants to restrict a path passed from an untrusted process,
216 // and do it without any TOCTOU attacks possible (e.g. where an attacker replaces one of
217 // the components with a symlink after the check passed). In that case opening a path through
218 // this function guarantees that the target directory stays the same, and that it can be
219 // referenced inside the current process via the virtual procfs symlink returned here.
220 std::pair<android::base::unique_fd, std::string> OpenDirInProcfs(std::string_view path);
221 
222 }  // namespace vold
223 }  // namespace android
224 
225 #endif
226