blob: 58d3f715a57062ceaac57dd05d52c8827e4c3642 [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>
Zim724b8ca2019-11-09 09:37:24 +000022#include <android/log.h>
Zimec8d5722019-12-05 07:26:13 +000023#include <android/trace.h>
shafik1e3a2672019-08-16 14:51:55 +010024#include <ctype.h>
25#include <dirent.h>
26#include <errno.h>
27#include <fcntl.h>
shafik8b57cd52019-09-06 10:51:29 +010028#include <fuse_i.h>
Zim724b8ca2019-11-09 09:37:24 +000029#include <fuse_log.h>
shafik8b57cd52019-09-06 10:51:29 +010030#include <fuse_lowlevel.h>
shafik1e3a2672019-08-16 14:51:55 +010031#include <inttypes.h>
32#include <limits.h>
33#include <linux/fuse.h>
shafik1e3a2672019-08-16 14:51:55 +010034#include <stdbool.h>
35#include <stdio.h>
36#include <stdlib.h>
37#include <string.h>
38#include <sys/inotify.h>
shafikb334a612019-09-30 20:38:16 +010039#include <sys/mman.h>
shafik1e3a2672019-08-16 14:51:55 +010040#include <sys/mount.h>
41#include <sys/param.h>
42#include <sys/resource.h>
43#include <sys/stat.h>
44#include <sys/statfs.h>
45#include <sys/statvfs.h>
46#include <sys/time.h>
47#include <sys/types.h>
48#include <sys/uio.h>
49#include <unistd.h>
shafik1e3a2672019-08-16 14:51:55 +010050
shafik8b57cd52019-09-06 10:51:29 +010051#include <iostream>
Narayan Kamath8d76d0c2019-12-31 13:14:50 +000052#include <list>
Paul Lawrence7e4a5a82019-09-27 21:39:49 +020053#include <map>
Narayan Kamath768bea32019-12-27 16:23:23 +000054#include <mutex>
Paul Lawrence7e4a5a82019-09-27 21:39:49 +020055#include <queue>
Zim859db932019-12-13 00:09:17 +000056#include <regex>
Paul Lawrence7e4a5a82019-09-27 21:39:49 +020057#include <thread>
Zim724b8ca2019-11-09 09:37:24 +000058#include <unordered_map>
Narayan Kamath92bf67b2020-01-03 17:49:09 +000059#include <unordered_set>
shafikc3f62672019-08-30 11:15:48 +010060#include <vector>
shafik1e3a2672019-08-16 14:51:55 +010061
shafikc3f62672019-08-30 11:15:48 +010062#include "MediaProviderWrapper.h"
Sahana Raoa82bd6a2019-10-10 18:10:37 +010063#include "libfuse_jni/ReaddirHelper.h"
shafikc3f62672019-08-30 11:15:48 +010064#include "libfuse_jni/RedactionInfo.h"
Narayan Kamathaef84a12020-01-02 15:20:13 +000065#include "node-inl.h"
shafikc3f62672019-08-30 11:15:48 +010066
Sahana Raoa82bd6a2019-10-10 18:10:37 +010067using mediaprovider::fuse::DirectoryEntry;
Narayan Kamathaef84a12020-01-02 15:20:13 +000068using mediaprovider::fuse::dirhandle;
69using mediaprovider::fuse::handle;
70using mediaprovider::fuse::node;
shafikc3f62672019-08-30 11:15:48 +010071using mediaprovider::fuse::RedactionInfo;
Narayan Kamath8d76d0c2019-12-31 13:14:50 +000072using std::list;
Jeff Sharkey7469b982019-08-28 16:51:02 -060073using std::string;
shafikc3f62672019-08-30 11:15:48 +010074using std::vector;
shafik1e3a2672019-08-16 14:51:55 +010075
Narayan Kamath88203dc2019-08-30 17:19:38 +010076// logging macros to avoid duplication.
Cody Schuffelen338bd1a2020-02-21 17:40:56 +000077#define TRACE LOG(DEBUG)
78#define TRACE_VERBOSE LOG(VERBOSE)
79#define TRACE_FUSE(__fuse) TRACE << "[" << __fuse->path << "] "
80#define TRACE_FUSE_VERBOSE(__fuse) TRACE_VERBOSE << "[" << __fuse->path << "] "
shafik1e3a2672019-08-16 14:51:55 +010081
Zimec8d5722019-12-05 07:26:13 +000082#define ATRACE_NAME(name) ScopedTrace ___tracer(name)
83#define ATRACE_CALL() ATRACE_NAME(__FUNCTION__)
84
85class ScopedTrace {
86 public:
Narayan Kamath64b44352019-12-27 17:07:50 +000087 explicit inline ScopedTrace(const char *name) {
Zimec8d5722019-12-05 07:26:13 +000088 ATrace_beginSection(name);
89 }
90
91 inline ~ScopedTrace() {
92 ATrace_endSection();
93 }
94};
95
shafik1e3a2672019-08-16 14:51:55 +010096#define FUSE_UNKNOWN_INO 0xffffffff
97
shafikb334a612019-09-30 20:38:16 +010098constexpr size_t MAX_READ_SIZE = 128 * 1024;
Zim859db932019-12-13 00:09:17 +000099// Stolen from: UserHandle#getUserId
100constexpr int PER_USER_RANGE = 100000;
Zim8b2b6f22020-01-22 13:53:59 +0000101// Cache inode attributes for a 'short' time so that performance is decent and last modified time
102// stamps are not too stale
103constexpr double DEFAULT_ATTR_TIMEOUT_SECONDS = 10;
104// Ensure the VFS does not cache dentries, if it caches, the following scenario could occur:
105// 1. Process A has access to file A and does a lookup
106// 2. Process B does not have access to file A and does a lookup
107// (2) will succeed because the lookup request will not be sent from kernel to the FUSE daemon
108// and the kernel will respond from cache. Even if this by itself is not a security risk
109// because subsequent FUSE requests will fail if B does not have access to the resource.
110// It does cause indeterministic behavior because whether (2) succeeds or not depends on if
111// (1) occurred.
112// We prevent this caching by setting the entry_timeout value to 0.
113constexpr double DEFAULT_ENTRY_TIMEOUT_SECONDS = 0;
shafikb334a612019-09-30 20:38:16 +0100114
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200115/*
116 * In order to avoid double caching with fuse, call fadvise on the file handles
117 * in the underlying file system. However, if this is done on every read/write,
118 * the fadvises cause a very significant slowdown in tests (specifically fio
119 * seq_write). So call fadvise on the file handles with the most reads/writes
120 * only after a threshold is passed.
121 */
122class FAdviser {
123 public:
124 FAdviser() : thread_(MessageLoop, this), total_size_(0) {}
125
126 ~FAdviser() {
127 SendMessage(Message::quit);
128 thread_.join();
129 }
130
131 void Record(int fd, size_t size) { SendMessage(Message::record, fd, size); }
132
133 void Close(int fd) { SendMessage(Message::close, fd); }
134
135 private:
136 std::thread thread_;
137
138 struct Message {
139 enum Type { record, close, quit };
140 Type type;
141 int fd;
142 size_t size;
143 };
144
145 void RecordImpl(int fd, size_t size) {
146 total_size_ += size;
147
148 // Find or create record in files_
149 // Remove record from sizes_ if it exists, adjusting size appropriately
150 auto file = files_.find(fd);
151 if (file != files_.end()) {
152 auto old_size = file->second;
153 size += old_size->first;
154 sizes_.erase(old_size);
155 } else {
156 file = files_.insert(Files::value_type(fd, sizes_.end())).first;
157 }
158
159 // Now (re) insert record in sizes_
160 auto new_size = sizes_.insert(Sizes::value_type(size, fd));
161 file->second = new_size;
162
163 if (total_size_ < threshold_) return;
164
165 LOG(INFO) << "Threshold exceeded - fadvising " << total_size_;
166 while (!sizes_.empty() && total_size_ > target_) {
167 auto size = --sizes_.end();
168 total_size_ -= size->first;
169 posix_fadvise(size->second, 0, 0, POSIX_FADV_DONTNEED);
170 files_.erase(size->second);
171 sizes_.erase(size);
172 }
173 LOG(INFO) << "Threshold now " << total_size_;
174 }
175
176 void CloseImpl(int fd) {
177 auto file = files_.find(fd);
178 if (file == files_.end()) return;
179
180 total_size_ -= file->second->first;
181 sizes_.erase(file->second);
182 files_.erase(file);
183 }
184
185 void MessageLoopImpl() {
186 while (1) {
187 Message message;
188
189 {
190 std::unique_lock<std::mutex> lock(mutex_);
191 cv_.wait(lock, [this] { return !queue_.empty(); });
192 message = queue_.front();
193 queue_.pop();
194 }
195
196 switch (message.type) {
197 case Message::record:
198 RecordImpl(message.fd, message.size);
199 break;
200
201 case Message::close:
202 CloseImpl(message.fd);
203 break;
204
205 case Message::quit:
206 return;
207 }
208 }
209 }
210
211 static int MessageLoop(FAdviser* ptr) {
212 ptr->MessageLoopImpl();
213 return 0;
214 }
215
216 void SendMessage(Message::Type type, int fd = -1, size_t size = 0) {
217 {
218 std::unique_lock<std::mutex> lock(mutex_);
219 Message message = {type, fd, size};
220 queue_.push(message);
221 }
222 cv_.notify_one();
223 }
224
225 std::queue<Message> queue_;
226 std::mutex mutex_;
227 std::condition_variable cv_;
228
229 typedef std::multimap<size_t, int> Sizes;
230 typedef std::map<int, Sizes::iterator> Files;
231
232 Files files_;
233 Sizes sizes_;
234 size_t total_size_;
235
236 const size_t threshold_ = 64 * 1024 * 1024;
237 const size_t target_ = 32 * 1024 * 1024;
238};
239
Narayan Kamath92bf67b2020-01-03 17:49:09 +0000240// Whether inode tracking is enabled or not. When enabled, we maintain a
241// separate mapping from inode numbers to "live" nodes so we can detect when
242// we receive a request to a node that has been deleted.
243static constexpr bool kEnableInodeTracking = true;
244
shafik1e3a2672019-08-16 14:51:55 +0100245/* Single FUSE mount */
246struct fuse {
Narayan Kamathaef84a12020-01-02 15:20:13 +0000247 explicit fuse(const std::string& _path)
248 : path(_path), root(node::CreateRoot(_path, &lock)), mp(0), zero_addr(0) {}
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200249
Narayan Kamathaef84a12020-01-02 15:20:13 +0000250 inline bool IsRoot(const node* node) const { return node == root; }
shafik1e3a2672019-08-16 14:51:55 +0100251
Narayan Kamathaef84a12020-01-02 15:20:13 +0000252 // Note that these two (FromInode / ToInode) conversion wrappers are required
253 // because fuse_lowlevel_ops documents that the root inode is always one
254 // (see FUSE_ROOT_ID in fuse_lowlevel.h). There are no particular requirements
255 // on any of the other inodes in the FS.
Narayan Kamath92bf67b2020-01-03 17:49:09 +0000256 inline node* FromInode(__u64 inode) {
Narayan Kamathaef84a12020-01-02 15:20:13 +0000257 if (inode == FUSE_ROOT_ID) {
258 return root;
259 }
shafik1e3a2672019-08-16 14:51:55 +0100260
Narayan Kamath92bf67b2020-01-03 17:49:09 +0000261 node* node = node::FromInode(inode);
262
263 if (kEnableInodeTracking) {
264 std::lock_guard<std::recursive_mutex> guard(lock);
265 CHECK(inode_tracker_.find(node) != inode_tracker_.end());
266 }
267
268 return node;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000269 }
270
271 inline __u64 ToInode(node* node) const {
272 if (IsRoot(node)) {
273 return FUSE_ROOT_ID;
274 }
275
276 return node::ToInode(node);
277 }
278
Narayan Kamath92bf67b2020-01-03 17:49:09 +0000279 // Notify this FUSE instance that one of its nodes has been deleted.
280 void NodeDeleted(const node* node) {
281 if (kEnableInodeTracking) {
282 LOG(INFO) << "Node: " << node << " deleted.";
283
284 std::lock_guard<std::recursive_mutex> guard(lock);
285 inode_tracker_.erase(node);
286 }
287 }
288
289 // Notify this FUSE instance that a new nodes has been created.
290 void NodeCreated(const node* node) {
291 if (kEnableInodeTracking) {
292 LOG(INFO) << "Node: " << node << " created.";
293
294 std::lock_guard<std::recursive_mutex> guard(lock);
295 inode_tracker_.insert(node);
296 }
297 }
298
Narayan Kamathaef84a12020-01-02 15:20:13 +0000299 std::recursive_mutex lock;
300 const string path;
301 node* const root;
Zima76c3492020-02-19 01:23:26 +0000302 struct fuse_session* se;
shafikc3f62672019-08-30 11:15:48 +0100303
304 /*
305 * Used to make JNI calls to MediaProvider.
306 * Responsibility of freeing this object falls on corresponding
307 * FuseDaemon object.
308 */
309 mediaprovider::fuse::MediaProviderWrapper* mp;
shafikb334a612019-09-30 20:38:16 +0100310
311 /*
312 * Points to a range of zeroized bytes, used by pf_read to represent redacted ranges.
313 * The memory is read only and should never be modified.
314 */
Narayan Kamathaef84a12020-01-02 15:20:13 +0000315 /* const */ char* zero_addr;
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200316
317 FAdviser fadviser;
Narayan Kamath92bf67b2020-01-03 17:49:09 +0000318
319 std::unordered_set<const node*> inode_tracker_;
shafik1e3a2672019-08-16 14:51:55 +0100320};
321
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000322static inline const char* safe_name(node* n) {
323 return n ? n->GetName().c_str() : "?";
shafik458d1102019-09-06 18:21:36 +0100324}
325
shafik1e3a2672019-08-16 14:51:55 +0100326static inline __u64 ptr_to_id(void* ptr) {
327 return (__u64)(uintptr_t) ptr;
328}
329
Zimedbe69e2019-12-13 18:49:36 +0000330/*
331 * Set an F_RDLCK or F_WRLCKK on fd with fcntl(2).
332 *
333 * This is called before the MediaProvider returns fd from the lower file
334 * system to an app over the ContentResolver interface. This allows us
335 * check with is_file_locked if any reference to that fd is still open.
336 */
337static int set_file_lock(int fd, bool for_read, const std::string& path) {
338 std::string lock_str = (for_read ? "read" : "write");
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000339 TRACE_VERBOSE << "Setting " << lock_str << " lock for path " << path;
Zimedbe69e2019-12-13 18:49:36 +0000340
341 struct flock fl{};
342 fl.l_type = for_read ? F_RDLCK : F_WRLCK;
343 fl.l_whence = SEEK_SET;
344
345 int res = fcntl(fd, F_OFD_SETLK, &fl);
346 if (res) {
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000347 PLOG(ERROR) << "Failed to set " << lock_str << " lock on path " << path;
Zimedbe69e2019-12-13 18:49:36 +0000348 return res;
349 }
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000350 TRACE_VERBOSE << "Successfully set " << lock_str << " lock on path " << path;
Zimedbe69e2019-12-13 18:49:36 +0000351 return res;
352}
353
354/*
355 * Check if an F_RDLCK or F_WRLCK is set on fd with fcntl(2).
356 *
357 * This is used to determine if the MediaProvider has given an fd to the lower fs to an app over
358 * the ContentResolver interface. Before that happens, we always call set_file_lock on the file
359 * allowing us to know if any reference to that fd is still open here.
360 *
361 * Returns true if fd may have a lock, false otherwise
362 */
363static bool is_file_locked(int fd, const std::string& path) {
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000364 TRACE_VERBOSE << "Checking if file is locked " << path;
365
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) {
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000372 PLOG(ERROR) << "Failed to check lock for file " << path;
Zimedbe69e2019-12-13 18:49:36 +0000373 // Assume worst
374 return true;
375 }
376 bool locked = fl.l_type != F_UNLCK;
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000377 TRACE_VERBOSE << "File " << path << " is " << (locked ? "locked" : "unlocked");
Zimedbe69e2019-12-13 18:49:36 +0000378 return locked;
379}
380
shafik1e3a2672019-08-16 14:51:55 +0100381static struct fuse* get_fuse(fuse_req_t req) {
382 return reinterpret_cast<struct fuse*>(fuse_req_userdata(req));
383}
384
Zim8b2b6f22020-01-22 13:53:59 +0000385static bool is_android_path(const string& path, const string& fuse_path, uid_t uid) {
386 int user_id = uid / PER_USER_RANGE;
387 const std::string android_path = fuse_path + "/" + std::to_string(user_id) + "/Android";
388 return path.rfind(android_path, 0) == 0;
389}
390
391static double get_attr_timeout(const string& path, uid_t uid, struct fuse* fuse, node* parent) {
392 if (fuse->IsRoot(parent) || is_android_path(path, fuse->path, uid)) {
393 // The /0 and /0/Android attrs can be always cached, as they never change
394 return DBL_MAX;
395 } else {
396 return DEFAULT_ATTR_TIMEOUT_SECONDS;
397 }
398}
399
400static double get_entry_timeout(const string& path, uid_t uid, struct fuse* fuse, node* parent) {
401 if (fuse->IsRoot(parent) || is_android_path(path, fuse->path, uid)) {
402 // The /0 and /0/Android dentries can be always cached, as they are visible to all apps
403 return DBL_MAX;
404 } else {
405 return DEFAULT_ENTRY_TIMEOUT_SECONDS;
406 }
407}
408
Narayan Kamathaef84a12020-01-02 15:20:13 +0000409static node* make_node_entry(fuse_req_t req, node* parent, const string& name, const string& path,
410 struct fuse_entry_param* e, int* error_code) {
shafik1e3a2672019-08-16 14:51:55 +0100411 struct fuse* fuse = get_fuse(req);
Martijn Coenenb8ff4eb2019-12-17 09:55:17 +0100412 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000413 node* node;
shafik1e3a2672019-08-16 14:51:55 +0100414
Jeff Sharkey7469b982019-08-28 16:51:02 -0600415 memset(e, 0, sizeof(*e));
shafik1e3a2672019-08-16 14:51:55 +0100416 if (lstat(path.c_str(), &e->attr) < 0) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000417 *error_code = errno;
shafik1e3a2672019-08-16 14:51:55 +0100418 return NULL;
419 }
420
Narayan Kamatheca34252020-02-11 13:08:37 +0000421 node = parent->LookupChildByName(name, true /* acquire */);
422 if (!node) {
Narayan Kamathaef84a12020-01-02 15:20:13 +0000423 node = ::node::Create(parent, name, &fuse->lock);
Narayan Kamath92bf67b2020-01-03 17:49:09 +0000424 fuse->NodeCreated(node);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000425 }
shafik1e3a2672019-08-16 14:51:55 +0100426
Narayan Kamathfc0aa952019-12-31 13:31:49 +0000427 // This FS is not being exported via NFS so just a fixed generation number
428 // for now. If we do need this, we need to increment the generation ID each
429 // time the fuse daemon restarts because that's what it takes for us to
430 // reuse inode numbers.
431 e->generation = 0;
Zim8b2b6f22020-01-22 13:53:59 +0000432 e->ino = fuse->ToInode(node);
433 e->entry_timeout = get_entry_timeout(path, ctx->uid, fuse, parent);
434 e->attr_timeout = get_attr_timeout(path, ctx->uid, fuse, parent);
shafik1e3a2672019-08-16 14:51:55 +0100435
436 return node;
437}
438
shafik15e2d612019-10-31 20:10:25 +0000439static inline bool is_requesting_write(int flags) {
440 return flags & (O_WRONLY | O_RDWR);
441}
442
shafik1e3a2672019-08-16 14:51:55 +0100443namespace mediaprovider {
444namespace fuse {
445
446/**
447 * Function implementations
448 *
449 * These implement the various functions in fuse_lowlevel_ops
450 *
451 */
452
453static void pf_init(void* userdata, struct fuse_conn_info* conn) {
Zima9fcd552019-08-29 15:17:04 +0100454 // We don't want a getattr request with every read request
455 conn->want &= ~FUSE_CAP_AUTO_INVAL_DATA;
shafik8b57cd52019-09-06 10:51:29 +0100456 unsigned mask = (FUSE_CAP_SPLICE_WRITE | FUSE_CAP_SPLICE_MOVE | FUSE_CAP_SPLICE_READ |
457 FUSE_CAP_ASYNC_READ | FUSE_CAP_ATOMIC_O_TRUNC | FUSE_CAP_WRITEBACK_CACHE |
458 FUSE_CAP_EXPORT_SUPPORT | FUSE_CAP_FLOCK_LOCKS);
shafik1e3a2672019-08-16 14:51:55 +0100459 conn->want |= conn->capable & mask;
shafikb334a612019-09-30 20:38:16 +0100460 conn->max_read = MAX_READ_SIZE;
shafik1e3a2672019-08-16 14:51:55 +0100461}
462
Zim005cd812019-12-17 15:35:51 +0000463static void pf_destroy(void* userdata) {
464 struct fuse* fuse = reinterpret_cast<struct fuse*>(userdata);
465 LOG(INFO) << "DESTROY " << fuse->path;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000466
467 node::DeleteTree(fuse->root);
shafik1e3a2672019-08-16 14:51:55 +0100468}
shafik1e3a2672019-08-16 14:51:55 +0100469
Zim859db932019-12-13 00:09:17 +0000470static std::regex storage_emulated_regex("^\\/storage\\/emulated\\/([0-9]+)");
Narayan Kamathaef84a12020-01-02 15:20:13 +0000471static node* do_lookup(fuse_req_t req, fuse_ino_t parent, const char* name,
472 struct fuse_entry_param* e, int* error_code) {
shafik1e3a2672019-08-16 14:51:55 +0100473 struct fuse* fuse = get_fuse(req);
474 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000475 node* parent_node = fuse->FromInode(parent);
476 string parent_path = parent_node->BuildPath();
shafik1e3a2672019-08-16 14:51:55 +0100477
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000478 TRACE_FUSE_VERBOSE(fuse) << "LOOKUP " << name << " @ " << parent << " ("
479 << safe_name(parent_node) << ")";
480
481 string child_path = parent_path + "/" + name;
Zim2c5eb692020-02-20 15:47:06 +0000482
Zim859db932019-12-13 00:09:17 +0000483 std::smatch match;
484 std::regex_search(child_path, match, storage_emulated_regex);
Zimf0e3cd92020-01-03 00:57:43 +0000485 if (match.size() == 2 && std::to_string(getuid() / PER_USER_RANGE) != match[1].str()) {
486 // Ensure the FuseDaemon user id matches the user id in requested path
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000487 *error_code = EPERM;
Zim859db932019-12-13 00:09:17 +0000488 return nullptr;
489 }
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000490 return make_node_entry(req, parent_node, name, child_path, e, error_code);
shafik1e3a2672019-08-16 14:51:55 +0100491}
492
493static void pf_lookup(fuse_req_t req, fuse_ino_t parent, const char* name) {
Zimec8d5722019-12-05 07:26:13 +0000494 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100495 struct fuse_entry_param e;
496
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000497 int error_code = 0;
498 if (do_lookup(req, parent, name, &e, &error_code)) {
shafik1e3a2672019-08-16 14:51:55 +0100499 fuse_reply_entry(req, &e);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000500 } else {
501 CHECK(error_code != 0);
502 fuse_reply_err(req, error_code);
503 }
shafik1e3a2672019-08-16 14:51:55 +0100504}
505
Narayan Kamathaef84a12020-01-02 15:20:13 +0000506static void do_forget(struct fuse* fuse, fuse_ino_t ino, uint64_t nlookup) {
507 node* node = fuse->FromInode(ino);
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000508 TRACE_FUSE(fuse) << "FORGET #" << nlookup << " @ " << ino << " (" << safe_name(node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100509 if (node) {
Narayan Kamathaef84a12020-01-02 15:20:13 +0000510 // This is a narrowing conversion from an unsigned 64bit to a 32bit value. For
511 // some reason we only keep 32 bit refcounts but the kernel issues
512 // forget requests with a 64 bit counter.
Narayan Kamath92bf67b2020-01-03 17:49:09 +0000513 if (node->Release(static_cast<uint32_t>(nlookup))) {
514 fuse->NodeDeleted(node);
515 }
shafik1e3a2672019-08-16 14:51:55 +0100516 }
517}
518
519static void pf_forget(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup) {
Zimec8d5722019-12-05 07:26:13 +0000520 ATRACE_CALL();
Narayan Kamathaef84a12020-01-02 15:20:13 +0000521 node* node;
shafik1e3a2672019-08-16 14:51:55 +0100522 struct fuse* fuse = get_fuse(req);
523
Narayan Kamathaef84a12020-01-02 15:20:13 +0000524 do_forget(fuse, ino, nlookup);
shafik1e3a2672019-08-16 14:51:55 +0100525 fuse_reply_none(req);
526}
527
528static void pf_forget_multi(fuse_req_t req,
529 size_t count,
530 struct fuse_forget_data* forgets) {
Zimec8d5722019-12-05 07:26:13 +0000531 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100532 struct fuse* fuse = get_fuse(req);
533
Narayan Kamathaef84a12020-01-02 15:20:13 +0000534 for (int i = 0; i < count; i++) {
535 do_forget(fuse, forgets[i].ino, forgets[i].nlookup);
Narayan Kamath768bea32019-12-27 16:23:23 +0000536 }
shafik1e3a2672019-08-16 14:51:55 +0100537 fuse_reply_none(req);
538}
539
540static void pf_getattr(fuse_req_t req,
541 fuse_ino_t ino,
542 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +0000543 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100544 struct fuse* fuse = get_fuse(req);
545 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000546 node* node = fuse->FromInode(ino);
547 string path = node->BuildPath();
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000548 TRACE_FUSE(fuse) << "GETATTR @ " << ino << " (" << safe_name(node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100549
550 if (!node) fuse_reply_err(req, ENOENT);
551
Narayan Kamathaef84a12020-01-02 15:20:13 +0000552 struct stat s;
shafik1e3a2672019-08-16 14:51:55 +0100553 memset(&s, 0, sizeof(s));
554 if (lstat(path.c_str(), &s) < 0) {
555 fuse_reply_err(req, errno);
556 } else {
Zim8b2b6f22020-01-22 13:53:59 +0000557 fuse_reply_attr(req, &s, get_attr_timeout(path, ctx->uid, fuse, nullptr));
shafik1e3a2672019-08-16 14:51:55 +0100558 }
559}
560
561static void pf_setattr(fuse_req_t req,
562 fuse_ino_t ino,
563 struct stat* attr,
564 int to_set,
565 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +0000566 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100567 struct fuse* fuse = get_fuse(req);
568 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000569 node* node = fuse->FromInode(ino);
570 string path = node->BuildPath();
shafik1e3a2672019-08-16 14:51:55 +0100571 struct timespec times[2];
shafik1e3a2672019-08-16 14:51:55 +0100572
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000573 TRACE_FUSE(fuse) << "SETATTR valid=" << to_set << " @ " << ino << "(" << safe_name(node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100574
575 if (!node) {
576 fuse_reply_err(req, ENOENT);
577 return;
578 }
579
580 /* XXX: incomplete implementation on purpose.
581 * chmod/chown should NEVER be implemented.*/
582
583 if ((to_set & FUSE_SET_ATTR_SIZE)
584 && truncate64(path.c_str(), attr->st_size) < 0) {
585 fuse_reply_err(req, errno);
586 return;
587 }
588
589 /* Handle changing atime and mtime. If FATTR_ATIME_and FATTR_ATIME_NOW
590 * are both set, then set it to the current time. Else, set it to the
591 * time specified in the request. Same goes for mtime. Use utimensat(2)
592 * as it allows ATIME and MTIME to be changed independently, and has
593 * nanosecond resolution which fuse also has.
594 */
595 if (to_set & (FATTR_ATIME | FATTR_MTIME)) {
596 times[0].tv_nsec = UTIME_OMIT;
597 times[1].tv_nsec = UTIME_OMIT;
598 if (to_set & FATTR_ATIME) {
599 if (to_set & FATTR_ATIME_NOW) {
600 times[0].tv_nsec = UTIME_NOW;
601 } else {
602 times[0].tv_sec = attr->st_atime;
603 // times[0].tv_nsec = attr->st_atime.tv_nsec;
604 }
605 }
606 if (to_set & FATTR_MTIME) {
607 if (to_set & FATTR_MTIME_NOW) {
608 times[1].tv_nsec = UTIME_NOW;
609 } else {
610 times[1].tv_sec = attr->st_mtime;
611 // times[1].tv_nsec = attr->st_mtime.tv_nsec;
612 }
613 }
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000614 TRACE_FUSE(fuse) << "Calling utimensat on " << path << " with atime " << times[0].tv_sec
615 << " mtime=" << times[1].tv_sec;
shafik1e3a2672019-08-16 14:51:55 +0100616 if (utimensat(-1, path.c_str(), times, 0) < 0) {
617 fuse_reply_err(req, errno);
618 return;
619 }
620 }
621
Zima9fcd552019-08-29 15:17:04 +0100622 lstat(path.c_str(), attr);
Zim8b2b6f22020-01-22 13:53:59 +0000623 fuse_reply_attr(req, attr, get_attr_timeout(path, ctx->uid, fuse, nullptr));
shafik1e3a2672019-08-16 14:51:55 +0100624}
Zimb9730bf2019-11-30 15:10:04 +0000625
626static void pf_canonical_path(fuse_req_t req, fuse_ino_t ino)
shafik1e3a2672019-08-16 14:51:55 +0100627{
Zimb9730bf2019-11-30 15:10:04 +0000628 node* node = get_fuse(req)->FromInode(ino);
629
630 if (node) {
631 // TODO(b/147482155): Check that uid has access to |path| and its contents
632 fuse_reply_canonical_path(req, node->BuildPath().c_str());
633 return;
634 }
635 fuse_reply_err(req, ENOENT);
shafik1e3a2672019-08-16 14:51:55 +0100636}
Zimb9730bf2019-11-30 15:10:04 +0000637
shafik1e3a2672019-08-16 14:51:55 +0100638static void pf_mknod(fuse_req_t req,
639 fuse_ino_t parent,
640 const char* name,
641 mode_t mode,
642 dev_t rdev) {
Zimec8d5722019-12-05 07:26:13 +0000643 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100644 struct fuse* fuse = get_fuse(req);
645 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000646 node* parent_node = fuse->FromInode(parent);
647 string parent_path = parent_node->BuildPath();
Narayan Kamath768bea32019-12-27 16:23:23 +0000648
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000649 TRACE_FUSE(fuse) << "MKNOD " << name << " 0" << std::oct << mode << " @ " << parent << " ("
650 << safe_name(parent_node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100651
652 if (!parent_node) {
653 fuse_reply_err(req, ENOENT);
654 return;
655 }
Narayan Kamathaef84a12020-01-02 15:20:13 +0000656 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100657
658 mode = (mode & (~0777)) | 0664;
659 if (mknod(child_path.c_str(), mode, rdev) < 0) {
660 fuse_reply_err(req, errno);
661 return;
662 }
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000663
664 int error_code = 0;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000665 struct fuse_entry_param e;
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000666 if (make_node_entry(req, parent_node, name, child_path, &e, &error_code)) {
shafik1e3a2672019-08-16 14:51:55 +0100667 fuse_reply_entry(req, &e);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000668 } else {
669 CHECK(error_code != 0);
670 fuse_reply_err(req, error_code);
671 }
shafik1e3a2672019-08-16 14:51:55 +0100672}
673
674static void pf_mkdir(fuse_req_t req,
675 fuse_ino_t parent,
676 const char* name,
677 mode_t mode) {
Zimec8d5722019-12-05 07:26:13 +0000678 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100679 struct fuse* fuse = get_fuse(req);
680 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000681 node* parent_node = fuse->FromInode(parent);
682 const string parent_path = parent_node->BuildPath();
Narayan Kamath768bea32019-12-27 16:23:23 +0000683
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000684 TRACE_FUSE(fuse) << "MKDIR " << name << " 0" << std::oct << mode << " @ " << parent << " ("
685 << safe_name(parent_node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100686
Narayan Kamathaef84a12020-01-02 15:20:13 +0000687 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100688
shafike4fb1462020-01-29 16:25:23 +0000689 int status = fuse->mp->IsCreatingDirAllowed(child_path, ctx->uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000690 if (status) {
691 fuse_reply_err(req, status);
692 return;
693 }
694
shafik1e3a2672019-08-16 14:51:55 +0100695 mode = (mode & (~0777)) | 0775;
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000696 if (mkdir(child_path.c_str(), mode) < 0) {
shafik1e3a2672019-08-16 14:51:55 +0100697 fuse_reply_err(req, errno);
698 return;
699 }
700
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000701 int error_code = 0;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000702 struct fuse_entry_param e;
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000703 if (make_node_entry(req, parent_node, name, child_path, &e, &error_code)) {
shafik1e3a2672019-08-16 14:51:55 +0100704 fuse_reply_entry(req, &e);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000705 } else {
706 CHECK(error_code != 0);
707 fuse_reply_err(req, error_code);
708 }
shafik1e3a2672019-08-16 14:51:55 +0100709}
710
711static void pf_unlink(fuse_req_t req, fuse_ino_t parent, const char* name) {
Zimec8d5722019-12-05 07:26:13 +0000712 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100713 struct fuse* fuse = get_fuse(req);
714 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000715 node* parent_node = fuse->FromInode(parent);
716 const string parent_path = parent_node->BuildPath();
shafik1e3a2672019-08-16 14:51:55 +0100717
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000718 TRACE_FUSE(fuse) << "UNLINK " << name << " @ " << parent << "(" << safe_name(parent_node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100719
Narayan Kamathaef84a12020-01-02 15:20:13 +0000720 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100721
shafike4fb1462020-01-29 16:25:23 +0000722 int status = fuse->mp->DeleteFile(child_path, ctx->uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000723 if (status) {
724 fuse_reply_err(req, status);
shafik1e3a2672019-08-16 14:51:55 +0100725 return;
726 }
Narayan Kamath768bea32019-12-27 16:23:23 +0000727
Narayan Kamatheca34252020-02-11 13:08:37 +0000728 node* child_node = parent_node->LookupChildByName(name, false /* acquire */);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000729 if (child_node) {
730 child_node->SetDeleted();
shafik1e3a2672019-08-16 14:51:55 +0100731 }
shafik1e3a2672019-08-16 14:51:55 +0100732
733 fuse_reply_err(req, 0);
734}
735
736static void pf_rmdir(fuse_req_t req, fuse_ino_t parent, const char* name) {
Zimec8d5722019-12-05 07:26:13 +0000737 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100738 struct fuse* fuse = get_fuse(req);
739 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000740 node* parent_node = fuse->FromInode(parent);
741 const string parent_path = parent_node->BuildPath();
shafik1e3a2672019-08-16 14:51:55 +0100742
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000743 TRACE_FUSE(fuse) << "RMDIR " << name << " @ " << parent << "(" << safe_name(parent_node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100744
Narayan Kamathaef84a12020-01-02 15:20:13 +0000745 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100746
shafike4fb1462020-01-29 16:25:23 +0000747 int status = fuse->mp->IsDeletingDirAllowed(child_path, ctx->uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000748 if (status) {
749 fuse_reply_err(req, status);
750 return;
751 }
752
753 if (rmdir(child_path.c_str()) < 0) {
shafik1e3a2672019-08-16 14:51:55 +0100754 fuse_reply_err(req, errno);
755 return;
756 }
Narayan Kamath768bea32019-12-27 16:23:23 +0000757
Narayan Kamatheca34252020-02-11 13:08:37 +0000758 node* child_node = parent_node->LookupChildByName(name, false /* acquire */);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000759 if (child_node) {
760 child_node->SetDeleted();
shafik1e3a2672019-08-16 14:51:55 +0100761 }
shafik1e3a2672019-08-16 14:51:55 +0100762
763 fuse_reply_err(req, 0);
764}
765/*
766static void pf_symlink(fuse_req_t req, const char* link, fuse_ino_t parent,
767 const char* name)
768{
769 cout << "TODO:" << __func__;
770}
771*/
Sahana Rao2c416032019-12-31 13:41:00 +0000772static int do_rename(fuse_req_t req, fuse_ino_t parent, const char* name, fuse_ino_t new_parent,
773 const char* new_name, unsigned int flags) {
Zimec8d5722019-12-05 07:26:13 +0000774 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100775 struct fuse* fuse = get_fuse(req);
776 const struct fuse_ctx* ctx = fuse_req_ctx(req);
shafik1e3a2672019-08-16 14:51:55 +0100777
Sahana Rao2c416032019-12-31 13:41:00 +0000778 if (flags != 0) {
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000779 LOG(ERROR) << "One or more rename flags not supported";
Sahana Rao2c416032019-12-31 13:41:00 +0000780 return EINVAL;
781 }
Narayan Kamath768bea32019-12-27 16:23:23 +0000782
Narayan Kamathaef84a12020-01-02 15:20:13 +0000783 node* old_parent_node = fuse->FromInode(parent);
784 const string old_parent_path = old_parent_node->BuildPath();
785 node* new_parent_node = fuse->FromInode(new_parent);
786 const string new_parent_path = new_parent_node->BuildPath();
Narayan Kamath768bea32019-12-27 16:23:23 +0000787
Narayan Kamathaef84a12020-01-02 15:20:13 +0000788 if (!old_parent_node || !new_parent_node) {
789 return ENOENT;
790 } else if (parent == new_parent && name == new_name) {
791 // No rename required.
792 return 0;
shafik1e3a2672019-08-16 14:51:55 +0100793 }
794
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000795 TRACE_FUSE(fuse) << "RENAME " << name << " -> " << new_name << " @ " << parent << " ("
796 << safe_name(old_parent_node) << ") -> " << new_parent << " ("
797 << safe_name(new_parent_node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100798
Narayan Kamatheca34252020-02-11 13:08:37 +0000799 node* child_node = old_parent_node->LookupChildByName(name, true /* acquire */);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000800
801 const string old_child_path = child_node->BuildPath();
802 const string new_child_path = new_parent_path + "/" + new_name;
803
Sahana Rao182ec6b2020-01-03 15:00:46 +0000804 // TODO(b/147408834): Check ENOTEMPTY & EEXIST error conditions before JNI call.
shafike4fb1462020-01-29 16:25:23 +0000805 const int res = fuse->mp->Rename(old_child_path, new_child_path, req->ctx.uid);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000806 // TODO(b/145663158): Lookups can go out of sync if file/directory is actually moved but
807 // EFAULT/EIO is reported due to JNI exception.
808 if (res == 0) {
809 child_node->Rename(new_name, new_parent_node);
shafik1e3a2672019-08-16 14:51:55 +0100810 }
811
Narayan Kamathaef84a12020-01-02 15:20:13 +0000812 child_node->Release(1);
Narayan Kamath768bea32019-12-27 16:23:23 +0000813 return res;
814}
shafik1e3a2672019-08-16 14:51:55 +0100815
Sahana Rao2c416032019-12-31 13:41:00 +0000816static void pf_rename(fuse_req_t req, fuse_ino_t parent, const char* name, fuse_ino_t new_parent,
817 const char* new_name, unsigned int flags) {
818 int res = do_rename(req, parent, name, new_parent, new_name, flags);
shafik1e3a2672019-08-16 14:51:55 +0100819 fuse_reply_err(req, res);
820}
Narayan Kamath768bea32019-12-27 16:23:23 +0000821
shafik1e3a2672019-08-16 14:51:55 +0100822/*
Sahana Rao2c416032019-12-31 13:41:00 +0000823static void pf_link(fuse_req_t req, fuse_ino_t ino, fuse_ino_t new_parent,
824 const char* new_name)
shafik1e3a2672019-08-16 14:51:55 +0100825{
826 cout << "TODO:" << __func__;
827}
828*/
829
830static void pf_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +0000831 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100832 struct fuse* fuse = get_fuse(req);
833 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000834 node* node = fuse->FromInode(ino);
835 const string path = node->BuildPath();
shafik1e3a2672019-08-16 14:51:55 +0100836
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000837 TRACE_FUSE(fuse) << "OPEN 0" << std::oct << fi->flags << " @ " << ino << " (" << safe_name(node)
838 << ")";
shafik1e3a2672019-08-16 14:51:55 +0100839
840 if (!node) {
841 fuse_reply_err(req, ENOENT);
842 return;
843 }
844
shafik15e2d612019-10-31 20:10:25 +0000845 if (fi->flags & O_DIRECT) {
846 fi->flags &= ~O_DIRECT;
847 fi->direct_io = true;
848 }
849
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000850 TRACE_FUSE(fuse) << "OPEN " << path;
shafike4fb1462020-01-29 16:25:23 +0000851 int status = fuse->mp->IsOpenAllowed(path, ctx->uid, is_requesting_write(fi->flags));
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000852 if (status) {
853 fuse_reply_err(req, status);
854 return;
855 }
856
Martijn Coenen2d7f1be2020-02-15 07:44:12 +0100857 // With the writeback cache enabled, FUSE may generate READ requests even for files that
858 // were opened O_WRONLY; so make sure we open it O_RDWR instead.
859 int open_flags = fi->flags;
860 if (open_flags & O_WRONLY) {
861 open_flags &= ~O_WRONLY;
862 open_flags |= O_RDWR;
863 }
864
865 const int fd = open(path.c_str(), open_flags);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000866 if (fd < 0) {
shafik1e3a2672019-08-16 14:51:55 +0100867 fuse_reply_err(req, errno);
868 return;
869 }
shafik15e2d612019-10-31 20:10:25 +0000870
shafikc580b6d2019-12-10 18:45:17 +0000871 // We don't redact if the caller was granted write permission for this file
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000872 std::unique_ptr<RedactionInfo> ri;
shafikc580b6d2019-12-10 18:45:17 +0000873 if (is_requesting_write(fi->flags)) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000874 ri = std::make_unique<RedactionInfo>();
shafikc580b6d2019-12-10 18:45:17 +0000875 } else {
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000876 ri = fuse->mp->GetRedactionInfo(path, req->ctx.uid);
shafikc580b6d2019-12-10 18:45:17 +0000877 }
878
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000879 if (!ri) {
880 close(fd);
881 fuse_reply_err(req, EFAULT);
shafikc580b6d2019-12-10 18:45:17 +0000882 return;
883 }
884
Narayan Kamathbd22bb02020-01-08 16:02:50 +0000885 if (ri->isRedactionNeeded() || is_file_locked(fd, path)) {
Zimedbe69e2019-12-13 18:49:36 +0000886 // We don't want to use the FUSE VFS cache in two cases:
887 // 1. When redaction is needed because app A with EXIF access might access
888 // a region that should have been redacted for app B without EXIF access, but app B on
889 // a subsequent read, will be able to see the EXIF data because the read request for that
890 // region will be served from cache and not get to the FUSE daemon
891 // 2. When the file has a read or write lock on it. This means that the MediaProvider has
892 // given an fd to the lower file system to an app. There are two cases where using the cache
893 // in this case can be a problem:
894 // a. Writing to a FUSE fd with caching enabled will use the write-back cache and a
895 // subsequent read from the lower fs fd will not see the write.
896 // b. Reading from a FUSE fd with caching enabled may not see the latest writes using the
897 // lower fs fd because those writes did not go through the FUSE layer and reads from FUSE
898 // after that write may be served from cache
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000899 if (ri->isRedactionNeeded()) {
900 TRACE_FUSE(fuse) << "Using direct io for " << path << " because redaction is needed.";
901 } else {
902 TRACE_FUSE(fuse) << "Using direct io for " << path << " because the file is locked.";
903 }
shafikc580b6d2019-12-10 18:45:17 +0000904 fi->direct_io = true;
Cody Schuffelen338bd1a2020-02-21 17:40:56 +0000905 } else {
906 TRACE_FUSE(fuse) << "Using cache for " << path;
shafikc580b6d2019-12-10 18:45:17 +0000907 }
908
Sahana Raoc0211d12020-02-17 10:11:56 +0000909 handle* h = new handle(path, fd, ri.release(), /*owner_uid*/ -1, !fi->direct_io);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000910 node->AddHandle(h);
Zimedbe69e2019-12-13 18:49:36 +0000911
shafik1e3a2672019-08-16 14:51:55 +0100912 fi->fh = ptr_to_id(h);
Zim61d12342019-10-01 15:47:45 +0100913 fi->keep_cache = 1;
shafik1e3a2672019-08-16 14:51:55 +0100914 fuse_reply_open(req, fi);
915}
916
shafikc3f62672019-08-30 11:15:48 +0100917static void do_read(fuse_req_t req, size_t size, off_t off, struct fuse_file_info* fi) {
shafika2ae9072019-10-28 12:16:00 +0000918 handle* h = reinterpret_cast<handle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +0100919 struct fuse_bufvec buf = FUSE_BUFVEC_INIT(size);
920
921 buf.buf[0].fd = h->fd;
922 buf.buf[0].pos = off;
923 buf.buf[0].flags =
924 (enum fuse_buf_flags) (FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
925
926 fuse_reply_data(req, &buf, (enum fuse_buf_copy_flags) 0);
927}
shafikc3f62672019-08-30 11:15:48 +0100928
929static bool range_contains(const RedactionRange& rr, off_t off) {
930 return rr.first <= off && off <= rr.second;
931}
932
933/**
934 * Sets the parameters for a fuse_buf that reads from memory, including flags.
shafikb334a612019-09-30 20:38:16 +0100935 * Makes buf->mem point to an already mapped region of zeroized memory.
936 * This memory is read only.
shafikc3f62672019-08-30 11:15:48 +0100937 */
shafikb334a612019-09-30 20:38:16 +0100938static void create_mem_fuse_buf(size_t size, fuse_buf* buf, struct fuse* fuse) {
shafikc3f62672019-08-30 11:15:48 +0100939 buf->size = size;
shafikb334a612019-09-30 20:38:16 +0100940 buf->mem = fuse->zero_addr;
shafikc3f62672019-08-30 11:15:48 +0100941 buf->flags = static_cast<fuse_buf_flags>(0 /*read from fuse_buf.mem*/);
942 buf->pos = -1;
943 buf->fd = -1;
944}
945
946/**
947 * Sets the parameters for a fuse_buf that reads from file, including flags.
948 */
949static void create_file_fuse_buf(size_t size, off_t pos, int fd, fuse_buf* buf) {
950 buf->size = size;
951 buf->fd = fd;
952 buf->pos = pos;
953 buf->flags = static_cast<fuse_buf_flags>(FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
954 buf->mem = nullptr;
955}
956
957static 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 +0000958 handle* h = reinterpret_cast<handle*>(fi->fh);
shafikc3f62672019-08-30 11:15:48 +0100959 auto overlapping_rr = h->ri->getOverlappingRedactionRanges(size, off);
960
961 if (overlapping_rr->size() <= 0) {
962 // no relevant redaction ranges for this request
963 do_read(req, size, off, fi);
964 return;
965 }
966 // the number of buffers we need, if the read doesn't start or end with
967 // a redaction range.
968 int num_bufs = overlapping_rr->size() * 2 + 1;
969 if (overlapping_rr->front().first <= off) {
970 // the beginning of the read request is redacted
971 num_bufs--;
972 }
973 if (overlapping_rr->back().second >= off + size) {
974 // the end of the read request is redacted
975 num_bufs--;
976 }
977 auto bufvec_ptr = std::unique_ptr<fuse_bufvec, decltype(free)*>{
978 reinterpret_cast<fuse_bufvec*>(
979 malloc(sizeof(fuse_bufvec) + (num_bufs - 1) * sizeof(fuse_buf))),
980 free};
981 fuse_bufvec& bufvec = *bufvec_ptr;
982
983 // initialize bufvec
984 bufvec.count = num_bufs;
985 bufvec.idx = 0;
986 bufvec.off = 0;
shafikc3f62672019-08-30 11:15:48 +0100987
988 int rr_idx = 0;
989 off_t start = off;
990 // Add a dummy redaction range to make sure we don't go out of vector
991 // limits when computing the end of the last non-redacted range.
992 // This ranges is invalid because its starting point is larger than it's ending point.
993 overlapping_rr->push_back(RedactionRange(LLONG_MAX, LLONG_MAX - 1));
994
995 for (int i = 0; i < num_bufs; ++i) {
996 off_t end;
997 if (range_contains(overlapping_rr->at(rr_idx), start)) {
998 // Handle a redacted range
999 // end should be the end of the redacted range, but can't be out of
1000 // the read request bounds
1001 end = std::min(static_cast<off_t>(off + size - 1), overlapping_rr->at(rr_idx).second);
shafikb334a612019-09-30 20:38:16 +01001002 create_mem_fuse_buf(/*size*/ end - start + 1, &(bufvec.buf[i]), get_fuse(req));
shafikc3f62672019-08-30 11:15:48 +01001003 ++rr_idx;
1004 } else {
1005 // Handle a non-redacted range
1006 // end should be right before the next redaction range starts or
1007 // the end of the read request
1008 end = std::min(static_cast<off_t>(off + size - 1),
1009 overlapping_rr->at(rr_idx).first - 1);
1010 create_file_fuse_buf(/*size*/ end - start + 1, start, h->fd, &(bufvec.buf[i]));
1011 }
1012 start = end + 1;
1013 }
1014
1015 fuse_reply_data(req, &bufvec, static_cast<fuse_buf_copy_flags>(0));
1016}
1017
1018static void pf_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off,
1019 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001020 ATRACE_CALL();
shafika2ae9072019-10-28 12:16:00 +00001021 handle* h = reinterpret_cast<handle*>(fi->fh);
shafikc3f62672019-08-30 11:15:48 +01001022 struct fuse* fuse = get_fuse(req);
shafikc3f62672019-08-30 11:15:48 +01001023
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001024 fuse->fadviser.Record(h->fd, size);
1025
shafikc3f62672019-08-30 11:15:48 +01001026 if (h->ri->isRedactionNeeded()) {
1027 do_read_with_redaction(req, size, off, fi);
1028 } else {
1029 do_read(req, size, off, fi);
1030 }
1031}
1032
shafik1e3a2672019-08-16 14:51:55 +01001033/*
1034static void pf_write(fuse_req_t req, fuse_ino_t ino, const char* buf,
1035 size_t size, off_t off, struct fuse_file_info* fi)
1036{
1037 cout << "TODO:" << __func__;
1038}
1039*/
1040
1041static void pf_write_buf(fuse_req_t req,
1042 fuse_ino_t ino,
1043 struct fuse_bufvec* bufv,
1044 off_t off,
1045 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001046 ATRACE_CALL();
shafika2ae9072019-10-28 12:16:00 +00001047 handle* h = reinterpret_cast<handle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001048 struct fuse_bufvec buf = FUSE_BUFVEC_INIT(fuse_buf_size(bufv));
1049 ssize_t size;
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001050 struct fuse* fuse = get_fuse(req);
shafik1e3a2672019-08-16 14:51:55 +01001051
1052 buf.buf[0].fd = h->fd;
1053 buf.buf[0].pos = off;
1054 buf.buf[0].flags =
1055 (enum fuse_buf_flags) (FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
1056 size = fuse_buf_copy(&buf, bufv, (enum fuse_buf_copy_flags) 0);
1057
1058 if (size < 0)
1059 fuse_reply_err(req, -size);
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001060 else {
shafik1e3a2672019-08-16 14:51:55 +01001061 fuse_reply_write(req, size);
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001062 fuse->fadviser.Record(h->fd, size);
1063 }
shafik1e3a2672019-08-16 14:51:55 +01001064}
1065// Haven't tested this one. Not sure what calls it.
1066#if 0
1067static void pf_copy_file_range(fuse_req_t req, fuse_ino_t ino_in,
1068 off_t off_in, struct fuse_file_info* fi_in,
1069 fuse_ino_t ino_out, off_t off_out,
1070 struct fuse_file_info* fi_out, size_t len,
1071 int flags)
1072{
shafika2ae9072019-10-28 12:16:00 +00001073 handle* h_in = reinterpret_cast<handle *>(fi_in->fh);
1074 handle* h_out = reinterpret_cast<handle *>(fi_out->fh);
shafik1e3a2672019-08-16 14:51:55 +01001075 struct fuse_bufvec buf_in = FUSE_BUFVEC_INIT(len);
1076 struct fuse_bufvec buf_out = FUSE_BUFVEC_INIT(len);
1077 ssize_t size;
1078
1079 buf_in.buf[0].fd = h_in->fd;
1080 buf_in.buf[0].pos = off_in;
1081 buf_in.buf[0].flags = (enum fuse_buf_flags)(FUSE_BUF_IS_FD|FUSE_BUF_FD_SEEK);
1082
1083 buf_out.buf[0].fd = h_out->fd;
1084 buf_out.buf[0].pos = off_out;
1085 buf_out.buf[0].flags = (enum fuse_buf_flags)(FUSE_BUF_IS_FD|FUSE_BUF_FD_SEEK);
1086 size = fuse_buf_copy(&buf_out, &buf_in, (enum fuse_buf_copy_flags) 0);
1087
1088 if (size < 0) {
1089 fuse_reply_err(req, -size);
1090 }
1091
1092 fuse_reply_write(req, size);
1093}
1094#endif
1095static void pf_flush(fuse_req_t req,
1096 fuse_ino_t ino,
1097 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001098 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001099 struct fuse* fuse = get_fuse(req);
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001100 TRACE_FUSE(fuse) << "FLUSH is a noop";
shafik1e3a2672019-08-16 14:51:55 +01001101 fuse_reply_err(req, 0);
1102}
1103
1104static void pf_release(fuse_req_t req,
1105 fuse_ino_t ino,
1106 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001107 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001108 struct fuse* fuse = get_fuse(req);
Kyle Tso613b7ab2019-12-24 06:30:00 +00001109
Narayan Kamathaef84a12020-01-02 15:20:13 +00001110 node* node = fuse->FromInode(ino);
1111 handle* h = reinterpret_cast<handle*>(fi->fh);
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001112 TRACE_FUSE(fuse) << "RELEASE "
1113 << "0" << std::oct << fi->flags << " " << h << "(" << h->fd << ")";
shafik15e2d612019-10-31 20:10:25 +00001114
Narayan Kamathaef84a12020-01-02 15:20:13 +00001115 fuse->fadviser.Close(h->fd);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001116 if (node) {
Sahana Raoc0211d12020-02-17 10:11:56 +00001117 if (h->owner_uid != -1) {
1118 fuse->mp->ScanFile(h->path, h->owner_uid);
Zimb3993882020-02-09 20:20:24 +00001119 }
Narayan Kamathaef84a12020-01-02 15:20:13 +00001120 node->DestroyHandle(h);
Zimedbe69e2019-12-13 18:49:36 +00001121 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001122
shafik1e3a2672019-08-16 14:51:55 +01001123 fuse_reply_err(req, 0);
1124}
1125
1126static int do_sync_common(int fd, bool datasync) {
1127 int res = datasync ? fdatasync(fd) : fsync(fd);
1128
1129 if (res == -1) return errno;
1130 return 0;
1131}
1132
1133static void pf_fsync(fuse_req_t req,
1134 fuse_ino_t ino,
1135 int datasync,
1136 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001137 ATRACE_CALL();
shafika2ae9072019-10-28 12:16:00 +00001138 handle* h = reinterpret_cast<handle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001139 int err = do_sync_common(h->fd, datasync);
1140
1141 fuse_reply_err(req, err);
1142}
1143
1144static void pf_fsyncdir(fuse_req_t req,
1145 fuse_ino_t ino,
1146 int datasync,
1147 struct fuse_file_info* fi) {
Narayan Kamathaef84a12020-01-02 15:20:13 +00001148 dirhandle* h = reinterpret_cast<dirhandle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001149 int err = do_sync_common(dirfd(h->d), datasync);
1150
1151 fuse_reply_err(req, err);
1152}
1153
1154static void pf_opendir(fuse_req_t req,
1155 fuse_ino_t ino,
1156 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001157 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001158 struct fuse* fuse = get_fuse(req);
1159 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001160 node* node = fuse->FromInode(ino);
1161 const string path = node->BuildPath();
shafik458d1102019-09-06 18:21:36 +01001162
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001163 TRACE_FUSE(fuse) << "OPENDIR @ " << ino << " (" << safe_name(node) << ")" << path;
shafik1e3a2672019-08-16 14:51:55 +01001164
1165 if (!node) {
1166 fuse_reply_err(req, ENOENT);
1167 return;
1168 }
1169
shafike4fb1462020-01-29 16:25:23 +00001170 int status = fuse->mp->IsOpendirAllowed(path, ctx->uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001171 if (status) {
1172 fuse_reply_err(req, status);
1173 return;
1174 }
1175
1176 DIR* dir = opendir(path.c_str());
1177 if (!dir) {
shafik1e3a2672019-08-16 14:51:55 +01001178 fuse_reply_err(req, errno);
1179 return;
1180 }
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001181
Narayan Kamathaef84a12020-01-02 15:20:13 +00001182 dirhandle* h = new dirhandle(dir);
1183 node->AddDirHandle(h);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001184
shafik1e3a2672019-08-16 14:51:55 +01001185 fi->fh = ptr_to_id(h);
1186 fuse_reply_open(req, fi);
1187}
1188
1189#define READDIR_BUF 8192LU
1190
1191static void do_readdir_common(fuse_req_t req,
1192 fuse_ino_t ino,
1193 size_t size,
1194 off_t off,
1195 struct fuse_file_info* fi,
1196 bool plus) {
1197 struct fuse* fuse = get_fuse(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001198 dirhandle* h = reinterpret_cast<dirhandle*>(fi->fh);
Jeff Sharkey7469b982019-08-28 16:51:02 -06001199 size_t len = std::min<size_t>(size, READDIR_BUF);
shafik1e3a2672019-08-16 14:51:55 +01001200 char buf[READDIR_BUF];
1201 size_t used = 0;
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001202 std::shared_ptr<DirectoryEntry> de;
1203
shafik1e3a2672019-08-16 14:51:55 +01001204 struct fuse_entry_param e;
Sahana Rao6f9ea982019-09-20 12:21:33 +01001205 size_t entry_size = 0;
shafik1e3a2672019-08-16 14:51:55 +01001206
Narayan Kamathaef84a12020-01-02 15:20:13 +00001207 node* node = fuse->FromInode(ino);
1208 const string path = node->BuildPath();
Narayan Kamath768bea32019-12-27 16:23:23 +00001209
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001210 TRACE_FUSE(fuse) << "READDIR @" << ino << " " << path << " at offset " << off;
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001211 // Get all directory entries from MediaProvider on first readdir() call of
1212 // directory handle. h->next_off = 0 indicates that current readdir() call
1213 // is first readdir() call for the directory handle, Avoid multiple JNI calls
1214 // for single directory handle.
1215 if (h->next_off == 0) {
Sahana Rao71693442019-11-13 13:48:07 +00001216 h->de = fuse->mp->GetDirectoryEntries(req->ctx.uid, path, h->d);
shafik1e3a2672019-08-16 14:51:55 +01001217 }
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001218 // If the last entry in the previous readdir() call was rejected due to
1219 // buffer capacity constraints, update directory offset to start from
1220 // previously rejected entry. Directory offset can also change if there was
Sahana Rao71693442019-11-13 13:48:07 +00001221 // a seekdir() on the given directory handle.
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001222 if (off != h->next_off) {
1223 h->next_off = off;
1224 }
1225 const int num_directory_entries = h->de.size();
Sahana Rao71693442019-11-13 13:48:07 +00001226 // Check for errors. Any error/exception occurred while obtaining directory
1227 // entries will be indicated by marking first directory entry name as empty
1228 // string. In the erroneous case corresponding d_type will hold error number.
Sahana Rao53bd1f62019-12-27 20:18:39 +00001229 if (num_directory_entries && h->de[0]->d_name.empty()) {
1230 fuse_reply_err(req, h->de[0]->d_type);
1231 return;
1232 }
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001233
Sahana Rao53bd1f62019-12-27 20:18:39 +00001234 while (h->next_off < num_directory_entries) {
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001235 de = h->de[h->next_off];
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001236 entry_size = 0;
1237 h->next_off++;
shafik1e3a2672019-08-16 14:51:55 +01001238 if (plus) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001239 int error_code = 0;
1240 if (do_lookup(req, ino, de->d_name.c_str(), &e, &error_code)) {
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001241 entry_size = fuse_add_direntry_plus(req, buf + used, len - used, de->d_name.c_str(),
1242 &e, h->next_off);
Sahana Rao8a588e72019-12-06 11:32:56 +00001243 } else {
Sahana Rao8d8dbb42019-12-18 12:57:02 +00001244 // Ignore lookup errors on
1245 // 1. non-existing files returned from MediaProvider database.
1246 // 2. path that doesn't match FuseDaemon UID and calling uid.
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001247 if (error_code == ENOENT || error_code == EPERM) continue;
1248 fuse_reply_err(req, error_code);
shafik1e3a2672019-08-16 14:51:55 +01001249 return;
1250 }
1251 } else {
1252 e.attr.st_ino = FUSE_UNKNOWN_INO;
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001253 e.attr.st_mode = de->d_type;
1254 entry_size = fuse_add_direntry(req, buf + used, len - used, de->d_name.c_str(), &e.attr,
1255 h->next_off);
shafik1e3a2672019-08-16 14:51:55 +01001256 }
Sahana Rao6f9ea982019-09-20 12:21:33 +01001257 // If buffer in fuse_add_direntry[_plus] is not large enough then
1258 // the entry is not added to buffer but the size of the entry is still
1259 // returned. Check available buffer size + returned entry size is less
1260 // than actual buffer size to confirm entry is added to buffer.
Sahana Rao43927f02019-12-10 22:59:01 +00001261 if (used + entry_size > len) {
1262 // When an entry is rejected, lookup called by readdir_plus will not be tracked by
1263 // kernel. Call forget on the rejected node to decrement the reference count.
Narayan Kamathd6219842019-12-27 17:44:35 +00001264 if (plus) {
Narayan Kamathaef84a12020-01-02 15:20:13 +00001265 do_forget(fuse, e.ino, 1);
Narayan Kamathd6219842019-12-27 17:44:35 +00001266 }
Sahana Rao43927f02019-12-10 22:59:01 +00001267 break;
1268 }
Sahana Rao6f9ea982019-09-20 12:21:33 +01001269 used += entry_size;
shafik1e3a2672019-08-16 14:51:55 +01001270 }
Sahana Rao53bd1f62019-12-27 20:18:39 +00001271 fuse_reply_buf(req, buf, used);
shafik1e3a2672019-08-16 14:51:55 +01001272}
1273
1274static void pf_readdir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off,
1275 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001276 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001277 do_readdir_common(req, ino, size, off, fi, false);
1278}
1279
1280static void pf_readdirplus(fuse_req_t req,
1281 fuse_ino_t ino,
1282 size_t size,
1283 off_t off,
1284 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001285 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001286 do_readdir_common(req, ino, size, off, fi, true);
1287}
1288
1289static void pf_releasedir(fuse_req_t req,
1290 fuse_ino_t ino,
1291 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001292 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001293 struct fuse* fuse = get_fuse(req);
shafik1e3a2672019-08-16 14:51:55 +01001294
Narayan Kamathaef84a12020-01-02 15:20:13 +00001295 node* node = fuse->FromInode(ino);
1296 dirhandle* h = reinterpret_cast<dirhandle*>(fi->fh);
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001297 TRACE_FUSE(fuse) << "RELEASEDIR " << h;
Narayan Kamathaef84a12020-01-02 15:20:13 +00001298 if (node) {
1299 node->DestroyDirHandle(h);
Zimedbe69e2019-12-13 18:49:36 +00001300 }
Zimedbe69e2019-12-13 18:49:36 +00001301
shafik1e3a2672019-08-16 14:51:55 +01001302 fuse_reply_err(req, 0);
1303}
1304
1305static void pf_statfs(fuse_req_t req, fuse_ino_t ino) {
Zimec8d5722019-12-05 07:26:13 +00001306 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001307 struct statvfs st;
1308 struct fuse* fuse = get_fuse(req);
1309
Narayan Kamathaef84a12020-01-02 15:20:13 +00001310 if (statvfs(fuse->root->GetName().c_str(), &st))
shafik1e3a2672019-08-16 14:51:55 +01001311 fuse_reply_err(req, errno);
1312 else
1313 fuse_reply_statfs(req, &st);
1314}
1315/*
1316static void pf_setxattr(fuse_req_t req, fuse_ino_t ino, const char* name,
1317 const char* value, size_t size, int flags)
1318{
1319 cout << "TODO:" << __func__;
1320}
1321
1322static void pf_getxattr(fuse_req_t req, fuse_ino_t ino, const char* name,
1323 size_t size)
1324{
1325 cout << "TODO:" << __func__;
1326}
1327
1328static void pf_listxattr(fuse_req_t req, fuse_ino_t ino, size_t size)
1329{
1330 cout << "TODO:" << __func__;
1331}
1332
1333static void pf_removexattr(fuse_req_t req, fuse_ino_t ino, const char* name)
1334{
1335 cout << "TODO:" << __func__;
Zima9fcd552019-08-29 15:17:04 +01001336}*/
1337
1338static void pf_access(fuse_req_t req, fuse_ino_t ino, int mask) {
Zimec8d5722019-12-05 07:26:13 +00001339 ATRACE_CALL();
Zima9fcd552019-08-29 15:17:04 +01001340 struct fuse* fuse = get_fuse(req);
1341 const struct fuse_ctx* ctx = fuse_req_ctx(req);
1342
Narayan Kamathaef84a12020-01-02 15:20:13 +00001343 node* node = fuse->FromInode(ino);
1344 const string path = node->BuildPath();
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001345 TRACE_FUSE_VERBOSE(fuse) << "ACCESS " << path;
Zima9fcd552019-08-29 15:17:04 +01001346
1347 int res = access(path.c_str(), F_OK);
1348 fuse_reply_err(req, res ? errno : 0);
shafik1e3a2672019-08-16 14:51:55 +01001349}
Zima9fcd552019-08-29 15:17:04 +01001350
shafik1e3a2672019-08-16 14:51:55 +01001351static void pf_create(fuse_req_t req,
1352 fuse_ino_t parent,
1353 const char* name,
1354 mode_t mode,
1355 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001356 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001357 struct fuse* fuse = get_fuse(req);
1358 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001359 node* parent_node = fuse->FromInode(parent);
1360 const string parent_path = parent_node->BuildPath();
shafik1e3a2672019-08-16 14:51:55 +01001361
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001362 TRACE_FUSE(fuse) << "CREATE " << name << " 0" << std::oct << fi->flags << " @ " << parent
1363 << " (" << safe_name(parent_node) << ")";
shafik1e3a2672019-08-16 14:51:55 +01001364
Narayan Kamathaef84a12020-01-02 15:20:13 +00001365 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +01001366
shafike4fb1462020-01-29 16:25:23 +00001367 int mp_return_code = fuse->mp->InsertFile(child_path.c_str(), ctx->uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001368 if (mp_return_code) {
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001369 PLOG(DEBUG) << "Could not create file: " << child_path;
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001370 fuse_reply_err(req, mp_return_code);
shafik1e3a2672019-08-16 14:51:55 +01001371 return;
1372 }
1373
Martijn Coenen2d7f1be2020-02-15 07:44:12 +01001374 // With the writeback cache enabled, FUSE may generate READ requests even for files that
1375 // were opened O_WRONLY; so make sure we open it O_RDWR instead.
1376 int open_flags = fi->flags;
1377 if (open_flags & O_WRONLY) {
1378 open_flags &= ~O_WRONLY;
1379 open_flags |= O_RDWR;
1380 }
1381
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001382 mode = (mode & (~0777)) | 0664;
Martijn Coenen2d7f1be2020-02-15 07:44:12 +01001383 int fd = open(child_path.c_str(), open_flags, mode);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001384 if (fd < 0) {
1385 int error_code = errno;
1386 // We've already inserted the file into the MP database before the
1387 // failed open(), so that needs to be rolled back here.
1388 fuse->mp->DeleteFile(child_path.c_str(), ctx->uid);
1389 fuse_reply_err(req, error_code);
1390 return;
1391 }
1392
Narayan Kamathbd22bb02020-01-08 16:02:50 +00001393 // TODO(b/147274248): Assume there will be no EXIF to redact.
Zim57a75352020-01-07 08:19:18 +00001394 // This prevents crashing during reads but can be a security hole if a malicious app opens an fd
1395 // to the file before all the EXIF content is written. We could special case reads before the
1396 // first close after a file has just been created.
Sahana Raoc0211d12020-02-17 10:11:56 +00001397 handle* h = new handle(child_path, fd, new RedactionInfo(), ctx->uid, /*cached*/ true);
shafik1e3a2672019-08-16 14:51:55 +01001398 fi->fh = ptr_to_id(h);
Zim61d12342019-10-01 15:47:45 +01001399 fi->keep_cache = 1;
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001400
1401 int error_code = 0;
Narayan Kamathaef84a12020-01-02 15:20:13 +00001402 struct fuse_entry_param e;
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001403 node* node = make_node_entry(req, parent_node, name, child_path, &e, &error_code);
Zimedbe69e2019-12-13 18:49:36 +00001404 if (node) {
Narayan Kamathaef84a12020-01-02 15:20:13 +00001405 node->AddHandle(h);
shafik1e3a2672019-08-16 14:51:55 +01001406 fuse_reply_create(req, &e, fi);
1407 } else {
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001408 CHECK(error_code != 0);
1409 fuse_reply_err(req, error_code);
shafik1e3a2672019-08-16 14:51:55 +01001410 }
1411}
1412/*
1413static void pf_getlk(fuse_req_t req, fuse_ino_t ino,
1414 struct fuse_file_info* fi, struct flock* lock)
1415{
1416 cout << "TODO:" << __func__;
1417}
1418
1419static void pf_setlk(fuse_req_t req, fuse_ino_t ino,
1420 struct fuse_file_info* fi,
1421 struct flock* lock, int sleep)
1422{
1423 cout << "TODO:" << __func__;
1424}
1425
1426static void pf_bmap(fuse_req_t req, fuse_ino_t ino, size_t blocksize,
1427 uint64_t idx)
1428{
1429 cout << "TODO:" << __func__;
1430}
1431
1432static void pf_ioctl(fuse_req_t req, fuse_ino_t ino, unsigned int cmd,
1433 void* arg, struct fuse_file_info* fi, unsigned flags,
1434 const void* in_buf, size_t in_bufsz, size_t out_bufsz)
1435{
1436 cout << "TODO:" << __func__;
1437}
1438
1439static void pf_poll(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi,
1440 struct fuse_pollhandle* ph)
1441{
1442 cout << "TODO:" << __func__;
1443}
1444
1445static void pf_retrieve_reply(fuse_req_t req, void* cookie, fuse_ino_t ino,
1446 off_t offset, struct fuse_bufvec* bufv)
1447{
1448 cout << "TODO:" << __func__;
1449}
1450
1451static void pf_flock(fuse_req_t req, fuse_ino_t ino,
1452 struct fuse_file_info* fi, int op)
1453{
1454 cout << "TODO:" << __func__;
1455}
1456
1457static void pf_fallocate(fuse_req_t req, fuse_ino_t ino, int mode,
1458 off_t offset, off_t length, struct fuse_file_info* fi)
1459{
1460 cout << "TODO:" << __func__;
1461}
1462*/
1463
1464static struct fuse_lowlevel_ops ops{
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001465 .init = pf_init,
1466 .destroy = pf_destroy,
1467 .lookup = pf_lookup, .forget = pf_forget, .getattr = pf_getattr,
1468 .setattr = pf_setattr,
1469 .canonical_path = pf_canonical_path,
1470 .mknod = pf_mknod, .mkdir = pf_mkdir, .unlink = pf_unlink,
1471 .rmdir = pf_rmdir,
shafik8b57cd52019-09-06 10:51:29 +01001472 /*.symlink = pf_symlink,*/
1473 .rename = pf_rename,
1474 /*.link = pf_link,*/
1475 .open = pf_open, .read = pf_read,
1476 /*.write = pf_write,*/
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001477 .flush = pf_flush, .release = pf_release, .fsync = pf_fsync,
1478 .opendir = pf_opendir, .readdir = pf_readdir, .releasedir = pf_releasedir,
1479 .fsyncdir = pf_fsyncdir, .statfs = pf_statfs,
shafik8b57cd52019-09-06 10:51:29 +01001480 /*.setxattr = pf_setxattr,
1481 .getxattr = pf_getxattr,
1482 .listxattr = pf_listxattr,
1483 .removexattr = pf_removexattr,*/
1484 .access = pf_access, .create = pf_create,
1485 /*.getlk = pf_getlk,
1486 .setlk = pf_setlk,
1487 .bmap = pf_bmap,
1488 .ioctl = pf_ioctl,
Nick Desaulniers17714b82019-11-05 09:44:35 -08001489 .poll = pf_poll,*/
1490 .write_buf = pf_write_buf,
1491 /*.retrieve_reply = pf_retrieve_reply,*/
1492 .forget_multi = pf_forget_multi,
shafik8b57cd52019-09-06 10:51:29 +01001493 /*.flock = pf_flock,
1494 .fallocate = pf_fallocate,*/
Nick Desaulniers17714b82019-11-05 09:44:35 -08001495 .readdirplus = pf_readdirplus,
1496 /*.copy_file_range = pf_copy_file_range,*/
shafik1e3a2672019-08-16 14:51:55 +01001497};
1498
1499static struct fuse_loop_config config = {
Zim549f9da2020-02-09 13:54:22 +00001500 .clone_fd = 1,
shafik1e3a2672019-08-16 14:51:55 +01001501 .max_idle_threads = 10,
1502};
1503
Zimb353eb42019-12-17 15:29:48 +00001504static std::unordered_map<enum fuse_log_level, enum android_LogPriority> fuse_to_android_loglevel({
1505 {FUSE_LOG_EMERG, ANDROID_LOG_FATAL},
1506 {FUSE_LOG_ALERT, ANDROID_LOG_ERROR},
1507 {FUSE_LOG_CRIT, ANDROID_LOG_ERROR},
1508 {FUSE_LOG_ERR, ANDROID_LOG_ERROR},
1509 {FUSE_LOG_WARNING, ANDROID_LOG_WARN},
1510 {FUSE_LOG_NOTICE, ANDROID_LOG_INFO},
1511 {FUSE_LOG_INFO, ANDROID_LOG_DEBUG},
1512 {FUSE_LOG_DEBUG, ANDROID_LOG_VERBOSE},
1513 });
Zim724b8ca2019-11-09 09:37:24 +00001514
1515static void fuse_logger(enum fuse_log_level level, const char* fmt, va_list ap) {
Zim357e3072020-01-15 10:50:01 +00001516 __android_log_vprint(fuse_to_android_loglevel.at(level), LIBFUSE_LOG_TAG, fmt, ap);
Zim724b8ca2019-11-09 09:37:24 +00001517}
1518
Zimedbe69e2019-12-13 18:49:36 +00001519bool FuseDaemon::ShouldOpenWithFuse(int fd, bool for_read, const std::string& path) {
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001520 TRACE_VERBOSE << "Checking if file should be opened with FUSE " << path;
Zimedbe69e2019-12-13 18:49:36 +00001521 bool use_fuse = false;
1522
1523 if (active.load(std::memory_order_acquire)) {
Narayan Kamathaef84a12020-01-02 15:20:13 +00001524 const node* node = node::LookupAbsolutePath(fuse->root, path);
Zimedbe69e2019-12-13 18:49:36 +00001525 if (node && node->HasCachedHandle()) {
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001526 TRACE << "Should open " << path << " with FUSE. Reason: cache";
Zimedbe69e2019-12-13 18:49:36 +00001527 use_fuse = true;
1528 } else {
1529 // If we are unable to set a lock, we should use fuse since we can't track
1530 // when all fd references (including dups) are closed. This can happen when
1531 // we try to set a write lock twice on the same file
1532 use_fuse = set_file_lock(fd, for_read, path);
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001533 TRACE << "Should open " << path << (use_fuse ? " with" : " without")
1534 << " FUSE. Reason: lock";
Zimedbe69e2019-12-13 18:49:36 +00001535 }
Zimedbe69e2019-12-13 18:49:36 +00001536 } else {
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001537 TRACE << "FUSE daemon is inactive. Should not open " << path << " with FUSE";
Zimedbe69e2019-12-13 18:49:36 +00001538 }
1539
1540 return use_fuse;
1541}
1542
Zima76c3492020-02-19 01:23:26 +00001543void FuseDaemon::InvalidateFuseDentryCache(const std::string& path) {
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001544 TRACE_VERBOSE << "Invalidating dentry for path " << path;
1545
Zima76c3492020-02-19 01:23:26 +00001546 if (active.load(std::memory_order_acquire)) {
1547 string name;
1548 fuse_ino_t parent;
1549
1550 {
1551 std::lock_guard<std::recursive_mutex> guard(fuse->lock);
1552 const node* node = node::LookupAbsolutePath(fuse->root, path);
1553 if (node) {
1554 name = node->GetName();
1555 parent = fuse->ToInode(node->GetParent());
1556 }
1557 }
1558
1559 if (!name.empty() &&
1560 fuse_lowlevel_notify_inval_entry(fuse->se, parent, name.c_str(), name.size())) {
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001561 LOG(ERROR) << "Failed to invalidate dentry for path " << path;
Zima76c3492020-02-19 01:23:26 +00001562 }
1563 } else {
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001564 TRACE << "FUSE daemon is inactive. Cannot invalidate dentry for " << path;
Zima76c3492020-02-19 01:23:26 +00001565 }
1566}
1567
Zimedbe69e2019-12-13 18:49:36 +00001568FuseDaemon::FuseDaemon(JNIEnv* env, jobject mediaProvider) : mp(env, mediaProvider),
1569 active(false), fuse(nullptr) {}
shafik1e3a2672019-08-16 14:51:55 +01001570
Zim7c8712d2019-10-03 21:01:26 +01001571void FuseDaemon::Start(const int fd, const std::string& path) {
shafik1e3a2672019-08-16 14:51:55 +01001572 struct fuse_args args;
1573 struct fuse_cmdline_opts opts;
shafik1e3a2672019-08-16 14:51:55 +01001574
Zimd3e957c2020-01-29 02:42:05 +00001575 SetMinimumLogSeverity(android::base::VERBOSE);
shafik458d1102019-09-06 18:21:36 +01001576
shafik1e3a2672019-08-16 14:51:55 +01001577 struct stat stat;
shafik1e3a2672019-08-16 14:51:55 +01001578
Zim7c8712d2019-10-03 21:01:26 +01001579 if (lstat(path.c_str(), &stat)) {
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001580 LOG(ERROR) << "ERROR: failed to stat source " << path;
Zim3e45d9b2019-08-19 21:14:14 +01001581 return;
1582 }
shafik1e3a2672019-08-16 14:51:55 +01001583
Zim3e45d9b2019-08-19 21:14:14 +01001584 if (!S_ISDIR(stat.st_mode)) {
Cody Schuffelen338bd1a2020-02-21 17:40:56 +00001585 LOG(ERROR) << "ERROR: source is not a directory";
Zim3e45d9b2019-08-19 21:14:14 +01001586 return;
1587 }
shafik1e3a2672019-08-16 14:51:55 +01001588
1589 args = FUSE_ARGS_INIT(0, nullptr);
Zim7c8712d2019-10-03 21:01:26 +01001590 if (fuse_opt_add_arg(&args, path.c_str()) || fuse_opt_add_arg(&args, "-odebug") ||
1591 fuse_opt_add_arg(&args, ("-omax_read=" + std::to_string(MAX_READ_SIZE)).c_str())) {
shafik458d1102019-09-06 18:21:36 +01001592 LOG(ERROR) << "ERROR: failed to set options";
shafik1e3a2672019-08-16 14:51:55 +01001593 return;
1594 }
1595
Narayan Kamathaef84a12020-01-02 15:20:13 +00001596 struct fuse fuse_default(path);
shafikc3f62672019-08-30 11:15:48 +01001597 fuse_default.mp = &mp;
Zimedbe69e2019-12-13 18:49:36 +00001598 // fuse_default is stack allocated, but it's safe to save it as an instance variable because
1599 // this method blocks and FuseDaemon#active tells if we are currently blocking
1600 fuse = &fuse_default;
shafikc3f62672019-08-30 11:15:48 +01001601
shafikb334a612019-09-30 20:38:16 +01001602 // Used by pf_read: redacted ranges are represented by zeroized ranges of bytes,
1603 // so we mmap the maximum length of redacted ranges in the beginning and save memory allocations
1604 // on each read.
1605 fuse_default.zero_addr = static_cast<char*>(mmap(
1606 NULL, MAX_READ_SIZE, PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, /*fd*/ -1, /*off*/ 0));
1607 if (fuse_default.zero_addr == MAP_FAILED) {
1608 LOG(FATAL) << "mmap failed - could not start fuse! errno = " << errno;
1609 }
1610
Zim7c8712d2019-10-03 21:01:26 +01001611 umask(0);
1612
Zim724b8ca2019-11-09 09:37:24 +00001613 // Custom logging for libfuse
Zim724b8ca2019-11-09 09:37:24 +00001614 fuse_set_log_func(fuse_logger);
1615
shafik1e3a2672019-08-16 14:51:55 +01001616 struct fuse_session
1617 * se = fuse_session_new(&args, &ops, sizeof(ops), &fuse_default);
Zim7e0d3142019-10-17 21:06:12 +01001618 if (!se) {
1619 PLOG(ERROR) << "Failed to create session ";
1620 return;
1621 }
Zima76c3492020-02-19 01:23:26 +00001622 fuse_default.se = se;
shafik1e3a2672019-08-16 14:51:55 +01001623 se->fd = fd;
Zim7c8712d2019-10-03 21:01:26 +01001624 se->mountpoint = strdup(path.c_str());
Zim3e45d9b2019-08-19 21:14:14 +01001625
1626 // Single thread. Useful for debugging
1627 // fuse_session_loop(se);
1628 // Multi-threaded
Zim7e0d3142019-10-17 21:06:12 +01001629 LOG(INFO) << "Starting fuse...";
Zimedbe69e2019-12-13 18:49:36 +00001630 active.store(true, std::memory_order_release);
shafik1e3a2672019-08-16 14:51:55 +01001631 fuse_session_loop_mt(se, &config);
Zim7e0d3142019-10-17 21:06:12 +01001632 LOG(INFO) << "Ending fuse...";
Zim3e45d9b2019-08-19 21:14:14 +01001633
Zim7c8712d2019-10-03 21:01:26 +01001634 if (munmap(fuse_default.zero_addr, MAX_READ_SIZE)) {
1635 PLOG(ERROR) << "munmap failed!";
shafikb334a612019-09-30 20:38:16 +01001636 }
1637
Zim7e0d3142019-10-17 21:06:12 +01001638 fuse_opt_free_args(&args);
1639 fuse_session_destroy(se);
Zimedbe69e2019-12-13 18:49:36 +00001640 active.store(false, std::memory_order_relaxed);
Zim7e0d3142019-10-17 21:06:12 +01001641 LOG(INFO) << "Ended fuse";
1642 return;
shafik1e3a2672019-08-16 14:51:55 +01001643}
1644} //namespace fuse
shafik8b57cd52019-09-06 10:51:29 +01001645} // namespace mediaprovider