blob: 58b6f27be118040e748b6d1530aa8f894c4e1e9a [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"
20
shafik458d1102019-09-06 18:21:36 +010021#include <android-base/logging.h>
Zim32129b62020-03-11 11:37:16 +000022#include <android-base/properties.h>
Zim724b8ca2019-11-09 09:37:24 +000023#include <android/log.h>
Zimec8d5722019-12-05 07:26:13 +000024#include <android/trace.h>
shafik1e3a2672019-08-16 14:51:55 +010025#include <ctype.h>
26#include <dirent.h>
27#include <errno.h>
28#include <fcntl.h>
shafik8b57cd52019-09-06 10:51:29 +010029#include <fuse_i.h>
Zim724b8ca2019-11-09 09:37:24 +000030#include <fuse_log.h>
shafik8b57cd52019-09-06 10:51:29 +010031#include <fuse_lowlevel.h>
shafik1e3a2672019-08-16 14:51:55 +010032#include <inttypes.h>
33#include <limits.h>
34#include <linux/fuse.h>
shafik1e3a2672019-08-16 14:51:55 +010035#include <stdbool.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
39#include <sys/inotify.h>
shafikb334a612019-09-30 20:38:16 +010040#include <sys/mman.h>
shafik1e3a2672019-08-16 14:51:55 +010041#include <sys/mount.h>
42#include <sys/param.h>
43#include <sys/resource.h>
44#include <sys/stat.h>
45#include <sys/statfs.h>
46#include <sys/statvfs.h>
47#include <sys/time.h>
48#include <sys/types.h>
49#include <sys/uio.h>
50#include <unistd.h>
shafik1e3a2672019-08-16 14:51:55 +010051
shafik8b57cd52019-09-06 10:51:29 +010052#include <iostream>
Narayan Kamath8d76d0c2019-12-31 13:14:50 +000053#include <list>
Paul Lawrence7e4a5a82019-09-27 21:39:49 +020054#include <map>
Narayan Kamath768bea32019-12-27 16:23:23 +000055#include <mutex>
Paul Lawrence7e4a5a82019-09-27 21:39:49 +020056#include <queue>
Zim859db932019-12-13 00:09:17 +000057#include <regex>
Paul Lawrence7e4a5a82019-09-27 21:39:49 +020058#include <thread>
Zim724b8ca2019-11-09 09:37:24 +000059#include <unordered_map>
Narayan Kamath92bf67b2020-01-03 17:49:09 +000060#include <unordered_set>
shafikc3f62672019-08-30 11:15:48 +010061#include <vector>
shafik1e3a2672019-08-16 14:51:55 +010062
shafikc3f62672019-08-30 11:15:48 +010063#include "MediaProviderWrapper.h"
Corina633099b2020-06-17 21:55:33 +010064#include "libfuse_jni/FuseUtils.h"
Sahana Raoa82bd6a2019-10-10 18:10:37 +010065#include "libfuse_jni/ReaddirHelper.h"
shafikc3f62672019-08-30 11:15:48 +010066#include "libfuse_jni/RedactionInfo.h"
Narayan Kamathaef84a12020-01-02 15:20:13 +000067#include "node-inl.h"
shafikc3f62672019-08-30 11:15:48 +010068
Sahana Raoa82bd6a2019-10-10 18:10:37 +010069using mediaprovider::fuse::DirectoryEntry;
Narayan Kamathaef84a12020-01-02 15:20:13 +000070using mediaprovider::fuse::dirhandle;
71using mediaprovider::fuse::handle;
72using mediaprovider::fuse::node;
shafikc3f62672019-08-30 11:15:48 +010073using mediaprovider::fuse::RedactionInfo;
Narayan Kamath8d76d0c2019-12-31 13:14:50 +000074using std::list;
Jeff Sharkey7469b982019-08-28 16:51:02 -060075using std::string;
shafikc3f62672019-08-30 11:15:48 +010076using std::vector;
shafik1e3a2672019-08-16 14:51:55 +010077
Narayan Kamath88203dc2019-08-30 17:19:38 +010078// logging macros to avoid duplication.
Nandana Dutt154cb5d2020-06-04 11:53:31 +010079#define TRACE_NODE(__node, __req) \
80 LOG(VERBOSE) << __FUNCTION__ << " : " << #__node << " = [" << get_name(__node) \
81 << "] (uid=" << __req->ctx.uid << ") "
shafik1e3a2672019-08-16 14:51:55 +010082
Zimec8d5722019-12-05 07:26:13 +000083#define ATRACE_NAME(name) ScopedTrace ___tracer(name)
84#define ATRACE_CALL() ATRACE_NAME(__FUNCTION__)
85
86class ScopedTrace {
87 public:
Narayan Kamath64b44352019-12-27 17:07:50 +000088 explicit inline ScopedTrace(const char *name) {
Zimec8d5722019-12-05 07:26:13 +000089 ATrace_beginSection(name);
90 }
91
92 inline ~ScopedTrace() {
93 ATrace_endSection();
94 }
95};
96
Zim32129b62020-03-11 11:37:16 +000097const bool IS_OS_DEBUGABLE = android::base::GetIntProperty("ro.debuggable", 0);
98
shafik1e3a2672019-08-16 14:51:55 +010099#define FUSE_UNKNOWN_INO 0xffffffff
100
Ricky Waif40c4022020-04-15 19:00:06 +0100101// Stolen from: android_filesystem_config.h
102#define AID_APP_START 10000
103
shafikb334a612019-09-30 20:38:16 +0100104constexpr size_t MAX_READ_SIZE = 128 * 1024;
Zim859db932019-12-13 00:09:17 +0000105// Stolen from: UserHandle#getUserId
106constexpr int PER_USER_RANGE = 100000;
shafikb334a612019-09-30 20:38:16 +0100107
Ricky Waif40c4022020-04-15 19:00:06 +0100108// Regex copied from FileUtils.java in MediaProvider, but without media directory.
109const std::regex PATTERN_OWNED_PATH(
Zim78ffeeb2020-09-22 20:15:25 +0100110 "^/storage/[^/]+/(?:[0-9]+/)?Android/(?:data|obb)/([^/]+)(/?.*)?",
111 std::regex_constants::icase);
Ricky Waif40c4022020-04-15 19:00:06 +0100112
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200113/*
114 * In order to avoid double caching with fuse, call fadvise on the file handles
115 * in the underlying file system. However, if this is done on every read/write,
116 * the fadvises cause a very significant slowdown in tests (specifically fio
117 * seq_write). So call fadvise on the file handles with the most reads/writes
118 * only after a threshold is passed.
119 */
120class FAdviser {
121 public:
122 FAdviser() : thread_(MessageLoop, this), total_size_(0) {}
123
124 ~FAdviser() {
125 SendMessage(Message::quit);
126 thread_.join();
127 }
128
129 void Record(int fd, size_t size) { SendMessage(Message::record, fd, size); }
130
131 void Close(int fd) { SendMessage(Message::close, fd); }
132
133 private:
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200134 struct Message {
135 enum Type { record, close, quit };
136 Type type;
137 int fd;
138 size_t size;
139 };
140
141 void RecordImpl(int fd, size_t size) {
142 total_size_ += size;
143
144 // Find or create record in files_
145 // Remove record from sizes_ if it exists, adjusting size appropriately
146 auto file = files_.find(fd);
147 if (file != files_.end()) {
148 auto old_size = file->second;
149 size += old_size->first;
150 sizes_.erase(old_size);
151 } else {
152 file = files_.insert(Files::value_type(fd, sizes_.end())).first;
153 }
154
155 // Now (re) insert record in sizes_
156 auto new_size = sizes_.insert(Sizes::value_type(size, fd));
157 file->second = new_size;
158
159 if (total_size_ < threshold_) return;
160
161 LOG(INFO) << "Threshold exceeded - fadvising " << total_size_;
162 while (!sizes_.empty() && total_size_ > target_) {
163 auto size = --sizes_.end();
164 total_size_ -= size->first;
165 posix_fadvise(size->second, 0, 0, POSIX_FADV_DONTNEED);
166 files_.erase(size->second);
167 sizes_.erase(size);
168 }
169 LOG(INFO) << "Threshold now " << total_size_;
170 }
171
172 void CloseImpl(int fd) {
173 auto file = files_.find(fd);
174 if (file == files_.end()) return;
175
176 total_size_ -= file->second->first;
177 sizes_.erase(file->second);
178 files_.erase(file);
179 }
180
181 void MessageLoopImpl() {
182 while (1) {
183 Message message;
184
185 {
186 std::unique_lock<std::mutex> lock(mutex_);
187 cv_.wait(lock, [this] { return !queue_.empty(); });
188 message = queue_.front();
189 queue_.pop();
190 }
191
192 switch (message.type) {
193 case Message::record:
194 RecordImpl(message.fd, message.size);
195 break;
196
197 case Message::close:
198 CloseImpl(message.fd);
199 break;
200
201 case Message::quit:
202 return;
203 }
204 }
205 }
206
207 static int MessageLoop(FAdviser* ptr) {
208 ptr->MessageLoopImpl();
209 return 0;
210 }
211
212 void SendMessage(Message::Type type, int fd = -1, size_t size = 0) {
213 {
214 std::unique_lock<std::mutex> lock(mutex_);
215 Message message = {type, fd, size};
216 queue_.push(message);
217 }
218 cv_.notify_one();
219 }
220
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200221 std::mutex mutex_;
222 std::condition_variable cv_;
Zim695a1272020-06-15 18:14:08 +0100223 std::queue<Message> queue_;
224 std::thread thread_;
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200225
226 typedef std::multimap<size_t, int> Sizes;
227 typedef std::map<int, Sizes::iterator> Files;
228
229 Files files_;
230 Sizes sizes_;
231 size_t total_size_;
232
233 const size_t threshold_ = 64 * 1024 * 1024;
234 const size_t target_ = 32 * 1024 * 1024;
235};
236
shafik1e3a2672019-08-16 14:51:55 +0100237/* Single FUSE mount */
238struct fuse {
Narayan Kamathaef84a12020-01-02 15:20:13 +0000239 explicit fuse(const std::string& _path)
Narayan Kamath568f17a2020-02-19 13:45:29 +0000240 : path(_path),
241 tracker(mediaprovider::fuse::NodeTracker(&lock)),
242 root(node::CreateRoot(_path, &lock, &tracker)),
243 mp(0),
244 zero_addr(0) {}
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200245
Narayan Kamathaef84a12020-01-02 15:20:13 +0000246 inline bool IsRoot(const node* node) const { return node == root; }
shafik1e3a2672019-08-16 14:51:55 +0100247
Zimb2834012020-06-17 13:26:27 +0100248 inline string GetEffectiveRootPath() {
249 if (path.find("/storage/emulated", 0) == 0) {
250 return path + "/" + std::to_string(getuid() / PER_USER_RANGE);
251 }
252 return path;
253 }
254
Narayan Kamathaef84a12020-01-02 15:20:13 +0000255 // Note that these two (FromInode / ToInode) conversion wrappers are required
256 // because fuse_lowlevel_ops documents that the root inode is always one
257 // (see FUSE_ROOT_ID in fuse_lowlevel.h). There are no particular requirements
258 // on any of the other inodes in the FS.
Ricky Wai44670762020-05-01 11:25:28 +0100259 inline node* FromInode(__u64 inode) {
Narayan Kamathaef84a12020-01-02 15:20:13 +0000260 if (inode == FUSE_ROOT_ID) {
261 return root;
262 }
shafik1e3a2672019-08-16 14:51:55 +0100263
Ricky Wai44670762020-05-01 11:25:28 +0100264 return node::FromInode(inode, &tracker);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000265 }
266
267 inline __u64 ToInode(node* node) const {
268 if (IsRoot(node)) {
269 return FUSE_ROOT_ID;
270 }
271
272 return node::ToInode(node);
273 }
274
275 std::recursive_mutex lock;
276 const string path;
Narayan Kamath568f17a2020-02-19 13:45:29 +0000277 // The Inode tracker associated with this FUSE instance.
278 mediaprovider::fuse::NodeTracker tracker;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000279 node* const root;
Zima76c3492020-02-19 01:23:26 +0000280 struct fuse_session* se;
shafikc3f62672019-08-30 11:15:48 +0100281
282 /*
283 * Used to make JNI calls to MediaProvider.
284 * Responsibility of freeing this object falls on corresponding
285 * FuseDaemon object.
286 */
287 mediaprovider::fuse::MediaProviderWrapper* mp;
shafikb334a612019-09-30 20:38:16 +0100288
289 /*
290 * Points to a range of zeroized bytes, used by pf_read to represent redacted ranges.
291 * The memory is read only and should never be modified.
292 */
Narayan Kamathaef84a12020-01-02 15:20:13 +0000293 /* const */ char* zero_addr;
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200294
295 FAdviser fadviser;
Zimd0435b22020-03-05 13:52:51 +0000296
297 std::atomic_bool* active;
shafik1e3a2672019-08-16 14:51:55 +0100298};
299
Zim32129b62020-03-11 11:37:16 +0000300static inline string get_name(node* n) {
301 if (n) {
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100302 std::string name = IS_OS_DEBUGABLE ? "real_path: " + n->BuildPath() + " " : "";
303 name += "node_path: " + n->BuildSafePath();
Zim32129b62020-03-11 11:37:16 +0000304 return name;
305 }
306 return "?";
shafik458d1102019-09-06 18:21:36 +0100307}
308
shafik1e3a2672019-08-16 14:51:55 +0100309static inline __u64 ptr_to_id(void* ptr) {
310 return (__u64)(uintptr_t) ptr;
311}
312
Zimedbe69e2019-12-13 18:49:36 +0000313/*
314 * Set an F_RDLCK or F_WRLCKK on fd with fcntl(2).
315 *
316 * This is called before the MediaProvider returns fd from the lower file
317 * system to an app over the ContentResolver interface. This allows us
318 * check with is_file_locked if any reference to that fd is still open.
319 */
320static int set_file_lock(int fd, bool for_read, const std::string& path) {
321 std::string lock_str = (for_read ? "read" : "write");
Zimedbe69e2019-12-13 18:49:36 +0000322
323 struct flock fl{};
324 fl.l_type = for_read ? F_RDLCK : F_WRLCK;
325 fl.l_whence = SEEK_SET;
326
327 int res = fcntl(fd, F_OFD_SETLK, &fl);
328 if (res) {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +0000329 PLOG(WARNING) << "Failed to set lock: " << lock_str;
Zimedbe69e2019-12-13 18:49:36 +0000330 return res;
331 }
Zimedbe69e2019-12-13 18:49:36 +0000332 return res;
333}
334
335/*
336 * Check if an F_RDLCK or F_WRLCK is set on fd with fcntl(2).
337 *
338 * This is used to determine if the MediaProvider has given an fd to the lower fs to an app over
339 * the ContentResolver interface. Before that happens, we always call set_file_lock on the file
340 * allowing us to know if any reference to that fd is still open here.
341 *
342 * Returns true if fd may have a lock, false otherwise
343 */
344static bool is_file_locked(int fd, const std::string& path) {
Zimedbe69e2019-12-13 18:49:36 +0000345 struct flock fl{};
346 fl.l_type = F_WRLCK;
347 fl.l_whence = SEEK_SET;
348
349 int res = fcntl(fd, F_OFD_GETLK, &fl);
350 if (res) {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +0000351 PLOG(WARNING) << "Failed to check lock";
Zimedbe69e2019-12-13 18:49:36 +0000352 // Assume worst
353 return true;
354 }
355 bool locked = fl.l_type != F_UNLCK;
Zimedbe69e2019-12-13 18:49:36 +0000356 return locked;
357}
358
shafik1e3a2672019-08-16 14:51:55 +0100359static struct fuse* get_fuse(fuse_req_t req) {
360 return reinterpret_cast<struct fuse*>(fuse_req_userdata(req));
361}
362
Ricky Waif40c4022020-04-15 19:00:06 +0100363static bool is_package_owned_path(const string& path, const string& fuse_path) {
364 if (path.rfind(fuse_path, 0) != 0) {
365 return false;
366 }
367 return std::regex_match(path, PATTERN_OWNED_PATH);
368}
369
Zim33aea102020-06-19 15:49:47 +0100370// See fuse_lowlevel.h fuse_lowlevel_notify_inval_entry for how to call this safetly without
371// deadlocking the kernel
372static void fuse_inval(fuse_session* se, fuse_ino_t parent_ino, fuse_ino_t child_ino,
373 const string& child_name, const string& path) {
Corina633099b2020-06-17 21:55:33 +0100374 if (mediaprovider::fuse::containsMount(path, std::to_string(getuid() / PER_USER_RANGE))) {
Zim33aea102020-06-19 15:49:47 +0100375 LOG(WARNING) << "Ignoring attempt to invalidate dentry for FUSE mounts";
376 return;
377 }
378
379 if (fuse_lowlevel_notify_inval_entry(se, parent_ino, child_name.c_str(), child_name.size())) {
380 // Invalidating the dentry can fail if there's no dcache entry, however, there may still
381 // be cached attributes, so attempt to invalidate those by invalidating the inode
382 fuse_lowlevel_notify_inval_inode(se, child_ino, 0, 0);
383 }
Zim89962312020-04-22 21:21:53 +0100384}
385
Zim867fece2020-09-23 15:23:19 +0100386static double get_attr_timeout(const string& path, bool should_inval, node* node,
387 struct fuse* fuse) {
388 if (should_inval || is_package_owned_path(path, fuse->path)) {
Zimb2834012020-06-17 13:26:27 +0100389 // We set dentry timeout to 0 for the following reasons:
Zim33aea102020-06-19 15:49:47 +0100390 // 1. Case-insensitive lookups need to invalidate other case-insensitive dentry matches
Zim867fece2020-09-23 15:23:19 +0100391 // 2. With app data isolation enabled, app A should not guess existence of app B from the
Zimb2834012020-06-17 13:26:27 +0100392 // Android/{data,obb}/<package> paths, hence we prevent the kernel from caching that
393 // information.
394 return 0;
395 }
396 return std::numeric_limits<double>::max();
397}
398
Zim867fece2020-09-23 15:23:19 +0100399static double get_entry_timeout(const string& path, bool should_inval, node* node,
400 struct fuse* fuse) {
401 string media_path = fuse->GetEffectiveRootPath() + "/Android/media";
402 if (path.find(media_path, 0) == 0) {
403 // Installd might delete Android/media/<package> dirs when app data is cleared.
404 // This can leave a stale entry in the kernel dcache, and break subsequent creation of the
405 // dir via FUSE.
406 return 0;
407 }
408 return get_attr_timeout(path, should_inval, node, fuse);
409}
410
411static std::string get_path(node* node) {
412 const string& io_path = node->GetIoPath();
413 return io_path.empty() ? node->BuildPath() : io_path;
414}
415
Narayan Kamathaef84a12020-01-02 15:20:13 +0000416static node* make_node_entry(fuse_req_t req, node* parent, const string& name, const string& path,
417 struct fuse_entry_param* e, int* error_code) {
shafik1e3a2672019-08-16 14:51:55 +0100418 struct fuse* fuse = get_fuse(req);
Martijn Coenenb8ff4eb2019-12-17 09:55:17 +0100419 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000420 node* node;
shafik1e3a2672019-08-16 14:51:55 +0100421
Jeff Sharkey7469b982019-08-28 16:51:02 -0600422 memset(e, 0, sizeof(*e));
shafik1e3a2672019-08-16 14:51:55 +0100423 if (lstat(path.c_str(), &e->attr) < 0) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000424 *error_code = errno;
shafik1e3a2672019-08-16 14:51:55 +0100425 return NULL;
426 }
427
Zim33aea102020-06-19 15:49:47 +0100428 bool should_inval = false;
Zimbb7c3762020-09-23 13:50:08 +0100429 bool transforms_complete = true;
430 int transforms = 0;
431 string io_path;
Zim867fece2020-09-23 15:23:19 +0100432
433 if (S_ISREG(e->attr.st_mode)) {
434 // Handle potential file transforms
435 transforms = fuse->mp->GetTransforms(path, req->ctx.uid);
436
437 if (transforms < 0) {
438 // Fail lookup if we can't fetch supported transforms for path
439 LOG(WARNING) << "Failed to fetch transforms for " << name;
440 *error_code = ENOENT;
441 return NULL;
442 }
443
444 // TODO(b/169412244): Improve JNI interaction
445 // Invalidate if there are any transforms so that we always get a lookup into userspace
446 should_inval = should_inval || transforms;
447 if (transforms) {
448 // If there are any transforms, fetch IO path
449 io_path = fuse->mp->GetIoPath(path, req->ctx.uid);
450 if (io_path.empty()) {
451 *error_code = EFAULT;
452 return NULL;
453 }
454
455 if (io_path != path) {
456 // Update size with io_path size
457 if (lstat(io_path.c_str(), &e->attr) < 0) {
458 *error_code = errno;
459 return NULL;
460 }
461 transforms_complete = false;
462 }
463 }
464 }
465
Zimed257c12020-10-15 13:47:45 +0100466 node = parent->LookupChildByName(name, true /* acquire */, transforms);
Narayan Kamatheca34252020-02-11 13:08:37 +0000467 if (!node) {
Zimbb7c3762020-09-23 13:50:08 +0100468 node = ::node::Create(parent, name, io_path, transforms_complete, transforms, &fuse->lock,
469 &fuse->tracker);
Corina633099b2020-06-17 21:55:33 +0100470 } else if (!mediaprovider::fuse::containsMount(path, std::to_string(getuid() / PER_USER_RANGE))) {
Zim867fece2020-09-23 15:23:19 +0100471 should_inval = should_inval || node->HasCaseInsensitiveMatch();
Corina633099b2020-06-17 21:55:33 +0100472 // Only invalidate a path if it does not contain mount.
Zim0852ba72020-06-09 11:50:33 +0100473 // Invalidate both names to ensure there's no dentry left in the kernel after the following
474 // operations:
475 // 1) touch foo, touch FOO, unlink *foo*
476 // 2) touch foo, touch FOO, unlink *FOO*
477 // Invalidating lookup_name fixes (1) and invalidating node_name fixes (2)
Zim33aea102020-06-19 15:49:47 +0100478 // |should_inval| invalidates lookup_name by using 0 timeout below and we explicitly
479 // invalidate node_name if different case
480 // Note that we invalidate async otherwise we will deadlock the kernel
481 if (name != node->GetName()) {
Zimf2b47b42020-09-16 14:54:06 +0100482 should_inval = true;
483 // Record that we have made a case insensitive lookup, this allows us invalidate nodes
484 // correctly on subsequent lookups for the case of |node|
485 node->SetCaseInsensitiveMatch();
486
Narayan Kamath8b296f52020-07-29 13:10:17 +0100487 // Make copies of the node name and path so we're not attempting to acquire
488 // any node locks from the invalidation thread. Depending on timing, we may end
489 // up invalidating the wrong inode but that shouldn't result in correctness issues.
490 const fuse_ino_t parent_ino = fuse->ToInode(parent);
491 const fuse_ino_t child_ino = fuse->ToInode(node);
492 const std::string& node_name = node->GetName();
Narayan Kamath8b296f52020-07-29 13:10:17 +0100493 std::thread t([=]() { fuse_inval(fuse->se, parent_ino, child_ino, node_name, path); });
Zim33aea102020-06-19 15:49:47 +0100494 t.detach();
495 }
Narayan Kamathaef84a12020-01-02 15:20:13 +0000496 }
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100497 TRACE_NODE(node, req);
Zim89962312020-04-22 21:21:53 +0100498
Narayan Kamathfc0aa952019-12-31 13:31:49 +0000499 // This FS is not being exported via NFS so just a fixed generation number
500 // for now. If we do need this, we need to increment the generation ID each
501 // time the fuse daemon restarts because that's what it takes for us to
502 // reuse inode numbers.
503 e->generation = 0;
Zim8b2b6f22020-01-22 13:53:59 +0000504 e->ino = fuse->ToInode(node);
Zim867fece2020-09-23 15:23:19 +0100505 e->entry_timeout = get_entry_timeout(path, should_inval, node, fuse);
506 e->attr_timeout = get_attr_timeout(path, should_inval, node, fuse);
shafik1e3a2672019-08-16 14:51:55 +0100507 return node;
508}
509
shafik15e2d612019-10-31 20:10:25 +0000510static inline bool is_requesting_write(int flags) {
511 return flags & (O_WRONLY | O_RDWR);
512}
513
shafik1e3a2672019-08-16 14:51:55 +0100514namespace mediaprovider {
515namespace fuse {
516
517/**
518 * Function implementations
519 *
520 * These implement the various functions in fuse_lowlevel_ops
521 *
522 */
523
524static void pf_init(void* userdata, struct fuse_conn_info* conn) {
Zima9fcd552019-08-29 15:17:04 +0100525 // We don't want a getattr request with every read request
Zim1100f342020-05-15 16:13:00 +0100526 conn->want &= ~FUSE_CAP_AUTO_INVAL_DATA & ~FUSE_CAP_READDIRPLUS_AUTO;
shafik8b57cd52019-09-06 10:51:29 +0100527 unsigned mask = (FUSE_CAP_SPLICE_WRITE | FUSE_CAP_SPLICE_MOVE | FUSE_CAP_SPLICE_READ |
528 FUSE_CAP_ASYNC_READ | FUSE_CAP_ATOMIC_O_TRUNC | FUSE_CAP_WRITEBACK_CACHE |
529 FUSE_CAP_EXPORT_SUPPORT | FUSE_CAP_FLOCK_LOCKS);
shafik1e3a2672019-08-16 14:51:55 +0100530 conn->want |= conn->capable & mask;
shafikb334a612019-09-30 20:38:16 +0100531 conn->max_read = MAX_READ_SIZE;
Zimd0435b22020-03-05 13:52:51 +0000532
533 struct fuse* fuse = reinterpret_cast<struct fuse*>(userdata);
534 fuse->active->store(true, std::memory_order_release);
shafik1e3a2672019-08-16 14:51:55 +0100535}
536
Zim005cd812019-12-17 15:35:51 +0000537static void pf_destroy(void* userdata) {
538 struct fuse* fuse = reinterpret_cast<struct fuse*>(userdata);
539 LOG(INFO) << "DESTROY " << fuse->path;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000540
541 node::DeleteTree(fuse->root);
shafik1e3a2672019-08-16 14:51:55 +0100542}
shafik1e3a2672019-08-16 14:51:55 +0100543
Ricky Wai44670762020-05-01 11:25:28 +0100544// Return true if the path is accessible for that uid.
545static bool is_app_accessible_path(MediaProviderWrapper* mp, const string& path, uid_t uid) {
546 if (uid < AID_APP_START) {
547 return true;
548 }
549
Martijn Coenen71435d52020-06-15 20:23:40 +0200550 if (path == "/storage/emulated") {
551 // Apps should never refer to /storage/emulated - they should be using the user-spcific
552 // subdirs, eg /storage/emulated/0
553 return false;
554 }
555
Ricky Wai44670762020-05-01 11:25:28 +0100556 std::smatch match;
557 if (std::regex_match(path, match, PATTERN_OWNED_PATH)) {
558 const std::string& pkg = match[1];
Abhijeet Kaur077fdd52020-05-28 13:59:31 +0100559 // .nomedia is not a valid package. .nomedia always exists in /Android/data directory,
560 // and it's not an external file/directory of any package
561 if (pkg == ".nomedia") {
562 return true;
563 }
Ricky Wai44670762020-05-01 11:25:28 +0100564 if (!mp->IsUidForPackage(pkg, uid)) {
565 PLOG(WARNING) << "Invalid other package file access from " << pkg << "(: " << path;
566 return false;
567 }
568 }
569 return true;
570}
571
Zim859db932019-12-13 00:09:17 +0000572static std::regex storage_emulated_regex("^\\/storage\\/emulated\\/([0-9]+)");
Narayan Kamathaef84a12020-01-02 15:20:13 +0000573static node* do_lookup(fuse_req_t req, fuse_ino_t parent, const char* name,
574 struct fuse_entry_param* e, int* error_code) {
shafik1e3a2672019-08-16 14:51:55 +0100575 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100576 node* parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +0100577 if (!parent_node) {
578 *error_code = ENOENT;
579 return nullptr;
580 }
Narayan Kamathaef84a12020-01-02 15:20:13 +0000581 string parent_path = parent_node->BuildPath();
Martijn Coenena5f19e82020-06-17 13:01:23 +0200582 // We should always allow lookups on the root, because failing them could cause
583 // bind mounts to be invalidated.
584 if (!fuse->IsRoot(parent_node) && !is_app_accessible_path(fuse->mp, parent_path, req->ctx.uid)) {
Ricky Wai44670762020-05-01 11:25:28 +0100585 *error_code = ENOENT;
586 return nullptr;
587 }
588
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000589 string child_path = parent_path + "/" + name;
Zim2c5eb692020-02-20 15:47:06 +0000590
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100591 TRACE_NODE(parent_node, req);
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +0000592
Zim859db932019-12-13 00:09:17 +0000593 std::smatch match;
594 std::regex_search(child_path, match, storage_emulated_regex);
Zim5077a892020-09-08 12:55:12 +0100595
596 // Ensure the FuseDaemon user id matches the user id or cross-user lookups are allowed in
597 // requested path
Zimf0e3cd92020-01-03 00:57:43 +0000598 if (match.size() == 2 && std::to_string(getuid() / PER_USER_RANGE) != match[1].str()) {
Zim5077a892020-09-08 12:55:12 +0100599 // If user id mismatch, check cross-user lookups
600 if (!fuse->mp->ShouldAllowLookup(req->ctx.uid, std::stoi(match[1].str()))) {
601 *error_code = EACCES;
602 return nullptr;
603 }
Zim859db932019-12-13 00:09:17 +0000604 }
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000605 return make_node_entry(req, parent_node, name, child_path, e, error_code);
shafik1e3a2672019-08-16 14:51:55 +0100606}
607
608static void pf_lookup(fuse_req_t req, fuse_ino_t parent, const char* name) {
Zimec8d5722019-12-05 07:26:13 +0000609 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100610 struct fuse_entry_param e;
611
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000612 int error_code = 0;
613 if (do_lookup(req, parent, name, &e, &error_code)) {
shafik1e3a2672019-08-16 14:51:55 +0100614 fuse_reply_entry(req, &e);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000615 } else {
616 CHECK(error_code != 0);
617 fuse_reply_err(req, error_code);
618 }
shafik1e3a2672019-08-16 14:51:55 +0100619}
620
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100621static void do_forget(fuse_req_t req, struct fuse* fuse, fuse_ino_t ino, uint64_t nlookup) {
Ricky Wai44670762020-05-01 11:25:28 +0100622 node* node = fuse->FromInode(ino);
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100623 TRACE_NODE(node, req);
shafik1e3a2672019-08-16 14:51:55 +0100624 if (node) {
Narayan Kamathaef84a12020-01-02 15:20:13 +0000625 // This is a narrowing conversion from an unsigned 64bit to a 32bit value. For
626 // some reason we only keep 32 bit refcounts but the kernel issues
627 // forget requests with a 64 bit counter.
Narayan Kamath568f17a2020-02-19 13:45:29 +0000628 node->Release(static_cast<uint32_t>(nlookup));
shafik1e3a2672019-08-16 14:51:55 +0100629 }
630}
631
632static void pf_forget(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup) {
Ricky Wai44670762020-05-01 11:25:28 +0100633 // Always allow to forget so no need to check is_app_accessible_path()
Zimec8d5722019-12-05 07:26:13 +0000634 ATRACE_CALL();
Narayan Kamathaef84a12020-01-02 15:20:13 +0000635 node* node;
shafik1e3a2672019-08-16 14:51:55 +0100636 struct fuse* fuse = get_fuse(req);
637
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100638 do_forget(req, fuse, ino, nlookup);
shafik1e3a2672019-08-16 14:51:55 +0100639 fuse_reply_none(req);
640}
641
642static void pf_forget_multi(fuse_req_t req,
643 size_t count,
644 struct fuse_forget_data* forgets) {
Zimec8d5722019-12-05 07:26:13 +0000645 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100646 struct fuse* fuse = get_fuse(req);
647
Narayan Kamathaef84a12020-01-02 15:20:13 +0000648 for (int i = 0; i < count; i++) {
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100649 do_forget(req, fuse, forgets[i].ino, forgets[i].nlookup);
Narayan Kamath768bea32019-12-27 16:23:23 +0000650 }
shafik1e3a2672019-08-16 14:51:55 +0100651 fuse_reply_none(req);
652}
653
654static void pf_getattr(fuse_req_t req,
655 fuse_ino_t ino,
656 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +0000657 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100658 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100659 node* node = fuse->FromInode(ino);
Ricky Waif40c4022020-04-15 19:00:06 +0100660 if (!node) {
661 fuse_reply_err(req, ENOENT);
662 return;
663 }
Zim867fece2020-09-23 15:23:19 +0100664 const string& path = get_path(node);
Ricky Wai44670762020-05-01 11:25:28 +0100665 if (!is_app_accessible_path(fuse->mp, path, req->ctx.uid)) {
666 fuse_reply_err(req, ENOENT);
667 return;
668 }
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100669 TRACE_NODE(node, req);
shafik1e3a2672019-08-16 14:51:55 +0100670
Narayan Kamathaef84a12020-01-02 15:20:13 +0000671 struct stat s;
shafik1e3a2672019-08-16 14:51:55 +0100672 memset(&s, 0, sizeof(s));
673 if (lstat(path.c_str(), &s) < 0) {
674 fuse_reply_err(req, errno);
675 } else {
Zim867fece2020-09-23 15:23:19 +0100676 fuse_reply_attr(
677 req, &s,
678 get_attr_timeout(path, node->GetTransforms() || node->HasCaseInsensitiveMatch(),
679 node, fuse));
shafik1e3a2672019-08-16 14:51:55 +0100680 }
681}
682
683static void pf_setattr(fuse_req_t req,
684 fuse_ino_t ino,
685 struct stat* attr,
686 int to_set,
687 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +0000688 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100689 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100690 node* node = fuse->FromInode(ino);
shafik1e3a2672019-08-16 14:51:55 +0100691 if (!node) {
692 fuse_reply_err(req, ENOENT);
693 return;
694 }
Zim867fece2020-09-23 15:23:19 +0100695 const string& path = get_path(node);
Ricky Wai44670762020-05-01 11:25:28 +0100696 if (!is_app_accessible_path(fuse->mp, path, req->ctx.uid)) {
697 fuse_reply_err(req, ENOENT);
698 return;
699 }
Ricky Waif40c4022020-04-15 19:00:06 +0100700
Zimuzo Ezeozue435bd252020-06-30 20:15:17 +0000701 int fd = -1;
702 if (fi) {
703 // If we have a file_info, setattr was called with an fd so use the fd instead of path
704 handle* h = reinterpret_cast<handle*>(fi->fh);
705 fd = h->fd;
706 } else {
707 const struct fuse_ctx* ctx = fuse_req_ctx(req);
708 int status = fuse->mp->IsOpenAllowed(path, ctx->uid, true);
709 if (status) {
710 fuse_reply_err(req, EACCES);
711 return;
712 }
713 }
714 struct timespec times[2];
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100715 TRACE_NODE(node, req);
shafik1e3a2672019-08-16 14:51:55 +0100716
717 /* XXX: incomplete implementation on purpose.
718 * chmod/chown should NEVER be implemented.*/
719
Zimuzo Ezeozue435bd252020-06-30 20:15:17 +0000720 if ((to_set & FUSE_SET_ATTR_SIZE)) {
721 int res = 0;
722 if (fd == -1) {
723 res = truncate64(path.c_str(), attr->st_size);
724 } else {
725 res = ftruncate64(fd, attr->st_size);
726 }
727
728 if (res < 0) {
729 fuse_reply_err(req, errno);
730 return;
731 }
shafik1e3a2672019-08-16 14:51:55 +0100732 }
733
734 /* Handle changing atime and mtime. If FATTR_ATIME_and FATTR_ATIME_NOW
735 * are both set, then set it to the current time. Else, set it to the
736 * time specified in the request. Same goes for mtime. Use utimensat(2)
737 * as it allows ATIME and MTIME to be changed independently, and has
738 * nanosecond resolution which fuse also has.
739 */
740 if (to_set & (FATTR_ATIME | FATTR_MTIME)) {
741 times[0].tv_nsec = UTIME_OMIT;
742 times[1].tv_nsec = UTIME_OMIT;
743 if (to_set & FATTR_ATIME) {
744 if (to_set & FATTR_ATIME_NOW) {
745 times[0].tv_nsec = UTIME_NOW;
746 } else {
Zim0056c4b2020-04-27 18:56:51 +0100747 times[0] = attr->st_atim;
shafik1e3a2672019-08-16 14:51:55 +0100748 }
749 }
Zim0056c4b2020-04-27 18:56:51 +0100750
shafik1e3a2672019-08-16 14:51:55 +0100751 if (to_set & FATTR_MTIME) {
752 if (to_set & FATTR_MTIME_NOW) {
753 times[1].tv_nsec = UTIME_NOW;
754 } else {
Zim0056c4b2020-04-27 18:56:51 +0100755 times[1] = attr->st_mtim;
shafik1e3a2672019-08-16 14:51:55 +0100756 }
757 }
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +0000758
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100759 TRACE_NODE(node, req);
Zimuzo Ezeozue435bd252020-06-30 20:15:17 +0000760 int res = 0;
761 if (fd == -1) {
762 res = utimensat(-1, path.c_str(), times, 0);
763 } else {
764 res = futimens(fd, times);
765 }
766
767 if (res < 0) {
shafik1e3a2672019-08-16 14:51:55 +0100768 fuse_reply_err(req, errno);
769 return;
770 }
771 }
772
Zima9fcd552019-08-29 15:17:04 +0100773 lstat(path.c_str(), attr);
Zim867fece2020-09-23 15:23:19 +0100774 fuse_reply_attr(req, attr,
775 get_attr_timeout(path, node->GetTransforms() || node->HasCaseInsensitiveMatch(),
776 node, fuse));
shafik1e3a2672019-08-16 14:51:55 +0100777}
Zimb9730bf2019-11-30 15:10:04 +0000778
779static void pf_canonical_path(fuse_req_t req, fuse_ino_t ino)
shafik1e3a2672019-08-16 14:51:55 +0100780{
Ricky Wai44670762020-05-01 11:25:28 +0100781 struct fuse* fuse = get_fuse(req);
782 node* node = fuse->FromInode(ino);
Zim867fece2020-09-23 15:23:19 +0100783 const string& path = node ? get_path(node) : "";
Zimb9730bf2019-11-30 15:10:04 +0000784
Ricky Wai44670762020-05-01 11:25:28 +0100785 if (node && is_app_accessible_path(fuse->mp, path, req->ctx.uid)) {
Zimb9730bf2019-11-30 15:10:04 +0000786 // TODO(b/147482155): Check that uid has access to |path| and its contents
Ricky Wai44670762020-05-01 11:25:28 +0100787 fuse_reply_canonical_path(req, path.c_str());
Zimb9730bf2019-11-30 15:10:04 +0000788 return;
789 }
790 fuse_reply_err(req, ENOENT);
shafik1e3a2672019-08-16 14:51:55 +0100791}
Zimb9730bf2019-11-30 15:10:04 +0000792
shafik1e3a2672019-08-16 14:51:55 +0100793static void pf_mknod(fuse_req_t req,
794 fuse_ino_t parent,
795 const char* name,
796 mode_t mode,
797 dev_t rdev) {
Zimec8d5722019-12-05 07:26:13 +0000798 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100799 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100800 node* parent_node = fuse->FromInode(parent);
shafik1e3a2672019-08-16 14:51:55 +0100801 if (!parent_node) {
802 fuse_reply_err(req, ENOENT);
803 return;
804 }
Ricky Waif40c4022020-04-15 19:00:06 +0100805 string parent_path = parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +0100806 if (!is_app_accessible_path(fuse->mp, parent_path, req->ctx.uid)) {
807 fuse_reply_err(req, ENOENT);
808 return;
809 }
Ricky Waif40c4022020-04-15 19:00:06 +0100810
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100811 TRACE_NODE(parent_node, req);
Ricky Waif40c4022020-04-15 19:00:06 +0100812
Narayan Kamathaef84a12020-01-02 15:20:13 +0000813 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100814
815 mode = (mode & (~0777)) | 0664;
816 if (mknod(child_path.c_str(), mode, rdev) < 0) {
817 fuse_reply_err(req, errno);
818 return;
819 }
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000820
821 int error_code = 0;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000822 struct fuse_entry_param e;
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000823 if (make_node_entry(req, parent_node, name, child_path, &e, &error_code)) {
shafik1e3a2672019-08-16 14:51:55 +0100824 fuse_reply_entry(req, &e);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000825 } else {
826 CHECK(error_code != 0);
827 fuse_reply_err(req, error_code);
828 }
shafik1e3a2672019-08-16 14:51:55 +0100829}
830
831static void pf_mkdir(fuse_req_t req,
832 fuse_ino_t parent,
833 const char* name,
834 mode_t mode) {
Zimec8d5722019-12-05 07:26:13 +0000835 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100836 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100837 node* parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +0100838 if (!parent_node) {
839 fuse_reply_err(req, ENOENT);
840 return;
841 }
Ricky Wai44670762020-05-01 11:25:28 +0100842 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000843 const string parent_path = parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +0100844 if (!is_app_accessible_path(fuse->mp, parent_path, ctx->uid)) {
845 fuse_reply_err(req, ENOENT);
846 return;
847 }
Narayan Kamath768bea32019-12-27 16:23:23 +0000848
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100849 TRACE_NODE(parent_node, req);
shafik1e3a2672019-08-16 14:51:55 +0100850
Narayan Kamathaef84a12020-01-02 15:20:13 +0000851 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100852
shafike4fb1462020-01-29 16:25:23 +0000853 int status = fuse->mp->IsCreatingDirAllowed(child_path, ctx->uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000854 if (status) {
855 fuse_reply_err(req, status);
856 return;
857 }
858
shafik1e3a2672019-08-16 14:51:55 +0100859 mode = (mode & (~0777)) | 0775;
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000860 if (mkdir(child_path.c_str(), mode) < 0) {
shafik1e3a2672019-08-16 14:51:55 +0100861 fuse_reply_err(req, errno);
862 return;
863 }
864
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000865 int error_code = 0;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000866 struct fuse_entry_param e;
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000867 if (make_node_entry(req, parent_node, name, child_path, &e, &error_code)) {
shafik1e3a2672019-08-16 14:51:55 +0100868 fuse_reply_entry(req, &e);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000869 } else {
870 CHECK(error_code != 0);
871 fuse_reply_err(req, error_code);
872 }
shafik1e3a2672019-08-16 14:51:55 +0100873}
874
875static void pf_unlink(fuse_req_t req, fuse_ino_t parent, const char* name) {
Zimec8d5722019-12-05 07:26:13 +0000876 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100877 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100878 node* parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +0100879 if (!parent_node) {
880 fuse_reply_err(req, ENOENT);
881 return;
882 }
Ricky Wai44670762020-05-01 11:25:28 +0100883 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000884 const string parent_path = parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +0100885 if (!is_app_accessible_path(fuse->mp, parent_path, ctx->uid)) {
886 fuse_reply_err(req, ENOENT);
887 return;
888 }
shafik1e3a2672019-08-16 14:51:55 +0100889
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100890 TRACE_NODE(parent_node, req);
shafik1e3a2672019-08-16 14:51:55 +0100891
Narayan Kamathaef84a12020-01-02 15:20:13 +0000892 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100893
shafike4fb1462020-01-29 16:25:23 +0000894 int status = fuse->mp->DeleteFile(child_path, ctx->uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000895 if (status) {
896 fuse_reply_err(req, status);
shafik1e3a2672019-08-16 14:51:55 +0100897 return;
898 }
Narayan Kamath768bea32019-12-27 16:23:23 +0000899
Zim53c2d702020-09-23 12:18:27 +0100900 // TODO(b/169306422): Log each deleted node
901 parent_node->SetDeletedForChild(name);
shafik1e3a2672019-08-16 14:51:55 +0100902 fuse_reply_err(req, 0);
903}
904
905static void pf_rmdir(fuse_req_t req, fuse_ino_t parent, const char* name) {
Zimec8d5722019-12-05 07:26:13 +0000906 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100907 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100908 node* parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +0100909 if (!parent_node) {
910 fuse_reply_err(req, ENOENT);
911 return;
912 }
Narayan Kamathaef84a12020-01-02 15:20:13 +0000913 const string parent_path = parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +0100914 if (!is_app_accessible_path(fuse->mp, parent_path, req->ctx.uid)) {
915 fuse_reply_err(req, ENOENT);
916 return;
917 }
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100918 TRACE_NODE(parent_node, req);
shafik1e3a2672019-08-16 14:51:55 +0100919
Narayan Kamathaef84a12020-01-02 15:20:13 +0000920 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100921
Ricky Wai44670762020-05-01 11:25:28 +0100922 int status = fuse->mp->IsDeletingDirAllowed(child_path, req->ctx.uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000923 if (status) {
924 fuse_reply_err(req, status);
925 return;
926 }
927
928 if (rmdir(child_path.c_str()) < 0) {
shafik1e3a2672019-08-16 14:51:55 +0100929 fuse_reply_err(req, errno);
930 return;
931 }
Narayan Kamath768bea32019-12-27 16:23:23 +0000932
Narayan Kamatheca34252020-02-11 13:08:37 +0000933 node* child_node = parent_node->LookupChildByName(name, false /* acquire */);
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100934 TRACE_NODE(child_node, req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000935 if (child_node) {
936 child_node->SetDeleted();
shafik1e3a2672019-08-16 14:51:55 +0100937 }
shafik1e3a2672019-08-16 14:51:55 +0100938
939 fuse_reply_err(req, 0);
940}
941/*
942static void pf_symlink(fuse_req_t req, const char* link, fuse_ino_t parent,
943 const char* name)
944{
945 cout << "TODO:" << __func__;
946}
947*/
Sahana Rao2c416032019-12-31 13:41:00 +0000948static int do_rename(fuse_req_t req, fuse_ino_t parent, const char* name, fuse_ino_t new_parent,
949 const char* new_name, unsigned int flags) {
Zimec8d5722019-12-05 07:26:13 +0000950 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100951 struct fuse* fuse = get_fuse(req);
shafik1e3a2672019-08-16 14:51:55 +0100952
Sahana Rao2c416032019-12-31 13:41:00 +0000953 if (flags != 0) {
Sahana Rao2c416032019-12-31 13:41:00 +0000954 return EINVAL;
955 }
Narayan Kamath768bea32019-12-27 16:23:23 +0000956
Ricky Wai44670762020-05-01 11:25:28 +0100957 node* old_parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +0100958 if (!old_parent_node) return ENOENT;
Ricky Wai44670762020-05-01 11:25:28 +0100959 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000960 const string old_parent_path = old_parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +0100961 if (!is_app_accessible_path(fuse->mp, old_parent_path, ctx->uid)) {
962 return ENOENT;
963 }
964
965 node* new_parent_node = fuse->FromInode(new_parent);
Ricky Waif40c4022020-04-15 19:00:06 +0100966 if (!new_parent_node) return ENOENT;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000967 const string new_parent_path = new_parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +0100968 if (!is_app_accessible_path(fuse->mp, new_parent_path, ctx->uid)) {
969 return ENOENT;
970 }
Narayan Kamath768bea32019-12-27 16:23:23 +0000971
Narayan Kamathaef84a12020-01-02 15:20:13 +0000972 if (!old_parent_node || !new_parent_node) {
973 return ENOENT;
974 } else if (parent == new_parent && name == new_name) {
975 // No rename required.
976 return 0;
shafik1e3a2672019-08-16 14:51:55 +0100977 }
978
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100979 TRACE_NODE(old_parent_node, req);
980 TRACE_NODE(new_parent_node, req);
shafik1e3a2672019-08-16 14:51:55 +0100981
Zim53c2d702020-09-23 12:18:27 +0100982 const string old_child_path = old_parent_path + "/" + name;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000983 const string new_child_path = new_parent_path + "/" + new_name;
984
Sahana Rao182ec6b2020-01-03 15:00:46 +0000985 // TODO(b/147408834): Check ENOTEMPTY & EEXIST error conditions before JNI call.
shafike4fb1462020-01-29 16:25:23 +0000986 const int res = fuse->mp->Rename(old_child_path, new_child_path, req->ctx.uid);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000987 // TODO(b/145663158): Lookups can go out of sync if file/directory is actually moved but
988 // EFAULT/EIO is reported due to JNI exception.
989 if (res == 0) {
Zim53c2d702020-09-23 12:18:27 +0100990 // TODO(b/169306422): Log each renamed node
991 old_parent_node->RenameChild(name, new_name, new_parent_node);
shafik1e3a2672019-08-16 14:51:55 +0100992 }
Narayan Kamath768bea32019-12-27 16:23:23 +0000993 return res;
994}
shafik1e3a2672019-08-16 14:51:55 +0100995
Sahana Rao2c416032019-12-31 13:41:00 +0000996static void pf_rename(fuse_req_t req, fuse_ino_t parent, const char* name, fuse_ino_t new_parent,
997 const char* new_name, unsigned int flags) {
998 int res = do_rename(req, parent, name, new_parent, new_name, flags);
shafik1e3a2672019-08-16 14:51:55 +0100999 fuse_reply_err(req, res);
1000}
Narayan Kamath768bea32019-12-27 16:23:23 +00001001
shafik1e3a2672019-08-16 14:51:55 +01001002/*
Sahana Rao2c416032019-12-31 13:41:00 +00001003static void pf_link(fuse_req_t req, fuse_ino_t ino, fuse_ino_t new_parent,
1004 const char* new_name)
shafik1e3a2672019-08-16 14:51:55 +01001005{
1006 cout << "TODO:" << __func__;
1007}
1008*/
1009
Zim9aa6f542020-10-19 15:39:33 +01001010static handle* create_handle_for_node(struct fuse* fuse, const string& path, int fd, uid_t uid,
1011 node* node, const RedactionInfo* ri, int* keep_cache) {
Zimc05c60f2020-03-05 13:02:26 +00001012 std::lock_guard<std::recursive_mutex> guard(fuse->lock);
1013 // We don't want to use the FUSE VFS cache in two cases:
1014 // 1. When redaction is needed because app A with EXIF access might access
1015 // a region that should have been redacted for app B without EXIF access, but app B on
1016 // a subsequent read, will be able to see the EXIF data because the read request for
1017 // that region will be served from cache and not get to the FUSE daemon
1018 // 2. When the file has a read or write lock on it. This means that the MediaProvider
1019 // has given an fd to the lower file system to an app. There are two cases where using
1020 // the cache in this case can be a problem:
1021 // a. Writing to a FUSE fd with caching enabled will use the write-back cache and a
1022 // subsequent read from the lower fs fd will not see the write.
1023 // b. Reading from a FUSE fd with caching enabled may not see the latest writes using
1024 // the lower fs fd because those writes did not go through the FUSE layer and reads from
1025 // FUSE after that write may be served from cache
Zim329ba2c2020-09-16 14:23:26 +01001026 bool has_redacted = node->HasRedactedCache();
1027 bool redaction_needed = ri->isRedactionNeeded();
1028 bool is_redaction_change =
1029 (redaction_needed && !has_redacted) || (!redaction_needed && has_redacted);
1030 bool is_cached_file_open = node->HasCachedHandle();
Zimc05c60f2020-03-05 13:02:26 +00001031
Zim329ba2c2020-09-16 14:23:26 +01001032 if (!is_cached_file_open && is_redaction_change) {
1033 node->SetRedactedCache(redaction_needed);
1034 // Purges stale page cache before open
1035 *keep_cache = 0;
1036 } else {
1037 *keep_cache = 1;
1038 }
1039
1040 bool direct_io = (is_cached_file_open && is_redaction_change) || is_file_locked(fd, path);
Zim9aa6f542020-10-19 15:39:33 +01001041 handle* h = new handle(fd, ri, !direct_io, uid);
Zimc05c60f2020-03-05 13:02:26 +00001042 node->AddHandle(h);
1043 return h;
1044}
1045
shafik1e3a2672019-08-16 14:51:55 +01001046static void pf_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001047 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001048 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +01001049 node* node = fuse->FromInode(ino);
shafik1e3a2672019-08-16 14:51:55 +01001050 if (!node) {
1051 fuse_reply_err(req, ENOENT);
1052 return;
1053 }
Ricky Wai44670762020-05-01 11:25:28 +01001054 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Zim867fece2020-09-23 15:23:19 +01001055 const string& path = get_path(node);
Ricky Wai44670762020-05-01 11:25:28 +01001056 if (!is_app_accessible_path(fuse->mp, path, ctx->uid)) {
1057 fuse_reply_err(req, ENOENT);
1058 return;
1059 }
Ricky Waif40c4022020-04-15 19:00:06 +01001060
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001061 TRACE_NODE(node, req) << (is_requesting_write(fi->flags) ? "write" : "read");
shafik1e3a2672019-08-16 14:51:55 +01001062
shafik15e2d612019-10-31 20:10:25 +00001063 if (fi->flags & O_DIRECT) {
1064 fi->flags &= ~O_DIRECT;
1065 fi->direct_io = true;
1066 }
1067
Zim867fece2020-09-23 15:23:19 +01001068 // TODO: If transform, disallow write
shafike4fb1462020-01-29 16:25:23 +00001069 int status = fuse->mp->IsOpenAllowed(path, ctx->uid, is_requesting_write(fi->flags));
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001070 if (status) {
1071 fuse_reply_err(req, status);
1072 return;
1073 }
1074
Martijn Coenen2d7f1be2020-02-15 07:44:12 +01001075 // With the writeback cache enabled, FUSE may generate READ requests even for files that
1076 // were opened O_WRONLY; so make sure we open it O_RDWR instead.
1077 int open_flags = fi->flags;
1078 if (open_flags & O_WRONLY) {
1079 open_flags &= ~O_WRONLY;
1080 open_flags |= O_RDWR;
1081 }
1082
Zim1b14f2f2020-07-03 07:05:53 +01001083 if (open_flags & O_APPEND) {
1084 open_flags &= ~O_APPEND;
1085 }
1086
Martijn Coenen2d7f1be2020-02-15 07:44:12 +01001087 const int fd = open(path.c_str(), open_flags);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001088 if (fd < 0) {
shafik1e3a2672019-08-16 14:51:55 +01001089 fuse_reply_err(req, errno);
1090 return;
1091 }
shafik15e2d612019-10-31 20:10:25 +00001092
shafikc580b6d2019-12-10 18:45:17 +00001093 // We don't redact if the caller was granted write permission for this file
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001094 std::unique_ptr<RedactionInfo> ri;
shafikc580b6d2019-12-10 18:45:17 +00001095 if (is_requesting_write(fi->flags)) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001096 ri = std::make_unique<RedactionInfo>();
shafikc580b6d2019-12-10 18:45:17 +00001097 } else {
Zim7d249ef2020-05-26 13:55:56 +01001098 ri = fuse->mp->GetRedactionInfo(path, req->ctx.uid, req->ctx.pid);
shafikc580b6d2019-12-10 18:45:17 +00001099 }
1100
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001101 if (!ri) {
1102 close(fd);
1103 fuse_reply_err(req, EFAULT);
shafikc580b6d2019-12-10 18:45:17 +00001104 return;
1105 }
1106
Zim329ba2c2020-09-16 14:23:26 +01001107 int keep_cache = 1;
Zim9aa6f542020-10-19 15:39:33 +01001108 handle* h =
1109 create_handle_for_node(fuse, path, fd, req->ctx.uid, node, ri.release(), &keep_cache);
shafik1e3a2672019-08-16 14:51:55 +01001110 fi->fh = ptr_to_id(h);
Zim329ba2c2020-09-16 14:23:26 +01001111 fi->keep_cache = keep_cache;
Zimc05c60f2020-03-05 13:02:26 +00001112 fi->direct_io = !h->cached;
shafik1e3a2672019-08-16 14:51:55 +01001113 fuse_reply_open(req, fi);
1114}
1115
shafikc3f62672019-08-30 11:15:48 +01001116static void do_read(fuse_req_t req, size_t size, off_t off, struct fuse_file_info* fi) {
shafika2ae9072019-10-28 12:16:00 +00001117 handle* h = reinterpret_cast<handle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001118 struct fuse_bufvec buf = FUSE_BUFVEC_INIT(size);
1119
1120 buf.buf[0].fd = h->fd;
1121 buf.buf[0].pos = off;
1122 buf.buf[0].flags =
1123 (enum fuse_buf_flags) (FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
1124
1125 fuse_reply_data(req, &buf, (enum fuse_buf_copy_flags) 0);
1126}
shafikc3f62672019-08-30 11:15:48 +01001127
shafikc3f62672019-08-30 11:15:48 +01001128/**
1129 * Sets the parameters for a fuse_buf that reads from memory, including flags.
shafikb334a612019-09-30 20:38:16 +01001130 * Makes buf->mem point to an already mapped region of zeroized memory.
1131 * This memory is read only.
shafikc3f62672019-08-30 11:15:48 +01001132 */
shafikb334a612019-09-30 20:38:16 +01001133static void create_mem_fuse_buf(size_t size, fuse_buf* buf, struct fuse* fuse) {
shafikc3f62672019-08-30 11:15:48 +01001134 buf->size = size;
shafikb334a612019-09-30 20:38:16 +01001135 buf->mem = fuse->zero_addr;
shafikc3f62672019-08-30 11:15:48 +01001136 buf->flags = static_cast<fuse_buf_flags>(0 /*read from fuse_buf.mem*/);
1137 buf->pos = -1;
1138 buf->fd = -1;
1139}
1140
1141/**
1142 * Sets the parameters for a fuse_buf that reads from file, including flags.
1143 */
1144static void create_file_fuse_buf(size_t size, off_t pos, int fd, fuse_buf* buf) {
1145 buf->size = size;
1146 buf->fd = fd;
1147 buf->pos = pos;
1148 buf->flags = static_cast<fuse_buf_flags>(FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
1149 buf->mem = nullptr;
1150}
1151
1152static 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 +00001153 handle* h = reinterpret_cast<handle*>(fi->fh);
shafikc3f62672019-08-30 11:15:48 +01001154
Narayan Kamath11700c02020-10-06 09:15:34 +01001155 std::vector<ReadRange> ranges;
1156 h->ri->getReadRanges(off, size, &ranges);
1157
1158 // As an optimization, return early if there are no ranges to redact.
1159 if (ranges.size() == 0) {
shafikc3f62672019-08-30 11:15:48 +01001160 do_read(req, size, off, fi);
1161 return;
1162 }
Narayan Kamath11700c02020-10-06 09:15:34 +01001163
1164 const size_t num_bufs = ranges.size();
shafikc3f62672019-08-30 11:15:48 +01001165 auto bufvec_ptr = std::unique_ptr<fuse_bufvec, decltype(free)*>{
1166 reinterpret_cast<fuse_bufvec*>(
1167 malloc(sizeof(fuse_bufvec) + (num_bufs - 1) * sizeof(fuse_buf))),
1168 free};
1169 fuse_bufvec& bufvec = *bufvec_ptr;
1170
1171 // initialize bufvec
1172 bufvec.count = num_bufs;
1173 bufvec.idx = 0;
1174 bufvec.off = 0;
shafikc3f62672019-08-30 11:15:48 +01001175
shafikc3f62672019-08-30 11:15:48 +01001176 for (int i = 0; i < num_bufs; ++i) {
Narayan Kamath11700c02020-10-06 09:15:34 +01001177 const ReadRange& range = ranges[i];
1178 if (range.is_redaction) {
1179 create_mem_fuse_buf(range.size, &(bufvec.buf[i]), get_fuse(req));
shafikc3f62672019-08-30 11:15:48 +01001180 } else {
Narayan Kamath11700c02020-10-06 09:15:34 +01001181 create_file_fuse_buf(range.size, range.start, h->fd, &(bufvec.buf[i]));
shafikc3f62672019-08-30 11:15:48 +01001182 }
shafikc3f62672019-08-30 11:15:48 +01001183 }
1184
1185 fuse_reply_data(req, &bufvec, static_cast<fuse_buf_copy_flags>(0));
1186}
1187
1188static void pf_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off,
1189 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001190 ATRACE_CALL();
shafika2ae9072019-10-28 12:16:00 +00001191 handle* h = reinterpret_cast<handle*>(fi->fh);
shafikc3f62672019-08-30 11:15:48 +01001192 struct fuse* fuse = get_fuse(req);
shafikc3f62672019-08-30 11:15:48 +01001193
Zim867fece2020-09-23 15:23:19 +01001194 node* node = fuse->FromInode(ino);
1195
1196 if (!node->IsTransformsComplete()) {
1197 if (!fuse->mp->Transform(node->BuildPath(), node->GetIoPath(), node->GetTransforms(),
Zim9aa6f542020-10-19 15:39:33 +01001198 h->uid)) {
Zim867fece2020-09-23 15:23:19 +01001199 fuse_reply_err(req, EFAULT);
1200 return;
1201 }
1202 node->SetTransformsComplete();
1203 }
1204
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001205 fuse->fadviser.Record(h->fd, size);
1206
shafikc3f62672019-08-30 11:15:48 +01001207 if (h->ri->isRedactionNeeded()) {
1208 do_read_with_redaction(req, size, off, fi);
1209 } else {
1210 do_read(req, size, off, fi);
1211 }
1212}
1213
shafik1e3a2672019-08-16 14:51:55 +01001214/*
1215static void pf_write(fuse_req_t req, fuse_ino_t ino, const char* buf,
1216 size_t size, off_t off, struct fuse_file_info* fi)
1217{
1218 cout << "TODO:" << __func__;
1219}
1220*/
1221
1222static void pf_write_buf(fuse_req_t req,
1223 fuse_ino_t ino,
1224 struct fuse_bufvec* bufv,
1225 off_t off,
1226 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001227 ATRACE_CALL();
shafika2ae9072019-10-28 12:16:00 +00001228 handle* h = reinterpret_cast<handle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001229 struct fuse_bufvec buf = FUSE_BUFVEC_INIT(fuse_buf_size(bufv));
1230 ssize_t size;
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001231 struct fuse* fuse = get_fuse(req);
shafik1e3a2672019-08-16 14:51:55 +01001232
1233 buf.buf[0].fd = h->fd;
1234 buf.buf[0].pos = off;
1235 buf.buf[0].flags =
1236 (enum fuse_buf_flags) (FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
1237 size = fuse_buf_copy(&buf, bufv, (enum fuse_buf_copy_flags) 0);
1238
1239 if (size < 0)
1240 fuse_reply_err(req, -size);
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001241 else {
shafik1e3a2672019-08-16 14:51:55 +01001242 fuse_reply_write(req, size);
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001243 fuse->fadviser.Record(h->fd, size);
1244 }
shafik1e3a2672019-08-16 14:51:55 +01001245}
1246// Haven't tested this one. Not sure what calls it.
1247#if 0
1248static void pf_copy_file_range(fuse_req_t req, fuse_ino_t ino_in,
1249 off_t off_in, struct fuse_file_info* fi_in,
1250 fuse_ino_t ino_out, off_t off_out,
1251 struct fuse_file_info* fi_out, size_t len,
1252 int flags)
1253{
shafika2ae9072019-10-28 12:16:00 +00001254 handle* h_in = reinterpret_cast<handle *>(fi_in->fh);
1255 handle* h_out = reinterpret_cast<handle *>(fi_out->fh);
shafik1e3a2672019-08-16 14:51:55 +01001256 struct fuse_bufvec buf_in = FUSE_BUFVEC_INIT(len);
1257 struct fuse_bufvec buf_out = FUSE_BUFVEC_INIT(len);
1258 ssize_t size;
1259
1260 buf_in.buf[0].fd = h_in->fd;
1261 buf_in.buf[0].pos = off_in;
1262 buf_in.buf[0].flags = (enum fuse_buf_flags)(FUSE_BUF_IS_FD|FUSE_BUF_FD_SEEK);
1263
1264 buf_out.buf[0].fd = h_out->fd;
1265 buf_out.buf[0].pos = off_out;
1266 buf_out.buf[0].flags = (enum fuse_buf_flags)(FUSE_BUF_IS_FD|FUSE_BUF_FD_SEEK);
1267 size = fuse_buf_copy(&buf_out, &buf_in, (enum fuse_buf_copy_flags) 0);
1268
1269 if (size < 0) {
1270 fuse_reply_err(req, -size);
1271 }
1272
1273 fuse_reply_write(req, size);
1274}
1275#endif
shafik1e3a2672019-08-16 14:51:55 +01001276
1277static void pf_release(fuse_req_t req,
1278 fuse_ino_t ino,
1279 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001280 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001281 struct fuse* fuse = get_fuse(req);
Kyle Tso613b7ab2019-12-24 06:30:00 +00001282
Ricky Wai44670762020-05-01 11:25:28 +01001283 node* node = fuse->FromInode(ino);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001284 handle* h = reinterpret_cast<handle*>(fi->fh);
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001285 TRACE_NODE(node, req);
shafik15e2d612019-10-31 20:10:25 +00001286
Narayan Kamathaef84a12020-01-02 15:20:13 +00001287 fuse->fadviser.Close(h->fd);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001288 if (node) {
1289 node->DestroyHandle(h);
Zimedbe69e2019-12-13 18:49:36 +00001290 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001291
shafik1e3a2672019-08-16 14:51:55 +01001292 fuse_reply_err(req, 0);
1293}
1294
1295static int do_sync_common(int fd, bool datasync) {
1296 int res = datasync ? fdatasync(fd) : fsync(fd);
1297
1298 if (res == -1) return errno;
1299 return 0;
1300}
1301
1302static void pf_fsync(fuse_req_t req,
1303 fuse_ino_t ino,
1304 int datasync,
1305 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001306 ATRACE_CALL();
shafika2ae9072019-10-28 12:16:00 +00001307 handle* h = reinterpret_cast<handle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001308 int err = do_sync_common(h->fd, datasync);
1309
1310 fuse_reply_err(req, err);
1311}
1312
1313static void pf_fsyncdir(fuse_req_t req,
1314 fuse_ino_t ino,
1315 int datasync,
1316 struct fuse_file_info* fi) {
Narayan Kamathaef84a12020-01-02 15:20:13 +00001317 dirhandle* h = reinterpret_cast<dirhandle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001318 int err = do_sync_common(dirfd(h->d), datasync);
1319
1320 fuse_reply_err(req, err);
1321}
1322
1323static void pf_opendir(fuse_req_t req,
1324 fuse_ino_t ino,
1325 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001326 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001327 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +01001328 node* node = fuse->FromInode(ino);
shafik1e3a2672019-08-16 14:51:55 +01001329 if (!node) {
1330 fuse_reply_err(req, ENOENT);
1331 return;
1332 }
Ricky Wai44670762020-05-01 11:25:28 +01001333 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Ricky Waif40c4022020-04-15 19:00:06 +01001334 const string path = node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +01001335 if (!is_app_accessible_path(fuse->mp, path, ctx->uid)) {
1336 fuse_reply_err(req, ENOENT);
1337 return;
1338 }
Ricky Waif40c4022020-04-15 19:00:06 +01001339
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001340 TRACE_NODE(node, req);
shafik1e3a2672019-08-16 14:51:55 +01001341
Nandana Dutt5fc32012020-06-25 10:55:52 +01001342 int status = fuse->mp->IsOpendirAllowed(path, ctx->uid, /* forWrite */ false);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001343 if (status) {
1344 fuse_reply_err(req, status);
1345 return;
1346 }
1347
1348 DIR* dir = opendir(path.c_str());
1349 if (!dir) {
shafik1e3a2672019-08-16 14:51:55 +01001350 fuse_reply_err(req, errno);
1351 return;
1352 }
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001353
Narayan Kamathaef84a12020-01-02 15:20:13 +00001354 dirhandle* h = new dirhandle(dir);
1355 node->AddDirHandle(h);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001356
shafik1e3a2672019-08-16 14:51:55 +01001357 fi->fh = ptr_to_id(h);
1358 fuse_reply_open(req, fi);
1359}
1360
1361#define READDIR_BUF 8192LU
1362
1363static void do_readdir_common(fuse_req_t req,
1364 fuse_ino_t ino,
1365 size_t size,
1366 off_t off,
1367 struct fuse_file_info* fi,
1368 bool plus) {
1369 struct fuse* fuse = get_fuse(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001370 dirhandle* h = reinterpret_cast<dirhandle*>(fi->fh);
Jeff Sharkey7469b982019-08-28 16:51:02 -06001371 size_t len = std::min<size_t>(size, READDIR_BUF);
shafik1e3a2672019-08-16 14:51:55 +01001372 char buf[READDIR_BUF];
1373 size_t used = 0;
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001374 std::shared_ptr<DirectoryEntry> de;
1375
shafik1e3a2672019-08-16 14:51:55 +01001376 struct fuse_entry_param e;
Sahana Rao6f9ea982019-09-20 12:21:33 +01001377 size_t entry_size = 0;
shafik1e3a2672019-08-16 14:51:55 +01001378
Ricky Wai44670762020-05-01 11:25:28 +01001379 node* node = fuse->FromInode(ino);
Ricky Waif40c4022020-04-15 19:00:06 +01001380 if (!node) {
1381 fuse_reply_err(req, ENOENT);
1382 return;
1383 }
Narayan Kamathaef84a12020-01-02 15:20:13 +00001384 const string path = node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +01001385 if (!is_app_accessible_path(fuse->mp, path, req->ctx.uid)) {
1386 fuse_reply_err(req, ENOENT);
1387 return;
1388 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001389
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001390 TRACE_NODE(node, req);
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001391 // Get all directory entries from MediaProvider on first readdir() call of
1392 // directory handle. h->next_off = 0 indicates that current readdir() call
1393 // is first readdir() call for the directory handle, Avoid multiple JNI calls
1394 // for single directory handle.
1395 if (h->next_off == 0) {
Sahana Rao71693442019-11-13 13:48:07 +00001396 h->de = fuse->mp->GetDirectoryEntries(req->ctx.uid, path, h->d);
shafik1e3a2672019-08-16 14:51:55 +01001397 }
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001398 // If the last entry in the previous readdir() call was rejected due to
1399 // buffer capacity constraints, update directory offset to start from
1400 // previously rejected entry. Directory offset can also change if there was
Sahana Rao71693442019-11-13 13:48:07 +00001401 // a seekdir() on the given directory handle.
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001402 if (off != h->next_off) {
1403 h->next_off = off;
1404 }
1405 const int num_directory_entries = h->de.size();
Sahana Rao71693442019-11-13 13:48:07 +00001406 // Check for errors. Any error/exception occurred while obtaining directory
1407 // entries will be indicated by marking first directory entry name as empty
1408 // string. In the erroneous case corresponding d_type will hold error number.
Sahana Rao53bd1f62019-12-27 20:18:39 +00001409 if (num_directory_entries && h->de[0]->d_name.empty()) {
1410 fuse_reply_err(req, h->de[0]->d_type);
1411 return;
1412 }
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001413
Sahana Rao53bd1f62019-12-27 20:18:39 +00001414 while (h->next_off < num_directory_entries) {
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001415 de = h->de[h->next_off];
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001416 entry_size = 0;
1417 h->next_off++;
shafik1e3a2672019-08-16 14:51:55 +01001418 if (plus) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001419 int error_code = 0;
1420 if (do_lookup(req, ino, de->d_name.c_str(), &e, &error_code)) {
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001421 entry_size = fuse_add_direntry_plus(req, buf + used, len - used, de->d_name.c_str(),
1422 &e, h->next_off);
Sahana Rao8a588e72019-12-06 11:32:56 +00001423 } else {
Sahana Rao8d8dbb42019-12-18 12:57:02 +00001424 // Ignore lookup errors on
1425 // 1. non-existing files returned from MediaProvider database.
1426 // 2. path that doesn't match FuseDaemon UID and calling uid.
Nikita Ioffe33d16ee2020-06-17 13:24:44 +01001427 if (error_code == ENOENT || error_code == EPERM || error_code == EACCES) continue;
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001428 fuse_reply_err(req, error_code);
shafik1e3a2672019-08-16 14:51:55 +01001429 return;
1430 }
1431 } else {
Zim1100f342020-05-15 16:13:00 +01001432 // This should never happen because we have readdir_plus enabled without adaptive
1433 // readdir_plus, FUSE_CAP_READDIRPLUS_AUTO
1434 LOG(WARNING) << "Handling plain readdir for " << de->d_name << ". Invalid d_ino";
shafik1e3a2672019-08-16 14:51:55 +01001435 e.attr.st_ino = FUSE_UNKNOWN_INO;
Zim1100f342020-05-15 16:13:00 +01001436 e.attr.st_mode = de->d_type << 12;
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001437 entry_size = fuse_add_direntry(req, buf + used, len - used, de->d_name.c_str(), &e.attr,
1438 h->next_off);
shafik1e3a2672019-08-16 14:51:55 +01001439 }
Sahana Rao6f9ea982019-09-20 12:21:33 +01001440 // If buffer in fuse_add_direntry[_plus] is not large enough then
1441 // the entry is not added to buffer but the size of the entry is still
1442 // returned. Check available buffer size + returned entry size is less
1443 // than actual buffer size to confirm entry is added to buffer.
Sahana Rao43927f02019-12-10 22:59:01 +00001444 if (used + entry_size > len) {
1445 // When an entry is rejected, lookup called by readdir_plus will not be tracked by
1446 // kernel. Call forget on the rejected node to decrement the reference count.
Narayan Kamathd6219842019-12-27 17:44:35 +00001447 if (plus) {
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001448 do_forget(req, fuse, e.ino, 1);
Narayan Kamathd6219842019-12-27 17:44:35 +00001449 }
Sahana Rao43927f02019-12-10 22:59:01 +00001450 break;
1451 }
Sahana Rao6f9ea982019-09-20 12:21:33 +01001452 used += entry_size;
shafik1e3a2672019-08-16 14:51:55 +01001453 }
Sahana Rao53bd1f62019-12-27 20:18:39 +00001454 fuse_reply_buf(req, buf, used);
shafik1e3a2672019-08-16 14:51:55 +01001455}
1456
1457static void pf_readdir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off,
1458 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001459 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001460 do_readdir_common(req, ino, size, off, fi, false);
1461}
1462
1463static void pf_readdirplus(fuse_req_t req,
1464 fuse_ino_t ino,
1465 size_t size,
1466 off_t off,
1467 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001468 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001469 do_readdir_common(req, ino, size, off, fi, true);
1470}
1471
1472static void pf_releasedir(fuse_req_t req,
1473 fuse_ino_t ino,
1474 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001475 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001476 struct fuse* fuse = get_fuse(req);
shafik1e3a2672019-08-16 14:51:55 +01001477
Ricky Wai44670762020-05-01 11:25:28 +01001478 node* node = fuse->FromInode(ino);
1479
Narayan Kamathaef84a12020-01-02 15:20:13 +00001480 dirhandle* h = reinterpret_cast<dirhandle*>(fi->fh);
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001481 TRACE_NODE(node, req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001482 if (node) {
1483 node->DestroyDirHandle(h);
Zimedbe69e2019-12-13 18:49:36 +00001484 }
Zimedbe69e2019-12-13 18:49:36 +00001485
shafik1e3a2672019-08-16 14:51:55 +01001486 fuse_reply_err(req, 0);
1487}
1488
1489static void pf_statfs(fuse_req_t req, fuse_ino_t ino) {
Zimec8d5722019-12-05 07:26:13 +00001490 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001491 struct statvfs st;
1492 struct fuse* fuse = get_fuse(req);
1493
Narayan Kamathaef84a12020-01-02 15:20:13 +00001494 if (statvfs(fuse->root->GetName().c_str(), &st))
shafik1e3a2672019-08-16 14:51:55 +01001495 fuse_reply_err(req, errno);
1496 else
1497 fuse_reply_statfs(req, &st);
1498}
1499/*
1500static void pf_setxattr(fuse_req_t req, fuse_ino_t ino, const char* name,
1501 const char* value, size_t size, int flags)
1502{
1503 cout << "TODO:" << __func__;
1504}
1505
1506static void pf_getxattr(fuse_req_t req, fuse_ino_t ino, const char* name,
1507 size_t size)
1508{
1509 cout << "TODO:" << __func__;
1510}
1511
1512static void pf_listxattr(fuse_req_t req, fuse_ino_t ino, size_t size)
1513{
1514 cout << "TODO:" << __func__;
1515}
1516
1517static void pf_removexattr(fuse_req_t req, fuse_ino_t ino, const char* name)
1518{
1519 cout << "TODO:" << __func__;
Zima9fcd552019-08-29 15:17:04 +01001520}*/
1521
1522static void pf_access(fuse_req_t req, fuse_ino_t ino, int mask) {
Zimec8d5722019-12-05 07:26:13 +00001523 ATRACE_CALL();
Zima9fcd552019-08-29 15:17:04 +01001524 struct fuse* fuse = get_fuse(req);
Zima9fcd552019-08-29 15:17:04 +01001525
Ricky Wai44670762020-05-01 11:25:28 +01001526 node* node = fuse->FromInode(ino);
Ricky Waif40c4022020-04-15 19:00:06 +01001527 if (!node) {
1528 fuse_reply_err(req, ENOENT);
1529 return;
1530 }
Narayan Kamathaef84a12020-01-02 15:20:13 +00001531 const string path = node->BuildPath();
Martijn Coenen19c1a872020-07-30 19:59:50 +02001532 if (path != "/storage/emulated" && !is_app_accessible_path(fuse->mp, path, req->ctx.uid)) {
Ricky Wai44670762020-05-01 11:25:28 +01001533 fuse_reply_err(req, ENOENT);
1534 return;
1535 }
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001536 TRACE_NODE(node, req);
Zima9fcd552019-08-29 15:17:04 +01001537
Nandana Dutt17555052020-04-09 16:19:57 +01001538 // exists() checks are always allowed.
1539 if (mask == F_OK) {
1540 int res = access(path.c_str(), F_OK);
1541 fuse_reply_err(req, res ? errno : 0);
1542 return;
1543 }
1544 struct stat stat;
1545 if (lstat(path.c_str(), &stat)) {
1546 // File doesn't exist
1547 fuse_reply_err(req, ENOENT);
1548 return;
1549 }
1550
1551 // For read and write permission checks we go to MediaProvider.
1552 int status = 0;
Nandana Dutt5fc32012020-06-25 10:55:52 +01001553 bool for_write = mask & W_OK;
Nandana Dutt17555052020-04-09 16:19:57 +01001554 bool is_directory = S_ISDIR(stat.st_mode);
1555 if (is_directory) {
Martijn Coenen19c1a872020-07-30 19:59:50 +02001556 if (path == "/storage/emulated" && mask == X_OK) {
1557 // Special case for this path: apps should be allowed to enter it,
1558 // but not list directory contents (which would be user numbers).
1559 int res = access(path.c_str(), X_OK);
1560 fuse_reply_err(req, res ? errno : 0);
1561 return;
1562 }
Nandana Dutt5fc32012020-06-25 10:55:52 +01001563 status = fuse->mp->IsOpendirAllowed(path, req->ctx.uid, for_write);
Nandana Dutt17555052020-04-09 16:19:57 +01001564 } else {
1565 if (mask & X_OK) {
1566 // Fuse is mounted with MS_NOEXEC.
1567 fuse_reply_err(req, EACCES);
1568 return;
1569 }
1570
Ricky Wai44670762020-05-01 11:25:28 +01001571 status = fuse->mp->IsOpenAllowed(path, req->ctx.uid, for_write);
Nandana Dutt17555052020-04-09 16:19:57 +01001572 }
1573
1574 fuse_reply_err(req, status);
shafik1e3a2672019-08-16 14:51:55 +01001575}
Zima9fcd552019-08-29 15:17:04 +01001576
shafik1e3a2672019-08-16 14:51:55 +01001577static void pf_create(fuse_req_t req,
1578 fuse_ino_t parent,
1579 const char* name,
1580 mode_t mode,
1581 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001582 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001583 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +01001584 node* parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +01001585 if (!parent_node) {
1586 fuse_reply_err(req, ENOENT);
1587 return;
1588 }
Narayan Kamathaef84a12020-01-02 15:20:13 +00001589 const string parent_path = parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +01001590 if (!is_app_accessible_path(fuse->mp, parent_path, req->ctx.uid)) {
1591 fuse_reply_err(req, ENOENT);
1592 return;
1593 }
shafik1e3a2672019-08-16 14:51:55 +01001594
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001595 TRACE_NODE(parent_node, req);
shafik1e3a2672019-08-16 14:51:55 +01001596
Narayan Kamathaef84a12020-01-02 15:20:13 +00001597 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +01001598
Ricky Wai44670762020-05-01 11:25:28 +01001599 int mp_return_code = fuse->mp->InsertFile(child_path.c_str(), req->ctx.uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001600 if (mp_return_code) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001601 fuse_reply_err(req, mp_return_code);
shafik1e3a2672019-08-16 14:51:55 +01001602 return;
1603 }
1604
Martijn Coenen2d7f1be2020-02-15 07:44:12 +01001605 // With the writeback cache enabled, FUSE may generate READ requests even for files that
1606 // were opened O_WRONLY; so make sure we open it O_RDWR instead.
1607 int open_flags = fi->flags;
1608 if (open_flags & O_WRONLY) {
1609 open_flags &= ~O_WRONLY;
1610 open_flags |= O_RDWR;
1611 }
1612
Zim1b14f2f2020-07-03 07:05:53 +01001613 if (open_flags & O_APPEND) {
1614 open_flags &= ~O_APPEND;
1615 }
1616
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001617 mode = (mode & (~0777)) | 0664;
Martijn Coenen2d7f1be2020-02-15 07:44:12 +01001618 int fd = open(child_path.c_str(), open_flags, mode);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001619 if (fd < 0) {
1620 int error_code = errno;
1621 // We've already inserted the file into the MP database before the
1622 // failed open(), so that needs to be rolled back here.
Ricky Wai44670762020-05-01 11:25:28 +01001623 fuse->mp->DeleteFile(child_path.c_str(), req->ctx.uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001624 fuse_reply_err(req, error_code);
1625 return;
1626 }
1627
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001628 int error_code = 0;
Narayan Kamathaef84a12020-01-02 15:20:13 +00001629 struct fuse_entry_param e;
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001630 node* node = make_node_entry(req, parent_node, name, child_path, &e, &error_code);
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001631 TRACE_NODE(node, req);
Zimc05c60f2020-03-05 13:02:26 +00001632 if (!node) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001633 CHECK(error_code != 0);
1634 fuse_reply_err(req, error_code);
Zimc05c60f2020-03-05 13:02:26 +00001635 return;
shafik1e3a2672019-08-16 14:51:55 +01001636 }
Zimc05c60f2020-03-05 13:02:26 +00001637
Martijn Coenenaf2d34d2020-06-19 12:52:20 +02001638 // Let MediaProvider know we've created a new file
1639 fuse->mp->OnFileCreated(child_path);
1640
Zimc05c60f2020-03-05 13:02:26 +00001641 // TODO(b/147274248): Assume there will be no EXIF to redact.
1642 // This prevents crashing during reads but can be a security hole if a malicious app opens an fd
1643 // to the file before all the EXIF content is written. We could special case reads before the
1644 // first close after a file has just been created.
Zim329ba2c2020-09-16 14:23:26 +01001645 int keep_cache = 1;
Zim9aa6f542020-10-19 15:39:33 +01001646 handle* h = create_handle_for_node(fuse, child_path, fd, req->ctx.uid, node,
1647 new RedactionInfo(), &keep_cache);
Zimc05c60f2020-03-05 13:02:26 +00001648 fi->fh = ptr_to_id(h);
Zim329ba2c2020-09-16 14:23:26 +01001649 fi->keep_cache = keep_cache;
Zimc05c60f2020-03-05 13:02:26 +00001650 fi->direct_io = !h->cached;
1651 fuse_reply_create(req, &e, fi);
shafik1e3a2672019-08-16 14:51:55 +01001652}
1653/*
1654static void pf_getlk(fuse_req_t req, fuse_ino_t ino,
1655 struct fuse_file_info* fi, struct flock* lock)
1656{
1657 cout << "TODO:" << __func__;
1658}
1659
1660static void pf_setlk(fuse_req_t req, fuse_ino_t ino,
1661 struct fuse_file_info* fi,
1662 struct flock* lock, int sleep)
1663{
1664 cout << "TODO:" << __func__;
1665}
1666
1667static void pf_bmap(fuse_req_t req, fuse_ino_t ino, size_t blocksize,
1668 uint64_t idx)
1669{
1670 cout << "TODO:" << __func__;
1671}
1672
1673static void pf_ioctl(fuse_req_t req, fuse_ino_t ino, unsigned int cmd,
1674 void* arg, struct fuse_file_info* fi, unsigned flags,
1675 const void* in_buf, size_t in_bufsz, size_t out_bufsz)
1676{
1677 cout << "TODO:" << __func__;
1678}
1679
1680static void pf_poll(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi,
1681 struct fuse_pollhandle* ph)
1682{
1683 cout << "TODO:" << __func__;
1684}
1685
1686static void pf_retrieve_reply(fuse_req_t req, void* cookie, fuse_ino_t ino,
1687 off_t offset, struct fuse_bufvec* bufv)
1688{
1689 cout << "TODO:" << __func__;
1690}
1691
1692static void pf_flock(fuse_req_t req, fuse_ino_t ino,
1693 struct fuse_file_info* fi, int op)
1694{
1695 cout << "TODO:" << __func__;
1696}
1697
1698static void pf_fallocate(fuse_req_t req, fuse_ino_t ino, int mode,
1699 off_t offset, off_t length, struct fuse_file_info* fi)
1700{
1701 cout << "TODO:" << __func__;
1702}
1703*/
1704
1705static struct fuse_lowlevel_ops ops{
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00001706 .init = pf_init, .destroy = pf_destroy, .lookup = pf_lookup, .forget = pf_forget,
1707 .getattr = pf_getattr, .setattr = pf_setattr, .canonical_path = pf_canonical_path,
1708 .mknod = pf_mknod, .mkdir = pf_mkdir, .unlink = pf_unlink, .rmdir = pf_rmdir,
shafik8b57cd52019-09-06 10:51:29 +01001709 /*.symlink = pf_symlink,*/
1710 .rename = pf_rename,
1711 /*.link = pf_link,*/
1712 .open = pf_open, .read = pf_read,
1713 /*.write = pf_write,*/
Alessio Balsini68c295d2020-07-23 14:32:01 +01001714 /*.flush = pf_flush,*/
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00001715 .release = pf_release, .fsync = pf_fsync, .opendir = pf_opendir, .readdir = pf_readdir,
1716 .releasedir = pf_releasedir, .fsyncdir = pf_fsyncdir, .statfs = pf_statfs,
shafik8b57cd52019-09-06 10:51:29 +01001717 /*.setxattr = pf_setxattr,
1718 .getxattr = pf_getxattr,
1719 .listxattr = pf_listxattr,
1720 .removexattr = pf_removexattr,*/
1721 .access = pf_access, .create = pf_create,
1722 /*.getlk = pf_getlk,
1723 .setlk = pf_setlk,
1724 .bmap = pf_bmap,
1725 .ioctl = pf_ioctl,
Nick Desaulniers17714b82019-11-05 09:44:35 -08001726 .poll = pf_poll,*/
1727 .write_buf = pf_write_buf,
1728 /*.retrieve_reply = pf_retrieve_reply,*/
1729 .forget_multi = pf_forget_multi,
shafik8b57cd52019-09-06 10:51:29 +01001730 /*.flock = pf_flock,
1731 .fallocate = pf_fallocate,*/
Nick Desaulniers17714b82019-11-05 09:44:35 -08001732 .readdirplus = pf_readdirplus,
1733 /*.copy_file_range = pf_copy_file_range,*/
shafik1e3a2672019-08-16 14:51:55 +01001734};
1735
1736static struct fuse_loop_config config = {
Zim549f9da2020-02-09 13:54:22 +00001737 .clone_fd = 1,
shafik1e3a2672019-08-16 14:51:55 +01001738 .max_idle_threads = 10,
1739};
1740
Zimb353eb42019-12-17 15:29:48 +00001741static std::unordered_map<enum fuse_log_level, enum android_LogPriority> fuse_to_android_loglevel({
1742 {FUSE_LOG_EMERG, ANDROID_LOG_FATAL},
1743 {FUSE_LOG_ALERT, ANDROID_LOG_ERROR},
1744 {FUSE_LOG_CRIT, ANDROID_LOG_ERROR},
1745 {FUSE_LOG_ERR, ANDROID_LOG_ERROR},
1746 {FUSE_LOG_WARNING, ANDROID_LOG_WARN},
1747 {FUSE_LOG_NOTICE, ANDROID_LOG_INFO},
1748 {FUSE_LOG_INFO, ANDROID_LOG_DEBUG},
1749 {FUSE_LOG_DEBUG, ANDROID_LOG_VERBOSE},
1750 });
Zim724b8ca2019-11-09 09:37:24 +00001751
1752static void fuse_logger(enum fuse_log_level level, const char* fmt, va_list ap) {
Zim357e3072020-01-15 10:50:01 +00001753 __android_log_vprint(fuse_to_android_loglevel.at(level), LIBFUSE_LOG_TAG, fmt, ap);
Zim724b8ca2019-11-09 09:37:24 +00001754}
1755
Zimedbe69e2019-12-13 18:49:36 +00001756bool FuseDaemon::ShouldOpenWithFuse(int fd, bool for_read, const std::string& path) {
Zimedbe69e2019-12-13 18:49:36 +00001757 bool use_fuse = false;
1758
1759 if (active.load(std::memory_order_acquire)) {
Zimdc78f532020-03-04 18:46:06 +00001760 std::lock_guard<std::recursive_mutex> guard(fuse->lock);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001761 const node* node = node::LookupAbsolutePath(fuse->root, path);
Zimedbe69e2019-12-13 18:49:36 +00001762 if (node && node->HasCachedHandle()) {
Zimedbe69e2019-12-13 18:49:36 +00001763 use_fuse = true;
1764 } else {
1765 // If we are unable to set a lock, we should use fuse since we can't track
1766 // when all fd references (including dups) are closed. This can happen when
1767 // we try to set a write lock twice on the same file
1768 use_fuse = set_file_lock(fd, for_read, path);
Zimedbe69e2019-12-13 18:49:36 +00001769 }
Zimedbe69e2019-12-13 18:49:36 +00001770 } else {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00001771 LOG(WARNING) << "FUSE daemon is inactive. Cannot open file with FUSE";
Zimedbe69e2019-12-13 18:49:36 +00001772 }
1773
1774 return use_fuse;
1775}
1776
Zima76c3492020-02-19 01:23:26 +00001777void FuseDaemon::InvalidateFuseDentryCache(const std::string& path) {
Zim4d3fa272020-03-06 13:45:19 +00001778 LOG(VERBOSE) << "Invalidating FUSE dentry cache";
Zima76c3492020-02-19 01:23:26 +00001779 if (active.load(std::memory_order_acquire)) {
Zima55568e2020-04-24 22:40:34 +01001780 string name;
1781 fuse_ino_t parent;
Zim33aea102020-06-19 15:49:47 +01001782 fuse_ino_t child;
Zima55568e2020-04-24 22:40:34 +01001783 {
1784 std::lock_guard<std::recursive_mutex> guard(fuse->lock);
1785 const node* node = node::LookupAbsolutePath(fuse->root, path);
1786 if (node) {
1787 name = node->GetName();
Zim33aea102020-06-19 15:49:47 +01001788 child = fuse->ToInode(const_cast<class node*>(node));
Zima55568e2020-04-24 22:40:34 +01001789 parent = fuse->ToInode(node->GetParent());
Zima76c3492020-02-19 01:23:26 +00001790 }
1791 }
Zima55568e2020-04-24 22:40:34 +01001792
Zim33aea102020-06-19 15:49:47 +01001793 if (!name.empty()) {
1794 fuse_inval(fuse->se, parent, child, name, path);
Zima55568e2020-04-24 22:40:34 +01001795 }
Zima76c3492020-02-19 01:23:26 +00001796 } else {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00001797 LOG(WARNING) << "FUSE daemon is inactive. Cannot invalidate dentry";
Zima76c3492020-02-19 01:23:26 +00001798 }
1799}
1800
Zimedbe69e2019-12-13 18:49:36 +00001801FuseDaemon::FuseDaemon(JNIEnv* env, jobject mediaProvider) : mp(env, mediaProvider),
1802 active(false), fuse(nullptr) {}
shafik1e3a2672019-08-16 14:51:55 +01001803
Zimd0435b22020-03-05 13:52:51 +00001804bool FuseDaemon::IsStarted() const {
1805 return active.load(std::memory_order_acquire);
1806}
1807
Martijn Coenen083eb692020-04-24 09:39:58 +02001808void FuseDaemon::Start(android::base::unique_fd fd, const std::string& path) {
Nikita Ioffec33ee1a2020-06-23 21:31:20 +01001809 android::base::SetDefaultTag(LOG_TAG);
1810
shafik1e3a2672019-08-16 14:51:55 +01001811 struct fuse_args args;
1812 struct fuse_cmdline_opts opts;
shafik1e3a2672019-08-16 14:51:55 +01001813
1814 struct stat stat;
shafik1e3a2672019-08-16 14:51:55 +01001815
Zim7c8712d2019-10-03 21:01:26 +01001816 if (lstat(path.c_str(), &stat)) {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00001817 PLOG(ERROR) << "ERROR: failed to stat source " << path;
Zim3e45d9b2019-08-19 21:14:14 +01001818 return;
1819 }
shafik1e3a2672019-08-16 14:51:55 +01001820
Zim3e45d9b2019-08-19 21:14:14 +01001821 if (!S_ISDIR(stat.st_mode)) {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00001822 PLOG(ERROR) << "ERROR: source is not a directory";
Zim3e45d9b2019-08-19 21:14:14 +01001823 return;
1824 }
shafik1e3a2672019-08-16 14:51:55 +01001825
1826 args = FUSE_ARGS_INIT(0, nullptr);
Zim7c8712d2019-10-03 21:01:26 +01001827 if (fuse_opt_add_arg(&args, path.c_str()) || fuse_opt_add_arg(&args, "-odebug") ||
1828 fuse_opt_add_arg(&args, ("-omax_read=" + std::to_string(MAX_READ_SIZE)).c_str())) {
shafik458d1102019-09-06 18:21:36 +01001829 LOG(ERROR) << "ERROR: failed to set options";
shafik1e3a2672019-08-16 14:51:55 +01001830 return;
1831 }
1832
Narayan Kamathaef84a12020-01-02 15:20:13 +00001833 struct fuse fuse_default(path);
shafikc3f62672019-08-30 11:15:48 +01001834 fuse_default.mp = &mp;
Zimedbe69e2019-12-13 18:49:36 +00001835 // fuse_default is stack allocated, but it's safe to save it as an instance variable because
1836 // this method blocks and FuseDaemon#active tells if we are currently blocking
1837 fuse = &fuse_default;
shafikc3f62672019-08-30 11:15:48 +01001838
shafikb334a612019-09-30 20:38:16 +01001839 // Used by pf_read: redacted ranges are represented by zeroized ranges of bytes,
1840 // so we mmap the maximum length of redacted ranges in the beginning and save memory allocations
1841 // on each read.
1842 fuse_default.zero_addr = static_cast<char*>(mmap(
1843 NULL, MAX_READ_SIZE, PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, /*fd*/ -1, /*off*/ 0));
1844 if (fuse_default.zero_addr == MAP_FAILED) {
1845 LOG(FATAL) << "mmap failed - could not start fuse! errno = " << errno;
1846 }
1847
Zim724b8ca2019-11-09 09:37:24 +00001848 // Custom logging for libfuse
Zim0594b032020-04-29 11:43:43 +01001849 if (android::base::GetBoolProperty("persist.sys.fuse.log", false)) {
1850 fuse_set_log_func(fuse_logger);
1851 }
Zim724b8ca2019-11-09 09:37:24 +00001852
shafik1e3a2672019-08-16 14:51:55 +01001853 struct fuse_session
1854 * se = fuse_session_new(&args, &ops, sizeof(ops), &fuse_default);
Zim7e0d3142019-10-17 21:06:12 +01001855 if (!se) {
1856 PLOG(ERROR) << "Failed to create session ";
1857 return;
1858 }
Zima76c3492020-02-19 01:23:26 +00001859 fuse_default.se = se;
Zimd0435b22020-03-05 13:52:51 +00001860 fuse_default.active = &active;
Martijn Coenen3ec6c062020-04-28 19:09:53 +02001861 se->fd = fd.release(); // libfuse owns the FD now
Zim7c8712d2019-10-03 21:01:26 +01001862 se->mountpoint = strdup(path.c_str());
Zim3e45d9b2019-08-19 21:14:14 +01001863
1864 // Single thread. Useful for debugging
1865 // fuse_session_loop(se);
1866 // Multi-threaded
Zim7e0d3142019-10-17 21:06:12 +01001867 LOG(INFO) << "Starting fuse...";
shafik1e3a2672019-08-16 14:51:55 +01001868 fuse_session_loop_mt(se, &config);
Zimd0435b22020-03-05 13:52:51 +00001869 fuse->active->store(false, std::memory_order_release);
Zim7e0d3142019-10-17 21:06:12 +01001870 LOG(INFO) << "Ending fuse...";
Zim3e45d9b2019-08-19 21:14:14 +01001871
Zim7c8712d2019-10-03 21:01:26 +01001872 if (munmap(fuse_default.zero_addr, MAX_READ_SIZE)) {
1873 PLOG(ERROR) << "munmap failed!";
shafikb334a612019-09-30 20:38:16 +01001874 }
1875
Zim7e0d3142019-10-17 21:06:12 +01001876 fuse_opt_free_args(&args);
1877 fuse_session_destroy(se);
1878 LOG(INFO) << "Ended fuse";
1879 return;
shafik1e3a2672019-08-16 14:51:55 +01001880}
1881} //namespace fuse
shafik8b57cd52019-09-06 10:51:29 +01001882} // namespace mediaprovider