blob: f7114054681f4d529dce1ff6f23e5e8fc82e46ef [file] [log] [blame]
shafik1e3a2672019-08-16 14:51:55 +01001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Zimec8d5722019-12-05 07:26:13 +000015#define ATRACE_TAG ATRACE_TAG_APP
shafik1e3a2672019-08-16 14:51:55 +010016#define LOG_TAG "FuseDaemon"
Zim357e3072020-01-15 10:50:01 +000017#define LIBFUSE_LOG_TAG "libfuse"
shafik1e3a2672019-08-16 14:51:55 +010018
19#include "FuseDaemon.h"
Zim29f9ff52021-01-20 10:47:04 +000020#include "android-base/strings.h"
shafik1e3a2672019-08-16 14:51:55 +010021
shafik458d1102019-09-06 18:21:36 +010022#include <android-base/logging.h>
Zim32129b62020-03-11 11:37:16 +000023#include <android-base/properties.h>
Zim724b8ca2019-11-09 09:37:24 +000024#include <android/log.h>
Zimec8d5722019-12-05 07:26:13 +000025#include <android/trace.h>
shafik1e3a2672019-08-16 14:51:55 +010026#include <ctype.h>
27#include <dirent.h>
28#include <errno.h>
29#include <fcntl.h>
shafik8b57cd52019-09-06 10:51:29 +010030#include <fuse_i.h>
Zim724b8ca2019-11-09 09:37:24 +000031#include <fuse_log.h>
shafik8b57cd52019-09-06 10:51:29 +010032#include <fuse_lowlevel.h>
shafik1e3a2672019-08-16 14:51:55 +010033#include <inttypes.h>
34#include <limits.h>
35#include <linux/fuse.h>
shafik1e3a2672019-08-16 14:51:55 +010036#include <stdbool.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40#include <sys/inotify.h>
shafikb334a612019-09-30 20:38:16 +010041#include <sys/mman.h>
shafik1e3a2672019-08-16 14:51:55 +010042#include <sys/mount.h>
43#include <sys/param.h>
44#include <sys/resource.h>
45#include <sys/stat.h>
46#include <sys/statfs.h>
47#include <sys/statvfs.h>
48#include <sys/time.h>
49#include <sys/types.h>
50#include <sys/uio.h>
51#include <unistd.h>
shafik1e3a2672019-08-16 14:51:55 +010052
shafik8b57cd52019-09-06 10:51:29 +010053#include <iostream>
Narayan Kamath8d76d0c2019-12-31 13:14:50 +000054#include <list>
Paul Lawrence7e4a5a82019-09-27 21:39:49 +020055#include <map>
Narayan Kamath768bea32019-12-27 16:23:23 +000056#include <mutex>
Paul Lawrence7e4a5a82019-09-27 21:39:49 +020057#include <queue>
Zim859db932019-12-13 00:09:17 +000058#include <regex>
Paul Lawrence7e4a5a82019-09-27 21:39:49 +020059#include <thread>
Zim724b8ca2019-11-09 09:37:24 +000060#include <unordered_map>
Narayan Kamath92bf67b2020-01-03 17:49:09 +000061#include <unordered_set>
shafikc3f62672019-08-30 11:15:48 +010062#include <vector>
shafik1e3a2672019-08-16 14:51:55 +010063
shafikc3f62672019-08-30 11:15:48 +010064#include "MediaProviderWrapper.h"
Corina633099b2020-06-17 21:55:33 +010065#include "libfuse_jni/FuseUtils.h"
Sahana Raoa82bd6a2019-10-10 18:10:37 +010066#include "libfuse_jni/ReaddirHelper.h"
shafikc3f62672019-08-30 11:15:48 +010067#include "libfuse_jni/RedactionInfo.h"
Narayan Kamathaef84a12020-01-02 15:20:13 +000068#include "node-inl.h"
shafikc3f62672019-08-30 11:15:48 +010069
Sahana Raoa82bd6a2019-10-10 18:10:37 +010070using mediaprovider::fuse::DirectoryEntry;
Narayan Kamathaef84a12020-01-02 15:20:13 +000071using mediaprovider::fuse::dirhandle;
72using mediaprovider::fuse::handle;
73using mediaprovider::fuse::node;
shafikc3f62672019-08-30 11:15:48 +010074using mediaprovider::fuse::RedactionInfo;
Narayan Kamath8d76d0c2019-12-31 13:14:50 +000075using std::list;
Jeff Sharkey7469b982019-08-28 16:51:02 -060076using std::string;
shafikc3f62672019-08-30 11:15:48 +010077using std::vector;
shafik1e3a2672019-08-16 14:51:55 +010078
Narayan Kamath88203dc2019-08-30 17:19:38 +010079// logging macros to avoid duplication.
Nandana Dutt154cb5d2020-06-04 11:53:31 +010080#define TRACE_NODE(__node, __req) \
81 LOG(VERBOSE) << __FUNCTION__ << " : " << #__node << " = [" << get_name(__node) \
Alessio Balsini328abac2020-11-25 17:49:25 +000082 << "] (uid=" << (__req)->ctx.uid << ") "
shafik1e3a2672019-08-16 14:51:55 +010083
Zimec8d5722019-12-05 07:26:13 +000084#define ATRACE_NAME(name) ScopedTrace ___tracer(name)
85#define ATRACE_CALL() ATRACE_NAME(__FUNCTION__)
86
87class ScopedTrace {
88 public:
Narayan Kamath64b44352019-12-27 17:07:50 +000089 explicit inline ScopedTrace(const char *name) {
Zimec8d5722019-12-05 07:26:13 +000090 ATrace_beginSection(name);
91 }
92
93 inline ~ScopedTrace() {
94 ATrace_endSection();
95 }
96};
97
Zim32129b62020-03-11 11:37:16 +000098const bool IS_OS_DEBUGABLE = android::base::GetIntProperty("ro.debuggable", 0);
99
shafik1e3a2672019-08-16 14:51:55 +0100100#define FUSE_UNKNOWN_INO 0xffffffff
101
Ricky Waif40c4022020-04-15 19:00:06 +0100102// Stolen from: android_filesystem_config.h
103#define AID_APP_START 10000
104
shafikb334a612019-09-30 20:38:16 +0100105constexpr size_t MAX_READ_SIZE = 128 * 1024;
Zim859db932019-12-13 00:09:17 +0000106// Stolen from: UserHandle#getUserId
107constexpr int PER_USER_RANGE = 100000;
shafikb334a612019-09-30 20:38:16 +0100108
Martijn Coenen44ef6302020-11-06 10:32:32 +0100109// Stolen from: UserManagerService
110constexpr int MAX_USER_ID = UINT32_MAX / PER_USER_RANGE;
111
Zim3cde2662021-02-22 21:20:33 +0000112const int MY_UID = getuid();
113const int MY_USER_ID = MY_UID / PER_USER_RANGE;
114const std::string MY_USER_ID_STRING(std::to_string(MY_UID / PER_USER_RANGE));
115
Ricky Waif40c4022020-04-15 19:00:06 +0100116// Regex copied from FileUtils.java in MediaProvider, but without media directory.
117const std::regex PATTERN_OWNED_PATH(
Zim78ffeeb2020-09-22 20:15:25 +0100118 "^/storage/[^/]+/(?:[0-9]+/)?Android/(?:data|obb)/([^/]+)(/?.*)?",
119 std::regex_constants::icase);
Ricky Waif40c4022020-04-15 19:00:06 +0100120
]3e9d56c2021-03-15 16:24:17 +0000121static constexpr char TRANSFORM_SYNTHETIC_DIR[] = "synthetic";
122static constexpr char TRANSFORM_TRANSCODE_DIR[] = "transcode";
123
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200124/*
125 * In order to avoid double caching with fuse, call fadvise on the file handles
126 * in the underlying file system. However, if this is done on every read/write,
127 * the fadvises cause a very significant slowdown in tests (specifically fio
128 * seq_write). So call fadvise on the file handles with the most reads/writes
129 * only after a threshold is passed.
130 */
131class FAdviser {
132 public:
133 FAdviser() : thread_(MessageLoop, this), total_size_(0) {}
134
135 ~FAdviser() {
136 SendMessage(Message::quit);
137 thread_.join();
138 }
139
140 void Record(int fd, size_t size) { SendMessage(Message::record, fd, size); }
141
142 void Close(int fd) { SendMessage(Message::close, fd); }
143
144 private:
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200145 struct Message {
146 enum Type { record, close, quit };
147 Type type;
148 int fd;
149 size_t size;
150 };
151
152 void RecordImpl(int fd, size_t size) {
153 total_size_ += size;
154
155 // Find or create record in files_
156 // Remove record from sizes_ if it exists, adjusting size appropriately
157 auto file = files_.find(fd);
158 if (file != files_.end()) {
159 auto old_size = file->second;
160 size += old_size->first;
161 sizes_.erase(old_size);
162 } else {
163 file = files_.insert(Files::value_type(fd, sizes_.end())).first;
164 }
165
166 // Now (re) insert record in sizes_
167 auto new_size = sizes_.insert(Sizes::value_type(size, fd));
168 file->second = new_size;
169
170 if (total_size_ < threshold_) return;
171
172 LOG(INFO) << "Threshold exceeded - fadvising " << total_size_;
173 while (!sizes_.empty() && total_size_ > target_) {
174 auto size = --sizes_.end();
175 total_size_ -= size->first;
176 posix_fadvise(size->second, 0, 0, POSIX_FADV_DONTNEED);
177 files_.erase(size->second);
178 sizes_.erase(size);
179 }
180 LOG(INFO) << "Threshold now " << total_size_;
181 }
182
183 void CloseImpl(int fd) {
184 auto file = files_.find(fd);
185 if (file == files_.end()) return;
186
187 total_size_ -= file->second->first;
188 sizes_.erase(file->second);
189 files_.erase(file);
190 }
191
192 void MessageLoopImpl() {
193 while (1) {
194 Message message;
195
196 {
197 std::unique_lock<std::mutex> lock(mutex_);
198 cv_.wait(lock, [this] { return !queue_.empty(); });
199 message = queue_.front();
200 queue_.pop();
201 }
202
203 switch (message.type) {
204 case Message::record:
205 RecordImpl(message.fd, message.size);
206 break;
207
208 case Message::close:
209 CloseImpl(message.fd);
210 break;
211
212 case Message::quit:
213 return;
214 }
215 }
216 }
217
218 static int MessageLoop(FAdviser* ptr) {
219 ptr->MessageLoopImpl();
220 return 0;
221 }
222
223 void SendMessage(Message::Type type, int fd = -1, size_t size = 0) {
224 {
225 std::unique_lock<std::mutex> lock(mutex_);
226 Message message = {type, fd, size};
227 queue_.push(message);
228 }
229 cv_.notify_one();
230 }
231
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200232 std::mutex mutex_;
233 std::condition_variable cv_;
Zim695a1272020-06-15 18:14:08 +0100234 std::queue<Message> queue_;
235 std::thread thread_;
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200236
237 typedef std::multimap<size_t, int> Sizes;
238 typedef std::map<int, Sizes::iterator> Files;
239
240 Files files_;
241 Sizes sizes_;
242 size_t total_size_;
243
244 const size_t threshold_ = 64 * 1024 * 1024;
245 const size_t target_ = 32 * 1024 * 1024;
246};
247
shafik1e3a2672019-08-16 14:51:55 +0100248/* Single FUSE mount */
249struct fuse {
Biswarup Pal93f4ec12021-02-15 13:39:36 +0000250 explicit fuse(const std::string& _path, ino_t _ino)
Narayan Kamath568f17a2020-02-19 13:45:29 +0000251 : path(_path),
252 tracker(mediaprovider::fuse::NodeTracker(&lock)),
Biswarup Pal93f4ec12021-02-15 13:39:36 +0000253 root(node::CreateRoot(_path, &lock, _ino, &tracker)),
Narayan Kamath568f17a2020-02-19 13:45:29 +0000254 mp(0),
Martijn Coenen87133092020-10-14 17:00:28 +0200255 zero_addr(0),
Alessio Balsinif220a962020-07-13 12:01:13 +0100256 disable_dentry_cache(false),
257 passthrough(false) {}
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200258
Narayan Kamathaef84a12020-01-02 15:20:13 +0000259 inline bool IsRoot(const node* node) const { return node == root; }
shafik1e3a2672019-08-16 14:51:55 +0100260
Zimb2834012020-06-17 13:26:27 +0100261 inline string GetEffectiveRootPath() {
Zim3b6ff4d2021-03-03 11:14:59 +0000262 if (android::base::StartsWith(path, "/storage/emulated")) {
Zim3cde2662021-02-22 21:20:33 +0000263 return path + "/" + MY_USER_ID_STRING;
Zimb2834012020-06-17 13:26:27 +0100264 }
265 return path;
266 }
267
]3e9d56c2021-03-15 16:24:17 +0000268 inline string GetTransformsDir() { return GetEffectiveRootPath() + "/.transforms"; }
269
Narayan Kamathaef84a12020-01-02 15:20:13 +0000270 // Note that these two (FromInode / ToInode) conversion wrappers are required
271 // because fuse_lowlevel_ops documents that the root inode is always one
272 // (see FUSE_ROOT_ID in fuse_lowlevel.h). There are no particular requirements
273 // on any of the other inodes in the FS.
Ricky Wai44670762020-05-01 11:25:28 +0100274 inline node* FromInode(__u64 inode) {
Narayan Kamathaef84a12020-01-02 15:20:13 +0000275 if (inode == FUSE_ROOT_ID) {
276 return root;
277 }
shafik1e3a2672019-08-16 14:51:55 +0100278
Ricky Wai44670762020-05-01 11:25:28 +0100279 return node::FromInode(inode, &tracker);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000280 }
281
282 inline __u64 ToInode(node* node) const {
283 if (IsRoot(node)) {
284 return FUSE_ROOT_ID;
285 }
286
287 return node::ToInode(node);
288 }
289
290 std::recursive_mutex lock;
291 const string path;
Narayan Kamath568f17a2020-02-19 13:45:29 +0000292 // The Inode tracker associated with this FUSE instance.
293 mediaprovider::fuse::NodeTracker tracker;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000294 node* const root;
Zima76c3492020-02-19 01:23:26 +0000295 struct fuse_session* se;
shafikc3f62672019-08-30 11:15:48 +0100296
297 /*
298 * Used to make JNI calls to MediaProvider.
299 * Responsibility of freeing this object falls on corresponding
300 * FuseDaemon object.
301 */
302 mediaprovider::fuse::MediaProviderWrapper* mp;
shafikb334a612019-09-30 20:38:16 +0100303
304 /*
305 * Points to a range of zeroized bytes, used by pf_read to represent redacted ranges.
306 * The memory is read only and should never be modified.
307 */
Narayan Kamathaef84a12020-01-02 15:20:13 +0000308 /* const */ char* zero_addr;
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200309
310 FAdviser fadviser;
Zimd0435b22020-03-05 13:52:51 +0000311
312 std::atomic_bool* active;
Martijn Coenen87133092020-10-14 17:00:28 +0200313 std::atomic_bool disable_dentry_cache;
Zim148cbe22020-11-17 15:58:29 +0000314 std::atomic_bool passthrough;
Biswarup Pal93f4ec12021-02-15 13:39:36 +0000315 // FUSE device id.
316 std::atomic_uint dev;
shafik1e3a2672019-08-16 14:51:55 +0100317};
318
]3e9d56c2021-03-15 16:24:17 +0000319enum class FuseOp { lookup, readdir, mknod, mkdir, create };
320
Zim32129b62020-03-11 11:37:16 +0000321static inline string get_name(node* n) {
322 if (n) {
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100323 std::string name = IS_OS_DEBUGABLE ? "real_path: " + n->BuildPath() + " " : "";
324 name += "node_path: " + n->BuildSafePath();
Zim32129b62020-03-11 11:37:16 +0000325 return name;
326 }
327 return "?";
shafik458d1102019-09-06 18:21:36 +0100328}
329
shafik1e3a2672019-08-16 14:51:55 +0100330static inline __u64 ptr_to_id(void* ptr) {
331 return (__u64)(uintptr_t) ptr;
332}
333
Zimedbe69e2019-12-13 18:49:36 +0000334/*
335 * Set an F_RDLCK or F_WRLCKK on fd with fcntl(2).
336 *
337 * This is called before the MediaProvider returns fd from the lower file
338 * system to an app over the ContentResolver interface. This allows us
339 * check with is_file_locked if any reference to that fd is still open.
340 */
341static int set_file_lock(int fd, bool for_read, const std::string& path) {
342 std::string lock_str = (for_read ? "read" : "write");
Zimedbe69e2019-12-13 18:49:36 +0000343
344 struct flock fl{};
345 fl.l_type = for_read ? F_RDLCK : F_WRLCK;
346 fl.l_whence = SEEK_SET;
347
348 int res = fcntl(fd, F_OFD_SETLK, &fl);
349 if (res) {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +0000350 PLOG(WARNING) << "Failed to set lock: " << lock_str;
Zimedbe69e2019-12-13 18:49:36 +0000351 return res;
352 }
Zimedbe69e2019-12-13 18:49:36 +0000353 return res;
354}
355
356/*
357 * Check if an F_RDLCK or F_WRLCK is set on fd with fcntl(2).
358 *
359 * This is used to determine if the MediaProvider has given an fd to the lower fs to an app over
360 * the ContentResolver interface. Before that happens, we always call set_file_lock on the file
361 * allowing us to know if any reference to that fd is still open here.
362 *
363 * Returns true if fd may have a lock, false otherwise
364 */
365static bool is_file_locked(int fd, const std::string& path) {
Zimedbe69e2019-12-13 18:49:36 +0000366 struct flock fl{};
367 fl.l_type = F_WRLCK;
368 fl.l_whence = SEEK_SET;
369
370 int res = fcntl(fd, F_OFD_GETLK, &fl);
371 if (res) {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +0000372 PLOG(WARNING) << "Failed to check lock";
Zimedbe69e2019-12-13 18:49:36 +0000373 // Assume worst
374 return true;
375 }
376 bool locked = fl.l_type != F_UNLCK;
Zimedbe69e2019-12-13 18:49:36 +0000377 return locked;
378}
379
shafik1e3a2672019-08-16 14:51:55 +0100380static struct fuse* get_fuse(fuse_req_t req) {
381 return reinterpret_cast<struct fuse*>(fuse_req_userdata(req));
382}
383
Ricky Waif40c4022020-04-15 19:00:06 +0100384static bool is_package_owned_path(const string& path, const string& fuse_path) {
385 if (path.rfind(fuse_path, 0) != 0) {
386 return false;
387 }
388 return std::regex_match(path, PATTERN_OWNED_PATH);
389}
390
Zim33aea102020-06-19 15:49:47 +0100391// See fuse_lowlevel.h fuse_lowlevel_notify_inval_entry for how to call this safetly without
392// deadlocking the kernel
393static void fuse_inval(fuse_session* se, fuse_ino_t parent_ino, fuse_ino_t child_ino,
394 const string& child_name, const string& path) {
Zim3cde2662021-02-22 21:20:33 +0000395 if (mediaprovider::fuse::containsMount(path, MY_USER_ID_STRING)) {
Zim33aea102020-06-19 15:49:47 +0100396 LOG(WARNING) << "Ignoring attempt to invalidate dentry for FUSE mounts";
397 return;
398 }
399
400 if (fuse_lowlevel_notify_inval_entry(se, parent_ino, child_name.c_str(), child_name.size())) {
401 // Invalidating the dentry can fail if there's no dcache entry, however, there may still
402 // be cached attributes, so attempt to invalidate those by invalidating the inode
403 fuse_lowlevel_notify_inval_inode(se, child_ino, 0, 0);
404 }
Zim89962312020-04-22 21:21:53 +0100405}
406
Zim3b6ff4d2021-03-03 11:14:59 +0000407static double get_entry_timeout(const string& path, node* node, struct fuse* fuse) {
408 string media_path = fuse->GetEffectiveRootPath() + "/Android/media";
Zimded1ab92021-01-15 10:36:17 +0000409 if (fuse->disable_dentry_cache || node->ShouldInvalidate() ||
Zim3b6ff4d2021-03-03 11:14:59 +0000410 is_package_owned_path(path, fuse->path) || android::base::StartsWith(path, media_path)) {
Zimb2834012020-06-17 13:26:27 +0100411 // We set dentry timeout to 0 for the following reasons:
Martijn Coenen87133092020-10-14 17:00:28 +0200412 // 1. The dentry cache was completely disabled
Zimded1ab92021-01-15 10:36:17 +0000413 // 2.1 Case-insensitive lookups need to invalidate other case-insensitive dentry matches
414 // 2.2 Nodes supporting transforms need to be invalidated, so that subsequent lookups by a
415 // uid requiring a transform is guaranteed to come to the FUSE daemon.
Martijn Coenen87133092020-10-14 17:00:28 +0200416 // 3. With app data isolation enabled, app A should not guess existence of app B from the
Zimb2834012020-06-17 13:26:27 +0100417 // Android/{data,obb}/<package> paths, hence we prevent the kernel from caching that
418 // information.
Zim3b6ff4d2021-03-03 11:14:59 +0000419 // 4. Installd might delete Android/media/<package> dirs when app data is cleared.
Zim867fece2020-09-23 15:23:19 +0100420 // This can leave a stale entry in the kernel dcache, and break subsequent creation of the
421 // dir via FUSE.
422 return 0;
423 }
Zim3b6ff4d2021-03-03 11:14:59 +0000424 return std::numeric_limits<double>::max();
Zim867fece2020-09-23 15:23:19 +0100425}
426
427static std::string get_path(node* node) {
428 const string& io_path = node->GetIoPath();
429 return io_path.empty() ? node->BuildPath() : io_path;
430}
431
]3e9d56c2021-03-15 16:24:17 +0000432// Returns true if the path resides under .transforms/synthetic.
433// NOTE: currently only file paths corresponding to redacted URIs reside under this folder. The path
434// itself never exists and just a link for transformation.
435static inline bool is_synthetic_path(const string& path, struct fuse* fuse) {
436 return android::base::StartsWithIgnoreCase(
437 path, fuse->GetTransformsDir() + "/" + TRANSFORM_SYNTHETIC_DIR);
438}
439
Zim549ee7d2021-03-19 17:26:20 +0000440static inline bool is_transcode_supported_path(const string& path, struct fuse* fuse) {
441 // Keep in sync with MediaProvider#supportsTranscode
442 return android::base::EndsWithIgnoreCase(path, ".mp4") &&
443 android::base::StartsWithIgnoreCase(path,
444 fuse->GetEffectiveRootPath() + "/dcim/camera/");
445}
446
]3e9d56c2021-03-15 16:24:17 +0000447static inline bool is_transforms_dir_path(const string& path, struct fuse* fuse) {
448 return android::base::StartsWithIgnoreCase(path, fuse->GetTransformsDir());
449}
450
451static std::unique_ptr<mediaprovider::fuse::FileLookupResult> validate_node_path(
452 const std::string& path, const std::string& name, fuse_req_t req, int* error_code,
453 struct fuse_entry_param* e, const FuseOp op) {
454 struct fuse* fuse = get_fuse(req);
455 const struct fuse_ctx* ctx = fuse_req_ctx(req);
456 memset(e, 0, sizeof(*e));
457
458 const bool synthetic_path = is_synthetic_path(path, fuse);
459 if (lstat(path.c_str(), &e->attr) < 0 && !(op == FuseOp::lookup && synthetic_path)) {
460 *error_code = errno;
461 return nullptr;
462 }
463
464 if (is_transforms_dir_path(path, fuse)) {
465 if (op == FuseOp::lookup) {
466 // Lookups are only allowed under .transforms/synthetic dir
467 if (!(android::base::EqualsIgnoreCase(path, fuse->GetTransformsDir()) ||
468 android::base::StartsWithIgnoreCase(
469 path, fuse->GetTransformsDir() + "/" + TRANSFORM_SYNTHETIC_DIR))) {
470 *error_code = ENONET;
471 return nullptr;
472 }
473 } else {
474 // user-code is only allowed to make lookups under .transforms dir, and that too only
475 // under .transforms/synthetic dir
476 *error_code = ENOENT;
477 return nullptr;
478 }
479 }
480
481 if (S_ISDIR(e->attr.st_mode)) {
482 // now that we have reached this point, ops on directories are safe and require no
483 // transformation.
484 return std::make_unique<mediaprovider::fuse::FileLookupResult>(0, 0, 0, true, false, "");
485 }
486
Zim549ee7d2021-03-19 17:26:20 +0000487 if (!synthetic_path && !is_transcode_supported_path(path, fuse)) {
488 // Transforms are only supported for synthetic or transcode-supported paths
489 return std::make_unique<mediaprovider::fuse::FileLookupResult>(0, 0, 0, true, false, "");
490 }
491
]3e9d56c2021-03-15 16:24:17 +0000492 // Handle potential file transforms
493 std::unique_ptr<mediaprovider::fuse::FileLookupResult> file_lookup_result =
494 fuse->mp->FileLookup(path, req->ctx.uid, req->ctx.pid);
495
496 if (!file_lookup_result) {
497 // Fail lookup if we can't fetch FileLookupResult for path
498 LOG(WARNING) << "Failed to fetch FileLookupResult for " << path;
499 *error_code = ENOENT;
500 return nullptr;
501 }
502
503 const string& io_path = file_lookup_result->io_path;
504 // Update size with io_path size if io_path is not same as path
505 if (!io_path.empty() && (io_path != path) && (lstat(io_path.c_str(), &e->attr) < 0)) {
506 *error_code = errno;
507 return nullptr;
508 }
509
510 return file_lookup_result;
511}
512
Narayan Kamathaef84a12020-01-02 15:20:13 +0000513static node* make_node_entry(fuse_req_t req, node* parent, const string& name, const string& path,
]3e9d56c2021-03-15 16:24:17 +0000514 struct fuse_entry_param* e, int* error_code, const FuseOp op) {
shafik1e3a2672019-08-16 14:51:55 +0100515 struct fuse* fuse = get_fuse(req);
Martijn Coenenb8ff4eb2019-12-17 09:55:17 +0100516 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000517 node* node;
shafik1e3a2672019-08-16 14:51:55 +0100518
Jeff Sharkey7469b982019-08-28 16:51:02 -0600519 memset(e, 0, sizeof(*e));
]3e9d56c2021-03-15 16:24:17 +0000520
521 std::unique_ptr<mediaprovider::fuse::FileLookupResult> file_lookup_result =
522 validate_node_path(path, name, req, error_code, e, op);
523 if (!file_lookup_result) {
524 // Fail lookup if we can't validate |path, |errno| would have already been set
525 return nullptr;
shafik1e3a2672019-08-16 14:51:55 +0100526 }
527
]3e9d56c2021-03-15 16:24:17 +0000528 const bool should_invalidate = file_lookup_result->transforms_supported;
529 const bool transforms_complete = file_lookup_result->transforms_complete;
530 const int transforms = file_lookup_result->transforms;
531 const int transforms_reason = file_lookup_result->transforms_reason;
532 const string& io_path = file_lookup_result->io_path;
Zim867fece2020-09-23 15:23:19 +0100533
Zimed257c12020-10-15 13:47:45 +0100534 node = parent->LookupChildByName(name, true /* acquire */, transforms);
Narayan Kamatheca34252020-02-11 13:08:37 +0000535 if (!node) {
Biswarup Pal93f4ec12021-02-15 13:39:36 +0000536 ino_t ino = e->attr.st_ino;
Zimded1ab92021-01-15 10:36:17 +0000537 node = ::node::Create(parent, name, io_path, should_invalidate, transforms_complete,
Biswarup Pal93f4ec12021-02-15 13:39:36 +0000538 transforms, transforms_reason, &fuse->lock, ino, &fuse->tracker);
Corina633099b2020-06-17 21:55:33 +0100539 } else if (!mediaprovider::fuse::containsMount(path, std::to_string(getuid() / PER_USER_RANGE))) {
Corina633099b2020-06-17 21:55:33 +0100540 // Only invalidate a path if it does not contain mount.
Zim0852ba72020-06-09 11:50:33 +0100541 // Invalidate both names to ensure there's no dentry left in the kernel after the following
542 // operations:
543 // 1) touch foo, touch FOO, unlink *foo*
544 // 2) touch foo, touch FOO, unlink *FOO*
545 // Invalidating lookup_name fixes (1) and invalidating node_name fixes (2)
Zimded1ab92021-01-15 10:36:17 +0000546 // SetShouldInvalidate invalidates lookup_name by using 0 timeout below and we explicitly
Zim33aea102020-06-19 15:49:47 +0100547 // invalidate node_name if different case
548 // Note that we invalidate async otherwise we will deadlock the kernel
549 if (name != node->GetName()) {
Zimf2b47b42020-09-16 14:54:06 +0100550 // Record that we have made a case insensitive lookup, this allows us invalidate nodes
551 // correctly on subsequent lookups for the case of |node|
Zimded1ab92021-01-15 10:36:17 +0000552 node->SetShouldInvalidate();
Zimf2b47b42020-09-16 14:54:06 +0100553
Narayan Kamath8b296f52020-07-29 13:10:17 +0100554 // Make copies of the node name and path so we're not attempting to acquire
555 // any node locks from the invalidation thread. Depending on timing, we may end
556 // up invalidating the wrong inode but that shouldn't result in correctness issues.
557 const fuse_ino_t parent_ino = fuse->ToInode(parent);
558 const fuse_ino_t child_ino = fuse->ToInode(node);
559 const std::string& node_name = node->GetName();
Narayan Kamath8b296f52020-07-29 13:10:17 +0100560 std::thread t([=]() { fuse_inval(fuse->se, parent_ino, child_ino, node_name, path); });
Zim33aea102020-06-19 15:49:47 +0100561 t.detach();
562 }
Zime5433682021-03-10 12:06:54 +0000563
564 // This updated value allows us correctly decide if to keep_cache and use direct_io during
565 // FUSE_OPEN. Between the last lookup and this lookup, we might have deleted a cached
566 // transcoded file on the lower fs. A subsequent transcode at FUSE_READ should ensure we
567 // don't reuse any stale transcode page cache content.
568 node->SetTransformsComplete(transforms_complete);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000569 }
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100570 TRACE_NODE(node, req);
Zim89962312020-04-22 21:21:53 +0100571
Narayan Kamathfc0aa952019-12-31 13:31:49 +0000572 // This FS is not being exported via NFS so just a fixed generation number
573 // for now. If we do need this, we need to increment the generation ID each
574 // time the fuse daemon restarts because that's what it takes for us to
575 // reuse inode numbers.
576 e->generation = 0;
Zim8b2b6f22020-01-22 13:53:59 +0000577 e->ino = fuse->ToInode(node);
Zimded1ab92021-01-15 10:36:17 +0000578 e->entry_timeout = get_entry_timeout(path, node, fuse);
Zim3b6ff4d2021-03-03 11:14:59 +0000579 e->attr_timeout = std::numeric_limits<double>::max();
shafik1e3a2672019-08-16 14:51:55 +0100580 return node;
581}
582
shafik15e2d612019-10-31 20:10:25 +0000583static inline bool is_requesting_write(int flags) {
584 return flags & (O_WRONLY | O_RDWR);
585}
586
shafik1e3a2672019-08-16 14:51:55 +0100587namespace mediaprovider {
588namespace fuse {
589
590/**
591 * Function implementations
592 *
593 * These implement the various functions in fuse_lowlevel_ops
594 *
595 */
596
597static void pf_init(void* userdata, struct fuse_conn_info* conn) {
Alessio Balsinif220a962020-07-13 12:01:13 +0100598 struct fuse* fuse = reinterpret_cast<struct fuse*>(userdata);
599
Zima9fcd552019-08-29 15:17:04 +0100600 // We don't want a getattr request with every read request
Zim1100f342020-05-15 16:13:00 +0100601 conn->want &= ~FUSE_CAP_AUTO_INVAL_DATA & ~FUSE_CAP_READDIRPLUS_AUTO;
shafik8b57cd52019-09-06 10:51:29 +0100602 unsigned mask = (FUSE_CAP_SPLICE_WRITE | FUSE_CAP_SPLICE_MOVE | FUSE_CAP_SPLICE_READ |
603 FUSE_CAP_ASYNC_READ | FUSE_CAP_ATOMIC_O_TRUNC | FUSE_CAP_WRITEBACK_CACHE |
604 FUSE_CAP_EXPORT_SUPPORT | FUSE_CAP_FLOCK_LOCKS);
Alessio Balsinif220a962020-07-13 12:01:13 +0100605
Zim87600222021-07-06 18:24:36 +0100606 bool disable_splice_write = false;
Alessio Balsinif220a962020-07-13 12:01:13 +0100607 if (fuse->passthrough) {
608 if (conn->capable & FUSE_CAP_PASSTHROUGH) {
609 mask |= FUSE_CAP_PASSTHROUGH;
Zim87600222021-07-06 18:24:36 +0100610
611 // SPLICE_WRITE seems to cause linux kernel cache corruption with passthrough enabled.
612 // It is still under investigation but while running
613 // ScopedStorageDeviceTest#testAccessMediaLocationInvalidation, we notice test flakes
614 // of about 1/20 for the following reason:
615 // 1. App without ACCESS_MEDIA_LOCATION permission reads redacted bytes via FUSE cache
616 // 2. App with ACCESS_MEDIA_LOCATION permission reads non-redacted bytes via passthrough
617 // cache
618 // (2) fails because bytes from (1) sneak into the passthrough cache??
619 // To workaround, we disable splice for write when passthrough is enabled.
620 // This shouldn't have any performance regression if comparing passthrough devices to
621 // no-passthrough devices for the following reasons:
622 // 1. No-op for no-passthrough devices
623 // 2. Passthrough devices
624 // a. Files not requiring redaction use passthrough which bypasses FUSE_READ entirely
625 // b. Files requiring redaction are still faster than no-passthrough devices that use
626 // direct_io
627 disable_splice_write = true;
Alessio Balsinif220a962020-07-13 12:01:13 +0100628 } else {
629 LOG(WARNING) << "Passthrough feature not supported by the kernel";
630 fuse->passthrough = false;
631 }
632 }
633
shafik1e3a2672019-08-16 14:51:55 +0100634 conn->want |= conn->capable & mask;
Zim87600222021-07-06 18:24:36 +0100635 if (disable_splice_write) {
636 conn->want &= ~FUSE_CAP_SPLICE_WRITE;
637 }
638
shafikb334a612019-09-30 20:38:16 +0100639 conn->max_read = MAX_READ_SIZE;
Zimd0435b22020-03-05 13:52:51 +0000640
Zimd0435b22020-03-05 13:52:51 +0000641 fuse->active->store(true, std::memory_order_release);
shafik1e3a2672019-08-16 14:51:55 +0100642}
643
Zim005cd812019-12-17 15:35:51 +0000644static void pf_destroy(void* userdata) {
645 struct fuse* fuse = reinterpret_cast<struct fuse*>(userdata);
646 LOG(INFO) << "DESTROY " << fuse->path;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000647
648 node::DeleteTree(fuse->root);
shafik1e3a2672019-08-16 14:51:55 +0100649}
shafik1e3a2672019-08-16 14:51:55 +0100650
Ricky Wai44670762020-05-01 11:25:28 +0100651// Return true if the path is accessible for that uid.
652static bool is_app_accessible_path(MediaProviderWrapper* mp, const string& path, uid_t uid) {
Zim3cde2662021-02-22 21:20:33 +0000653 if (uid < AID_APP_START || uid == MY_UID) {
Ricky Wai44670762020-05-01 11:25:28 +0100654 return true;
655 }
656
Martijn Coenen71435d52020-06-15 20:23:40 +0200657 if (path == "/storage/emulated") {
658 // Apps should never refer to /storage/emulated - they should be using the user-spcific
659 // subdirs, eg /storage/emulated/0
660 return false;
661 }
662
Ricky Wai44670762020-05-01 11:25:28 +0100663 std::smatch match;
664 if (std::regex_match(path, match, PATTERN_OWNED_PATH)) {
665 const std::string& pkg = match[1];
Abhijeet Kaur077fdd52020-05-28 13:59:31 +0100666 // .nomedia is not a valid package. .nomedia always exists in /Android/data directory,
667 // and it's not an external file/directory of any package
668 if (pkg == ".nomedia") {
669 return true;
670 }
Martijn Coenenba3e6772021-04-28 09:27:54 +0200671 if (android::base::StartsWith(path, "/storage/emulated")) {
672 // Emulated storage bind-mounts app-private data directories, and so these
673 // should not be accessible through FUSE anyway.
674 LOG(WARNING) << "Rejected access to app-private dir on FUSE: " << path
675 << " from uid: " << uid;
676 return false;
677 }
Abhijeet Kaurb3ac2802020-10-07 16:42:42 +0100678 if (!mp->isUidAllowedAccessToDataOrObbPath(uid, path)) {
679 PLOG(WARNING) << "Invalid other package file access from " << uid << "(: " << path;
Ricky Wai44670762020-05-01 11:25:28 +0100680 return false;
681 }
682 }
683 return true;
684}
685
Zim859db932019-12-13 00:09:17 +0000686static std::regex storage_emulated_regex("^\\/storage\\/emulated\\/([0-9]+)");
Narayan Kamathaef84a12020-01-02 15:20:13 +0000687static node* do_lookup(fuse_req_t req, fuse_ino_t parent, const char* name,
]3e9d56c2021-03-15 16:24:17 +0000688 struct fuse_entry_param* e, int* error_code, const FuseOp op) {
shafik1e3a2672019-08-16 14:51:55 +0100689 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100690 node* parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +0100691 if (!parent_node) {
692 *error_code = ENOENT;
693 return nullptr;
694 }
Narayan Kamathaef84a12020-01-02 15:20:13 +0000695 string parent_path = parent_node->BuildPath();
Martijn Coenena5f19e82020-06-17 13:01:23 +0200696 // We should always allow lookups on the root, because failing them could cause
697 // bind mounts to be invalidated.
698 if (!fuse->IsRoot(parent_node) && !is_app_accessible_path(fuse->mp, parent_path, req->ctx.uid)) {
Ricky Wai44670762020-05-01 11:25:28 +0100699 *error_code = ENOENT;
700 return nullptr;
701 }
702
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100703 TRACE_NODE(parent_node, req);
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +0000704
]3e9d56c2021-03-15 16:24:17 +0000705 const string child_path = parent_path + "/" + name;
Zim859db932019-12-13 00:09:17 +0000706 std::smatch match;
707 std::regex_search(child_path, match, storage_emulated_regex);
Zim5077a892020-09-08 12:55:12 +0100708
709 // Ensure the FuseDaemon user id matches the user id or cross-user lookups are allowed in
710 // requested path
Zim3cde2662021-02-22 21:20:33 +0000711 if (match.size() == 2 && MY_USER_ID_STRING != match[1].str()) {
Zim5077a892020-09-08 12:55:12 +0100712 // If user id mismatch, check cross-user lookups
Martijn Coenen44ef6302020-11-06 10:32:32 +0100713 long userId = strtol(match[1].str().c_str(), nullptr, 10);
714 if (userId < 0 || userId > MAX_USER_ID ||
715 !fuse->mp->ShouldAllowLookup(req->ctx.uid, userId)) {
Zim5077a892020-09-08 12:55:12 +0100716 *error_code = EACCES;
717 return nullptr;
718 }
Zim859db932019-12-13 00:09:17 +0000719 }
]3e9d56c2021-03-15 16:24:17 +0000720
721 return make_node_entry(req, parent_node, name, child_path, e, error_code, op);
shafik1e3a2672019-08-16 14:51:55 +0100722}
723
724static void pf_lookup(fuse_req_t req, fuse_ino_t parent, const char* name) {
Zimec8d5722019-12-05 07:26:13 +0000725 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100726 struct fuse_entry_param e;
727
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000728 int error_code = 0;
]3e9d56c2021-03-15 16:24:17 +0000729 if (do_lookup(req, parent, name, &e, &error_code, FuseOp::lookup)) {
shafik1e3a2672019-08-16 14:51:55 +0100730 fuse_reply_entry(req, &e);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000731 } else {
732 CHECK(error_code != 0);
733 fuse_reply_err(req, error_code);
734 }
shafik1e3a2672019-08-16 14:51:55 +0100735}
736
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100737static void do_forget(fuse_req_t req, struct fuse* fuse, fuse_ino_t ino, uint64_t nlookup) {
Ricky Wai44670762020-05-01 11:25:28 +0100738 node* node = fuse->FromInode(ino);
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100739 TRACE_NODE(node, req);
shafik1e3a2672019-08-16 14:51:55 +0100740 if (node) {
Narayan Kamathaef84a12020-01-02 15:20:13 +0000741 // This is a narrowing conversion from an unsigned 64bit to a 32bit value. For
742 // some reason we only keep 32 bit refcounts but the kernel issues
743 // forget requests with a 64 bit counter.
Narayan Kamath568f17a2020-02-19 13:45:29 +0000744 node->Release(static_cast<uint32_t>(nlookup));
shafik1e3a2672019-08-16 14:51:55 +0100745 }
746}
747
748static void pf_forget(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup) {
Ricky Wai44670762020-05-01 11:25:28 +0100749 // Always allow to forget so no need to check is_app_accessible_path()
Zimec8d5722019-12-05 07:26:13 +0000750 ATRACE_CALL();
Narayan Kamathaef84a12020-01-02 15:20:13 +0000751 node* node;
shafik1e3a2672019-08-16 14:51:55 +0100752 struct fuse* fuse = get_fuse(req);
753
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100754 do_forget(req, fuse, ino, nlookup);
shafik1e3a2672019-08-16 14:51:55 +0100755 fuse_reply_none(req);
756}
757
758static void pf_forget_multi(fuse_req_t req,
759 size_t count,
760 struct fuse_forget_data* forgets) {
Zimec8d5722019-12-05 07:26:13 +0000761 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100762 struct fuse* fuse = get_fuse(req);
763
Narayan Kamathaef84a12020-01-02 15:20:13 +0000764 for (int i = 0; i < count; i++) {
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100765 do_forget(req, fuse, forgets[i].ino, forgets[i].nlookup);
Narayan Kamath768bea32019-12-27 16:23:23 +0000766 }
shafik1e3a2672019-08-16 14:51:55 +0100767 fuse_reply_none(req);
768}
769
Zim9e3c40b2021-04-09 15:51:15 +0100770static void pf_fallocate(fuse_req_t req, fuse_ino_t ino, int mode, off_t offset, off_t length,
771 fuse_file_info* fi) {
772 ATRACE_CALL();
773 struct fuse* fuse = get_fuse(req);
774
Zim9e3c40b2021-04-09 15:51:15 +0100775 handle* h = reinterpret_cast<handle*>(fi->fh);
Zim9e3652b2021-05-05 11:35:00 +0100776 auto err = fallocate(h->fd, mode, offset, length);
Zim23cdfd42021-06-04 16:26:08 +0100777 fuse_reply_err(req, err ? errno : 0);
Zim9e3c40b2021-04-09 15:51:15 +0100778}
779
shafik1e3a2672019-08-16 14:51:55 +0100780static void pf_getattr(fuse_req_t req,
781 fuse_ino_t ino,
782 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +0000783 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100784 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100785 node* node = fuse->FromInode(ino);
Ricky Waif40c4022020-04-15 19:00:06 +0100786 if (!node) {
787 fuse_reply_err(req, ENOENT);
788 return;
789 }
Zim867fece2020-09-23 15:23:19 +0100790 const string& path = get_path(node);
Ricky Wai44670762020-05-01 11:25:28 +0100791 if (!is_app_accessible_path(fuse->mp, path, req->ctx.uid)) {
792 fuse_reply_err(req, ENOENT);
793 return;
794 }
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100795 TRACE_NODE(node, req);
shafik1e3a2672019-08-16 14:51:55 +0100796
Narayan Kamathaef84a12020-01-02 15:20:13 +0000797 struct stat s;
shafik1e3a2672019-08-16 14:51:55 +0100798 memset(&s, 0, sizeof(s));
799 if (lstat(path.c_str(), &s) < 0) {
800 fuse_reply_err(req, errno);
801 } else {
Zim3b6ff4d2021-03-03 11:14:59 +0000802 fuse_reply_attr(req, &s, std::numeric_limits<double>::max());
shafik1e3a2672019-08-16 14:51:55 +0100803 }
804}
805
806static void pf_setattr(fuse_req_t req,
807 fuse_ino_t ino,
808 struct stat* attr,
809 int to_set,
810 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +0000811 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100812 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100813 node* node = fuse->FromInode(ino);
shafik1e3a2672019-08-16 14:51:55 +0100814 if (!node) {
815 fuse_reply_err(req, ENOENT);
816 return;
817 }
Zim867fece2020-09-23 15:23:19 +0100818 const string& path = get_path(node);
Ricky Wai44670762020-05-01 11:25:28 +0100819 if (!is_app_accessible_path(fuse->mp, path, req->ctx.uid)) {
820 fuse_reply_err(req, ENOENT);
821 return;
822 }
Ricky Waif40c4022020-04-15 19:00:06 +0100823
Zimuzo Ezeozue435bd252020-06-30 20:15:17 +0000824 int fd = -1;
825 if (fi) {
826 // If we have a file_info, setattr was called with an fd so use the fd instead of path
827 handle* h = reinterpret_cast<handle*>(fi->fh);
828 fd = h->fd;
829 } else {
830 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Zim73895ba2021-01-13 12:51:20 +0000831 std::unique_ptr<FileOpenResult> result = fuse->mp->OnFileOpen(
Zim801d9852021-01-26 18:30:53 +0000832 path, path, ctx->uid, ctx->pid, node->GetTransformsReason(), true /* for_write */,
833 false /* redact */, false /* log_transforms_metrics */);
Zim73895ba2021-01-13 12:51:20 +0000834
835 if (!result) {
836 fuse_reply_err(req, EFAULT);
837 return;
838 }
839
840 if (result->status) {
Zimuzo Ezeozue435bd252020-06-30 20:15:17 +0000841 fuse_reply_err(req, EACCES);
842 return;
843 }
844 }
845 struct timespec times[2];
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100846 TRACE_NODE(node, req);
shafik1e3a2672019-08-16 14:51:55 +0100847
848 /* XXX: incomplete implementation on purpose.
849 * chmod/chown should NEVER be implemented.*/
850
Zimuzo Ezeozue435bd252020-06-30 20:15:17 +0000851 if ((to_set & FUSE_SET_ATTR_SIZE)) {
852 int res = 0;
853 if (fd == -1) {
854 res = truncate64(path.c_str(), attr->st_size);
855 } else {
856 res = ftruncate64(fd, attr->st_size);
857 }
858
859 if (res < 0) {
860 fuse_reply_err(req, errno);
861 return;
862 }
shafik1e3a2672019-08-16 14:51:55 +0100863 }
864
865 /* Handle changing atime and mtime. If FATTR_ATIME_and FATTR_ATIME_NOW
866 * are both set, then set it to the current time. Else, set it to the
867 * time specified in the request. Same goes for mtime. Use utimensat(2)
868 * as it allows ATIME and MTIME to be changed independently, and has
869 * nanosecond resolution which fuse also has.
870 */
871 if (to_set & (FATTR_ATIME | FATTR_MTIME)) {
872 times[0].tv_nsec = UTIME_OMIT;
873 times[1].tv_nsec = UTIME_OMIT;
874 if (to_set & FATTR_ATIME) {
875 if (to_set & FATTR_ATIME_NOW) {
876 times[0].tv_nsec = UTIME_NOW;
877 } else {
Zim0056c4b2020-04-27 18:56:51 +0100878 times[0] = attr->st_atim;
shafik1e3a2672019-08-16 14:51:55 +0100879 }
880 }
Zim0056c4b2020-04-27 18:56:51 +0100881
shafik1e3a2672019-08-16 14:51:55 +0100882 if (to_set & FATTR_MTIME) {
883 if (to_set & FATTR_MTIME_NOW) {
884 times[1].tv_nsec = UTIME_NOW;
885 } else {
Zim0056c4b2020-04-27 18:56:51 +0100886 times[1] = attr->st_mtim;
shafik1e3a2672019-08-16 14:51:55 +0100887 }
888 }
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +0000889
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100890 TRACE_NODE(node, req);
Zimuzo Ezeozue435bd252020-06-30 20:15:17 +0000891 int res = 0;
892 if (fd == -1) {
893 res = utimensat(-1, path.c_str(), times, 0);
894 } else {
895 res = futimens(fd, times);
896 }
897
898 if (res < 0) {
shafik1e3a2672019-08-16 14:51:55 +0100899 fuse_reply_err(req, errno);
900 return;
901 }
902 }
903
Zima9fcd552019-08-29 15:17:04 +0100904 lstat(path.c_str(), attr);
Zim3b6ff4d2021-03-03 11:14:59 +0000905 fuse_reply_attr(req, attr, std::numeric_limits<double>::max());
shafik1e3a2672019-08-16 14:51:55 +0100906}
Zimb9730bf2019-11-30 15:10:04 +0000907
908static void pf_canonical_path(fuse_req_t req, fuse_ino_t ino)
shafik1e3a2672019-08-16 14:51:55 +0100909{
Ricky Wai44670762020-05-01 11:25:28 +0100910 struct fuse* fuse = get_fuse(req);
911 node* node = fuse->FromInode(ino);
Zim867fece2020-09-23 15:23:19 +0100912 const string& path = node ? get_path(node) : "";
Zimb9730bf2019-11-30 15:10:04 +0000913
Ricky Wai44670762020-05-01 11:25:28 +0100914 if (node && is_app_accessible_path(fuse->mp, path, req->ctx.uid)) {
Zimb9730bf2019-11-30 15:10:04 +0000915 // TODO(b/147482155): Check that uid has access to |path| and its contents
Ricky Wai44670762020-05-01 11:25:28 +0100916 fuse_reply_canonical_path(req, path.c_str());
Zimb9730bf2019-11-30 15:10:04 +0000917 return;
918 }
919 fuse_reply_err(req, ENOENT);
shafik1e3a2672019-08-16 14:51:55 +0100920}
Zimb9730bf2019-11-30 15:10:04 +0000921
shafik1e3a2672019-08-16 14:51:55 +0100922static void pf_mknod(fuse_req_t req,
923 fuse_ino_t parent,
924 const char* name,
925 mode_t mode,
926 dev_t rdev) {
Zimec8d5722019-12-05 07:26:13 +0000927 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100928 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100929 node* parent_node = fuse->FromInode(parent);
shafik1e3a2672019-08-16 14:51:55 +0100930 if (!parent_node) {
931 fuse_reply_err(req, ENOENT);
932 return;
933 }
Ricky Waif40c4022020-04-15 19:00:06 +0100934 string parent_path = parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +0100935 if (!is_app_accessible_path(fuse->mp, parent_path, req->ctx.uid)) {
936 fuse_reply_err(req, ENOENT);
937 return;
938 }
Ricky Waif40c4022020-04-15 19:00:06 +0100939
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100940 TRACE_NODE(parent_node, req);
Ricky Waif40c4022020-04-15 19:00:06 +0100941
Narayan Kamathaef84a12020-01-02 15:20:13 +0000942 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100943
944 mode = (mode & (~0777)) | 0664;
945 if (mknod(child_path.c_str(), mode, rdev) < 0) {
946 fuse_reply_err(req, errno);
947 return;
948 }
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000949
950 int error_code = 0;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000951 struct fuse_entry_param e;
]3e9d56c2021-03-15 16:24:17 +0000952 if (make_node_entry(req, parent_node, name, child_path, &e, &error_code, FuseOp::mknod)) {
shafik1e3a2672019-08-16 14:51:55 +0100953 fuse_reply_entry(req, &e);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000954 } else {
955 CHECK(error_code != 0);
956 fuse_reply_err(req, error_code);
957 }
shafik1e3a2672019-08-16 14:51:55 +0100958}
959
960static void pf_mkdir(fuse_req_t req,
961 fuse_ino_t parent,
962 const char* name,
963 mode_t mode) {
Zimec8d5722019-12-05 07:26:13 +0000964 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100965 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100966 node* parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +0100967 if (!parent_node) {
968 fuse_reply_err(req, ENOENT);
969 return;
970 }
Ricky Wai44670762020-05-01 11:25:28 +0100971 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000972 const string parent_path = parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +0100973 if (!is_app_accessible_path(fuse->mp, parent_path, ctx->uid)) {
974 fuse_reply_err(req, ENOENT);
975 return;
976 }
Narayan Kamath768bea32019-12-27 16:23:23 +0000977
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100978 TRACE_NODE(parent_node, req);
shafik1e3a2672019-08-16 14:51:55 +0100979
Narayan Kamathaef84a12020-01-02 15:20:13 +0000980 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100981
shafike4fb1462020-01-29 16:25:23 +0000982 int status = fuse->mp->IsCreatingDirAllowed(child_path, ctx->uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000983 if (status) {
984 fuse_reply_err(req, status);
985 return;
986 }
987
shafik1e3a2672019-08-16 14:51:55 +0100988 mode = (mode & (~0777)) | 0775;
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000989 if (mkdir(child_path.c_str(), mode) < 0) {
shafik1e3a2672019-08-16 14:51:55 +0100990 fuse_reply_err(req, errno);
991 return;
992 }
993
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000994 int error_code = 0;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000995 struct fuse_entry_param e;
]3e9d56c2021-03-15 16:24:17 +0000996 if (make_node_entry(req, parent_node, name, child_path, &e, &error_code, FuseOp::mkdir)) {
shafik1e3a2672019-08-16 14:51:55 +0100997 fuse_reply_entry(req, &e);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000998 } else {
999 CHECK(error_code != 0);
1000 fuse_reply_err(req, error_code);
1001 }
shafik1e3a2672019-08-16 14:51:55 +01001002}
1003
1004static void pf_unlink(fuse_req_t req, fuse_ino_t parent, const char* name) {
Zimec8d5722019-12-05 07:26:13 +00001005 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001006 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +01001007 node* parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +01001008 if (!parent_node) {
1009 fuse_reply_err(req, ENOENT);
1010 return;
1011 }
Ricky Wai44670762020-05-01 11:25:28 +01001012 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001013 const string parent_path = parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +01001014 if (!is_app_accessible_path(fuse->mp, parent_path, ctx->uid)) {
1015 fuse_reply_err(req, ENOENT);
1016 return;
1017 }
shafik1e3a2672019-08-16 14:51:55 +01001018
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001019 TRACE_NODE(parent_node, req);
shafik1e3a2672019-08-16 14:51:55 +01001020
Narayan Kamathaef84a12020-01-02 15:20:13 +00001021 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +01001022
shafike4fb1462020-01-29 16:25:23 +00001023 int status = fuse->mp->DeleteFile(child_path, ctx->uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001024 if (status) {
1025 fuse_reply_err(req, status);
shafik1e3a2672019-08-16 14:51:55 +01001026 return;
1027 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001028
Zim53c2d702020-09-23 12:18:27 +01001029 // TODO(b/169306422): Log each deleted node
1030 parent_node->SetDeletedForChild(name);
shafik1e3a2672019-08-16 14:51:55 +01001031 fuse_reply_err(req, 0);
1032}
1033
1034static void pf_rmdir(fuse_req_t req, fuse_ino_t parent, const char* name) {
Zimec8d5722019-12-05 07:26:13 +00001035 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001036 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +01001037 node* parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +01001038 if (!parent_node) {
1039 fuse_reply_err(req, ENOENT);
1040 return;
1041 }
Narayan Kamathaef84a12020-01-02 15:20:13 +00001042 const string parent_path = parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +01001043 if (!is_app_accessible_path(fuse->mp, parent_path, req->ctx.uid)) {
1044 fuse_reply_err(req, ENOENT);
1045 return;
1046 }
]3e9d56c2021-03-15 16:24:17 +00001047
1048 if (is_transforms_dir_path(parent_path, fuse)) {
1049 // .transforms is a special daemon controlled dir so apps shouldn't be able to see it via
1050 // readdir, and any dir operations attempted on it should fail
1051 fuse_reply_err(req, ENOENT);
1052 return;
1053 }
1054
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001055 TRACE_NODE(parent_node, req);
shafik1e3a2672019-08-16 14:51:55 +01001056
Narayan Kamathaef84a12020-01-02 15:20:13 +00001057 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +01001058
Ricky Wai44670762020-05-01 11:25:28 +01001059 int status = fuse->mp->IsDeletingDirAllowed(child_path, req->ctx.uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001060 if (status) {
1061 fuse_reply_err(req, status);
1062 return;
1063 }
1064
1065 if (rmdir(child_path.c_str()) < 0) {
shafik1e3a2672019-08-16 14:51:55 +01001066 fuse_reply_err(req, errno);
1067 return;
1068 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001069
Narayan Kamatheca34252020-02-11 13:08:37 +00001070 node* child_node = parent_node->LookupChildByName(name, false /* acquire */);
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001071 TRACE_NODE(child_node, req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001072 if (child_node) {
1073 child_node->SetDeleted();
shafik1e3a2672019-08-16 14:51:55 +01001074 }
shafik1e3a2672019-08-16 14:51:55 +01001075
1076 fuse_reply_err(req, 0);
1077}
1078/*
1079static void pf_symlink(fuse_req_t req, const char* link, fuse_ino_t parent,
1080 const char* name)
1081{
1082 cout << "TODO:" << __func__;
1083}
1084*/
Sahana Rao2c416032019-12-31 13:41:00 +00001085static int do_rename(fuse_req_t req, fuse_ino_t parent, const char* name, fuse_ino_t new_parent,
1086 const char* new_name, unsigned int flags) {
Zimec8d5722019-12-05 07:26:13 +00001087 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001088 struct fuse* fuse = get_fuse(req);
shafik1e3a2672019-08-16 14:51:55 +01001089
Sahana Rao2c416032019-12-31 13:41:00 +00001090 if (flags != 0) {
Sahana Rao2c416032019-12-31 13:41:00 +00001091 return EINVAL;
1092 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001093
Ricky Wai44670762020-05-01 11:25:28 +01001094 node* old_parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +01001095 if (!old_parent_node) return ENOENT;
Ricky Wai44670762020-05-01 11:25:28 +01001096 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001097 const string old_parent_path = old_parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +01001098 if (!is_app_accessible_path(fuse->mp, old_parent_path, ctx->uid)) {
1099 return ENOENT;
1100 }
1101
]3e9d56c2021-03-15 16:24:17 +00001102 if (is_transforms_dir_path(old_parent_path, fuse)) {
1103 // .transforms is a special daemon controlled dir so apps shouldn't be able to see it via
1104 // readdir, and any dir operations attempted on it should fail
1105 return ENOENT;
1106 }
1107
Ricky Wai44670762020-05-01 11:25:28 +01001108 node* new_parent_node = fuse->FromInode(new_parent);
Ricky Waif40c4022020-04-15 19:00:06 +01001109 if (!new_parent_node) return ENOENT;
Narayan Kamathaef84a12020-01-02 15:20:13 +00001110 const string new_parent_path = new_parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +01001111 if (!is_app_accessible_path(fuse->mp, new_parent_path, ctx->uid)) {
1112 return ENOENT;
1113 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001114
Narayan Kamathaef84a12020-01-02 15:20:13 +00001115 if (!old_parent_node || !new_parent_node) {
1116 return ENOENT;
1117 } else if (parent == new_parent && name == new_name) {
1118 // No rename required.
1119 return 0;
shafik1e3a2672019-08-16 14:51:55 +01001120 }
1121
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001122 TRACE_NODE(old_parent_node, req);
1123 TRACE_NODE(new_parent_node, req);
shafik1e3a2672019-08-16 14:51:55 +01001124
Zim53c2d702020-09-23 12:18:27 +01001125 const string old_child_path = old_parent_path + "/" + name;
Narayan Kamathaef84a12020-01-02 15:20:13 +00001126 const string new_child_path = new_parent_path + "/" + new_name;
1127
Zimbd89e7a2021-01-27 19:02:11 +00001128 if (android::base::EqualsIgnoreCase(fuse->GetEffectiveRootPath() + "/android", old_child_path)) {
1129 // Prevent renaming Android/ dir since it contains bind-mounts on the primary volume
1130 return EACCES;
1131 }
1132
Sahana Rao182ec6b2020-01-03 15:00:46 +00001133 // TODO(b/147408834): Check ENOTEMPTY & EEXIST error conditions before JNI call.
shafike4fb1462020-01-29 16:25:23 +00001134 const int res = fuse->mp->Rename(old_child_path, new_child_path, req->ctx.uid);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001135 // TODO(b/145663158): Lookups can go out of sync if file/directory is actually moved but
1136 // EFAULT/EIO is reported due to JNI exception.
1137 if (res == 0) {
Zim53c2d702020-09-23 12:18:27 +01001138 // TODO(b/169306422): Log each renamed node
1139 old_parent_node->RenameChild(name, new_name, new_parent_node);
shafik1e3a2672019-08-16 14:51:55 +01001140 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001141 return res;
1142}
shafik1e3a2672019-08-16 14:51:55 +01001143
Sahana Rao2c416032019-12-31 13:41:00 +00001144static void pf_rename(fuse_req_t req, fuse_ino_t parent, const char* name, fuse_ino_t new_parent,
1145 const char* new_name, unsigned int flags) {
1146 int res = do_rename(req, parent, name, new_parent, new_name, flags);
shafik1e3a2672019-08-16 14:51:55 +01001147 fuse_reply_err(req, res);
1148}
Narayan Kamath768bea32019-12-27 16:23:23 +00001149
shafik1e3a2672019-08-16 14:51:55 +01001150/*
Sahana Rao2c416032019-12-31 13:41:00 +00001151static void pf_link(fuse_req_t req, fuse_ino_t ino, fuse_ino_t new_parent,
1152 const char* new_name)
shafik1e3a2672019-08-16 14:51:55 +01001153{
1154 cout << "TODO:" << __func__;
1155}
1156*/
1157
Zim9aa6f542020-10-19 15:39:33 +01001158static handle* create_handle_for_node(struct fuse* fuse, const string& path, int fd, uid_t uid,
Manish Singh9a6ccce2021-02-05 23:50:08 +00001159 uid_t transforms_uid, node* node, const RedactionInfo* ri,
1160 int* keep_cache) {
Zimc05c60f2020-03-05 13:02:26 +00001161 std::lock_guard<std::recursive_mutex> guard(fuse->lock);
Zimc05c60f2020-03-05 13:02:26 +00001162
Zim148cbe22020-11-17 15:58:29 +00001163 bool redaction_needed = ri->isRedactionNeeded();
1164 handle* handle = nullptr;
Manish Singh9a6ccce2021-02-05 23:50:08 +00001165 int transforms = node->GetTransforms();
Zime5433682021-03-10 12:06:54 +00001166 bool transforms_complete = node->IsTransformsComplete();
Manish Singh9a6ccce2021-02-05 23:50:08 +00001167 if (transforms_uid > 0) {
1168 CHECK(transforms);
1169 }
Zim148cbe22020-11-17 15:58:29 +00001170
1171 if (fuse->passthrough) {
Zime5433682021-03-10 12:06:54 +00001172 *keep_cache = transforms_complete;
Zimuzo Ezeozue158b6582021-03-04 12:50:54 +00001173 // We only enabled passthrough iff these 2 conditions hold
1174 // 1. Redaction is not needed
1175 // 2. Node transforms are completed, e.g transcoding.
1176 // (2) is important because we transcode lazily (on the first read) and with passthrough,
1177 // we will never get a read into the FUSE daemon, so passthrough would have returned
1178 // arbitrary bytes the first time around. However, if we ensure that transforms are
1179 // completed, then it's safe to use passthrough. Additionally, transcoded nodes never
1180 // require redaction so (2) implies (1)
Zime5433682021-03-10 12:06:54 +00001181 handle = new struct handle(fd, ri, true /* cached */,
1182 !redaction_needed && transforms_complete /* passthrough */, uid,
1183 transforms_uid);
Zim148cbe22020-11-17 15:58:29 +00001184 } else {
1185 // Without fuse->passthrough, we don't want to use the FUSE VFS cache in two cases:
1186 // 1. When redaction is needed because app A with EXIF access might access
1187 // a region that should have been redacted for app B without EXIF access, but app B on
1188 // a subsequent read, will be able to see the EXIF data because the read request for
1189 // that region will be served from cache and not get to the FUSE daemon
1190 // 2. When the file has a read or write lock on it. This means that the MediaProvider
1191 // has given an fd to the lower file system to an app. There are two cases where using
1192 // the cache in this case can be a problem:
1193 // a. Writing to a FUSE fd with caching enabled will use the write-back cache and a
1194 // subsequent read from the lower fs fd will not see the write.
1195 // b. Reading from a FUSE fd with caching enabled may not see the latest writes using
1196 // the lower fs fd because those writes did not go through the FUSE layer and reads from
1197 // FUSE after that write may be served from cache
1198 bool has_redacted = node->HasRedactedCache();
1199 bool is_redaction_change =
1200 (redaction_needed && !has_redacted) || (!redaction_needed && has_redacted);
1201 bool is_cached_file_open = node->HasCachedHandle();
1202 bool direct_io = (is_cached_file_open && is_redaction_change) || is_file_locked(fd, path);
1203
1204 if (!is_cached_file_open && is_redaction_change) {
1205 node->SetRedactedCache(redaction_needed);
1206 // Purges stale page cache before open
1207 *keep_cache = 0;
1208 } else {
Zime5433682021-03-10 12:06:54 +00001209 *keep_cache = transforms_complete;
Zim148cbe22020-11-17 15:58:29 +00001210 }
Manish Singh9a6ccce2021-02-05 23:50:08 +00001211 handle = new struct handle(fd, ri, !direct_io /* cached */, false /* passthrough */, uid,
1212 transforms_uid);
Zim329ba2c2020-09-16 14:23:26 +01001213 }
1214
Zim148cbe22020-11-17 15:58:29 +00001215 node->AddHandle(handle);
1216 return handle;
Zimc05c60f2020-03-05 13:02:26 +00001217}
1218
Alessio Balsinif220a962020-07-13 12:01:13 +01001219bool do_passthrough_enable(fuse_req_t req, struct fuse_file_info* fi, unsigned int fd) {
1220 int passthrough_fh = fuse_passthrough_enable(req, fd);
1221
1222 if (passthrough_fh <= 0) {
1223 return false;
1224 }
1225
1226 fi->passthrough_fh = passthrough_fh;
1227 return true;
1228}
1229
shafik1e3a2672019-08-16 14:51:55 +01001230static void pf_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001231 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001232 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +01001233 node* node = fuse->FromInode(ino);
shafik1e3a2672019-08-16 14:51:55 +01001234 if (!node) {
1235 fuse_reply_err(req, ENOENT);
1236 return;
1237 }
Ricky Wai44670762020-05-01 11:25:28 +01001238 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Zime9ae6ee2020-11-26 15:38:13 +00001239 const string& io_path = get_path(node);
Zimf7ec8672020-10-28 18:25:45 +00001240 const string& build_path = node->BuildPath();
Zime9ae6ee2020-11-26 15:38:13 +00001241 if (!is_app_accessible_path(fuse->mp, io_path, ctx->uid)) {
Ricky Wai44670762020-05-01 11:25:28 +01001242 fuse_reply_err(req, ENOENT);
1243 return;
1244 }
Ricky Waif40c4022020-04-15 19:00:06 +01001245
Manish Singh0f79b452021-03-04 00:20:38 +00001246 bool for_write = is_requesting_write(fi->flags);
1247
1248 if (for_write && node->GetTransforms()) {
1249 TRACE_NODE(node, req) << "write with transforms";
1250 } else {
1251 TRACE_NODE(node, req) << (for_write ? "write" : "read");
1252 }
shafik1e3a2672019-08-16 14:51:55 +01001253
shafik15e2d612019-10-31 20:10:25 +00001254 if (fi->flags & O_DIRECT) {
1255 fi->flags &= ~O_DIRECT;
1256 fi->direct_io = true;
1257 }
1258
Zimf7ec8672020-10-28 18:25:45 +00001259 // Force permission check with the build path because the MediaProvider database might not be
1260 // aware of the io_path
Zim73895ba2021-01-13 12:51:20 +00001261 // We don't redact if the caller was granted write permission for this file
1262 std::unique_ptr<FileOpenResult> result = fuse->mp->OnFileOpen(
Zim801d9852021-01-26 18:30:53 +00001263 build_path, io_path, ctx->uid, ctx->pid, node->GetTransformsReason(), for_write,
1264 !for_write /* redact */, true /* log_transforms_metrics */);
Zim73895ba2021-01-13 12:51:20 +00001265 if (!result) {
1266 fuse_reply_err(req, EFAULT);
1267 return;
1268 }
1269
1270 if (result->status) {
1271 fuse_reply_err(req, result->status);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001272 return;
1273 }
1274
Martijn Coenen2d7f1be2020-02-15 07:44:12 +01001275 // With the writeback cache enabled, FUSE may generate READ requests even for files that
1276 // were opened O_WRONLY; so make sure we open it O_RDWR instead.
1277 int open_flags = fi->flags;
1278 if (open_flags & O_WRONLY) {
1279 open_flags &= ~O_WRONLY;
1280 open_flags |= O_RDWR;
1281 }
1282
Zim1b14f2f2020-07-03 07:05:53 +01001283 if (open_flags & O_APPEND) {
1284 open_flags &= ~O_APPEND;
1285 }
1286
Zime9ae6ee2020-11-26 15:38:13 +00001287 const int fd = open(io_path.c_str(), open_flags);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001288 if (fd < 0) {
shafik1e3a2672019-08-16 14:51:55 +01001289 fuse_reply_err(req, errno);
1290 return;
1291 }
shafik15e2d612019-10-31 20:10:25 +00001292
Zim329ba2c2020-09-16 14:23:26 +01001293 int keep_cache = 1;
Manish Singh9a6ccce2021-02-05 23:50:08 +00001294 handle* h = create_handle_for_node(fuse, io_path, fd, result->uid, result->transforms_uid, node,
Zim73895ba2021-01-13 12:51:20 +00001295 result->redaction_info.release(), &keep_cache);
shafik1e3a2672019-08-16 14:51:55 +01001296 fi->fh = ptr_to_id(h);
Zim329ba2c2020-09-16 14:23:26 +01001297 fi->keep_cache = keep_cache;
Zimc05c60f2020-03-05 13:02:26 +00001298 fi->direct_io = !h->cached;
Alessio Balsinif220a962020-07-13 12:01:13 +01001299
1300 // TODO(b/173190192) ensuring that h->cached must be enabled in order to
1301 // user FUSE passthrough is a conservative rule and might be dropped as
1302 // soon as demonstrated its correctness.
Zim148cbe22020-11-17 15:58:29 +00001303 if (h->passthrough) {
Alessio Balsinif220a962020-07-13 12:01:13 +01001304 if (!do_passthrough_enable(req, fi, fd)) {
Zim148cbe22020-11-17 15:58:29 +00001305 // TODO: Should we crash here so we can find errors easily?
Zime9ae6ee2020-11-26 15:38:13 +00001306 PLOG(ERROR) << "Passthrough OPEN failed for " << io_path;
Zim148cbe22020-11-17 15:58:29 +00001307 fuse_reply_err(req, EFAULT);
1308 return;
Alessio Balsinif220a962020-07-13 12:01:13 +01001309 }
1310 }
1311
shafik1e3a2672019-08-16 14:51:55 +01001312 fuse_reply_open(req, fi);
1313}
1314
shafikc3f62672019-08-30 11:15:48 +01001315static void do_read(fuse_req_t req, size_t size, off_t off, struct fuse_file_info* fi) {
shafika2ae9072019-10-28 12:16:00 +00001316 handle* h = reinterpret_cast<handle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001317 struct fuse_bufvec buf = FUSE_BUFVEC_INIT(size);
1318
1319 buf.buf[0].fd = h->fd;
1320 buf.buf[0].pos = off;
1321 buf.buf[0].flags =
1322 (enum fuse_buf_flags) (FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
1323
1324 fuse_reply_data(req, &buf, (enum fuse_buf_copy_flags) 0);
1325}
shafikc3f62672019-08-30 11:15:48 +01001326
shafikc3f62672019-08-30 11:15:48 +01001327/**
1328 * Sets the parameters for a fuse_buf that reads from memory, including flags.
shafikb334a612019-09-30 20:38:16 +01001329 * Makes buf->mem point to an already mapped region of zeroized memory.
1330 * This memory is read only.
shafikc3f62672019-08-30 11:15:48 +01001331 */
shafikb334a612019-09-30 20:38:16 +01001332static void create_mem_fuse_buf(size_t size, fuse_buf* buf, struct fuse* fuse) {
shafikc3f62672019-08-30 11:15:48 +01001333 buf->size = size;
shafikb334a612019-09-30 20:38:16 +01001334 buf->mem = fuse->zero_addr;
shafikc3f62672019-08-30 11:15:48 +01001335 buf->flags = static_cast<fuse_buf_flags>(0 /*read from fuse_buf.mem*/);
1336 buf->pos = -1;
1337 buf->fd = -1;
1338}
1339
1340/**
1341 * Sets the parameters for a fuse_buf that reads from file, including flags.
1342 */
1343static void create_file_fuse_buf(size_t size, off_t pos, int fd, fuse_buf* buf) {
1344 buf->size = size;
1345 buf->fd = fd;
1346 buf->pos = pos;
1347 buf->flags = static_cast<fuse_buf_flags>(FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
1348 buf->mem = nullptr;
1349}
1350
1351static void do_read_with_redaction(fuse_req_t req, size_t size, off_t off, fuse_file_info* fi) {
shafika2ae9072019-10-28 12:16:00 +00001352 handle* h = reinterpret_cast<handle*>(fi->fh);
shafikc3f62672019-08-30 11:15:48 +01001353
Narayan Kamath11700c02020-10-06 09:15:34 +01001354 std::vector<ReadRange> ranges;
1355 h->ri->getReadRanges(off, size, &ranges);
1356
1357 // As an optimization, return early if there are no ranges to redact.
1358 if (ranges.size() == 0) {
shafikc3f62672019-08-30 11:15:48 +01001359 do_read(req, size, off, fi);
1360 return;
1361 }
Narayan Kamath11700c02020-10-06 09:15:34 +01001362
1363 const size_t num_bufs = ranges.size();
shafikc3f62672019-08-30 11:15:48 +01001364 auto bufvec_ptr = std::unique_ptr<fuse_bufvec, decltype(free)*>{
1365 reinterpret_cast<fuse_bufvec*>(
1366 malloc(sizeof(fuse_bufvec) + (num_bufs - 1) * sizeof(fuse_buf))),
1367 free};
1368 fuse_bufvec& bufvec = *bufvec_ptr;
1369
1370 // initialize bufvec
1371 bufvec.count = num_bufs;
1372 bufvec.idx = 0;
1373 bufvec.off = 0;
shafikc3f62672019-08-30 11:15:48 +01001374
shafikc3f62672019-08-30 11:15:48 +01001375 for (int i = 0; i < num_bufs; ++i) {
Narayan Kamath11700c02020-10-06 09:15:34 +01001376 const ReadRange& range = ranges[i];
1377 if (range.is_redaction) {
1378 create_mem_fuse_buf(range.size, &(bufvec.buf[i]), get_fuse(req));
shafikc3f62672019-08-30 11:15:48 +01001379 } else {
Narayan Kamath11700c02020-10-06 09:15:34 +01001380 create_file_fuse_buf(range.size, range.start, h->fd, &(bufvec.buf[i]));
shafikc3f62672019-08-30 11:15:48 +01001381 }
shafikc3f62672019-08-30 11:15:48 +01001382 }
1383
1384 fuse_reply_data(req, &bufvec, static_cast<fuse_buf_copy_flags>(0));
1385}
1386
1387static void pf_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off,
1388 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001389 ATRACE_CALL();
shafika2ae9072019-10-28 12:16:00 +00001390 handle* h = reinterpret_cast<handle*>(fi->fh);
shafikc3f62672019-08-30 11:15:48 +01001391 struct fuse* fuse = get_fuse(req);
shafikc3f62672019-08-30 11:15:48 +01001392
Zim867fece2020-09-23 15:23:19 +01001393 node* node = fuse->FromInode(ino);
1394
1395 if (!node->IsTransformsComplete()) {
1396 if (!fuse->mp->Transform(node->BuildPath(), node->GetIoPath(), node->GetTransforms(),
Manish Singh9a6ccce2021-02-05 23:50:08 +00001397 node->GetTransformsReason(), req->ctx.uid, h->uid,
1398 h->transforms_uid)) {
Zim867fece2020-09-23 15:23:19 +01001399 fuse_reply_err(req, EFAULT);
1400 return;
1401 }
Zime5433682021-03-10 12:06:54 +00001402 node->SetTransformsComplete(true);
Zim867fece2020-09-23 15:23:19 +01001403 }
1404
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001405 fuse->fadviser.Record(h->fd, size);
1406
shafikc3f62672019-08-30 11:15:48 +01001407 if (h->ri->isRedactionNeeded()) {
1408 do_read_with_redaction(req, size, off, fi);
1409 } else {
1410 do_read(req, size, off, fi);
1411 }
1412}
1413
shafik1e3a2672019-08-16 14:51:55 +01001414/*
1415static void pf_write(fuse_req_t req, fuse_ino_t ino, const char* buf,
1416 size_t size, off_t off, struct fuse_file_info* fi)
1417{
1418 cout << "TODO:" << __func__;
1419}
1420*/
1421
1422static void pf_write_buf(fuse_req_t req,
1423 fuse_ino_t ino,
1424 struct fuse_bufvec* bufv,
1425 off_t off,
1426 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001427 ATRACE_CALL();
shafika2ae9072019-10-28 12:16:00 +00001428 handle* h = reinterpret_cast<handle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001429 struct fuse_bufvec buf = FUSE_BUFVEC_INIT(fuse_buf_size(bufv));
1430 ssize_t size;
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001431 struct fuse* fuse = get_fuse(req);
shafik1e3a2672019-08-16 14:51:55 +01001432
1433 buf.buf[0].fd = h->fd;
1434 buf.buf[0].pos = off;
1435 buf.buf[0].flags =
1436 (enum fuse_buf_flags) (FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
1437 size = fuse_buf_copy(&buf, bufv, (enum fuse_buf_copy_flags) 0);
1438
1439 if (size < 0)
1440 fuse_reply_err(req, -size);
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001441 else {
Zimf38de0b2021-08-05 15:29:02 +01001442 // Execute Record *before* fuse_reply_write to avoid the following ordering:
1443 // fuse_reply_write -> pf_release (destroy handle) -> Record (use handle after free)
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001444 fuse->fadviser.Record(h->fd, size);
Zimf38de0b2021-08-05 15:29:02 +01001445 fuse_reply_write(req, size);
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001446 }
shafik1e3a2672019-08-16 14:51:55 +01001447}
1448// Haven't tested this one. Not sure what calls it.
1449#if 0
1450static void pf_copy_file_range(fuse_req_t req, fuse_ino_t ino_in,
1451 off_t off_in, struct fuse_file_info* fi_in,
1452 fuse_ino_t ino_out, off_t off_out,
1453 struct fuse_file_info* fi_out, size_t len,
1454 int flags)
1455{
shafika2ae9072019-10-28 12:16:00 +00001456 handle* h_in = reinterpret_cast<handle *>(fi_in->fh);
1457 handle* h_out = reinterpret_cast<handle *>(fi_out->fh);
shafik1e3a2672019-08-16 14:51:55 +01001458 struct fuse_bufvec buf_in = FUSE_BUFVEC_INIT(len);
1459 struct fuse_bufvec buf_out = FUSE_BUFVEC_INIT(len);
1460 ssize_t size;
1461
1462 buf_in.buf[0].fd = h_in->fd;
1463 buf_in.buf[0].pos = off_in;
1464 buf_in.buf[0].flags = (enum fuse_buf_flags)(FUSE_BUF_IS_FD|FUSE_BUF_FD_SEEK);
1465
1466 buf_out.buf[0].fd = h_out->fd;
1467 buf_out.buf[0].pos = off_out;
1468 buf_out.buf[0].flags = (enum fuse_buf_flags)(FUSE_BUF_IS_FD|FUSE_BUF_FD_SEEK);
1469 size = fuse_buf_copy(&buf_out, &buf_in, (enum fuse_buf_copy_flags) 0);
1470
1471 if (size < 0) {
1472 fuse_reply_err(req, -size);
1473 }
1474
1475 fuse_reply_write(req, size);
1476}
1477#endif
shafik1e3a2672019-08-16 14:51:55 +01001478
1479static void pf_release(fuse_req_t req,
1480 fuse_ino_t ino,
1481 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001482 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001483 struct fuse* fuse = get_fuse(req);
Kyle Tso613b7ab2019-12-24 06:30:00 +00001484
Ricky Wai44670762020-05-01 11:25:28 +01001485 node* node = fuse->FromInode(ino);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001486 handle* h = reinterpret_cast<handle*>(fi->fh);
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001487 TRACE_NODE(node, req);
shafik15e2d612019-10-31 20:10:25 +00001488
Narayan Kamathaef84a12020-01-02 15:20:13 +00001489 fuse->fadviser.Close(h->fd);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001490 if (node) {
1491 node->DestroyHandle(h);
Zimedbe69e2019-12-13 18:49:36 +00001492 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001493
shafik1e3a2672019-08-16 14:51:55 +01001494 fuse_reply_err(req, 0);
1495}
1496
1497static int do_sync_common(int fd, bool datasync) {
1498 int res = datasync ? fdatasync(fd) : fsync(fd);
1499
1500 if (res == -1) return errno;
1501 return 0;
1502}
1503
1504static void pf_fsync(fuse_req_t req,
1505 fuse_ino_t ino,
1506 int datasync,
1507 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001508 ATRACE_CALL();
shafika2ae9072019-10-28 12:16:00 +00001509 handle* h = reinterpret_cast<handle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001510 int err = do_sync_common(h->fd, datasync);
1511
1512 fuse_reply_err(req, err);
1513}
1514
1515static void pf_fsyncdir(fuse_req_t req,
1516 fuse_ino_t ino,
1517 int datasync,
1518 struct fuse_file_info* fi) {
Narayan Kamathaef84a12020-01-02 15:20:13 +00001519 dirhandle* h = reinterpret_cast<dirhandle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001520 int err = do_sync_common(dirfd(h->d), datasync);
1521
1522 fuse_reply_err(req, err);
1523}
1524
1525static void pf_opendir(fuse_req_t req,
1526 fuse_ino_t ino,
1527 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001528 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001529 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +01001530 node* node = fuse->FromInode(ino);
shafik1e3a2672019-08-16 14:51:55 +01001531 if (!node) {
1532 fuse_reply_err(req, ENOENT);
1533 return;
1534 }
Ricky Wai44670762020-05-01 11:25:28 +01001535 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Ricky Waif40c4022020-04-15 19:00:06 +01001536 const string path = node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +01001537 if (!is_app_accessible_path(fuse->mp, path, ctx->uid)) {
1538 fuse_reply_err(req, ENOENT);
1539 return;
1540 }
Ricky Waif40c4022020-04-15 19:00:06 +01001541
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001542 TRACE_NODE(node, req);
shafik1e3a2672019-08-16 14:51:55 +01001543
Nandana Dutt5fc32012020-06-25 10:55:52 +01001544 int status = fuse->mp->IsOpendirAllowed(path, ctx->uid, /* forWrite */ false);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001545 if (status) {
1546 fuse_reply_err(req, status);
1547 return;
1548 }
1549
1550 DIR* dir = opendir(path.c_str());
1551 if (!dir) {
shafik1e3a2672019-08-16 14:51:55 +01001552 fuse_reply_err(req, errno);
1553 return;
1554 }
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001555
Narayan Kamathaef84a12020-01-02 15:20:13 +00001556 dirhandle* h = new dirhandle(dir);
1557 node->AddDirHandle(h);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001558
shafik1e3a2672019-08-16 14:51:55 +01001559 fi->fh = ptr_to_id(h);
1560 fuse_reply_open(req, fi);
1561}
1562
1563#define READDIR_BUF 8192LU
1564
1565static void do_readdir_common(fuse_req_t req,
1566 fuse_ino_t ino,
1567 size_t size,
1568 off_t off,
1569 struct fuse_file_info* fi,
1570 bool plus) {
1571 struct fuse* fuse = get_fuse(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001572 dirhandle* h = reinterpret_cast<dirhandle*>(fi->fh);
Jeff Sharkey7469b982019-08-28 16:51:02 -06001573 size_t len = std::min<size_t>(size, READDIR_BUF);
shafik1e3a2672019-08-16 14:51:55 +01001574 char buf[READDIR_BUF];
1575 size_t used = 0;
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001576 std::shared_ptr<DirectoryEntry> de;
1577
shafik1e3a2672019-08-16 14:51:55 +01001578 struct fuse_entry_param e;
Sahana Rao6f9ea982019-09-20 12:21:33 +01001579 size_t entry_size = 0;
shafik1e3a2672019-08-16 14:51:55 +01001580
Ricky Wai44670762020-05-01 11:25:28 +01001581 node* node = fuse->FromInode(ino);
Ricky Waif40c4022020-04-15 19:00:06 +01001582 if (!node) {
1583 fuse_reply_err(req, ENOENT);
1584 return;
1585 }
Narayan Kamathaef84a12020-01-02 15:20:13 +00001586 const string path = node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +01001587 if (!is_app_accessible_path(fuse->mp, path, req->ctx.uid)) {
1588 fuse_reply_err(req, ENOENT);
1589 return;
1590 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001591
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001592 TRACE_NODE(node, req);
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001593 // Get all directory entries from MediaProvider on first readdir() call of
1594 // directory handle. h->next_off = 0 indicates that current readdir() call
1595 // is first readdir() call for the directory handle, Avoid multiple JNI calls
1596 // for single directory handle.
1597 if (h->next_off == 0) {
Sahana Rao71693442019-11-13 13:48:07 +00001598 h->de = fuse->mp->GetDirectoryEntries(req->ctx.uid, path, h->d);
shafik1e3a2672019-08-16 14:51:55 +01001599 }
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001600 // If the last entry in the previous readdir() call was rejected due to
1601 // buffer capacity constraints, update directory offset to start from
1602 // previously rejected entry. Directory offset can also change if there was
Sahana Rao71693442019-11-13 13:48:07 +00001603 // a seekdir() on the given directory handle.
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001604 if (off != h->next_off) {
1605 h->next_off = off;
1606 }
1607 const int num_directory_entries = h->de.size();
Sahana Rao71693442019-11-13 13:48:07 +00001608 // Check for errors. Any error/exception occurred while obtaining directory
1609 // entries will be indicated by marking first directory entry name as empty
1610 // string. In the erroneous case corresponding d_type will hold error number.
Sahana Rao53bd1f62019-12-27 20:18:39 +00001611 if (num_directory_entries && h->de[0]->d_name.empty()) {
1612 fuse_reply_err(req, h->de[0]->d_type);
1613 return;
1614 }
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001615
Sahana Rao53bd1f62019-12-27 20:18:39 +00001616 while (h->next_off < num_directory_entries) {
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001617 de = h->de[h->next_off];
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001618 entry_size = 0;
1619 h->next_off++;
shafik1e3a2672019-08-16 14:51:55 +01001620 if (plus) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001621 int error_code = 0;
]3e9d56c2021-03-15 16:24:17 +00001622 if (do_lookup(req, ino, de->d_name.c_str(), &e, &error_code, FuseOp::readdir)) {
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001623 entry_size = fuse_add_direntry_plus(req, buf + used, len - used, de->d_name.c_str(),
1624 &e, h->next_off);
Sahana Rao8a588e72019-12-06 11:32:56 +00001625 } else {
Sahana Rao8d8dbb42019-12-18 12:57:02 +00001626 // Ignore lookup errors on
1627 // 1. non-existing files returned from MediaProvider database.
1628 // 2. path that doesn't match FuseDaemon UID and calling uid.
likaid31e75b2020-12-09 16:14:28 +08001629 if (error_code == ENOENT || error_code == EPERM || error_code == EACCES
1630 || error_code == EIO) continue;
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001631 fuse_reply_err(req, error_code);
shafik1e3a2672019-08-16 14:51:55 +01001632 return;
1633 }
1634 } else {
Zim1100f342020-05-15 16:13:00 +01001635 // This should never happen because we have readdir_plus enabled without adaptive
1636 // readdir_plus, FUSE_CAP_READDIRPLUS_AUTO
1637 LOG(WARNING) << "Handling plain readdir for " << de->d_name << ". Invalid d_ino";
shafik1e3a2672019-08-16 14:51:55 +01001638 e.attr.st_ino = FUSE_UNKNOWN_INO;
Zim1100f342020-05-15 16:13:00 +01001639 e.attr.st_mode = de->d_type << 12;
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001640 entry_size = fuse_add_direntry(req, buf + used, len - used, de->d_name.c_str(), &e.attr,
1641 h->next_off);
shafik1e3a2672019-08-16 14:51:55 +01001642 }
Sahana Rao6f9ea982019-09-20 12:21:33 +01001643 // If buffer in fuse_add_direntry[_plus] is not large enough then
1644 // the entry is not added to buffer but the size of the entry is still
1645 // returned. Check available buffer size + returned entry size is less
1646 // than actual buffer size to confirm entry is added to buffer.
Sahana Rao43927f02019-12-10 22:59:01 +00001647 if (used + entry_size > len) {
1648 // When an entry is rejected, lookup called by readdir_plus will not be tracked by
1649 // kernel. Call forget on the rejected node to decrement the reference count.
Narayan Kamathd6219842019-12-27 17:44:35 +00001650 if (plus) {
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001651 do_forget(req, fuse, e.ino, 1);
Narayan Kamathd6219842019-12-27 17:44:35 +00001652 }
Sahana Rao43927f02019-12-10 22:59:01 +00001653 break;
1654 }
Sahana Rao6f9ea982019-09-20 12:21:33 +01001655 used += entry_size;
shafik1e3a2672019-08-16 14:51:55 +01001656 }
Sahana Rao53bd1f62019-12-27 20:18:39 +00001657 fuse_reply_buf(req, buf, used);
shafik1e3a2672019-08-16 14:51:55 +01001658}
1659
1660static void pf_readdir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off,
1661 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001662 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001663 do_readdir_common(req, ino, size, off, fi, false);
1664}
1665
1666static void pf_readdirplus(fuse_req_t req,
1667 fuse_ino_t ino,
1668 size_t size,
1669 off_t off,
1670 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001671 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001672 do_readdir_common(req, ino, size, off, fi, true);
1673}
1674
1675static void pf_releasedir(fuse_req_t req,
1676 fuse_ino_t ino,
1677 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001678 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001679 struct fuse* fuse = get_fuse(req);
shafik1e3a2672019-08-16 14:51:55 +01001680
Ricky Wai44670762020-05-01 11:25:28 +01001681 node* node = fuse->FromInode(ino);
1682
Narayan Kamathaef84a12020-01-02 15:20:13 +00001683 dirhandle* h = reinterpret_cast<dirhandle*>(fi->fh);
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001684 TRACE_NODE(node, req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001685 if (node) {
1686 node->DestroyDirHandle(h);
Zimedbe69e2019-12-13 18:49:36 +00001687 }
Zimedbe69e2019-12-13 18:49:36 +00001688
shafik1e3a2672019-08-16 14:51:55 +01001689 fuse_reply_err(req, 0);
1690}
1691
1692static void pf_statfs(fuse_req_t req, fuse_ino_t ino) {
Zimec8d5722019-12-05 07:26:13 +00001693 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001694 struct statvfs st;
1695 struct fuse* fuse = get_fuse(req);
1696
Narayan Kamathaef84a12020-01-02 15:20:13 +00001697 if (statvfs(fuse->root->GetName().c_str(), &st))
shafik1e3a2672019-08-16 14:51:55 +01001698 fuse_reply_err(req, errno);
1699 else
1700 fuse_reply_statfs(req, &st);
1701}
1702/*
1703static void pf_setxattr(fuse_req_t req, fuse_ino_t ino, const char* name,
1704 const char* value, size_t size, int flags)
1705{
1706 cout << "TODO:" << __func__;
1707}
1708
1709static void pf_getxattr(fuse_req_t req, fuse_ino_t ino, const char* name,
1710 size_t size)
1711{
1712 cout << "TODO:" << __func__;
1713}
1714
1715static void pf_listxattr(fuse_req_t req, fuse_ino_t ino, size_t size)
1716{
1717 cout << "TODO:" << __func__;
1718}
1719
1720static void pf_removexattr(fuse_req_t req, fuse_ino_t ino, const char* name)
1721{
1722 cout << "TODO:" << __func__;
Zima9fcd552019-08-29 15:17:04 +01001723}*/
1724
1725static void pf_access(fuse_req_t req, fuse_ino_t ino, int mask) {
Zimec8d5722019-12-05 07:26:13 +00001726 ATRACE_CALL();
Zima9fcd552019-08-29 15:17:04 +01001727 struct fuse* fuse = get_fuse(req);
Zima9fcd552019-08-29 15:17:04 +01001728
Ricky Wai44670762020-05-01 11:25:28 +01001729 node* node = fuse->FromInode(ino);
Ricky Waif40c4022020-04-15 19:00:06 +01001730 if (!node) {
1731 fuse_reply_err(req, ENOENT);
1732 return;
1733 }
Narayan Kamathaef84a12020-01-02 15:20:13 +00001734 const string path = node->BuildPath();
Martijn Coenen19c1a872020-07-30 19:59:50 +02001735 if (path != "/storage/emulated" && !is_app_accessible_path(fuse->mp, path, req->ctx.uid)) {
Ricky Wai44670762020-05-01 11:25:28 +01001736 fuse_reply_err(req, ENOENT);
1737 return;
1738 }
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001739 TRACE_NODE(node, req);
Zima9fcd552019-08-29 15:17:04 +01001740
Nandana Dutt17555052020-04-09 16:19:57 +01001741 // exists() checks are always allowed.
1742 if (mask == F_OK) {
1743 int res = access(path.c_str(), F_OK);
1744 fuse_reply_err(req, res ? errno : 0);
1745 return;
1746 }
1747 struct stat stat;
1748 if (lstat(path.c_str(), &stat)) {
1749 // File doesn't exist
1750 fuse_reply_err(req, ENOENT);
1751 return;
1752 }
1753
1754 // For read and write permission checks we go to MediaProvider.
1755 int status = 0;
Nandana Dutt5fc32012020-06-25 10:55:52 +01001756 bool for_write = mask & W_OK;
Nandana Dutt17555052020-04-09 16:19:57 +01001757 bool is_directory = S_ISDIR(stat.st_mode);
1758 if (is_directory) {
Martijn Coenen19c1a872020-07-30 19:59:50 +02001759 if (path == "/storage/emulated" && mask == X_OK) {
1760 // Special case for this path: apps should be allowed to enter it,
1761 // but not list directory contents (which would be user numbers).
1762 int res = access(path.c_str(), X_OK);
1763 fuse_reply_err(req, res ? errno : 0);
1764 return;
1765 }
Nandana Dutt5fc32012020-06-25 10:55:52 +01001766 status = fuse->mp->IsOpendirAllowed(path, req->ctx.uid, for_write);
Nandana Dutt17555052020-04-09 16:19:57 +01001767 } else {
1768 if (mask & X_OK) {
1769 // Fuse is mounted with MS_NOEXEC.
1770 fuse_reply_err(req, EACCES);
1771 return;
1772 }
1773
Zim73895ba2021-01-13 12:51:20 +00001774 std::unique_ptr<FileOpenResult> result = fuse->mp->OnFileOpen(
Zim801d9852021-01-26 18:30:53 +00001775 path, path, req->ctx.uid, req->ctx.pid, node->GetTransformsReason(), for_write,
1776 false /* redact */, false /* log_transforms_metrics */);
Zim73895ba2021-01-13 12:51:20 +00001777 if (!result) {
1778 status = EFAULT;
Martijn Coenen4c2da352021-07-22 17:09:05 +02001779 } else if (result->status) {
Zim73895ba2021-01-13 12:51:20 +00001780 status = EACCES;
1781 }
Nandana Dutt17555052020-04-09 16:19:57 +01001782 }
1783
1784 fuse_reply_err(req, status);
shafik1e3a2672019-08-16 14:51:55 +01001785}
Zima9fcd552019-08-29 15:17:04 +01001786
shafik1e3a2672019-08-16 14:51:55 +01001787static void pf_create(fuse_req_t req,
1788 fuse_ino_t parent,
1789 const char* name,
1790 mode_t mode,
1791 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001792 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001793 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +01001794 node* parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +01001795 if (!parent_node) {
1796 fuse_reply_err(req, ENOENT);
1797 return;
1798 }
Narayan Kamathaef84a12020-01-02 15:20:13 +00001799 const string parent_path = parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +01001800 if (!is_app_accessible_path(fuse->mp, parent_path, req->ctx.uid)) {
1801 fuse_reply_err(req, ENOENT);
1802 return;
1803 }
shafik1e3a2672019-08-16 14:51:55 +01001804
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001805 TRACE_NODE(parent_node, req);
shafik1e3a2672019-08-16 14:51:55 +01001806
Narayan Kamathaef84a12020-01-02 15:20:13 +00001807 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +01001808
Ricky Wai44670762020-05-01 11:25:28 +01001809 int mp_return_code = fuse->mp->InsertFile(child_path.c_str(), req->ctx.uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001810 if (mp_return_code) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001811 fuse_reply_err(req, mp_return_code);
shafik1e3a2672019-08-16 14:51:55 +01001812 return;
1813 }
1814
Martijn Coenen2d7f1be2020-02-15 07:44:12 +01001815 // With the writeback cache enabled, FUSE may generate READ requests even for files that
1816 // were opened O_WRONLY; so make sure we open it O_RDWR instead.
1817 int open_flags = fi->flags;
1818 if (open_flags & O_WRONLY) {
1819 open_flags &= ~O_WRONLY;
1820 open_flags |= O_RDWR;
1821 }
1822
Zim1b14f2f2020-07-03 07:05:53 +01001823 if (open_flags & O_APPEND) {
1824 open_flags &= ~O_APPEND;
1825 }
1826
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001827 mode = (mode & (~0777)) | 0664;
Martijn Coenen2d7f1be2020-02-15 07:44:12 +01001828 int fd = open(child_path.c_str(), open_flags, mode);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001829 if (fd < 0) {
1830 int error_code = errno;
1831 // We've already inserted the file into the MP database before the
1832 // failed open(), so that needs to be rolled back here.
Ricky Wai44670762020-05-01 11:25:28 +01001833 fuse->mp->DeleteFile(child_path.c_str(), req->ctx.uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001834 fuse_reply_err(req, error_code);
1835 return;
1836 }
1837
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001838 int error_code = 0;
Narayan Kamathaef84a12020-01-02 15:20:13 +00001839 struct fuse_entry_param e;
]3e9d56c2021-03-15 16:24:17 +00001840 node* node =
1841 make_node_entry(req, parent_node, name, child_path, &e, &error_code, FuseOp::create);
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001842 TRACE_NODE(node, req);
Zimc05c60f2020-03-05 13:02:26 +00001843 if (!node) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001844 CHECK(error_code != 0);
1845 fuse_reply_err(req, error_code);
Zimc05c60f2020-03-05 13:02:26 +00001846 return;
shafik1e3a2672019-08-16 14:51:55 +01001847 }
Zimc05c60f2020-03-05 13:02:26 +00001848
Martijn Coenenaf2d34d2020-06-19 12:52:20 +02001849 // Let MediaProvider know we've created a new file
1850 fuse->mp->OnFileCreated(child_path);
1851
Zimc05c60f2020-03-05 13:02:26 +00001852 // TODO(b/147274248): Assume there will be no EXIF to redact.
1853 // This prevents crashing during reads but can be a security hole if a malicious app opens an fd
1854 // to the file before all the EXIF content is written. We could special case reads before the
1855 // first close after a file has just been created.
Zim329ba2c2020-09-16 14:23:26 +01001856 int keep_cache = 1;
Manish Singh9a6ccce2021-02-05 23:50:08 +00001857 handle* h = create_handle_for_node(fuse, child_path, fd, req->ctx.uid, 0 /* transforms_uid */,
1858 node, new RedactionInfo(), &keep_cache);
Zimc05c60f2020-03-05 13:02:26 +00001859 fi->fh = ptr_to_id(h);
Zim329ba2c2020-09-16 14:23:26 +01001860 fi->keep_cache = keep_cache;
Zimc05c60f2020-03-05 13:02:26 +00001861 fi->direct_io = !h->cached;
Alessio Balsinif220a962020-07-13 12:01:13 +01001862
1863 // TODO(b/173190192) ensuring that h->cached must be enabled in order to
1864 // user FUSE passthrough is a conservative rule and might be dropped as
1865 // soon as demonstrated its correctness.
Zim148cbe22020-11-17 15:58:29 +00001866 if (h->passthrough) {
Alessio Balsinif220a962020-07-13 12:01:13 +01001867 if (!do_passthrough_enable(req, fi, fd)) {
Zim148cbe22020-11-17 15:58:29 +00001868 PLOG(ERROR) << "Passthrough CREATE failed for " << child_path;
1869 fuse_reply_err(req, EFAULT);
1870 return;
Alessio Balsinif220a962020-07-13 12:01:13 +01001871 }
1872 }
1873
Zimc05c60f2020-03-05 13:02:26 +00001874 fuse_reply_create(req, &e, fi);
shafik1e3a2672019-08-16 14:51:55 +01001875}
1876/*
1877static void pf_getlk(fuse_req_t req, fuse_ino_t ino,
1878 struct fuse_file_info* fi, struct flock* lock)
1879{
1880 cout << "TODO:" << __func__;
1881}
1882
1883static void pf_setlk(fuse_req_t req, fuse_ino_t ino,
1884 struct fuse_file_info* fi,
1885 struct flock* lock, int sleep)
1886{
1887 cout << "TODO:" << __func__;
1888}
1889
1890static void pf_bmap(fuse_req_t req, fuse_ino_t ino, size_t blocksize,
1891 uint64_t idx)
1892{
1893 cout << "TODO:" << __func__;
1894}
1895
1896static void pf_ioctl(fuse_req_t req, fuse_ino_t ino, unsigned int cmd,
1897 void* arg, struct fuse_file_info* fi, unsigned flags,
1898 const void* in_buf, size_t in_bufsz, size_t out_bufsz)
1899{
1900 cout << "TODO:" << __func__;
1901}
1902
1903static void pf_poll(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi,
1904 struct fuse_pollhandle* ph)
1905{
1906 cout << "TODO:" << __func__;
1907}
1908
1909static void pf_retrieve_reply(fuse_req_t req, void* cookie, fuse_ino_t ino,
1910 off_t offset, struct fuse_bufvec* bufv)
1911{
1912 cout << "TODO:" << __func__;
1913}
1914
1915static void pf_flock(fuse_req_t req, fuse_ino_t ino,
1916 struct fuse_file_info* fi, int op)
1917{
1918 cout << "TODO:" << __func__;
1919}
1920
1921static void pf_fallocate(fuse_req_t req, fuse_ino_t ino, int mode,
1922 off_t offset, off_t length, struct fuse_file_info* fi)
1923{
1924 cout << "TODO:" << __func__;
1925}
1926*/
1927
1928static struct fuse_lowlevel_ops ops{
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00001929 .init = pf_init, .destroy = pf_destroy, .lookup = pf_lookup, .forget = pf_forget,
1930 .getattr = pf_getattr, .setattr = pf_setattr, .canonical_path = pf_canonical_path,
1931 .mknod = pf_mknod, .mkdir = pf_mkdir, .unlink = pf_unlink, .rmdir = pf_rmdir,
shafik8b57cd52019-09-06 10:51:29 +01001932 /*.symlink = pf_symlink,*/
1933 .rename = pf_rename,
1934 /*.link = pf_link,*/
1935 .open = pf_open, .read = pf_read,
1936 /*.write = pf_write,*/
Alessio Balsini68c295d2020-07-23 14:32:01 +01001937 /*.flush = pf_flush,*/
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00001938 .release = pf_release, .fsync = pf_fsync, .opendir = pf_opendir, .readdir = pf_readdir,
1939 .releasedir = pf_releasedir, .fsyncdir = pf_fsyncdir, .statfs = pf_statfs,
shafik8b57cd52019-09-06 10:51:29 +01001940 /*.setxattr = pf_setxattr,
1941 .getxattr = pf_getxattr,
1942 .listxattr = pf_listxattr,
1943 .removexattr = pf_removexattr,*/
1944 .access = pf_access, .create = pf_create,
1945 /*.getlk = pf_getlk,
1946 .setlk = pf_setlk,
1947 .bmap = pf_bmap,
1948 .ioctl = pf_ioctl,
Nick Desaulniers17714b82019-11-05 09:44:35 -08001949 .poll = pf_poll,*/
1950 .write_buf = pf_write_buf,
1951 /*.retrieve_reply = pf_retrieve_reply,*/
1952 .forget_multi = pf_forget_multi,
Zim9e3c40b2021-04-09 15:51:15 +01001953 /*.flock = pf_flock,*/
1954 .fallocate = pf_fallocate,
Nick Desaulniers17714b82019-11-05 09:44:35 -08001955 .readdirplus = pf_readdirplus,
1956 /*.copy_file_range = pf_copy_file_range,*/
shafik1e3a2672019-08-16 14:51:55 +01001957};
1958
1959static struct fuse_loop_config config = {
Zim549f9da2020-02-09 13:54:22 +00001960 .clone_fd = 1,
shafik1e3a2672019-08-16 14:51:55 +01001961 .max_idle_threads = 10,
1962};
1963
Zimb353eb42019-12-17 15:29:48 +00001964static std::unordered_map<enum fuse_log_level, enum android_LogPriority> fuse_to_android_loglevel({
1965 {FUSE_LOG_EMERG, ANDROID_LOG_FATAL},
1966 {FUSE_LOG_ALERT, ANDROID_LOG_ERROR},
1967 {FUSE_LOG_CRIT, ANDROID_LOG_ERROR},
1968 {FUSE_LOG_ERR, ANDROID_LOG_ERROR},
1969 {FUSE_LOG_WARNING, ANDROID_LOG_WARN},
1970 {FUSE_LOG_NOTICE, ANDROID_LOG_INFO},
1971 {FUSE_LOG_INFO, ANDROID_LOG_DEBUG},
1972 {FUSE_LOG_DEBUG, ANDROID_LOG_VERBOSE},
1973 });
Zim724b8ca2019-11-09 09:37:24 +00001974
1975static void fuse_logger(enum fuse_log_level level, const char* fmt, va_list ap) {
Zim357e3072020-01-15 10:50:01 +00001976 __android_log_vprint(fuse_to_android_loglevel.at(level), LIBFUSE_LOG_TAG, fmt, ap);
Zim724b8ca2019-11-09 09:37:24 +00001977}
1978
Zimedbe69e2019-12-13 18:49:36 +00001979bool FuseDaemon::ShouldOpenWithFuse(int fd, bool for_read, const std::string& path) {
Zim148cbe22020-11-17 15:58:29 +00001980 if (fuse->passthrough) {
1981 // Always open with FUSE if passthrough is enabled. This avoids the delicate file lock
1982 // acquisition below to ensure VFS cache consistency and doesn't impact filesystem
1983 // performance since read(2)/write(2) happen in the kernel
1984 return true;
1985 }
1986
Zimedbe69e2019-12-13 18:49:36 +00001987 bool use_fuse = false;
1988
1989 if (active.load(std::memory_order_acquire)) {
Zimdc78f532020-03-04 18:46:06 +00001990 std::lock_guard<std::recursive_mutex> guard(fuse->lock);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001991 const node* node = node::LookupAbsolutePath(fuse->root, path);
Zimedbe69e2019-12-13 18:49:36 +00001992 if (node && node->HasCachedHandle()) {
Zimedbe69e2019-12-13 18:49:36 +00001993 use_fuse = true;
1994 } else {
1995 // If we are unable to set a lock, we should use fuse since we can't track
1996 // when all fd references (including dups) are closed. This can happen when
1997 // we try to set a write lock twice on the same file
1998 use_fuse = set_file_lock(fd, for_read, path);
Zimedbe69e2019-12-13 18:49:36 +00001999 }
Zimedbe69e2019-12-13 18:49:36 +00002000 } else {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00002001 LOG(WARNING) << "FUSE daemon is inactive. Cannot open file with FUSE";
Zimedbe69e2019-12-13 18:49:36 +00002002 }
2003
2004 return use_fuse;
2005}
2006
Zima76c3492020-02-19 01:23:26 +00002007void FuseDaemon::InvalidateFuseDentryCache(const std::string& path) {
Zim4d3fa272020-03-06 13:45:19 +00002008 LOG(VERBOSE) << "Invalidating FUSE dentry cache";
Zima76c3492020-02-19 01:23:26 +00002009 if (active.load(std::memory_order_acquire)) {
Zima55568e2020-04-24 22:40:34 +01002010 string name;
2011 fuse_ino_t parent;
Zim33aea102020-06-19 15:49:47 +01002012 fuse_ino_t child;
Zima55568e2020-04-24 22:40:34 +01002013 {
2014 std::lock_guard<std::recursive_mutex> guard(fuse->lock);
2015 const node* node = node::LookupAbsolutePath(fuse->root, path);
2016 if (node) {
2017 name = node->GetName();
Zim33aea102020-06-19 15:49:47 +01002018 child = fuse->ToInode(const_cast<class node*>(node));
Zima55568e2020-04-24 22:40:34 +01002019 parent = fuse->ToInode(node->GetParent());
Zima76c3492020-02-19 01:23:26 +00002020 }
2021 }
Zima55568e2020-04-24 22:40:34 +01002022
Zim33aea102020-06-19 15:49:47 +01002023 if (!name.empty()) {
2024 fuse_inval(fuse->se, parent, child, name, path);
Zima55568e2020-04-24 22:40:34 +01002025 }
Zima76c3492020-02-19 01:23:26 +00002026 } else {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00002027 LOG(WARNING) << "FUSE daemon is inactive. Cannot invalidate dentry";
Zima76c3492020-02-19 01:23:26 +00002028 }
2029}
2030
Zimedbe69e2019-12-13 18:49:36 +00002031FuseDaemon::FuseDaemon(JNIEnv* env, jobject mediaProvider) : mp(env, mediaProvider),
2032 active(false), fuse(nullptr) {}
shafik1e3a2672019-08-16 14:51:55 +01002033
Zimd0435b22020-03-05 13:52:51 +00002034bool FuseDaemon::IsStarted() const {
2035 return active.load(std::memory_order_acquire);
2036}
2037
Martijn Coenen083eb692020-04-24 09:39:58 +02002038void FuseDaemon::Start(android::base::unique_fd fd, const std::string& path) {
Nikita Ioffec33ee1a2020-06-23 21:31:20 +01002039 android::base::SetDefaultTag(LOG_TAG);
2040
shafik1e3a2672019-08-16 14:51:55 +01002041 struct fuse_args args;
2042 struct fuse_cmdline_opts opts;
shafik1e3a2672019-08-16 14:51:55 +01002043
2044 struct stat stat;
shafik1e3a2672019-08-16 14:51:55 +01002045
Zim7c8712d2019-10-03 21:01:26 +01002046 if (lstat(path.c_str(), &stat)) {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00002047 PLOG(ERROR) << "ERROR: failed to stat source " << path;
Zim3e45d9b2019-08-19 21:14:14 +01002048 return;
2049 }
shafik1e3a2672019-08-16 14:51:55 +01002050
Zim3e45d9b2019-08-19 21:14:14 +01002051 if (!S_ISDIR(stat.st_mode)) {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00002052 PLOG(ERROR) << "ERROR: source is not a directory";
Zim3e45d9b2019-08-19 21:14:14 +01002053 return;
2054 }
shafik1e3a2672019-08-16 14:51:55 +01002055
2056 args = FUSE_ARGS_INIT(0, nullptr);
Zim7c8712d2019-10-03 21:01:26 +01002057 if (fuse_opt_add_arg(&args, path.c_str()) || fuse_opt_add_arg(&args, "-odebug") ||
2058 fuse_opt_add_arg(&args, ("-omax_read=" + std::to_string(MAX_READ_SIZE)).c_str())) {
shafik458d1102019-09-06 18:21:36 +01002059 LOG(ERROR) << "ERROR: failed to set options";
shafik1e3a2672019-08-16 14:51:55 +01002060 return;
2061 }
2062
Biswarup Pal93f4ec12021-02-15 13:39:36 +00002063 struct fuse fuse_default(path, stat.st_ino);
shafikc3f62672019-08-30 11:15:48 +01002064 fuse_default.mp = &mp;
Zimedbe69e2019-12-13 18:49:36 +00002065 // fuse_default is stack allocated, but it's safe to save it as an instance variable because
2066 // this method blocks and FuseDaemon#active tells if we are currently blocking
2067 fuse = &fuse_default;
shafikc3f62672019-08-30 11:15:48 +01002068
shafikb334a612019-09-30 20:38:16 +01002069 // Used by pf_read: redacted ranges are represented by zeroized ranges of bytes,
2070 // so we mmap the maximum length of redacted ranges in the beginning and save memory allocations
2071 // on each read.
2072 fuse_default.zero_addr = static_cast<char*>(mmap(
2073 NULL, MAX_READ_SIZE, PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, /*fd*/ -1, /*off*/ 0));
2074 if (fuse_default.zero_addr == MAP_FAILED) {
2075 LOG(FATAL) << "mmap failed - could not start fuse! errno = " << errno;
2076 }
2077
Zim724b8ca2019-11-09 09:37:24 +00002078 // Custom logging for libfuse
Zim0594b032020-04-29 11:43:43 +01002079 if (android::base::GetBoolProperty("persist.sys.fuse.log", false)) {
2080 fuse_set_log_func(fuse_logger);
2081 }
Zim724b8ca2019-11-09 09:37:24 +00002082
Zim3cde2662021-02-22 21:20:33 +00002083 if (MY_USER_ID != 0 && mp.IsAppCloneUser(MY_USER_ID)) {
Martijn Coenen87133092020-10-14 17:00:28 +02002084 // Disable dentry caching for the app clone user
2085 fuse->disable_dentry_cache = true;
2086 }
2087
Alessio Balsinib1c366b2020-11-26 15:15:14 +00002088 fuse->passthrough = android::base::GetBoolProperty("persist.sys.fuse.passthrough.enable", false);
2089 if (fuse->passthrough) {
2090 LOG(INFO) << "Using FUSE passthrough";
2091 }
Alessio Balsinif220a962020-07-13 12:01:13 +01002092
shafik1e3a2672019-08-16 14:51:55 +01002093 struct fuse_session
2094 * se = fuse_session_new(&args, &ops, sizeof(ops), &fuse_default);
Zim7e0d3142019-10-17 21:06:12 +01002095 if (!se) {
2096 PLOG(ERROR) << "Failed to create session ";
2097 return;
2098 }
Zima76c3492020-02-19 01:23:26 +00002099 fuse_default.se = se;
Zimd0435b22020-03-05 13:52:51 +00002100 fuse_default.active = &active;
Martijn Coenen3ec6c062020-04-28 19:09:53 +02002101 se->fd = fd.release(); // libfuse owns the FD now
Zim7c8712d2019-10-03 21:01:26 +01002102 se->mountpoint = strdup(path.c_str());
Zim3e45d9b2019-08-19 21:14:14 +01002103
2104 // Single thread. Useful for debugging
2105 // fuse_session_loop(se);
2106 // Multi-threaded
Zim7e0d3142019-10-17 21:06:12 +01002107 LOG(INFO) << "Starting fuse...";
shafik1e3a2672019-08-16 14:51:55 +01002108 fuse_session_loop_mt(se, &config);
Zimd0435b22020-03-05 13:52:51 +00002109 fuse->active->store(false, std::memory_order_release);
Zim7e0d3142019-10-17 21:06:12 +01002110 LOG(INFO) << "Ending fuse...";
Zim3e45d9b2019-08-19 21:14:14 +01002111
Zim7c8712d2019-10-03 21:01:26 +01002112 if (munmap(fuse_default.zero_addr, MAX_READ_SIZE)) {
2113 PLOG(ERROR) << "munmap failed!";
shafikb334a612019-09-30 20:38:16 +01002114 }
2115
Zim7e0d3142019-10-17 21:06:12 +01002116 fuse_opt_free_args(&args);
2117 fuse_session_destroy(se);
2118 LOG(INFO) << "Ended fuse";
2119 return;
shafik1e3a2672019-08-16 14:51:55 +01002120}
Biswarup Pal93f4ec12021-02-15 13:39:36 +00002121
2122const string FuseDaemon::GetOriginalMediaFormatFilePath(int fd) const {
2123 struct stat s;
2124 memset(&s, 0, sizeof(s));
2125 if (fstat(fd, &s) < 0) {
2126 PLOG(DEBUG) << "GetOriginalMediaFormatFilePath fstat failed.";
2127 return string();
2128 }
2129
2130 ino_t ino = s.st_ino;
2131 dev_t dev = s.st_dev;
2132
2133 dev_t fuse_dev = fuse->dev.load(std::memory_order_acquire);
2134 if (dev != fuse_dev) {
2135 PLOG(DEBUG) << "GetOriginalMediaFormatFilePath FUSE device id does not match.";
2136 return string();
2137 }
2138
2139 const node* node = node::LookupInode(fuse->root, ino);
2140 if (!node) {
2141 PLOG(DEBUG) << "GetOriginalMediaFormatFilePath no node found with given ino";
2142 return string();
2143 }
2144
2145 return node->BuildPath();
2146}
2147
2148void FuseDaemon::InitializeDeviceId(const std::string& path) {
2149 struct stat stat;
2150
2151 if (lstat(path.c_str(), &stat)) {
2152 PLOG(ERROR) << "InitializeDeviceId failed to stat given path " << path;
2153 return;
2154 }
2155
2156 fuse->dev.store(stat.st_dev, std::memory_order_release);
2157}
shafik1e3a2672019-08-16 14:51:55 +01002158} //namespace fuse
shafik8b57cd52019-09-06 10:51:29 +01002159} // namespace mediaprovider