blob: 833e9c646d97efc90779e52cc8aebe5bbc2c1d22 [file] [log] [blame]
shafik1e3a2672019-08-16 14:51:55 +01001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Zimec8d5722019-12-05 07:26:13 +000015#define ATRACE_TAG ATRACE_TAG_APP
shafik1e3a2672019-08-16 14:51:55 +010016#define LOG_TAG "FuseDaemon"
Zim357e3072020-01-15 10:50:01 +000017#define LIBFUSE_LOG_TAG "libfuse"
shafik1e3a2672019-08-16 14:51:55 +010018
19#include "FuseDaemon.h"
Zim29f9ff52021-01-20 10:47:04 +000020#include "android-base/strings.h"
shafik1e3a2672019-08-16 14:51:55 +010021
shafik458d1102019-09-06 18:21:36 +010022#include <android-base/logging.h>
Zim32129b62020-03-11 11:37:16 +000023#include <android-base/properties.h>
Zim724b8ca2019-11-09 09:37:24 +000024#include <android/log.h>
Zimec8d5722019-12-05 07:26:13 +000025#include <android/trace.h>
shafik1e3a2672019-08-16 14:51:55 +010026#include <ctype.h>
27#include <dirent.h>
28#include <errno.h>
29#include <fcntl.h>
shafik8b57cd52019-09-06 10:51:29 +010030#include <fuse_i.h>
Zim724b8ca2019-11-09 09:37:24 +000031#include <fuse_log.h>
shafik8b57cd52019-09-06 10:51:29 +010032#include <fuse_lowlevel.h>
shafik1e3a2672019-08-16 14:51:55 +010033#include <inttypes.h>
34#include <limits.h>
35#include <linux/fuse.h>
shafik1e3a2672019-08-16 14:51:55 +010036#include <stdbool.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40#include <sys/inotify.h>
shafikb334a612019-09-30 20:38:16 +010041#include <sys/mman.h>
shafik1e3a2672019-08-16 14:51:55 +010042#include <sys/mount.h>
43#include <sys/param.h>
44#include <sys/resource.h>
45#include <sys/stat.h>
46#include <sys/statfs.h>
47#include <sys/statvfs.h>
48#include <sys/time.h>
49#include <sys/types.h>
50#include <sys/uio.h>
51#include <unistd.h>
shafik1e3a2672019-08-16 14:51:55 +010052
shafik8b57cd52019-09-06 10:51:29 +010053#include <iostream>
Narayan Kamath8d76d0c2019-12-31 13:14:50 +000054#include <list>
Paul Lawrence7e4a5a82019-09-27 21:39:49 +020055#include <map>
Narayan Kamath768bea32019-12-27 16:23:23 +000056#include <mutex>
Paul Lawrence7e4a5a82019-09-27 21:39:49 +020057#include <queue>
Zim859db932019-12-13 00:09:17 +000058#include <regex>
Paul Lawrence7e4a5a82019-09-27 21:39:49 +020059#include <thread>
Zim724b8ca2019-11-09 09:37:24 +000060#include <unordered_map>
Narayan Kamath92bf67b2020-01-03 17:49:09 +000061#include <unordered_set>
shafikc3f62672019-08-30 11:15:48 +010062#include <vector>
shafik1e3a2672019-08-16 14:51:55 +010063
shafikc3f62672019-08-30 11:15:48 +010064#include "MediaProviderWrapper.h"
Corina633099b2020-06-17 21:55:33 +010065#include "libfuse_jni/FuseUtils.h"
Sahana Raoa82bd6a2019-10-10 18:10:37 +010066#include "libfuse_jni/ReaddirHelper.h"
shafikc3f62672019-08-30 11:15:48 +010067#include "libfuse_jni/RedactionInfo.h"
Narayan Kamathaef84a12020-01-02 15:20:13 +000068#include "node-inl.h"
shafikc3f62672019-08-30 11:15:48 +010069
Sahana Raoa82bd6a2019-10-10 18:10:37 +010070using mediaprovider::fuse::DirectoryEntry;
Narayan Kamathaef84a12020-01-02 15:20:13 +000071using mediaprovider::fuse::dirhandle;
72using mediaprovider::fuse::handle;
73using mediaprovider::fuse::node;
shafikc3f62672019-08-30 11:15:48 +010074using mediaprovider::fuse::RedactionInfo;
Narayan Kamath8d76d0c2019-12-31 13:14:50 +000075using std::list;
Jeff Sharkey7469b982019-08-28 16:51:02 -060076using std::string;
shafikc3f62672019-08-30 11:15:48 +010077using std::vector;
shafik1e3a2672019-08-16 14:51:55 +010078
Narayan Kamath88203dc2019-08-30 17:19:38 +010079// logging macros to avoid duplication.
Nandana Dutt154cb5d2020-06-04 11:53:31 +010080#define TRACE_NODE(__node, __req) \
81 LOG(VERBOSE) << __FUNCTION__ << " : " << #__node << " = [" << get_name(__node) \
Alessio Balsini328abac2020-11-25 17:49:25 +000082 << "] (uid=" << (__req)->ctx.uid << ") "
shafik1e3a2672019-08-16 14:51:55 +010083
Zimec8d5722019-12-05 07:26:13 +000084#define ATRACE_NAME(name) ScopedTrace ___tracer(name)
85#define ATRACE_CALL() ATRACE_NAME(__FUNCTION__)
86
87class ScopedTrace {
88 public:
Narayan Kamath64b44352019-12-27 17:07:50 +000089 explicit inline ScopedTrace(const char *name) {
Zimec8d5722019-12-05 07:26:13 +000090 ATrace_beginSection(name);
91 }
92
93 inline ~ScopedTrace() {
94 ATrace_endSection();
95 }
96};
97
Zim32129b62020-03-11 11:37:16 +000098const bool IS_OS_DEBUGABLE = android::base::GetIntProperty("ro.debuggable", 0);
99
shafik1e3a2672019-08-16 14:51:55 +0100100#define FUSE_UNKNOWN_INO 0xffffffff
101
Ricky Waif40c4022020-04-15 19:00:06 +0100102// Stolen from: android_filesystem_config.h
103#define AID_APP_START 10000
104
shafikb334a612019-09-30 20:38:16 +0100105constexpr size_t MAX_READ_SIZE = 128 * 1024;
Zim859db932019-12-13 00:09:17 +0000106// Stolen from: UserHandle#getUserId
107constexpr int PER_USER_RANGE = 100000;
shafikb334a612019-09-30 20:38:16 +0100108
Martijn Coenen44ef6302020-11-06 10:32:32 +0100109// Stolen from: UserManagerService
110constexpr int MAX_USER_ID = UINT32_MAX / PER_USER_RANGE;
111
Zim3cde2662021-02-22 21:20:33 +0000112const int MY_UID = getuid();
113const int MY_USER_ID = MY_UID / PER_USER_RANGE;
114const std::string MY_USER_ID_STRING(std::to_string(MY_UID / PER_USER_RANGE));
115
Ricky Waif40c4022020-04-15 19:00:06 +0100116// Regex copied from FileUtils.java in MediaProvider, but without media directory.
117const std::regex PATTERN_OWNED_PATH(
Zim78ffeeb2020-09-22 20:15:25 +0100118 "^/storage/[^/]+/(?:[0-9]+/)?Android/(?:data|obb)/([^/]+)(/?.*)?",
119 std::regex_constants::icase);
Ricky Waif40c4022020-04-15 19:00:06 +0100120
]3e9d56c2021-03-15 16:24:17 +0000121static constexpr char TRANSFORM_SYNTHETIC_DIR[] = "synthetic";
122static constexpr char TRANSFORM_TRANSCODE_DIR[] = "transcode";
123
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200124/*
125 * In order to avoid double caching with fuse, call fadvise on the file handles
126 * in the underlying file system. However, if this is done on every read/write,
127 * the fadvises cause a very significant slowdown in tests (specifically fio
128 * seq_write). So call fadvise on the file handles with the most reads/writes
129 * only after a threshold is passed.
130 */
131class FAdviser {
132 public:
133 FAdviser() : thread_(MessageLoop, this), total_size_(0) {}
134
135 ~FAdviser() {
136 SendMessage(Message::quit);
137 thread_.join();
138 }
139
140 void Record(int fd, size_t size) { SendMessage(Message::record, fd, size); }
141
142 void Close(int fd) { SendMessage(Message::close, fd); }
143
144 private:
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200145 struct Message {
146 enum Type { record, close, quit };
147 Type type;
148 int fd;
149 size_t size;
150 };
151
152 void RecordImpl(int fd, size_t size) {
153 total_size_ += size;
154
155 // Find or create record in files_
156 // Remove record from sizes_ if it exists, adjusting size appropriately
157 auto file = files_.find(fd);
158 if (file != files_.end()) {
159 auto old_size = file->second;
160 size += old_size->first;
161 sizes_.erase(old_size);
162 } else {
163 file = files_.insert(Files::value_type(fd, sizes_.end())).first;
164 }
165
166 // Now (re) insert record in sizes_
167 auto new_size = sizes_.insert(Sizes::value_type(size, fd));
168 file->second = new_size;
169
170 if (total_size_ < threshold_) return;
171
172 LOG(INFO) << "Threshold exceeded - fadvising " << total_size_;
173 while (!sizes_.empty() && total_size_ > target_) {
174 auto size = --sizes_.end();
175 total_size_ -= size->first;
176 posix_fadvise(size->second, 0, 0, POSIX_FADV_DONTNEED);
177 files_.erase(size->second);
178 sizes_.erase(size);
179 }
180 LOG(INFO) << "Threshold now " << total_size_;
181 }
182
183 void CloseImpl(int fd) {
184 auto file = files_.find(fd);
185 if (file == files_.end()) return;
186
187 total_size_ -= file->second->first;
188 sizes_.erase(file->second);
189 files_.erase(file);
190 }
191
192 void MessageLoopImpl() {
193 while (1) {
194 Message message;
195
196 {
197 std::unique_lock<std::mutex> lock(mutex_);
198 cv_.wait(lock, [this] { return !queue_.empty(); });
199 message = queue_.front();
200 queue_.pop();
201 }
202
203 switch (message.type) {
204 case Message::record:
205 RecordImpl(message.fd, message.size);
206 break;
207
208 case Message::close:
209 CloseImpl(message.fd);
210 break;
211
212 case Message::quit:
213 return;
214 }
215 }
216 }
217
218 static int MessageLoop(FAdviser* ptr) {
219 ptr->MessageLoopImpl();
220 return 0;
221 }
222
223 void SendMessage(Message::Type type, int fd = -1, size_t size = 0) {
224 {
225 std::unique_lock<std::mutex> lock(mutex_);
226 Message message = {type, fd, size};
227 queue_.push(message);
228 }
229 cv_.notify_one();
230 }
231
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200232 std::mutex mutex_;
233 std::condition_variable cv_;
Zim695a1272020-06-15 18:14:08 +0100234 std::queue<Message> queue_;
235 std::thread thread_;
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200236
237 typedef std::multimap<size_t, int> Sizes;
238 typedef std::map<int, Sizes::iterator> Files;
239
240 Files files_;
241 Sizes sizes_;
242 size_t total_size_;
243
244 const size_t threshold_ = 64 * 1024 * 1024;
245 const size_t target_ = 32 * 1024 * 1024;
246};
247
shafik1e3a2672019-08-16 14:51:55 +0100248/* Single FUSE mount */
249struct fuse {
Biswarup Pal93f4ec12021-02-15 13:39:36 +0000250 explicit fuse(const std::string& _path, ino_t _ino)
Narayan Kamath568f17a2020-02-19 13:45:29 +0000251 : path(_path),
252 tracker(mediaprovider::fuse::NodeTracker(&lock)),
Biswarup Pal93f4ec12021-02-15 13:39:36 +0000253 root(node::CreateRoot(_path, &lock, _ino, &tracker)),
Narayan Kamath568f17a2020-02-19 13:45:29 +0000254 mp(0),
Martijn Coenen87133092020-10-14 17:00:28 +0200255 zero_addr(0),
Alessio Balsinif220a962020-07-13 12:01:13 +0100256 disable_dentry_cache(false),
257 passthrough(false) {}
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200258
Narayan Kamathaef84a12020-01-02 15:20:13 +0000259 inline bool IsRoot(const node* node) const { return node == root; }
shafik1e3a2672019-08-16 14:51:55 +0100260
Zimb2834012020-06-17 13:26:27 +0100261 inline string GetEffectiveRootPath() {
Zim3b6ff4d2021-03-03 11:14:59 +0000262 if (android::base::StartsWith(path, "/storage/emulated")) {
Zim3cde2662021-02-22 21:20:33 +0000263 return path + "/" + MY_USER_ID_STRING;
Zimb2834012020-06-17 13:26:27 +0100264 }
265 return path;
266 }
267
]3e9d56c2021-03-15 16:24:17 +0000268 inline string GetTransformsDir() { return GetEffectiveRootPath() + "/.transforms"; }
269
Narayan Kamathaef84a12020-01-02 15:20:13 +0000270 // Note that these two (FromInode / ToInode) conversion wrappers are required
271 // because fuse_lowlevel_ops documents that the root inode is always one
272 // (see FUSE_ROOT_ID in fuse_lowlevel.h). There are no particular requirements
273 // on any of the other inodes in the FS.
Ricky Wai44670762020-05-01 11:25:28 +0100274 inline node* FromInode(__u64 inode) {
Narayan Kamathaef84a12020-01-02 15:20:13 +0000275 if (inode == FUSE_ROOT_ID) {
276 return root;
277 }
shafik1e3a2672019-08-16 14:51:55 +0100278
Ricky Wai44670762020-05-01 11:25:28 +0100279 return node::FromInode(inode, &tracker);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000280 }
281
282 inline __u64 ToInode(node* node) const {
283 if (IsRoot(node)) {
284 return FUSE_ROOT_ID;
285 }
286
287 return node::ToInode(node);
288 }
289
290 std::recursive_mutex lock;
291 const string path;
Narayan Kamath568f17a2020-02-19 13:45:29 +0000292 // The Inode tracker associated with this FUSE instance.
293 mediaprovider::fuse::NodeTracker tracker;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000294 node* const root;
Zima76c3492020-02-19 01:23:26 +0000295 struct fuse_session* se;
shafikc3f62672019-08-30 11:15:48 +0100296
297 /*
298 * Used to make JNI calls to MediaProvider.
299 * Responsibility of freeing this object falls on corresponding
300 * FuseDaemon object.
301 */
302 mediaprovider::fuse::MediaProviderWrapper* mp;
shafikb334a612019-09-30 20:38:16 +0100303
304 /*
305 * Points to a range of zeroized bytes, used by pf_read to represent redacted ranges.
306 * The memory is read only and should never be modified.
307 */
Narayan Kamathaef84a12020-01-02 15:20:13 +0000308 /* const */ char* zero_addr;
Paul Lawrence7e4a5a82019-09-27 21:39:49 +0200309
310 FAdviser fadviser;
Zimd0435b22020-03-05 13:52:51 +0000311
312 std::atomic_bool* active;
Martijn Coenen87133092020-10-14 17:00:28 +0200313 std::atomic_bool disable_dentry_cache;
Zim148cbe22020-11-17 15:58:29 +0000314 std::atomic_bool passthrough;
Biswarup Pal93f4ec12021-02-15 13:39:36 +0000315 // FUSE device id.
316 std::atomic_uint dev;
shafik1e3a2672019-08-16 14:51:55 +0100317};
318
]3e9d56c2021-03-15 16:24:17 +0000319enum class FuseOp { lookup, readdir, mknod, mkdir, create };
320
Zim32129b62020-03-11 11:37:16 +0000321static inline string get_name(node* n) {
322 if (n) {
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100323 std::string name = IS_OS_DEBUGABLE ? "real_path: " + n->BuildPath() + " " : "";
324 name += "node_path: " + n->BuildSafePath();
Zim32129b62020-03-11 11:37:16 +0000325 return name;
326 }
327 return "?";
shafik458d1102019-09-06 18:21:36 +0100328}
329
shafik1e3a2672019-08-16 14:51:55 +0100330static inline __u64 ptr_to_id(void* ptr) {
331 return (__u64)(uintptr_t) ptr;
332}
333
Zimedbe69e2019-12-13 18:49:36 +0000334/*
335 * Set an F_RDLCK or F_WRLCKK on fd with fcntl(2).
336 *
337 * This is called before the MediaProvider returns fd from the lower file
338 * system to an app over the ContentResolver interface. This allows us
339 * check with is_file_locked if any reference to that fd is still open.
340 */
341static int set_file_lock(int fd, bool for_read, const std::string& path) {
342 std::string lock_str = (for_read ? "read" : "write");
Zimedbe69e2019-12-13 18:49:36 +0000343
344 struct flock fl{};
345 fl.l_type = for_read ? F_RDLCK : F_WRLCK;
346 fl.l_whence = SEEK_SET;
347
348 int res = fcntl(fd, F_OFD_SETLK, &fl);
349 if (res) {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +0000350 PLOG(WARNING) << "Failed to set lock: " << lock_str;
Zimedbe69e2019-12-13 18:49:36 +0000351 return res;
352 }
Zimedbe69e2019-12-13 18:49:36 +0000353 return res;
354}
355
356/*
357 * Check if an F_RDLCK or F_WRLCK is set on fd with fcntl(2).
358 *
359 * This is used to determine if the MediaProvider has given an fd to the lower fs to an app over
360 * the ContentResolver interface. Before that happens, we always call set_file_lock on the file
361 * allowing us to know if any reference to that fd is still open here.
362 *
363 * Returns true if fd may have a lock, false otherwise
364 */
365static bool is_file_locked(int fd, const std::string& path) {
Zimedbe69e2019-12-13 18:49:36 +0000366 struct flock fl{};
367 fl.l_type = F_WRLCK;
368 fl.l_whence = SEEK_SET;
369
370 int res = fcntl(fd, F_OFD_GETLK, &fl);
371 if (res) {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +0000372 PLOG(WARNING) << "Failed to check lock";
Zimedbe69e2019-12-13 18:49:36 +0000373 // Assume worst
374 return true;
375 }
376 bool locked = fl.l_type != F_UNLCK;
Zimedbe69e2019-12-13 18:49:36 +0000377 return locked;
378}
379
shafik1e3a2672019-08-16 14:51:55 +0100380static struct fuse* get_fuse(fuse_req_t req) {
381 return reinterpret_cast<struct fuse*>(fuse_req_userdata(req));
382}
383
Ricky Waif40c4022020-04-15 19:00:06 +0100384static bool is_package_owned_path(const string& path, const string& fuse_path) {
385 if (path.rfind(fuse_path, 0) != 0) {
386 return false;
387 }
388 return std::regex_match(path, PATTERN_OWNED_PATH);
389}
390
Zim33aea102020-06-19 15:49:47 +0100391// See fuse_lowlevel.h fuse_lowlevel_notify_inval_entry for how to call this safetly without
392// deadlocking the kernel
393static void fuse_inval(fuse_session* se, fuse_ino_t parent_ino, fuse_ino_t child_ino,
394 const string& child_name, const string& path) {
Zim3cde2662021-02-22 21:20:33 +0000395 if (mediaprovider::fuse::containsMount(path, MY_USER_ID_STRING)) {
Zim33aea102020-06-19 15:49:47 +0100396 LOG(WARNING) << "Ignoring attempt to invalidate dentry for FUSE mounts";
397 return;
398 }
399
400 if (fuse_lowlevel_notify_inval_entry(se, parent_ino, child_name.c_str(), child_name.size())) {
401 // Invalidating the dentry can fail if there's no dcache entry, however, there may still
402 // be cached attributes, so attempt to invalidate those by invalidating the inode
403 fuse_lowlevel_notify_inval_inode(se, child_ino, 0, 0);
404 }
Zim89962312020-04-22 21:21:53 +0100405}
406
Zim3b6ff4d2021-03-03 11:14:59 +0000407static double get_entry_timeout(const string& path, node* node, struct fuse* fuse) {
408 string media_path = fuse->GetEffectiveRootPath() + "/Android/media";
Zimded1ab92021-01-15 10:36:17 +0000409 if (fuse->disable_dentry_cache || node->ShouldInvalidate() ||
Zim3b6ff4d2021-03-03 11:14:59 +0000410 is_package_owned_path(path, fuse->path) || android::base::StartsWith(path, media_path)) {
Zimb2834012020-06-17 13:26:27 +0100411 // We set dentry timeout to 0 for the following reasons:
Martijn Coenen87133092020-10-14 17:00:28 +0200412 // 1. The dentry cache was completely disabled
Zimded1ab92021-01-15 10:36:17 +0000413 // 2.1 Case-insensitive lookups need to invalidate other case-insensitive dentry matches
414 // 2.2 Nodes supporting transforms need to be invalidated, so that subsequent lookups by a
415 // uid requiring a transform is guaranteed to come to the FUSE daemon.
Martijn Coenen87133092020-10-14 17:00:28 +0200416 // 3. With app data isolation enabled, app A should not guess existence of app B from the
Zimb2834012020-06-17 13:26:27 +0100417 // Android/{data,obb}/<package> paths, hence we prevent the kernel from caching that
418 // information.
Zim3b6ff4d2021-03-03 11:14:59 +0000419 // 4. Installd might delete Android/media/<package> dirs when app data is cleared.
Zim867fece2020-09-23 15:23:19 +0100420 // This can leave a stale entry in the kernel dcache, and break subsequent creation of the
421 // dir via FUSE.
422 return 0;
423 }
Zim3b6ff4d2021-03-03 11:14:59 +0000424 return std::numeric_limits<double>::max();
Zim867fece2020-09-23 15:23:19 +0100425}
426
427static std::string get_path(node* node) {
428 const string& io_path = node->GetIoPath();
429 return io_path.empty() ? node->BuildPath() : io_path;
430}
431
]3e9d56c2021-03-15 16:24:17 +0000432// Returns true if the path resides under .transforms/synthetic.
433// NOTE: currently only file paths corresponding to redacted URIs reside under this folder. The path
434// itself never exists and just a link for transformation.
435static inline bool is_synthetic_path(const string& path, struct fuse* fuse) {
436 return android::base::StartsWithIgnoreCase(
437 path, fuse->GetTransformsDir() + "/" + TRANSFORM_SYNTHETIC_DIR);
438}
439
Zim549ee7d2021-03-19 17:26:20 +0000440static inline bool is_transcode_supported_path(const string& path, struct fuse* fuse) {
441 // Keep in sync with MediaProvider#supportsTranscode
442 return android::base::EndsWithIgnoreCase(path, ".mp4") &&
443 android::base::StartsWithIgnoreCase(path,
444 fuse->GetEffectiveRootPath() + "/dcim/camera/");
445}
446
]3e9d56c2021-03-15 16:24:17 +0000447static inline bool is_transforms_dir_path(const string& path, struct fuse* fuse) {
448 return android::base::StartsWithIgnoreCase(path, fuse->GetTransformsDir());
449}
450
451static std::unique_ptr<mediaprovider::fuse::FileLookupResult> validate_node_path(
452 const std::string& path, const std::string& name, fuse_req_t req, int* error_code,
453 struct fuse_entry_param* e, const FuseOp op) {
454 struct fuse* fuse = get_fuse(req);
455 const struct fuse_ctx* ctx = fuse_req_ctx(req);
456 memset(e, 0, sizeof(*e));
457
458 const bool synthetic_path = is_synthetic_path(path, fuse);
459 if (lstat(path.c_str(), &e->attr) < 0 && !(op == FuseOp::lookup && synthetic_path)) {
460 *error_code = errno;
461 return nullptr;
462 }
463
464 if (is_transforms_dir_path(path, fuse)) {
465 if (op == FuseOp::lookup) {
466 // Lookups are only allowed under .transforms/synthetic dir
467 if (!(android::base::EqualsIgnoreCase(path, fuse->GetTransformsDir()) ||
468 android::base::StartsWithIgnoreCase(
469 path, fuse->GetTransformsDir() + "/" + TRANSFORM_SYNTHETIC_DIR))) {
470 *error_code = ENONET;
471 return nullptr;
472 }
473 } else {
474 // user-code is only allowed to make lookups under .transforms dir, and that too only
475 // under .transforms/synthetic dir
476 *error_code = ENOENT;
477 return nullptr;
478 }
479 }
480
481 if (S_ISDIR(e->attr.st_mode)) {
482 // now that we have reached this point, ops on directories are safe and require no
483 // transformation.
484 return std::make_unique<mediaprovider::fuse::FileLookupResult>(0, 0, 0, true, false, "");
485 }
486
Zim549ee7d2021-03-19 17:26:20 +0000487 if (!synthetic_path && !is_transcode_supported_path(path, fuse)) {
488 // Transforms are only supported for synthetic or transcode-supported paths
489 return std::make_unique<mediaprovider::fuse::FileLookupResult>(0, 0, 0, true, false, "");
490 }
491
]3e9d56c2021-03-15 16:24:17 +0000492 // Handle potential file transforms
493 std::unique_ptr<mediaprovider::fuse::FileLookupResult> file_lookup_result =
494 fuse->mp->FileLookup(path, req->ctx.uid, req->ctx.pid);
495
496 if (!file_lookup_result) {
497 // Fail lookup if we can't fetch FileLookupResult for path
498 LOG(WARNING) << "Failed to fetch FileLookupResult for " << path;
499 *error_code = ENOENT;
500 return nullptr;
501 }
502
503 const string& io_path = file_lookup_result->io_path;
504 // Update size with io_path size if io_path is not same as path
505 if (!io_path.empty() && (io_path != path) && (lstat(io_path.c_str(), &e->attr) < 0)) {
506 *error_code = errno;
507 return nullptr;
508 }
509
510 return file_lookup_result;
511}
512
Narayan Kamathaef84a12020-01-02 15:20:13 +0000513static node* make_node_entry(fuse_req_t req, node* parent, const string& name, const string& path,
]3e9d56c2021-03-15 16:24:17 +0000514 struct fuse_entry_param* e, int* error_code, const FuseOp op) {
shafik1e3a2672019-08-16 14:51:55 +0100515 struct fuse* fuse = get_fuse(req);
Martijn Coenenb8ff4eb2019-12-17 09:55:17 +0100516 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000517 node* node;
shafik1e3a2672019-08-16 14:51:55 +0100518
Jeff Sharkey7469b982019-08-28 16:51:02 -0600519 memset(e, 0, sizeof(*e));
]3e9d56c2021-03-15 16:24:17 +0000520
521 std::unique_ptr<mediaprovider::fuse::FileLookupResult> file_lookup_result =
522 validate_node_path(path, name, req, error_code, e, op);
523 if (!file_lookup_result) {
524 // Fail lookup if we can't validate |path, |errno| would have already been set
525 return nullptr;
shafik1e3a2672019-08-16 14:51:55 +0100526 }
527
]3e9d56c2021-03-15 16:24:17 +0000528 const bool should_invalidate = file_lookup_result->transforms_supported;
529 const bool transforms_complete = file_lookup_result->transforms_complete;
530 const int transforms = file_lookup_result->transforms;
531 const int transforms_reason = file_lookup_result->transforms_reason;
532 const string& io_path = file_lookup_result->io_path;
Zim867fece2020-09-23 15:23:19 +0100533
Zimed257c12020-10-15 13:47:45 +0100534 node = parent->LookupChildByName(name, true /* acquire */, transforms);
Narayan Kamatheca34252020-02-11 13:08:37 +0000535 if (!node) {
Biswarup Pal93f4ec12021-02-15 13:39:36 +0000536 ino_t ino = e->attr.st_ino;
Zimded1ab92021-01-15 10:36:17 +0000537 node = ::node::Create(parent, name, io_path, should_invalidate, transforms_complete,
Biswarup Pal93f4ec12021-02-15 13:39:36 +0000538 transforms, transforms_reason, &fuse->lock, ino, &fuse->tracker);
Corina633099b2020-06-17 21:55:33 +0100539 } else if (!mediaprovider::fuse::containsMount(path, std::to_string(getuid() / PER_USER_RANGE))) {
Corina633099b2020-06-17 21:55:33 +0100540 // Only invalidate a path if it does not contain mount.
Zim0852ba72020-06-09 11:50:33 +0100541 // Invalidate both names to ensure there's no dentry left in the kernel after the following
542 // operations:
543 // 1) touch foo, touch FOO, unlink *foo*
544 // 2) touch foo, touch FOO, unlink *FOO*
545 // Invalidating lookup_name fixes (1) and invalidating node_name fixes (2)
Zimded1ab92021-01-15 10:36:17 +0000546 // SetShouldInvalidate invalidates lookup_name by using 0 timeout below and we explicitly
Zim33aea102020-06-19 15:49:47 +0100547 // invalidate node_name if different case
548 // Note that we invalidate async otherwise we will deadlock the kernel
549 if (name != node->GetName()) {
Zimf2b47b42020-09-16 14:54:06 +0100550 // Record that we have made a case insensitive lookup, this allows us invalidate nodes
551 // correctly on subsequent lookups for the case of |node|
Zimded1ab92021-01-15 10:36:17 +0000552 node->SetShouldInvalidate();
Zimf2b47b42020-09-16 14:54:06 +0100553
Narayan Kamath8b296f52020-07-29 13:10:17 +0100554 // Make copies of the node name and path so we're not attempting to acquire
555 // any node locks from the invalidation thread. Depending on timing, we may end
556 // up invalidating the wrong inode but that shouldn't result in correctness issues.
557 const fuse_ino_t parent_ino = fuse->ToInode(parent);
558 const fuse_ino_t child_ino = fuse->ToInode(node);
559 const std::string& node_name = node->GetName();
Narayan Kamath8b296f52020-07-29 13:10:17 +0100560 std::thread t([=]() { fuse_inval(fuse->se, parent_ino, child_ino, node_name, path); });
Zim33aea102020-06-19 15:49:47 +0100561 t.detach();
562 }
Zime5433682021-03-10 12:06:54 +0000563
564 // This updated value allows us correctly decide if to keep_cache and use direct_io during
565 // FUSE_OPEN. Between the last lookup and this lookup, we might have deleted a cached
566 // transcoded file on the lower fs. A subsequent transcode at FUSE_READ should ensure we
567 // don't reuse any stale transcode page cache content.
568 node->SetTransformsComplete(transforms_complete);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000569 }
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100570 TRACE_NODE(node, req);
Zim89962312020-04-22 21:21:53 +0100571
Narayan Kamathfc0aa952019-12-31 13:31:49 +0000572 // This FS is not being exported via NFS so just a fixed generation number
573 // for now. If we do need this, we need to increment the generation ID each
574 // time the fuse daemon restarts because that's what it takes for us to
575 // reuse inode numbers.
576 e->generation = 0;
Zim8b2b6f22020-01-22 13:53:59 +0000577 e->ino = fuse->ToInode(node);
Zimded1ab92021-01-15 10:36:17 +0000578 e->entry_timeout = get_entry_timeout(path, node, fuse);
Zim3b6ff4d2021-03-03 11:14:59 +0000579 e->attr_timeout = std::numeric_limits<double>::max();
shafik1e3a2672019-08-16 14:51:55 +0100580 return node;
581}
582
shafik15e2d612019-10-31 20:10:25 +0000583static inline bool is_requesting_write(int flags) {
584 return flags & (O_WRONLY | O_RDWR);
585}
586
shafik1e3a2672019-08-16 14:51:55 +0100587namespace mediaprovider {
588namespace fuse {
589
590/**
591 * Function implementations
592 *
593 * These implement the various functions in fuse_lowlevel_ops
594 *
595 */
596
597static void pf_init(void* userdata, struct fuse_conn_info* conn) {
Alessio Balsinif220a962020-07-13 12:01:13 +0100598 struct fuse* fuse = reinterpret_cast<struct fuse*>(userdata);
599
Zima9fcd552019-08-29 15:17:04 +0100600 // We don't want a getattr request with every read request
Zim1100f342020-05-15 16:13:00 +0100601 conn->want &= ~FUSE_CAP_AUTO_INVAL_DATA & ~FUSE_CAP_READDIRPLUS_AUTO;
shafik8b57cd52019-09-06 10:51:29 +0100602 unsigned mask = (FUSE_CAP_SPLICE_WRITE | FUSE_CAP_SPLICE_MOVE | FUSE_CAP_SPLICE_READ |
603 FUSE_CAP_ASYNC_READ | FUSE_CAP_ATOMIC_O_TRUNC | FUSE_CAP_WRITEBACK_CACHE |
604 FUSE_CAP_EXPORT_SUPPORT | FUSE_CAP_FLOCK_LOCKS);
Alessio Balsinif220a962020-07-13 12:01:13 +0100605
606 if (fuse->passthrough) {
607 if (conn->capable & FUSE_CAP_PASSTHROUGH) {
608 mask |= FUSE_CAP_PASSTHROUGH;
609 } else {
610 LOG(WARNING) << "Passthrough feature not supported by the kernel";
611 fuse->passthrough = false;
612 }
613 }
614
shafik1e3a2672019-08-16 14:51:55 +0100615 conn->want |= conn->capable & mask;
shafikb334a612019-09-30 20:38:16 +0100616 conn->max_read = MAX_READ_SIZE;
Zimd0435b22020-03-05 13:52:51 +0000617
Zimd0435b22020-03-05 13:52:51 +0000618 fuse->active->store(true, std::memory_order_release);
shafik1e3a2672019-08-16 14:51:55 +0100619}
620
Zim005cd812019-12-17 15:35:51 +0000621static void pf_destroy(void* userdata) {
622 struct fuse* fuse = reinterpret_cast<struct fuse*>(userdata);
623 LOG(INFO) << "DESTROY " << fuse->path;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000624
625 node::DeleteTree(fuse->root);
shafik1e3a2672019-08-16 14:51:55 +0100626}
shafik1e3a2672019-08-16 14:51:55 +0100627
Ricky Wai44670762020-05-01 11:25:28 +0100628// Return true if the path is accessible for that uid.
629static bool is_app_accessible_path(MediaProviderWrapper* mp, const string& path, uid_t uid) {
Zim3cde2662021-02-22 21:20:33 +0000630 if (uid < AID_APP_START || uid == MY_UID) {
Ricky Wai44670762020-05-01 11:25:28 +0100631 return true;
632 }
633
Martijn Coenen71435d52020-06-15 20:23:40 +0200634 if (path == "/storage/emulated") {
635 // Apps should never refer to /storage/emulated - they should be using the user-spcific
636 // subdirs, eg /storage/emulated/0
637 return false;
638 }
639
Ricky Wai44670762020-05-01 11:25:28 +0100640 std::smatch match;
641 if (std::regex_match(path, match, PATTERN_OWNED_PATH)) {
642 const std::string& pkg = match[1];
Abhijeet Kaur077fdd52020-05-28 13:59:31 +0100643 // .nomedia is not a valid package. .nomedia always exists in /Android/data directory,
644 // and it's not an external file/directory of any package
645 if (pkg == ".nomedia") {
646 return true;
647 }
Martijn Coenenba3e6772021-04-28 09:27:54 +0200648 if (android::base::StartsWith(path, "/storage/emulated")) {
649 // Emulated storage bind-mounts app-private data directories, and so these
650 // should not be accessible through FUSE anyway.
651 LOG(WARNING) << "Rejected access to app-private dir on FUSE: " << path
652 << " from uid: " << uid;
653 return false;
654 }
Abhijeet Kaurb3ac2802020-10-07 16:42:42 +0100655 if (!mp->isUidAllowedAccessToDataOrObbPath(uid, path)) {
656 PLOG(WARNING) << "Invalid other package file access from " << uid << "(: " << path;
Ricky Wai44670762020-05-01 11:25:28 +0100657 return false;
658 }
659 }
660 return true;
661}
662
Zim859db932019-12-13 00:09:17 +0000663static std::regex storage_emulated_regex("^\\/storage\\/emulated\\/([0-9]+)");
Narayan Kamathaef84a12020-01-02 15:20:13 +0000664static node* do_lookup(fuse_req_t req, fuse_ino_t parent, const char* name,
]3e9d56c2021-03-15 16:24:17 +0000665 struct fuse_entry_param* e, int* error_code, const FuseOp op) {
shafik1e3a2672019-08-16 14:51:55 +0100666 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100667 node* parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +0100668 if (!parent_node) {
669 *error_code = ENOENT;
670 return nullptr;
671 }
Narayan Kamathaef84a12020-01-02 15:20:13 +0000672 string parent_path = parent_node->BuildPath();
Martijn Coenena5f19e82020-06-17 13:01:23 +0200673 // We should always allow lookups on the root, because failing them could cause
674 // bind mounts to be invalidated.
675 if (!fuse->IsRoot(parent_node) && !is_app_accessible_path(fuse->mp, parent_path, req->ctx.uid)) {
Ricky Wai44670762020-05-01 11:25:28 +0100676 *error_code = ENOENT;
677 return nullptr;
678 }
679
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100680 TRACE_NODE(parent_node, req);
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +0000681
]3e9d56c2021-03-15 16:24:17 +0000682 const string child_path = parent_path + "/" + name;
Zim859db932019-12-13 00:09:17 +0000683 std::smatch match;
684 std::regex_search(child_path, match, storage_emulated_regex);
Zim5077a892020-09-08 12:55:12 +0100685
686 // Ensure the FuseDaemon user id matches the user id or cross-user lookups are allowed in
687 // requested path
Zim3cde2662021-02-22 21:20:33 +0000688 if (match.size() == 2 && MY_USER_ID_STRING != match[1].str()) {
Zim5077a892020-09-08 12:55:12 +0100689 // If user id mismatch, check cross-user lookups
Martijn Coenen44ef6302020-11-06 10:32:32 +0100690 long userId = strtol(match[1].str().c_str(), nullptr, 10);
691 if (userId < 0 || userId > MAX_USER_ID ||
692 !fuse->mp->ShouldAllowLookup(req->ctx.uid, userId)) {
Zim5077a892020-09-08 12:55:12 +0100693 *error_code = EACCES;
694 return nullptr;
695 }
Zim859db932019-12-13 00:09:17 +0000696 }
]3e9d56c2021-03-15 16:24:17 +0000697
698 return make_node_entry(req, parent_node, name, child_path, e, error_code, op);
shafik1e3a2672019-08-16 14:51:55 +0100699}
700
701static void pf_lookup(fuse_req_t req, fuse_ino_t parent, const char* name) {
Zimec8d5722019-12-05 07:26:13 +0000702 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100703 struct fuse_entry_param e;
704
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000705 int error_code = 0;
]3e9d56c2021-03-15 16:24:17 +0000706 if (do_lookup(req, parent, name, &e, &error_code, FuseOp::lookup)) {
shafik1e3a2672019-08-16 14:51:55 +0100707 fuse_reply_entry(req, &e);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000708 } else {
709 CHECK(error_code != 0);
710 fuse_reply_err(req, error_code);
711 }
shafik1e3a2672019-08-16 14:51:55 +0100712}
713
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100714static void do_forget(fuse_req_t req, struct fuse* fuse, fuse_ino_t ino, uint64_t nlookup) {
Ricky Wai44670762020-05-01 11:25:28 +0100715 node* node = fuse->FromInode(ino);
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100716 TRACE_NODE(node, req);
shafik1e3a2672019-08-16 14:51:55 +0100717 if (node) {
Narayan Kamathaef84a12020-01-02 15:20:13 +0000718 // This is a narrowing conversion from an unsigned 64bit to a 32bit value. For
719 // some reason we only keep 32 bit refcounts but the kernel issues
720 // forget requests with a 64 bit counter.
Narayan Kamath568f17a2020-02-19 13:45:29 +0000721 node->Release(static_cast<uint32_t>(nlookup));
shafik1e3a2672019-08-16 14:51:55 +0100722 }
723}
724
725static void pf_forget(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup) {
Ricky Wai44670762020-05-01 11:25:28 +0100726 // Always allow to forget so no need to check is_app_accessible_path()
Zimec8d5722019-12-05 07:26:13 +0000727 ATRACE_CALL();
Narayan Kamathaef84a12020-01-02 15:20:13 +0000728 node* node;
shafik1e3a2672019-08-16 14:51:55 +0100729 struct fuse* fuse = get_fuse(req);
730
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100731 do_forget(req, fuse, ino, nlookup);
shafik1e3a2672019-08-16 14:51:55 +0100732 fuse_reply_none(req);
733}
734
735static void pf_forget_multi(fuse_req_t req,
736 size_t count,
737 struct fuse_forget_data* forgets) {
Zimec8d5722019-12-05 07:26:13 +0000738 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100739 struct fuse* fuse = get_fuse(req);
740
Narayan Kamathaef84a12020-01-02 15:20:13 +0000741 for (int i = 0; i < count; i++) {
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100742 do_forget(req, fuse, forgets[i].ino, forgets[i].nlookup);
Narayan Kamath768bea32019-12-27 16:23:23 +0000743 }
shafik1e3a2672019-08-16 14:51:55 +0100744 fuse_reply_none(req);
745}
746
Zim9e3c40b2021-04-09 15:51:15 +0100747static void pf_fallocate(fuse_req_t req, fuse_ino_t ino, int mode, off_t offset, off_t length,
748 fuse_file_info* fi) {
749 ATRACE_CALL();
750 struct fuse* fuse = get_fuse(req);
751
Zim9e3c40b2021-04-09 15:51:15 +0100752 handle* h = reinterpret_cast<handle*>(fi->fh);
Zim9e3652b2021-05-05 11:35:00 +0100753 auto err = fallocate(h->fd, mode, offset, length);
Zim9e3c40b2021-04-09 15:51:15 +0100754 fuse_reply_err(req, err);
755}
756
shafik1e3a2672019-08-16 14:51:55 +0100757static void pf_getattr(fuse_req_t req,
758 fuse_ino_t ino,
759 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +0000760 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100761 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100762 node* node = fuse->FromInode(ino);
Ricky Waif40c4022020-04-15 19:00:06 +0100763 if (!node) {
764 fuse_reply_err(req, ENOENT);
765 return;
766 }
Zim867fece2020-09-23 15:23:19 +0100767 const string& path = get_path(node);
Ricky Wai44670762020-05-01 11:25:28 +0100768 if (!is_app_accessible_path(fuse->mp, path, req->ctx.uid)) {
769 fuse_reply_err(req, ENOENT);
770 return;
771 }
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100772 TRACE_NODE(node, req);
shafik1e3a2672019-08-16 14:51:55 +0100773
Narayan Kamathaef84a12020-01-02 15:20:13 +0000774 struct stat s;
shafik1e3a2672019-08-16 14:51:55 +0100775 memset(&s, 0, sizeof(s));
776 if (lstat(path.c_str(), &s) < 0) {
777 fuse_reply_err(req, errno);
778 } else {
Zim3b6ff4d2021-03-03 11:14:59 +0000779 fuse_reply_attr(req, &s, std::numeric_limits<double>::max());
shafik1e3a2672019-08-16 14:51:55 +0100780 }
781}
782
783static void pf_setattr(fuse_req_t req,
784 fuse_ino_t ino,
785 struct stat* attr,
786 int to_set,
787 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +0000788 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100789 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100790 node* node = fuse->FromInode(ino);
shafik1e3a2672019-08-16 14:51:55 +0100791 if (!node) {
792 fuse_reply_err(req, ENOENT);
793 return;
794 }
Zim867fece2020-09-23 15:23:19 +0100795 const string& path = get_path(node);
Ricky Wai44670762020-05-01 11:25:28 +0100796 if (!is_app_accessible_path(fuse->mp, path, req->ctx.uid)) {
797 fuse_reply_err(req, ENOENT);
798 return;
799 }
Ricky Waif40c4022020-04-15 19:00:06 +0100800
Zimuzo Ezeozue435bd252020-06-30 20:15:17 +0000801 int fd = -1;
802 if (fi) {
803 // If we have a file_info, setattr was called with an fd so use the fd instead of path
804 handle* h = reinterpret_cast<handle*>(fi->fh);
805 fd = h->fd;
806 } else {
807 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Zim73895ba2021-01-13 12:51:20 +0000808 std::unique_ptr<FileOpenResult> result = fuse->mp->OnFileOpen(
Zim801d9852021-01-26 18:30:53 +0000809 path, path, ctx->uid, ctx->pid, node->GetTransformsReason(), true /* for_write */,
810 false /* redact */, false /* log_transforms_metrics */);
Zim73895ba2021-01-13 12:51:20 +0000811
812 if (!result) {
813 fuse_reply_err(req, EFAULT);
814 return;
815 }
816
817 if (result->status) {
Zimuzo Ezeozue435bd252020-06-30 20:15:17 +0000818 fuse_reply_err(req, EACCES);
819 return;
820 }
821 }
822 struct timespec times[2];
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100823 TRACE_NODE(node, req);
shafik1e3a2672019-08-16 14:51:55 +0100824
825 /* XXX: incomplete implementation on purpose.
826 * chmod/chown should NEVER be implemented.*/
827
Zimuzo Ezeozue435bd252020-06-30 20:15:17 +0000828 if ((to_set & FUSE_SET_ATTR_SIZE)) {
829 int res = 0;
830 if (fd == -1) {
831 res = truncate64(path.c_str(), attr->st_size);
832 } else {
833 res = ftruncate64(fd, attr->st_size);
834 }
835
836 if (res < 0) {
837 fuse_reply_err(req, errno);
838 return;
839 }
shafik1e3a2672019-08-16 14:51:55 +0100840 }
841
842 /* Handle changing atime and mtime. If FATTR_ATIME_and FATTR_ATIME_NOW
843 * are both set, then set it to the current time. Else, set it to the
844 * time specified in the request. Same goes for mtime. Use utimensat(2)
845 * as it allows ATIME and MTIME to be changed independently, and has
846 * nanosecond resolution which fuse also has.
847 */
848 if (to_set & (FATTR_ATIME | FATTR_MTIME)) {
849 times[0].tv_nsec = UTIME_OMIT;
850 times[1].tv_nsec = UTIME_OMIT;
851 if (to_set & FATTR_ATIME) {
852 if (to_set & FATTR_ATIME_NOW) {
853 times[0].tv_nsec = UTIME_NOW;
854 } else {
Zim0056c4b2020-04-27 18:56:51 +0100855 times[0] = attr->st_atim;
shafik1e3a2672019-08-16 14:51:55 +0100856 }
857 }
Zim0056c4b2020-04-27 18:56:51 +0100858
shafik1e3a2672019-08-16 14:51:55 +0100859 if (to_set & FATTR_MTIME) {
860 if (to_set & FATTR_MTIME_NOW) {
861 times[1].tv_nsec = UTIME_NOW;
862 } else {
Zim0056c4b2020-04-27 18:56:51 +0100863 times[1] = attr->st_mtim;
shafik1e3a2672019-08-16 14:51:55 +0100864 }
865 }
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +0000866
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100867 TRACE_NODE(node, req);
Zimuzo Ezeozue435bd252020-06-30 20:15:17 +0000868 int res = 0;
869 if (fd == -1) {
870 res = utimensat(-1, path.c_str(), times, 0);
871 } else {
872 res = futimens(fd, times);
873 }
874
875 if (res < 0) {
shafik1e3a2672019-08-16 14:51:55 +0100876 fuse_reply_err(req, errno);
877 return;
878 }
879 }
880
Zima9fcd552019-08-29 15:17:04 +0100881 lstat(path.c_str(), attr);
Zim3b6ff4d2021-03-03 11:14:59 +0000882 fuse_reply_attr(req, attr, std::numeric_limits<double>::max());
shafik1e3a2672019-08-16 14:51:55 +0100883}
Zimb9730bf2019-11-30 15:10:04 +0000884
885static void pf_canonical_path(fuse_req_t req, fuse_ino_t ino)
shafik1e3a2672019-08-16 14:51:55 +0100886{
Ricky Wai44670762020-05-01 11:25:28 +0100887 struct fuse* fuse = get_fuse(req);
888 node* node = fuse->FromInode(ino);
Zim867fece2020-09-23 15:23:19 +0100889 const string& path = node ? get_path(node) : "";
Zimb9730bf2019-11-30 15:10:04 +0000890
Ricky Wai44670762020-05-01 11:25:28 +0100891 if (node && is_app_accessible_path(fuse->mp, path, req->ctx.uid)) {
Zimb9730bf2019-11-30 15:10:04 +0000892 // TODO(b/147482155): Check that uid has access to |path| and its contents
Ricky Wai44670762020-05-01 11:25:28 +0100893 fuse_reply_canonical_path(req, path.c_str());
Zimb9730bf2019-11-30 15:10:04 +0000894 return;
895 }
896 fuse_reply_err(req, ENOENT);
shafik1e3a2672019-08-16 14:51:55 +0100897}
Zimb9730bf2019-11-30 15:10:04 +0000898
shafik1e3a2672019-08-16 14:51:55 +0100899static void pf_mknod(fuse_req_t req,
900 fuse_ino_t parent,
901 const char* name,
902 mode_t mode,
903 dev_t rdev) {
Zimec8d5722019-12-05 07:26:13 +0000904 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100905 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100906 node* parent_node = fuse->FromInode(parent);
shafik1e3a2672019-08-16 14:51:55 +0100907 if (!parent_node) {
908 fuse_reply_err(req, ENOENT);
909 return;
910 }
Ricky Waif40c4022020-04-15 19:00:06 +0100911 string parent_path = parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +0100912 if (!is_app_accessible_path(fuse->mp, parent_path, req->ctx.uid)) {
913 fuse_reply_err(req, ENOENT);
914 return;
915 }
Ricky Waif40c4022020-04-15 19:00:06 +0100916
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100917 TRACE_NODE(parent_node, req);
Ricky Waif40c4022020-04-15 19:00:06 +0100918
Narayan Kamathaef84a12020-01-02 15:20:13 +0000919 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100920
921 mode = (mode & (~0777)) | 0664;
922 if (mknod(child_path.c_str(), mode, rdev) < 0) {
923 fuse_reply_err(req, errno);
924 return;
925 }
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000926
927 int error_code = 0;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000928 struct fuse_entry_param e;
]3e9d56c2021-03-15 16:24:17 +0000929 if (make_node_entry(req, parent_node, name, child_path, &e, &error_code, FuseOp::mknod)) {
shafik1e3a2672019-08-16 14:51:55 +0100930 fuse_reply_entry(req, &e);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000931 } else {
932 CHECK(error_code != 0);
933 fuse_reply_err(req, error_code);
934 }
shafik1e3a2672019-08-16 14:51:55 +0100935}
936
937static void pf_mkdir(fuse_req_t req,
938 fuse_ino_t parent,
939 const char* name,
940 mode_t mode) {
Zimec8d5722019-12-05 07:26:13 +0000941 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100942 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100943 node* parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +0100944 if (!parent_node) {
945 fuse_reply_err(req, ENOENT);
946 return;
947 }
Ricky Wai44670762020-05-01 11:25:28 +0100948 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000949 const string parent_path = parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +0100950 if (!is_app_accessible_path(fuse->mp, parent_path, ctx->uid)) {
951 fuse_reply_err(req, ENOENT);
952 return;
953 }
Narayan Kamath768bea32019-12-27 16:23:23 +0000954
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100955 TRACE_NODE(parent_node, req);
shafik1e3a2672019-08-16 14:51:55 +0100956
Narayan Kamathaef84a12020-01-02 15:20:13 +0000957 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100958
shafike4fb1462020-01-29 16:25:23 +0000959 int status = fuse->mp->IsCreatingDirAllowed(child_path, ctx->uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000960 if (status) {
961 fuse_reply_err(req, status);
962 return;
963 }
964
shafik1e3a2672019-08-16 14:51:55 +0100965 mode = (mode & (~0777)) | 0775;
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000966 if (mkdir(child_path.c_str(), mode) < 0) {
shafik1e3a2672019-08-16 14:51:55 +0100967 fuse_reply_err(req, errno);
968 return;
969 }
970
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000971 int error_code = 0;
Narayan Kamathaef84a12020-01-02 15:20:13 +0000972 struct fuse_entry_param e;
]3e9d56c2021-03-15 16:24:17 +0000973 if (make_node_entry(req, parent_node, name, child_path, &e, &error_code, FuseOp::mkdir)) {
shafik1e3a2672019-08-16 14:51:55 +0100974 fuse_reply_entry(req, &e);
Narayan Kamathbbb779a2019-12-31 16:30:11 +0000975 } else {
976 CHECK(error_code != 0);
977 fuse_reply_err(req, error_code);
978 }
shafik1e3a2672019-08-16 14:51:55 +0100979}
980
981static void pf_unlink(fuse_req_t req, fuse_ino_t parent, const char* name) {
Zimec8d5722019-12-05 07:26:13 +0000982 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +0100983 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +0100984 node* parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +0100985 if (!parent_node) {
986 fuse_reply_err(req, ENOENT);
987 return;
988 }
Ricky Wai44670762020-05-01 11:25:28 +0100989 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +0000990 const string parent_path = parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +0100991 if (!is_app_accessible_path(fuse->mp, parent_path, ctx->uid)) {
992 fuse_reply_err(req, ENOENT);
993 return;
994 }
shafik1e3a2672019-08-16 14:51:55 +0100995
Nandana Dutt154cb5d2020-06-04 11:53:31 +0100996 TRACE_NODE(parent_node, req);
shafik1e3a2672019-08-16 14:51:55 +0100997
Narayan Kamathaef84a12020-01-02 15:20:13 +0000998 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +0100999
shafike4fb1462020-01-29 16:25:23 +00001000 int status = fuse->mp->DeleteFile(child_path, ctx->uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001001 if (status) {
1002 fuse_reply_err(req, status);
shafik1e3a2672019-08-16 14:51:55 +01001003 return;
1004 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001005
Zim53c2d702020-09-23 12:18:27 +01001006 // TODO(b/169306422): Log each deleted node
1007 parent_node->SetDeletedForChild(name);
shafik1e3a2672019-08-16 14:51:55 +01001008 fuse_reply_err(req, 0);
1009}
1010
1011static void pf_rmdir(fuse_req_t req, fuse_ino_t parent, const char* name) {
Zimec8d5722019-12-05 07:26:13 +00001012 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001013 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +01001014 node* parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +01001015 if (!parent_node) {
1016 fuse_reply_err(req, ENOENT);
1017 return;
1018 }
Narayan Kamathaef84a12020-01-02 15:20:13 +00001019 const string parent_path = parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +01001020 if (!is_app_accessible_path(fuse->mp, parent_path, req->ctx.uid)) {
1021 fuse_reply_err(req, ENOENT);
1022 return;
1023 }
]3e9d56c2021-03-15 16:24:17 +00001024
1025 if (is_transforms_dir_path(parent_path, fuse)) {
1026 // .transforms is a special daemon controlled dir so apps shouldn't be able to see it via
1027 // readdir, and any dir operations attempted on it should fail
1028 fuse_reply_err(req, ENOENT);
1029 return;
1030 }
1031
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001032 TRACE_NODE(parent_node, req);
shafik1e3a2672019-08-16 14:51:55 +01001033
Narayan Kamathaef84a12020-01-02 15:20:13 +00001034 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +01001035
Ricky Wai44670762020-05-01 11:25:28 +01001036 int status = fuse->mp->IsDeletingDirAllowed(child_path, req->ctx.uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001037 if (status) {
1038 fuse_reply_err(req, status);
1039 return;
1040 }
1041
1042 if (rmdir(child_path.c_str()) < 0) {
shafik1e3a2672019-08-16 14:51:55 +01001043 fuse_reply_err(req, errno);
1044 return;
1045 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001046
Narayan Kamatheca34252020-02-11 13:08:37 +00001047 node* child_node = parent_node->LookupChildByName(name, false /* acquire */);
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001048 TRACE_NODE(child_node, req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001049 if (child_node) {
1050 child_node->SetDeleted();
shafik1e3a2672019-08-16 14:51:55 +01001051 }
shafik1e3a2672019-08-16 14:51:55 +01001052
1053 fuse_reply_err(req, 0);
1054}
1055/*
1056static void pf_symlink(fuse_req_t req, const char* link, fuse_ino_t parent,
1057 const char* name)
1058{
1059 cout << "TODO:" << __func__;
1060}
1061*/
Sahana Rao2c416032019-12-31 13:41:00 +00001062static int do_rename(fuse_req_t req, fuse_ino_t parent, const char* name, fuse_ino_t new_parent,
1063 const char* new_name, unsigned int flags) {
Zimec8d5722019-12-05 07:26:13 +00001064 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001065 struct fuse* fuse = get_fuse(req);
shafik1e3a2672019-08-16 14:51:55 +01001066
Sahana Rao2c416032019-12-31 13:41:00 +00001067 if (flags != 0) {
Sahana Rao2c416032019-12-31 13:41:00 +00001068 return EINVAL;
1069 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001070
Ricky Wai44670762020-05-01 11:25:28 +01001071 node* old_parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +01001072 if (!old_parent_node) return ENOENT;
Ricky Wai44670762020-05-01 11:25:28 +01001073 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001074 const string old_parent_path = old_parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +01001075 if (!is_app_accessible_path(fuse->mp, old_parent_path, ctx->uid)) {
1076 return ENOENT;
1077 }
1078
]3e9d56c2021-03-15 16:24:17 +00001079 if (is_transforms_dir_path(old_parent_path, fuse)) {
1080 // .transforms is a special daemon controlled dir so apps shouldn't be able to see it via
1081 // readdir, and any dir operations attempted on it should fail
1082 return ENOENT;
1083 }
1084
Ricky Wai44670762020-05-01 11:25:28 +01001085 node* new_parent_node = fuse->FromInode(new_parent);
Ricky Waif40c4022020-04-15 19:00:06 +01001086 if (!new_parent_node) return ENOENT;
Narayan Kamathaef84a12020-01-02 15:20:13 +00001087 const string new_parent_path = new_parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +01001088 if (!is_app_accessible_path(fuse->mp, new_parent_path, ctx->uid)) {
1089 return ENOENT;
1090 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001091
Narayan Kamathaef84a12020-01-02 15:20:13 +00001092 if (!old_parent_node || !new_parent_node) {
1093 return ENOENT;
1094 } else if (parent == new_parent && name == new_name) {
1095 // No rename required.
1096 return 0;
shafik1e3a2672019-08-16 14:51:55 +01001097 }
1098
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001099 TRACE_NODE(old_parent_node, req);
1100 TRACE_NODE(new_parent_node, req);
shafik1e3a2672019-08-16 14:51:55 +01001101
Zim53c2d702020-09-23 12:18:27 +01001102 const string old_child_path = old_parent_path + "/" + name;
Narayan Kamathaef84a12020-01-02 15:20:13 +00001103 const string new_child_path = new_parent_path + "/" + new_name;
1104
Zimbd89e7a2021-01-27 19:02:11 +00001105 if (android::base::EqualsIgnoreCase(fuse->GetEffectiveRootPath() + "/android", old_child_path)) {
1106 // Prevent renaming Android/ dir since it contains bind-mounts on the primary volume
1107 return EACCES;
1108 }
1109
Sahana Rao182ec6b2020-01-03 15:00:46 +00001110 // TODO(b/147408834): Check ENOTEMPTY & EEXIST error conditions before JNI call.
shafike4fb1462020-01-29 16:25:23 +00001111 const int res = fuse->mp->Rename(old_child_path, new_child_path, req->ctx.uid);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001112 // TODO(b/145663158): Lookups can go out of sync if file/directory is actually moved but
1113 // EFAULT/EIO is reported due to JNI exception.
1114 if (res == 0) {
Zim53c2d702020-09-23 12:18:27 +01001115 // TODO(b/169306422): Log each renamed node
1116 old_parent_node->RenameChild(name, new_name, new_parent_node);
shafik1e3a2672019-08-16 14:51:55 +01001117 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001118 return res;
1119}
shafik1e3a2672019-08-16 14:51:55 +01001120
Sahana Rao2c416032019-12-31 13:41:00 +00001121static void pf_rename(fuse_req_t req, fuse_ino_t parent, const char* name, fuse_ino_t new_parent,
1122 const char* new_name, unsigned int flags) {
1123 int res = do_rename(req, parent, name, new_parent, new_name, flags);
shafik1e3a2672019-08-16 14:51:55 +01001124 fuse_reply_err(req, res);
1125}
Narayan Kamath768bea32019-12-27 16:23:23 +00001126
shafik1e3a2672019-08-16 14:51:55 +01001127/*
Sahana Rao2c416032019-12-31 13:41:00 +00001128static void pf_link(fuse_req_t req, fuse_ino_t ino, fuse_ino_t new_parent,
1129 const char* new_name)
shafik1e3a2672019-08-16 14:51:55 +01001130{
1131 cout << "TODO:" << __func__;
1132}
1133*/
1134
Zim9aa6f542020-10-19 15:39:33 +01001135static handle* create_handle_for_node(struct fuse* fuse, const string& path, int fd, uid_t uid,
Manish Singh9a6ccce2021-02-05 23:50:08 +00001136 uid_t transforms_uid, node* node, const RedactionInfo* ri,
1137 int* keep_cache) {
Zimc05c60f2020-03-05 13:02:26 +00001138 std::lock_guard<std::recursive_mutex> guard(fuse->lock);
Zimc05c60f2020-03-05 13:02:26 +00001139
Zim148cbe22020-11-17 15:58:29 +00001140 bool redaction_needed = ri->isRedactionNeeded();
1141 handle* handle = nullptr;
Manish Singh9a6ccce2021-02-05 23:50:08 +00001142 int transforms = node->GetTransforms();
Zime5433682021-03-10 12:06:54 +00001143 bool transforms_complete = node->IsTransformsComplete();
Manish Singh9a6ccce2021-02-05 23:50:08 +00001144 if (transforms_uid > 0) {
1145 CHECK(transforms);
1146 }
Zim148cbe22020-11-17 15:58:29 +00001147
1148 if (fuse->passthrough) {
Zime5433682021-03-10 12:06:54 +00001149 *keep_cache = transforms_complete;
Zimuzo Ezeozue158b6582021-03-04 12:50:54 +00001150 // We only enabled passthrough iff these 2 conditions hold
1151 // 1. Redaction is not needed
1152 // 2. Node transforms are completed, e.g transcoding.
1153 // (2) is important because we transcode lazily (on the first read) and with passthrough,
1154 // we will never get a read into the FUSE daemon, so passthrough would have returned
1155 // arbitrary bytes the first time around. However, if we ensure that transforms are
1156 // completed, then it's safe to use passthrough. Additionally, transcoded nodes never
1157 // require redaction so (2) implies (1)
Zime5433682021-03-10 12:06:54 +00001158 handle = new struct handle(fd, ri, true /* cached */,
1159 !redaction_needed && transforms_complete /* passthrough */, uid,
1160 transforms_uid);
Zim148cbe22020-11-17 15:58:29 +00001161 } else {
1162 // Without fuse->passthrough, we don't want to use the FUSE VFS cache in two cases:
1163 // 1. When redaction is needed because app A with EXIF access might access
1164 // a region that should have been redacted for app B without EXIF access, but app B on
1165 // a subsequent read, will be able to see the EXIF data because the read request for
1166 // that region will be served from cache and not get to the FUSE daemon
1167 // 2. When the file has a read or write lock on it. This means that the MediaProvider
1168 // has given an fd to the lower file system to an app. There are two cases where using
1169 // the cache in this case can be a problem:
1170 // a. Writing to a FUSE fd with caching enabled will use the write-back cache and a
1171 // subsequent read from the lower fs fd will not see the write.
1172 // b. Reading from a FUSE fd with caching enabled may not see the latest writes using
1173 // the lower fs fd because those writes did not go through the FUSE layer and reads from
1174 // FUSE after that write may be served from cache
1175 bool has_redacted = node->HasRedactedCache();
1176 bool is_redaction_change =
1177 (redaction_needed && !has_redacted) || (!redaction_needed && has_redacted);
1178 bool is_cached_file_open = node->HasCachedHandle();
1179 bool direct_io = (is_cached_file_open && is_redaction_change) || is_file_locked(fd, path);
1180
1181 if (!is_cached_file_open && is_redaction_change) {
1182 node->SetRedactedCache(redaction_needed);
1183 // Purges stale page cache before open
1184 *keep_cache = 0;
1185 } else {
Zime5433682021-03-10 12:06:54 +00001186 *keep_cache = transforms_complete;
Zim148cbe22020-11-17 15:58:29 +00001187 }
Manish Singh9a6ccce2021-02-05 23:50:08 +00001188 handle = new struct handle(fd, ri, !direct_io /* cached */, false /* passthrough */, uid,
1189 transforms_uid);
Zim329ba2c2020-09-16 14:23:26 +01001190 }
1191
Zim148cbe22020-11-17 15:58:29 +00001192 node->AddHandle(handle);
1193 return handle;
Zimc05c60f2020-03-05 13:02:26 +00001194}
1195
Alessio Balsinif220a962020-07-13 12:01:13 +01001196bool do_passthrough_enable(fuse_req_t req, struct fuse_file_info* fi, unsigned int fd) {
1197 int passthrough_fh = fuse_passthrough_enable(req, fd);
1198
1199 if (passthrough_fh <= 0) {
1200 return false;
1201 }
1202
1203 fi->passthrough_fh = passthrough_fh;
1204 return true;
1205}
1206
shafik1e3a2672019-08-16 14:51:55 +01001207static void pf_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001208 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001209 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +01001210 node* node = fuse->FromInode(ino);
shafik1e3a2672019-08-16 14:51:55 +01001211 if (!node) {
1212 fuse_reply_err(req, ENOENT);
1213 return;
1214 }
Ricky Wai44670762020-05-01 11:25:28 +01001215 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Zime9ae6ee2020-11-26 15:38:13 +00001216 const string& io_path = get_path(node);
Zimf7ec8672020-10-28 18:25:45 +00001217 const string& build_path = node->BuildPath();
Zime9ae6ee2020-11-26 15:38:13 +00001218 if (!is_app_accessible_path(fuse->mp, io_path, ctx->uid)) {
Ricky Wai44670762020-05-01 11:25:28 +01001219 fuse_reply_err(req, ENOENT);
1220 return;
1221 }
Ricky Waif40c4022020-04-15 19:00:06 +01001222
Manish Singh0f79b452021-03-04 00:20:38 +00001223 bool for_write = is_requesting_write(fi->flags);
1224
1225 if (for_write && node->GetTransforms()) {
1226 TRACE_NODE(node, req) << "write with transforms";
1227 } else {
1228 TRACE_NODE(node, req) << (for_write ? "write" : "read");
1229 }
shafik1e3a2672019-08-16 14:51:55 +01001230
shafik15e2d612019-10-31 20:10:25 +00001231 if (fi->flags & O_DIRECT) {
1232 fi->flags &= ~O_DIRECT;
1233 fi->direct_io = true;
1234 }
1235
Zimf7ec8672020-10-28 18:25:45 +00001236 // Force permission check with the build path because the MediaProvider database might not be
1237 // aware of the io_path
Zim73895ba2021-01-13 12:51:20 +00001238 // We don't redact if the caller was granted write permission for this file
1239 std::unique_ptr<FileOpenResult> result = fuse->mp->OnFileOpen(
Zim801d9852021-01-26 18:30:53 +00001240 build_path, io_path, ctx->uid, ctx->pid, node->GetTransformsReason(), for_write,
1241 !for_write /* redact */, true /* log_transforms_metrics */);
Zim73895ba2021-01-13 12:51:20 +00001242 if (!result) {
1243 fuse_reply_err(req, EFAULT);
1244 return;
1245 }
1246
1247 if (result->status) {
1248 fuse_reply_err(req, result->status);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001249 return;
1250 }
1251
Martijn Coenen2d7f1be2020-02-15 07:44:12 +01001252 // With the writeback cache enabled, FUSE may generate READ requests even for files that
1253 // were opened O_WRONLY; so make sure we open it O_RDWR instead.
1254 int open_flags = fi->flags;
1255 if (open_flags & O_WRONLY) {
1256 open_flags &= ~O_WRONLY;
1257 open_flags |= O_RDWR;
1258 }
1259
Zim1b14f2f2020-07-03 07:05:53 +01001260 if (open_flags & O_APPEND) {
1261 open_flags &= ~O_APPEND;
1262 }
1263
Zime9ae6ee2020-11-26 15:38:13 +00001264 const int fd = open(io_path.c_str(), open_flags);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001265 if (fd < 0) {
shafik1e3a2672019-08-16 14:51:55 +01001266 fuse_reply_err(req, errno);
1267 return;
1268 }
shafik15e2d612019-10-31 20:10:25 +00001269
Zim329ba2c2020-09-16 14:23:26 +01001270 int keep_cache = 1;
Manish Singh9a6ccce2021-02-05 23:50:08 +00001271 handle* h = create_handle_for_node(fuse, io_path, fd, result->uid, result->transforms_uid, node,
Zim73895ba2021-01-13 12:51:20 +00001272 result->redaction_info.release(), &keep_cache);
shafik1e3a2672019-08-16 14:51:55 +01001273 fi->fh = ptr_to_id(h);
Zim329ba2c2020-09-16 14:23:26 +01001274 fi->keep_cache = keep_cache;
Zimc05c60f2020-03-05 13:02:26 +00001275 fi->direct_io = !h->cached;
Alessio Balsinif220a962020-07-13 12:01:13 +01001276
1277 // TODO(b/173190192) ensuring that h->cached must be enabled in order to
1278 // user FUSE passthrough is a conservative rule and might be dropped as
1279 // soon as demonstrated its correctness.
Zim148cbe22020-11-17 15:58:29 +00001280 if (h->passthrough) {
Alessio Balsinif220a962020-07-13 12:01:13 +01001281 if (!do_passthrough_enable(req, fi, fd)) {
Zim148cbe22020-11-17 15:58:29 +00001282 // TODO: Should we crash here so we can find errors easily?
Zime9ae6ee2020-11-26 15:38:13 +00001283 PLOG(ERROR) << "Passthrough OPEN failed for " << io_path;
Zim148cbe22020-11-17 15:58:29 +00001284 fuse_reply_err(req, EFAULT);
1285 return;
Alessio Balsinif220a962020-07-13 12:01:13 +01001286 }
1287 }
1288
shafik1e3a2672019-08-16 14:51:55 +01001289 fuse_reply_open(req, fi);
1290}
1291
shafikc3f62672019-08-30 11:15:48 +01001292static void do_read(fuse_req_t req, size_t size, off_t off, struct fuse_file_info* fi) {
shafika2ae9072019-10-28 12:16:00 +00001293 handle* h = reinterpret_cast<handle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001294 struct fuse_bufvec buf = FUSE_BUFVEC_INIT(size);
1295
1296 buf.buf[0].fd = h->fd;
1297 buf.buf[0].pos = off;
1298 buf.buf[0].flags =
1299 (enum fuse_buf_flags) (FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
1300
1301 fuse_reply_data(req, &buf, (enum fuse_buf_copy_flags) 0);
1302}
shafikc3f62672019-08-30 11:15:48 +01001303
shafikc3f62672019-08-30 11:15:48 +01001304/**
1305 * Sets the parameters for a fuse_buf that reads from memory, including flags.
shafikb334a612019-09-30 20:38:16 +01001306 * Makes buf->mem point to an already mapped region of zeroized memory.
1307 * This memory is read only.
shafikc3f62672019-08-30 11:15:48 +01001308 */
shafikb334a612019-09-30 20:38:16 +01001309static void create_mem_fuse_buf(size_t size, fuse_buf* buf, struct fuse* fuse) {
shafikc3f62672019-08-30 11:15:48 +01001310 buf->size = size;
shafikb334a612019-09-30 20:38:16 +01001311 buf->mem = fuse->zero_addr;
shafikc3f62672019-08-30 11:15:48 +01001312 buf->flags = static_cast<fuse_buf_flags>(0 /*read from fuse_buf.mem*/);
1313 buf->pos = -1;
1314 buf->fd = -1;
1315}
1316
1317/**
1318 * Sets the parameters for a fuse_buf that reads from file, including flags.
1319 */
1320static void create_file_fuse_buf(size_t size, off_t pos, int fd, fuse_buf* buf) {
1321 buf->size = size;
1322 buf->fd = fd;
1323 buf->pos = pos;
1324 buf->flags = static_cast<fuse_buf_flags>(FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
1325 buf->mem = nullptr;
1326}
1327
1328static 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 +00001329 handle* h = reinterpret_cast<handle*>(fi->fh);
shafikc3f62672019-08-30 11:15:48 +01001330
Narayan Kamath11700c02020-10-06 09:15:34 +01001331 std::vector<ReadRange> ranges;
1332 h->ri->getReadRanges(off, size, &ranges);
1333
1334 // As an optimization, return early if there are no ranges to redact.
1335 if (ranges.size() == 0) {
shafikc3f62672019-08-30 11:15:48 +01001336 do_read(req, size, off, fi);
1337 return;
1338 }
Narayan Kamath11700c02020-10-06 09:15:34 +01001339
1340 const size_t num_bufs = ranges.size();
shafikc3f62672019-08-30 11:15:48 +01001341 auto bufvec_ptr = std::unique_ptr<fuse_bufvec, decltype(free)*>{
1342 reinterpret_cast<fuse_bufvec*>(
1343 malloc(sizeof(fuse_bufvec) + (num_bufs - 1) * sizeof(fuse_buf))),
1344 free};
1345 fuse_bufvec& bufvec = *bufvec_ptr;
1346
1347 // initialize bufvec
1348 bufvec.count = num_bufs;
1349 bufvec.idx = 0;
1350 bufvec.off = 0;
shafikc3f62672019-08-30 11:15:48 +01001351
shafikc3f62672019-08-30 11:15:48 +01001352 for (int i = 0; i < num_bufs; ++i) {
Narayan Kamath11700c02020-10-06 09:15:34 +01001353 const ReadRange& range = ranges[i];
1354 if (range.is_redaction) {
1355 create_mem_fuse_buf(range.size, &(bufvec.buf[i]), get_fuse(req));
shafikc3f62672019-08-30 11:15:48 +01001356 } else {
Narayan Kamath11700c02020-10-06 09:15:34 +01001357 create_file_fuse_buf(range.size, range.start, h->fd, &(bufvec.buf[i]));
shafikc3f62672019-08-30 11:15:48 +01001358 }
shafikc3f62672019-08-30 11:15:48 +01001359 }
1360
1361 fuse_reply_data(req, &bufvec, static_cast<fuse_buf_copy_flags>(0));
1362}
1363
1364static void pf_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off,
1365 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001366 ATRACE_CALL();
shafika2ae9072019-10-28 12:16:00 +00001367 handle* h = reinterpret_cast<handle*>(fi->fh);
shafikc3f62672019-08-30 11:15:48 +01001368 struct fuse* fuse = get_fuse(req);
shafikc3f62672019-08-30 11:15:48 +01001369
Zim867fece2020-09-23 15:23:19 +01001370 node* node = fuse->FromInode(ino);
1371
1372 if (!node->IsTransformsComplete()) {
1373 if (!fuse->mp->Transform(node->BuildPath(), node->GetIoPath(), node->GetTransforms(),
Manish Singh9a6ccce2021-02-05 23:50:08 +00001374 node->GetTransformsReason(), req->ctx.uid, h->uid,
1375 h->transforms_uid)) {
Zim867fece2020-09-23 15:23:19 +01001376 fuse_reply_err(req, EFAULT);
1377 return;
1378 }
Zime5433682021-03-10 12:06:54 +00001379 node->SetTransformsComplete(true);
Zim867fece2020-09-23 15:23:19 +01001380 }
1381
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001382 fuse->fadviser.Record(h->fd, size);
1383
shafikc3f62672019-08-30 11:15:48 +01001384 if (h->ri->isRedactionNeeded()) {
1385 do_read_with_redaction(req, size, off, fi);
1386 } else {
1387 do_read(req, size, off, fi);
1388 }
1389}
1390
shafik1e3a2672019-08-16 14:51:55 +01001391/*
1392static void pf_write(fuse_req_t req, fuse_ino_t ino, const char* buf,
1393 size_t size, off_t off, struct fuse_file_info* fi)
1394{
1395 cout << "TODO:" << __func__;
1396}
1397*/
1398
1399static void pf_write_buf(fuse_req_t req,
1400 fuse_ino_t ino,
1401 struct fuse_bufvec* bufv,
1402 off_t off,
1403 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001404 ATRACE_CALL();
shafika2ae9072019-10-28 12:16:00 +00001405 handle* h = reinterpret_cast<handle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001406 struct fuse_bufvec buf = FUSE_BUFVEC_INIT(fuse_buf_size(bufv));
1407 ssize_t size;
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001408 struct fuse* fuse = get_fuse(req);
shafik1e3a2672019-08-16 14:51:55 +01001409
1410 buf.buf[0].fd = h->fd;
1411 buf.buf[0].pos = off;
1412 buf.buf[0].flags =
1413 (enum fuse_buf_flags) (FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK);
1414 size = fuse_buf_copy(&buf, bufv, (enum fuse_buf_copy_flags) 0);
1415
1416 if (size < 0)
1417 fuse_reply_err(req, -size);
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001418 else {
shafik1e3a2672019-08-16 14:51:55 +01001419 fuse_reply_write(req, size);
Paul Lawrence7e4a5a82019-09-27 21:39:49 +02001420 fuse->fadviser.Record(h->fd, size);
1421 }
shafik1e3a2672019-08-16 14:51:55 +01001422}
1423// Haven't tested this one. Not sure what calls it.
1424#if 0
1425static void pf_copy_file_range(fuse_req_t req, fuse_ino_t ino_in,
1426 off_t off_in, struct fuse_file_info* fi_in,
1427 fuse_ino_t ino_out, off_t off_out,
1428 struct fuse_file_info* fi_out, size_t len,
1429 int flags)
1430{
shafika2ae9072019-10-28 12:16:00 +00001431 handle* h_in = reinterpret_cast<handle *>(fi_in->fh);
1432 handle* h_out = reinterpret_cast<handle *>(fi_out->fh);
shafik1e3a2672019-08-16 14:51:55 +01001433 struct fuse_bufvec buf_in = FUSE_BUFVEC_INIT(len);
1434 struct fuse_bufvec buf_out = FUSE_BUFVEC_INIT(len);
1435 ssize_t size;
1436
1437 buf_in.buf[0].fd = h_in->fd;
1438 buf_in.buf[0].pos = off_in;
1439 buf_in.buf[0].flags = (enum fuse_buf_flags)(FUSE_BUF_IS_FD|FUSE_BUF_FD_SEEK);
1440
1441 buf_out.buf[0].fd = h_out->fd;
1442 buf_out.buf[0].pos = off_out;
1443 buf_out.buf[0].flags = (enum fuse_buf_flags)(FUSE_BUF_IS_FD|FUSE_BUF_FD_SEEK);
1444 size = fuse_buf_copy(&buf_out, &buf_in, (enum fuse_buf_copy_flags) 0);
1445
1446 if (size < 0) {
1447 fuse_reply_err(req, -size);
1448 }
1449
1450 fuse_reply_write(req, size);
1451}
1452#endif
shafik1e3a2672019-08-16 14:51:55 +01001453
1454static void pf_release(fuse_req_t req,
1455 fuse_ino_t ino,
1456 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001457 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001458 struct fuse* fuse = get_fuse(req);
Kyle Tso613b7ab2019-12-24 06:30:00 +00001459
Ricky Wai44670762020-05-01 11:25:28 +01001460 node* node = fuse->FromInode(ino);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001461 handle* h = reinterpret_cast<handle*>(fi->fh);
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001462 TRACE_NODE(node, req);
shafik15e2d612019-10-31 20:10:25 +00001463
Narayan Kamathaef84a12020-01-02 15:20:13 +00001464 fuse->fadviser.Close(h->fd);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001465 if (node) {
1466 node->DestroyHandle(h);
Zimedbe69e2019-12-13 18:49:36 +00001467 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001468
shafik1e3a2672019-08-16 14:51:55 +01001469 fuse_reply_err(req, 0);
1470}
1471
1472static int do_sync_common(int fd, bool datasync) {
1473 int res = datasync ? fdatasync(fd) : fsync(fd);
1474
1475 if (res == -1) return errno;
1476 return 0;
1477}
1478
1479static void pf_fsync(fuse_req_t req,
1480 fuse_ino_t ino,
1481 int datasync,
1482 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001483 ATRACE_CALL();
shafika2ae9072019-10-28 12:16:00 +00001484 handle* h = reinterpret_cast<handle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001485 int err = do_sync_common(h->fd, datasync);
1486
1487 fuse_reply_err(req, err);
1488}
1489
1490static void pf_fsyncdir(fuse_req_t req,
1491 fuse_ino_t ino,
1492 int datasync,
1493 struct fuse_file_info* fi) {
Narayan Kamathaef84a12020-01-02 15:20:13 +00001494 dirhandle* h = reinterpret_cast<dirhandle*>(fi->fh);
shafik1e3a2672019-08-16 14:51:55 +01001495 int err = do_sync_common(dirfd(h->d), datasync);
1496
1497 fuse_reply_err(req, err);
1498}
1499
1500static void pf_opendir(fuse_req_t req,
1501 fuse_ino_t ino,
1502 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001503 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001504 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +01001505 node* node = fuse->FromInode(ino);
shafik1e3a2672019-08-16 14:51:55 +01001506 if (!node) {
1507 fuse_reply_err(req, ENOENT);
1508 return;
1509 }
Ricky Wai44670762020-05-01 11:25:28 +01001510 const struct fuse_ctx* ctx = fuse_req_ctx(req);
Ricky Waif40c4022020-04-15 19:00:06 +01001511 const string path = node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +01001512 if (!is_app_accessible_path(fuse->mp, path, ctx->uid)) {
1513 fuse_reply_err(req, ENOENT);
1514 return;
1515 }
Ricky Waif40c4022020-04-15 19:00:06 +01001516
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001517 TRACE_NODE(node, req);
shafik1e3a2672019-08-16 14:51:55 +01001518
Nandana Dutt5fc32012020-06-25 10:55:52 +01001519 int status = fuse->mp->IsOpendirAllowed(path, ctx->uid, /* forWrite */ false);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001520 if (status) {
1521 fuse_reply_err(req, status);
1522 return;
1523 }
1524
1525 DIR* dir = opendir(path.c_str());
1526 if (!dir) {
shafik1e3a2672019-08-16 14:51:55 +01001527 fuse_reply_err(req, errno);
1528 return;
1529 }
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001530
Narayan Kamathaef84a12020-01-02 15:20:13 +00001531 dirhandle* h = new dirhandle(dir);
1532 node->AddDirHandle(h);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001533
shafik1e3a2672019-08-16 14:51:55 +01001534 fi->fh = ptr_to_id(h);
1535 fuse_reply_open(req, fi);
1536}
1537
1538#define READDIR_BUF 8192LU
1539
1540static void do_readdir_common(fuse_req_t req,
1541 fuse_ino_t ino,
1542 size_t size,
1543 off_t off,
1544 struct fuse_file_info* fi,
1545 bool plus) {
1546 struct fuse* fuse = get_fuse(req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001547 dirhandle* h = reinterpret_cast<dirhandle*>(fi->fh);
Jeff Sharkey7469b982019-08-28 16:51:02 -06001548 size_t len = std::min<size_t>(size, READDIR_BUF);
shafik1e3a2672019-08-16 14:51:55 +01001549 char buf[READDIR_BUF];
1550 size_t used = 0;
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001551 std::shared_ptr<DirectoryEntry> de;
1552
shafik1e3a2672019-08-16 14:51:55 +01001553 struct fuse_entry_param e;
Sahana Rao6f9ea982019-09-20 12:21:33 +01001554 size_t entry_size = 0;
shafik1e3a2672019-08-16 14:51:55 +01001555
Ricky Wai44670762020-05-01 11:25:28 +01001556 node* node = fuse->FromInode(ino);
Ricky Waif40c4022020-04-15 19:00:06 +01001557 if (!node) {
1558 fuse_reply_err(req, ENOENT);
1559 return;
1560 }
Narayan Kamathaef84a12020-01-02 15:20:13 +00001561 const string path = node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +01001562 if (!is_app_accessible_path(fuse->mp, path, req->ctx.uid)) {
1563 fuse_reply_err(req, ENOENT);
1564 return;
1565 }
Narayan Kamath768bea32019-12-27 16:23:23 +00001566
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001567 TRACE_NODE(node, req);
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001568 // Get all directory entries from MediaProvider on first readdir() call of
1569 // directory handle. h->next_off = 0 indicates that current readdir() call
1570 // is first readdir() call for the directory handle, Avoid multiple JNI calls
1571 // for single directory handle.
1572 if (h->next_off == 0) {
Sahana Rao71693442019-11-13 13:48:07 +00001573 h->de = fuse->mp->GetDirectoryEntries(req->ctx.uid, path, h->d);
shafik1e3a2672019-08-16 14:51:55 +01001574 }
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001575 // If the last entry in the previous readdir() call was rejected due to
1576 // buffer capacity constraints, update directory offset to start from
1577 // previously rejected entry. Directory offset can also change if there was
Sahana Rao71693442019-11-13 13:48:07 +00001578 // a seekdir() on the given directory handle.
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001579 if (off != h->next_off) {
1580 h->next_off = off;
1581 }
1582 const int num_directory_entries = h->de.size();
Sahana Rao71693442019-11-13 13:48:07 +00001583 // Check for errors. Any error/exception occurred while obtaining directory
1584 // entries will be indicated by marking first directory entry name as empty
1585 // string. In the erroneous case corresponding d_type will hold error number.
Sahana Rao53bd1f62019-12-27 20:18:39 +00001586 if (num_directory_entries && h->de[0]->d_name.empty()) {
1587 fuse_reply_err(req, h->de[0]->d_type);
1588 return;
1589 }
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001590
Sahana Rao53bd1f62019-12-27 20:18:39 +00001591 while (h->next_off < num_directory_entries) {
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001592 de = h->de[h->next_off];
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001593 entry_size = 0;
1594 h->next_off++;
shafik1e3a2672019-08-16 14:51:55 +01001595 if (plus) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001596 int error_code = 0;
]3e9d56c2021-03-15 16:24:17 +00001597 if (do_lookup(req, ino, de->d_name.c_str(), &e, &error_code, FuseOp::readdir)) {
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001598 entry_size = fuse_add_direntry_plus(req, buf + used, len - used, de->d_name.c_str(),
1599 &e, h->next_off);
Sahana Rao8a588e72019-12-06 11:32:56 +00001600 } else {
Sahana Rao8d8dbb42019-12-18 12:57:02 +00001601 // Ignore lookup errors on
1602 // 1. non-existing files returned from MediaProvider database.
1603 // 2. path that doesn't match FuseDaemon UID and calling uid.
likaid31e75b2020-12-09 16:14:28 +08001604 if (error_code == ENOENT || error_code == EPERM || error_code == EACCES
1605 || error_code == EIO) continue;
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001606 fuse_reply_err(req, error_code);
shafik1e3a2672019-08-16 14:51:55 +01001607 return;
1608 }
1609 } else {
Zim1100f342020-05-15 16:13:00 +01001610 // This should never happen because we have readdir_plus enabled without adaptive
1611 // readdir_plus, FUSE_CAP_READDIRPLUS_AUTO
1612 LOG(WARNING) << "Handling plain readdir for " << de->d_name << ". Invalid d_ino";
shafik1e3a2672019-08-16 14:51:55 +01001613 e.attr.st_ino = FUSE_UNKNOWN_INO;
Zim1100f342020-05-15 16:13:00 +01001614 e.attr.st_mode = de->d_type << 12;
Sahana Raoa82bd6a2019-10-10 18:10:37 +01001615 entry_size = fuse_add_direntry(req, buf + used, len - used, de->d_name.c_str(), &e.attr,
1616 h->next_off);
shafik1e3a2672019-08-16 14:51:55 +01001617 }
Sahana Rao6f9ea982019-09-20 12:21:33 +01001618 // If buffer in fuse_add_direntry[_plus] is not large enough then
1619 // the entry is not added to buffer but the size of the entry is still
1620 // returned. Check available buffer size + returned entry size is less
1621 // than actual buffer size to confirm entry is added to buffer.
Sahana Rao43927f02019-12-10 22:59:01 +00001622 if (used + entry_size > len) {
1623 // When an entry is rejected, lookup called by readdir_plus will not be tracked by
1624 // kernel. Call forget on the rejected node to decrement the reference count.
Narayan Kamathd6219842019-12-27 17:44:35 +00001625 if (plus) {
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001626 do_forget(req, fuse, e.ino, 1);
Narayan Kamathd6219842019-12-27 17:44:35 +00001627 }
Sahana Rao43927f02019-12-10 22:59:01 +00001628 break;
1629 }
Sahana Rao6f9ea982019-09-20 12:21:33 +01001630 used += entry_size;
shafik1e3a2672019-08-16 14:51:55 +01001631 }
Sahana Rao53bd1f62019-12-27 20:18:39 +00001632 fuse_reply_buf(req, buf, used);
shafik1e3a2672019-08-16 14:51:55 +01001633}
1634
1635static void pf_readdir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off,
1636 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001637 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001638 do_readdir_common(req, ino, size, off, fi, false);
1639}
1640
1641static void pf_readdirplus(fuse_req_t req,
1642 fuse_ino_t ino,
1643 size_t size,
1644 off_t off,
1645 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001646 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001647 do_readdir_common(req, ino, size, off, fi, true);
1648}
1649
1650static void pf_releasedir(fuse_req_t req,
1651 fuse_ino_t ino,
1652 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001653 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001654 struct fuse* fuse = get_fuse(req);
shafik1e3a2672019-08-16 14:51:55 +01001655
Ricky Wai44670762020-05-01 11:25:28 +01001656 node* node = fuse->FromInode(ino);
1657
Narayan Kamathaef84a12020-01-02 15:20:13 +00001658 dirhandle* h = reinterpret_cast<dirhandle*>(fi->fh);
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001659 TRACE_NODE(node, req);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001660 if (node) {
1661 node->DestroyDirHandle(h);
Zimedbe69e2019-12-13 18:49:36 +00001662 }
Zimedbe69e2019-12-13 18:49:36 +00001663
shafik1e3a2672019-08-16 14:51:55 +01001664 fuse_reply_err(req, 0);
1665}
1666
1667static void pf_statfs(fuse_req_t req, fuse_ino_t ino) {
Zimec8d5722019-12-05 07:26:13 +00001668 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001669 struct statvfs st;
1670 struct fuse* fuse = get_fuse(req);
1671
Narayan Kamathaef84a12020-01-02 15:20:13 +00001672 if (statvfs(fuse->root->GetName().c_str(), &st))
shafik1e3a2672019-08-16 14:51:55 +01001673 fuse_reply_err(req, errno);
1674 else
1675 fuse_reply_statfs(req, &st);
1676}
1677/*
1678static void pf_setxattr(fuse_req_t req, fuse_ino_t ino, const char* name,
1679 const char* value, size_t size, int flags)
1680{
1681 cout << "TODO:" << __func__;
1682}
1683
1684static void pf_getxattr(fuse_req_t req, fuse_ino_t ino, const char* name,
1685 size_t size)
1686{
1687 cout << "TODO:" << __func__;
1688}
1689
1690static void pf_listxattr(fuse_req_t req, fuse_ino_t ino, size_t size)
1691{
1692 cout << "TODO:" << __func__;
1693}
1694
1695static void pf_removexattr(fuse_req_t req, fuse_ino_t ino, const char* name)
1696{
1697 cout << "TODO:" << __func__;
Zima9fcd552019-08-29 15:17:04 +01001698}*/
1699
1700static void pf_access(fuse_req_t req, fuse_ino_t ino, int mask) {
Zimec8d5722019-12-05 07:26:13 +00001701 ATRACE_CALL();
Zima9fcd552019-08-29 15:17:04 +01001702 struct fuse* fuse = get_fuse(req);
Zima9fcd552019-08-29 15:17:04 +01001703
Ricky Wai44670762020-05-01 11:25:28 +01001704 node* node = fuse->FromInode(ino);
Ricky Waif40c4022020-04-15 19:00:06 +01001705 if (!node) {
1706 fuse_reply_err(req, ENOENT);
1707 return;
1708 }
Narayan Kamathaef84a12020-01-02 15:20:13 +00001709 const string path = node->BuildPath();
Martijn Coenen19c1a872020-07-30 19:59:50 +02001710 if (path != "/storage/emulated" && !is_app_accessible_path(fuse->mp, path, req->ctx.uid)) {
Ricky Wai44670762020-05-01 11:25:28 +01001711 fuse_reply_err(req, ENOENT);
1712 return;
1713 }
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001714 TRACE_NODE(node, req);
Zima9fcd552019-08-29 15:17:04 +01001715
Nandana Dutt17555052020-04-09 16:19:57 +01001716 // exists() checks are always allowed.
1717 if (mask == F_OK) {
1718 int res = access(path.c_str(), F_OK);
1719 fuse_reply_err(req, res ? errno : 0);
1720 return;
1721 }
1722 struct stat stat;
1723 if (lstat(path.c_str(), &stat)) {
1724 // File doesn't exist
1725 fuse_reply_err(req, ENOENT);
1726 return;
1727 }
1728
1729 // For read and write permission checks we go to MediaProvider.
1730 int status = 0;
Nandana Dutt5fc32012020-06-25 10:55:52 +01001731 bool for_write = mask & W_OK;
Nandana Dutt17555052020-04-09 16:19:57 +01001732 bool is_directory = S_ISDIR(stat.st_mode);
1733 if (is_directory) {
Martijn Coenen19c1a872020-07-30 19:59:50 +02001734 if (path == "/storage/emulated" && mask == X_OK) {
1735 // Special case for this path: apps should be allowed to enter it,
1736 // but not list directory contents (which would be user numbers).
1737 int res = access(path.c_str(), X_OK);
1738 fuse_reply_err(req, res ? errno : 0);
1739 return;
1740 }
Nandana Dutt5fc32012020-06-25 10:55:52 +01001741 status = fuse->mp->IsOpendirAllowed(path, req->ctx.uid, for_write);
Nandana Dutt17555052020-04-09 16:19:57 +01001742 } else {
1743 if (mask & X_OK) {
1744 // Fuse is mounted with MS_NOEXEC.
1745 fuse_reply_err(req, EACCES);
1746 return;
1747 }
1748
Zim73895ba2021-01-13 12:51:20 +00001749 std::unique_ptr<FileOpenResult> result = fuse->mp->OnFileOpen(
Zim801d9852021-01-26 18:30:53 +00001750 path, path, req->ctx.uid, req->ctx.pid, node->GetTransformsReason(), for_write,
1751 false /* redact */, false /* log_transforms_metrics */);
Zim73895ba2021-01-13 12:51:20 +00001752 if (!result) {
1753 status = EFAULT;
1754 }
1755
1756 if (result->status) {
1757 status = EACCES;
1758 }
Nandana Dutt17555052020-04-09 16:19:57 +01001759 }
1760
1761 fuse_reply_err(req, status);
shafik1e3a2672019-08-16 14:51:55 +01001762}
Zima9fcd552019-08-29 15:17:04 +01001763
shafik1e3a2672019-08-16 14:51:55 +01001764static void pf_create(fuse_req_t req,
1765 fuse_ino_t parent,
1766 const char* name,
1767 mode_t mode,
1768 struct fuse_file_info* fi) {
Zimec8d5722019-12-05 07:26:13 +00001769 ATRACE_CALL();
shafik1e3a2672019-08-16 14:51:55 +01001770 struct fuse* fuse = get_fuse(req);
Ricky Wai44670762020-05-01 11:25:28 +01001771 node* parent_node = fuse->FromInode(parent);
Ricky Waif40c4022020-04-15 19:00:06 +01001772 if (!parent_node) {
1773 fuse_reply_err(req, ENOENT);
1774 return;
1775 }
Narayan Kamathaef84a12020-01-02 15:20:13 +00001776 const string parent_path = parent_node->BuildPath();
Ricky Wai44670762020-05-01 11:25:28 +01001777 if (!is_app_accessible_path(fuse->mp, parent_path, req->ctx.uid)) {
1778 fuse_reply_err(req, ENOENT);
1779 return;
1780 }
shafik1e3a2672019-08-16 14:51:55 +01001781
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001782 TRACE_NODE(parent_node, req);
shafik1e3a2672019-08-16 14:51:55 +01001783
Narayan Kamathaef84a12020-01-02 15:20:13 +00001784 const string child_path = parent_path + "/" + name;
shafik1e3a2672019-08-16 14:51:55 +01001785
Ricky Wai44670762020-05-01 11:25:28 +01001786 int mp_return_code = fuse->mp->InsertFile(child_path.c_str(), req->ctx.uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001787 if (mp_return_code) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001788 fuse_reply_err(req, mp_return_code);
shafik1e3a2672019-08-16 14:51:55 +01001789 return;
1790 }
1791
Martijn Coenen2d7f1be2020-02-15 07:44:12 +01001792 // With the writeback cache enabled, FUSE may generate READ requests even for files that
1793 // were opened O_WRONLY; so make sure we open it O_RDWR instead.
1794 int open_flags = fi->flags;
1795 if (open_flags & O_WRONLY) {
1796 open_flags &= ~O_WRONLY;
1797 open_flags |= O_RDWR;
1798 }
1799
Zim1b14f2f2020-07-03 07:05:53 +01001800 if (open_flags & O_APPEND) {
1801 open_flags &= ~O_APPEND;
1802 }
1803
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001804 mode = (mode & (~0777)) | 0664;
Martijn Coenen2d7f1be2020-02-15 07:44:12 +01001805 int fd = open(child_path.c_str(), open_flags, mode);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001806 if (fd < 0) {
1807 int error_code = errno;
1808 // We've already inserted the file into the MP database before the
1809 // failed open(), so that needs to be rolled back here.
Ricky Wai44670762020-05-01 11:25:28 +01001810 fuse->mp->DeleteFile(child_path.c_str(), req->ctx.uid);
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001811 fuse_reply_err(req, error_code);
1812 return;
1813 }
1814
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001815 int error_code = 0;
Narayan Kamathaef84a12020-01-02 15:20:13 +00001816 struct fuse_entry_param e;
]3e9d56c2021-03-15 16:24:17 +00001817 node* node =
1818 make_node_entry(req, parent_node, name, child_path, &e, &error_code, FuseOp::create);
Nandana Dutt154cb5d2020-06-04 11:53:31 +01001819 TRACE_NODE(node, req);
Zimc05c60f2020-03-05 13:02:26 +00001820 if (!node) {
Narayan Kamathbbb779a2019-12-31 16:30:11 +00001821 CHECK(error_code != 0);
1822 fuse_reply_err(req, error_code);
Zimc05c60f2020-03-05 13:02:26 +00001823 return;
shafik1e3a2672019-08-16 14:51:55 +01001824 }
Zimc05c60f2020-03-05 13:02:26 +00001825
Martijn Coenenaf2d34d2020-06-19 12:52:20 +02001826 // Let MediaProvider know we've created a new file
1827 fuse->mp->OnFileCreated(child_path);
1828
Zimc05c60f2020-03-05 13:02:26 +00001829 // TODO(b/147274248): Assume there will be no EXIF to redact.
1830 // This prevents crashing during reads but can be a security hole if a malicious app opens an fd
1831 // to the file before all the EXIF content is written. We could special case reads before the
1832 // first close after a file has just been created.
Zim329ba2c2020-09-16 14:23:26 +01001833 int keep_cache = 1;
Manish Singh9a6ccce2021-02-05 23:50:08 +00001834 handle* h = create_handle_for_node(fuse, child_path, fd, req->ctx.uid, 0 /* transforms_uid */,
1835 node, new RedactionInfo(), &keep_cache);
Zimc05c60f2020-03-05 13:02:26 +00001836 fi->fh = ptr_to_id(h);
Zim329ba2c2020-09-16 14:23:26 +01001837 fi->keep_cache = keep_cache;
Zimc05c60f2020-03-05 13:02:26 +00001838 fi->direct_io = !h->cached;
Alessio Balsinif220a962020-07-13 12:01:13 +01001839
1840 // TODO(b/173190192) ensuring that h->cached must be enabled in order to
1841 // user FUSE passthrough is a conservative rule and might be dropped as
1842 // soon as demonstrated its correctness.
Zim148cbe22020-11-17 15:58:29 +00001843 if (h->passthrough) {
Alessio Balsinif220a962020-07-13 12:01:13 +01001844 if (!do_passthrough_enable(req, fi, fd)) {
Zim148cbe22020-11-17 15:58:29 +00001845 PLOG(ERROR) << "Passthrough CREATE failed for " << child_path;
1846 fuse_reply_err(req, EFAULT);
1847 return;
Alessio Balsinif220a962020-07-13 12:01:13 +01001848 }
1849 }
1850
Zimc05c60f2020-03-05 13:02:26 +00001851 fuse_reply_create(req, &e, fi);
shafik1e3a2672019-08-16 14:51:55 +01001852}
1853/*
1854static void pf_getlk(fuse_req_t req, fuse_ino_t ino,
1855 struct fuse_file_info* fi, struct flock* lock)
1856{
1857 cout << "TODO:" << __func__;
1858}
1859
1860static void pf_setlk(fuse_req_t req, fuse_ino_t ino,
1861 struct fuse_file_info* fi,
1862 struct flock* lock, int sleep)
1863{
1864 cout << "TODO:" << __func__;
1865}
1866
1867static void pf_bmap(fuse_req_t req, fuse_ino_t ino, size_t blocksize,
1868 uint64_t idx)
1869{
1870 cout << "TODO:" << __func__;
1871}
1872
1873static void pf_ioctl(fuse_req_t req, fuse_ino_t ino, unsigned int cmd,
1874 void* arg, struct fuse_file_info* fi, unsigned flags,
1875 const void* in_buf, size_t in_bufsz, size_t out_bufsz)
1876{
1877 cout << "TODO:" << __func__;
1878}
1879
1880static void pf_poll(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi,
1881 struct fuse_pollhandle* ph)
1882{
1883 cout << "TODO:" << __func__;
1884}
1885
1886static void pf_retrieve_reply(fuse_req_t req, void* cookie, fuse_ino_t ino,
1887 off_t offset, struct fuse_bufvec* bufv)
1888{
1889 cout << "TODO:" << __func__;
1890}
1891
1892static void pf_flock(fuse_req_t req, fuse_ino_t ino,
1893 struct fuse_file_info* fi, int op)
1894{
1895 cout << "TODO:" << __func__;
1896}
1897
1898static void pf_fallocate(fuse_req_t req, fuse_ino_t ino, int mode,
1899 off_t offset, off_t length, struct fuse_file_info* fi)
1900{
1901 cout << "TODO:" << __func__;
1902}
1903*/
1904
1905static struct fuse_lowlevel_ops ops{
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00001906 .init = pf_init, .destroy = pf_destroy, .lookup = pf_lookup, .forget = pf_forget,
1907 .getattr = pf_getattr, .setattr = pf_setattr, .canonical_path = pf_canonical_path,
1908 .mknod = pf_mknod, .mkdir = pf_mkdir, .unlink = pf_unlink, .rmdir = pf_rmdir,
shafik8b57cd52019-09-06 10:51:29 +01001909 /*.symlink = pf_symlink,*/
1910 .rename = pf_rename,
1911 /*.link = pf_link,*/
1912 .open = pf_open, .read = pf_read,
1913 /*.write = pf_write,*/
Alessio Balsini68c295d2020-07-23 14:32:01 +01001914 /*.flush = pf_flush,*/
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00001915 .release = pf_release, .fsync = pf_fsync, .opendir = pf_opendir, .readdir = pf_readdir,
1916 .releasedir = pf_releasedir, .fsyncdir = pf_fsyncdir, .statfs = pf_statfs,
shafik8b57cd52019-09-06 10:51:29 +01001917 /*.setxattr = pf_setxattr,
1918 .getxattr = pf_getxattr,
1919 .listxattr = pf_listxattr,
1920 .removexattr = pf_removexattr,*/
1921 .access = pf_access, .create = pf_create,
1922 /*.getlk = pf_getlk,
1923 .setlk = pf_setlk,
1924 .bmap = pf_bmap,
1925 .ioctl = pf_ioctl,
Nick Desaulniers17714b82019-11-05 09:44:35 -08001926 .poll = pf_poll,*/
1927 .write_buf = pf_write_buf,
1928 /*.retrieve_reply = pf_retrieve_reply,*/
1929 .forget_multi = pf_forget_multi,
Zim9e3c40b2021-04-09 15:51:15 +01001930 /*.flock = pf_flock,*/
1931 .fallocate = pf_fallocate,
Nick Desaulniers17714b82019-11-05 09:44:35 -08001932 .readdirplus = pf_readdirplus,
1933 /*.copy_file_range = pf_copy_file_range,*/
shafik1e3a2672019-08-16 14:51:55 +01001934};
1935
1936static struct fuse_loop_config config = {
Zim549f9da2020-02-09 13:54:22 +00001937 .clone_fd = 1,
shafik1e3a2672019-08-16 14:51:55 +01001938 .max_idle_threads = 10,
1939};
1940
Zimb353eb42019-12-17 15:29:48 +00001941static std::unordered_map<enum fuse_log_level, enum android_LogPriority> fuse_to_android_loglevel({
1942 {FUSE_LOG_EMERG, ANDROID_LOG_FATAL},
1943 {FUSE_LOG_ALERT, ANDROID_LOG_ERROR},
1944 {FUSE_LOG_CRIT, ANDROID_LOG_ERROR},
1945 {FUSE_LOG_ERR, ANDROID_LOG_ERROR},
1946 {FUSE_LOG_WARNING, ANDROID_LOG_WARN},
1947 {FUSE_LOG_NOTICE, ANDROID_LOG_INFO},
1948 {FUSE_LOG_INFO, ANDROID_LOG_DEBUG},
1949 {FUSE_LOG_DEBUG, ANDROID_LOG_VERBOSE},
1950 });
Zim724b8ca2019-11-09 09:37:24 +00001951
1952static void fuse_logger(enum fuse_log_level level, const char* fmt, va_list ap) {
Zim357e3072020-01-15 10:50:01 +00001953 __android_log_vprint(fuse_to_android_loglevel.at(level), LIBFUSE_LOG_TAG, fmt, ap);
Zim724b8ca2019-11-09 09:37:24 +00001954}
1955
Zimedbe69e2019-12-13 18:49:36 +00001956bool FuseDaemon::ShouldOpenWithFuse(int fd, bool for_read, const std::string& path) {
Zim148cbe22020-11-17 15:58:29 +00001957 if (fuse->passthrough) {
1958 // Always open with FUSE if passthrough is enabled. This avoids the delicate file lock
1959 // acquisition below to ensure VFS cache consistency and doesn't impact filesystem
1960 // performance since read(2)/write(2) happen in the kernel
1961 return true;
1962 }
1963
Zimedbe69e2019-12-13 18:49:36 +00001964 bool use_fuse = false;
1965
1966 if (active.load(std::memory_order_acquire)) {
Zimdc78f532020-03-04 18:46:06 +00001967 std::lock_guard<std::recursive_mutex> guard(fuse->lock);
Narayan Kamathaef84a12020-01-02 15:20:13 +00001968 const node* node = node::LookupAbsolutePath(fuse->root, path);
Zimedbe69e2019-12-13 18:49:36 +00001969 if (node && node->HasCachedHandle()) {
Zimedbe69e2019-12-13 18:49:36 +00001970 use_fuse = true;
1971 } else {
1972 // If we are unable to set a lock, we should use fuse since we can't track
1973 // when all fd references (including dups) are closed. This can happen when
1974 // we try to set a write lock twice on the same file
1975 use_fuse = set_file_lock(fd, for_read, path);
Zimedbe69e2019-12-13 18:49:36 +00001976 }
Zimedbe69e2019-12-13 18:49:36 +00001977 } else {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00001978 LOG(WARNING) << "FUSE daemon is inactive. Cannot open file with FUSE";
Zimedbe69e2019-12-13 18:49:36 +00001979 }
1980
1981 return use_fuse;
1982}
1983
Zima76c3492020-02-19 01:23:26 +00001984void FuseDaemon::InvalidateFuseDentryCache(const std::string& path) {
Zim4d3fa272020-03-06 13:45:19 +00001985 LOG(VERBOSE) << "Invalidating FUSE dentry cache";
Zima76c3492020-02-19 01:23:26 +00001986 if (active.load(std::memory_order_acquire)) {
Zima55568e2020-04-24 22:40:34 +01001987 string name;
1988 fuse_ino_t parent;
Zim33aea102020-06-19 15:49:47 +01001989 fuse_ino_t child;
Zima55568e2020-04-24 22:40:34 +01001990 {
1991 std::lock_guard<std::recursive_mutex> guard(fuse->lock);
1992 const node* node = node::LookupAbsolutePath(fuse->root, path);
1993 if (node) {
1994 name = node->GetName();
Zim33aea102020-06-19 15:49:47 +01001995 child = fuse->ToInode(const_cast<class node*>(node));
Zima55568e2020-04-24 22:40:34 +01001996 parent = fuse->ToInode(node->GetParent());
Zima76c3492020-02-19 01:23:26 +00001997 }
1998 }
Zima55568e2020-04-24 22:40:34 +01001999
Zim33aea102020-06-19 15:49:47 +01002000 if (!name.empty()) {
2001 fuse_inval(fuse->se, parent, child, name, path);
Zima55568e2020-04-24 22:40:34 +01002002 }
Zima76c3492020-02-19 01:23:26 +00002003 } else {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00002004 LOG(WARNING) << "FUSE daemon is inactive. Cannot invalidate dentry";
Zima76c3492020-02-19 01:23:26 +00002005 }
2006}
2007
Zimedbe69e2019-12-13 18:49:36 +00002008FuseDaemon::FuseDaemon(JNIEnv* env, jobject mediaProvider) : mp(env, mediaProvider),
2009 active(false), fuse(nullptr) {}
shafik1e3a2672019-08-16 14:51:55 +01002010
Zimd0435b22020-03-05 13:52:51 +00002011bool FuseDaemon::IsStarted() const {
2012 return active.load(std::memory_order_acquire);
2013}
2014
Martijn Coenen083eb692020-04-24 09:39:58 +02002015void FuseDaemon::Start(android::base::unique_fd fd, const std::string& path) {
Nikita Ioffec33ee1a2020-06-23 21:31:20 +01002016 android::base::SetDefaultTag(LOG_TAG);
2017
shafik1e3a2672019-08-16 14:51:55 +01002018 struct fuse_args args;
2019 struct fuse_cmdline_opts opts;
shafik1e3a2672019-08-16 14:51:55 +01002020
2021 struct stat stat;
shafik1e3a2672019-08-16 14:51:55 +01002022
Zim7c8712d2019-10-03 21:01:26 +01002023 if (lstat(path.c_str(), &stat)) {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00002024 PLOG(ERROR) << "ERROR: failed to stat source " << path;
Zim3e45d9b2019-08-19 21:14:14 +01002025 return;
2026 }
shafik1e3a2672019-08-16 14:51:55 +01002027
Zim3e45d9b2019-08-19 21:14:14 +01002028 if (!S_ISDIR(stat.st_mode)) {
Zimuzo Ezeozue67db40c2020-02-21 19:41:33 +00002029 PLOG(ERROR) << "ERROR: source is not a directory";
Zim3e45d9b2019-08-19 21:14:14 +01002030 return;
2031 }
shafik1e3a2672019-08-16 14:51:55 +01002032
2033 args = FUSE_ARGS_INIT(0, nullptr);
Zim7c8712d2019-10-03 21:01:26 +01002034 if (fuse_opt_add_arg(&args, path.c_str()) || fuse_opt_add_arg(&args, "-odebug") ||
2035 fuse_opt_add_arg(&args, ("-omax_read=" + std::to_string(MAX_READ_SIZE)).c_str())) {
shafik458d1102019-09-06 18:21:36 +01002036 LOG(ERROR) << "ERROR: failed to set options";
shafik1e3a2672019-08-16 14:51:55 +01002037 return;
2038 }
2039
Biswarup Pal93f4ec12021-02-15 13:39:36 +00002040 struct fuse fuse_default(path, stat.st_ino);
shafikc3f62672019-08-30 11:15:48 +01002041 fuse_default.mp = &mp;
Zimedbe69e2019-12-13 18:49:36 +00002042 // fuse_default is stack allocated, but it's safe to save it as an instance variable because
2043 // this method blocks and FuseDaemon#active tells if we are currently blocking
2044 fuse = &fuse_default;
shafikc3f62672019-08-30 11:15:48 +01002045
shafikb334a612019-09-30 20:38:16 +01002046 // Used by pf_read: redacted ranges are represented by zeroized ranges of bytes,
2047 // so we mmap the maximum length of redacted ranges in the beginning and save memory allocations
2048 // on each read.
2049 fuse_default.zero_addr = static_cast<char*>(mmap(
2050 NULL, MAX_READ_SIZE, PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, /*fd*/ -1, /*off*/ 0));
2051 if (fuse_default.zero_addr == MAP_FAILED) {
2052 LOG(FATAL) << "mmap failed - could not start fuse! errno = " << errno;
2053 }
2054
Zim724b8ca2019-11-09 09:37:24 +00002055 // Custom logging for libfuse
Zim0594b032020-04-29 11:43:43 +01002056 if (android::base::GetBoolProperty("persist.sys.fuse.log", false)) {
2057 fuse_set_log_func(fuse_logger);
2058 }
Zim724b8ca2019-11-09 09:37:24 +00002059
Zim3cde2662021-02-22 21:20:33 +00002060 if (MY_USER_ID != 0 && mp.IsAppCloneUser(MY_USER_ID)) {
Martijn Coenen87133092020-10-14 17:00:28 +02002061 // Disable dentry caching for the app clone user
2062 fuse->disable_dentry_cache = true;
2063 }
2064
Alessio Balsinib1c366b2020-11-26 15:15:14 +00002065 fuse->passthrough = android::base::GetBoolProperty("persist.sys.fuse.passthrough.enable", false);
2066 if (fuse->passthrough) {
2067 LOG(INFO) << "Using FUSE passthrough";
2068 }
Alessio Balsinif220a962020-07-13 12:01:13 +01002069
shafik1e3a2672019-08-16 14:51:55 +01002070 struct fuse_session
2071 * se = fuse_session_new(&args, &ops, sizeof(ops), &fuse_default);
Zim7e0d3142019-10-17 21:06:12 +01002072 if (!se) {
2073 PLOG(ERROR) << "Failed to create session ";
2074 return;
2075 }
Zima76c3492020-02-19 01:23:26 +00002076 fuse_default.se = se;
Zimd0435b22020-03-05 13:52:51 +00002077 fuse_default.active = &active;
Martijn Coenen3ec6c062020-04-28 19:09:53 +02002078 se->fd = fd.release(); // libfuse owns the FD now
Zim7c8712d2019-10-03 21:01:26 +01002079 se->mountpoint = strdup(path.c_str());
Zim3e45d9b2019-08-19 21:14:14 +01002080
2081 // Single thread. Useful for debugging
2082 // fuse_session_loop(se);
2083 // Multi-threaded
Zim7e0d3142019-10-17 21:06:12 +01002084 LOG(INFO) << "Starting fuse...";
shafik1e3a2672019-08-16 14:51:55 +01002085 fuse_session_loop_mt(se, &config);
Zimd0435b22020-03-05 13:52:51 +00002086 fuse->active->store(false, std::memory_order_release);
Zim7e0d3142019-10-17 21:06:12 +01002087 LOG(INFO) << "Ending fuse...";
Zim3e45d9b2019-08-19 21:14:14 +01002088
Zim7c8712d2019-10-03 21:01:26 +01002089 if (munmap(fuse_default.zero_addr, MAX_READ_SIZE)) {
2090 PLOG(ERROR) << "munmap failed!";
shafikb334a612019-09-30 20:38:16 +01002091 }
2092
Zim7e0d3142019-10-17 21:06:12 +01002093 fuse_opt_free_args(&args);
2094 fuse_session_destroy(se);
2095 LOG(INFO) << "Ended fuse";
2096 return;
shafik1e3a2672019-08-16 14:51:55 +01002097}
Biswarup Pal93f4ec12021-02-15 13:39:36 +00002098
2099const string FuseDaemon::GetOriginalMediaFormatFilePath(int fd) const {
2100 struct stat s;
2101 memset(&s, 0, sizeof(s));
2102 if (fstat(fd, &s) < 0) {
2103 PLOG(DEBUG) << "GetOriginalMediaFormatFilePath fstat failed.";
2104 return string();
2105 }
2106
2107 ino_t ino = s.st_ino;
2108 dev_t dev = s.st_dev;
2109
2110 dev_t fuse_dev = fuse->dev.load(std::memory_order_acquire);
2111 if (dev != fuse_dev) {
2112 PLOG(DEBUG) << "GetOriginalMediaFormatFilePath FUSE device id does not match.";
2113 return string();
2114 }
2115
2116 const node* node = node::LookupInode(fuse->root, ino);
2117 if (!node) {
2118 PLOG(DEBUG) << "GetOriginalMediaFormatFilePath no node found with given ino";
2119 return string();
2120 }
2121
2122 return node->BuildPath();
2123}
2124
2125void FuseDaemon::InitializeDeviceId(const std::string& path) {
2126 struct stat stat;
2127
2128 if (lstat(path.c_str(), &stat)) {
2129 PLOG(ERROR) << "InitializeDeviceId failed to stat given path " << path;
2130 return;
2131 }
2132
2133 fuse->dev.store(stat.st_dev, std::memory_order_release);
2134}
shafik1e3a2672019-08-16 14:51:55 +01002135} //namespace fuse
shafik8b57cd52019-09-06 10:51:29 +01002136} // namespace mediaprovider