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 a FUSE_FORGET request.
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 if (lo
->posix_lock
) {
906 pthread_mutex_init(&inode
->plock_mutex
, NULL
);
907 inode
->posix_locks
= g_hash_table_new_full(
908 g_direct_hash
, g_direct_equal
, NULL
, posix_locks_value_destroy
);
910 pthread_mutex_lock(&lo
->mutex
);
911 inode
->fuse_ino
= lo_add_inode_mapping(req
, inode
);
912 g_hash_table_insert(lo
->inodes
, &inode
->key
, inode
);
913 pthread_mutex_unlock(&lo
->mutex
);
915 e
->ino
= inode
->fuse_ino
;
916 lo_inode_put(lo
, &inode
);
917 lo_inode_put(lo
, &dir
);
919 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
920 name
, (unsigned long long)e
->ino
);
929 lo_inode_put(lo
, &inode
);
930 lo_inode_put(lo
, &dir
);
934 static void lo_lookup(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
936 struct fuse_entry_param e
;
939 fuse_log(FUSE_LOG_DEBUG
, "lo_lookup(parent=%" PRIu64
", name=%s)\n", parent
,
943 * Don't use is_safe_path_component(), allow "." and ".." for NFS export
946 if (strchr(name
, '/')) {
947 fuse_reply_err(req
, EINVAL
);
951 err
= lo_do_lookup(req
, parent
, name
, &e
);
953 fuse_reply_err(req
, err
);
955 fuse_reply_entry(req
, &e
);
960 * On some archs, setres*id is limited to 2^16 but they
961 * provide setres*id32 variants that allow 2^32.
962 * Others just let setres*id do 2^32 anyway.
964 #ifdef SYS_setresgid32
965 #define OURSYS_setresgid SYS_setresgid32
967 #define OURSYS_setresgid SYS_setresgid
970 #ifdef SYS_setresuid32
971 #define OURSYS_setresuid SYS_setresuid32
973 #define OURSYS_setresuid SYS_setresuid
977 * Change to uid/gid of caller so that file is created with
978 * ownership of caller.
979 * TODO: What about selinux context?
981 static int lo_change_cred(fuse_req_t req
, struct lo_cred
*old
)
985 old
->euid
= geteuid();
986 old
->egid
= getegid();
988 res
= syscall(OURSYS_setresgid
, -1, fuse_req_ctx(req
)->gid
, -1);
993 res
= syscall(OURSYS_setresuid
, -1, fuse_req_ctx(req
)->uid
, -1);
995 int errno_save
= errno
;
997 syscall(OURSYS_setresgid
, -1, old
->egid
, -1);
1004 /* Regain Privileges */
1005 static void lo_restore_cred(struct lo_cred
*old
)
1009 res
= syscall(OURSYS_setresuid
, -1, old
->euid
, -1);
1011 fuse_log(FUSE_LOG_ERR
, "seteuid(%u): %m\n", old
->euid
);
1015 res
= syscall(OURSYS_setresgid
, -1, old
->egid
, -1);
1017 fuse_log(FUSE_LOG_ERR
, "setegid(%u): %m\n", old
->egid
);
1022 static void lo_mknod_symlink(fuse_req_t req
, fuse_ino_t parent
,
1023 const char *name
, mode_t mode
, dev_t rdev
,
1028 struct lo_data
*lo
= lo_data(req
);
1029 struct lo_inode
*dir
;
1030 struct fuse_entry_param e
;
1031 struct lo_cred old
= {};
1033 if (!is_safe_path_component(name
)) {
1034 fuse_reply_err(req
, EINVAL
);
1038 dir
= lo_inode(req
, parent
);
1040 fuse_reply_err(req
, EBADF
);
1044 saverr
= lo_change_cred(req
, &old
);
1049 res
= mknod_wrapper(dir
->fd
, name
, link
, mode
, rdev
);
1053 lo_restore_cred(&old
);
1059 saverr
= lo_do_lookup(req
, parent
, name
, &e
);
1064 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
1065 name
, (unsigned long long)e
.ino
);
1067 fuse_reply_entry(req
, &e
);
1068 lo_inode_put(lo
, &dir
);
1072 lo_inode_put(lo
, &dir
);
1073 fuse_reply_err(req
, saverr
);
1076 static void lo_mknod(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1077 mode_t mode
, dev_t rdev
)
1079 lo_mknod_symlink(req
, parent
, name
, mode
, rdev
, NULL
);
1082 static void lo_mkdir(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1085 lo_mknod_symlink(req
, parent
, name
, S_IFDIR
| mode
, 0, NULL
);
1088 static void lo_symlink(fuse_req_t req
, const char *link
, fuse_ino_t parent
,
1091 lo_mknod_symlink(req
, parent
, name
, S_IFLNK
, 0, link
);
1094 static void lo_link(fuse_req_t req
, fuse_ino_t ino
, fuse_ino_t parent
,
1098 struct lo_data
*lo
= lo_data(req
);
1099 struct lo_inode
*parent_inode
;
1100 struct lo_inode
*inode
;
1101 struct fuse_entry_param e
;
1105 if (!is_safe_path_component(name
)) {
1106 fuse_reply_err(req
, EINVAL
);
1110 parent_inode
= lo_inode(req
, parent
);
1111 inode
= lo_inode(req
, ino
);
1112 if (!parent_inode
|| !inode
) {
1117 memset(&e
, 0, sizeof(struct fuse_entry_param
));
1118 e
.attr_timeout
= lo
->timeout
;
1119 e
.entry_timeout
= lo
->timeout
;
1121 sprintf(procname
, "%i", inode
->fd
);
1122 res
= linkat(lo
->proc_self_fd
, procname
, parent_inode
->fd
, name
,
1128 res
= fstatat(inode
->fd
, "", &e
.attr
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
1133 pthread_mutex_lock(&lo
->mutex
);
1135 pthread_mutex_unlock(&lo
->mutex
);
1136 e
.ino
= inode
->fuse_ino
;
1138 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
1139 name
, (unsigned long long)e
.ino
);
1141 fuse_reply_entry(req
, &e
);
1142 lo_inode_put(lo
, &parent_inode
);
1143 lo_inode_put(lo
, &inode
);
1148 lo_inode_put(lo
, &parent_inode
);
1149 lo_inode_put(lo
, &inode
);
1150 fuse_reply_err(req
, saverr
);
1153 /* Increments nlookup and caller must release refcount using lo_inode_put() */
1154 static struct lo_inode
*lookup_name(fuse_req_t req
, fuse_ino_t parent
,
1160 struct lo_data
*lo
= lo_data(req
);
1161 struct lo_inode
*dir
= lo_inode(req
, parent
);
1167 res
= do_statx(lo
, dir
->fd
, name
, &attr
,
1168 AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
, &mnt_id
);
1169 lo_inode_put(lo
, &dir
);
1174 return lo_find(lo
, &attr
, mnt_id
);
1177 static void lo_rmdir(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
1180 struct lo_inode
*inode
;
1181 struct lo_data
*lo
= lo_data(req
);
1183 if (!is_safe_path_component(name
)) {
1184 fuse_reply_err(req
, EINVAL
);
1188 inode
= lookup_name(req
, parent
, name
);
1190 fuse_reply_err(req
, EIO
);
1194 res
= unlinkat(lo_fd(req
, parent
), name
, AT_REMOVEDIR
);
1196 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1197 unref_inode_lolocked(lo
, inode
, 1);
1198 lo_inode_put(lo
, &inode
);
1201 static void lo_rename(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1202 fuse_ino_t newparent
, const char *newname
,
1206 struct lo_inode
*parent_inode
;
1207 struct lo_inode
*newparent_inode
;
1208 struct lo_inode
*oldinode
= NULL
;
1209 struct lo_inode
*newinode
= NULL
;
1210 struct lo_data
*lo
= lo_data(req
);
1212 if (!is_safe_path_component(name
) || !is_safe_path_component(newname
)) {
1213 fuse_reply_err(req
, EINVAL
);
1217 parent_inode
= lo_inode(req
, parent
);
1218 newparent_inode
= lo_inode(req
, newparent
);
1219 if (!parent_inode
|| !newparent_inode
) {
1220 fuse_reply_err(req
, EBADF
);
1224 oldinode
= lookup_name(req
, parent
, name
);
1225 newinode
= lookup_name(req
, newparent
, newname
);
1228 fuse_reply_err(req
, EIO
);
1233 #ifndef SYS_renameat2
1234 fuse_reply_err(req
, EINVAL
);
1236 res
= syscall(SYS_renameat2
, parent_inode
->fd
, name
,
1237 newparent_inode
->fd
, newname
, flags
);
1238 if (res
== -1 && errno
== ENOSYS
) {
1239 fuse_reply_err(req
, EINVAL
);
1241 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1247 res
= renameat(parent_inode
->fd
, name
, newparent_inode
->fd
, newname
);
1249 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1251 unref_inode_lolocked(lo
, oldinode
, 1);
1252 unref_inode_lolocked(lo
, newinode
, 1);
1253 lo_inode_put(lo
, &oldinode
);
1254 lo_inode_put(lo
, &newinode
);
1255 lo_inode_put(lo
, &parent_inode
);
1256 lo_inode_put(lo
, &newparent_inode
);
1259 static void lo_unlink(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
1262 struct lo_inode
*inode
;
1263 struct lo_data
*lo
= lo_data(req
);
1265 if (!is_safe_path_component(name
)) {
1266 fuse_reply_err(req
, EINVAL
);
1270 inode
= lookup_name(req
, parent
, name
);
1272 fuse_reply_err(req
, EIO
);
1276 res
= unlinkat(lo_fd(req
, parent
), name
, 0);
1278 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1279 unref_inode_lolocked(lo
, inode
, 1);
1280 lo_inode_put(lo
, &inode
);
1283 /* To be called with lo->mutex held */
1284 static void unref_inode(struct lo_data
*lo
, struct lo_inode
*inode
, uint64_t n
)
1290 assert(inode
->nlookup
>= n
);
1291 inode
->nlookup
-= n
;
1292 if (!inode
->nlookup
) {
1293 lo_map_remove(&lo
->ino_map
, inode
->fuse_ino
);
1294 g_hash_table_remove(lo
->inodes
, &inode
->key
);
1295 if (lo
->posix_lock
) {
1296 if (g_hash_table_size(inode
->posix_locks
)) {
1297 fuse_log(FUSE_LOG_WARNING
, "Hash table is not empty\n");
1299 g_hash_table_destroy(inode
->posix_locks
);
1300 pthread_mutex_destroy(&inode
->plock_mutex
);
1302 /* Drop our refcount from lo_do_lookup() */
1303 lo_inode_put(lo
, &inode
);
1307 static void unref_inode_lolocked(struct lo_data
*lo
, struct lo_inode
*inode
,
1314 pthread_mutex_lock(&lo
->mutex
);
1315 unref_inode(lo
, inode
, n
);
1316 pthread_mutex_unlock(&lo
->mutex
);
1319 static void lo_forget_one(fuse_req_t req
, fuse_ino_t ino
, uint64_t nlookup
)
1321 struct lo_data
*lo
= lo_data(req
);
1322 struct lo_inode
*inode
;
1324 inode
= lo_inode(req
, ino
);
1329 fuse_log(FUSE_LOG_DEBUG
, " forget %lli %lli -%lli\n",
1330 (unsigned long long)ino
, (unsigned long long)inode
->nlookup
,
1331 (unsigned long long)nlookup
);
1333 unref_inode_lolocked(lo
, inode
, nlookup
);
1334 lo_inode_put(lo
, &inode
);
1337 static void lo_forget(fuse_req_t req
, fuse_ino_t ino
, uint64_t nlookup
)
1339 lo_forget_one(req
, ino
, nlookup
);
1340 fuse_reply_none(req
);
1343 static void lo_forget_multi(fuse_req_t req
, size_t count
,
1344 struct fuse_forget_data
*forgets
)
1348 for (i
= 0; i
< count
; i
++) {
1349 lo_forget_one(req
, forgets
[i
].ino
, forgets
[i
].nlookup
);
1351 fuse_reply_none(req
);
1354 static void lo_readlink(fuse_req_t req
, fuse_ino_t ino
)
1356 char buf
[PATH_MAX
+ 1];
1359 res
= readlinkat(lo_fd(req
, ino
), "", buf
, sizeof(buf
));
1361 return (void)fuse_reply_err(req
, errno
);
1364 if (res
== sizeof(buf
)) {
1365 return (void)fuse_reply_err(req
, ENAMETOOLONG
);
1370 fuse_reply_readlink(req
, buf
);
1376 struct dirent
*entry
;
1380 static void lo_dirp_put(struct lo_dirp
**dp
)
1382 struct lo_dirp
*d
= *dp
;
1389 if (g_atomic_int_dec_and_test(&d
->refcount
)) {
1395 /* Call lo_dirp_put() on the return value when no longer needed */
1396 static struct lo_dirp
*lo_dirp(fuse_req_t req
, struct fuse_file_info
*fi
)
1398 struct lo_data
*lo
= lo_data(req
);
1399 struct lo_map_elem
*elem
;
1401 pthread_mutex_lock(&lo
->mutex
);
1402 elem
= lo_map_get(&lo
->dirp_map
, fi
->fh
);
1404 g_atomic_int_inc(&elem
->dirp
->refcount
);
1406 pthread_mutex_unlock(&lo
->mutex
);
1414 static void lo_opendir(fuse_req_t req
, fuse_ino_t ino
,
1415 struct fuse_file_info
*fi
)
1418 struct lo_data
*lo
= lo_data(req
);
1423 d
= calloc(1, sizeof(struct lo_dirp
));
1428 fd
= openat(lo_fd(req
, ino
), ".", O_RDONLY
);
1433 d
->dp
= fdopendir(fd
);
1434 if (d
->dp
== NULL
) {
1441 g_atomic_int_set(&d
->refcount
, 1); /* paired with lo_releasedir() */
1442 pthread_mutex_lock(&lo
->mutex
);
1443 fh
= lo_add_dirp_mapping(req
, d
);
1444 pthread_mutex_unlock(&lo
->mutex
);
1450 if (lo
->cache
== CACHE_ALWAYS
) {
1451 fi
->cache_readdir
= 1;
1453 fuse_reply_open(req
, fi
);
1462 } else if (fd
!= -1) {
1467 fuse_reply_err(req
, error
);
1470 static void lo_do_readdir(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
1471 off_t offset
, struct fuse_file_info
*fi
, int plus
)
1473 struct lo_data
*lo
= lo_data(req
);
1474 struct lo_dirp
*d
= NULL
;
1475 struct lo_inode
*dinode
;
1481 dinode
= lo_inode(req
, ino
);
1486 d
= lo_dirp(req
, fi
);
1492 buf
= calloc(1, size
);
1498 if (offset
!= d
->offset
) {
1499 seekdir(d
->dp
, offset
);
1510 d
->entry
= readdir(d
->dp
);
1512 if (errno
) { /* Error */
1515 } else { /* End of stream */
1520 nextoff
= d
->entry
->d_off
;
1521 name
= d
->entry
->d_name
;
1523 fuse_ino_t entry_ino
= 0;
1524 struct fuse_entry_param e
= (struct fuse_entry_param
){
1525 .attr
.st_ino
= d
->entry
->d_ino
,
1526 .attr
.st_mode
= d
->entry
->d_type
<< 12,
1529 /* Hide root's parent directory */
1530 if (dinode
== &lo
->root
&& strcmp(name
, "..") == 0) {
1531 e
.attr
.st_ino
= lo
->root
.key
.ino
;
1532 e
.attr
.st_mode
= DT_DIR
<< 12;
1536 if (!is_dot_or_dotdot(name
)) {
1537 err
= lo_do_lookup(req
, ino
, name
, &e
);
1544 entsize
= fuse_add_direntry_plus(req
, p
, rem
, name
, &e
, nextoff
);
1546 entsize
= fuse_add_direntry(req
, p
, rem
, name
, &e
.attr
, nextoff
);
1548 if (entsize
> rem
) {
1549 if (entry_ino
!= 0) {
1550 lo_forget_one(req
, entry_ino
, 1);
1559 d
->offset
= nextoff
;
1565 lo_inode_put(lo
, &dinode
);
1568 * If there's an error, we can only signal it if we haven't stored
1569 * any entries yet - otherwise we'd end up with wrong lookup
1570 * counts for the entries that are already in the buffer. So we
1571 * return what we've collected until that point.
1573 if (err
&& rem
== size
) {
1574 fuse_reply_err(req
, err
);
1576 fuse_reply_buf(req
, buf
, size
- rem
);
1581 static void lo_readdir(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
1582 off_t offset
, struct fuse_file_info
*fi
)
1584 lo_do_readdir(req
, ino
, size
, offset
, fi
, 0);
1587 static void lo_readdirplus(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
1588 off_t offset
, struct fuse_file_info
*fi
)
1590 lo_do_readdir(req
, ino
, size
, offset
, fi
, 1);
1593 static void lo_releasedir(fuse_req_t req
, fuse_ino_t ino
,
1594 struct fuse_file_info
*fi
)
1596 struct lo_data
*lo
= lo_data(req
);
1597 struct lo_map_elem
*elem
;
1602 pthread_mutex_lock(&lo
->mutex
);
1603 elem
= lo_map_get(&lo
->dirp_map
, fi
->fh
);
1605 pthread_mutex_unlock(&lo
->mutex
);
1606 fuse_reply_err(req
, EBADF
);
1611 lo_map_remove(&lo
->dirp_map
, fi
->fh
);
1612 pthread_mutex_unlock(&lo
->mutex
);
1614 lo_dirp_put(&d
); /* paired with lo_opendir() */
1616 fuse_reply_err(req
, 0);
1619 static void update_open_flags(int writeback
, int allow_direct_io
,
1620 struct fuse_file_info
*fi
)
1623 * With writeback cache, kernel may send read requests even
1624 * when userspace opened write-only
1626 if (writeback
&& (fi
->flags
& O_ACCMODE
) == O_WRONLY
) {
1627 fi
->flags
&= ~O_ACCMODE
;
1628 fi
->flags
|= O_RDWR
;
1632 * With writeback cache, O_APPEND is handled by the kernel.
1633 * This breaks atomicity (since the file may change in the
1634 * underlying filesystem, so that the kernel's idea of the
1635 * end of the file isn't accurate anymore). In this example,
1636 * we just accept that. A more rigorous filesystem may want
1637 * to return an error here
1639 if (writeback
&& (fi
->flags
& O_APPEND
)) {
1640 fi
->flags
&= ~O_APPEND
;
1644 * O_DIRECT in guest should not necessarily mean bypassing page
1645 * cache on host as well. Therefore, we discard it by default
1646 * ('-o no_allow_direct_io'). If somebody needs that behavior,
1647 * the '-o allow_direct_io' option should be set.
1649 if (!allow_direct_io
) {
1650 fi
->flags
&= ~O_DIRECT
;
1654 static void lo_create(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1655 mode_t mode
, struct fuse_file_info
*fi
)
1658 struct lo_data
*lo
= lo_data(req
);
1659 struct lo_inode
*parent_inode
;
1660 struct fuse_entry_param e
;
1662 struct lo_cred old
= {};
1664 fuse_log(FUSE_LOG_DEBUG
, "lo_create(parent=%" PRIu64
", name=%s)\n", parent
,
1667 if (!is_safe_path_component(name
)) {
1668 fuse_reply_err(req
, EINVAL
);
1672 parent_inode
= lo_inode(req
, parent
);
1673 if (!parent_inode
) {
1674 fuse_reply_err(req
, EBADF
);
1678 err
= lo_change_cred(req
, &old
);
1683 update_open_flags(lo
->writeback
, lo
->allow_direct_io
, fi
);
1685 fd
= openat(parent_inode
->fd
, name
, (fi
->flags
| O_CREAT
) & ~O_NOFOLLOW
,
1687 err
= fd
== -1 ? errno
: 0;
1688 lo_restore_cred(&old
);
1693 pthread_mutex_lock(&lo
->mutex
);
1694 fh
= lo_add_fd_mapping(req
, fd
);
1695 pthread_mutex_unlock(&lo
->mutex
);
1703 err
= lo_do_lookup(req
, parent
, name
, &e
);
1705 if (lo
->cache
== CACHE_NONE
) {
1707 } else if (lo
->cache
== CACHE_ALWAYS
) {
1712 lo_inode_put(lo
, &parent_inode
);
1715 fuse_reply_err(req
, err
);
1717 fuse_reply_create(req
, &e
, fi
);
1721 /* Should be called with inode->plock_mutex held */
1722 static struct lo_inode_plock
*lookup_create_plock_ctx(struct lo_data
*lo
,
1723 struct lo_inode
*inode
,
1724 uint64_t lock_owner
,
1725 pid_t pid
, int *err
)
1727 struct lo_inode_plock
*plock
;
1732 g_hash_table_lookup(inode
->posix_locks
, GUINT_TO_POINTER(lock_owner
));
1738 plock
= malloc(sizeof(struct lo_inode_plock
));
1744 /* Open another instance of file which can be used for ofd locks. */
1745 sprintf(procname
, "%i", inode
->fd
);
1747 /* TODO: What if file is not writable? */
1748 fd
= openat(lo
->proc_self_fd
, procname
, O_RDWR
);
1755 plock
->lock_owner
= lock_owner
;
1757 g_hash_table_insert(inode
->posix_locks
, GUINT_TO_POINTER(plock
->lock_owner
),
1762 static void lo_getlk(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
1765 struct lo_data
*lo
= lo_data(req
);
1766 struct lo_inode
*inode
;
1767 struct lo_inode_plock
*plock
;
1768 int ret
, saverr
= 0;
1770 fuse_log(FUSE_LOG_DEBUG
,
1771 "lo_getlk(ino=%" PRIu64
", flags=%d)"
1772 " owner=0x%lx, l_type=%d l_start=0x%lx"
1774 ino
, fi
->flags
, fi
->lock_owner
, lock
->l_type
, lock
->l_start
,
1777 if (!lo
->posix_lock
) {
1778 fuse_reply_err(req
, ENOSYS
);
1782 inode
= lo_inode(req
, ino
);
1784 fuse_reply_err(req
, EBADF
);
1788 pthread_mutex_lock(&inode
->plock_mutex
);
1790 lookup_create_plock_ctx(lo
, inode
, fi
->lock_owner
, lock
->l_pid
, &ret
);
1796 ret
= fcntl(plock
->fd
, F_OFD_GETLK
, lock
);
1802 pthread_mutex_unlock(&inode
->plock_mutex
);
1803 lo_inode_put(lo
, &inode
);
1806 fuse_reply_err(req
, saverr
);
1808 fuse_reply_lock(req
, lock
);
1812 static void lo_setlk(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
1813 struct flock
*lock
, int sleep
)
1815 struct lo_data
*lo
= lo_data(req
);
1816 struct lo_inode
*inode
;
1817 struct lo_inode_plock
*plock
;
1818 int ret
, saverr
= 0;
1820 fuse_log(FUSE_LOG_DEBUG
,
1821 "lo_setlk(ino=%" PRIu64
", flags=%d)"
1822 " cmd=%d pid=%d owner=0x%lx sleep=%d l_whence=%d"
1823 " l_start=0x%lx l_len=0x%lx\n",
1824 ino
, fi
->flags
, lock
->l_type
, lock
->l_pid
, fi
->lock_owner
, sleep
,
1825 lock
->l_whence
, lock
->l_start
, lock
->l_len
);
1827 if (!lo
->posix_lock
) {
1828 fuse_reply_err(req
, ENOSYS
);
1833 fuse_reply_err(req
, EOPNOTSUPP
);
1837 inode
= lo_inode(req
, ino
);
1839 fuse_reply_err(req
, EBADF
);
1843 pthread_mutex_lock(&inode
->plock_mutex
);
1845 lookup_create_plock_ctx(lo
, inode
, fi
->lock_owner
, lock
->l_pid
, &ret
);
1852 /* TODO: Is it alright to modify flock? */
1854 ret
= fcntl(plock
->fd
, F_OFD_SETLK
, lock
);
1860 pthread_mutex_unlock(&inode
->plock_mutex
);
1861 lo_inode_put(lo
, &inode
);
1863 fuse_reply_err(req
, saverr
);
1866 static void lo_fsyncdir(fuse_req_t req
, fuse_ino_t ino
, int datasync
,
1867 struct fuse_file_info
*fi
)
1875 d
= lo_dirp(req
, fi
);
1877 fuse_reply_err(req
, EBADF
);
1883 res
= fdatasync(fd
);
1890 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1893 static void lo_open(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
)
1898 struct lo_data
*lo
= lo_data(req
);
1900 fuse_log(FUSE_LOG_DEBUG
, "lo_open(ino=%" PRIu64
", flags=%d)\n", ino
,
1903 update_open_flags(lo
->writeback
, lo
->allow_direct_io
, fi
);
1905 sprintf(buf
, "%i", lo_fd(req
, ino
));
1906 fd
= openat(lo
->proc_self_fd
, buf
, fi
->flags
& ~O_NOFOLLOW
);
1908 return (void)fuse_reply_err(req
, errno
);
1911 pthread_mutex_lock(&lo
->mutex
);
1912 fh
= lo_add_fd_mapping(req
, fd
);
1913 pthread_mutex_unlock(&lo
->mutex
);
1916 fuse_reply_err(req
, ENOMEM
);
1921 if (lo
->cache
== CACHE_NONE
) {
1923 } else if (lo
->cache
== CACHE_ALWAYS
) {
1926 fuse_reply_open(req
, fi
);
1929 static void lo_release(fuse_req_t req
, fuse_ino_t ino
,
1930 struct fuse_file_info
*fi
)
1932 struct lo_data
*lo
= lo_data(req
);
1933 struct lo_map_elem
*elem
;
1938 pthread_mutex_lock(&lo
->mutex
);
1939 elem
= lo_map_get(&lo
->fd_map
, fi
->fh
);
1943 lo_map_remove(&lo
->fd_map
, fi
->fh
);
1945 pthread_mutex_unlock(&lo
->mutex
);
1948 fuse_reply_err(req
, 0);
1951 static void lo_flush(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
)
1955 struct lo_inode
*inode
;
1956 struct lo_data
*lo
= lo_data(req
);
1958 inode
= lo_inode(req
, ino
);
1960 fuse_reply_err(req
, EBADF
);
1964 if (!S_ISREG(inode
->filetype
)) {
1965 lo_inode_put(lo
, &inode
);
1966 fuse_reply_err(req
, EBADF
);
1970 /* An fd is going away. Cleanup associated posix locks */
1971 if (lo
->posix_lock
) {
1972 pthread_mutex_lock(&inode
->plock_mutex
);
1973 g_hash_table_remove(inode
->posix_locks
,
1974 GUINT_TO_POINTER(fi
->lock_owner
));
1975 pthread_mutex_unlock(&inode
->plock_mutex
);
1977 res
= close(dup(lo_fi_fd(req
, fi
)));
1978 lo_inode_put(lo
, &inode
);
1979 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1982 static void lo_fsync(fuse_req_t req
, fuse_ino_t ino
, int datasync
,
1983 struct fuse_file_info
*fi
)
1989 fuse_log(FUSE_LOG_DEBUG
, "lo_fsync(ino=%" PRIu64
", fi=0x%p)\n", ino
,
1993 struct lo_data
*lo
= lo_data(req
);
1995 res
= asprintf(&buf
, "%i", lo_fd(req
, ino
));
1997 return (void)fuse_reply_err(req
, errno
);
2000 fd
= openat(lo
->proc_self_fd
, buf
, O_RDWR
);
2003 return (void)fuse_reply_err(req
, errno
);
2006 fd
= lo_fi_fd(req
, fi
);
2010 res
= fdatasync(fd
);
2017 fuse_reply_err(req
, res
== -1 ? errno
: 0);
2020 static void lo_read(fuse_req_t req
, fuse_ino_t ino
, size_t size
, off_t offset
,
2021 struct fuse_file_info
*fi
)
2023 struct fuse_bufvec buf
= FUSE_BUFVEC_INIT(size
);
2025 fuse_log(FUSE_LOG_DEBUG
,
2026 "lo_read(ino=%" PRIu64
", size=%zd, "
2028 ino
, size
, (unsigned long)offset
);
2030 buf
.buf
[0].flags
= FUSE_BUF_IS_FD
| FUSE_BUF_FD_SEEK
;
2031 buf
.buf
[0].fd
= lo_fi_fd(req
, fi
);
2032 buf
.buf
[0].pos
= offset
;
2034 fuse_reply_data(req
, &buf
);
2037 static void lo_write_buf(fuse_req_t req
, fuse_ino_t ino
,
2038 struct fuse_bufvec
*in_buf
, off_t off
,
2039 struct fuse_file_info
*fi
)
2043 struct fuse_bufvec out_buf
= FUSE_BUFVEC_INIT(fuse_buf_size(in_buf
));
2044 bool cap_fsetid_dropped
= false;
2046 out_buf
.buf
[0].flags
= FUSE_BUF_IS_FD
| FUSE_BUF_FD_SEEK
;
2047 out_buf
.buf
[0].fd
= lo_fi_fd(req
, fi
);
2048 out_buf
.buf
[0].pos
= off
;
2050 fuse_log(FUSE_LOG_DEBUG
,
2051 "lo_write_buf(ino=%" PRIu64
", size=%zd, off=%lu)\n", ino
,
2052 out_buf
.buf
[0].size
, (unsigned long)off
);
2055 * If kill_priv is set, drop CAP_FSETID which should lead to kernel
2056 * clearing setuid/setgid on file.
2058 if (fi
->kill_priv
) {
2059 res
= drop_effective_cap("FSETID", &cap_fsetid_dropped
);
2061 fuse_reply_err(req
, res
);
2066 res
= fuse_buf_copy(&out_buf
, in_buf
);
2068 fuse_reply_err(req
, -res
);
2070 fuse_reply_write(req
, (size_t)res
);
2073 if (cap_fsetid_dropped
) {
2074 res
= gain_effective_cap("FSETID");
2076 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_FSETID\n");
2081 static void lo_statfs(fuse_req_t req
, fuse_ino_t ino
)
2084 struct statvfs stbuf
;
2086 res
= fstatvfs(lo_fd(req
, ino
), &stbuf
);
2088 fuse_reply_err(req
, errno
);
2090 fuse_reply_statfs(req
, &stbuf
);
2094 static void lo_fallocate(fuse_req_t req
, fuse_ino_t ino
, int mode
, off_t offset
,
2095 off_t length
, struct fuse_file_info
*fi
)
2097 int err
= EOPNOTSUPP
;
2100 #ifdef CONFIG_FALLOCATE
2101 err
= fallocate(lo_fi_fd(req
, fi
), mode
, offset
, length
);
2106 #elif defined(CONFIG_POSIX_FALLOCATE)
2108 fuse_reply_err(req
, EOPNOTSUPP
);
2112 err
= posix_fallocate(lo_fi_fd(req
, fi
), offset
, length
);
2115 fuse_reply_err(req
, err
);
2118 static void lo_flock(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
2124 res
= flock(lo_fi_fd(req
, fi
), op
);
2126 fuse_reply_err(req
, res
== -1 ? errno
: 0);
2131 * Exit; process attribute unmodified if matched.
2132 * An empty key applies to all.
2134 #define XATTR_MAP_FLAG_OK (1 << 0)
2136 * The attribute is unwanted;
2137 * EPERM on write, hidden on read.
2139 #define XATTR_MAP_FLAG_BAD (1 << 1)
2141 * For attr that start with 'key' prepend 'prepend'
2142 * 'key' may be empty to prepend for all attrs
2143 * key is defined from set/remove point of view.
2144 * Automatically reversed on read
2146 #define XATTR_MAP_FLAG_PREFIX (1 << 2)
2149 /* Apply rule to get/set/remove */
2150 #define XATTR_MAP_FLAG_CLIENT (1 << 16)
2151 /* Apply rule to list */
2152 #define XATTR_MAP_FLAG_SERVER (1 << 17)
2153 /* Apply rule to all */
2154 #define XATTR_MAP_FLAG_ALL (XATTR_MAP_FLAG_SERVER | XATTR_MAP_FLAG_CLIENT)
2156 static void add_xattrmap_entry(struct lo_data
*lo
,
2157 const XattrMapEntry
*new_entry
)
2159 XattrMapEntry
*res
= g_realloc_n(lo
->xattr_map_list
,
2160 lo
->xattr_map_nentries
+ 1,
2161 sizeof(XattrMapEntry
));
2162 res
[lo
->xattr_map_nentries
++] = *new_entry
;
2164 lo
->xattr_map_list
= res
;
2167 static void free_xattrmap(struct lo_data
*lo
)
2169 XattrMapEntry
*map
= lo
->xattr_map_list
;
2176 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
2178 g_free(map
[i
].prepend
);
2182 lo
->xattr_map_list
= NULL
;
2183 lo
->xattr_map_nentries
= -1;
2187 * Handle the 'map' type, which is sugar for a set of commands
2188 * for the common case of prefixing a subset or everything,
2189 * and allowing anything not prefixed through.
2190 * It must be the last entry in the stream, although there
2191 * can be other entries before it.
2195 * key maybe empty in which case all entries are prefixed.
2197 static void parse_xattrmap_map(struct lo_data
*lo
,
2198 const char *rule
, char sep
)
2203 XattrMapEntry tmp_entry
;
2206 fuse_log(FUSE_LOG_ERR
,
2207 "%s: Expecting '%c' after 'map' keyword, found '%c'\n",
2208 __func__
, sep
, *rule
);
2214 /* At start of 'key' field */
2215 tmp
= strchr(rule
, sep
);
2217 fuse_log(FUSE_LOG_ERR
,
2218 "%s: Missing '%c' at end of key field in map rule\n",
2223 key
= g_strndup(rule
, tmp
- rule
);
2226 /* At start of prefix field */
2227 tmp
= strchr(rule
, sep
);
2229 fuse_log(FUSE_LOG_ERR
,
2230 "%s: Missing '%c' at end of prefix field in map rule\n",
2235 prefix
= g_strndup(rule
, tmp
- rule
);
2239 * This should be the end of the string, we don't allow
2240 * any more commands after 'map'.
2243 fuse_log(FUSE_LOG_ERR
,
2244 "%s: Expecting end of command after map, found '%c'\n",
2249 /* 1st: Prefix matches/everything */
2250 tmp_entry
.flags
= XATTR_MAP_FLAG_PREFIX
| XATTR_MAP_FLAG_ALL
;
2251 tmp_entry
.key
= g_strdup(key
);
2252 tmp_entry
.prepend
= g_strdup(prefix
);
2253 add_xattrmap_entry(lo
, &tmp_entry
);
2256 /* Prefix all case */
2258 /* 2nd: Hide any non-prefixed entries on the host */
2259 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_ALL
;
2260 tmp_entry
.key
= g_strdup("");
2261 tmp_entry
.prepend
= g_strdup("");
2262 add_xattrmap_entry(lo
, &tmp_entry
);
2264 /* Prefix matching case */
2266 /* 2nd: Hide non-prefixed but matching entries on the host */
2267 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_SERVER
;
2268 tmp_entry
.key
= g_strdup(""); /* Not used */
2269 tmp_entry
.prepend
= g_strdup(key
);
2270 add_xattrmap_entry(lo
, &tmp_entry
);
2272 /* 3rd: Stop the client accessing prefixed attributes directly */
2273 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_CLIENT
;
2274 tmp_entry
.key
= g_strdup(prefix
);
2275 tmp_entry
.prepend
= g_strdup(""); /* Not used */
2276 add_xattrmap_entry(lo
, &tmp_entry
);
2278 /* 4th: Everything else is OK */
2279 tmp_entry
.flags
= XATTR_MAP_FLAG_OK
| XATTR_MAP_FLAG_ALL
;
2280 tmp_entry
.key
= g_strdup("");
2281 tmp_entry
.prepend
= g_strdup("");
2282 add_xattrmap_entry(lo
, &tmp_entry
);
2289 static void parse_xattrmap(struct lo_data
*lo
)
2291 const char *map
= lo
->xattrmap
;
2294 lo
->xattr_map_nentries
= 0;
2296 XattrMapEntry tmp_entry
;
2299 if (isspace(*map
)) {
2303 /* The separator is the first non-space of the rule */
2309 tmp_entry
.flags
= 0;
2310 /* Start of 'type' */
2311 if (strstart(map
, "prefix", &map
)) {
2312 tmp_entry
.flags
|= XATTR_MAP_FLAG_PREFIX
;
2313 } else if (strstart(map
, "ok", &map
)) {
2314 tmp_entry
.flags
|= XATTR_MAP_FLAG_OK
;
2315 } else if (strstart(map
, "bad", &map
)) {
2316 tmp_entry
.flags
|= XATTR_MAP_FLAG_BAD
;
2317 } else if (strstart(map
, "map", &map
)) {
2319 * map is sugar that adds a number of rules, and must be
2322 parse_xattrmap_map(lo
, map
, sep
);
2325 fuse_log(FUSE_LOG_ERR
,
2326 "%s: Unexpected type;"
2327 "Expecting 'prefix', 'ok', 'bad' or 'map' in rule %zu\n",
2328 __func__
, lo
->xattr_map_nentries
);
2332 if (*map
++ != sep
) {
2333 fuse_log(FUSE_LOG_ERR
,
2334 "%s: Missing '%c' at end of type field of rule %zu\n",
2335 __func__
, sep
, lo
->xattr_map_nentries
);
2339 /* Start of 'scope' */
2340 if (strstart(map
, "client", &map
)) {
2341 tmp_entry
.flags
|= XATTR_MAP_FLAG_CLIENT
;
2342 } else if (strstart(map
, "server", &map
)) {
2343 tmp_entry
.flags
|= XATTR_MAP_FLAG_SERVER
;
2344 } else if (strstart(map
, "all", &map
)) {
2345 tmp_entry
.flags
|= XATTR_MAP_FLAG_ALL
;
2347 fuse_log(FUSE_LOG_ERR
,
2348 "%s: Unexpected scope;"
2349 " Expecting 'client', 'server', or 'all', in rule %zu\n",
2350 __func__
, lo
->xattr_map_nentries
);
2354 if (*map
++ != sep
) {
2355 fuse_log(FUSE_LOG_ERR
,
2356 "%s: Expecting '%c' found '%c'"
2357 " after scope in rule %zu\n",
2358 __func__
, sep
, *map
, lo
->xattr_map_nentries
);
2362 /* At start of 'key' field */
2363 tmp
= strchr(map
, sep
);
2365 fuse_log(FUSE_LOG_ERR
,
2366 "%s: Missing '%c' at end of key field of rule %zu",
2367 __func__
, sep
, lo
->xattr_map_nentries
);
2370 tmp_entry
.key
= g_strndup(map
, tmp
- map
);
2373 /* At start of 'prepend' field */
2374 tmp
= strchr(map
, sep
);
2376 fuse_log(FUSE_LOG_ERR
,
2377 "%s: Missing '%c' at end of prepend field of rule %zu",
2378 __func__
, sep
, lo
->xattr_map_nentries
);
2381 tmp_entry
.prepend
= g_strndup(map
, tmp
- map
);
2384 add_xattrmap_entry(lo
, &tmp_entry
);
2385 /* End of rule - go around again for another rule */
2388 if (!lo
->xattr_map_nentries
) {
2389 fuse_log(FUSE_LOG_ERR
, "Empty xattr map\n");
2395 * For use with getxattr/setxattr/removexattr, where the client
2396 * gives us a name and we may need to choose a different one.
2397 * Allocates a buffer for the result placing it in *out_name.
2398 * If there's no change then *out_name is not set.
2399 * Returns 0 on success
2400 * Can return -EPERM to indicate we block a given attribute
2401 * (in which case out_name is not allocated)
2402 * Can return -ENOMEM to indicate out_name couldn't be allocated.
2404 static int xattr_map_client(const struct lo_data
*lo
, const char *client_name
,
2408 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
2409 const XattrMapEntry
*cur_entry
= lo
->xattr_map_list
+ i
;
2411 if ((cur_entry
->flags
& XATTR_MAP_FLAG_CLIENT
) &&
2412 (strstart(client_name
, cur_entry
->key
, NULL
))) {
2413 if (cur_entry
->flags
& XATTR_MAP_FLAG_BAD
) {
2416 if (cur_entry
->flags
& XATTR_MAP_FLAG_OK
) {
2417 /* Unmodified name */
2420 if (cur_entry
->flags
& XATTR_MAP_FLAG_PREFIX
) {
2421 *out_name
= g_try_malloc(strlen(client_name
) +
2422 strlen(cur_entry
->prepend
) + 1);
2426 sprintf(*out_name
, "%s%s", cur_entry
->prepend
, client_name
);
2436 * For use with listxattr where the server fs gives us a name and we may need
2437 * to sanitize this for the client.
2438 * Returns a pointer to the result in *out_name
2439 * This is always the original string or the current string with some prefix
2440 * removed; no reallocation is done.
2441 * Returns 0 on success
2442 * Can return -ENODATA to indicate the name should be dropped from the list.
2444 static int xattr_map_server(const struct lo_data
*lo
, const char *server_name
,
2445 const char **out_name
)
2450 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
2451 const XattrMapEntry
*cur_entry
= lo
->xattr_map_list
+ i
;
2453 if ((cur_entry
->flags
& XATTR_MAP_FLAG_SERVER
) &&
2454 (strstart(server_name
, cur_entry
->prepend
, &end
))) {
2455 if (cur_entry
->flags
& XATTR_MAP_FLAG_BAD
) {
2458 if (cur_entry
->flags
& XATTR_MAP_FLAG_OK
) {
2459 *out_name
= server_name
;
2462 if (cur_entry
->flags
& XATTR_MAP_FLAG_PREFIX
) {
2473 static void lo_getxattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
,
2476 struct lo_data
*lo
= lo_data(req
);
2481 struct lo_inode
*inode
;
2489 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
2491 if (ret
== -EPERM
) {
2494 fuse_reply_err(req
, -ret
);
2502 inode
= lo_inode(req
, ino
);
2504 fuse_reply_err(req
, EBADF
);
2505 g_free(mapped_name
);
2510 if (!lo_data(req
)->xattr
) {
2514 fuse_log(FUSE_LOG_DEBUG
, "lo_getxattr(ino=%" PRIu64
", name=%s size=%zd)\n",
2518 value
= malloc(size
);
2524 sprintf(procname
, "%i", inode
->fd
);
2526 * It is not safe to open() non-regular/non-dir files in file server
2527 * unless O_PATH is used, so use that method for regular files/dir
2528 * only (as it seems giving less performance overhead).
2529 * Otherwise, call fchdir() to avoid open().
2531 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
2532 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
2536 ret
= fgetxattr(fd
, name
, value
, size
);
2538 /* fchdir should not fail here */
2539 assert(fchdir(lo
->proc_self_fd
) == 0);
2540 ret
= getxattr(procname
, name
, value
, size
);
2541 assert(fchdir(lo
->root
.fd
) == 0);
2552 fuse_reply_buf(req
, value
, ret
);
2554 fuse_reply_xattr(req
, ret
);
2563 lo_inode_put(lo
, &inode
);
2569 fuse_reply_err(req
, saverr
);
2570 g_free(mapped_name
);
2574 static void lo_listxattr(fuse_req_t req
, fuse_ino_t ino
, size_t size
)
2576 struct lo_data
*lo
= lo_data(req
);
2579 struct lo_inode
*inode
;
2584 inode
= lo_inode(req
, ino
);
2586 fuse_reply_err(req
, EBADF
);
2591 if (!lo_data(req
)->xattr
) {
2595 fuse_log(FUSE_LOG_DEBUG
, "lo_listxattr(ino=%" PRIu64
", size=%zd)\n", ino
,
2599 value
= malloc(size
);
2605 sprintf(procname
, "%i", inode
->fd
);
2606 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
2607 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
2611 ret
= flistxattr(fd
, value
, size
);
2613 /* fchdir should not fail here */
2614 assert(fchdir(lo
->proc_self_fd
) == 0);
2615 ret
= listxattr(procname
, value
, size
);
2616 assert(fchdir(lo
->root
.fd
) == 0);
2628 if (lo
->xattr_map_list
) {
2630 * Map the names back, some attributes might be dropped,
2631 * some shortened, but not increased, so we shouldn't
2634 size_t out_index
, in_index
;
2637 while (in_index
< ret
) {
2638 const char *map_out
;
2639 char *in_ptr
= value
+ in_index
;
2640 /* Length of current attribute name */
2641 size_t in_len
= strlen(value
+ in_index
) + 1;
2643 int mapret
= xattr_map_server(lo
, in_ptr
, &map_out
);
2644 if (mapret
!= -ENODATA
&& mapret
!= 0) {
2645 /* Shouldn't happen */
2650 /* Either unchanged, or truncated */
2652 if (map_out
!= in_ptr
) {
2653 /* +1 copies the NIL */
2654 out_len
= strlen(map_out
) + 1;
2660 * Move result along, may still be needed for an unchanged
2661 * entry if a previous entry was changed.
2663 memmove(value
+ out_index
, map_out
, out_len
);
2665 out_index
+= out_len
;
2674 fuse_reply_buf(req
, value
, ret
);
2677 * xattrmap only ever shortens the result,
2678 * so we don't need to do anything clever with the
2679 * allocation length here.
2681 fuse_reply_xattr(req
, ret
);
2690 lo_inode_put(lo
, &inode
);
2696 fuse_reply_err(req
, saverr
);
2700 static void lo_setxattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
,
2701 const char *value
, size_t size
, int flags
)
2706 struct lo_data
*lo
= lo_data(req
);
2707 struct lo_inode
*inode
;
2715 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
2717 fuse_reply_err(req
, -ret
);
2725 inode
= lo_inode(req
, ino
);
2727 fuse_reply_err(req
, EBADF
);
2728 g_free(mapped_name
);
2733 if (!lo_data(req
)->xattr
) {
2737 fuse_log(FUSE_LOG_DEBUG
, "lo_setxattr(ino=%" PRIu64
2738 ", name=%s value=%s size=%zd)\n", ino
, name
, value
, size
);
2740 sprintf(procname
, "%i", inode
->fd
);
2741 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
2742 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
2747 ret
= fsetxattr(fd
, name
, value
, size
, flags
);
2749 /* fchdir should not fail here */
2750 assert(fchdir(lo
->proc_self_fd
) == 0);
2751 ret
= setxattr(procname
, name
, value
, size
, flags
);
2752 assert(fchdir(lo
->root
.fd
) == 0);
2755 saverr
= ret
== -1 ? errno
: 0;
2762 lo_inode_put(lo
, &inode
);
2763 g_free(mapped_name
);
2764 fuse_reply_err(req
, saverr
);
2767 static void lo_removexattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
)
2772 struct lo_data
*lo
= lo_data(req
);
2773 struct lo_inode
*inode
;
2781 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
2783 fuse_reply_err(req
, -ret
);
2791 inode
= lo_inode(req
, ino
);
2793 fuse_reply_err(req
, EBADF
);
2794 g_free(mapped_name
);
2799 if (!lo_data(req
)->xattr
) {
2803 fuse_log(FUSE_LOG_DEBUG
, "lo_removexattr(ino=%" PRIu64
", name=%s)\n", ino
,
2806 sprintf(procname
, "%i", inode
->fd
);
2807 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
2808 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
2813 ret
= fremovexattr(fd
, name
);
2815 /* fchdir should not fail here */
2816 assert(fchdir(lo
->proc_self_fd
) == 0);
2817 ret
= removexattr(procname
, name
);
2818 assert(fchdir(lo
->root
.fd
) == 0);
2821 saverr
= ret
== -1 ? errno
: 0;
2828 lo_inode_put(lo
, &inode
);
2829 g_free(mapped_name
);
2830 fuse_reply_err(req
, saverr
);
2833 #ifdef HAVE_COPY_FILE_RANGE
2834 static void lo_copy_file_range(fuse_req_t req
, fuse_ino_t ino_in
, off_t off_in
,
2835 struct fuse_file_info
*fi_in
, fuse_ino_t ino_out
,
2836 off_t off_out
, struct fuse_file_info
*fi_out
,
2837 size_t len
, int flags
)
2842 in_fd
= lo_fi_fd(req
, fi_in
);
2843 out_fd
= lo_fi_fd(req
, fi_out
);
2845 fuse_log(FUSE_LOG_DEBUG
,
2846 "lo_copy_file_range(ino=%" PRIu64
"/fd=%d, "
2847 "off=%lu, ino=%" PRIu64
"/fd=%d, "
2848 "off=%lu, size=%zd, flags=0x%x)\n",
2849 ino_in
, in_fd
, off_in
, ino_out
, out_fd
, off_out
, len
, flags
);
2851 res
= copy_file_range(in_fd
, &off_in
, out_fd
, &off_out
, len
, flags
);
2853 fuse_reply_err(req
, errno
);
2855 fuse_reply_write(req
, res
);
2860 static void lo_lseek(fuse_req_t req
, fuse_ino_t ino
, off_t off
, int whence
,
2861 struct fuse_file_info
*fi
)
2866 res
= lseek(lo_fi_fd(req
, fi
), off
, whence
);
2868 fuse_reply_lseek(req
, res
);
2870 fuse_reply_err(req
, errno
);
2874 static void lo_destroy(void *userdata
)
2876 struct lo_data
*lo
= (struct lo_data
*)userdata
;
2878 pthread_mutex_lock(&lo
->mutex
);
2880 GHashTableIter iter
;
2881 gpointer key
, value
;
2883 g_hash_table_iter_init(&iter
, lo
->inodes
);
2884 if (!g_hash_table_iter_next(&iter
, &key
, &value
)) {
2888 struct lo_inode
*inode
= value
;
2889 unref_inode(lo
, inode
, inode
->nlookup
);
2891 pthread_mutex_unlock(&lo
->mutex
);
2894 static struct fuse_lowlevel_ops lo_oper
= {
2896 .lookup
= lo_lookup
,
2899 .symlink
= lo_symlink
,
2901 .unlink
= lo_unlink
,
2903 .rename
= lo_rename
,
2904 .forget
= lo_forget
,
2905 .forget_multi
= lo_forget_multi
,
2906 .getattr
= lo_getattr
,
2907 .setattr
= lo_setattr
,
2908 .readlink
= lo_readlink
,
2909 .opendir
= lo_opendir
,
2910 .readdir
= lo_readdir
,
2911 .readdirplus
= lo_readdirplus
,
2912 .releasedir
= lo_releasedir
,
2913 .fsyncdir
= lo_fsyncdir
,
2914 .create
= lo_create
,
2918 .release
= lo_release
,
2922 .write_buf
= lo_write_buf
,
2923 .statfs
= lo_statfs
,
2924 .fallocate
= lo_fallocate
,
2926 .getxattr
= lo_getxattr
,
2927 .listxattr
= lo_listxattr
,
2928 .setxattr
= lo_setxattr
,
2929 .removexattr
= lo_removexattr
,
2930 #ifdef HAVE_COPY_FILE_RANGE
2931 .copy_file_range
= lo_copy_file_range
,
2934 .destroy
= lo_destroy
,
2937 /* Print vhost-user.json backend program capabilities */
2938 static void print_capabilities(void)
2941 printf(" \"type\": \"fs\"\n");
2946 * Drop all Linux capabilities because the wait parent process only needs to
2947 * sit in waitpid(2) and terminate.
2949 static void setup_wait_parent_capabilities(void)
2951 capng_setpid(syscall(SYS_gettid
));
2952 capng_clear(CAPNG_SELECT_BOTH
);
2953 capng_apply(CAPNG_SELECT_BOTH
);
2957 * Move to a new mount, net, and pid namespaces to isolate this process.
2959 static void setup_namespaces(struct lo_data
*lo
, struct fuse_session
*se
)
2964 * Create a new pid namespace for *child* processes. We'll have to
2965 * fork in order to enter the new pid namespace. A new mount namespace
2966 * is also needed so that we can remount /proc for the new pid
2969 * Our UNIX domain sockets have been created. Now we can move to
2970 * an empty network namespace to prevent TCP/IP and other network
2971 * activity in case this process is compromised.
2973 if (unshare(CLONE_NEWPID
| CLONE_NEWNS
| CLONE_NEWNET
) != 0) {
2974 fuse_log(FUSE_LOG_ERR
, "unshare(CLONE_NEWPID | CLONE_NEWNS): %m\n");
2980 fuse_log(FUSE_LOG_ERR
, "fork() failed: %m\n");
2987 setup_wait_parent_capabilities();
2989 /* The parent waits for the child */
2991 waited
= waitpid(child
, &wstatus
, 0);
2992 } while (waited
< 0 && errno
== EINTR
&& !se
->exited
);
2994 /* We were terminated by a signal, see fuse_signals.c */
2999 if (WIFEXITED(wstatus
)) {
3000 exit(WEXITSTATUS(wstatus
));
3006 /* Send us SIGTERM when the parent thread terminates, see prctl(2) */
3007 prctl(PR_SET_PDEATHSIG
, SIGTERM
);
3010 * If the mounts have shared propagation then we want to opt out so our
3011 * mount changes don't affect the parent mount namespace.
3013 if (mount(NULL
, "/", NULL
, MS_REC
| MS_SLAVE
, NULL
) < 0) {
3014 fuse_log(FUSE_LOG_ERR
, "mount(/, MS_REC|MS_SLAVE): %m\n");
3018 /* The child must remount /proc to use the new pid namespace */
3019 if (mount("proc", "/proc", "proc",
3020 MS_NODEV
| MS_NOEXEC
| MS_NOSUID
| MS_RELATIME
, NULL
) < 0) {
3021 fuse_log(FUSE_LOG_ERR
, "mount(/proc): %m\n");
3026 * We only need /proc/self/fd. Prevent ".." from accessing parent
3027 * directories of /proc/self/fd by bind-mounting it over /proc. Since / was
3028 * previously remounted with MS_REC | MS_SLAVE this mount change only
3029 * affects our process.
3031 if (mount("/proc/self/fd", "/proc", NULL
, MS_BIND
, NULL
) < 0) {
3032 fuse_log(FUSE_LOG_ERR
, "mount(/proc/self/fd, MS_BIND): %m\n");
3036 /* Get the /proc (actually /proc/self/fd, see above) file descriptor */
3037 lo
->proc_self_fd
= open("/proc", O_PATH
);
3038 if (lo
->proc_self_fd
== -1) {
3039 fuse_log(FUSE_LOG_ERR
, "open(/proc, O_PATH): %m\n");
3045 * Capture the capability state, we'll need to restore this for individual
3046 * threads later; see load_capng.
3048 static void setup_capng(void)
3050 /* Note this accesses /proc so has to happen before the sandbox */
3051 if (capng_get_caps_process()) {
3052 fuse_log(FUSE_LOG_ERR
, "capng_get_caps_process\n");
3055 pthread_mutex_init(&cap
.mutex
, NULL
);
3056 pthread_mutex_lock(&cap
.mutex
);
3057 cap
.saved
= capng_save_state();
3059 fuse_log(FUSE_LOG_ERR
, "capng_save_state\n");
3062 pthread_mutex_unlock(&cap
.mutex
);
3065 static void cleanup_capng(void)
3069 pthread_mutex_destroy(&cap
.mutex
);
3074 * Make the source directory our root so symlinks cannot escape and no other
3075 * files are accessible. Assumes unshare(CLONE_NEWNS) was already called.
3077 static void setup_mounts(const char *source
)
3082 if (mount(source
, source
, NULL
, MS_BIND
| MS_REC
, NULL
) < 0) {
3083 fuse_log(FUSE_LOG_ERR
, "mount(%s, %s, MS_BIND): %m\n", source
, source
);
3087 /* This magic is based on lxc's lxc_pivot_root() */
3088 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
3090 fuse_log(FUSE_LOG_ERR
, "open(/): %m\n");
3094 newroot
= open(source
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
3096 fuse_log(FUSE_LOG_ERR
, "open(%s): %m\n", source
);
3100 if (fchdir(newroot
) < 0) {
3101 fuse_log(FUSE_LOG_ERR
, "fchdir(newroot): %m\n");
3105 if (syscall(__NR_pivot_root
, ".", ".") < 0) {
3106 fuse_log(FUSE_LOG_ERR
, "pivot_root(., .): %m\n");
3110 if (fchdir(oldroot
) < 0) {
3111 fuse_log(FUSE_LOG_ERR
, "fchdir(oldroot): %m\n");
3115 if (mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
) < 0) {
3116 fuse_log(FUSE_LOG_ERR
, "mount(., MS_SLAVE | MS_REC): %m\n");
3120 if (umount2(".", MNT_DETACH
) < 0) {
3121 fuse_log(FUSE_LOG_ERR
, "umount2(., MNT_DETACH): %m\n");
3125 if (fchdir(newroot
) < 0) {
3126 fuse_log(FUSE_LOG_ERR
, "fchdir(newroot): %m\n");
3135 * Only keep whitelisted capabilities that are needed for file system operation
3136 * The (possibly NULL) modcaps_in string passed in is free'd before exit.
3138 static void setup_capabilities(char *modcaps_in
)
3140 char *modcaps
= modcaps_in
;
3141 pthread_mutex_lock(&cap
.mutex
);
3142 capng_restore_state(&cap
.saved
);
3145 * Whitelist file system-related capabilities that are needed for a file
3146 * server to act like root. Drop everything else like networking and
3147 * sysadmin capabilities.
3150 * 1. CAP_LINUX_IMMUTABLE is not included because it's only used via ioctl
3151 * and we don't support that.
3152 * 2. CAP_MAC_OVERRIDE is not included because it only seems to be
3153 * used by the Smack LSM. Omit it until there is demand for it.
3155 capng_setpid(syscall(SYS_gettid
));
3156 capng_clear(CAPNG_SELECT_BOTH
);
3157 if (capng_updatev(CAPNG_ADD
, CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
3167 fuse_log(FUSE_LOG_ERR
, "%s: capng_updatev failed\n", __func__
);
3172 * The modcaps option is a colon separated list of caps,
3173 * each preceded by either + or -.
3179 char *next
= strchr(modcaps
, ':');
3185 switch (modcaps
[0]) {
3191 action
= CAPNG_DROP
;
3195 fuse_log(FUSE_LOG_ERR
,
3196 "%s: Expecting '+'/'-' in modcaps but found '%c'\n",
3197 __func__
, modcaps
[0]);
3200 cap
= capng_name_to_capability(modcaps
+ 1);
3202 fuse_log(FUSE_LOG_ERR
, "%s: Unknown capability '%s'\n", __func__
,
3206 if (capng_update(action
, CAPNG_PERMITTED
| CAPNG_EFFECTIVE
, cap
)) {
3207 fuse_log(FUSE_LOG_ERR
, "%s: capng_update failed for '%s'\n",
3216 if (capng_apply(CAPNG_SELECT_BOTH
)) {
3217 fuse_log(FUSE_LOG_ERR
, "%s: capng_apply failed\n", __func__
);
3221 cap
.saved
= capng_save_state();
3223 fuse_log(FUSE_LOG_ERR
, "%s: capng_save_state failed\n", __func__
);
3226 pthread_mutex_unlock(&cap
.mutex
);
3230 * Use chroot as a weaker sandbox for environments where the process is
3231 * launched without CAP_SYS_ADMIN.
3233 static void setup_chroot(struct lo_data
*lo
)
3235 lo
->proc_self_fd
= open("/proc/self/fd", O_PATH
);
3236 if (lo
->proc_self_fd
== -1) {
3237 fuse_log(FUSE_LOG_ERR
, "open(\"/proc/self/fd\", O_PATH): %m\n");
3242 * Make the shared directory the file system root so that FUSE_OPEN
3243 * (lo_open()) cannot escape the shared directory by opening a symlink.
3245 * The chroot(2) syscall is later disabled by seccomp and the
3246 * CAP_SYS_CHROOT capability is dropped so that tampering with the chroot
3249 * However, it's still possible to escape the chroot via lo->proc_self_fd
3250 * but that requires first gaining control of the process.
3252 if (chroot(lo
->source
) != 0) {
3253 fuse_log(FUSE_LOG_ERR
, "chroot(\"%s\"): %m\n", lo
->source
);
3257 /* Move into the chroot */
3258 if (chdir("/") != 0) {
3259 fuse_log(FUSE_LOG_ERR
, "chdir(\"/\"): %m\n");
3265 * Lock down this process to prevent access to other processes or files outside
3266 * source directory. This reduces the impact of arbitrary code execution bugs.
3268 static void setup_sandbox(struct lo_data
*lo
, struct fuse_session
*se
,
3271 if (lo
->sandbox
== SANDBOX_NAMESPACE
) {
3272 setup_namespaces(lo
, se
);
3273 setup_mounts(lo
->source
);
3278 setup_seccomp(enable_syslog
);
3279 setup_capabilities(g_strdup(lo
->modcaps
));
3282 /* Set the maximum number of open file descriptors */
3283 static void setup_nofile_rlimit(unsigned long rlimit_nofile
)
3285 struct rlimit rlim
= {
3286 .rlim_cur
= rlimit_nofile
,
3287 .rlim_max
= rlimit_nofile
,
3290 if (rlimit_nofile
== 0) {
3291 return; /* nothing to do */
3294 if (setrlimit(RLIMIT_NOFILE
, &rlim
) < 0) {
3295 /* Ignore SELinux denials */
3296 if (errno
== EPERM
) {
3300 fuse_log(FUSE_LOG_ERR
, "setrlimit(RLIMIT_NOFILE): %m\n");
3305 static void log_func(enum fuse_log_level level
, const char *fmt
, va_list ap
)
3307 g_autofree
char *localfmt
= NULL
;
3310 char sec_fmt
[sizeof "2020-12-07 18:17:54"];
3311 char zone_fmt
[sizeof "+0100"];
3313 if (current_log_level
< level
) {
3317 if (current_log_level
== FUSE_LOG_DEBUG
) {
3319 /* no timestamp needed */
3320 localfmt
= g_strdup_printf("[ID: %08ld] %s", syscall(__NR_gettid
),
3323 /* try formatting a broken-down timestamp */
3324 if (clock_gettime(CLOCK_REALTIME
, &ts
) != -1 &&
3325 localtime_r(&ts
.tv_sec
, &tm
) != NULL
&&
3326 strftime(sec_fmt
, sizeof sec_fmt
, "%Y-%m-%d %H:%M:%S",
3328 strftime(zone_fmt
, sizeof zone_fmt
, "%z", &tm
) != 0) {
3329 localfmt
= g_strdup_printf("[%s.%02ld%s] [ID: %08ld] %s",
3331 ts
.tv_nsec
/ (10L * 1000 * 1000),
3332 zone_fmt
, syscall(__NR_gettid
),
3335 /* fall back to a flat timestamp */
3336 localfmt
= g_strdup_printf("[%" PRId64
"] [ID: %08ld] %s",
3337 get_clock(), syscall(__NR_gettid
),
3345 int priority
= LOG_ERR
;
3347 case FUSE_LOG_EMERG
:
3348 priority
= LOG_EMERG
;
3350 case FUSE_LOG_ALERT
:
3351 priority
= LOG_ALERT
;
3354 priority
= LOG_CRIT
;
3359 case FUSE_LOG_WARNING
:
3360 priority
= LOG_WARNING
;
3362 case FUSE_LOG_NOTICE
:
3363 priority
= LOG_NOTICE
;
3366 priority
= LOG_INFO
;
3368 case FUSE_LOG_DEBUG
:
3369 priority
= LOG_DEBUG
;
3372 vsyslog(priority
, fmt
, ap
);
3374 vfprintf(stderr
, fmt
, ap
);
3378 static void setup_root(struct lo_data
*lo
, struct lo_inode
*root
)
3384 fd
= open("/", O_PATH
);
3386 fuse_log(FUSE_LOG_ERR
, "open(%s, O_PATH): %m\n", lo
->source
);
3390 res
= do_statx(lo
, fd
, "", &stat
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
,
3393 fuse_log(FUSE_LOG_ERR
, "fstatat(%s): %m\n", lo
->source
);
3397 root
->filetype
= S_IFDIR
;
3399 root
->key
.ino
= stat
.st_ino
;
3400 root
->key
.dev
= stat
.st_dev
;
3401 root
->key
.mnt_id
= mnt_id
;
3403 g_atomic_int_set(&root
->refcount
, 2);
3404 if (lo
->posix_lock
) {
3405 pthread_mutex_init(&root
->plock_mutex
, NULL
);
3406 root
->posix_locks
= g_hash_table_new_full(
3407 g_direct_hash
, g_direct_equal
, NULL
, posix_locks_value_destroy
);
3411 static guint
lo_key_hash(gconstpointer key
)
3413 const struct lo_key
*lkey
= key
;
3415 return (guint
)lkey
->ino
+ (guint
)lkey
->dev
+ (guint
)lkey
->mnt_id
;
3418 static gboolean
lo_key_equal(gconstpointer a
, gconstpointer b
)
3420 const struct lo_key
*la
= a
;
3421 const struct lo_key
*lb
= b
;
3423 return la
->ino
== lb
->ino
&& la
->dev
== lb
->dev
&& la
->mnt_id
== lb
->mnt_id
;
3426 static void fuse_lo_data_cleanup(struct lo_data
*lo
)
3429 g_hash_table_destroy(lo
->inodes
);
3432 if (lo
->root
.posix_locks
) {
3433 g_hash_table_destroy(lo
->root
.posix_locks
);
3435 lo_map_destroy(&lo
->fd_map
);
3436 lo_map_destroy(&lo
->dirp_map
);
3437 lo_map_destroy(&lo
->ino_map
);
3439 if (lo
->proc_self_fd
>= 0) {
3440 close(lo
->proc_self_fd
);
3443 if (lo
->root
.fd
>= 0) {
3452 int main(int argc
, char *argv
[])
3454 struct fuse_args args
= FUSE_ARGS_INIT(argc
, argv
);
3455 struct fuse_session
*se
;
3456 struct fuse_cmdline_opts opts
;
3457 struct lo_data lo
= {
3458 .sandbox
= SANDBOX_NAMESPACE
,
3462 .allow_direct_io
= 0,
3465 struct lo_map_elem
*root_elem
;
3466 struct lo_map_elem
*reserve_elem
;
3469 /* Initialize time conversion information for localtime_r(). */
3472 /* Don't mask creation mode, kernel already did that */
3475 qemu_init_exec_dir(argv
[0]);
3477 pthread_mutex_init(&lo
.mutex
, NULL
);
3478 lo
.inodes
= g_hash_table_new(lo_key_hash
, lo_key_equal
);
3480 lo
.root
.fuse_ino
= FUSE_ROOT_ID
;
3481 lo
.cache
= CACHE_AUTO
;
3484 * Set up the ino map like this:
3485 * [0] Reserved (will not be used)
3488 lo_map_init(&lo
.ino_map
);
3489 reserve_elem
= lo_map_reserve(&lo
.ino_map
, 0);
3490 if (!reserve_elem
) {
3491 fuse_log(FUSE_LOG_ERR
, "failed to alloc reserve_elem.\n");
3494 reserve_elem
->in_use
= false;
3495 root_elem
= lo_map_reserve(&lo
.ino_map
, lo
.root
.fuse_ino
);
3497 fuse_log(FUSE_LOG_ERR
, "failed to alloc root_elem.\n");
3500 root_elem
->inode
= &lo
.root
;
3502 lo_map_init(&lo
.dirp_map
);
3503 lo_map_init(&lo
.fd_map
);
3505 if (fuse_parse_cmdline(&args
, &opts
) != 0) {
3508 fuse_set_log_func(log_func
);
3509 use_syslog
= opts
.syslog
;
3511 openlog("virtiofsd", LOG_PID
, LOG_DAEMON
);
3514 if (opts
.show_help
) {
3515 printf("usage: %s [options]\n\n", argv
[0]);
3516 fuse_cmdline_help();
3517 printf(" -o source=PATH shared directory tree\n");
3518 fuse_lowlevel_help();
3521 } else if (opts
.show_version
) {
3522 fuse_lowlevel_version();
3525 } else if (opts
.print_capabilities
) {
3526 print_capabilities();
3531 if (fuse_opt_parse(&args
, &lo
, lo_opts
, NULL
) == -1) {
3535 if (opts
.log_level
!= 0) {
3536 current_log_level
= opts
.log_level
;
3538 /* default log level is INFO */
3539 current_log_level
= FUSE_LOG_INFO
;
3541 lo
.debug
= opts
.debug
;
3543 current_log_level
= FUSE_LOG_DEBUG
;
3549 res
= lstat(lo
.source
, &stat
);
3551 fuse_log(FUSE_LOG_ERR
, "failed to stat source (\"%s\"): %m\n",
3555 if (!S_ISDIR(stat
.st_mode
)) {
3556 fuse_log(FUSE_LOG_ERR
, "source is not a directory\n");
3560 lo
.source
= strdup("/");
3562 fuse_log(FUSE_LOG_ERR
, "failed to strdup source\n");
3568 parse_xattrmap(&lo
);
3571 if (!lo
.timeout_set
) {
3582 lo
.timeout
= 86400.0;
3585 } else if (lo
.timeout
< 0) {
3586 fuse_log(FUSE_LOG_ERR
, "timeout is negative (%lf)\n", lo
.timeout
);
3590 lo
.use_statx
= true;
3592 se
= fuse_session_new(&args
, &lo_oper
, sizeof(lo_oper
), &lo
);
3597 if (fuse_set_signal_handlers(se
) != 0) {
3601 if (fuse_session_mount(se
) != 0) {
3605 fuse_daemonize(opts
.foreground
);
3607 setup_nofile_rlimit(opts
.rlimit_nofile
);
3609 /* Must be before sandbox since it wants /proc */
3612 setup_sandbox(&lo
, se
, opts
.syslog
);
3614 setup_root(&lo
, &lo
.root
);
3615 /* Block until ctrl+c or fusermount -u */
3616 ret
= virtio_loop(se
);
3618 fuse_session_unmount(se
);
3621 fuse_remove_signal_handlers(se
);
3623 fuse_session_destroy(se
);
3625 fuse_opt_free_args(&args
);
3627 fuse_lo_data_cleanup(&lo
);