2 * FUSE: Filesystem in Userspace
3 * Copyright (C) 2001-2007 Miklos Szeredi <miklos@szeredi.hu>
5 * This program can be distributed under the terms of the GNU GPLv2.
6 * See the file COPYING.
11 * This file system mirrors the existing file system hierarchy of the
12 * system, starting at the root file system. This is implemented by
13 * just "passing through" all requests to the corresponding user-space
14 * libc functions. In contrast to passthrough.c and passthrough_fh.c,
15 * this implementation uses the low-level API. Its performance should
16 * be the least bad among the three, but many operations are not
17 * implemented. In particular, it is not possible to remove files (or
18 * directories) because the code necessary to defer actual removal
19 * until the file is not opened anymore would make the example much
22 * When writeback caching is enabled (-o writeback mount option), it
23 * is only possible to write to files for which the mounting user has
24 * read permissions. This is because the writeback cache requires the
25 * kernel to be able to issue read requests for all files (which the
26 * passthrough filesystem cannot satisfy if it can't read the file in
27 * the underlying filesystem).
31 * gcc -Wall passthrough_ll.c `pkg-config fuse3 --cflags --libs` -o
35 * \include passthrough_ll.c
38 #include "qemu/osdep.h"
39 #include "qemu/timer.h"
40 #include "fuse_virtio.h"
42 #include "fuse_lowlevel.h"
43 #include "standard-headers/linux/fuse.h"
48 #include <sys/mount.h>
49 #include <sys/prctl.h>
50 #include <sys/resource.h>
51 #include <sys/syscall.h>
53 #include <sys/xattr.h>
56 #include "qemu/cutils.h"
57 #include "passthrough_helpers.h"
58 #include "passthrough_seccomp.h"
60 /* Keep track of inode posix locks for each owner. */
61 struct lo_inode_plock
{
63 int fd
; /* fd for OFD locks */
68 struct lo_inode
*inode
;
76 /* Maps FUSE fh or ino values to internal objects */
78 struct lo_map_elem
*elems
;
93 * Atomic reference count for this object. The nlookup field holds a
94 * reference and release it when nlookup reaches 0.
101 * This counter keeps the inode alive during the FUSE session.
102 * Incremented when the FUSE inode number is sent in a reply
103 * (FUSE_LOOKUP, FUSE_READDIRPLUS, etc). Decremented when an inode is
104 * released by requests like FUSE_FORGET, FUSE_RMDIR, FUSE_RENAME, etc.
106 * Note that this value is untrusted because the client can manipulate
107 * it arbitrarily using FUSE_FORGET requests.
109 * Protected by lo->mutex.
114 pthread_mutex_t plock_mutex
;
115 GHashTable
*posix_locks
; /* protected by lo_inode->plock_mutex */
136 typedef struct xattr_map_entry
{
143 pthread_mutex_t mutex
;
157 int readdirplus_clear
;
159 int announce_submounts
;
161 struct lo_inode root
;
162 GHashTable
*inodes
; /* protected by lo->mutex */
163 struct lo_map ino_map
; /* protected by lo->mutex */
164 struct lo_map dirp_map
; /* protected by lo->mutex */
165 struct lo_map fd_map
; /* protected by lo->mutex */
166 XattrMapEntry
*xattr_map_list
;
167 size_t xattr_map_nentries
;
169 /* An O_PATH file descriptor to /proc/self/fd/ */
173 static const struct fuse_opt lo_opts
[] = {
174 { "sandbox=namespace",
175 offsetof(struct lo_data
, sandbox
),
178 offsetof(struct lo_data
, sandbox
),
180 { "writeback", offsetof(struct lo_data
, writeback
), 1 },
181 { "no_writeback", offsetof(struct lo_data
, writeback
), 0 },
182 { "source=%s", offsetof(struct lo_data
, source
), 0 },
183 { "flock", offsetof(struct lo_data
, flock
), 1 },
184 { "no_flock", offsetof(struct lo_data
, flock
), 0 },
185 { "posix_lock", offsetof(struct lo_data
, posix_lock
), 1 },
186 { "no_posix_lock", offsetof(struct lo_data
, posix_lock
), 0 },
187 { "xattr", offsetof(struct lo_data
, xattr
), 1 },
188 { "no_xattr", offsetof(struct lo_data
, xattr
), 0 },
189 { "xattrmap=%s", offsetof(struct lo_data
, xattrmap
), 0 },
190 { "modcaps=%s", offsetof(struct lo_data
, modcaps
), 0 },
191 { "timeout=%lf", offsetof(struct lo_data
, timeout
), 0 },
192 { "timeout=", offsetof(struct lo_data
, timeout_set
), 1 },
193 { "cache=none", offsetof(struct lo_data
, cache
), CACHE_NONE
},
194 { "cache=auto", offsetof(struct lo_data
, cache
), CACHE_AUTO
},
195 { "cache=always", offsetof(struct lo_data
, cache
), CACHE_ALWAYS
},
196 { "readdirplus", offsetof(struct lo_data
, readdirplus_set
), 1 },
197 { "no_readdirplus", offsetof(struct lo_data
, readdirplus_clear
), 1 },
198 { "allow_direct_io", offsetof(struct lo_data
, allow_direct_io
), 1 },
199 { "no_allow_direct_io", offsetof(struct lo_data
, allow_direct_io
), 0 },
200 { "announce_submounts", offsetof(struct lo_data
, announce_submounts
), 1 },
203 static bool use_syslog
= false;
204 static int current_log_level
;
205 static void unref_inode_lolocked(struct lo_data
*lo
, struct lo_inode
*inode
,
209 pthread_mutex_t mutex
;
212 /* That we loaded cap-ng in the current thread from the saved */
213 static __thread
bool cap_loaded
= 0;
215 static struct lo_inode
*lo_find(struct lo_data
*lo
, struct stat
*st
,
218 static int is_dot_or_dotdot(const char *name
)
220 return name
[0] == '.' &&
221 (name
[1] == '\0' || (name
[1] == '.' && name
[2] == '\0'));
224 /* Is `path` a single path component that is not "." or ".."? */
225 static int is_safe_path_component(const char *path
)
227 if (strchr(path
, '/')) {
231 return !is_dot_or_dotdot(path
);
234 static struct lo_data
*lo_data(fuse_req_t req
)
236 return (struct lo_data
*)fuse_req_userdata(req
);
240 * Load capng's state from our saved state if the current thread
241 * hadn't previously been loaded.
242 * returns 0 on success
244 static int load_capng(void)
247 pthread_mutex_lock(&cap
.mutex
);
248 capng_restore_state(&cap
.saved
);
250 * restore_state free's the saved copy
253 cap
.saved
= capng_save_state();
255 pthread_mutex_unlock(&cap
.mutex
);
256 fuse_log(FUSE_LOG_ERR
, "capng_save_state (thread)\n");
259 pthread_mutex_unlock(&cap
.mutex
);
262 * We want to use the loaded state for our pid,
265 capng_setpid(syscall(SYS_gettid
));
272 * Helpers for dropping and regaining effective capabilities. Returns 0
273 * on success, error otherwise
275 static int drop_effective_cap(const char *cap_name
, bool *cap_dropped
)
279 cap
= capng_name_to_capability(cap_name
);
282 fuse_log(FUSE_LOG_ERR
, "capng_name_to_capability(%s) failed:%s\n",
283 cap_name
, strerror(errno
));
289 fuse_log(FUSE_LOG_ERR
, "load_capng() failed\n");
293 /* We dont have this capability in effective set already. */
294 if (!capng_have_capability(CAPNG_EFFECTIVE
, cap
)) {
299 if (capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, cap
)) {
301 fuse_log(FUSE_LOG_ERR
, "capng_update(DROP,) failed\n");
305 if (capng_apply(CAPNG_SELECT_CAPS
)) {
307 fuse_log(FUSE_LOG_ERR
, "drop:capng_apply() failed\n");
320 static int gain_effective_cap(const char *cap_name
)
325 cap
= capng_name_to_capability(cap_name
);
328 fuse_log(FUSE_LOG_ERR
, "capng_name_to_capability(%s) failed:%s\n",
329 cap_name
, strerror(errno
));
335 fuse_log(FUSE_LOG_ERR
, "load_capng() failed\n");
339 if (capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, cap
)) {
341 fuse_log(FUSE_LOG_ERR
, "capng_update(ADD,) failed\n");
345 if (capng_apply(CAPNG_SELECT_CAPS
)) {
347 fuse_log(FUSE_LOG_ERR
, "gain:capng_apply() failed\n");
356 static void lo_map_init(struct lo_map
*map
)
363 static void lo_map_destroy(struct lo_map
*map
)
368 static int lo_map_grow(struct lo_map
*map
, size_t new_nelems
)
370 struct lo_map_elem
*new_elems
;
373 if (new_nelems
<= map
->nelems
) {
377 new_elems
= realloc(map
->elems
, sizeof(map
->elems
[0]) * new_nelems
);
382 for (i
= map
->nelems
; i
< new_nelems
; i
++) {
383 new_elems
[i
].freelist
= i
+ 1;
384 new_elems
[i
].in_use
= false;
386 new_elems
[new_nelems
- 1].freelist
= -1;
388 map
->elems
= new_elems
;
389 map
->freelist
= map
->nelems
;
390 map
->nelems
= new_nelems
;
394 static struct lo_map_elem
*lo_map_alloc_elem(struct lo_map
*map
)
396 struct lo_map_elem
*elem
;
398 if (map
->freelist
== -1 && !lo_map_grow(map
, map
->nelems
+ 256)) {
402 elem
= &map
->elems
[map
->freelist
];
403 map
->freelist
= elem
->freelist
;
410 static struct lo_map_elem
*lo_map_reserve(struct lo_map
*map
, size_t key
)
414 if (!lo_map_grow(map
, key
+ 1)) {
418 for (prev
= &map
->freelist
; *prev
!= -1;
419 prev
= &map
->elems
[*prev
].freelist
) {
421 struct lo_map_elem
*elem
= &map
->elems
[key
];
423 *prev
= elem
->freelist
;
431 static struct lo_map_elem
*lo_map_get(struct lo_map
*map
, size_t key
)
433 if (key
>= map
->nelems
) {
436 if (!map
->elems
[key
].in_use
) {
439 return &map
->elems
[key
];
442 static void lo_map_remove(struct lo_map
*map
, size_t key
)
444 struct lo_map_elem
*elem
;
446 if (key
>= map
->nelems
) {
450 elem
= &map
->elems
[key
];
455 elem
->in_use
= false;
457 elem
->freelist
= map
->freelist
;
461 /* Assumes lo->mutex is held */
462 static ssize_t
lo_add_fd_mapping(fuse_req_t req
, int fd
)
464 struct lo_map_elem
*elem
;
466 elem
= lo_map_alloc_elem(&lo_data(req
)->fd_map
);
472 return elem
- lo_data(req
)->fd_map
.elems
;
475 /* Assumes lo->mutex is held */
476 static ssize_t
lo_add_dirp_mapping(fuse_req_t req
, struct lo_dirp
*dirp
)
478 struct lo_map_elem
*elem
;
480 elem
= lo_map_alloc_elem(&lo_data(req
)->dirp_map
);
486 return elem
- lo_data(req
)->dirp_map
.elems
;
489 /* Assumes lo->mutex is held */
490 static ssize_t
lo_add_inode_mapping(fuse_req_t req
, struct lo_inode
*inode
)
492 struct lo_map_elem
*elem
;
494 elem
= lo_map_alloc_elem(&lo_data(req
)->ino_map
);
500 return elem
- lo_data(req
)->ino_map
.elems
;
503 static void lo_inode_put(struct lo_data
*lo
, struct lo_inode
**inodep
)
505 struct lo_inode
*inode
= *inodep
;
513 if (g_atomic_int_dec_and_test(&inode
->refcount
)) {
519 /* Caller must release refcount using lo_inode_put() */
520 static struct lo_inode
*lo_inode(fuse_req_t req
, fuse_ino_t ino
)
522 struct lo_data
*lo
= lo_data(req
);
523 struct lo_map_elem
*elem
;
525 pthread_mutex_lock(&lo
->mutex
);
526 elem
= lo_map_get(&lo
->ino_map
, ino
);
528 g_atomic_int_inc(&elem
->inode
->refcount
);
530 pthread_mutex_unlock(&lo
->mutex
);
540 * TODO Remove this helper and force callers to hold an inode refcount until
541 * they are done with the fd. This will be done in a later patch to make
544 static int lo_fd(fuse_req_t req
, fuse_ino_t ino
)
546 struct lo_inode
*inode
= lo_inode(req
, ino
);
554 lo_inode_put(lo_data(req
), &inode
);
558 static void lo_init(void *userdata
, struct fuse_conn_info
*conn
)
560 struct lo_data
*lo
= (struct lo_data
*)userdata
;
562 if (conn
->capable
& FUSE_CAP_EXPORT_SUPPORT
) {
563 conn
->want
|= FUSE_CAP_EXPORT_SUPPORT
;
566 if (lo
->writeback
&& conn
->capable
& FUSE_CAP_WRITEBACK_CACHE
) {
567 fuse_log(FUSE_LOG_DEBUG
, "lo_init: activating writeback\n");
568 conn
->want
|= FUSE_CAP_WRITEBACK_CACHE
;
570 if (conn
->capable
& FUSE_CAP_FLOCK_LOCKS
) {
572 fuse_log(FUSE_LOG_DEBUG
, "lo_init: activating flock locks\n");
573 conn
->want
|= FUSE_CAP_FLOCK_LOCKS
;
575 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling flock locks\n");
576 conn
->want
&= ~FUSE_CAP_FLOCK_LOCKS
;
580 if (conn
->capable
& FUSE_CAP_POSIX_LOCKS
) {
581 if (lo
->posix_lock
) {
582 fuse_log(FUSE_LOG_DEBUG
, "lo_init: activating posix locks\n");
583 conn
->want
|= FUSE_CAP_POSIX_LOCKS
;
585 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling posix locks\n");
586 conn
->want
&= ~FUSE_CAP_POSIX_LOCKS
;
590 if ((lo
->cache
== CACHE_NONE
&& !lo
->readdirplus_set
) ||
591 lo
->readdirplus_clear
) {
592 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling readdirplus\n");
593 conn
->want
&= ~FUSE_CAP_READDIRPLUS
;
596 if (!(conn
->capable
& FUSE_CAP_SUBMOUNTS
) && lo
->announce_submounts
) {
597 fuse_log(FUSE_LOG_WARNING
, "lo_init: Cannot announce submounts, client "
598 "does not support it\n");
599 lo
->announce_submounts
= false;
603 static void lo_getattr(fuse_req_t req
, fuse_ino_t ino
,
604 struct fuse_file_info
*fi
)
608 struct lo_data
*lo
= lo_data(req
);
613 fstatat(lo_fd(req
, ino
), "", &buf
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
615 return (void)fuse_reply_err(req
, errno
);
618 fuse_reply_attr(req
, &buf
, lo
->timeout
);
621 static int lo_fi_fd(fuse_req_t req
, struct fuse_file_info
*fi
)
623 struct lo_data
*lo
= lo_data(req
);
624 struct lo_map_elem
*elem
;
626 pthread_mutex_lock(&lo
->mutex
);
627 elem
= lo_map_get(&lo
->fd_map
, fi
->fh
);
628 pthread_mutex_unlock(&lo
->mutex
);
637 static void lo_setattr(fuse_req_t req
, fuse_ino_t ino
, struct stat
*attr
,
638 int valid
, struct fuse_file_info
*fi
)
642 struct lo_data
*lo
= lo_data(req
);
643 struct lo_inode
*inode
;
648 inode
= lo_inode(req
, ino
);
650 fuse_reply_err(req
, EBADF
);
656 /* If fi->fh is invalid we'll report EBADF later */
658 fd
= lo_fi_fd(req
, fi
);
661 if (valid
& FUSE_SET_ATTR_MODE
) {
663 res
= fchmod(fd
, attr
->st_mode
);
665 sprintf(procname
, "%i", ifd
);
666 res
= fchmodat(lo
->proc_self_fd
, procname
, attr
->st_mode
, 0);
672 if (valid
& (FUSE_SET_ATTR_UID
| FUSE_SET_ATTR_GID
)) {
673 uid_t uid
= (valid
& FUSE_SET_ATTR_UID
) ? attr
->st_uid
: (uid_t
)-1;
674 gid_t gid
= (valid
& FUSE_SET_ATTR_GID
) ? attr
->st_gid
: (gid_t
)-1;
676 res
= fchownat(ifd
, "", uid
, gid
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
681 if (valid
& FUSE_SET_ATTR_SIZE
) {
687 sprintf(procname
, "%i", ifd
);
688 truncfd
= openat(lo
->proc_self_fd
, procname
, O_RDWR
);
694 res
= ftruncate(truncfd
, attr
->st_size
);
704 if (valid
& (FUSE_SET_ATTR_ATIME
| FUSE_SET_ATTR_MTIME
)) {
705 struct timespec tv
[2];
709 tv
[0].tv_nsec
= UTIME_OMIT
;
710 tv
[1].tv_nsec
= UTIME_OMIT
;
712 if (valid
& FUSE_SET_ATTR_ATIME_NOW
) {
713 tv
[0].tv_nsec
= UTIME_NOW
;
714 } else if (valid
& FUSE_SET_ATTR_ATIME
) {
715 tv
[0] = attr
->st_atim
;
718 if (valid
& FUSE_SET_ATTR_MTIME_NOW
) {
719 tv
[1].tv_nsec
= UTIME_NOW
;
720 } else if (valid
& FUSE_SET_ATTR_MTIME
) {
721 tv
[1] = attr
->st_mtim
;
725 res
= futimens(fd
, tv
);
727 sprintf(procname
, "%i", inode
->fd
);
728 res
= utimensat(lo
->proc_self_fd
, procname
, tv
, 0);
734 lo_inode_put(lo
, &inode
);
736 return lo_getattr(req
, ino
, fi
);
740 lo_inode_put(lo
, &inode
);
741 fuse_reply_err(req
, saverr
);
744 static struct lo_inode
*lo_find(struct lo_data
*lo
, struct stat
*st
,
748 struct lo_key key
= {
754 pthread_mutex_lock(&lo
->mutex
);
755 p
= g_hash_table_lookup(lo
->inodes
, &key
);
757 assert(p
->nlookup
> 0);
759 g_atomic_int_inc(&p
->refcount
);
761 pthread_mutex_unlock(&lo
->mutex
);
766 /* value_destroy_func for posix_locks GHashTable */
767 static void posix_locks_value_destroy(gpointer data
)
769 struct lo_inode_plock
*plock
= data
;
772 * We had used open() for locks and had only one fd. So
773 * closing this fd should release all OFD locks.
779 static int do_statx(struct lo_data
*lo
, int dirfd
, const char *pathname
,
780 struct stat
*statbuf
, int flags
, uint64_t *mnt_id
)
784 #if defined(CONFIG_STATX) && defined(STATX_MNT_ID)
786 struct statx statxbuf
;
788 res
= statx(dirfd
, pathname
, flags
, STATX_BASIC_STATS
| STATX_MNT_ID
,
791 memset(statbuf
, 0, sizeof(*statbuf
));
792 statbuf
->st_dev
= makedev(statxbuf
.stx_dev_major
,
793 statxbuf
.stx_dev_minor
);
794 statbuf
->st_ino
= statxbuf
.stx_ino
;
795 statbuf
->st_mode
= statxbuf
.stx_mode
;
796 statbuf
->st_nlink
= statxbuf
.stx_nlink
;
797 statbuf
->st_uid
= statxbuf
.stx_uid
;
798 statbuf
->st_gid
= statxbuf
.stx_gid
;
799 statbuf
->st_rdev
= makedev(statxbuf
.stx_rdev_major
,
800 statxbuf
.stx_rdev_minor
);
801 statbuf
->st_size
= statxbuf
.stx_size
;
802 statbuf
->st_blksize
= statxbuf
.stx_blksize
;
803 statbuf
->st_blocks
= statxbuf
.stx_blocks
;
804 statbuf
->st_atim
.tv_sec
= statxbuf
.stx_atime
.tv_sec
;
805 statbuf
->st_atim
.tv_nsec
= statxbuf
.stx_atime
.tv_nsec
;
806 statbuf
->st_mtim
.tv_sec
= statxbuf
.stx_mtime
.tv_sec
;
807 statbuf
->st_mtim
.tv_nsec
= statxbuf
.stx_mtime
.tv_nsec
;
808 statbuf
->st_ctim
.tv_sec
= statxbuf
.stx_ctime
.tv_sec
;
809 statbuf
->st_ctim
.tv_nsec
= statxbuf
.stx_ctime
.tv_nsec
;
811 if (statxbuf
.stx_mask
& STATX_MNT_ID
) {
812 *mnt_id
= statxbuf
.stx_mnt_id
;
817 } else if (errno
!= ENOSYS
) {
820 lo
->use_statx
= false;
824 res
= fstatat(dirfd
, pathname
, statbuf
, flags
);
834 * Increments nlookup and caller must release refcount using
835 * lo_inode_put(&parent).
837 static int lo_do_lookup(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
838 struct fuse_entry_param
*e
)
844 struct lo_data
*lo
= lo_data(req
);
845 struct lo_inode
*inode
= NULL
;
846 struct lo_inode
*dir
= lo_inode(req
, parent
);
849 * name_to_handle_at() and open_by_handle_at() can reach here with fuse
850 * mount point in guest, but we don't have its inode info in the
857 memset(e
, 0, sizeof(*e
));
858 e
->attr_timeout
= lo
->timeout
;
859 e
->entry_timeout
= lo
->timeout
;
861 /* Do not allow escaping root directory */
862 if (dir
== &lo
->root
&& strcmp(name
, "..") == 0) {
866 newfd
= openat(dir
->fd
, name
, O_PATH
| O_NOFOLLOW
);
871 res
= do_statx(lo
, newfd
, "", &e
->attr
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
,
877 if (S_ISDIR(e
->attr
.st_mode
) && lo
->announce_submounts
&&
878 (e
->attr
.st_dev
!= dir
->key
.dev
|| mnt_id
!= dir
->key
.mnt_id
)) {
879 e
->attr_flags
|= FUSE_ATTR_SUBMOUNT
;
882 inode
= lo_find(lo
, &e
->attr
, mnt_id
);
886 inode
= calloc(1, sizeof(struct lo_inode
));
891 /* cache only filetype */
892 inode
->filetype
= (e
->attr
.st_mode
& S_IFMT
);
895 * One for the caller and one for nlookup (released in
896 * unref_inode_lolocked())
898 g_atomic_int_set(&inode
->refcount
, 2);
902 inode
->key
.ino
= e
->attr
.st_ino
;
903 inode
->key
.dev
= e
->attr
.st_dev
;
904 inode
->key
.mnt_id
= mnt_id
;
905 pthread_mutex_init(&inode
->plock_mutex
, NULL
);
906 inode
->posix_locks
= g_hash_table_new_full(
907 g_direct_hash
, g_direct_equal
, NULL
, posix_locks_value_destroy
);
909 pthread_mutex_lock(&lo
->mutex
);
910 inode
->fuse_ino
= lo_add_inode_mapping(req
, inode
);
911 g_hash_table_insert(lo
->inodes
, &inode
->key
, inode
);
912 pthread_mutex_unlock(&lo
->mutex
);
914 e
->ino
= inode
->fuse_ino
;
915 lo_inode_put(lo
, &inode
);
916 lo_inode_put(lo
, &dir
);
918 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
919 name
, (unsigned long long)e
->ino
);
928 lo_inode_put(lo
, &inode
);
929 lo_inode_put(lo
, &dir
);
933 static void lo_lookup(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
935 struct fuse_entry_param e
;
938 fuse_log(FUSE_LOG_DEBUG
, "lo_lookup(parent=%" PRIu64
", name=%s)\n", parent
,
942 * Don't use is_safe_path_component(), allow "." and ".." for NFS export
945 if (strchr(name
, '/')) {
946 fuse_reply_err(req
, EINVAL
);
950 err
= lo_do_lookup(req
, parent
, name
, &e
);
952 fuse_reply_err(req
, err
);
954 fuse_reply_entry(req
, &e
);
959 * On some archs, setres*id is limited to 2^16 but they
960 * provide setres*id32 variants that allow 2^32.
961 * Others just let setres*id do 2^32 anyway.
963 #ifdef SYS_setresgid32
964 #define OURSYS_setresgid SYS_setresgid32
966 #define OURSYS_setresgid SYS_setresgid
969 #ifdef SYS_setresuid32
970 #define OURSYS_setresuid SYS_setresuid32
972 #define OURSYS_setresuid SYS_setresuid
976 * Change to uid/gid of caller so that file is created with
977 * ownership of caller.
978 * TODO: What about selinux context?
980 static int lo_change_cred(fuse_req_t req
, struct lo_cred
*old
)
984 old
->euid
= geteuid();
985 old
->egid
= getegid();
987 res
= syscall(OURSYS_setresgid
, -1, fuse_req_ctx(req
)->gid
, -1);
992 res
= syscall(OURSYS_setresuid
, -1, fuse_req_ctx(req
)->uid
, -1);
994 int errno_save
= errno
;
996 syscall(OURSYS_setresgid
, -1, old
->egid
, -1);
1003 /* Regain Privileges */
1004 static void lo_restore_cred(struct lo_cred
*old
)
1008 res
= syscall(OURSYS_setresuid
, -1, old
->euid
, -1);
1010 fuse_log(FUSE_LOG_ERR
, "seteuid(%u): %m\n", old
->euid
);
1014 res
= syscall(OURSYS_setresgid
, -1, old
->egid
, -1);
1016 fuse_log(FUSE_LOG_ERR
, "setegid(%u): %m\n", old
->egid
);
1021 static void lo_mknod_symlink(fuse_req_t req
, fuse_ino_t parent
,
1022 const char *name
, mode_t mode
, dev_t rdev
,
1027 struct lo_data
*lo
= lo_data(req
);
1028 struct lo_inode
*dir
;
1029 struct fuse_entry_param e
;
1030 struct lo_cred old
= {};
1032 if (!is_safe_path_component(name
)) {
1033 fuse_reply_err(req
, EINVAL
);
1037 dir
= lo_inode(req
, parent
);
1039 fuse_reply_err(req
, EBADF
);
1043 saverr
= lo_change_cred(req
, &old
);
1048 res
= mknod_wrapper(dir
->fd
, name
, link
, mode
, rdev
);
1052 lo_restore_cred(&old
);
1058 saverr
= lo_do_lookup(req
, parent
, name
, &e
);
1063 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
1064 name
, (unsigned long long)e
.ino
);
1066 fuse_reply_entry(req
, &e
);
1067 lo_inode_put(lo
, &dir
);
1071 lo_inode_put(lo
, &dir
);
1072 fuse_reply_err(req
, saverr
);
1075 static void lo_mknod(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1076 mode_t mode
, dev_t rdev
)
1078 lo_mknod_symlink(req
, parent
, name
, mode
, rdev
, NULL
);
1081 static void lo_mkdir(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1084 lo_mknod_symlink(req
, parent
, name
, S_IFDIR
| mode
, 0, NULL
);
1087 static void lo_symlink(fuse_req_t req
, const char *link
, fuse_ino_t parent
,
1090 lo_mknod_symlink(req
, parent
, name
, S_IFLNK
, 0, link
);
1093 static void lo_link(fuse_req_t req
, fuse_ino_t ino
, fuse_ino_t parent
,
1097 struct lo_data
*lo
= lo_data(req
);
1098 struct lo_inode
*parent_inode
;
1099 struct lo_inode
*inode
;
1100 struct fuse_entry_param e
;
1104 if (!is_safe_path_component(name
)) {
1105 fuse_reply_err(req
, EINVAL
);
1109 parent_inode
= lo_inode(req
, parent
);
1110 inode
= lo_inode(req
, ino
);
1111 if (!parent_inode
|| !inode
) {
1116 memset(&e
, 0, sizeof(struct fuse_entry_param
));
1117 e
.attr_timeout
= lo
->timeout
;
1118 e
.entry_timeout
= lo
->timeout
;
1120 sprintf(procname
, "%i", inode
->fd
);
1121 res
= linkat(lo
->proc_self_fd
, procname
, parent_inode
->fd
, name
,
1127 res
= fstatat(inode
->fd
, "", &e
.attr
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
1132 pthread_mutex_lock(&lo
->mutex
);
1134 pthread_mutex_unlock(&lo
->mutex
);
1135 e
.ino
= inode
->fuse_ino
;
1137 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
1138 name
, (unsigned long long)e
.ino
);
1140 fuse_reply_entry(req
, &e
);
1141 lo_inode_put(lo
, &parent_inode
);
1142 lo_inode_put(lo
, &inode
);
1147 lo_inode_put(lo
, &parent_inode
);
1148 lo_inode_put(lo
, &inode
);
1149 fuse_reply_err(req
, saverr
);
1152 /* Increments nlookup and caller must release refcount using lo_inode_put() */
1153 static struct lo_inode
*lookup_name(fuse_req_t req
, fuse_ino_t parent
,
1159 struct lo_data
*lo
= lo_data(req
);
1160 struct lo_inode
*dir
= lo_inode(req
, parent
);
1166 res
= do_statx(lo
, dir
->fd
, name
, &attr
,
1167 AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
, &mnt_id
);
1168 lo_inode_put(lo
, &dir
);
1173 return lo_find(lo
, &attr
, mnt_id
);
1176 static void lo_rmdir(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
1179 struct lo_inode
*inode
;
1180 struct lo_data
*lo
= lo_data(req
);
1182 if (!is_safe_path_component(name
)) {
1183 fuse_reply_err(req
, EINVAL
);
1187 inode
= lookup_name(req
, parent
, name
);
1189 fuse_reply_err(req
, EIO
);
1193 res
= unlinkat(lo_fd(req
, parent
), name
, AT_REMOVEDIR
);
1195 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1196 unref_inode_lolocked(lo
, inode
, 1);
1197 lo_inode_put(lo
, &inode
);
1200 static void lo_rename(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1201 fuse_ino_t newparent
, const char *newname
,
1205 struct lo_inode
*parent_inode
;
1206 struct lo_inode
*newparent_inode
;
1207 struct lo_inode
*oldinode
= NULL
;
1208 struct lo_inode
*newinode
= NULL
;
1209 struct lo_data
*lo
= lo_data(req
);
1211 if (!is_safe_path_component(name
) || !is_safe_path_component(newname
)) {
1212 fuse_reply_err(req
, EINVAL
);
1216 parent_inode
= lo_inode(req
, parent
);
1217 newparent_inode
= lo_inode(req
, newparent
);
1218 if (!parent_inode
|| !newparent_inode
) {
1219 fuse_reply_err(req
, EBADF
);
1223 oldinode
= lookup_name(req
, parent
, name
);
1224 newinode
= lookup_name(req
, newparent
, newname
);
1227 fuse_reply_err(req
, EIO
);
1232 #ifndef SYS_renameat2
1233 fuse_reply_err(req
, EINVAL
);
1235 res
= syscall(SYS_renameat2
, parent_inode
->fd
, name
,
1236 newparent_inode
->fd
, newname
, flags
);
1237 if (res
== -1 && errno
== ENOSYS
) {
1238 fuse_reply_err(req
, EINVAL
);
1240 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1246 res
= renameat(parent_inode
->fd
, name
, newparent_inode
->fd
, newname
);
1248 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1250 unref_inode_lolocked(lo
, oldinode
, 1);
1251 unref_inode_lolocked(lo
, newinode
, 1);
1252 lo_inode_put(lo
, &oldinode
);
1253 lo_inode_put(lo
, &newinode
);
1254 lo_inode_put(lo
, &parent_inode
);
1255 lo_inode_put(lo
, &newparent_inode
);
1258 static void lo_unlink(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
1261 struct lo_inode
*inode
;
1262 struct lo_data
*lo
= lo_data(req
);
1264 if (!is_safe_path_component(name
)) {
1265 fuse_reply_err(req
, EINVAL
);
1269 inode
= lookup_name(req
, parent
, name
);
1271 fuse_reply_err(req
, EIO
);
1275 res
= unlinkat(lo_fd(req
, parent
), name
, 0);
1277 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1278 unref_inode_lolocked(lo
, inode
, 1);
1279 lo_inode_put(lo
, &inode
);
1282 /* To be called with lo->mutex held */
1283 static void unref_inode(struct lo_data
*lo
, struct lo_inode
*inode
, uint64_t n
)
1289 assert(inode
->nlookup
>= n
);
1290 inode
->nlookup
-= n
;
1291 if (!inode
->nlookup
) {
1292 lo_map_remove(&lo
->ino_map
, inode
->fuse_ino
);
1293 g_hash_table_remove(lo
->inodes
, &inode
->key
);
1294 if (g_hash_table_size(inode
->posix_locks
)) {
1295 fuse_log(FUSE_LOG_WARNING
, "Hash table is not empty\n");
1297 g_hash_table_destroy(inode
->posix_locks
);
1298 pthread_mutex_destroy(&inode
->plock_mutex
);
1300 /* Drop our refcount from lo_do_lookup() */
1301 lo_inode_put(lo
, &inode
);
1305 static void unref_inode_lolocked(struct lo_data
*lo
, struct lo_inode
*inode
,
1312 pthread_mutex_lock(&lo
->mutex
);
1313 unref_inode(lo
, inode
, n
);
1314 pthread_mutex_unlock(&lo
->mutex
);
1317 static void lo_forget_one(fuse_req_t req
, fuse_ino_t ino
, uint64_t nlookup
)
1319 struct lo_data
*lo
= lo_data(req
);
1320 struct lo_inode
*inode
;
1322 inode
= lo_inode(req
, ino
);
1327 fuse_log(FUSE_LOG_DEBUG
, " forget %lli %lli -%lli\n",
1328 (unsigned long long)ino
, (unsigned long long)inode
->nlookup
,
1329 (unsigned long long)nlookup
);
1331 unref_inode_lolocked(lo
, inode
, nlookup
);
1332 lo_inode_put(lo
, &inode
);
1335 static void lo_forget(fuse_req_t req
, fuse_ino_t ino
, uint64_t nlookup
)
1337 lo_forget_one(req
, ino
, nlookup
);
1338 fuse_reply_none(req
);
1341 static void lo_forget_multi(fuse_req_t req
, size_t count
,
1342 struct fuse_forget_data
*forgets
)
1346 for (i
= 0; i
< count
; i
++) {
1347 lo_forget_one(req
, forgets
[i
].ino
, forgets
[i
].nlookup
);
1349 fuse_reply_none(req
);
1352 static void lo_readlink(fuse_req_t req
, fuse_ino_t ino
)
1354 char buf
[PATH_MAX
+ 1];
1357 res
= readlinkat(lo_fd(req
, ino
), "", buf
, sizeof(buf
));
1359 return (void)fuse_reply_err(req
, errno
);
1362 if (res
== sizeof(buf
)) {
1363 return (void)fuse_reply_err(req
, ENAMETOOLONG
);
1368 fuse_reply_readlink(req
, buf
);
1374 struct dirent
*entry
;
1378 static void lo_dirp_put(struct lo_dirp
**dp
)
1380 struct lo_dirp
*d
= *dp
;
1387 if (g_atomic_int_dec_and_test(&d
->refcount
)) {
1393 /* Call lo_dirp_put() on the return value when no longer needed */
1394 static struct lo_dirp
*lo_dirp(fuse_req_t req
, struct fuse_file_info
*fi
)
1396 struct lo_data
*lo
= lo_data(req
);
1397 struct lo_map_elem
*elem
;
1399 pthread_mutex_lock(&lo
->mutex
);
1400 elem
= lo_map_get(&lo
->dirp_map
, fi
->fh
);
1402 g_atomic_int_inc(&elem
->dirp
->refcount
);
1404 pthread_mutex_unlock(&lo
->mutex
);
1412 static void lo_opendir(fuse_req_t req
, fuse_ino_t ino
,
1413 struct fuse_file_info
*fi
)
1416 struct lo_data
*lo
= lo_data(req
);
1421 d
= calloc(1, sizeof(struct lo_dirp
));
1426 fd
= openat(lo_fd(req
, ino
), ".", O_RDONLY
);
1431 d
->dp
= fdopendir(fd
);
1432 if (d
->dp
== NULL
) {
1439 g_atomic_int_set(&d
->refcount
, 1); /* paired with lo_releasedir() */
1440 pthread_mutex_lock(&lo
->mutex
);
1441 fh
= lo_add_dirp_mapping(req
, d
);
1442 pthread_mutex_unlock(&lo
->mutex
);
1448 if (lo
->cache
== CACHE_ALWAYS
) {
1449 fi
->cache_readdir
= 1;
1451 fuse_reply_open(req
, fi
);
1460 } else if (fd
!= -1) {
1465 fuse_reply_err(req
, error
);
1468 static void lo_do_readdir(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
1469 off_t offset
, struct fuse_file_info
*fi
, int plus
)
1471 struct lo_data
*lo
= lo_data(req
);
1472 struct lo_dirp
*d
= NULL
;
1473 struct lo_inode
*dinode
;
1479 dinode
= lo_inode(req
, ino
);
1484 d
= lo_dirp(req
, fi
);
1490 buf
= calloc(1, size
);
1496 if (offset
!= d
->offset
) {
1497 seekdir(d
->dp
, offset
);
1508 d
->entry
= readdir(d
->dp
);
1510 if (errno
) { /* Error */
1513 } else { /* End of stream */
1518 nextoff
= d
->entry
->d_off
;
1519 name
= d
->entry
->d_name
;
1521 fuse_ino_t entry_ino
= 0;
1522 struct fuse_entry_param e
= (struct fuse_entry_param
){
1523 .attr
.st_ino
= d
->entry
->d_ino
,
1524 .attr
.st_mode
= d
->entry
->d_type
<< 12,
1527 /* Hide root's parent directory */
1528 if (dinode
== &lo
->root
&& strcmp(name
, "..") == 0) {
1529 e
.attr
.st_ino
= lo
->root
.key
.ino
;
1530 e
.attr
.st_mode
= DT_DIR
<< 12;
1534 if (!is_dot_or_dotdot(name
)) {
1535 err
= lo_do_lookup(req
, ino
, name
, &e
);
1542 entsize
= fuse_add_direntry_plus(req
, p
, rem
, name
, &e
, nextoff
);
1544 entsize
= fuse_add_direntry(req
, p
, rem
, name
, &e
.attr
, nextoff
);
1546 if (entsize
> rem
) {
1547 if (entry_ino
!= 0) {
1548 lo_forget_one(req
, entry_ino
, 1);
1557 d
->offset
= nextoff
;
1563 lo_inode_put(lo
, &dinode
);
1566 * If there's an error, we can only signal it if we haven't stored
1567 * any entries yet - otherwise we'd end up with wrong lookup
1568 * counts for the entries that are already in the buffer. So we
1569 * return what we've collected until that point.
1571 if (err
&& rem
== size
) {
1572 fuse_reply_err(req
, err
);
1574 fuse_reply_buf(req
, buf
, size
- rem
);
1579 static void lo_readdir(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
1580 off_t offset
, struct fuse_file_info
*fi
)
1582 lo_do_readdir(req
, ino
, size
, offset
, fi
, 0);
1585 static void lo_readdirplus(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
1586 off_t offset
, struct fuse_file_info
*fi
)
1588 lo_do_readdir(req
, ino
, size
, offset
, fi
, 1);
1591 static void lo_releasedir(fuse_req_t req
, fuse_ino_t ino
,
1592 struct fuse_file_info
*fi
)
1594 struct lo_data
*lo
= lo_data(req
);
1595 struct lo_map_elem
*elem
;
1600 pthread_mutex_lock(&lo
->mutex
);
1601 elem
= lo_map_get(&lo
->dirp_map
, fi
->fh
);
1603 pthread_mutex_unlock(&lo
->mutex
);
1604 fuse_reply_err(req
, EBADF
);
1609 lo_map_remove(&lo
->dirp_map
, fi
->fh
);
1610 pthread_mutex_unlock(&lo
->mutex
);
1612 lo_dirp_put(&d
); /* paired with lo_opendir() */
1614 fuse_reply_err(req
, 0);
1617 static void update_open_flags(int writeback
, int allow_direct_io
,
1618 struct fuse_file_info
*fi
)
1621 * With writeback cache, kernel may send read requests even
1622 * when userspace opened write-only
1624 if (writeback
&& (fi
->flags
& O_ACCMODE
) == O_WRONLY
) {
1625 fi
->flags
&= ~O_ACCMODE
;
1626 fi
->flags
|= O_RDWR
;
1630 * With writeback cache, O_APPEND is handled by the kernel.
1631 * This breaks atomicity (since the file may change in the
1632 * underlying filesystem, so that the kernel's idea of the
1633 * end of the file isn't accurate anymore). In this example,
1634 * we just accept that. A more rigorous filesystem may want
1635 * to return an error here
1637 if (writeback
&& (fi
->flags
& O_APPEND
)) {
1638 fi
->flags
&= ~O_APPEND
;
1642 * O_DIRECT in guest should not necessarily mean bypassing page
1643 * cache on host as well. Therefore, we discard it by default
1644 * ('-o no_allow_direct_io'). If somebody needs that behavior,
1645 * the '-o allow_direct_io' option should be set.
1647 if (!allow_direct_io
) {
1648 fi
->flags
&= ~O_DIRECT
;
1652 static void lo_create(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1653 mode_t mode
, struct fuse_file_info
*fi
)
1656 struct lo_data
*lo
= lo_data(req
);
1657 struct lo_inode
*parent_inode
;
1658 struct fuse_entry_param e
;
1660 struct lo_cred old
= {};
1662 fuse_log(FUSE_LOG_DEBUG
, "lo_create(parent=%" PRIu64
", name=%s)\n", parent
,
1665 if (!is_safe_path_component(name
)) {
1666 fuse_reply_err(req
, EINVAL
);
1670 parent_inode
= lo_inode(req
, parent
);
1671 if (!parent_inode
) {
1672 fuse_reply_err(req
, EBADF
);
1676 err
= lo_change_cred(req
, &old
);
1681 update_open_flags(lo
->writeback
, lo
->allow_direct_io
, fi
);
1683 fd
= openat(parent_inode
->fd
, name
, (fi
->flags
| O_CREAT
) & ~O_NOFOLLOW
,
1685 err
= fd
== -1 ? errno
: 0;
1686 lo_restore_cred(&old
);
1691 pthread_mutex_lock(&lo
->mutex
);
1692 fh
= lo_add_fd_mapping(req
, fd
);
1693 pthread_mutex_unlock(&lo
->mutex
);
1701 err
= lo_do_lookup(req
, parent
, name
, &e
);
1703 if (lo
->cache
== CACHE_NONE
) {
1705 } else if (lo
->cache
== CACHE_ALWAYS
) {
1710 lo_inode_put(lo
, &parent_inode
);
1713 fuse_reply_err(req
, err
);
1715 fuse_reply_create(req
, &e
, fi
);
1719 /* Should be called with inode->plock_mutex held */
1720 static struct lo_inode_plock
*lookup_create_plock_ctx(struct lo_data
*lo
,
1721 struct lo_inode
*inode
,
1722 uint64_t lock_owner
,
1723 pid_t pid
, int *err
)
1725 struct lo_inode_plock
*plock
;
1730 g_hash_table_lookup(inode
->posix_locks
, GUINT_TO_POINTER(lock_owner
));
1736 plock
= malloc(sizeof(struct lo_inode_plock
));
1742 /* Open another instance of file which can be used for ofd locks. */
1743 sprintf(procname
, "%i", inode
->fd
);
1745 /* TODO: What if file is not writable? */
1746 fd
= openat(lo
->proc_self_fd
, procname
, O_RDWR
);
1753 plock
->lock_owner
= lock_owner
;
1755 g_hash_table_insert(inode
->posix_locks
, GUINT_TO_POINTER(plock
->lock_owner
),
1760 static void lo_getlk(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
1763 struct lo_data
*lo
= lo_data(req
);
1764 struct lo_inode
*inode
;
1765 struct lo_inode_plock
*plock
;
1766 int ret
, saverr
= 0;
1768 fuse_log(FUSE_LOG_DEBUG
,
1769 "lo_getlk(ino=%" PRIu64
", flags=%d)"
1770 " owner=0x%lx, l_type=%d l_start=0x%lx"
1772 ino
, fi
->flags
, fi
->lock_owner
, lock
->l_type
, lock
->l_start
,
1775 inode
= lo_inode(req
, ino
);
1777 fuse_reply_err(req
, EBADF
);
1781 pthread_mutex_lock(&inode
->plock_mutex
);
1783 lookup_create_plock_ctx(lo
, inode
, fi
->lock_owner
, lock
->l_pid
, &ret
);
1789 ret
= fcntl(plock
->fd
, F_OFD_GETLK
, lock
);
1795 pthread_mutex_unlock(&inode
->plock_mutex
);
1796 lo_inode_put(lo
, &inode
);
1799 fuse_reply_err(req
, saverr
);
1801 fuse_reply_lock(req
, lock
);
1805 static void lo_setlk(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
1806 struct flock
*lock
, int sleep
)
1808 struct lo_data
*lo
= lo_data(req
);
1809 struct lo_inode
*inode
;
1810 struct lo_inode_plock
*plock
;
1811 int ret
, saverr
= 0;
1813 fuse_log(FUSE_LOG_DEBUG
,
1814 "lo_setlk(ino=%" PRIu64
", flags=%d)"
1815 " cmd=%d pid=%d owner=0x%lx sleep=%d l_whence=%d"
1816 " l_start=0x%lx l_len=0x%lx\n",
1817 ino
, fi
->flags
, lock
->l_type
, lock
->l_pid
, fi
->lock_owner
, sleep
,
1818 lock
->l_whence
, lock
->l_start
, lock
->l_len
);
1821 fuse_reply_err(req
, EOPNOTSUPP
);
1825 inode
= lo_inode(req
, ino
);
1827 fuse_reply_err(req
, EBADF
);
1831 pthread_mutex_lock(&inode
->plock_mutex
);
1833 lookup_create_plock_ctx(lo
, inode
, fi
->lock_owner
, lock
->l_pid
, &ret
);
1840 /* TODO: Is it alright to modify flock? */
1842 ret
= fcntl(plock
->fd
, F_OFD_SETLK
, lock
);
1848 pthread_mutex_unlock(&inode
->plock_mutex
);
1849 lo_inode_put(lo
, &inode
);
1851 fuse_reply_err(req
, saverr
);
1854 static void lo_fsyncdir(fuse_req_t req
, fuse_ino_t ino
, int datasync
,
1855 struct fuse_file_info
*fi
)
1863 d
= lo_dirp(req
, fi
);
1865 fuse_reply_err(req
, EBADF
);
1871 res
= fdatasync(fd
);
1878 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1881 static void lo_open(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
)
1886 struct lo_data
*lo
= lo_data(req
);
1888 fuse_log(FUSE_LOG_DEBUG
, "lo_open(ino=%" PRIu64
", flags=%d)\n", ino
,
1891 update_open_flags(lo
->writeback
, lo
->allow_direct_io
, fi
);
1893 sprintf(buf
, "%i", lo_fd(req
, ino
));
1894 fd
= openat(lo
->proc_self_fd
, buf
, fi
->flags
& ~O_NOFOLLOW
);
1896 return (void)fuse_reply_err(req
, errno
);
1899 pthread_mutex_lock(&lo
->mutex
);
1900 fh
= lo_add_fd_mapping(req
, fd
);
1901 pthread_mutex_unlock(&lo
->mutex
);
1904 fuse_reply_err(req
, ENOMEM
);
1909 if (lo
->cache
== CACHE_NONE
) {
1911 } else if (lo
->cache
== CACHE_ALWAYS
) {
1914 fuse_reply_open(req
, fi
);
1917 static void lo_release(fuse_req_t req
, fuse_ino_t ino
,
1918 struct fuse_file_info
*fi
)
1920 struct lo_data
*lo
= lo_data(req
);
1921 struct lo_map_elem
*elem
;
1926 pthread_mutex_lock(&lo
->mutex
);
1927 elem
= lo_map_get(&lo
->fd_map
, fi
->fh
);
1931 lo_map_remove(&lo
->fd_map
, fi
->fh
);
1933 pthread_mutex_unlock(&lo
->mutex
);
1936 fuse_reply_err(req
, 0);
1939 static void lo_flush(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
)
1943 struct lo_inode
*inode
;
1945 inode
= lo_inode(req
, ino
);
1947 fuse_reply_err(req
, EBADF
);
1951 /* An fd is going away. Cleanup associated posix locks */
1952 pthread_mutex_lock(&inode
->plock_mutex
);
1953 g_hash_table_remove(inode
->posix_locks
, GUINT_TO_POINTER(fi
->lock_owner
));
1954 pthread_mutex_unlock(&inode
->plock_mutex
);
1956 res
= close(dup(lo_fi_fd(req
, fi
)));
1957 lo_inode_put(lo_data(req
), &inode
);
1958 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1961 static void lo_fsync(fuse_req_t req
, fuse_ino_t ino
, int datasync
,
1962 struct fuse_file_info
*fi
)
1968 fuse_log(FUSE_LOG_DEBUG
, "lo_fsync(ino=%" PRIu64
", fi=0x%p)\n", ino
,
1972 struct lo_data
*lo
= lo_data(req
);
1974 res
= asprintf(&buf
, "%i", lo_fd(req
, ino
));
1976 return (void)fuse_reply_err(req
, errno
);
1979 fd
= openat(lo
->proc_self_fd
, buf
, O_RDWR
);
1982 return (void)fuse_reply_err(req
, errno
);
1985 fd
= lo_fi_fd(req
, fi
);
1989 res
= fdatasync(fd
);
1996 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1999 static void lo_read(fuse_req_t req
, fuse_ino_t ino
, size_t size
, off_t offset
,
2000 struct fuse_file_info
*fi
)
2002 struct fuse_bufvec buf
= FUSE_BUFVEC_INIT(size
);
2004 fuse_log(FUSE_LOG_DEBUG
,
2005 "lo_read(ino=%" PRIu64
", size=%zd, "
2007 ino
, size
, (unsigned long)offset
);
2009 buf
.buf
[0].flags
= FUSE_BUF_IS_FD
| FUSE_BUF_FD_SEEK
;
2010 buf
.buf
[0].fd
= lo_fi_fd(req
, fi
);
2011 buf
.buf
[0].pos
= offset
;
2013 fuse_reply_data(req
, &buf
);
2016 static void lo_write_buf(fuse_req_t req
, fuse_ino_t ino
,
2017 struct fuse_bufvec
*in_buf
, off_t off
,
2018 struct fuse_file_info
*fi
)
2022 struct fuse_bufvec out_buf
= FUSE_BUFVEC_INIT(fuse_buf_size(in_buf
));
2023 bool cap_fsetid_dropped
= false;
2025 out_buf
.buf
[0].flags
= FUSE_BUF_IS_FD
| FUSE_BUF_FD_SEEK
;
2026 out_buf
.buf
[0].fd
= lo_fi_fd(req
, fi
);
2027 out_buf
.buf
[0].pos
= off
;
2029 fuse_log(FUSE_LOG_DEBUG
,
2030 "lo_write_buf(ino=%" PRIu64
", size=%zd, off=%lu)\n", ino
,
2031 out_buf
.buf
[0].size
, (unsigned long)off
);
2034 * If kill_priv is set, drop CAP_FSETID which should lead to kernel
2035 * clearing setuid/setgid on file.
2037 if (fi
->kill_priv
) {
2038 res
= drop_effective_cap("FSETID", &cap_fsetid_dropped
);
2040 fuse_reply_err(req
, res
);
2045 res
= fuse_buf_copy(&out_buf
, in_buf
);
2047 fuse_reply_err(req
, -res
);
2049 fuse_reply_write(req
, (size_t)res
);
2052 if (cap_fsetid_dropped
) {
2053 res
= gain_effective_cap("FSETID");
2055 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_FSETID\n");
2060 static void lo_statfs(fuse_req_t req
, fuse_ino_t ino
)
2063 struct statvfs stbuf
;
2065 res
= fstatvfs(lo_fd(req
, ino
), &stbuf
);
2067 fuse_reply_err(req
, errno
);
2069 fuse_reply_statfs(req
, &stbuf
);
2073 static void lo_fallocate(fuse_req_t req
, fuse_ino_t ino
, int mode
, off_t offset
,
2074 off_t length
, struct fuse_file_info
*fi
)
2076 int err
= EOPNOTSUPP
;
2079 #ifdef CONFIG_FALLOCATE
2080 err
= fallocate(lo_fi_fd(req
, fi
), mode
, offset
, length
);
2085 #elif defined(CONFIG_POSIX_FALLOCATE)
2087 fuse_reply_err(req
, EOPNOTSUPP
);
2091 err
= posix_fallocate(lo_fi_fd(req
, fi
), offset
, length
);
2094 fuse_reply_err(req
, err
);
2097 static void lo_flock(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
2103 res
= flock(lo_fi_fd(req
, fi
), op
);
2105 fuse_reply_err(req
, res
== -1 ? errno
: 0);
2110 * Exit; process attribute unmodified if matched.
2111 * An empty key applies to all.
2113 #define XATTR_MAP_FLAG_OK (1 << 0)
2115 * The attribute is unwanted;
2116 * EPERM on write, hidden on read.
2118 #define XATTR_MAP_FLAG_BAD (1 << 1)
2120 * For attr that start with 'key' prepend 'prepend'
2121 * 'key' may be empty to prepend for all attrs
2122 * key is defined from set/remove point of view.
2123 * Automatically reversed on read
2125 #define XATTR_MAP_FLAG_PREFIX (1 << 2)
2128 /* Apply rule to get/set/remove */
2129 #define XATTR_MAP_FLAG_CLIENT (1 << 16)
2130 /* Apply rule to list */
2131 #define XATTR_MAP_FLAG_SERVER (1 << 17)
2132 /* Apply rule to all */
2133 #define XATTR_MAP_FLAG_ALL (XATTR_MAP_FLAG_SERVER | XATTR_MAP_FLAG_CLIENT)
2135 static void add_xattrmap_entry(struct lo_data
*lo
,
2136 const XattrMapEntry
*new_entry
)
2138 XattrMapEntry
*res
= g_realloc_n(lo
->xattr_map_list
,
2139 lo
->xattr_map_nentries
+ 1,
2140 sizeof(XattrMapEntry
));
2141 res
[lo
->xattr_map_nentries
++] = *new_entry
;
2143 lo
->xattr_map_list
= res
;
2146 static void free_xattrmap(struct lo_data
*lo
)
2148 XattrMapEntry
*map
= lo
->xattr_map_list
;
2155 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
2157 g_free(map
[i
].prepend
);
2161 lo
->xattr_map_list
= NULL
;
2162 lo
->xattr_map_nentries
= -1;
2166 * Handle the 'map' type, which is sugar for a set of commands
2167 * for the common case of prefixing a subset or everything,
2168 * and allowing anything not prefixed through.
2169 * It must be the last entry in the stream, although there
2170 * can be other entries before it.
2174 * key maybe empty in which case all entries are prefixed.
2176 static void parse_xattrmap_map(struct lo_data
*lo
,
2177 const char *rule
, char sep
)
2182 XattrMapEntry tmp_entry
;
2185 fuse_log(FUSE_LOG_ERR
,
2186 "%s: Expecting '%c' after 'map' keyword, found '%c'\n",
2187 __func__
, sep
, *rule
);
2193 /* At start of 'key' field */
2194 tmp
= strchr(rule
, sep
);
2196 fuse_log(FUSE_LOG_ERR
,
2197 "%s: Missing '%c' at end of key field in map rule\n",
2202 key
= g_strndup(rule
, tmp
- rule
);
2205 /* At start of prefix field */
2206 tmp
= strchr(rule
, sep
);
2208 fuse_log(FUSE_LOG_ERR
,
2209 "%s: Missing '%c' at end of prefix field in map rule\n",
2214 prefix
= g_strndup(rule
, tmp
- rule
);
2218 * This should be the end of the string, we don't allow
2219 * any more commands after 'map'.
2222 fuse_log(FUSE_LOG_ERR
,
2223 "%s: Expecting end of command after map, found '%c'\n",
2228 /* 1st: Prefix matches/everything */
2229 tmp_entry
.flags
= XATTR_MAP_FLAG_PREFIX
| XATTR_MAP_FLAG_ALL
;
2230 tmp_entry
.key
= g_strdup(key
);
2231 tmp_entry
.prepend
= g_strdup(prefix
);
2232 add_xattrmap_entry(lo
, &tmp_entry
);
2235 /* Prefix all case */
2237 /* 2nd: Hide any non-prefixed entries on the host */
2238 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_ALL
;
2239 tmp_entry
.key
= g_strdup("");
2240 tmp_entry
.prepend
= g_strdup("");
2241 add_xattrmap_entry(lo
, &tmp_entry
);
2243 /* Prefix matching case */
2245 /* 2nd: Hide non-prefixed but matching entries on the host */
2246 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_SERVER
;
2247 tmp_entry
.key
= g_strdup(""); /* Not used */
2248 tmp_entry
.prepend
= g_strdup(key
);
2249 add_xattrmap_entry(lo
, &tmp_entry
);
2251 /* 3rd: Stop the client accessing prefixed attributes directly */
2252 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_CLIENT
;
2253 tmp_entry
.key
= g_strdup(prefix
);
2254 tmp_entry
.prepend
= g_strdup(""); /* Not used */
2255 add_xattrmap_entry(lo
, &tmp_entry
);
2257 /* 4th: Everything else is OK */
2258 tmp_entry
.flags
= XATTR_MAP_FLAG_OK
| XATTR_MAP_FLAG_ALL
;
2259 tmp_entry
.key
= g_strdup("");
2260 tmp_entry
.prepend
= g_strdup("");
2261 add_xattrmap_entry(lo
, &tmp_entry
);
2268 static void parse_xattrmap(struct lo_data
*lo
)
2270 const char *map
= lo
->xattrmap
;
2273 lo
->xattr_map_nentries
= 0;
2275 XattrMapEntry tmp_entry
;
2278 if (isspace(*map
)) {
2282 /* The separator is the first non-space of the rule */
2288 tmp_entry
.flags
= 0;
2289 /* Start of 'type' */
2290 if (strstart(map
, "prefix", &map
)) {
2291 tmp_entry
.flags
|= XATTR_MAP_FLAG_PREFIX
;
2292 } else if (strstart(map
, "ok", &map
)) {
2293 tmp_entry
.flags
|= XATTR_MAP_FLAG_OK
;
2294 } else if (strstart(map
, "bad", &map
)) {
2295 tmp_entry
.flags
|= XATTR_MAP_FLAG_BAD
;
2296 } else if (strstart(map
, "map", &map
)) {
2298 * map is sugar that adds a number of rules, and must be
2301 parse_xattrmap_map(lo
, map
, sep
);
2304 fuse_log(FUSE_LOG_ERR
,
2305 "%s: Unexpected type;"
2306 "Expecting 'prefix', 'ok', 'bad' or 'map' in rule %zu\n",
2307 __func__
, lo
->xattr_map_nentries
);
2311 if (*map
++ != sep
) {
2312 fuse_log(FUSE_LOG_ERR
,
2313 "%s: Missing '%c' at end of type field of rule %zu\n",
2314 __func__
, sep
, lo
->xattr_map_nentries
);
2318 /* Start of 'scope' */
2319 if (strstart(map
, "client", &map
)) {
2320 tmp_entry
.flags
|= XATTR_MAP_FLAG_CLIENT
;
2321 } else if (strstart(map
, "server", &map
)) {
2322 tmp_entry
.flags
|= XATTR_MAP_FLAG_SERVER
;
2323 } else if (strstart(map
, "all", &map
)) {
2324 tmp_entry
.flags
|= XATTR_MAP_FLAG_ALL
;
2326 fuse_log(FUSE_LOG_ERR
,
2327 "%s: Unexpected scope;"
2328 " Expecting 'client', 'server', or 'all', in rule %zu\n",
2329 __func__
, lo
->xattr_map_nentries
);
2333 if (*map
++ != sep
) {
2334 fuse_log(FUSE_LOG_ERR
,
2335 "%s: Expecting '%c' found '%c'"
2336 " after scope in rule %zu\n",
2337 __func__
, sep
, *map
, lo
->xattr_map_nentries
);
2341 /* At start of 'key' field */
2342 tmp
= strchr(map
, sep
);
2344 fuse_log(FUSE_LOG_ERR
,
2345 "%s: Missing '%c' at end of key field of rule %zu",
2346 __func__
, sep
, lo
->xattr_map_nentries
);
2349 tmp_entry
.key
= g_strndup(map
, tmp
- map
);
2352 /* At start of 'prepend' field */
2353 tmp
= strchr(map
, sep
);
2355 fuse_log(FUSE_LOG_ERR
,
2356 "%s: Missing '%c' at end of prepend field of rule %zu",
2357 __func__
, sep
, lo
->xattr_map_nentries
);
2360 tmp_entry
.prepend
= g_strndup(map
, tmp
- map
);
2363 add_xattrmap_entry(lo
, &tmp_entry
);
2364 /* End of rule - go around again for another rule */
2367 if (!lo
->xattr_map_nentries
) {
2368 fuse_log(FUSE_LOG_ERR
, "Empty xattr map\n");
2374 * For use with getxattr/setxattr/removexattr, where the client
2375 * gives us a name and we may need to choose a different one.
2376 * Allocates a buffer for the result placing it in *out_name.
2377 * If there's no change then *out_name is not set.
2378 * Returns 0 on success
2379 * Can return -EPERM to indicate we block a given attribute
2380 * (in which case out_name is not allocated)
2381 * Can return -ENOMEM to indicate out_name couldn't be allocated.
2383 static int xattr_map_client(const struct lo_data
*lo
, const char *client_name
,
2387 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
2388 const XattrMapEntry
*cur_entry
= lo
->xattr_map_list
+ i
;
2390 if ((cur_entry
->flags
& XATTR_MAP_FLAG_CLIENT
) &&
2391 (strstart(client_name
, cur_entry
->key
, NULL
))) {
2392 if (cur_entry
->flags
& XATTR_MAP_FLAG_BAD
) {
2395 if (cur_entry
->flags
& XATTR_MAP_FLAG_OK
) {
2396 /* Unmodified name */
2399 if (cur_entry
->flags
& XATTR_MAP_FLAG_PREFIX
) {
2400 *out_name
= g_try_malloc(strlen(client_name
) +
2401 strlen(cur_entry
->prepend
) + 1);
2405 sprintf(*out_name
, "%s%s", cur_entry
->prepend
, client_name
);
2415 * For use with listxattr where the server fs gives us a name and we may need
2416 * to sanitize this for the client.
2417 * Returns a pointer to the result in *out_name
2418 * This is always the original string or the current string with some prefix
2419 * removed; no reallocation is done.
2420 * Returns 0 on success
2421 * Can return -ENODATA to indicate the name should be dropped from the list.
2423 static int xattr_map_server(const struct lo_data
*lo
, const char *server_name
,
2424 const char **out_name
)
2429 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
2430 const XattrMapEntry
*cur_entry
= lo
->xattr_map_list
+ i
;
2432 if ((cur_entry
->flags
& XATTR_MAP_FLAG_SERVER
) &&
2433 (strstart(server_name
, cur_entry
->prepend
, &end
))) {
2434 if (cur_entry
->flags
& XATTR_MAP_FLAG_BAD
) {
2437 if (cur_entry
->flags
& XATTR_MAP_FLAG_OK
) {
2438 *out_name
= server_name
;
2441 if (cur_entry
->flags
& XATTR_MAP_FLAG_PREFIX
) {
2452 static void lo_getxattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
,
2455 struct lo_data
*lo
= lo_data(req
);
2460 struct lo_inode
*inode
;
2468 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
2470 if (ret
== -EPERM
) {
2473 fuse_reply_err(req
, -ret
);
2481 inode
= lo_inode(req
, ino
);
2483 fuse_reply_err(req
, EBADF
);
2484 g_free(mapped_name
);
2489 if (!lo_data(req
)->xattr
) {
2493 fuse_log(FUSE_LOG_DEBUG
, "lo_getxattr(ino=%" PRIu64
", name=%s size=%zd)\n",
2497 value
= malloc(size
);
2503 sprintf(procname
, "%i", inode
->fd
);
2505 * It is not safe to open() non-regular/non-dir files in file server
2506 * unless O_PATH is used, so use that method for regular files/dir
2507 * only (as it seems giving less performance overhead).
2508 * Otherwise, call fchdir() to avoid open().
2510 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
2511 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
2515 ret
= fgetxattr(fd
, name
, value
, size
);
2517 /* fchdir should not fail here */
2518 assert(fchdir(lo
->proc_self_fd
) == 0);
2519 ret
= getxattr(procname
, name
, value
, size
);
2520 assert(fchdir(lo
->root
.fd
) == 0);
2531 fuse_reply_buf(req
, value
, ret
);
2533 fuse_reply_xattr(req
, ret
);
2542 lo_inode_put(lo
, &inode
);
2548 fuse_reply_err(req
, saverr
);
2549 g_free(mapped_name
);
2553 static void lo_listxattr(fuse_req_t req
, fuse_ino_t ino
, size_t size
)
2555 struct lo_data
*lo
= lo_data(req
);
2558 struct lo_inode
*inode
;
2563 inode
= lo_inode(req
, ino
);
2565 fuse_reply_err(req
, EBADF
);
2570 if (!lo_data(req
)->xattr
) {
2574 fuse_log(FUSE_LOG_DEBUG
, "lo_listxattr(ino=%" PRIu64
", size=%zd)\n", ino
,
2578 value
= malloc(size
);
2584 sprintf(procname
, "%i", inode
->fd
);
2585 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
2586 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
2590 ret
= flistxattr(fd
, value
, size
);
2592 /* fchdir should not fail here */
2593 assert(fchdir(lo
->proc_self_fd
) == 0);
2594 ret
= listxattr(procname
, value
, size
);
2595 assert(fchdir(lo
->root
.fd
) == 0);
2607 if (lo
->xattr_map_list
) {
2609 * Map the names back, some attributes might be dropped,
2610 * some shortened, but not increased, so we shouldn't
2613 size_t out_index
, in_index
;
2616 while (in_index
< ret
) {
2617 const char *map_out
;
2618 char *in_ptr
= value
+ in_index
;
2619 /* Length of current attribute name */
2620 size_t in_len
= strlen(value
+ in_index
) + 1;
2622 int mapret
= xattr_map_server(lo
, in_ptr
, &map_out
);
2623 if (mapret
!= -ENODATA
&& mapret
!= 0) {
2624 /* Shouldn't happen */
2629 /* Either unchanged, or truncated */
2631 if (map_out
!= in_ptr
) {
2632 /* +1 copies the NIL */
2633 out_len
= strlen(map_out
) + 1;
2639 * Move result along, may still be needed for an unchanged
2640 * entry if a previous entry was changed.
2642 memmove(value
+ out_index
, map_out
, out_len
);
2644 out_index
+= out_len
;
2653 fuse_reply_buf(req
, value
, ret
);
2656 * xattrmap only ever shortens the result,
2657 * so we don't need to do anything clever with the
2658 * allocation length here.
2660 fuse_reply_xattr(req
, ret
);
2669 lo_inode_put(lo
, &inode
);
2675 fuse_reply_err(req
, saverr
);
2679 static void lo_setxattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
,
2680 const char *value
, size_t size
, int flags
)
2685 struct lo_data
*lo
= lo_data(req
);
2686 struct lo_inode
*inode
;
2694 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
2696 fuse_reply_err(req
, -ret
);
2704 inode
= lo_inode(req
, ino
);
2706 fuse_reply_err(req
, EBADF
);
2707 g_free(mapped_name
);
2712 if (!lo_data(req
)->xattr
) {
2716 fuse_log(FUSE_LOG_DEBUG
, "lo_setxattr(ino=%" PRIu64
2717 ", name=%s value=%s size=%zd)\n", ino
, name
, value
, size
);
2719 sprintf(procname
, "%i", inode
->fd
);
2720 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
2721 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
2726 ret
= fsetxattr(fd
, name
, value
, size
, flags
);
2728 /* fchdir should not fail here */
2729 assert(fchdir(lo
->proc_self_fd
) == 0);
2730 ret
= setxattr(procname
, name
, value
, size
, flags
);
2731 assert(fchdir(lo
->root
.fd
) == 0);
2734 saverr
= ret
== -1 ? errno
: 0;
2741 lo_inode_put(lo
, &inode
);
2742 g_free(mapped_name
);
2743 fuse_reply_err(req
, saverr
);
2746 static void lo_removexattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
)
2751 struct lo_data
*lo
= lo_data(req
);
2752 struct lo_inode
*inode
;
2760 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
2762 fuse_reply_err(req
, -ret
);
2770 inode
= lo_inode(req
, ino
);
2772 fuse_reply_err(req
, EBADF
);
2773 g_free(mapped_name
);
2778 if (!lo_data(req
)->xattr
) {
2782 fuse_log(FUSE_LOG_DEBUG
, "lo_removexattr(ino=%" PRIu64
", name=%s)\n", ino
,
2785 sprintf(procname
, "%i", inode
->fd
);
2786 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
2787 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
2792 ret
= fremovexattr(fd
, name
);
2794 /* fchdir should not fail here */
2795 assert(fchdir(lo
->proc_self_fd
) == 0);
2796 ret
= removexattr(procname
, name
);
2797 assert(fchdir(lo
->root
.fd
) == 0);
2800 saverr
= ret
== -1 ? errno
: 0;
2807 lo_inode_put(lo
, &inode
);
2808 g_free(mapped_name
);
2809 fuse_reply_err(req
, saverr
);
2812 #ifdef HAVE_COPY_FILE_RANGE
2813 static void lo_copy_file_range(fuse_req_t req
, fuse_ino_t ino_in
, off_t off_in
,
2814 struct fuse_file_info
*fi_in
, fuse_ino_t ino_out
,
2815 off_t off_out
, struct fuse_file_info
*fi_out
,
2816 size_t len
, int flags
)
2821 in_fd
= lo_fi_fd(req
, fi_in
);
2822 out_fd
= lo_fi_fd(req
, fi_out
);
2824 fuse_log(FUSE_LOG_DEBUG
,
2825 "lo_copy_file_range(ino=%" PRIu64
"/fd=%d, "
2826 "off=%lu, ino=%" PRIu64
"/fd=%d, "
2827 "off=%lu, size=%zd, flags=0x%x)\n",
2828 ino_in
, in_fd
, off_in
, ino_out
, out_fd
, off_out
, len
, flags
);
2830 res
= copy_file_range(in_fd
, &off_in
, out_fd
, &off_out
, len
, flags
);
2832 fuse_reply_err(req
, errno
);
2834 fuse_reply_write(req
, res
);
2839 static void lo_lseek(fuse_req_t req
, fuse_ino_t ino
, off_t off
, int whence
,
2840 struct fuse_file_info
*fi
)
2845 res
= lseek(lo_fi_fd(req
, fi
), off
, whence
);
2847 fuse_reply_lseek(req
, res
);
2849 fuse_reply_err(req
, errno
);
2853 static void lo_destroy(void *userdata
)
2855 struct lo_data
*lo
= (struct lo_data
*)userdata
;
2857 pthread_mutex_lock(&lo
->mutex
);
2859 GHashTableIter iter
;
2860 gpointer key
, value
;
2862 g_hash_table_iter_init(&iter
, lo
->inodes
);
2863 if (!g_hash_table_iter_next(&iter
, &key
, &value
)) {
2867 struct lo_inode
*inode
= value
;
2868 unref_inode(lo
, inode
, inode
->nlookup
);
2870 pthread_mutex_unlock(&lo
->mutex
);
2873 static struct fuse_lowlevel_ops lo_oper
= {
2875 .lookup
= lo_lookup
,
2878 .symlink
= lo_symlink
,
2880 .unlink
= lo_unlink
,
2882 .rename
= lo_rename
,
2883 .forget
= lo_forget
,
2884 .forget_multi
= lo_forget_multi
,
2885 .getattr
= lo_getattr
,
2886 .setattr
= lo_setattr
,
2887 .readlink
= lo_readlink
,
2888 .opendir
= lo_opendir
,
2889 .readdir
= lo_readdir
,
2890 .readdirplus
= lo_readdirplus
,
2891 .releasedir
= lo_releasedir
,
2892 .fsyncdir
= lo_fsyncdir
,
2893 .create
= lo_create
,
2897 .release
= lo_release
,
2901 .write_buf
= lo_write_buf
,
2902 .statfs
= lo_statfs
,
2903 .fallocate
= lo_fallocate
,
2905 .getxattr
= lo_getxattr
,
2906 .listxattr
= lo_listxattr
,
2907 .setxattr
= lo_setxattr
,
2908 .removexattr
= lo_removexattr
,
2909 #ifdef HAVE_COPY_FILE_RANGE
2910 .copy_file_range
= lo_copy_file_range
,
2913 .destroy
= lo_destroy
,
2916 /* Print vhost-user.json backend program capabilities */
2917 static void print_capabilities(void)
2920 printf(" \"type\": \"fs\"\n");
2925 * Drop all Linux capabilities because the wait parent process only needs to
2926 * sit in waitpid(2) and terminate.
2928 static void setup_wait_parent_capabilities(void)
2930 capng_setpid(syscall(SYS_gettid
));
2931 capng_clear(CAPNG_SELECT_BOTH
);
2932 capng_apply(CAPNG_SELECT_BOTH
);
2936 * Move to a new mount, net, and pid namespaces to isolate this process.
2938 static void setup_namespaces(struct lo_data
*lo
, struct fuse_session
*se
)
2943 * Create a new pid namespace for *child* processes. We'll have to
2944 * fork in order to enter the new pid namespace. A new mount namespace
2945 * is also needed so that we can remount /proc for the new pid
2948 * Our UNIX domain sockets have been created. Now we can move to
2949 * an empty network namespace to prevent TCP/IP and other network
2950 * activity in case this process is compromised.
2952 if (unshare(CLONE_NEWPID
| CLONE_NEWNS
| CLONE_NEWNET
) != 0) {
2953 fuse_log(FUSE_LOG_ERR
, "unshare(CLONE_NEWPID | CLONE_NEWNS): %m\n");
2959 fuse_log(FUSE_LOG_ERR
, "fork() failed: %m\n");
2966 setup_wait_parent_capabilities();
2968 /* The parent waits for the child */
2970 waited
= waitpid(child
, &wstatus
, 0);
2971 } while (waited
< 0 && errno
== EINTR
&& !se
->exited
);
2973 /* We were terminated by a signal, see fuse_signals.c */
2978 if (WIFEXITED(wstatus
)) {
2979 exit(WEXITSTATUS(wstatus
));
2985 /* Send us SIGTERM when the parent thread terminates, see prctl(2) */
2986 prctl(PR_SET_PDEATHSIG
, SIGTERM
);
2989 * If the mounts have shared propagation then we want to opt out so our
2990 * mount changes don't affect the parent mount namespace.
2992 if (mount(NULL
, "/", NULL
, MS_REC
| MS_SLAVE
, NULL
) < 0) {
2993 fuse_log(FUSE_LOG_ERR
, "mount(/, MS_REC|MS_SLAVE): %m\n");
2997 /* The child must remount /proc to use the new pid namespace */
2998 if (mount("proc", "/proc", "proc",
2999 MS_NODEV
| MS_NOEXEC
| MS_NOSUID
| MS_RELATIME
, NULL
) < 0) {
3000 fuse_log(FUSE_LOG_ERR
, "mount(/proc): %m\n");
3005 * We only need /proc/self/fd. Prevent ".." from accessing parent
3006 * directories of /proc/self/fd by bind-mounting it over /proc. Since / was
3007 * previously remounted with MS_REC | MS_SLAVE this mount change only
3008 * affects our process.
3010 if (mount("/proc/self/fd", "/proc", NULL
, MS_BIND
, NULL
) < 0) {
3011 fuse_log(FUSE_LOG_ERR
, "mount(/proc/self/fd, MS_BIND): %m\n");
3015 /* Get the /proc (actually /proc/self/fd, see above) file descriptor */
3016 lo
->proc_self_fd
= open("/proc", O_PATH
);
3017 if (lo
->proc_self_fd
== -1) {
3018 fuse_log(FUSE_LOG_ERR
, "open(/proc, O_PATH): %m\n");
3024 * Capture the capability state, we'll need to restore this for individual
3025 * threads later; see load_capng.
3027 static void setup_capng(void)
3029 /* Note this accesses /proc so has to happen before the sandbox */
3030 if (capng_get_caps_process()) {
3031 fuse_log(FUSE_LOG_ERR
, "capng_get_caps_process\n");
3034 pthread_mutex_init(&cap
.mutex
, NULL
);
3035 pthread_mutex_lock(&cap
.mutex
);
3036 cap
.saved
= capng_save_state();
3038 fuse_log(FUSE_LOG_ERR
, "capng_save_state\n");
3041 pthread_mutex_unlock(&cap
.mutex
);
3044 static void cleanup_capng(void)
3048 pthread_mutex_destroy(&cap
.mutex
);
3053 * Make the source directory our root so symlinks cannot escape and no other
3054 * files are accessible. Assumes unshare(CLONE_NEWNS) was already called.
3056 static void setup_mounts(const char *source
)
3061 if (mount(source
, source
, NULL
, MS_BIND
| MS_REC
, NULL
) < 0) {
3062 fuse_log(FUSE_LOG_ERR
, "mount(%s, %s, MS_BIND): %m\n", source
, source
);
3066 /* This magic is based on lxc's lxc_pivot_root() */
3067 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
3069 fuse_log(FUSE_LOG_ERR
, "open(/): %m\n");
3073 newroot
= open(source
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
3075 fuse_log(FUSE_LOG_ERR
, "open(%s): %m\n", source
);
3079 if (fchdir(newroot
) < 0) {
3080 fuse_log(FUSE_LOG_ERR
, "fchdir(newroot): %m\n");
3084 if (syscall(__NR_pivot_root
, ".", ".") < 0) {
3085 fuse_log(FUSE_LOG_ERR
, "pivot_root(., .): %m\n");
3089 if (fchdir(oldroot
) < 0) {
3090 fuse_log(FUSE_LOG_ERR
, "fchdir(oldroot): %m\n");
3094 if (mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
) < 0) {
3095 fuse_log(FUSE_LOG_ERR
, "mount(., MS_SLAVE | MS_REC): %m\n");
3099 if (umount2(".", MNT_DETACH
) < 0) {
3100 fuse_log(FUSE_LOG_ERR
, "umount2(., MNT_DETACH): %m\n");
3104 if (fchdir(newroot
) < 0) {
3105 fuse_log(FUSE_LOG_ERR
, "fchdir(newroot): %m\n");
3114 * Only keep whitelisted capabilities that are needed for file system operation
3115 * The (possibly NULL) modcaps_in string passed in is free'd before exit.
3117 static void setup_capabilities(char *modcaps_in
)
3119 char *modcaps
= modcaps_in
;
3120 pthread_mutex_lock(&cap
.mutex
);
3121 capng_restore_state(&cap
.saved
);
3124 * Whitelist file system-related capabilities that are needed for a file
3125 * server to act like root. Drop everything else like networking and
3126 * sysadmin capabilities.
3129 * 1. CAP_LINUX_IMMUTABLE is not included because it's only used via ioctl
3130 * and we don't support that.
3131 * 2. CAP_MAC_OVERRIDE is not included because it only seems to be
3132 * used by the Smack LSM. Omit it until there is demand for it.
3134 capng_setpid(syscall(SYS_gettid
));
3135 capng_clear(CAPNG_SELECT_BOTH
);
3136 if (capng_updatev(CAPNG_ADD
, CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
3146 fuse_log(FUSE_LOG_ERR
, "%s: capng_updatev failed\n", __func__
);
3151 * The modcaps option is a colon separated list of caps,
3152 * each preceded by either + or -.
3158 char *next
= strchr(modcaps
, ':');
3164 switch (modcaps
[0]) {
3170 action
= CAPNG_DROP
;
3174 fuse_log(FUSE_LOG_ERR
,
3175 "%s: Expecting '+'/'-' in modcaps but found '%c'\n",
3176 __func__
, modcaps
[0]);
3179 cap
= capng_name_to_capability(modcaps
+ 1);
3181 fuse_log(FUSE_LOG_ERR
, "%s: Unknown capability '%s'\n", __func__
,
3185 if (capng_update(action
, CAPNG_PERMITTED
| CAPNG_EFFECTIVE
, cap
)) {
3186 fuse_log(FUSE_LOG_ERR
, "%s: capng_update failed for '%s'\n",
3195 if (capng_apply(CAPNG_SELECT_BOTH
)) {
3196 fuse_log(FUSE_LOG_ERR
, "%s: capng_apply failed\n", __func__
);
3200 cap
.saved
= capng_save_state();
3202 fuse_log(FUSE_LOG_ERR
, "%s: capng_save_state failed\n", __func__
);
3205 pthread_mutex_unlock(&cap
.mutex
);
3209 * Use chroot as a weaker sandbox for environments where the process is
3210 * launched without CAP_SYS_ADMIN.
3212 static void setup_chroot(struct lo_data
*lo
)
3214 lo
->proc_self_fd
= open("/proc/self/fd", O_PATH
);
3215 if (lo
->proc_self_fd
== -1) {
3216 fuse_log(FUSE_LOG_ERR
, "open(\"/proc/self/fd\", O_PATH): %m\n");
3221 * Make the shared directory the file system root so that FUSE_OPEN
3222 * (lo_open()) cannot escape the shared directory by opening a symlink.
3224 * The chroot(2) syscall is later disabled by seccomp and the
3225 * CAP_SYS_CHROOT capability is dropped so that tampering with the chroot
3228 * However, it's still possible to escape the chroot via lo->proc_self_fd
3229 * but that requires first gaining control of the process.
3231 if (chroot(lo
->source
) != 0) {
3232 fuse_log(FUSE_LOG_ERR
, "chroot(\"%s\"): %m\n", lo
->source
);
3236 /* Move into the chroot */
3237 if (chdir("/") != 0) {
3238 fuse_log(FUSE_LOG_ERR
, "chdir(\"/\"): %m\n");
3244 * Lock down this process to prevent access to other processes or files outside
3245 * source directory. This reduces the impact of arbitrary code execution bugs.
3247 static void setup_sandbox(struct lo_data
*lo
, struct fuse_session
*se
,
3250 if (lo
->sandbox
== SANDBOX_NAMESPACE
) {
3251 setup_namespaces(lo
, se
);
3252 setup_mounts(lo
->source
);
3257 setup_seccomp(enable_syslog
);
3258 setup_capabilities(g_strdup(lo
->modcaps
));
3261 /* Set the maximum number of open file descriptors */
3262 static void setup_nofile_rlimit(unsigned long rlimit_nofile
)
3264 struct rlimit rlim
= {
3265 .rlim_cur
= rlimit_nofile
,
3266 .rlim_max
= rlimit_nofile
,
3269 if (rlimit_nofile
== 0) {
3270 return; /* nothing to do */
3273 if (setrlimit(RLIMIT_NOFILE
, &rlim
) < 0) {
3274 /* Ignore SELinux denials */
3275 if (errno
== EPERM
) {
3279 fuse_log(FUSE_LOG_ERR
, "setrlimit(RLIMIT_NOFILE): %m\n");
3284 static void log_func(enum fuse_log_level level
, const char *fmt
, va_list ap
)
3286 g_autofree
char *localfmt
= NULL
;
3288 if (current_log_level
< level
) {
3292 if (current_log_level
== FUSE_LOG_DEBUG
) {
3294 localfmt
= g_strdup_printf("[%" PRId64
"] [ID: %08ld] %s",
3295 get_clock(), syscall(__NR_gettid
), fmt
);
3297 localfmt
= g_strdup_printf("[ID: %08ld] %s", syscall(__NR_gettid
),
3304 int priority
= LOG_ERR
;
3306 case FUSE_LOG_EMERG
:
3307 priority
= LOG_EMERG
;
3309 case FUSE_LOG_ALERT
:
3310 priority
= LOG_ALERT
;
3313 priority
= LOG_CRIT
;
3318 case FUSE_LOG_WARNING
:
3319 priority
= LOG_WARNING
;
3321 case FUSE_LOG_NOTICE
:
3322 priority
= LOG_NOTICE
;
3325 priority
= LOG_INFO
;
3327 case FUSE_LOG_DEBUG
:
3328 priority
= LOG_DEBUG
;
3331 vsyslog(priority
, fmt
, ap
);
3333 vfprintf(stderr
, fmt
, ap
);
3337 static void setup_root(struct lo_data
*lo
, struct lo_inode
*root
)
3343 fd
= open("/", O_PATH
);
3345 fuse_log(FUSE_LOG_ERR
, "open(%s, O_PATH): %m\n", lo
->source
);
3349 res
= do_statx(lo
, fd
, "", &stat
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
,
3352 fuse_log(FUSE_LOG_ERR
, "fstatat(%s): %m\n", lo
->source
);
3356 root
->filetype
= S_IFDIR
;
3358 root
->key
.ino
= stat
.st_ino
;
3359 root
->key
.dev
= stat
.st_dev
;
3360 root
->key
.mnt_id
= mnt_id
;
3362 g_atomic_int_set(&root
->refcount
, 2);
3365 static guint
lo_key_hash(gconstpointer key
)
3367 const struct lo_key
*lkey
= key
;
3369 return (guint
)lkey
->ino
+ (guint
)lkey
->dev
+ (guint
)lkey
->mnt_id
;
3372 static gboolean
lo_key_equal(gconstpointer a
, gconstpointer b
)
3374 const struct lo_key
*la
= a
;
3375 const struct lo_key
*lb
= b
;
3377 return la
->ino
== lb
->ino
&& la
->dev
== lb
->dev
&& la
->mnt_id
== lb
->mnt_id
;
3380 static void fuse_lo_data_cleanup(struct lo_data
*lo
)
3383 g_hash_table_destroy(lo
->inodes
);
3385 lo_map_destroy(&lo
->fd_map
);
3386 lo_map_destroy(&lo
->dirp_map
);
3387 lo_map_destroy(&lo
->ino_map
);
3389 if (lo
->proc_self_fd
>= 0) {
3390 close(lo
->proc_self_fd
);
3393 if (lo
->root
.fd
>= 0) {
3402 int main(int argc
, char *argv
[])
3404 struct fuse_args args
= FUSE_ARGS_INIT(argc
, argv
);
3405 struct fuse_session
*se
;
3406 struct fuse_cmdline_opts opts
;
3407 struct lo_data lo
= {
3408 .sandbox
= SANDBOX_NAMESPACE
,
3412 .allow_direct_io
= 0,
3415 struct lo_map_elem
*root_elem
;
3416 struct lo_map_elem
*reserve_elem
;
3419 /* Don't mask creation mode, kernel already did that */
3422 qemu_init_exec_dir(argv
[0]);
3424 pthread_mutex_init(&lo
.mutex
, NULL
);
3425 lo
.inodes
= g_hash_table_new(lo_key_hash
, lo_key_equal
);
3427 lo
.root
.fuse_ino
= FUSE_ROOT_ID
;
3428 lo
.cache
= CACHE_AUTO
;
3431 * Set up the ino map like this:
3432 * [0] Reserved (will not be used)
3435 lo_map_init(&lo
.ino_map
);
3436 reserve_elem
= lo_map_reserve(&lo
.ino_map
, 0);
3437 if (!reserve_elem
) {
3438 fuse_log(FUSE_LOG_ERR
, "failed to alloc reserve_elem.\n");
3441 reserve_elem
->in_use
= false;
3442 root_elem
= lo_map_reserve(&lo
.ino_map
, lo
.root
.fuse_ino
);
3444 fuse_log(FUSE_LOG_ERR
, "failed to alloc root_elem.\n");
3447 root_elem
->inode
= &lo
.root
;
3449 lo_map_init(&lo
.dirp_map
);
3450 lo_map_init(&lo
.fd_map
);
3452 if (fuse_parse_cmdline(&args
, &opts
) != 0) {
3455 fuse_set_log_func(log_func
);
3456 use_syslog
= opts
.syslog
;
3458 openlog("virtiofsd", LOG_PID
, LOG_DAEMON
);
3461 if (opts
.show_help
) {
3462 printf("usage: %s [options]\n\n", argv
[0]);
3463 fuse_cmdline_help();
3464 printf(" -o source=PATH shared directory tree\n");
3465 fuse_lowlevel_help();
3468 } else if (opts
.show_version
) {
3469 fuse_lowlevel_version();
3472 } else if (opts
.print_capabilities
) {
3473 print_capabilities();
3478 if (fuse_opt_parse(&args
, &lo
, lo_opts
, NULL
) == -1) {
3482 if (opts
.log_level
!= 0) {
3483 current_log_level
= opts
.log_level
;
3485 /* default log level is INFO */
3486 current_log_level
= FUSE_LOG_INFO
;
3488 lo
.debug
= opts
.debug
;
3490 current_log_level
= FUSE_LOG_DEBUG
;
3496 res
= lstat(lo
.source
, &stat
);
3498 fuse_log(FUSE_LOG_ERR
, "failed to stat source (\"%s\"): %m\n",
3502 if (!S_ISDIR(stat
.st_mode
)) {
3503 fuse_log(FUSE_LOG_ERR
, "source is not a directory\n");
3507 lo
.source
= strdup("/");
3509 fuse_log(FUSE_LOG_ERR
, "failed to strdup source\n");
3515 parse_xattrmap(&lo
);
3518 if (!lo
.timeout_set
) {
3529 lo
.timeout
= 86400.0;
3532 } else if (lo
.timeout
< 0) {
3533 fuse_log(FUSE_LOG_ERR
, "timeout is negative (%lf)\n", lo
.timeout
);
3537 lo
.use_statx
= true;
3539 se
= fuse_session_new(&args
, &lo_oper
, sizeof(lo_oper
), &lo
);
3544 if (fuse_set_signal_handlers(se
) != 0) {
3548 if (fuse_session_mount(se
) != 0) {
3552 fuse_daemonize(opts
.foreground
);
3554 setup_nofile_rlimit(opts
.rlimit_nofile
);
3556 /* Must be before sandbox since it wants /proc */
3559 setup_sandbox(&lo
, se
, opts
.syslog
);
3561 setup_root(&lo
, &lo
.root
);
3562 /* Block until ctrl+c or fusermount -u */
3563 ret
= virtio_loop(se
);
3565 fuse_session_unmount(se
);
3568 fuse_remove_signal_handlers(se
);
3570 fuse_session_destroy(se
);
3572 fuse_opt_free_args(&args
);
3574 fuse_lo_data_cleanup(&lo
);