blob: 8c9608887bf84f0753aa8b5017a37020a85d5d35 [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.
shafik458d1102019-09-06 18:21:36 +010077#define TRACE LOG(DEBUG)
Zim357e3072020-01-15 10:50:01 +000078#define TRACE_VERBOSE LOG(VERBOSE)
Zim7c8712d2019-10-03 21:01:26 +010079#define TRACE_FUSE(__fuse) TRACE << "[" << __fuse->path << "] "
Zim357e3072020-01-15 10:50:01 +000080#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;
shafikb334a612019-09-30 20:38:16 +0100101
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200102/*
103 * In order to avoid double caching with fuse, call fadvise on the file handles
104 * in the underlying file system. However, if this is done on every read/write,
105 * the fadvises cause a very significant slowdown in tests (specifically fio
106 * seq_write). So call fadvise on the file handles with the most reads/writes
107 * only after a threshold is passed.
108 */
109class FAdviser {
110 public:
111 FAdviser() : thread_(MessageLoop, this), total_size_(0) {}
112
113 ~FAdviser() {
114 SendMessage(Message::quit);
115 thread_.join();
116 }
117
118 void Record(int fd, size_t size) { SendMessage(Message::record, fd, size); }
119
120 void Close(int fd) { SendMessage(Message::close, fd); }
121
122 private:
123 std::thread thread_;
124
125 struct Message {
126 enum Type { record, close, quit };
127 Type type;
128 int fd;
129 size_t size;
130 };
131
132 void RecordImpl(int fd, size_t size) {
133 total_size_ += size;
134
135 // Find or create record in files_
136 // Remove record from sizes_ if it exists, adjusting size appropriately
137 auto file = files_.find(fd);
138 if (file != files_.end()) {
139 auto old_size = file->second;
140 size += old_size->first;
141 sizes_.erase(old_size);
142 } else {
143 file = files_.insert(Files::value_type(fd, sizes_.end())).first;
144 }
145
146 // Now (re) insert record in sizes_
147 auto new_size = sizes_.insert(Sizes::value_type(size, fd));
148 file->second = new_size;
149
150 if (total_size_ < threshold_) return;
151
152 LOG(INFO) << "Threshold exceeded - fadvising " << total_size_;
153 while (!sizes_.empty() && total_size_ > target_) {
154 auto size = --sizes_.end();
155 total_size_ -= size->first;
156 posix_fadvise(size->second, 0, 0, POSIX_FADV_DONTNEED);
157 files_.erase(size->second);
158 sizes_.erase(size);
159 }
160 LOG(INFO) << "Threshold now " << total_size_;
161 }
162
163 void CloseImpl(int fd) {
164 auto file = files_.find(fd);
165 if (file == files_.end()) return;
166
167 total_size_ -= file->second->first;
168 sizes_.erase(file->second);
169 files_.erase(file);
170 }
171
172 void MessageLoopImpl() {
173 while (1) {
174 Message message;
175
176 {
177 std::unique_lock<std::mutex> lock(mutex_);
178 cv_.wait(lock, [this] { return !queue_.empty(); });
179 message = queue_.front();
180 queue_.pop();
181 }
182
183 switch (message.type) {
184 case Message::record:
185 RecordImpl(message.fd, message.size);
186 break;
187
188 case Message::close:
189 CloseImpl(message.fd);
190 break;
191
192 case Message::quit:
193 return;
194 }
195 }
196 }
197
198 static int MessageLoop(FAdviser* ptr) {
199 ptr->MessageLoopImpl();
200 return 0;
201 }
202
203 void SendMessage(Message::Type type, int fd = -1, size_t size = 0) {
204 {
205 std::unique_lock<std::mutex> lock(mutex_);
206 Message message = {type, fd, size};
207 queue_.push(message);
208 }
209 cv_.notify_one();
210 }
211
212 std::queue<Message> queue_;
213 std::mutex mutex_;
214 std::condition_variable cv_;
215
216 typedef std::multimap<size_t, int> Sizes;
217 typedef std::map<int, Sizes::iterator> Files;
218
219 Files files_;
220 Sizes sizes_;
221 size_t total_size_;
222
223 const size_t threshold_ = 64 * 1024 * 1024;
224 const size_t target_ = 32 * 1024 * 1024;
225};
226
Narayan Kamath92bf67b2020-01-03 17:49:09 +0000227// Whether inode tracking is enabled or not. When enabled, we maintain a
228// separate mapping from inode numbers to "live" nodes so we can detect when
229// we receive a request to a node that has been deleted.
230static constexpr bool kEnableInodeTracking = true;
231
shafik1e3a2672019-08-16 14:51:55 +0100232/* Single FUSE mount */
233struct fuse {
Narayan Kamathaef84a12020-01-02 15:20:13 +0000234 explicit fuse(const std::string& _path)
235 : path(_path), root(node::CreateRoot(_path, &lock)), mp(0), zero_addr(0) {}
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200236
Narayan Kamathaef84a12020-01-02 15:20:13 +0000237 inline bool IsRoot(const node* node) const { return node == root; }
shafik1e3a2672019-08-16 14:51:55 +0100238
Narayan Kamathaef84a12020-01-02 15:20:13 +0000239 // Note that these two (FromInode / ToInode) conversion wrappers are required
240 // because fuse_lowlevel_ops documents that the root inode is always one
241 // (see FUSE_ROOT_ID in fuse_lowlevel.h). There are no particular requirements
242 // on any of the other inodes in the FS.
Narayan Kamath92bf67b2020-01-03 17:49:09 +0000243 inline node* FromInode(__u64 inode) {
Narayan Kamathaef84a12020-01-02 15:20:13 +0000244 if (inode == FUSE_ROOT_ID) {
245 return root;
246 }
shafik1e3a2672019-08-16 14:51:55 +0100247
Narayan Kamath92bf67b2020-01-03 17:49:09 +0000248 node* node = node::FromInode(inode);
249
250 if (kEnableInodeTracking) {
251 std::lock_guard<std::recursive_mutex> guard(lock);
252 CHECK(inode_tracker_.find(node) != inode_tracker_.end());
253 }
254
255 return node;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000256 }
257
258 inline __u64 ToInode(node* node) const {
259 if (IsRoot(node)) {
260 return FUSE_ROOT_ID;
261 }
262
263 return node::ToInode(node);
264 }
265
Narayan Kamath92bf67b2020-01-03 17:49:09 +0000266 // Notify this FUSE instance that one of its nodes has been deleted.
267 void NodeDeleted(const node* node) {
268 if (kEnableInodeTracking) {
269 LOG(INFO) << "Node: " << node << " deleted.";
270
271 std::lock_guard<std::recursive_mutex> guard(lock);
272 inode_tracker_.erase(node);
273 }
274 }
275
276 // Notify this FUSE instance that a new nodes has been created.
277 void NodeCreated(const node* node) {
278 if (kEnableInodeTracking) {
279 LOG(INFO) << "Node: " << node << " created.";
280
281 std::lock_guard<std::recursive_mutex> guard(lock);
282 inode_tracker_.insert(node);
283 }
284 }
285
Narayan Kamathaef84a12020-01-02 15:20:13 +0000286 std::recursive_mutex lock;
287 const string path;
288 node* const root;
shafikc3f62672019-08-30 11:15:48 +0100289
290 /*
291 * Used to make JNI calls to MediaProvider.
292 * Responsibility of freeing this object falls on corresponding
293 * FuseDaemon object.
294 */
295 mediaprovider::fuse::MediaProviderWrapper* mp;
shafikb334a612019-09-30 20:38:16 +0100296
297 /*
298 * Points to a range of zeroized bytes, used by pf_read to represent redacted ranges.
299 * The memory is read only and should never be modified.
300 */
Narayan Kamathaef84a12020-01-02 15:20:13 +0000301 /* const */ char* zero_addr;
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200302
303 FAdviser fadviser;
Narayan Kamath92bf67b2020-01-03 17:49:09 +0000304
305 std::unordered_set<const node*> inode_tracker_;
shafik1e3a2672019-08-16 14:51:55 +0100306};
307
Narayan Kamathaef84a12020-01-02 15:20:13 +0000308static inline const char* safe_name(node* n) {
309 return n ? n->GetName().c_str() : "?";
shafik458d1102019-09-06 18:21:36 +0100310}
311
shafik1e3a2672019-08-16 14:51:55 +0100312static inline __u64 ptr_to_id(void* ptr) {
313 return (__u64)(uintptr_t) ptr;
314}
315
Zimedbe69e2019-12-13 18:49:36 +0000316/*
317 * Set an F_RDLCK or F_WRLCKK on fd with fcntl(2).
318 *
319 * This is called before the MediaProvider returns fd from the lower file
320 * system to an app over the ContentResolver interface. This allows us
321 * check with is_file_locked if any reference to that fd is still open.
322 */
323static int set_file_lock(int fd, bool for_read, const std::string& path) {
324 std::string lock_str = (for_read ? "read" : "write");
Zim5c57d832020-01-15 16:16:12 +0000325 TRACE_VERBOSE << "Setting " << lock_str << " lock for path " << path;
Zimedbe69e2019-12-13 18:49:36 +0000326
327 struct flock fl{};
328 fl.l_type = for_read ? F_RDLCK : F_WRLCK;
329 fl.l_whence = SEEK_SET;
330
331 int res = fcntl(fd, F_OFD_SETLK, &fl);
332 if (res) {
333 PLOG(ERROR) << "Failed to set " << lock_str << " lock on path " << path;
334 return res;
335 }
Zim5c57d832020-01-15 16:16:12 +0000336 TRACE_VERBOSE << "Successfully set " << lock_str << " lock on path " << path;
Zimedbe69e2019-12-13 18:49:36 +0000337 return res;
338}
339
340/*
341 * Check if an F_RDLCK or F_WRLCK is set on fd with fcntl(2).
342 *
343 * This is used to determine if the MediaProvider has given an fd to the lower fs to an app over
344 * the ContentResolver interface. Before that happens, we always call set_file_lock on the file
345 * allowing us to know if any reference to that fd is still open here.
346 *
347 * Returns true if fd may have a lock, false otherwise
348 */
349static bool is_file_locked(int fd, const std::string& path) {
Zim5c57d832020-01-15 16:16:12 +0000350 TRACE_VERBOSE << "Checking if file is locked " << path;
Zimedbe69e2019-12-13 18:49:36 +0000351
352 struct flock fl{};
353 fl.l_type = F_WRLCK;
354 fl.l_whence = SEEK_SET;
355
356 int res = fcntl(fd, F_OFD_GETLK, &fl);
357 if (res) {
358 PLOG(ERROR) << "Failed to check lock for file " << path;
359 // Assume worst
360 return true;
361 }
362 bool locked = fl.l_type != F_UNLCK;
Zim5c57d832020-01-15 16:16:12 +0000363 TRACE_VERBOSE << "File " << path << " is " << (locked ? "locked" : "unlocked");
Zimedbe69e2019-12-13 18:49:36 +0000364 return locked;
365}
366
shafik1e3a2672019-08-16 14:51:55 +0100367static struct fuse* get_fuse(fuse_req_t req) {
368 return reinterpret_cast<struct fuse*>(fuse_req_userdata(req));
369}
370
Narayan Kamathaef84a12020-01-02 15:20:13 +0000371static node* make_node_entry(fuse_req_t req, node* parent, const string& name, const string& path,
372 struct fuse_entry_param* e, int* error_code) {
shafik1e3a2672019-08-16 14:51:55 +0100373 struct fuse* fuse = get_fuse(req);
Martijn Coenenb8ff4eb2019-12-17 09:55:17 +0100374 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000375 node* node;
shafik1e3a2672019-08-16 14:51:55 +0100376
Jeff Sharkey7469b982019-08-28 16:51:02 -0600377 memset(e, 0, sizeof(*e));
shafik1e3a2672019-08-16 14:51:55 +0100378 if (lstat(path.c_str(), &e->attr) < 0) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000379 *error_code = errno;
shafik1e3a2672019-08-16 14:51:55 +0100380 return NULL;
381 }
382
Narayan Kamathaef84a12020-01-02 15:20:13 +0000383 node = parent->LookupChildByName(name);
384 if (node) {
385 node->Acquire();
386 } else {
387 node = ::node::Create(parent, name, &fuse->lock);
Narayan Kamath92bf67b2020-01-03 17:49:09 +0000388 fuse->NodeCreated(node);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000389 }
shafik1e3a2672019-08-16 14:51:55 +0100390
391 // Manipulate attr here if needed
shafik1e3a2672019-08-16 14:51:55 +0100392 e->attr_timeout = 10;
Martijn Coenenb8ff4eb2019-12-17 09:55:17 +0100393 int user_id = ctx->uid / PER_USER_RANGE;
394 const std::string android_path = fuse->path + "/" + std::to_string(user_id) + "/Android";
Zim6d0a3f12019-12-13 10:48:03 +0000395 // Ensure the VFS does not cache dentries, if it caches, the following scenario could occur:
396 // 1. Process A has access to file A and does a lookup
397 // 2. Process B does not have access to file A and does a lookup
398 // (2) will succeed because the lookup request will not be sent from kernel to the FUSE daemon
399 // and the kernel will respond from cache. Even if this by itself is not a security risk
400 // because subsequent FUSE requests will fail if B does not have access to the resource.
401 // It does cause indeterministic behavior because whether (2) succeeds or not depends on if
402 // (1) occurred.
Martijn Coenenb8ff4eb2019-12-17 09:55:17 +0100403 // We prevent this caching by setting the entry_timeout value to 0.
404 // The /0 and /0/Android paths are exempt, as they are visible to all apps.
Narayan Kamathaef84a12020-01-02 15:20:13 +0000405 if (fuse->IsRoot(parent) || path.rfind(android_path, 0) == 0) {
Martijn Coenenb8ff4eb2019-12-17 09:55:17 +0100406 e->entry_timeout = 10;
407 } else {
408 e->entry_timeout = 0;
409 }
Narayan Kamathaef84a12020-01-02 15:20:13 +0000410 e->ino = fuse->ToInode(node);
Narayan Kamathfc0aa952019-12-31 13:31:49 +0000411 // This FS is not being exported via NFS so just a fixed generation number
412 // for now. If we do need this, we need to increment the generation ID each
413 // time the fuse daemon restarts because that's what it takes for us to
414 // reuse inode numbers.
415 e->generation = 0;
shafik1e3a2672019-08-16 14:51:55 +0100416
417 return node;
418}
419
shafik15e2d612019-10-31 20:10:25 +0000420static inline bool is_requesting_write(int flags) {
421 return flags & (O_WRONLY | O_RDWR);
422}
423
shafik1e3a2672019-08-16 14:51:55 +0100424namespace mediaprovider {
425namespace fuse {
426
427/**
428 * Function implementations
429 *
430 * These implement the various functions in fuse_lowlevel_ops
431 *
432 */
433
434static void pf_init(void* userdata, struct fuse_conn_info* conn) {
Zima9fcd552019-08-29 15:17:04 +0100435 // We don't want a getattr request with every read request
436 conn->want &= ~FUSE_CAP_AUTO_INVAL_DATA;
shafik8b57cd52019-09-06 10:51:29 +0100437 unsigned mask = (FUSE_CAP_SPLICE_WRITE | FUSE_CAP_SPLICE_MOVE | FUSE_CAP_SPLICE_READ |
438 FUSE_CAP_ASYNC_READ | FUSE_CAP_ATOMIC_O_TRUNC | FUSE_CAP_WRITEBACK_CACHE |
439 FUSE_CAP_EXPORT_SUPPORT | FUSE_CAP_FLOCK_LOCKS);
shafik1e3a2672019-08-16 14:51:55 +0100440 conn->want |= conn->capable & mask;
shafikb334a612019-09-30 20:38:16 +0100441 conn->max_read = MAX_READ_SIZE;
shafik1e3a2672019-08-16 14:51:55 +0100442}
443
Zim005cd812019-12-17 15:35:51 +0000444static void pf_destroy(void* userdata) {
445 struct fuse* fuse = reinterpret_cast<struct fuse*>(userdata);
446 LOG(INFO) << "DESTROY " << fuse->path;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000447
448 node::DeleteTree(fuse->root);
shafik1e3a2672019-08-16 14:51:55 +0100449}
shafik1e3a2672019-08-16 14:51:55 +0100450
Zim859db932019-12-13 00:09:17 +0000451static std::regex storage_emulated_regex("^\\/storage\\/emulated\\/([0-9]+)");
Narayan Kamathaef84a12020-01-02 15:20:13 +0000452static node* do_lookup(fuse_req_t req, fuse_ino_t parent, const char* name,
453 struct fuse_entry_param* e, int* error_code) {
shafik1e3a2672019-08-16 14:51:55 +0100454 struct fuse* fuse = get_fuse(req);
455 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000456 node* parent_node = fuse->FromInode(parent);
457 string parent_path = parent_node->BuildPath();
Narayan Kamath768bea32019-12-27 16:23:23 +0000458
Zim357e3072020-01-15 10:50:01 +0000459 TRACE_FUSE_VERBOSE(fuse) << "LOOKUP " << name << " @ " << parent << " ("
460 << safe_name(parent_node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100461
Narayan Kamathaef84a12020-01-02 15:20:13 +0000462 string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100463
Zim859db932019-12-13 00:09:17 +0000464 std::smatch match;
465 std::regex_search(child_path, match, storage_emulated_regex);
Zimf0e3cd92020-01-03 00:57:43 +0000466 if (match.size() == 2 && std::to_string(getuid() / PER_USER_RANGE) != match[1].str()) {
467 // Ensure the FuseDaemon user id matches the user id in requested path
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000468 *error_code = EPERM;
Zim859db932019-12-13 00:09:17 +0000469 return nullptr;
470 }
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000471 return make_node_entry(req, parent_node, name, child_path, e, error_code);
shafik1e3a2672019-08-16 14:51:55 +0100472}
473
474static void pf_lookup(fuse_req_t req, fuse_ino_t parent, const char* name) {
Zimec8d5722019-12-05 07:26:13 +0000475 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100476 struct fuse_entry_param e;
477
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000478 int error_code = 0;
479 if (do_lookup(req, parent, name, &e, &error_code)) {
shafik1e3a2672019-08-16 14:51:55 +0100480 fuse_reply_entry(req, &e);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000481 } else {
482 CHECK(error_code != 0);
483 fuse_reply_err(req, error_code);
484 }
shafik1e3a2672019-08-16 14:51:55 +0100485}
486
Narayan Kamathaef84a12020-01-02 15:20:13 +0000487static void do_forget(struct fuse* fuse, fuse_ino_t ino, uint64_t nlookup) {
488 node* node = fuse->FromInode(ino);
shafik458d1102019-09-06 18:21:36 +0100489 TRACE_FUSE(fuse) << "FORGET #" << nlookup << " @ " << ino << " (" << safe_name(node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100490 if (node) {
Narayan Kamathaef84a12020-01-02 15:20:13 +0000491 // This is a narrowing conversion from an unsigned 64bit to a 32bit value. For
492 // some reason we only keep 32 bit refcounts but the kernel issues
493 // forget requests with a 64 bit counter.
Narayan Kamath92bf67b2020-01-03 17:49:09 +0000494 if (node->Release(static_cast<uint32_t>(nlookup))) {
495 fuse->NodeDeleted(node);
496 }
shafik1e3a2672019-08-16 14:51:55 +0100497 }
498}
499
500static void pf_forget(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup) {
Zimec8d5722019-12-05 07:26:13 +0000501 ATRACE_CALL();
Narayan Kamathaef84a12020-01-02 15:20:13 +0000502 node* node;
shafik1e3a2672019-08-16 14:51:55 +0100503 struct fuse* fuse = get_fuse(req);
504
Narayan Kamathaef84a12020-01-02 15:20:13 +0000505 do_forget(fuse, ino, nlookup);
shafik1e3a2672019-08-16 14:51:55 +0100506 fuse_reply_none(req);
507}
508
509static void pf_forget_multi(fuse_req_t req,
510 size_t count,
511 struct fuse_forget_data* forgets) {
Zimec8d5722019-12-05 07:26:13 +0000512 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100513 struct fuse* fuse = get_fuse(req);
514
Narayan Kamathaef84a12020-01-02 15:20:13 +0000515 for (int i = 0; i < count; i++) {
516 do_forget(fuse, forgets[i].ino, forgets[i].nlookup);
Narayan Kamath768bea32019-12-27 16:23:23 +0000517 }
shafik1e3a2672019-08-16 14:51:55 +0100518 fuse_reply_none(req);
519}
520
521static void pf_getattr(fuse_req_t req,
522 fuse_ino_t ino,
523 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +0000524 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100525 struct fuse* fuse = get_fuse(req);
526 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000527 node* node = fuse->FromInode(ino);
528 string path = node->BuildPath();
shafik458d1102019-09-06 18:21:36 +0100529 TRACE_FUSE(fuse) << "GETATTR @ " << ino << " (" << safe_name(node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100530
531 if (!node) fuse_reply_err(req, ENOENT);
532
Narayan Kamathaef84a12020-01-02 15:20:13 +0000533 struct stat s;
shafik1e3a2672019-08-16 14:51:55 +0100534 memset(&s, 0, sizeof(s));
535 if (lstat(path.c_str(), &s) < 0) {
536 fuse_reply_err(req, errno);
537 } else {
538 fuse_reply_attr(req, &s, 10);
539 }
540}
541
542static void pf_setattr(fuse_req_t req,
543 fuse_ino_t ino,
544 struct stat* attr,
545 int to_set,
546 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +0000547 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100548 struct fuse* fuse = get_fuse(req);
549 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000550 node* node = fuse->FromInode(ino);
551 string path = node->BuildPath();
shafik1e3a2672019-08-16 14:51:55 +0100552 struct timespec times[2];
shafik1e3a2672019-08-16 14:51:55 +0100553
shafik458d1102019-09-06 18:21:36 +0100554 TRACE_FUSE(fuse) << "SETATTR valid=" << to_set << " @ " << ino << "(" << safe_name(node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100555
556 if (!node) {
557 fuse_reply_err(req, ENOENT);
558 return;
559 }
560
561 /* XXX: incomplete implementation on purpose.
562 * chmod/chown should NEVER be implemented.*/
563
564 if ((to_set & FUSE_SET_ATTR_SIZE)
565 && truncate64(path.c_str(), attr->st_size) < 0) {
566 fuse_reply_err(req, errno);
567 return;
568 }
569
570 /* Handle changing atime and mtime. If FATTR_ATIME_and FATTR_ATIME_NOW
571 * are both set, then set it to the current time. Else, set it to the
572 * time specified in the request. Same goes for mtime. Use utimensat(2)
573 * as it allows ATIME and MTIME to be changed independently, and has
574 * nanosecond resolution which fuse also has.
575 */
576 if (to_set & (FATTR_ATIME | FATTR_MTIME)) {
577 times[0].tv_nsec = UTIME_OMIT;
578 times[1].tv_nsec = UTIME_OMIT;
579 if (to_set & FATTR_ATIME) {
580 if (to_set & FATTR_ATIME_NOW) {
581 times[0].tv_nsec = UTIME_NOW;
582 } else {
583 times[0].tv_sec = attr->st_atime;
584 // times[0].tv_nsec = attr->st_atime.tv_nsec;
585 }
586 }
587 if (to_set & FATTR_MTIME) {
588 if (to_set & FATTR_MTIME_NOW) {
589 times[1].tv_nsec = UTIME_NOW;
590 } else {
591 times[1].tv_sec = attr->st_mtime;
592 // times[1].tv_nsec = attr->st_mtime.tv_nsec;
593 }
594 }
shafik458d1102019-09-06 18:21:36 +0100595 TRACE_FUSE(fuse) << "Calling utimensat on " << path << " with atime " << times[0].tv_sec
596 << " mtime=" << times[1].tv_sec;
shafik1e3a2672019-08-16 14:51:55 +0100597 if (utimensat(-1, path.c_str(), times, 0) < 0) {
598 fuse_reply_err(req, errno);
599 return;
600 }
601 }
602
Zima9fcd552019-08-29 15:17:04 +0100603 lstat(path.c_str(), attr);
shafik1e3a2672019-08-16 14:51:55 +0100604 fuse_reply_attr(req, attr, 10);
605}
Zimb9730bf2019-11-30 15:10:04 +0000606
607static void pf_canonical_path(fuse_req_t req, fuse_ino_t ino)
shafik1e3a2672019-08-16 14:51:55 +0100608{
Zimb9730bf2019-11-30 15:10:04 +0000609 node* node = get_fuse(req)->FromInode(ino);
610
611 if (node) {
612 // TODO(b/147482155): Check that uid has access to |path| and its contents
613 fuse_reply_canonical_path(req, node->BuildPath().c_str());
614 return;
615 }
616 fuse_reply_err(req, ENOENT);
shafik1e3a2672019-08-16 14:51:55 +0100617}
Zimb9730bf2019-11-30 15:10:04 +0000618
shafik1e3a2672019-08-16 14:51:55 +0100619static void pf_mknod(fuse_req_t req,
620 fuse_ino_t parent,
621 const char* name,
622 mode_t mode,
623 dev_t rdev) {
Zimec8d5722019-12-05 07:26:13 +0000624 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100625 struct fuse* fuse = get_fuse(req);
626 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000627 node* parent_node = fuse->FromInode(parent);
628 string parent_path = parent_node->BuildPath();
Narayan Kamath768bea32019-12-27 16:23:23 +0000629
shafik458d1102019-09-06 18:21:36 +0100630 TRACE_FUSE(fuse) << "MKNOD " << name << " 0" << std::oct << mode << " @ " << parent << " ("
631 << safe_name(parent_node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100632
633 if (!parent_node) {
634 fuse_reply_err(req, ENOENT);
635 return;
636 }
Narayan Kamathaef84a12020-01-02 15:20:13 +0000637 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100638
639 mode = (mode & (~0777)) | 0664;
640 if (mknod(child_path.c_str(), mode, rdev) < 0) {
641 fuse_reply_err(req, errno);
642 return;
643 }
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000644
645 int error_code = 0;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000646 struct fuse_entry_param e;
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000647 if (make_node_entry(req, parent_node, name, child_path, &e, &error_code)) {
shafik1e3a2672019-08-16 14:51:55 +0100648 fuse_reply_entry(req, &e);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000649 } else {
650 CHECK(error_code != 0);
651 fuse_reply_err(req, error_code);
652 }
shafik1e3a2672019-08-16 14:51:55 +0100653}
654
655static void pf_mkdir(fuse_req_t req,
656 fuse_ino_t parent,
657 const char* name,
658 mode_t mode) {
Zimec8d5722019-12-05 07:26:13 +0000659 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100660 struct fuse* fuse = get_fuse(req);
661 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000662 node* parent_node = fuse->FromInode(parent);
663 const string parent_path = parent_node->BuildPath();
Narayan Kamath768bea32019-12-27 16:23:23 +0000664
shafik458d1102019-09-06 18:21:36 +0100665 TRACE_FUSE(fuse) << "MKDIR " << name << " 0" << std::oct << mode << " @ " << parent << " ("
666 << safe_name(parent_node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100667
Narayan Kamathaef84a12020-01-02 15:20:13 +0000668 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100669
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000670 int status = -fuse->mp->IsCreatingDirAllowed(child_path, ctx->uid);
671 if (status) {
672 fuse_reply_err(req, status);
673 return;
674 }
675
shafik1e3a2672019-08-16 14:51:55 +0100676 mode = (mode & (~0777)) | 0775;
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000677 if (mkdir(child_path.c_str(), mode) < 0) {
shafik1e3a2672019-08-16 14:51:55 +0100678 fuse_reply_err(req, errno);
679 return;
680 }
681
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000682 int error_code = 0;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000683 struct fuse_entry_param e;
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000684 if (make_node_entry(req, parent_node, name, child_path, &e, &error_code)) {
shafik1e3a2672019-08-16 14:51:55 +0100685 fuse_reply_entry(req, &e);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000686 } else {
687 CHECK(error_code != 0);
688 fuse_reply_err(req, error_code);
689 }
shafik1e3a2672019-08-16 14:51:55 +0100690}
691
692static void pf_unlink(fuse_req_t req, fuse_ino_t parent, const char* name) {
Zimec8d5722019-12-05 07:26:13 +0000693 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100694 struct fuse* fuse = get_fuse(req);
695 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000696 node* parent_node = fuse->FromInode(parent);
697 const string parent_path = parent_node->BuildPath();
shafik1e3a2672019-08-16 14:51:55 +0100698
shafik458d1102019-09-06 18:21:36 +0100699 TRACE_FUSE(fuse) << "UNLINK " << name << " @ " << parent << "(" << safe_name(parent_node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100700
Narayan Kamathaef84a12020-01-02 15:20:13 +0000701 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100702
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000703 int status = -fuse->mp->DeleteFile(child_path, ctx->uid);
704 if (status) {
705 fuse_reply_err(req, status);
shafik1e3a2672019-08-16 14:51:55 +0100706 return;
707 }
Narayan Kamath768bea32019-12-27 16:23:23 +0000708
Narayan Kamathaef84a12020-01-02 15:20:13 +0000709 node* child_node = parent_node->LookupChildByName(name);
710 if (child_node) {
711 child_node->SetDeleted();
shafik1e3a2672019-08-16 14:51:55 +0100712 }
shafik1e3a2672019-08-16 14:51:55 +0100713
714 fuse_reply_err(req, 0);
715}
716
717static void pf_rmdir(fuse_req_t req, fuse_ino_t parent, const char* name) {
Zimec8d5722019-12-05 07:26:13 +0000718 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100719 struct fuse* fuse = get_fuse(req);
720 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000721 node* parent_node = fuse->FromInode(parent);
722 const string parent_path = parent_node->BuildPath();
shafik1e3a2672019-08-16 14:51:55 +0100723
shafik458d1102019-09-06 18:21:36 +0100724 TRACE_FUSE(fuse) << "RMDIR " << name << " @ " << parent << "(" << safe_name(parent_node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100725
Narayan Kamathaef84a12020-01-02 15:20:13 +0000726 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100727
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000728 int status = -fuse->mp->IsDeletingDirAllowed(child_path, ctx->uid);
729 if (status) {
730 fuse_reply_err(req, status);
731 return;
732 }
733
734 if (rmdir(child_path.c_str()) < 0) {
shafik1e3a2672019-08-16 14:51:55 +0100735 fuse_reply_err(req, errno);
736 return;
737 }
Narayan Kamath768bea32019-12-27 16:23:23 +0000738
Narayan Kamathaef84a12020-01-02 15:20:13 +0000739 node* child_node = parent_node->LookupChildByName(name);
740 if (child_node) {
741 child_node->SetDeleted();
shafik1e3a2672019-08-16 14:51:55 +0100742 }
shafik1e3a2672019-08-16 14:51:55 +0100743
744 fuse_reply_err(req, 0);
745}
746/*
747static void pf_symlink(fuse_req_t req, const char* link, fuse_ino_t parent,
748 const char* name)
749{
750 cout << "TODO:" << __func__;
751}
752*/
Sahana Rao2c416032019-12-31 13:41:00 +0000753static int do_rename(fuse_req_t req, fuse_ino_t parent, const char* name, fuse_ino_t new_parent,
754 const char* new_name, unsigned int flags) {
Zimec8d5722019-12-05 07:26:13 +0000755 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100756 struct fuse* fuse = get_fuse(req);
757 const struct fuse_ctx* ctx = fuse_req_ctx(req);
shafik1e3a2672019-08-16 14:51:55 +0100758
Sahana Rao2c416032019-12-31 13:41:00 +0000759 if (flags != 0) {
760 LOG(ERROR) << "One or more rename flags not supported";
761 return EINVAL;
762 }
Narayan Kamath768bea32019-12-27 16:23:23 +0000763
Narayan Kamathaef84a12020-01-02 15:20:13 +0000764 node* old_parent_node = fuse->FromInode(parent);
765 const string old_parent_path = old_parent_node->BuildPath();
766 node* new_parent_node = fuse->FromInode(new_parent);
767 const string new_parent_path = new_parent_node->BuildPath();
Narayan Kamath768bea32019-12-27 16:23:23 +0000768
Narayan Kamathaef84a12020-01-02 15:20:13 +0000769 if (!old_parent_node || !new_parent_node) {
770 return ENOENT;
771 } else if (parent == new_parent && name == new_name) {
772 // No rename required.
773 return 0;
shafik1e3a2672019-08-16 14:51:55 +0100774 }
775
Narayan Kamathaef84a12020-01-02 15:20:13 +0000776 TRACE_FUSE(fuse) << "RENAME " << name << " -> " << new_name << " @ " << parent << " ("
777 << safe_name(old_parent_node) << ") -> " << new_parent << " ("
778 << safe_name(new_parent_node) << ")";
shafik1e3a2672019-08-16 14:51:55 +0100779
Narayan Kamathaef84a12020-01-02 15:20:13 +0000780 node* child_node = old_parent_node->LookupChildByName(name);
781 child_node->Acquire();
782
783 const string old_child_path = child_node->BuildPath();
784 const string new_child_path = new_parent_path + "/" + new_name;
785
Sahana Rao182ec6b2020-01-03 15:00:46 +0000786 // TODO(b/147408834): Check ENOTEMPTY & EEXIST error conditions before JNI call.
Sahana Rao2c416032019-12-31 13:41:00 +0000787 const int res = -fuse->mp->Rename(old_child_path, new_child_path, req->ctx.uid);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000788 // TODO(b/145663158): Lookups can go out of sync if file/directory is actually moved but
789 // EFAULT/EIO is reported due to JNI exception.
790 if (res == 0) {
791 child_node->Rename(new_name, new_parent_node);
shafik1e3a2672019-08-16 14:51:55 +0100792 }
793
Narayan Kamathaef84a12020-01-02 15:20:13 +0000794 child_node->Release(1);
Narayan Kamath768bea32019-12-27 16:23:23 +0000795 return res;
796}
shafik1e3a2672019-08-16 14:51:55 +0100797
Sahana Rao2c416032019-12-31 13:41:00 +0000798static void pf_rename(fuse_req_t req, fuse_ino_t parent, const char* name, fuse_ino_t new_parent,
799 const char* new_name, unsigned int flags) {
800 int res = do_rename(req, parent, name, new_parent, new_name, flags);
shafik1e3a2672019-08-16 14:51:55 +0100801 fuse_reply_err(req, res);
802}
Narayan Kamath768bea32019-12-27 16:23:23 +0000803
shafik1e3a2672019-08-16 14:51:55 +0100804/*
Sahana Rao2c416032019-12-31 13:41:00 +0000805static void pf_link(fuse_req_t req, fuse_ino_t ino, fuse_ino_t new_parent,
806 const char* new_name)
shafik1e3a2672019-08-16 14:51:55 +0100807{
808 cout << "TODO:" << __func__;
809}
810*/
811
812static void pf_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +0000813 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100814 struct fuse* fuse = get_fuse(req);
815 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000816 node* node = fuse->FromInode(ino);
817 const string path = node->BuildPath();
shafik1e3a2672019-08-16 14:51:55 +0100818
shafik458d1102019-09-06 18:21:36 +0100819 TRACE_FUSE(fuse) << "OPEN 0" << std::oct << fi->flags << " @ " << ino << " (" << safe_name(node)
820 << ")";
shafik1e3a2672019-08-16 14:51:55 +0100821
822 if (!node) {
823 fuse_reply_err(req, ENOENT);
824 return;
825 }
826
shafik15e2d612019-10-31 20:10:25 +0000827 if (fi->flags & O_DIRECT) {
828 fi->flags &= ~O_DIRECT;
829 fi->direct_io = true;
830 }
831
shafik458d1102019-09-06 18:21:36 +0100832 TRACE_FUSE(fuse) << "OPEN " << path;
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000833 int status = -fuse->mp->IsOpenAllowed(path, ctx->uid, is_requesting_write(fi->flags));
834 if (status) {
835 fuse_reply_err(req, status);
836 return;
837 }
838
839 const int fd = open(path.c_str(), fi->flags);
840 if (fd < 0) {
shafik1e3a2672019-08-16 14:51:55 +0100841 fuse_reply_err(req, errno);
842 return;
843 }
shafik15e2d612019-10-31 20:10:25 +0000844
shafikc580b6d2019-12-10 18:45:17 +0000845 // We don't redact if the caller was granted write permission for this file
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000846 std::unique_ptr<RedactionInfo> ri;
shafikc580b6d2019-12-10 18:45:17 +0000847 if (is_requesting_write(fi->flags)) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000848 ri = std::make_unique<RedactionInfo>();
shafikc580b6d2019-12-10 18:45:17 +0000849 } else {
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000850 ri = fuse->mp->GetRedactionInfo(path, req->ctx.uid);
shafikc580b6d2019-12-10 18:45:17 +0000851 }
852
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000853 if (!ri) {
854 close(fd);
855 fuse_reply_err(req, EFAULT);
shafikc580b6d2019-12-10 18:45:17 +0000856 return;
857 }
858
Narayan Kamathbd22bb02020-01-08 16:02:50 +0000859 if (ri->isRedactionNeeded() || is_file_locked(fd, path)) {
Zimedbe69e2019-12-13 18:49:36 +0000860 // We don't want to use the FUSE VFS cache in two cases:
861 // 1. When redaction is needed because app A with EXIF access might access
862 // a region that should have been redacted for app B without EXIF access, but app B on
863 // a subsequent read, will be able to see the EXIF data because the read request for that
864 // region will be served from cache and not get to the FUSE daemon
865 // 2. When the file has a read or write lock on it. This means that the MediaProvider has
866 // given an fd to the lower file system to an app. There are two cases where using the cache
867 // in this case can be a problem:
868 // a. Writing to a FUSE fd with caching enabled will use the write-back cache and a
869 // subsequent read from the lower fs fd will not see the write.
870 // b. Reading from a FUSE fd with caching enabled may not see the latest writes using the
871 // lower fs fd because those writes did not go through the FUSE layer and reads from FUSE
872 // after that write may be served from cache
Narayan Kamathbd22bb02020-01-08 16:02:50 +0000873 if (ri->isRedactionNeeded()) {
Martijn Coenend0f95892020-01-09 10:14:26 +0100874 TRACE_FUSE(fuse) << "Using direct io for " << path << " because redaction is needed.";
Narayan Kamathbd22bb02020-01-08 16:02:50 +0000875 } else {
Martijn Coenend0f95892020-01-09 10:14:26 +0100876 TRACE_FUSE(fuse) << "Using direct io for " << path << " because the file is locked.";
877 }
shafikc580b6d2019-12-10 18:45:17 +0000878 fi->direct_io = true;
Zimedbe69e2019-12-13 18:49:36 +0000879 } else {
880 TRACE_FUSE(fuse) << "Using cache for " << path;
shafikc580b6d2019-12-10 18:45:17 +0000881 }
882
Narayan Kamathbd22bb02020-01-08 16:02:50 +0000883 handle* h = new handle(path, fd, ri.release(), !fi->direct_io);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000884 node->AddHandle(h);
Zimedbe69e2019-12-13 18:49:36 +0000885
shafik1e3a2672019-08-16 14:51:55 +0100886 fi->fh = ptr_to_id(h);
Zim61d12342019-10-01 15:47:45 +0100887 fi->keep_cache = 1;
shafik1e3a2672019-08-16 14:51:55 +0100888 fuse_reply_open(req, fi);
889}
890
shafikc3f62672019-08-30 11:15:48 +0100891static void do_read(fuse_req_t req, size_t size, off_t off, struct fuse_file_info* fi) {
shafika2ae9072019-10-28 12:16:00 +0000892 handle* h = reinterpret_cast<handle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +0100893 struct fuse_bufvec buf = FUSE_BUFVEC_INIT(size);
894
895 buf.buf[0].fd = h->fd;
896 buf.buf[0].pos = off;
897 buf.buf[0].flags =
898 (enum fuse_buf_flags) (FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
899
900 fuse_reply_data(req, &buf, (enum fuse_buf_copy_flags) 0);
901}
shafikc3f62672019-08-30 11:15:48 +0100902
903static bool range_contains(const RedactionRange& rr, off_t off) {
904 return rr.first <= off && off <= rr.second;
905}
906
907/**
908 * Sets the parameters for a fuse_buf that reads from memory, including flags.
shafikb334a612019-09-30 20:38:16 +0100909 * Makes buf->mem point to an already mapped region of zeroized memory.
910 * This memory is read only.
shafikc3f62672019-08-30 11:15:48 +0100911 */
shafikb334a612019-09-30 20:38:16 +0100912static void create_mem_fuse_buf(size_t size, fuse_buf* buf, struct fuse* fuse) {
shafikc3f62672019-08-30 11:15:48 +0100913 buf->size = size;
shafikb334a612019-09-30 20:38:16 +0100914 buf->mem = fuse->zero_addr;
shafikc3f62672019-08-30 11:15:48 +0100915 buf->flags = static_cast<fuse_buf_flags>(0 /*read from fuse_buf.mem*/);
916 buf->pos = -1;
917 buf->fd = -1;
918}
919
920/**
921 * Sets the parameters for a fuse_buf that reads from file, including flags.
922 */
923static void create_file_fuse_buf(size_t size, off_t pos, int fd, fuse_buf* buf) {
924 buf->size = size;
925 buf->fd = fd;
926 buf->pos = pos;
927 buf->flags = static_cast<fuse_buf_flags>(FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
928 buf->mem = nullptr;
929}
930
931static 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 +0000932 handle* h = reinterpret_cast<handle*>(fi->fh);
shafikc3f62672019-08-30 11:15:48 +0100933 auto overlapping_rr = h->ri->getOverlappingRedactionRanges(size, off);
934
935 if (overlapping_rr->size() <= 0) {
936 // no relevant redaction ranges for this request
937 do_read(req, size, off, fi);
938 return;
939 }
940 // the number of buffers we need, if the read doesn't start or end with
941 // a redaction range.
942 int num_bufs = overlapping_rr->size() * 2 + 1;
943 if (overlapping_rr->front().first <= off) {
944 // the beginning of the read request is redacted
945 num_bufs--;
946 }
947 if (overlapping_rr->back().second >= off + size) {
948 // the end of the read request is redacted
949 num_bufs--;
950 }
951 auto bufvec_ptr = std::unique_ptr<fuse_bufvec, decltype(free)*>{
952 reinterpret_cast<fuse_bufvec*>(
953 malloc(sizeof(fuse_bufvec) + (num_bufs - 1) * sizeof(fuse_buf))),
954 free};
955 fuse_bufvec& bufvec = *bufvec_ptr;
956
957 // initialize bufvec
958 bufvec.count = num_bufs;
959 bufvec.idx = 0;
960 bufvec.off = 0;
shafikc3f62672019-08-30 11:15:48 +0100961
962 int rr_idx = 0;
963 off_t start = off;
964 // Add a dummy redaction range to make sure we don't go out of vector
965 // limits when computing the end of the last non-redacted range.
966 // This ranges is invalid because its starting point is larger than it's ending point.
967 overlapping_rr->push_back(RedactionRange(LLONG_MAX, LLONG_MAX - 1));
968
969 for (int i = 0; i < num_bufs; ++i) {
970 off_t end;
971 if (range_contains(overlapping_rr->at(rr_idx), start)) {
972 // Handle a redacted range
973 // end should be the end of the redacted range, but can't be out of
974 // the read request bounds
975 end = std::min(static_cast<off_t>(off + size - 1), overlapping_rr->at(rr_idx).second);
shafikb334a612019-09-30 20:38:16 +0100976 create_mem_fuse_buf(/*size*/ end - start + 1, &(bufvec.buf[i]), get_fuse(req));
shafikc3f62672019-08-30 11:15:48 +0100977 ++rr_idx;
978 } else {
979 // Handle a non-redacted range
980 // end should be right before the next redaction range starts or
981 // the end of the read request
982 end = std::min(static_cast<off_t>(off + size - 1),
983 overlapping_rr->at(rr_idx).first - 1);
984 create_file_fuse_buf(/*size*/ end - start + 1, start, h->fd, &(bufvec.buf[i]));
985 }
986 start = end + 1;
987 }
988
989 fuse_reply_data(req, &bufvec, static_cast<fuse_buf_copy_flags>(0));
990}
991
992static void pf_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off,
993 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +0000994 ATRACE_CALL();
shafika2ae9072019-10-28 12:16:00 +0000995 handle* h = reinterpret_cast<handle*>(fi->fh);
shafikc3f62672019-08-30 11:15:48 +0100996 struct fuse* fuse = get_fuse(req);
shafikc3f62672019-08-30 11:15:48 +0100997
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200998 fuse->fadviser.Record(h->fd, size);
999
shafikc3f62672019-08-30 11:15:48 +01001000 if (h->ri->isRedactionNeeded()) {
1001 do_read_with_redaction(req, size, off, fi);
1002 } else {
1003 do_read(req, size, off, fi);
1004 }
1005}
1006
shafik1e3a2672019-08-16 14:51:55 +01001007/*
1008static void pf_write(fuse_req_t req, fuse_ino_t ino, const char* buf,
1009 size_t size, off_t off, struct fuse_file_info* fi)
1010{
1011 cout << "TODO:" << __func__;
1012}
1013*/
1014
1015static void pf_write_buf(fuse_req_t req,
1016 fuse_ino_t ino,
1017 struct fuse_bufvec* bufv,
1018 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);
shafik1e3a2672019-08-16 14:51:55 +01001022 struct fuse_bufvec buf = FUSE_BUFVEC_INIT(fuse_buf_size(bufv));
1023 ssize_t size;
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001024 struct fuse* fuse = get_fuse(req);
shafik1e3a2672019-08-16 14:51:55 +01001025
1026 buf.buf[0].fd = h->fd;
1027 buf.buf[0].pos = off;
1028 buf.buf[0].flags =
1029 (enum fuse_buf_flags) (FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
1030 size = fuse_buf_copy(&buf, bufv, (enum fuse_buf_copy_flags) 0);
1031
1032 if (size < 0)
1033 fuse_reply_err(req, -size);
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001034 else {
shafik1e3a2672019-08-16 14:51:55 +01001035 fuse_reply_write(req, size);
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001036 fuse->fadviser.Record(h->fd, size);
1037 }
shafik1e3a2672019-08-16 14:51:55 +01001038}
1039// Haven't tested this one. Not sure what calls it.
1040#if 0
1041static void pf_copy_file_range(fuse_req_t req, fuse_ino_t ino_in,
1042 off_t off_in, struct fuse_file_info* fi_in,
1043 fuse_ino_t ino_out, off_t off_out,
1044 struct fuse_file_info* fi_out, size_t len,
1045 int flags)
1046{
shafika2ae9072019-10-28 12:16:00 +00001047 handle* h_in = reinterpret_cast<handle *>(fi_in->fh);
1048 handle* h_out = reinterpret_cast<handle *>(fi_out->fh);
shafik1e3a2672019-08-16 14:51:55 +01001049 struct fuse_bufvec buf_in = FUSE_BUFVEC_INIT(len);
1050 struct fuse_bufvec buf_out = FUSE_BUFVEC_INIT(len);
1051 ssize_t size;
1052
1053 buf_in.buf[0].fd = h_in->fd;
1054 buf_in.buf[0].pos = off_in;
1055 buf_in.buf[0].flags = (enum fuse_buf_flags)(FUSE_BUF_IS_FD|FUSE_BUF_FD_SEEK);
1056
1057 buf_out.buf[0].fd = h_out->fd;
1058 buf_out.buf[0].pos = off_out;
1059 buf_out.buf[0].flags = (enum fuse_buf_flags)(FUSE_BUF_IS_FD|FUSE_BUF_FD_SEEK);
1060 size = fuse_buf_copy(&buf_out, &buf_in, (enum fuse_buf_copy_flags) 0);
1061
1062 if (size < 0) {
1063 fuse_reply_err(req, -size);
1064 }
1065
1066 fuse_reply_write(req, size);
1067}
1068#endif
1069static void pf_flush(fuse_req_t req,
1070 fuse_ino_t ino,
1071 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001072 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001073 struct fuse* fuse = get_fuse(req);
shafik458d1102019-09-06 18:21:36 +01001074 TRACE_FUSE(fuse) << "FLUSH is a noop";
shafik1e3a2672019-08-16 14:51:55 +01001075 fuse_reply_err(req, 0);
1076}
1077
1078static void pf_release(fuse_req_t req,
1079 fuse_ino_t ino,
1080 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001081 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001082 struct fuse* fuse = get_fuse(req);
Kyle Tso613b7ab2019-12-24 06:30:00 +00001083
Narayan Kamathaef84a12020-01-02 15:20:13 +00001084 node* node = fuse->FromInode(ino);
1085 handle* h = reinterpret_cast<handle*>(fi->fh);
1086 TRACE_FUSE(fuse) << "RELEASE "
1087 << "0" << std::oct << fi->flags << " " << h << "(" << h->fd << ")";
shafik15e2d612019-10-31 20:10:25 +00001088
Narayan Kamathaef84a12020-01-02 15:20:13 +00001089 fuse->fadviser.Close(h->fd);
1090 // TODO(b/145737191): Figure out if we need to scan files on close, and how to do it properly
1091 if (node) {
1092 node->DestroyHandle(h);
Zimedbe69e2019-12-13 18:49:36 +00001093 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001094
shafik1e3a2672019-08-16 14:51:55 +01001095 fuse_reply_err(req, 0);
1096}
1097
1098static int do_sync_common(int fd, bool datasync) {
1099 int res = datasync ? fdatasync(fd) : fsync(fd);
1100
1101 if (res == -1) return errno;
1102 return 0;
1103}
1104
1105static void pf_fsync(fuse_req_t req,
1106 fuse_ino_t ino,
1107 int datasync,
1108 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001109 ATRACE_CALL();
shafika2ae9072019-10-28 12:16:00 +00001110 handle* h = reinterpret_cast<handle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001111 int err = do_sync_common(h->fd, datasync);
1112
1113 fuse_reply_err(req, err);
1114}
1115
1116static void pf_fsyncdir(fuse_req_t req,
1117 fuse_ino_t ino,
1118 int datasync,
1119 struct fuse_file_info* fi) {
Narayan Kamathaef84a12020-01-02 15:20:13 +00001120 dirhandle* h = reinterpret_cast<dirhandle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001121 int err = do_sync_common(dirfd(h->d), datasync);
1122
1123 fuse_reply_err(req, err);
1124}
1125
1126static void pf_opendir(fuse_req_t req,
1127 fuse_ino_t ino,
1128 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001129 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001130 struct fuse* fuse = get_fuse(req);
1131 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001132 node* node = fuse->FromInode(ino);
1133 const string path = node->BuildPath();
shafik458d1102019-09-06 18:21:36 +01001134
Zimdb34d472019-09-30 12:29:24 +01001135 TRACE_FUSE(fuse) << "OPENDIR @ " << ino << " (" << safe_name(node) << ")" << path;
shafik1e3a2672019-08-16 14:51:55 +01001136
1137 if (!node) {
1138 fuse_reply_err(req, ENOENT);
1139 return;
1140 }
1141
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001142 int status = -fuse->mp->IsOpendirAllowed(path, ctx->uid);
1143 if (status) {
1144 fuse_reply_err(req, status);
1145 return;
1146 }
1147
1148 DIR* dir = opendir(path.c_str());
1149 if (!dir) {
shafik1e3a2672019-08-16 14:51:55 +01001150 fuse_reply_err(req, errno);
1151 return;
1152 }
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001153
Narayan Kamathaef84a12020-01-02 15:20:13 +00001154 dirhandle* h = new dirhandle(dir);
1155 node->AddDirHandle(h);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001156
shafik1e3a2672019-08-16 14:51:55 +01001157 fi->fh = ptr_to_id(h);
1158 fuse_reply_open(req, fi);
1159}
1160
1161#define READDIR_BUF 8192LU
1162
1163static void do_readdir_common(fuse_req_t req,
1164 fuse_ino_t ino,
1165 size_t size,
1166 off_t off,
1167 struct fuse_file_info* fi,
1168 bool plus) {
1169 struct fuse* fuse = get_fuse(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001170 dirhandle* h = reinterpret_cast<dirhandle*>(fi->fh);
Jeff Sharkey7469b982019-08-28 16:51:02 -06001171 size_t len = std::min<size_t>(size, READDIR_BUF);
shafik1e3a2672019-08-16 14:51:55 +01001172 char buf[READDIR_BUF];
1173 size_t used = 0;
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001174 std::shared_ptr<DirectoryEntry> de;
1175
shafik1e3a2672019-08-16 14:51:55 +01001176 struct fuse_entry_param e;
Sahana Rao6f9ea982019-09-20 12:21:33 +01001177 size_t entry_size = 0;
shafik1e3a2672019-08-16 14:51:55 +01001178
Narayan Kamathaef84a12020-01-02 15:20:13 +00001179 node* node = fuse->FromInode(ino);
1180 const string path = node->BuildPath();
Narayan Kamath768bea32019-12-27 16:23:23 +00001181
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001182 TRACE_FUSE(fuse) << "READDIR @" << ino << " " << path << " at offset " << off;
1183 // Get all directory entries from MediaProvider on first readdir() call of
1184 // directory handle. h->next_off = 0 indicates that current readdir() call
1185 // is first readdir() call for the directory handle, Avoid multiple JNI calls
1186 // for single directory handle.
1187 if (h->next_off == 0) {
Sahana Rao71693442019-11-13 13:48:07 +00001188 h->de = fuse->mp->GetDirectoryEntries(req->ctx.uid, path, h->d);
shafik1e3a2672019-08-16 14:51:55 +01001189 }
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001190 // If the last entry in the previous readdir() call was rejected due to
1191 // buffer capacity constraints, update directory offset to start from
1192 // previously rejected entry. Directory offset can also change if there was
Sahana Rao71693442019-11-13 13:48:07 +00001193 // a seekdir() on the given directory handle.
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001194 if (off != h->next_off) {
1195 h->next_off = off;
1196 }
1197 const int num_directory_entries = h->de.size();
Sahana Rao71693442019-11-13 13:48:07 +00001198 // Check for errors. Any error/exception occurred while obtaining directory
1199 // entries will be indicated by marking first directory entry name as empty
1200 // string. In the erroneous case corresponding d_type will hold error number.
Sahana Rao53bd1f62019-12-27 20:18:39 +00001201 if (num_directory_entries && h->de[0]->d_name.empty()) {
1202 fuse_reply_err(req, h->de[0]->d_type);
1203 return;
1204 }
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001205
Sahana Rao53bd1f62019-12-27 20:18:39 +00001206 while (h->next_off < num_directory_entries) {
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001207 de = h->de[h->next_off];
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001208 entry_size = 0;
1209 h->next_off++;
shafik1e3a2672019-08-16 14:51:55 +01001210 if (plus) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001211 int error_code = 0;
1212 if (do_lookup(req, ino, de->d_name.c_str(), &e, &error_code)) {
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001213 entry_size = fuse_add_direntry_plus(req, buf + used, len - used, de->d_name.c_str(),
1214 &e, h->next_off);
Sahana Rao8a588e72019-12-06 11:32:56 +00001215 } else {
Sahana Rao8d8dbb42019-12-18 12:57:02 +00001216 // Ignore lookup errors on
1217 // 1. non-existing files returned from MediaProvider database.
1218 // 2. path that doesn't match FuseDaemon UID and calling uid.
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001219 if (error_code == ENOENT || error_code == EPERM) continue;
1220 fuse_reply_err(req, error_code);
shafik1e3a2672019-08-16 14:51:55 +01001221 return;
1222 }
1223 } else {
1224 e.attr.st_ino = FUSE_UNKNOWN_INO;
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001225 e.attr.st_mode = de->d_type;
1226 entry_size = fuse_add_direntry(req, buf + used, len - used, de->d_name.c_str(), &e.attr,
1227 h->next_off);
shafik1e3a2672019-08-16 14:51:55 +01001228 }
Sahana Rao6f9ea982019-09-20 12:21:33 +01001229 // If buffer in fuse_add_direntry[_plus] is not large enough then
1230 // the entry is not added to buffer but the size of the entry is still
1231 // returned. Check available buffer size + returned entry size is less
1232 // than actual buffer size to confirm entry is added to buffer.
Sahana Rao43927f02019-12-10 22:59:01 +00001233 if (used + entry_size > len) {
1234 // When an entry is rejected, lookup called by readdir_plus will not be tracked by
1235 // kernel. Call forget on the rejected node to decrement the reference count.
Narayan Kamathd6219842019-12-27 17:44:35 +00001236 if (plus) {
Narayan Kamathaef84a12020-01-02 15:20:13 +00001237 do_forget(fuse, e.ino, 1);
Narayan Kamathd6219842019-12-27 17:44:35 +00001238 }
Sahana Rao43927f02019-12-10 22:59:01 +00001239 break;
1240 }
Sahana Rao6f9ea982019-09-20 12:21:33 +01001241 used += entry_size;
shafik1e3a2672019-08-16 14:51:55 +01001242 }
Sahana Rao53bd1f62019-12-27 20:18:39 +00001243 fuse_reply_buf(req, buf, used);
shafik1e3a2672019-08-16 14:51:55 +01001244}
1245
1246static void pf_readdir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off,
1247 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001248 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001249 do_readdir_common(req, ino, size, off, fi, false);
1250}
1251
1252static void pf_readdirplus(fuse_req_t req,
1253 fuse_ino_t ino,
1254 size_t size,
1255 off_t off,
1256 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001257 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001258 do_readdir_common(req, ino, size, off, fi, true);
1259}
1260
1261static void pf_releasedir(fuse_req_t req,
1262 fuse_ino_t ino,
1263 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001264 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001265 struct fuse* fuse = get_fuse(req);
shafik1e3a2672019-08-16 14:51:55 +01001266
Narayan Kamathaef84a12020-01-02 15:20:13 +00001267 node* node = fuse->FromInode(ino);
1268 dirhandle* h = reinterpret_cast<dirhandle*>(fi->fh);
1269 TRACE_FUSE(fuse) << "RELEASEDIR " << h;
1270 if (node) {
1271 node->DestroyDirHandle(h);
Zimedbe69e2019-12-13 18:49:36 +00001272 }
Zimedbe69e2019-12-13 18:49:36 +00001273
shafik1e3a2672019-08-16 14:51:55 +01001274 fuse_reply_err(req, 0);
1275}
1276
1277static void pf_statfs(fuse_req_t req, fuse_ino_t ino) {
Zimec8d5722019-12-05 07:26:13 +00001278 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001279 struct statvfs st;
1280 struct fuse* fuse = get_fuse(req);
1281
Narayan Kamathaef84a12020-01-02 15:20:13 +00001282 if (statvfs(fuse->root->GetName().c_str(), &st))
shafik1e3a2672019-08-16 14:51:55 +01001283 fuse_reply_err(req, errno);
1284 else
1285 fuse_reply_statfs(req, &st);
1286}
1287/*
1288static void pf_setxattr(fuse_req_t req, fuse_ino_t ino, const char* name,
1289 const char* value, size_t size, int flags)
1290{
1291 cout << "TODO:" << __func__;
1292}
1293
1294static void pf_getxattr(fuse_req_t req, fuse_ino_t ino, const char* name,
1295 size_t size)
1296{
1297 cout << "TODO:" << __func__;
1298}
1299
1300static void pf_listxattr(fuse_req_t req, fuse_ino_t ino, size_t size)
1301{
1302 cout << "TODO:" << __func__;
1303}
1304
1305static void pf_removexattr(fuse_req_t req, fuse_ino_t ino, const char* name)
1306{
1307 cout << "TODO:" << __func__;
Zima9fcd552019-08-29 15:17:04 +01001308}*/
1309
1310static void pf_access(fuse_req_t req, fuse_ino_t ino, int mask) {
Zimec8d5722019-12-05 07:26:13 +00001311 ATRACE_CALL();
Zima9fcd552019-08-29 15:17:04 +01001312 struct fuse* fuse = get_fuse(req);
1313 const struct fuse_ctx* ctx = fuse_req_ctx(req);
1314
Narayan Kamathaef84a12020-01-02 15:20:13 +00001315 node* node = fuse->FromInode(ino);
1316 const string path = node->BuildPath();
Zim357e3072020-01-15 10:50:01 +00001317 TRACE_FUSE_VERBOSE(fuse) << "ACCESS " << path;
Zima9fcd552019-08-29 15:17:04 +01001318
1319 int res = access(path.c_str(), F_OK);
1320 fuse_reply_err(req, res ? errno : 0);
shafik1e3a2672019-08-16 14:51:55 +01001321}
Zima9fcd552019-08-29 15:17:04 +01001322
shafik1e3a2672019-08-16 14:51:55 +01001323static void pf_create(fuse_req_t req,
1324 fuse_ino_t parent,
1325 const char* name,
1326 mode_t mode,
1327 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001328 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001329 struct fuse* fuse = get_fuse(req);
1330 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001331 node* parent_node = fuse->FromInode(parent);
1332 const string parent_path = parent_node->BuildPath();
shafik1e3a2672019-08-16 14:51:55 +01001333
shafik9dd60eb2019-11-12 20:28:53 +00001334 TRACE_FUSE(fuse) << "CREATE " << name << " 0" << std::oct << fi->flags << " @ " << parent
1335 << " (" << safe_name(parent_node) << ")";
shafik1e3a2672019-08-16 14:51:55 +01001336
Narayan Kamathaef84a12020-01-02 15:20:13 +00001337 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +01001338
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001339 int mp_return_code = -fuse->mp->InsertFile(child_path.c_str(), ctx->uid);
1340 if (mp_return_code) {
shafika51f3ce2019-10-10 17:06:41 +01001341 PLOG(DEBUG) << "Could not create file: " << child_path;
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001342 fuse_reply_err(req, mp_return_code);
shafik1e3a2672019-08-16 14:51:55 +01001343 return;
1344 }
1345
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001346 mode = (mode & (~0777)) | 0664;
1347 int fd = open(child_path.c_str(), fi->flags, mode);
1348 if (fd < 0) {
1349 int error_code = errno;
1350 // We've already inserted the file into the MP database before the
1351 // failed open(), so that needs to be rolled back here.
1352 fuse->mp->DeleteFile(child_path.c_str(), ctx->uid);
1353 fuse_reply_err(req, error_code);
1354 return;
1355 }
1356
Narayan Kamathbd22bb02020-01-08 16:02:50 +00001357 // TODO(b/147274248): Assume there will be no EXIF to redact.
Zim57a75352020-01-07 08:19:18 +00001358 // This prevents crashing during reads but can be a security hole if a malicious app opens an fd
1359 // to the file before all the EXIF content is written. We could special case reads before the
1360 // first close after a file has just been created.
Narayan Kamathbd22bb02020-01-08 16:02:50 +00001361 handle* h = new handle(child_path, fd, new RedactionInfo(), true /* cached */);
shafik1e3a2672019-08-16 14:51:55 +01001362 fi->fh = ptr_to_id(h);
Zim61d12342019-10-01 15:47:45 +01001363 fi->keep_cache = 1;
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001364
1365 int error_code = 0;
Narayan Kamathaef84a12020-01-02 15:20:13 +00001366 struct fuse_entry_param e;
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001367 node* node = make_node_entry(req, parent_node, name, child_path, &e, &error_code);
Zimedbe69e2019-12-13 18:49:36 +00001368 if (node) {
Narayan Kamathaef84a12020-01-02 15:20:13 +00001369 node->AddHandle(h);
shafik1e3a2672019-08-16 14:51:55 +01001370 fuse_reply_create(req, &e, fi);
1371 } else {
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001372 CHECK(error_code != 0);
1373 fuse_reply_err(req, error_code);
shafik1e3a2672019-08-16 14:51:55 +01001374 }
1375}
1376/*
1377static void pf_getlk(fuse_req_t req, fuse_ino_t ino,
1378 struct fuse_file_info* fi, struct flock* lock)
1379{
1380 cout << "TODO:" << __func__;
1381}
1382
1383static void pf_setlk(fuse_req_t req, fuse_ino_t ino,
1384 struct fuse_file_info* fi,
1385 struct flock* lock, int sleep)
1386{
1387 cout << "TODO:" << __func__;
1388}
1389
1390static void pf_bmap(fuse_req_t req, fuse_ino_t ino, size_t blocksize,
1391 uint64_t idx)
1392{
1393 cout << "TODO:" << __func__;
1394}
1395
1396static void pf_ioctl(fuse_req_t req, fuse_ino_t ino, unsigned int cmd,
1397 void* arg, struct fuse_file_info* fi, unsigned flags,
1398 const void* in_buf, size_t in_bufsz, size_t out_bufsz)
1399{
1400 cout << "TODO:" << __func__;
1401}
1402
1403static void pf_poll(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi,
1404 struct fuse_pollhandle* ph)
1405{
1406 cout << "TODO:" << __func__;
1407}
1408
1409static void pf_retrieve_reply(fuse_req_t req, void* cookie, fuse_ino_t ino,
1410 off_t offset, struct fuse_bufvec* bufv)
1411{
1412 cout << "TODO:" << __func__;
1413}
1414
1415static void pf_flock(fuse_req_t req, fuse_ino_t ino,
1416 struct fuse_file_info* fi, int op)
1417{
1418 cout << "TODO:" << __func__;
1419}
1420
1421static void pf_fallocate(fuse_req_t req, fuse_ino_t ino, int mode,
1422 off_t offset, off_t length, struct fuse_file_info* fi)
1423{
1424 cout << "TODO:" << __func__;
1425}
1426*/
1427
1428static struct fuse_lowlevel_ops ops{
shafik8b57cd52019-09-06 10:51:29 +01001429 .init = pf_init,
Zim005cd812019-12-17 15:35:51 +00001430 .destroy = pf_destroy,
Nick Desaulniers17714b82019-11-05 09:44:35 -08001431 .lookup = pf_lookup, .forget = pf_forget, .getattr = pf_getattr,
1432 .setattr = pf_setattr,
Zimb9730bf2019-11-30 15:10:04 +00001433 .canonical_path = pf_canonical_path,
Nick Desaulniers17714b82019-11-05 09:44:35 -08001434 .mknod = pf_mknod, .mkdir = pf_mkdir, .unlink = pf_unlink,
1435 .rmdir = pf_rmdir,
shafik8b57cd52019-09-06 10:51:29 +01001436 /*.symlink = pf_symlink,*/
1437 .rename = pf_rename,
1438 /*.link = pf_link,*/
1439 .open = pf_open, .read = pf_read,
1440 /*.write = pf_write,*/
Nick Desaulniers17714b82019-11-05 09:44:35 -08001441 .flush = pf_flush, .release = pf_release, .fsync = pf_fsync,
1442 .opendir = pf_opendir, .readdir = pf_readdir, .releasedir = pf_releasedir,
1443 .fsyncdir = pf_fsyncdir, .statfs = pf_statfs,
shafik8b57cd52019-09-06 10:51:29 +01001444 /*.setxattr = pf_setxattr,
1445 .getxattr = pf_getxattr,
1446 .listxattr = pf_listxattr,
1447 .removexattr = pf_removexattr,*/
1448 .access = pf_access, .create = pf_create,
1449 /*.getlk = pf_getlk,
1450 .setlk = pf_setlk,
1451 .bmap = pf_bmap,
1452 .ioctl = pf_ioctl,
Nick Desaulniers17714b82019-11-05 09:44:35 -08001453 .poll = pf_poll,*/
1454 .write_buf = pf_write_buf,
1455 /*.retrieve_reply = pf_retrieve_reply,*/
1456 .forget_multi = pf_forget_multi,
shafik8b57cd52019-09-06 10:51:29 +01001457 /*.flock = pf_flock,
1458 .fallocate = pf_fallocate,*/
Nick Desaulniers17714b82019-11-05 09:44:35 -08001459 .readdirplus = pf_readdirplus,
1460 /*.copy_file_range = pf_copy_file_range,*/
shafik1e3a2672019-08-16 14:51:55 +01001461};
1462
1463static struct fuse_loop_config config = {
1464 .clone_fd = 0,
1465 .max_idle_threads = 10,
1466};
1467
Zimb353eb42019-12-17 15:29:48 +00001468static std::unordered_map<enum fuse_log_level, enum android_LogPriority> fuse_to_android_loglevel({
1469 {FUSE_LOG_EMERG, ANDROID_LOG_FATAL},
1470 {FUSE_LOG_ALERT, ANDROID_LOG_ERROR},
1471 {FUSE_LOG_CRIT, ANDROID_LOG_ERROR},
1472 {FUSE_LOG_ERR, ANDROID_LOG_ERROR},
1473 {FUSE_LOG_WARNING, ANDROID_LOG_WARN},
1474 {FUSE_LOG_NOTICE, ANDROID_LOG_INFO},
1475 {FUSE_LOG_INFO, ANDROID_LOG_DEBUG},
1476 {FUSE_LOG_DEBUG, ANDROID_LOG_VERBOSE},
1477 });
Zim724b8ca2019-11-09 09:37:24 +00001478
1479static void fuse_logger(enum fuse_log_level level, const char* fmt, va_list ap) {
Zim357e3072020-01-15 10:50:01 +00001480 __android_log_vprint(fuse_to_android_loglevel.at(level), LIBFUSE_LOG_TAG, fmt, ap);
Zim724b8ca2019-11-09 09:37:24 +00001481}
1482
Zimedbe69e2019-12-13 18:49:36 +00001483bool FuseDaemon::ShouldOpenWithFuse(int fd, bool for_read, const std::string& path) {
Zim5c57d832020-01-15 16:16:12 +00001484 TRACE_VERBOSE << "Checking if file should be opened with FUSE " << path;
Zimedbe69e2019-12-13 18:49:36 +00001485 bool use_fuse = false;
1486
1487 if (active.load(std::memory_order_acquire)) {
Narayan Kamathaef84a12020-01-02 15:20:13 +00001488 const node* node = node::LookupAbsolutePath(fuse->root, path);
Zimedbe69e2019-12-13 18:49:36 +00001489 if (node && node->HasCachedHandle()) {
1490 TRACE << "Should open " << path << " with FUSE. Reason: cache";
1491 use_fuse = true;
1492 } else {
1493 // If we are unable to set a lock, we should use fuse since we can't track
1494 // when all fd references (including dups) are closed. This can happen when
1495 // we try to set a write lock twice on the same file
1496 use_fuse = set_file_lock(fd, for_read, path);
1497 TRACE << "Should open " << path << (use_fuse ? " with" : " without")
1498 << " FUSE. Reason: lock";
1499 }
Zimedbe69e2019-12-13 18:49:36 +00001500 } else {
1501 TRACE << "FUSE daemon is inactive. Should not open " << path << " with FUSE";
1502 }
1503
1504 return use_fuse;
1505}
1506
1507FuseDaemon::FuseDaemon(JNIEnv* env, jobject mediaProvider) : mp(env, mediaProvider),
1508 active(false), fuse(nullptr) {}
shafik1e3a2672019-08-16 14:51:55 +01001509
Zim7c8712d2019-10-03 21:01:26 +01001510void FuseDaemon::Start(const int fd, const std::string& path) {
shafik1e3a2672019-08-16 14:51:55 +01001511 struct fuse_args args;
1512 struct fuse_cmdline_opts opts;
shafik1e3a2672019-08-16 14:51:55 +01001513
shafik458d1102019-09-06 18:21:36 +01001514 SetMinimumLogSeverity(android::base::DEBUG);
1515
shafik1e3a2672019-08-16 14:51:55 +01001516 struct stat stat;
shafik1e3a2672019-08-16 14:51:55 +01001517
Zim7c8712d2019-10-03 21:01:26 +01001518 if (lstat(path.c_str(), &stat)) {
1519 LOG(ERROR) << "ERROR: failed to stat source " << path;
Zim3e45d9b2019-08-19 21:14:14 +01001520 return;
1521 }
shafik1e3a2672019-08-16 14:51:55 +01001522
Zim3e45d9b2019-08-19 21:14:14 +01001523 if (!S_ISDIR(stat.st_mode)) {
shafik458d1102019-09-06 18:21:36 +01001524 LOG(ERROR) << "ERROR: source is not a directory";
Zim3e45d9b2019-08-19 21:14:14 +01001525 return;
1526 }
shafik1e3a2672019-08-16 14:51:55 +01001527
1528 args = FUSE_ARGS_INIT(0, nullptr);
Zim7c8712d2019-10-03 21:01:26 +01001529 if (fuse_opt_add_arg(&args, path.c_str()) || fuse_opt_add_arg(&args, "-odebug") ||
1530 fuse_opt_add_arg(&args, ("-omax_read=" + std::to_string(MAX_READ_SIZE)).c_str())) {
shafik458d1102019-09-06 18:21:36 +01001531 LOG(ERROR) << "ERROR: failed to set options";
shafik1e3a2672019-08-16 14:51:55 +01001532 return;
1533 }
1534
Narayan Kamathaef84a12020-01-02 15:20:13 +00001535 struct fuse fuse_default(path);
shafikc3f62672019-08-30 11:15:48 +01001536 fuse_default.mp = &mp;
Zimedbe69e2019-12-13 18:49:36 +00001537 // fuse_default is stack allocated, but it's safe to save it as an instance variable because
1538 // this method blocks and FuseDaemon#active tells if we are currently blocking
1539 fuse = &fuse_default;
shafikc3f62672019-08-30 11:15:48 +01001540
shafikb334a612019-09-30 20:38:16 +01001541 // Used by pf_read: redacted ranges are represented by zeroized ranges of bytes,
1542 // so we mmap the maximum length of redacted ranges in the beginning and save memory allocations
1543 // on each read.
1544 fuse_default.zero_addr = static_cast<char*>(mmap(
1545 NULL, MAX_READ_SIZE, PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, /*fd*/ -1, /*off*/ 0));
1546 if (fuse_default.zero_addr == MAP_FAILED) {
1547 LOG(FATAL) << "mmap failed - could not start fuse! errno = " << errno;
1548 }
1549
Zim7c8712d2019-10-03 21:01:26 +01001550 umask(0);
1551
Zim724b8ca2019-11-09 09:37:24 +00001552 // Custom logging for libfuse
Zim724b8ca2019-11-09 09:37:24 +00001553 fuse_set_log_func(fuse_logger);
1554
shafik1e3a2672019-08-16 14:51:55 +01001555 struct fuse_session
1556 * se = fuse_session_new(&args, &ops, sizeof(ops), &fuse_default);
Zim7e0d3142019-10-17 21:06:12 +01001557 if (!se) {
1558 PLOG(ERROR) << "Failed to create session ";
1559 return;
1560 }
shafik1e3a2672019-08-16 14:51:55 +01001561 se->fd = fd;
Zim7c8712d2019-10-03 21:01:26 +01001562 se->mountpoint = strdup(path.c_str());
Zim3e45d9b2019-08-19 21:14:14 +01001563
1564 // Single thread. Useful for debugging
1565 // fuse_session_loop(se);
1566 // Multi-threaded
Zim7e0d3142019-10-17 21:06:12 +01001567 LOG(INFO) << "Starting fuse...";
Zimedbe69e2019-12-13 18:49:36 +00001568 active.store(true, std::memory_order_release);
shafik1e3a2672019-08-16 14:51:55 +01001569 fuse_session_loop_mt(se, &config);
Zim7e0d3142019-10-17 21:06:12 +01001570 LOG(INFO) << "Ending fuse...";
Zim3e45d9b2019-08-19 21:14:14 +01001571
Zim7c8712d2019-10-03 21:01:26 +01001572 if (munmap(fuse_default.zero_addr, MAX_READ_SIZE)) {
1573 PLOG(ERROR) << "munmap failed!";
shafikb334a612019-09-30 20:38:16 +01001574 }
1575
Zim7e0d3142019-10-17 21:06:12 +01001576 fuse_opt_free_args(&args);
1577 fuse_session_destroy(se);
Zimedbe69e2019-12-13 18:49:36 +00001578 active.store(false, std::memory_order_relaxed);
Zim7e0d3142019-10-17 21:06:12 +01001579 LOG(INFO) << "Ended fuse";
1580 return;
shafik1e3a2672019-08-16 14:51:55 +01001581}
1582} //namespace fuse
shafik8b57cd52019-09-06 10:51:29 +01001583} // namespace mediaprovider