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 "qemu-version.h"
41 #include "qemu-common.h"
42 #include "fuse_virtio.h"
44 #include "fuse_lowlevel.h"
45 #include "standard-headers/linux/fuse.h"
50 #include <sys/mount.h>
51 #include <sys/prctl.h>
52 #include <sys/resource.h>
53 #include <sys/syscall.h>
55 #include <sys/xattr.h>
59 #include "qemu/cutils.h"
60 #include "passthrough_helpers.h"
61 #include "passthrough_seccomp.h"
63 /* Keep track of inode posix locks for each owner. */
64 struct lo_inode_plock
{
66 int fd
; /* fd for OFD locks */
71 struct lo_inode
*inode
;
79 /* Maps FUSE fh or ino values to internal objects */
81 struct lo_map_elem
*elems
;
96 * Atomic reference count for this object. The nlookup field holds a
97 * reference and release it when nlookup reaches 0.
104 * This counter keeps the inode alive during the FUSE session.
105 * Incremented when the FUSE inode number is sent in a reply
106 * (FUSE_LOOKUP, FUSE_READDIRPLUS, etc). Decremented when an inode is
107 * released by a FUSE_FORGET request.
109 * Note that this value is untrusted because the client can manipulate
110 * it arbitrarily using FUSE_FORGET requests.
112 * Protected by lo->mutex.
117 pthread_mutex_t plock_mutex
;
118 GHashTable
*posix_locks
; /* protected by lo_inode->plock_mutex */
140 typedef struct xattr_map_entry
{
147 pthread_mutex_t mutex
;
155 char *xattr_security_capability
;
162 int readdirplus_clear
;
164 int announce_submounts
;
166 struct lo_inode root
;
167 GHashTable
*inodes
; /* protected by lo->mutex */
168 struct lo_map ino_map
; /* protected by lo->mutex */
169 struct lo_map dirp_map
; /* protected by lo->mutex */
170 struct lo_map fd_map
; /* protected by lo->mutex */
171 XattrMapEntry
*xattr_map_list
;
172 size_t xattr_map_nentries
;
174 /* An O_PATH file descriptor to /proc/self/fd/ */
176 int user_killpriv_v2
, killpriv_v2
;
177 /* If set, virtiofsd is responsible for setting umask during creation */
179 int user_posix_acl
, posix_acl
;
182 static const struct fuse_opt lo_opts
[] = {
183 { "sandbox=namespace",
184 offsetof(struct lo_data
, sandbox
),
187 offsetof(struct lo_data
, sandbox
),
189 { "writeback", offsetof(struct lo_data
, writeback
), 1 },
190 { "no_writeback", offsetof(struct lo_data
, writeback
), 0 },
191 { "source=%s", offsetof(struct lo_data
, source
), 0 },
192 { "flock", offsetof(struct lo_data
, flock
), 1 },
193 { "no_flock", offsetof(struct lo_data
, flock
), 0 },
194 { "posix_lock", offsetof(struct lo_data
, posix_lock
), 1 },
195 { "no_posix_lock", offsetof(struct lo_data
, posix_lock
), 0 },
196 { "xattr", offsetof(struct lo_data
, xattr
), 1 },
197 { "no_xattr", offsetof(struct lo_data
, xattr
), 0 },
198 { "xattrmap=%s", offsetof(struct lo_data
, xattrmap
), 0 },
199 { "modcaps=%s", offsetof(struct lo_data
, modcaps
), 0 },
200 { "timeout=%lf", offsetof(struct lo_data
, timeout
), 0 },
201 { "timeout=", offsetof(struct lo_data
, timeout_set
), 1 },
202 { "cache=none", offsetof(struct lo_data
, cache
), CACHE_NONE
},
203 { "cache=auto", offsetof(struct lo_data
, cache
), CACHE_AUTO
},
204 { "cache=always", offsetof(struct lo_data
, cache
), CACHE_ALWAYS
},
205 { "readdirplus", offsetof(struct lo_data
, readdirplus_set
), 1 },
206 { "no_readdirplus", offsetof(struct lo_data
, readdirplus_clear
), 1 },
207 { "allow_direct_io", offsetof(struct lo_data
, allow_direct_io
), 1 },
208 { "no_allow_direct_io", offsetof(struct lo_data
, allow_direct_io
), 0 },
209 { "announce_submounts", offsetof(struct lo_data
, announce_submounts
), 1 },
210 { "killpriv_v2", offsetof(struct lo_data
, user_killpriv_v2
), 1 },
211 { "no_killpriv_v2", offsetof(struct lo_data
, user_killpriv_v2
), 0 },
212 { "posix_acl", offsetof(struct lo_data
, user_posix_acl
), 1 },
213 { "no_posix_acl", offsetof(struct lo_data
, user_posix_acl
), 0 },
216 static bool use_syslog
= false;
217 static int current_log_level
;
218 static void unref_inode_lolocked(struct lo_data
*lo
, struct lo_inode
*inode
,
222 pthread_mutex_t mutex
;
225 /* That we loaded cap-ng in the current thread from the saved */
226 static __thread
bool cap_loaded
= 0;
228 static struct lo_inode
*lo_find(struct lo_data
*lo
, struct stat
*st
,
230 static int xattr_map_client(const struct lo_data
*lo
, const char *client_name
,
233 static bool is_dot_or_dotdot(const char *name
)
235 return name
[0] == '.' &&
236 (name
[1] == '\0' || (name
[1] == '.' && name
[2] == '\0'));
239 /* Is `path` a single path component that is not "." or ".."? */
240 static bool is_safe_path_component(const char *path
)
242 if (strchr(path
, '/')) {
246 return !is_dot_or_dotdot(path
);
249 static bool is_empty(const char *name
)
251 return name
[0] == '\0';
254 static struct lo_data
*lo_data(fuse_req_t req
)
256 return (struct lo_data
*)fuse_req_userdata(req
);
260 * Load capng's state from our saved state if the current thread
261 * hadn't previously been loaded.
262 * returns 0 on success
264 static int load_capng(void)
267 pthread_mutex_lock(&cap
.mutex
);
268 capng_restore_state(&cap
.saved
);
270 * restore_state free's the saved copy
273 cap
.saved
= capng_save_state();
275 pthread_mutex_unlock(&cap
.mutex
);
276 fuse_log(FUSE_LOG_ERR
, "capng_save_state (thread)\n");
279 pthread_mutex_unlock(&cap
.mutex
);
282 * We want to use the loaded state for our pid,
285 capng_setpid(syscall(SYS_gettid
));
292 * Helpers for dropping and regaining effective capabilities. Returns 0
293 * on success, error otherwise
295 static int drop_effective_cap(const char *cap_name
, bool *cap_dropped
)
299 cap
= capng_name_to_capability(cap_name
);
302 fuse_log(FUSE_LOG_ERR
, "capng_name_to_capability(%s) failed:%s\n",
303 cap_name
, strerror(errno
));
309 fuse_log(FUSE_LOG_ERR
, "load_capng() failed\n");
313 /* We dont have this capability in effective set already. */
314 if (!capng_have_capability(CAPNG_EFFECTIVE
, cap
)) {
319 if (capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, cap
)) {
321 fuse_log(FUSE_LOG_ERR
, "capng_update(DROP,) failed\n");
325 if (capng_apply(CAPNG_SELECT_CAPS
)) {
327 fuse_log(FUSE_LOG_ERR
, "drop:capng_apply() failed\n");
340 static int gain_effective_cap(const char *cap_name
)
345 cap
= capng_name_to_capability(cap_name
);
348 fuse_log(FUSE_LOG_ERR
, "capng_name_to_capability(%s) failed:%s\n",
349 cap_name
, strerror(errno
));
355 fuse_log(FUSE_LOG_ERR
, "load_capng() failed\n");
359 if (capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, cap
)) {
361 fuse_log(FUSE_LOG_ERR
, "capng_update(ADD,) failed\n");
365 if (capng_apply(CAPNG_SELECT_CAPS
)) {
367 fuse_log(FUSE_LOG_ERR
, "gain:capng_apply() failed\n");
377 * The host kernel normally drops security.capability xattr's on
378 * any write, however if we're remapping xattr names we need to drop
379 * whatever the clients security.capability is actually stored as.
381 static int drop_security_capability(const struct lo_data
*lo
, int fd
)
383 if (!lo
->xattr_security_capability
) {
384 /* We didn't remap the name, let the host kernel do it */
387 if (!fremovexattr(fd
, lo
->xattr_security_capability
)) {
394 /* Attribute didn't exist, that's fine */
398 /* FS didn't support attribute anyway, also fine */
402 /* Hmm other error */
407 static void lo_map_init(struct lo_map
*map
)
414 static void lo_map_destroy(struct lo_map
*map
)
419 static int lo_map_grow(struct lo_map
*map
, size_t new_nelems
)
421 struct lo_map_elem
*new_elems
;
424 if (new_nelems
<= map
->nelems
) {
428 new_elems
= g_try_realloc_n(map
->elems
, new_nelems
, sizeof(map
->elems
[0]));
433 for (i
= map
->nelems
; i
< new_nelems
; i
++) {
434 new_elems
[i
].freelist
= i
+ 1;
435 new_elems
[i
].in_use
= false;
437 new_elems
[new_nelems
- 1].freelist
= -1;
439 map
->elems
= new_elems
;
440 map
->freelist
= map
->nelems
;
441 map
->nelems
= new_nelems
;
445 static struct lo_map_elem
*lo_map_alloc_elem(struct lo_map
*map
)
447 struct lo_map_elem
*elem
;
449 if (map
->freelist
== -1 && !lo_map_grow(map
, map
->nelems
+ 256)) {
453 elem
= &map
->elems
[map
->freelist
];
454 map
->freelist
= elem
->freelist
;
461 static struct lo_map_elem
*lo_map_reserve(struct lo_map
*map
, size_t key
)
465 if (!lo_map_grow(map
, key
+ 1)) {
469 for (prev
= &map
->freelist
; *prev
!= -1;
470 prev
= &map
->elems
[*prev
].freelist
) {
472 struct lo_map_elem
*elem
= &map
->elems
[key
];
474 *prev
= elem
->freelist
;
482 static struct lo_map_elem
*lo_map_get(struct lo_map
*map
, size_t key
)
484 if (key
>= map
->nelems
) {
487 if (!map
->elems
[key
].in_use
) {
490 return &map
->elems
[key
];
493 static void lo_map_remove(struct lo_map
*map
, size_t key
)
495 struct lo_map_elem
*elem
;
497 if (key
>= map
->nelems
) {
501 elem
= &map
->elems
[key
];
506 elem
->in_use
= false;
508 elem
->freelist
= map
->freelist
;
512 /* Assumes lo->mutex is held */
513 static ssize_t
lo_add_fd_mapping(struct lo_data
*lo
, int fd
)
515 struct lo_map_elem
*elem
;
517 elem
= lo_map_alloc_elem(&lo
->fd_map
);
523 return elem
- lo
->fd_map
.elems
;
526 /* Assumes lo->mutex is held */
527 static ssize_t
lo_add_dirp_mapping(fuse_req_t req
, struct lo_dirp
*dirp
)
529 struct lo_map_elem
*elem
;
531 elem
= lo_map_alloc_elem(&lo_data(req
)->dirp_map
);
537 return elem
- lo_data(req
)->dirp_map
.elems
;
540 /* Assumes lo->mutex is held */
541 static ssize_t
lo_add_inode_mapping(fuse_req_t req
, struct lo_inode
*inode
)
543 struct lo_map_elem
*elem
;
545 elem
= lo_map_alloc_elem(&lo_data(req
)->ino_map
);
551 return elem
- lo_data(req
)->ino_map
.elems
;
554 static void lo_inode_put(struct lo_data
*lo
, struct lo_inode
**inodep
)
556 struct lo_inode
*inode
= *inodep
;
564 if (g_atomic_int_dec_and_test(&inode
->refcount
)) {
570 /* Caller must release refcount using lo_inode_put() */
571 static struct lo_inode
*lo_inode(fuse_req_t req
, fuse_ino_t ino
)
573 struct lo_data
*lo
= lo_data(req
);
574 struct lo_map_elem
*elem
;
576 pthread_mutex_lock(&lo
->mutex
);
577 elem
= lo_map_get(&lo
->ino_map
, ino
);
579 g_atomic_int_inc(&elem
->inode
->refcount
);
581 pthread_mutex_unlock(&lo
->mutex
);
591 * TODO Remove this helper and force callers to hold an inode refcount until
592 * they are done with the fd. This will be done in a later patch to make
595 static int lo_fd(fuse_req_t req
, fuse_ino_t ino
)
597 struct lo_inode
*inode
= lo_inode(req
, ino
);
605 lo_inode_put(lo_data(req
), &inode
);
610 * Open a file descriptor for an inode. Returns -EBADF if the inode is not a
611 * regular file or a directory.
613 * Use this helper function instead of raw openat(2) to prevent security issues
614 * when a malicious client opens special files such as block device nodes.
615 * Symlink inodes are also rejected since symlinks must already have been
616 * traversed on the client side.
618 static int lo_inode_open(struct lo_data
*lo
, struct lo_inode
*inode
,
621 g_autofree
char *fd_str
= g_strdup_printf("%d", inode
->fd
);
624 if (!S_ISREG(inode
->filetype
) && !S_ISDIR(inode
->filetype
)) {
629 * The file is a symlink so O_NOFOLLOW must be ignored. We checked earlier
630 * that the inode is not a special file but if an external process races
631 * with us then symlinks are traversed here. It is not possible to escape
632 * the shared directory since it is mounted as "/" though.
634 fd
= openat(lo
->proc_self_fd
, fd_str
, open_flags
& ~O_NOFOLLOW
);
641 static void lo_init(void *userdata
, struct fuse_conn_info
*conn
)
643 struct lo_data
*lo
= (struct lo_data
*)userdata
;
645 if (conn
->capable
& FUSE_CAP_EXPORT_SUPPORT
) {
646 conn
->want
|= FUSE_CAP_EXPORT_SUPPORT
;
649 if (lo
->writeback
&& conn
->capable
& FUSE_CAP_WRITEBACK_CACHE
) {
650 fuse_log(FUSE_LOG_DEBUG
, "lo_init: activating writeback\n");
651 conn
->want
|= FUSE_CAP_WRITEBACK_CACHE
;
653 if (conn
->capable
& FUSE_CAP_FLOCK_LOCKS
) {
655 fuse_log(FUSE_LOG_DEBUG
, "lo_init: activating flock locks\n");
656 conn
->want
|= FUSE_CAP_FLOCK_LOCKS
;
658 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling flock locks\n");
659 conn
->want
&= ~FUSE_CAP_FLOCK_LOCKS
;
663 if (conn
->capable
& FUSE_CAP_POSIX_LOCKS
) {
664 if (lo
->posix_lock
) {
665 fuse_log(FUSE_LOG_DEBUG
, "lo_init: activating posix locks\n");
666 conn
->want
|= FUSE_CAP_POSIX_LOCKS
;
668 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling posix locks\n");
669 conn
->want
&= ~FUSE_CAP_POSIX_LOCKS
;
673 if ((lo
->cache
== CACHE_NONE
&& !lo
->readdirplus_set
) ||
674 lo
->readdirplus_clear
) {
675 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling readdirplus\n");
676 conn
->want
&= ~FUSE_CAP_READDIRPLUS
;
679 if (!(conn
->capable
& FUSE_CAP_SUBMOUNTS
) && lo
->announce_submounts
) {
680 fuse_log(FUSE_LOG_WARNING
, "lo_init: Cannot announce submounts, client "
681 "does not support it\n");
682 lo
->announce_submounts
= false;
685 if (lo
->user_killpriv_v2
== 1) {
687 * User explicitly asked for this option. Enable it unconditionally.
688 * If connection does not have this capability, it should fail
691 fuse_log(FUSE_LOG_DEBUG
, "lo_init: enabling killpriv_v2\n");
692 conn
->want
|= FUSE_CAP_HANDLE_KILLPRIV_V2
;
694 } else if (lo
->user_killpriv_v2
== -1 &&
695 conn
->capable
& FUSE_CAP_HANDLE_KILLPRIV_V2
) {
697 * User did not specify a value for killpriv_v2. By default enable it
698 * if connection offers this capability
700 fuse_log(FUSE_LOG_DEBUG
, "lo_init: enabling killpriv_v2\n");
701 conn
->want
|= FUSE_CAP_HANDLE_KILLPRIV_V2
;
705 * Either user specified to disable killpriv_v2, or connection does
706 * not offer this capability. Disable killpriv_v2 in both the cases
708 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling killpriv_v2\n");
709 conn
->want
&= ~FUSE_CAP_HANDLE_KILLPRIV_V2
;
713 if (lo
->user_posix_acl
== 1) {
715 * User explicitly asked for this option. Enable it unconditionally.
716 * If connection does not have this capability, print error message
717 * now. It will fail later in fuse_lowlevel.c
719 if (!(conn
->capable
& FUSE_CAP_POSIX_ACL
) ||
720 !(conn
->capable
& FUSE_CAP_DONT_MASK
) ||
721 !(conn
->capable
& FUSE_CAP_SETXATTR_EXT
)) {
722 fuse_log(FUSE_LOG_ERR
, "lo_init: Can not enable posix acl."
723 " kernel does not support FUSE_POSIX_ACL, FUSE_DONT_MASK"
724 " or FUSE_SETXATTR_EXT capability.\n");
726 fuse_log(FUSE_LOG_DEBUG
, "lo_init: enabling posix acl\n");
729 conn
->want
|= FUSE_CAP_POSIX_ACL
| FUSE_CAP_DONT_MASK
|
730 FUSE_CAP_SETXATTR_EXT
;
731 lo
->change_umask
= true;
732 lo
->posix_acl
= true;
734 /* User either did not specify anything or wants it disabled */
735 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling posix_acl\n");
736 conn
->want
&= ~FUSE_CAP_POSIX_ACL
;
740 static void lo_getattr(fuse_req_t req
, fuse_ino_t ino
,
741 struct fuse_file_info
*fi
)
745 struct lo_data
*lo
= lo_data(req
);
750 fstatat(lo_fd(req
, ino
), "", &buf
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
752 return (void)fuse_reply_err(req
, errno
);
755 fuse_reply_attr(req
, &buf
, lo
->timeout
);
758 static int lo_fi_fd(fuse_req_t req
, struct fuse_file_info
*fi
)
760 struct lo_data
*lo
= lo_data(req
);
761 struct lo_map_elem
*elem
;
763 pthread_mutex_lock(&lo
->mutex
);
764 elem
= lo_map_get(&lo
->fd_map
, fi
->fh
);
765 pthread_mutex_unlock(&lo
->mutex
);
774 static void lo_setattr(fuse_req_t req
, fuse_ino_t ino
, struct stat
*attr
,
775 int valid
, struct fuse_file_info
*fi
)
779 struct lo_data
*lo
= lo_data(req
);
780 struct lo_inode
*inode
;
785 inode
= lo_inode(req
, ino
);
787 fuse_reply_err(req
, EBADF
);
793 /* If fi->fh is invalid we'll report EBADF later */
795 fd
= lo_fi_fd(req
, fi
);
798 if (valid
& FUSE_SET_ATTR_MODE
) {
800 res
= fchmod(fd
, attr
->st_mode
);
802 sprintf(procname
, "%i", ifd
);
803 res
= fchmodat(lo
->proc_self_fd
, procname
, attr
->st_mode
, 0);
810 if (valid
& (FUSE_SET_ATTR_UID
| FUSE_SET_ATTR_GID
)) {
811 uid_t uid
= (valid
& FUSE_SET_ATTR_UID
) ? attr
->st_uid
: (uid_t
)-1;
812 gid_t gid
= (valid
& FUSE_SET_ATTR_GID
) ? attr
->st_gid
: (gid_t
)-1;
814 saverr
= drop_security_capability(lo
, ifd
);
819 res
= fchownat(ifd
, "", uid
, gid
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
825 if (valid
& FUSE_SET_ATTR_SIZE
) {
828 bool cap_fsetid_dropped
= false;
830 kill_suidgid
= lo
->killpriv_v2
&& (valid
& FUSE_SET_ATTR_KILL_SUIDGID
);
834 truncfd
= lo_inode_open(lo
, inode
, O_RDWR
);
841 saverr
= drop_security_capability(lo
, truncfd
);
850 res
= drop_effective_cap("FSETID", &cap_fsetid_dropped
);
860 res
= ftruncate(truncfd
, attr
->st_size
);
861 saverr
= res
== -1 ? errno
: 0;
863 if (cap_fsetid_dropped
) {
864 if (gain_effective_cap("FSETID")) {
865 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_FSETID\n");
875 if (valid
& (FUSE_SET_ATTR_ATIME
| FUSE_SET_ATTR_MTIME
)) {
876 struct timespec tv
[2];
880 tv
[0].tv_nsec
= UTIME_OMIT
;
881 tv
[1].tv_nsec
= UTIME_OMIT
;
883 if (valid
& FUSE_SET_ATTR_ATIME_NOW
) {
884 tv
[0].tv_nsec
= UTIME_NOW
;
885 } else if (valid
& FUSE_SET_ATTR_ATIME
) {
886 tv
[0] = attr
->st_atim
;
889 if (valid
& FUSE_SET_ATTR_MTIME_NOW
) {
890 tv
[1].tv_nsec
= UTIME_NOW
;
891 } else if (valid
& FUSE_SET_ATTR_MTIME
) {
892 tv
[1] = attr
->st_mtim
;
896 res
= futimens(fd
, tv
);
898 sprintf(procname
, "%i", inode
->fd
);
899 res
= utimensat(lo
->proc_self_fd
, procname
, tv
, 0);
906 lo_inode_put(lo
, &inode
);
908 return lo_getattr(req
, ino
, fi
);
911 lo_inode_put(lo
, &inode
);
912 fuse_reply_err(req
, saverr
);
915 static struct lo_inode
*lo_find(struct lo_data
*lo
, struct stat
*st
,
919 struct lo_key key
= {
925 pthread_mutex_lock(&lo
->mutex
);
926 p
= g_hash_table_lookup(lo
->inodes
, &key
);
928 assert(p
->nlookup
> 0);
930 g_atomic_int_inc(&p
->refcount
);
932 pthread_mutex_unlock(&lo
->mutex
);
937 /* value_destroy_func for posix_locks GHashTable */
938 static void posix_locks_value_destroy(gpointer data
)
940 struct lo_inode_plock
*plock
= data
;
943 * We had used open() for locks and had only one fd. So
944 * closing this fd should release all OFD locks.
950 static int do_statx(struct lo_data
*lo
, int dirfd
, const char *pathname
,
951 struct stat
*statbuf
, int flags
, uint64_t *mnt_id
)
955 #if defined(CONFIG_STATX) && defined(STATX_MNT_ID)
957 struct statx statxbuf
;
959 res
= statx(dirfd
, pathname
, flags
, STATX_BASIC_STATS
| STATX_MNT_ID
,
962 memset(statbuf
, 0, sizeof(*statbuf
));
963 statbuf
->st_dev
= makedev(statxbuf
.stx_dev_major
,
964 statxbuf
.stx_dev_minor
);
965 statbuf
->st_ino
= statxbuf
.stx_ino
;
966 statbuf
->st_mode
= statxbuf
.stx_mode
;
967 statbuf
->st_nlink
= statxbuf
.stx_nlink
;
968 statbuf
->st_uid
= statxbuf
.stx_uid
;
969 statbuf
->st_gid
= statxbuf
.stx_gid
;
970 statbuf
->st_rdev
= makedev(statxbuf
.stx_rdev_major
,
971 statxbuf
.stx_rdev_minor
);
972 statbuf
->st_size
= statxbuf
.stx_size
;
973 statbuf
->st_blksize
= statxbuf
.stx_blksize
;
974 statbuf
->st_blocks
= statxbuf
.stx_blocks
;
975 statbuf
->st_atim
.tv_sec
= statxbuf
.stx_atime
.tv_sec
;
976 statbuf
->st_atim
.tv_nsec
= statxbuf
.stx_atime
.tv_nsec
;
977 statbuf
->st_mtim
.tv_sec
= statxbuf
.stx_mtime
.tv_sec
;
978 statbuf
->st_mtim
.tv_nsec
= statxbuf
.stx_mtime
.tv_nsec
;
979 statbuf
->st_ctim
.tv_sec
= statxbuf
.stx_ctime
.tv_sec
;
980 statbuf
->st_ctim
.tv_nsec
= statxbuf
.stx_ctime
.tv_nsec
;
982 if (statxbuf
.stx_mask
& STATX_MNT_ID
) {
983 *mnt_id
= statxbuf
.stx_mnt_id
;
988 } else if (errno
!= ENOSYS
) {
991 lo
->use_statx
= false;
995 res
= fstatat(dirfd
, pathname
, statbuf
, flags
);
1005 * Increments nlookup on the inode on success. unref_inode_lolocked() must be
1006 * called eventually to decrement nlookup again. If inodep is non-NULL, the
1007 * inode pointer is stored and the caller must call lo_inode_put().
1009 static int lo_do_lookup(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1010 struct fuse_entry_param
*e
,
1011 struct lo_inode
**inodep
)
1017 struct lo_data
*lo
= lo_data(req
);
1018 struct lo_inode
*inode
= NULL
;
1019 struct lo_inode
*dir
= lo_inode(req
, parent
);
1022 *inodep
= NULL
; /* in case there is an error */
1026 * name_to_handle_at() and open_by_handle_at() can reach here with fuse
1027 * mount point in guest, but we don't have its inode info in the
1034 memset(e
, 0, sizeof(*e
));
1035 e
->attr_timeout
= lo
->timeout
;
1036 e
->entry_timeout
= lo
->timeout
;
1038 /* Do not allow escaping root directory */
1039 if (dir
== &lo
->root
&& strcmp(name
, "..") == 0) {
1043 newfd
= openat(dir
->fd
, name
, O_PATH
| O_NOFOLLOW
);
1048 res
= do_statx(lo
, newfd
, "", &e
->attr
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
,
1054 if (S_ISDIR(e
->attr
.st_mode
) && lo
->announce_submounts
&&
1055 (e
->attr
.st_dev
!= dir
->key
.dev
|| mnt_id
!= dir
->key
.mnt_id
)) {
1056 e
->attr_flags
|= FUSE_ATTR_SUBMOUNT
;
1059 inode
= lo_find(lo
, &e
->attr
, mnt_id
);
1063 inode
= calloc(1, sizeof(struct lo_inode
));
1068 /* cache only filetype */
1069 inode
->filetype
= (e
->attr
.st_mode
& S_IFMT
);
1072 * One for the caller and one for nlookup (released in
1073 * unref_inode_lolocked())
1075 g_atomic_int_set(&inode
->refcount
, 2);
1079 inode
->key
.ino
= e
->attr
.st_ino
;
1080 inode
->key
.dev
= e
->attr
.st_dev
;
1081 inode
->key
.mnt_id
= mnt_id
;
1082 if (lo
->posix_lock
) {
1083 pthread_mutex_init(&inode
->plock_mutex
, NULL
);
1084 inode
->posix_locks
= g_hash_table_new_full(
1085 g_direct_hash
, g_direct_equal
, NULL
, posix_locks_value_destroy
);
1087 pthread_mutex_lock(&lo
->mutex
);
1088 inode
->fuse_ino
= lo_add_inode_mapping(req
, inode
);
1089 g_hash_table_insert(lo
->inodes
, &inode
->key
, inode
);
1090 pthread_mutex_unlock(&lo
->mutex
);
1092 e
->ino
= inode
->fuse_ino
;
1094 /* Transfer ownership of inode pointer to caller or drop it */
1098 lo_inode_put(lo
, &inode
);
1101 lo_inode_put(lo
, &dir
);
1103 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
1104 name
, (unsigned long long)e
->ino
);
1113 lo_inode_put(lo
, &inode
);
1114 lo_inode_put(lo
, &dir
);
1118 static void lo_lookup(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
1120 struct fuse_entry_param e
;
1123 fuse_log(FUSE_LOG_DEBUG
, "lo_lookup(parent=%" PRIu64
", name=%s)\n", parent
,
1126 if (is_empty(name
)) {
1127 fuse_reply_err(req
, ENOENT
);
1132 * Don't use is_safe_path_component(), allow "." and ".." for NFS export
1135 if (strchr(name
, '/')) {
1136 fuse_reply_err(req
, EINVAL
);
1140 err
= lo_do_lookup(req
, parent
, name
, &e
, NULL
);
1142 fuse_reply_err(req
, err
);
1144 fuse_reply_entry(req
, &e
);
1149 * On some archs, setres*id is limited to 2^16 but they
1150 * provide setres*id32 variants that allow 2^32.
1151 * Others just let setres*id do 2^32 anyway.
1153 #ifdef SYS_setresgid32
1154 #define OURSYS_setresgid SYS_setresgid32
1156 #define OURSYS_setresgid SYS_setresgid
1159 #ifdef SYS_setresuid32
1160 #define OURSYS_setresuid SYS_setresuid32
1162 #define OURSYS_setresuid SYS_setresuid
1165 static void drop_supplementary_groups(void)
1169 ret
= getgroups(0, NULL
);
1171 fuse_log(FUSE_LOG_ERR
, "getgroups() failed with error=%d:%s\n",
1172 errno
, strerror(errno
));
1180 /* Drop all supplementary groups. We should not need it */
1181 ret
= setgroups(0, NULL
);
1183 fuse_log(FUSE_LOG_ERR
, "setgroups() failed with error=%d:%s\n",
1184 errno
, strerror(errno
));
1190 * Change to uid/gid of caller so that file is created with
1191 * ownership of caller.
1192 * TODO: What about selinux context?
1194 static int lo_change_cred(fuse_req_t req
, struct lo_cred
*old
,
1199 old
->euid
= geteuid();
1200 old
->egid
= getegid();
1202 res
= syscall(OURSYS_setresgid
, -1, fuse_req_ctx(req
)->gid
, -1);
1207 res
= syscall(OURSYS_setresuid
, -1, fuse_req_ctx(req
)->uid
, -1);
1209 int errno_save
= errno
;
1211 syscall(OURSYS_setresgid
, -1, old
->egid
, -1);
1216 old
->umask
= umask(req
->ctx
.umask
);
1221 /* Regain Privileges */
1222 static void lo_restore_cred(struct lo_cred
*old
, bool restore_umask
)
1226 res
= syscall(OURSYS_setresuid
, -1, old
->euid
, -1);
1228 fuse_log(FUSE_LOG_ERR
, "seteuid(%u): %m\n", old
->euid
);
1232 res
= syscall(OURSYS_setresgid
, -1, old
->egid
, -1);
1234 fuse_log(FUSE_LOG_ERR
, "setegid(%u): %m\n", old
->egid
);
1243 * A helper to change cred and drop capability. Returns 0 on success and
1246 static int lo_drop_cap_change_cred(fuse_req_t req
, struct lo_cred
*old
,
1247 bool change_umask
, const char *cap_name
,
1255 ret
= drop_effective_cap(cap_name
, &__cap_dropped
);
1260 ret
= lo_change_cred(req
, old
, change_umask
);
1262 if (__cap_dropped
) {
1263 if (gain_effective_cap(cap_name
)) {
1264 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_%s\n", cap_name
);
1270 *cap_dropped
= __cap_dropped
;
1275 static void lo_restore_cred_gain_cap(struct lo_cred
*old
, bool restore_umask
,
1276 const char *cap_name
)
1280 lo_restore_cred(old
, restore_umask
);
1282 if (gain_effective_cap(cap_name
)) {
1283 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_%s\n", cap_name
);
1287 static void lo_mknod_symlink(fuse_req_t req
, fuse_ino_t parent
,
1288 const char *name
, mode_t mode
, dev_t rdev
,
1293 struct lo_data
*lo
= lo_data(req
);
1294 struct lo_inode
*dir
;
1295 struct fuse_entry_param e
;
1296 struct lo_cred old
= {};
1298 if (is_empty(name
)) {
1299 fuse_reply_err(req
, ENOENT
);
1303 if (!is_safe_path_component(name
)) {
1304 fuse_reply_err(req
, EINVAL
);
1308 dir
= lo_inode(req
, parent
);
1310 fuse_reply_err(req
, EBADF
);
1314 saverr
= lo_change_cred(req
, &old
, lo
->change_umask
&& !S_ISLNK(mode
));
1319 res
= mknod_wrapper(dir
->fd
, name
, link
, mode
, rdev
);
1323 lo_restore_cred(&old
, lo
->change_umask
&& !S_ISLNK(mode
));
1329 saverr
= lo_do_lookup(req
, parent
, name
, &e
, NULL
);
1334 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
1335 name
, (unsigned long long)e
.ino
);
1337 fuse_reply_entry(req
, &e
);
1338 lo_inode_put(lo
, &dir
);
1342 lo_inode_put(lo
, &dir
);
1343 fuse_reply_err(req
, saverr
);
1346 static void lo_mknod(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1347 mode_t mode
, dev_t rdev
)
1349 lo_mknod_symlink(req
, parent
, name
, mode
, rdev
, NULL
);
1352 static void lo_mkdir(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1355 lo_mknod_symlink(req
, parent
, name
, S_IFDIR
| mode
, 0, NULL
);
1358 static void lo_symlink(fuse_req_t req
, const char *link
, fuse_ino_t parent
,
1361 lo_mknod_symlink(req
, parent
, name
, S_IFLNK
, 0, link
);
1364 static void lo_link(fuse_req_t req
, fuse_ino_t ino
, fuse_ino_t parent
,
1368 struct lo_data
*lo
= lo_data(req
);
1369 struct lo_inode
*parent_inode
;
1370 struct lo_inode
*inode
;
1371 struct fuse_entry_param e
;
1375 if (is_empty(name
)) {
1376 fuse_reply_err(req
, ENOENT
);
1380 if (!is_safe_path_component(name
)) {
1381 fuse_reply_err(req
, EINVAL
);
1385 parent_inode
= lo_inode(req
, parent
);
1386 inode
= lo_inode(req
, ino
);
1387 if (!parent_inode
|| !inode
) {
1392 memset(&e
, 0, sizeof(struct fuse_entry_param
));
1393 e
.attr_timeout
= lo
->timeout
;
1394 e
.entry_timeout
= lo
->timeout
;
1396 sprintf(procname
, "%i", inode
->fd
);
1397 res
= linkat(lo
->proc_self_fd
, procname
, parent_inode
->fd
, name
,
1403 res
= fstatat(inode
->fd
, "", &e
.attr
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
1408 pthread_mutex_lock(&lo
->mutex
);
1410 pthread_mutex_unlock(&lo
->mutex
);
1411 e
.ino
= inode
->fuse_ino
;
1413 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
1414 name
, (unsigned long long)e
.ino
);
1416 fuse_reply_entry(req
, &e
);
1417 lo_inode_put(lo
, &parent_inode
);
1418 lo_inode_put(lo
, &inode
);
1423 lo_inode_put(lo
, &parent_inode
);
1424 lo_inode_put(lo
, &inode
);
1425 fuse_reply_err(req
, saverr
);
1428 /* Increments nlookup and caller must release refcount using lo_inode_put() */
1429 static struct lo_inode
*lookup_name(fuse_req_t req
, fuse_ino_t parent
,
1435 struct lo_data
*lo
= lo_data(req
);
1436 struct lo_inode
*dir
= lo_inode(req
, parent
);
1442 res
= do_statx(lo
, dir
->fd
, name
, &attr
, AT_SYMLINK_NOFOLLOW
, &mnt_id
);
1443 lo_inode_put(lo
, &dir
);
1448 return lo_find(lo
, &attr
, mnt_id
);
1451 static void lo_rmdir(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
1454 struct lo_inode
*inode
;
1455 struct lo_data
*lo
= lo_data(req
);
1457 if (is_empty(name
)) {
1458 fuse_reply_err(req
, ENOENT
);
1462 if (!is_safe_path_component(name
)) {
1463 fuse_reply_err(req
, EINVAL
);
1467 inode
= lookup_name(req
, parent
, name
);
1469 fuse_reply_err(req
, EIO
);
1473 res
= unlinkat(lo_fd(req
, parent
), name
, AT_REMOVEDIR
);
1475 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1476 unref_inode_lolocked(lo
, inode
, 1);
1477 lo_inode_put(lo
, &inode
);
1480 static void lo_rename(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1481 fuse_ino_t newparent
, const char *newname
,
1485 struct lo_inode
*parent_inode
;
1486 struct lo_inode
*newparent_inode
;
1487 struct lo_inode
*oldinode
= NULL
;
1488 struct lo_inode
*newinode
= NULL
;
1489 struct lo_data
*lo
= lo_data(req
);
1491 if (is_empty(name
) || is_empty(newname
)) {
1492 fuse_reply_err(req
, ENOENT
);
1496 if (!is_safe_path_component(name
) || !is_safe_path_component(newname
)) {
1497 fuse_reply_err(req
, EINVAL
);
1501 parent_inode
= lo_inode(req
, parent
);
1502 newparent_inode
= lo_inode(req
, newparent
);
1503 if (!parent_inode
|| !newparent_inode
) {
1504 fuse_reply_err(req
, EBADF
);
1508 oldinode
= lookup_name(req
, parent
, name
);
1509 newinode
= lookup_name(req
, newparent
, newname
);
1512 fuse_reply_err(req
, EIO
);
1517 #ifndef SYS_renameat2
1518 fuse_reply_err(req
, EINVAL
);
1520 res
= syscall(SYS_renameat2
, parent_inode
->fd
, name
,
1521 newparent_inode
->fd
, newname
, flags
);
1522 if (res
== -1 && errno
== ENOSYS
) {
1523 fuse_reply_err(req
, EINVAL
);
1525 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1531 res
= renameat(parent_inode
->fd
, name
, newparent_inode
->fd
, newname
);
1533 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1535 unref_inode_lolocked(lo
, oldinode
, 1);
1536 unref_inode_lolocked(lo
, newinode
, 1);
1537 lo_inode_put(lo
, &oldinode
);
1538 lo_inode_put(lo
, &newinode
);
1539 lo_inode_put(lo
, &parent_inode
);
1540 lo_inode_put(lo
, &newparent_inode
);
1543 static void lo_unlink(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
1546 struct lo_inode
*inode
;
1547 struct lo_data
*lo
= lo_data(req
);
1549 if (is_empty(name
)) {
1550 fuse_reply_err(req
, ENOENT
);
1554 if (!is_safe_path_component(name
)) {
1555 fuse_reply_err(req
, EINVAL
);
1559 inode
= lookup_name(req
, parent
, name
);
1561 fuse_reply_err(req
, EIO
);
1565 res
= unlinkat(lo_fd(req
, parent
), name
, 0);
1567 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1568 unref_inode_lolocked(lo
, inode
, 1);
1569 lo_inode_put(lo
, &inode
);
1572 /* To be called with lo->mutex held */
1573 static void unref_inode(struct lo_data
*lo
, struct lo_inode
*inode
, uint64_t n
)
1579 assert(inode
->nlookup
>= n
);
1580 inode
->nlookup
-= n
;
1581 if (!inode
->nlookup
) {
1582 lo_map_remove(&lo
->ino_map
, inode
->fuse_ino
);
1583 g_hash_table_remove(lo
->inodes
, &inode
->key
);
1584 if (lo
->posix_lock
) {
1585 if (g_hash_table_size(inode
->posix_locks
)) {
1586 fuse_log(FUSE_LOG_WARNING
, "Hash table is not empty\n");
1588 g_hash_table_destroy(inode
->posix_locks
);
1589 pthread_mutex_destroy(&inode
->plock_mutex
);
1591 /* Drop our refcount from lo_do_lookup() */
1592 lo_inode_put(lo
, &inode
);
1596 static void unref_inode_lolocked(struct lo_data
*lo
, struct lo_inode
*inode
,
1603 pthread_mutex_lock(&lo
->mutex
);
1604 unref_inode(lo
, inode
, n
);
1605 pthread_mutex_unlock(&lo
->mutex
);
1608 static void lo_forget_one(fuse_req_t req
, fuse_ino_t ino
, uint64_t nlookup
)
1610 struct lo_data
*lo
= lo_data(req
);
1611 struct lo_inode
*inode
;
1613 inode
= lo_inode(req
, ino
);
1618 fuse_log(FUSE_LOG_DEBUG
, " forget %lli %lli -%lli\n",
1619 (unsigned long long)ino
, (unsigned long long)inode
->nlookup
,
1620 (unsigned long long)nlookup
);
1622 unref_inode_lolocked(lo
, inode
, nlookup
);
1623 lo_inode_put(lo
, &inode
);
1626 static void lo_forget(fuse_req_t req
, fuse_ino_t ino
, uint64_t nlookup
)
1628 lo_forget_one(req
, ino
, nlookup
);
1629 fuse_reply_none(req
);
1632 static void lo_forget_multi(fuse_req_t req
, size_t count
,
1633 struct fuse_forget_data
*forgets
)
1637 for (i
= 0; i
< count
; i
++) {
1638 lo_forget_one(req
, forgets
[i
].ino
, forgets
[i
].nlookup
);
1640 fuse_reply_none(req
);
1643 static void lo_readlink(fuse_req_t req
, fuse_ino_t ino
)
1645 char buf
[PATH_MAX
+ 1];
1648 res
= readlinkat(lo_fd(req
, ino
), "", buf
, sizeof(buf
));
1650 return (void)fuse_reply_err(req
, errno
);
1653 if (res
== sizeof(buf
)) {
1654 return (void)fuse_reply_err(req
, ENAMETOOLONG
);
1659 fuse_reply_readlink(req
, buf
);
1665 struct dirent
*entry
;
1669 static void lo_dirp_put(struct lo_dirp
**dp
)
1671 struct lo_dirp
*d
= *dp
;
1678 if (g_atomic_int_dec_and_test(&d
->refcount
)) {
1684 /* Call lo_dirp_put() on the return value when no longer needed */
1685 static struct lo_dirp
*lo_dirp(fuse_req_t req
, struct fuse_file_info
*fi
)
1687 struct lo_data
*lo
= lo_data(req
);
1688 struct lo_map_elem
*elem
;
1690 pthread_mutex_lock(&lo
->mutex
);
1691 elem
= lo_map_get(&lo
->dirp_map
, fi
->fh
);
1693 g_atomic_int_inc(&elem
->dirp
->refcount
);
1695 pthread_mutex_unlock(&lo
->mutex
);
1703 static void lo_opendir(fuse_req_t req
, fuse_ino_t ino
,
1704 struct fuse_file_info
*fi
)
1707 struct lo_data
*lo
= lo_data(req
);
1712 d
= calloc(1, sizeof(struct lo_dirp
));
1717 fd
= openat(lo_fd(req
, ino
), ".", O_RDONLY
);
1722 d
->dp
= fdopendir(fd
);
1723 if (d
->dp
== NULL
) {
1730 g_atomic_int_set(&d
->refcount
, 1); /* paired with lo_releasedir() */
1731 pthread_mutex_lock(&lo
->mutex
);
1732 fh
= lo_add_dirp_mapping(req
, d
);
1733 pthread_mutex_unlock(&lo
->mutex
);
1739 if (lo
->cache
== CACHE_ALWAYS
) {
1740 fi
->cache_readdir
= 1;
1742 fuse_reply_open(req
, fi
);
1751 } else if (fd
!= -1) {
1756 fuse_reply_err(req
, error
);
1759 static void lo_do_readdir(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
1760 off_t offset
, struct fuse_file_info
*fi
, int plus
)
1762 struct lo_data
*lo
= lo_data(req
);
1763 struct lo_dirp
*d
= NULL
;
1764 struct lo_inode
*dinode
;
1765 g_autofree
char *buf
= NULL
;
1770 dinode
= lo_inode(req
, ino
);
1775 d
= lo_dirp(req
, fi
);
1781 buf
= g_try_malloc0(size
);
1787 if (offset
!= d
->offset
) {
1788 seekdir(d
->dp
, offset
);
1799 d
->entry
= readdir(d
->dp
);
1801 if (errno
) { /* Error */
1804 } else { /* End of stream */
1809 nextoff
= d
->entry
->d_off
;
1810 name
= d
->entry
->d_name
;
1812 fuse_ino_t entry_ino
= 0;
1813 struct fuse_entry_param e
= (struct fuse_entry_param
){
1814 .attr
.st_ino
= d
->entry
->d_ino
,
1815 .attr
.st_mode
= d
->entry
->d_type
<< 12,
1818 /* Hide root's parent directory */
1819 if (dinode
== &lo
->root
&& strcmp(name
, "..") == 0) {
1820 e
.attr
.st_ino
= lo
->root
.key
.ino
;
1821 e
.attr
.st_mode
= DT_DIR
<< 12;
1825 if (!is_dot_or_dotdot(name
)) {
1826 err
= lo_do_lookup(req
, ino
, name
, &e
, NULL
);
1833 entsize
= fuse_add_direntry_plus(req
, p
, rem
, name
, &e
, nextoff
);
1835 entsize
= fuse_add_direntry(req
, p
, rem
, name
, &e
.attr
, nextoff
);
1837 if (entsize
> rem
) {
1838 if (entry_ino
!= 0) {
1839 lo_forget_one(req
, entry_ino
, 1);
1848 d
->offset
= nextoff
;
1854 lo_inode_put(lo
, &dinode
);
1857 * If there's an error, we can only signal it if we haven't stored
1858 * any entries yet - otherwise we'd end up with wrong lookup
1859 * counts for the entries that are already in the buffer. So we
1860 * return what we've collected until that point.
1862 if (err
&& rem
== size
) {
1863 fuse_reply_err(req
, err
);
1865 fuse_reply_buf(req
, buf
, size
- rem
);
1869 static void lo_readdir(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
1870 off_t offset
, struct fuse_file_info
*fi
)
1872 lo_do_readdir(req
, ino
, size
, offset
, fi
, 0);
1875 static void lo_readdirplus(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
1876 off_t offset
, struct fuse_file_info
*fi
)
1878 lo_do_readdir(req
, ino
, size
, offset
, fi
, 1);
1881 static void lo_releasedir(fuse_req_t req
, fuse_ino_t ino
,
1882 struct fuse_file_info
*fi
)
1884 struct lo_data
*lo
= lo_data(req
);
1885 struct lo_map_elem
*elem
;
1890 pthread_mutex_lock(&lo
->mutex
);
1891 elem
= lo_map_get(&lo
->dirp_map
, fi
->fh
);
1893 pthread_mutex_unlock(&lo
->mutex
);
1894 fuse_reply_err(req
, EBADF
);
1899 lo_map_remove(&lo
->dirp_map
, fi
->fh
);
1900 pthread_mutex_unlock(&lo
->mutex
);
1902 lo_dirp_put(&d
); /* paired with lo_opendir() */
1904 fuse_reply_err(req
, 0);
1907 static void update_open_flags(int writeback
, int allow_direct_io
,
1908 struct fuse_file_info
*fi
)
1911 * With writeback cache, kernel may send read requests even
1912 * when userspace opened write-only
1914 if (writeback
&& (fi
->flags
& O_ACCMODE
) == O_WRONLY
) {
1915 fi
->flags
&= ~O_ACCMODE
;
1916 fi
->flags
|= O_RDWR
;
1920 * With writeback cache, O_APPEND is handled by the kernel.
1921 * This breaks atomicity (since the file may change in the
1922 * underlying filesystem, so that the kernel's idea of the
1923 * end of the file isn't accurate anymore). In this example,
1924 * we just accept that. A more rigorous filesystem may want
1925 * to return an error here
1927 if (writeback
&& (fi
->flags
& O_APPEND
)) {
1928 fi
->flags
&= ~O_APPEND
;
1932 * O_DIRECT in guest should not necessarily mean bypassing page
1933 * cache on host as well. Therefore, we discard it by default
1934 * ('-o no_allow_direct_io'). If somebody needs that behavior,
1935 * the '-o allow_direct_io' option should be set.
1937 if (!allow_direct_io
) {
1938 fi
->flags
&= ~O_DIRECT
;
1943 * Open a regular file, set up an fd mapping, and fill out the struct
1944 * fuse_file_info for it. If existing_fd is not negative, use that fd instead
1945 * opening a new one. Takes ownership of existing_fd.
1947 * Returns 0 on success or a positive errno.
1949 static int lo_do_open(struct lo_data
*lo
, struct lo_inode
*inode
,
1950 int existing_fd
, struct fuse_file_info
*fi
)
1953 int fd
= existing_fd
;
1955 bool cap_fsetid_dropped
= false;
1956 bool kill_suidgid
= lo
->killpriv_v2
&& fi
->kill_priv
;
1958 update_open_flags(lo
->writeback
, lo
->allow_direct_io
, fi
);
1962 err
= drop_effective_cap("FSETID", &cap_fsetid_dropped
);
1968 fd
= lo_inode_open(lo
, inode
, fi
->flags
);
1970 if (cap_fsetid_dropped
) {
1971 if (gain_effective_cap("FSETID")) {
1972 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_FSETID\n");
1978 if (fi
->flags
& (O_TRUNC
)) {
1979 int err
= drop_security_capability(lo
, fd
);
1987 pthread_mutex_lock(&lo
->mutex
);
1988 fh
= lo_add_fd_mapping(lo
, fd
);
1989 pthread_mutex_unlock(&lo
->mutex
);
1996 if (lo
->cache
== CACHE_NONE
) {
1998 } else if (lo
->cache
== CACHE_ALWAYS
) {
2004 static void lo_create(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
2005 mode_t mode
, struct fuse_file_info
*fi
)
2008 struct lo_data
*lo
= lo_data(req
);
2009 struct lo_inode
*parent_inode
;
2010 struct lo_inode
*inode
= NULL
;
2011 struct fuse_entry_param e
;
2013 struct lo_cred old
= {};
2015 fuse_log(FUSE_LOG_DEBUG
, "lo_create(parent=%" PRIu64
", name=%s)"
2016 " kill_priv=%d\n", parent
, name
, fi
->kill_priv
);
2018 if (!is_safe_path_component(name
)) {
2019 fuse_reply_err(req
, EINVAL
);
2023 parent_inode
= lo_inode(req
, parent
);
2024 if (!parent_inode
) {
2025 fuse_reply_err(req
, EBADF
);
2029 err
= lo_change_cred(req
, &old
, lo
->change_umask
);
2034 update_open_flags(lo
->writeback
, lo
->allow_direct_io
, fi
);
2036 /* Try to create a new file but don't open existing files */
2037 fd
= openat(parent_inode
->fd
, name
, fi
->flags
| O_CREAT
| O_EXCL
, mode
);
2038 err
= fd
== -1 ? errno
: 0;
2040 lo_restore_cred(&old
, lo
->change_umask
);
2042 /* Ignore the error if file exists and O_EXCL was not given */
2043 if (err
&& (err
!= EEXIST
|| (fi
->flags
& O_EXCL
))) {
2047 err
= lo_do_lookup(req
, parent
, name
, &e
, &inode
);
2052 err
= lo_do_open(lo
, inode
, fd
, fi
);
2053 fd
= -1; /* lo_do_open() takes ownership of fd */
2055 /* Undo lo_do_lookup() nlookup ref */
2056 unref_inode_lolocked(lo
, inode
, 1);
2060 lo_inode_put(lo
, &inode
);
2061 lo_inode_put(lo
, &parent_inode
);
2068 fuse_reply_err(req
, err
);
2070 fuse_reply_create(req
, &e
, fi
);
2074 /* Should be called with inode->plock_mutex held */
2075 static struct lo_inode_plock
*lookup_create_plock_ctx(struct lo_data
*lo
,
2076 struct lo_inode
*inode
,
2077 uint64_t lock_owner
,
2078 pid_t pid
, int *err
)
2080 struct lo_inode_plock
*plock
;
2084 g_hash_table_lookup(inode
->posix_locks
, GUINT_TO_POINTER(lock_owner
));
2090 plock
= malloc(sizeof(struct lo_inode_plock
));
2096 /* Open another instance of file which can be used for ofd locks. */
2097 /* TODO: What if file is not writable? */
2098 fd
= lo_inode_open(lo
, inode
, O_RDWR
);
2105 plock
->lock_owner
= lock_owner
;
2107 g_hash_table_insert(inode
->posix_locks
, GUINT_TO_POINTER(plock
->lock_owner
),
2112 static void lo_getlk(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
2115 struct lo_data
*lo
= lo_data(req
);
2116 struct lo_inode
*inode
;
2117 struct lo_inode_plock
*plock
;
2118 int ret
, saverr
= 0;
2120 fuse_log(FUSE_LOG_DEBUG
,
2121 "lo_getlk(ino=%" PRIu64
", flags=%d)"
2122 " owner=0x%" PRIx64
", l_type=%d l_start=0x%" PRIx64
2123 " l_len=0x%" PRIx64
"\n",
2124 ino
, fi
->flags
, fi
->lock_owner
, lock
->l_type
,
2125 (uint64_t)lock
->l_start
, (uint64_t)lock
->l_len
);
2127 if (!lo
->posix_lock
) {
2128 fuse_reply_err(req
, ENOSYS
);
2132 inode
= lo_inode(req
, ino
);
2134 fuse_reply_err(req
, EBADF
);
2138 pthread_mutex_lock(&inode
->plock_mutex
);
2140 lookup_create_plock_ctx(lo
, inode
, fi
->lock_owner
, lock
->l_pid
, &ret
);
2146 ret
= fcntl(plock
->fd
, F_OFD_GETLK
, lock
);
2152 pthread_mutex_unlock(&inode
->plock_mutex
);
2153 lo_inode_put(lo
, &inode
);
2156 fuse_reply_err(req
, saverr
);
2158 fuse_reply_lock(req
, lock
);
2162 static void lo_setlk(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
2163 struct flock
*lock
, int sleep
)
2165 struct lo_data
*lo
= lo_data(req
);
2166 struct lo_inode
*inode
;
2167 struct lo_inode_plock
*plock
;
2168 int ret
, saverr
= 0;
2170 fuse_log(FUSE_LOG_DEBUG
,
2171 "lo_setlk(ino=%" PRIu64
", flags=%d)"
2172 " cmd=%d pid=%d owner=0x%" PRIx64
" sleep=%d l_whence=%d"
2173 " l_start=0x%" PRIx64
" l_len=0x%" PRIx64
"\n",
2174 ino
, fi
->flags
, lock
->l_type
, lock
->l_pid
, fi
->lock_owner
, sleep
,
2175 lock
->l_whence
, (uint64_t)lock
->l_start
, (uint64_t)lock
->l_len
);
2177 if (!lo
->posix_lock
) {
2178 fuse_reply_err(req
, ENOSYS
);
2183 fuse_reply_err(req
, EOPNOTSUPP
);
2187 inode
= lo_inode(req
, ino
);
2189 fuse_reply_err(req
, EBADF
);
2193 pthread_mutex_lock(&inode
->plock_mutex
);
2195 lookup_create_plock_ctx(lo
, inode
, fi
->lock_owner
, lock
->l_pid
, &ret
);
2202 /* TODO: Is it alright to modify flock? */
2204 ret
= fcntl(plock
->fd
, F_OFD_SETLK
, lock
);
2210 pthread_mutex_unlock(&inode
->plock_mutex
);
2211 lo_inode_put(lo
, &inode
);
2213 fuse_reply_err(req
, saverr
);
2216 static void lo_fsyncdir(fuse_req_t req
, fuse_ino_t ino
, int datasync
,
2217 struct fuse_file_info
*fi
)
2225 d
= lo_dirp(req
, fi
);
2227 fuse_reply_err(req
, EBADF
);
2233 res
= fdatasync(fd
);
2240 fuse_reply_err(req
, res
== -1 ? errno
: 0);
2243 static void lo_open(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
)
2245 struct lo_data
*lo
= lo_data(req
);
2246 struct lo_inode
*inode
= lo_inode(req
, ino
);
2249 fuse_log(FUSE_LOG_DEBUG
, "lo_open(ino=%" PRIu64
", flags=%d, kill_priv=%d)"
2250 "\n", ino
, fi
->flags
, fi
->kill_priv
);
2253 fuse_reply_err(req
, EBADF
);
2257 err
= lo_do_open(lo
, inode
, -1, fi
);
2258 lo_inode_put(lo
, &inode
);
2260 fuse_reply_err(req
, err
);
2262 fuse_reply_open(req
, fi
);
2266 static void lo_release(fuse_req_t req
, fuse_ino_t ino
,
2267 struct fuse_file_info
*fi
)
2269 struct lo_data
*lo
= lo_data(req
);
2270 struct lo_map_elem
*elem
;
2275 pthread_mutex_lock(&lo
->mutex
);
2276 elem
= lo_map_get(&lo
->fd_map
, fi
->fh
);
2280 lo_map_remove(&lo
->fd_map
, fi
->fh
);
2282 pthread_mutex_unlock(&lo
->mutex
);
2285 fuse_reply_err(req
, 0);
2288 static void lo_flush(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
)
2292 struct lo_inode
*inode
;
2293 struct lo_data
*lo
= lo_data(req
);
2295 inode
= lo_inode(req
, ino
);
2297 fuse_reply_err(req
, EBADF
);
2301 if (!S_ISREG(inode
->filetype
)) {
2302 lo_inode_put(lo
, &inode
);
2303 fuse_reply_err(req
, EBADF
);
2307 /* An fd is going away. Cleanup associated posix locks */
2308 if (lo
->posix_lock
) {
2309 pthread_mutex_lock(&inode
->plock_mutex
);
2310 g_hash_table_remove(inode
->posix_locks
,
2311 GUINT_TO_POINTER(fi
->lock_owner
));
2312 pthread_mutex_unlock(&inode
->plock_mutex
);
2314 res
= close(dup(lo_fi_fd(req
, fi
)));
2315 lo_inode_put(lo
, &inode
);
2316 fuse_reply_err(req
, res
== -1 ? errno
: 0);
2319 static void lo_fsync(fuse_req_t req
, fuse_ino_t ino
, int datasync
,
2320 struct fuse_file_info
*fi
)
2322 struct lo_inode
*inode
= lo_inode(req
, ino
);
2323 struct lo_data
*lo
= lo_data(req
);
2327 fuse_log(FUSE_LOG_DEBUG
, "lo_fsync(ino=%" PRIu64
", fi=0x%p)\n", ino
,
2331 fuse_reply_err(req
, EBADF
);
2336 fd
= lo_inode_open(lo
, inode
, O_RDWR
);
2342 fd
= lo_fi_fd(req
, fi
);
2346 res
= fdatasync(fd
) == -1 ? errno
: 0;
2348 res
= fsync(fd
) == -1 ? errno
: 0;
2354 lo_inode_put(lo
, &inode
);
2355 fuse_reply_err(req
, res
);
2358 static void lo_read(fuse_req_t req
, fuse_ino_t ino
, size_t size
, off_t offset
,
2359 struct fuse_file_info
*fi
)
2361 struct fuse_bufvec buf
= FUSE_BUFVEC_INIT(size
);
2363 fuse_log(FUSE_LOG_DEBUG
,
2364 "lo_read(ino=%" PRIu64
", size=%zd, "
2366 ino
, size
, (unsigned long)offset
);
2368 buf
.buf
[0].flags
= FUSE_BUF_IS_FD
| FUSE_BUF_FD_SEEK
;
2369 buf
.buf
[0].fd
= lo_fi_fd(req
, fi
);
2370 buf
.buf
[0].pos
= offset
;
2372 fuse_reply_data(req
, &buf
);
2375 static void lo_write_buf(fuse_req_t req
, fuse_ino_t ino
,
2376 struct fuse_bufvec
*in_buf
, off_t off
,
2377 struct fuse_file_info
*fi
)
2381 struct fuse_bufvec out_buf
= FUSE_BUFVEC_INIT(fuse_buf_size(in_buf
));
2382 bool cap_fsetid_dropped
= false;
2384 out_buf
.buf
[0].flags
= FUSE_BUF_IS_FD
| FUSE_BUF_FD_SEEK
;
2385 out_buf
.buf
[0].fd
= lo_fi_fd(req
, fi
);
2386 out_buf
.buf
[0].pos
= off
;
2388 fuse_log(FUSE_LOG_DEBUG
,
2389 "lo_write_buf(ino=%" PRIu64
", size=%zd, off=%lu kill_priv=%d)\n",
2390 ino
, out_buf
.buf
[0].size
, (unsigned long)off
, fi
->kill_priv
);
2392 res
= drop_security_capability(lo_data(req
), out_buf
.buf
[0].fd
);
2394 fuse_reply_err(req
, res
);
2399 * If kill_priv is set, drop CAP_FSETID which should lead to kernel
2400 * clearing setuid/setgid on file. Note, for WRITE, we need to do
2401 * this even if killpriv_v2 is not enabled. fuse direct write path
2404 if (fi
->kill_priv
) {
2405 res
= drop_effective_cap("FSETID", &cap_fsetid_dropped
);
2407 fuse_reply_err(req
, res
);
2412 res
= fuse_buf_copy(&out_buf
, in_buf
);
2414 fuse_reply_err(req
, -res
);
2416 fuse_reply_write(req
, (size_t)res
);
2419 if (cap_fsetid_dropped
) {
2420 res
= gain_effective_cap("FSETID");
2422 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_FSETID\n");
2427 static void lo_statfs(fuse_req_t req
, fuse_ino_t ino
)
2430 struct statvfs stbuf
;
2432 res
= fstatvfs(lo_fd(req
, ino
), &stbuf
);
2434 fuse_reply_err(req
, errno
);
2436 fuse_reply_statfs(req
, &stbuf
);
2440 static void lo_fallocate(fuse_req_t req
, fuse_ino_t ino
, int mode
, off_t offset
,
2441 off_t length
, struct fuse_file_info
*fi
)
2443 int err
= EOPNOTSUPP
;
2446 #ifdef CONFIG_FALLOCATE
2447 err
= fallocate(lo_fi_fd(req
, fi
), mode
, offset
, length
);
2452 #elif defined(CONFIG_POSIX_FALLOCATE)
2454 fuse_reply_err(req
, EOPNOTSUPP
);
2458 err
= posix_fallocate(lo_fi_fd(req
, fi
), offset
, length
);
2461 fuse_reply_err(req
, err
);
2464 static void lo_flock(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
2470 res
= flock(lo_fi_fd(req
, fi
), op
);
2472 fuse_reply_err(req
, res
== -1 ? errno
: 0);
2477 * Exit; process attribute unmodified if matched.
2478 * An empty key applies to all.
2480 #define XATTR_MAP_FLAG_OK (1 << 0)
2482 * The attribute is unwanted;
2483 * EPERM on write, hidden on read.
2485 #define XATTR_MAP_FLAG_BAD (1 << 1)
2487 * For attr that start with 'key' prepend 'prepend'
2488 * 'key' may be empty to prepend for all attrs
2489 * key is defined from set/remove point of view.
2490 * Automatically reversed on read
2492 #define XATTR_MAP_FLAG_PREFIX (1 << 2)
2494 * The attribute is unsupported;
2495 * ENOTSUP on write, hidden on read.
2497 #define XATTR_MAP_FLAG_UNSUPPORTED (1 << 3)
2500 /* Apply rule to get/set/remove */
2501 #define XATTR_MAP_FLAG_CLIENT (1 << 16)
2502 /* Apply rule to list */
2503 #define XATTR_MAP_FLAG_SERVER (1 << 17)
2504 /* Apply rule to all */
2505 #define XATTR_MAP_FLAG_ALL (XATTR_MAP_FLAG_SERVER | XATTR_MAP_FLAG_CLIENT)
2507 static void add_xattrmap_entry(struct lo_data
*lo
,
2508 const XattrMapEntry
*new_entry
)
2510 XattrMapEntry
*res
= g_realloc_n(lo
->xattr_map_list
,
2511 lo
->xattr_map_nentries
+ 1,
2512 sizeof(XattrMapEntry
));
2513 res
[lo
->xattr_map_nentries
++] = *new_entry
;
2515 lo
->xattr_map_list
= res
;
2518 static void free_xattrmap(struct lo_data
*lo
)
2520 XattrMapEntry
*map
= lo
->xattr_map_list
;
2527 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
2529 g_free(map
[i
].prepend
);
2533 lo
->xattr_map_list
= NULL
;
2534 lo
->xattr_map_nentries
= -1;
2538 * Handle the 'map' type, which is sugar for a set of commands
2539 * for the common case of prefixing a subset or everything,
2540 * and allowing anything not prefixed through.
2541 * It must be the last entry in the stream, although there
2542 * can be other entries before it.
2546 * key maybe empty in which case all entries are prefixed.
2548 static void parse_xattrmap_map(struct lo_data
*lo
,
2549 const char *rule
, char sep
)
2554 XattrMapEntry tmp_entry
;
2557 fuse_log(FUSE_LOG_ERR
,
2558 "%s: Expecting '%c' after 'map' keyword, found '%c'\n",
2559 __func__
, sep
, *rule
);
2565 /* At start of 'key' field */
2566 tmp
= strchr(rule
, sep
);
2568 fuse_log(FUSE_LOG_ERR
,
2569 "%s: Missing '%c' at end of key field in map rule\n",
2574 key
= g_strndup(rule
, tmp
- rule
);
2577 /* At start of prefix field */
2578 tmp
= strchr(rule
, sep
);
2580 fuse_log(FUSE_LOG_ERR
,
2581 "%s: Missing '%c' at end of prefix field in map rule\n",
2586 prefix
= g_strndup(rule
, tmp
- rule
);
2590 * This should be the end of the string, we don't allow
2591 * any more commands after 'map'.
2594 fuse_log(FUSE_LOG_ERR
,
2595 "%s: Expecting end of command after map, found '%c'\n",
2600 /* 1st: Prefix matches/everything */
2601 tmp_entry
.flags
= XATTR_MAP_FLAG_PREFIX
| XATTR_MAP_FLAG_ALL
;
2602 tmp_entry
.key
= g_strdup(key
);
2603 tmp_entry
.prepend
= g_strdup(prefix
);
2604 add_xattrmap_entry(lo
, &tmp_entry
);
2607 /* Prefix all case */
2609 /* 2nd: Hide any non-prefixed entries on the host */
2610 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_ALL
;
2611 tmp_entry
.key
= g_strdup("");
2612 tmp_entry
.prepend
= g_strdup("");
2613 add_xattrmap_entry(lo
, &tmp_entry
);
2615 /* Prefix matching case */
2617 /* 2nd: Hide non-prefixed but matching entries on the host */
2618 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_SERVER
;
2619 tmp_entry
.key
= g_strdup(""); /* Not used */
2620 tmp_entry
.prepend
= g_strdup(key
);
2621 add_xattrmap_entry(lo
, &tmp_entry
);
2623 /* 3rd: Stop the client accessing prefixed attributes directly */
2624 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_CLIENT
;
2625 tmp_entry
.key
= g_strdup(prefix
);
2626 tmp_entry
.prepend
= g_strdup(""); /* Not used */
2627 add_xattrmap_entry(lo
, &tmp_entry
);
2629 /* 4th: Everything else is OK */
2630 tmp_entry
.flags
= XATTR_MAP_FLAG_OK
| XATTR_MAP_FLAG_ALL
;
2631 tmp_entry
.key
= g_strdup("");
2632 tmp_entry
.prepend
= g_strdup("");
2633 add_xattrmap_entry(lo
, &tmp_entry
);
2640 static void parse_xattrmap(struct lo_data
*lo
)
2642 const char *map
= lo
->xattrmap
;
2646 lo
->xattr_map_nentries
= 0;
2648 XattrMapEntry tmp_entry
;
2651 if (isspace(*map
)) {
2655 /* The separator is the first non-space of the rule */
2661 tmp_entry
.flags
= 0;
2662 /* Start of 'type' */
2663 if (strstart(map
, "prefix", &map
)) {
2664 tmp_entry
.flags
|= XATTR_MAP_FLAG_PREFIX
;
2665 } else if (strstart(map
, "ok", &map
)) {
2666 tmp_entry
.flags
|= XATTR_MAP_FLAG_OK
;
2667 } else if (strstart(map
, "bad", &map
)) {
2668 tmp_entry
.flags
|= XATTR_MAP_FLAG_BAD
;
2669 } else if (strstart(map
, "unsupported", &map
)) {
2670 tmp_entry
.flags
|= XATTR_MAP_FLAG_UNSUPPORTED
;
2671 } else if (strstart(map
, "map", &map
)) {
2673 * map is sugar that adds a number of rules, and must be
2676 parse_xattrmap_map(lo
, map
, sep
);
2679 fuse_log(FUSE_LOG_ERR
,
2680 "%s: Unexpected type;"
2681 "Expecting 'prefix', 'ok', 'bad', 'unsupported' or 'map'"
2682 " in rule %zu\n", __func__
, lo
->xattr_map_nentries
);
2686 if (*map
++ != sep
) {
2687 fuse_log(FUSE_LOG_ERR
,
2688 "%s: Missing '%c' at end of type field of rule %zu\n",
2689 __func__
, sep
, lo
->xattr_map_nentries
);
2693 /* Start of 'scope' */
2694 if (strstart(map
, "client", &map
)) {
2695 tmp_entry
.flags
|= XATTR_MAP_FLAG_CLIENT
;
2696 } else if (strstart(map
, "server", &map
)) {
2697 tmp_entry
.flags
|= XATTR_MAP_FLAG_SERVER
;
2698 } else if (strstart(map
, "all", &map
)) {
2699 tmp_entry
.flags
|= XATTR_MAP_FLAG_ALL
;
2701 fuse_log(FUSE_LOG_ERR
,
2702 "%s: Unexpected scope;"
2703 " Expecting 'client', 'server', or 'all', in rule %zu\n",
2704 __func__
, lo
->xattr_map_nentries
);
2708 if (*map
++ != sep
) {
2709 fuse_log(FUSE_LOG_ERR
,
2710 "%s: Expecting '%c' found '%c'"
2711 " after scope in rule %zu\n",
2712 __func__
, sep
, *map
, lo
->xattr_map_nentries
);
2716 /* At start of 'key' field */
2717 tmp
= strchr(map
, sep
);
2719 fuse_log(FUSE_LOG_ERR
,
2720 "%s: Missing '%c' at end of key field of rule %zu",
2721 __func__
, sep
, lo
->xattr_map_nentries
);
2724 tmp_entry
.key
= g_strndup(map
, tmp
- map
);
2727 /* At start of 'prepend' field */
2728 tmp
= strchr(map
, sep
);
2730 fuse_log(FUSE_LOG_ERR
,
2731 "%s: Missing '%c' at end of prepend field of rule %zu",
2732 __func__
, sep
, lo
->xattr_map_nentries
);
2735 tmp_entry
.prepend
= g_strndup(map
, tmp
- map
);
2738 add_xattrmap_entry(lo
, &tmp_entry
);
2739 /* End of rule - go around again for another rule */
2742 if (!lo
->xattr_map_nentries
) {
2743 fuse_log(FUSE_LOG_ERR
, "Empty xattr map\n");
2747 ret
= xattr_map_client(lo
, "security.capability",
2748 &lo
->xattr_security_capability
);
2750 fuse_log(FUSE_LOG_ERR
, "Failed to map security.capability: %s\n",
2754 if (!lo
->xattr_security_capability
||
2755 !strcmp(lo
->xattr_security_capability
, "security.capability")) {
2756 /* 1-1 mapping, don't need to do anything */
2757 free(lo
->xattr_security_capability
);
2758 lo
->xattr_security_capability
= NULL
;
2763 * For use with getxattr/setxattr/removexattr, where the client
2764 * gives us a name and we may need to choose a different one.
2765 * Allocates a buffer for the result placing it in *out_name.
2766 * If there's no change then *out_name is not set.
2767 * Returns 0 on success
2768 * Can return -EPERM to indicate we block a given attribute
2769 * (in which case out_name is not allocated)
2770 * Can return -ENOMEM to indicate out_name couldn't be allocated.
2772 static int xattr_map_client(const struct lo_data
*lo
, const char *client_name
,
2776 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
2777 const XattrMapEntry
*cur_entry
= lo
->xattr_map_list
+ i
;
2779 if ((cur_entry
->flags
& XATTR_MAP_FLAG_CLIENT
) &&
2780 (strstart(client_name
, cur_entry
->key
, NULL
))) {
2781 if (cur_entry
->flags
& XATTR_MAP_FLAG_BAD
) {
2784 if (cur_entry
->flags
& XATTR_MAP_FLAG_UNSUPPORTED
) {
2787 if (cur_entry
->flags
& XATTR_MAP_FLAG_OK
) {
2788 /* Unmodified name */
2791 if (cur_entry
->flags
& XATTR_MAP_FLAG_PREFIX
) {
2792 *out_name
= g_try_malloc(strlen(client_name
) +
2793 strlen(cur_entry
->prepend
) + 1);
2797 sprintf(*out_name
, "%s%s", cur_entry
->prepend
, client_name
);
2807 * For use with listxattr where the server fs gives us a name and we may need
2808 * to sanitize this for the client.
2809 * Returns a pointer to the result in *out_name
2810 * This is always the original string or the current string with some prefix
2811 * removed; no reallocation is done.
2812 * Returns 0 on success
2813 * Can return -ENODATA to indicate the name should be dropped from the list.
2815 static int xattr_map_server(const struct lo_data
*lo
, const char *server_name
,
2816 const char **out_name
)
2821 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
2822 const XattrMapEntry
*cur_entry
= lo
->xattr_map_list
+ i
;
2824 if ((cur_entry
->flags
& XATTR_MAP_FLAG_SERVER
) &&
2825 (strstart(server_name
, cur_entry
->prepend
, &end
))) {
2826 if (cur_entry
->flags
& XATTR_MAP_FLAG_BAD
||
2827 cur_entry
->flags
& XATTR_MAP_FLAG_UNSUPPORTED
) {
2830 if (cur_entry
->flags
& XATTR_MAP_FLAG_OK
) {
2831 *out_name
= server_name
;
2834 if (cur_entry
->flags
& XATTR_MAP_FLAG_PREFIX
) {
2845 #define FCHDIR_NOFAIL(fd) do { \
2846 int fchdir_res = fchdir(fd); \
2847 assert(fchdir_res == 0); \
2850 static bool block_xattr(struct lo_data
*lo
, const char *name
)
2853 * If user explicitly enabled posix_acl or did not provide any option,
2854 * do not block acl. Otherwise block system.posix_acl_access and
2855 * system.posix_acl_default xattrs.
2857 if (lo
->user_posix_acl
) {
2860 if (!strcmp(name
, "system.posix_acl_access") ||
2861 !strcmp(name
, "system.posix_acl_default"))
2868 * Returns number of bytes in xattr_list after filtering on success. This
2869 * could be zero as well if nothing is left after filtering.
2871 * Returns negative error code on failure.
2872 * xattr_list is modified in place.
2874 static int remove_blocked_xattrs(struct lo_data
*lo
, char *xattr_list
,
2877 size_t out_index
, in_index
;
2880 * As of now we only filter out acl xattrs. If acls are enabled or
2881 * they have not been explicitly disabled, there is nothing to
2884 if (lo
->user_posix_acl
) {
2890 while (in_index
< in_size
) {
2891 char *in_ptr
= xattr_list
+ in_index
;
2893 /* Length of current attribute name */
2894 size_t in_len
= strlen(xattr_list
+ in_index
) + 1;
2896 if (!block_xattr(lo
, in_ptr
)) {
2897 if (in_index
!= out_index
) {
2898 memmove(xattr_list
+ out_index
, xattr_list
+ in_index
, in_len
);
2900 out_index
+= in_len
;
2907 static void lo_getxattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
,
2910 struct lo_data
*lo
= lo_data(req
);
2911 g_autofree
char *value
= NULL
;
2915 struct lo_inode
*inode
;
2920 if (block_xattr(lo
, in_name
)) {
2921 fuse_reply_err(req
, EOPNOTSUPP
);
2928 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
2930 if (ret
== -EPERM
) {
2933 fuse_reply_err(req
, -ret
);
2941 inode
= lo_inode(req
, ino
);
2943 fuse_reply_err(req
, EBADF
);
2944 g_free(mapped_name
);
2949 if (!lo_data(req
)->xattr
) {
2953 fuse_log(FUSE_LOG_DEBUG
, "lo_getxattr(ino=%" PRIu64
", name=%s size=%zd)\n",
2957 value
= g_try_malloc(size
);
2963 sprintf(procname
, "%i", inode
->fd
);
2965 * It is not safe to open() non-regular/non-dir files in file server
2966 * unless O_PATH is used, so use that method for regular files/dir
2967 * only (as it seems giving less performance overhead).
2968 * Otherwise, call fchdir() to avoid open().
2970 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
2971 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
2975 ret
= fgetxattr(fd
, name
, value
, size
);
2976 saverr
= ret
== -1 ? errno
: 0;
2978 /* fchdir should not fail here */
2979 FCHDIR_NOFAIL(lo
->proc_self_fd
);
2980 ret
= getxattr(procname
, name
, value
, size
);
2981 saverr
= ret
== -1 ? errno
: 0;
2982 FCHDIR_NOFAIL(lo
->root
.fd
);
2993 fuse_reply_buf(req
, value
, ret
);
2995 fuse_reply_xattr(req
, ret
);
3002 lo_inode_put(lo
, &inode
);
3008 fuse_reply_err(req
, saverr
);
3009 g_free(mapped_name
);
3013 static void lo_listxattr(fuse_req_t req
, fuse_ino_t ino
, size_t size
)
3015 struct lo_data
*lo
= lo_data(req
);
3016 g_autofree
char *value
= NULL
;
3018 struct lo_inode
*inode
;
3023 inode
= lo_inode(req
, ino
);
3025 fuse_reply_err(req
, EBADF
);
3030 if (!lo_data(req
)->xattr
) {
3034 fuse_log(FUSE_LOG_DEBUG
, "lo_listxattr(ino=%" PRIu64
", size=%zd)\n", ino
,
3038 value
= g_try_malloc(size
);
3044 sprintf(procname
, "%i", inode
->fd
);
3045 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
3046 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
3050 ret
= flistxattr(fd
, value
, size
);
3051 saverr
= ret
== -1 ? errno
: 0;
3053 /* fchdir should not fail here */
3054 FCHDIR_NOFAIL(lo
->proc_self_fd
);
3055 ret
= listxattr(procname
, value
, size
);
3056 saverr
= ret
== -1 ? errno
: 0;
3057 FCHDIR_NOFAIL(lo
->root
.fd
);
3069 if (lo
->xattr_map_list
) {
3071 * Map the names back, some attributes might be dropped,
3072 * some shortened, but not increased, so we shouldn't
3075 size_t out_index
, in_index
;
3078 while (in_index
< ret
) {
3079 const char *map_out
;
3080 char *in_ptr
= value
+ in_index
;
3081 /* Length of current attribute name */
3082 size_t in_len
= strlen(value
+ in_index
) + 1;
3084 int mapret
= xattr_map_server(lo
, in_ptr
, &map_out
);
3085 if (mapret
!= -ENODATA
&& mapret
!= 0) {
3086 /* Shouldn't happen */
3091 /* Either unchanged, or truncated */
3093 if (map_out
!= in_ptr
) {
3094 /* +1 copies the NIL */
3095 out_len
= strlen(map_out
) + 1;
3101 * Move result along, may still be needed for an unchanged
3102 * entry if a previous entry was changed.
3104 memmove(value
+ out_index
, map_out
, out_len
);
3106 out_index
+= out_len
;
3116 ret
= remove_blocked_xattrs(lo
, value
, ret
);
3121 fuse_reply_buf(req
, value
, ret
);
3124 * xattrmap only ever shortens the result,
3125 * so we don't need to do anything clever with the
3126 * allocation length here.
3128 fuse_reply_xattr(req
, ret
);
3135 lo_inode_put(lo
, &inode
);
3141 fuse_reply_err(req
, saverr
);
3145 static void lo_setxattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
,
3146 const char *value
, size_t size
, int flags
,
3147 uint32_t extra_flags
)
3152 struct lo_data
*lo
= lo_data(req
);
3153 struct lo_inode
*inode
;
3157 bool switched_creds
= false;
3158 bool cap_fsetid_dropped
= false;
3159 struct lo_cred old
= {};
3161 if (block_xattr(lo
, in_name
)) {
3162 fuse_reply_err(req
, EOPNOTSUPP
);
3169 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
3171 fuse_reply_err(req
, -ret
);
3179 inode
= lo_inode(req
, ino
);
3181 fuse_reply_err(req
, EBADF
);
3182 g_free(mapped_name
);
3187 if (!lo_data(req
)->xattr
) {
3191 fuse_log(FUSE_LOG_DEBUG
, "lo_setxattr(ino=%" PRIu64
3192 ", name=%s value=%s size=%zd)\n", ino
, name
, value
, size
);
3194 sprintf(procname
, "%i", inode
->fd
);
3196 * If we are setting posix access acl and if SGID needs to be
3197 * cleared, then switch to caller's gid and drop CAP_FSETID
3198 * and that should make sure host kernel clears SGID.
3200 * This probably will not work when we support idmapped mounts.
3201 * In that case we will need to find a non-root gid and switch
3202 * to it. (Instead of gid in request). Fix it when we support
3205 if (lo
->posix_acl
&& !strcmp(name
, "system.posix_acl_access")
3206 && (extra_flags
& FUSE_SETXATTR_ACL_KILL_SGID
)) {
3207 ret
= lo_drop_cap_change_cred(req
, &old
, false, "FSETID",
3208 &cap_fsetid_dropped
);
3213 switched_creds
= true;
3215 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
3216 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
3221 ret
= fsetxattr(fd
, name
, value
, size
, flags
);
3222 saverr
= ret
== -1 ? errno
: 0;
3224 /* fchdir should not fail here */
3225 FCHDIR_NOFAIL(lo
->proc_self_fd
);
3226 ret
= setxattr(procname
, name
, value
, size
, flags
);
3227 saverr
= ret
== -1 ? errno
: 0;
3228 FCHDIR_NOFAIL(lo
->root
.fd
);
3230 if (switched_creds
) {
3231 if (cap_fsetid_dropped
)
3232 lo_restore_cred_gain_cap(&old
, false, "FSETID");
3234 lo_restore_cred(&old
, false);
3242 lo_inode_put(lo
, &inode
);
3243 g_free(mapped_name
);
3244 fuse_reply_err(req
, saverr
);
3247 static void lo_removexattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
)
3252 struct lo_data
*lo
= lo_data(req
);
3253 struct lo_inode
*inode
;
3258 if (block_xattr(lo
, in_name
)) {
3259 fuse_reply_err(req
, EOPNOTSUPP
);
3266 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
3268 fuse_reply_err(req
, -ret
);
3276 inode
= lo_inode(req
, ino
);
3278 fuse_reply_err(req
, EBADF
);
3279 g_free(mapped_name
);
3284 if (!lo_data(req
)->xattr
) {
3288 fuse_log(FUSE_LOG_DEBUG
, "lo_removexattr(ino=%" PRIu64
", name=%s)\n", ino
,
3291 sprintf(procname
, "%i", inode
->fd
);
3292 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
3293 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
3298 ret
= fremovexattr(fd
, name
);
3299 saverr
= ret
== -1 ? errno
: 0;
3301 /* fchdir should not fail here */
3302 FCHDIR_NOFAIL(lo
->proc_self_fd
);
3303 ret
= removexattr(procname
, name
);
3304 saverr
= ret
== -1 ? errno
: 0;
3305 FCHDIR_NOFAIL(lo
->root
.fd
);
3313 lo_inode_put(lo
, &inode
);
3314 g_free(mapped_name
);
3315 fuse_reply_err(req
, saverr
);
3318 #ifdef HAVE_COPY_FILE_RANGE
3319 static void lo_copy_file_range(fuse_req_t req
, fuse_ino_t ino_in
, off_t off_in
,
3320 struct fuse_file_info
*fi_in
, fuse_ino_t ino_out
,
3321 off_t off_out
, struct fuse_file_info
*fi_out
,
3322 size_t len
, int flags
)
3327 in_fd
= lo_fi_fd(req
, fi_in
);
3328 out_fd
= lo_fi_fd(req
, fi_out
);
3330 fuse_log(FUSE_LOG_DEBUG
,
3331 "lo_copy_file_range(ino=%" PRIu64
"/fd=%d, "
3332 "off=%ju, ino=%" PRIu64
"/fd=%d, "
3333 "off=%ju, size=%zd, flags=0x%x)\n",
3334 ino_in
, in_fd
, (intmax_t)off_in
,
3335 ino_out
, out_fd
, (intmax_t)off_out
, len
, flags
);
3337 res
= copy_file_range(in_fd
, &off_in
, out_fd
, &off_out
, len
, flags
);
3339 fuse_reply_err(req
, errno
);
3341 fuse_reply_write(req
, res
);
3346 static void lo_lseek(fuse_req_t req
, fuse_ino_t ino
, off_t off
, int whence
,
3347 struct fuse_file_info
*fi
)
3352 res
= lseek(lo_fi_fd(req
, fi
), off
, whence
);
3354 fuse_reply_lseek(req
, res
);
3356 fuse_reply_err(req
, errno
);
3360 static void lo_destroy(void *userdata
)
3362 struct lo_data
*lo
= (struct lo_data
*)userdata
;
3364 pthread_mutex_lock(&lo
->mutex
);
3366 GHashTableIter iter
;
3367 gpointer key
, value
;
3369 g_hash_table_iter_init(&iter
, lo
->inodes
);
3370 if (!g_hash_table_iter_next(&iter
, &key
, &value
)) {
3374 struct lo_inode
*inode
= value
;
3375 unref_inode(lo
, inode
, inode
->nlookup
);
3377 pthread_mutex_unlock(&lo
->mutex
);
3380 static struct fuse_lowlevel_ops lo_oper
= {
3382 .lookup
= lo_lookup
,
3385 .symlink
= lo_symlink
,
3387 .unlink
= lo_unlink
,
3389 .rename
= lo_rename
,
3390 .forget
= lo_forget
,
3391 .forget_multi
= lo_forget_multi
,
3392 .getattr
= lo_getattr
,
3393 .setattr
= lo_setattr
,
3394 .readlink
= lo_readlink
,
3395 .opendir
= lo_opendir
,
3396 .readdir
= lo_readdir
,
3397 .readdirplus
= lo_readdirplus
,
3398 .releasedir
= lo_releasedir
,
3399 .fsyncdir
= lo_fsyncdir
,
3400 .create
= lo_create
,
3404 .release
= lo_release
,
3408 .write_buf
= lo_write_buf
,
3409 .statfs
= lo_statfs
,
3410 .fallocate
= lo_fallocate
,
3412 .getxattr
= lo_getxattr
,
3413 .listxattr
= lo_listxattr
,
3414 .setxattr
= lo_setxattr
,
3415 .removexattr
= lo_removexattr
,
3416 #ifdef HAVE_COPY_FILE_RANGE
3417 .copy_file_range
= lo_copy_file_range
,
3420 .destroy
= lo_destroy
,
3423 /* Print vhost-user.json backend program capabilities */
3424 static void print_capabilities(void)
3427 printf(" \"type\": \"fs\"\n");
3432 * Drop all Linux capabilities because the wait parent process only needs to
3433 * sit in waitpid(2) and terminate.
3435 static void setup_wait_parent_capabilities(void)
3437 capng_setpid(syscall(SYS_gettid
));
3438 capng_clear(CAPNG_SELECT_BOTH
);
3439 capng_apply(CAPNG_SELECT_BOTH
);
3443 * Move to a new mount, net, and pid namespaces to isolate this process.
3445 static void setup_namespaces(struct lo_data
*lo
, struct fuse_session
*se
)
3450 * Create a new pid namespace for *child* processes. We'll have to
3451 * fork in order to enter the new pid namespace. A new mount namespace
3452 * is also needed so that we can remount /proc for the new pid
3455 * Our UNIX domain sockets have been created. Now we can move to
3456 * an empty network namespace to prevent TCP/IP and other network
3457 * activity in case this process is compromised.
3459 if (unshare(CLONE_NEWPID
| CLONE_NEWNS
| CLONE_NEWNET
) != 0) {
3460 fuse_log(FUSE_LOG_ERR
, "unshare(CLONE_NEWPID | CLONE_NEWNS): %m\n");
3466 fuse_log(FUSE_LOG_ERR
, "fork() failed: %m\n");
3473 setup_wait_parent_capabilities();
3475 /* The parent waits for the child */
3477 waited
= waitpid(child
, &wstatus
, 0);
3478 } while (waited
< 0 && errno
== EINTR
&& !se
->exited
);
3480 /* We were terminated by a signal, see fuse_signals.c */
3485 if (WIFEXITED(wstatus
)) {
3486 exit(WEXITSTATUS(wstatus
));
3492 /* Send us SIGTERM when the parent thread terminates, see prctl(2) */
3493 prctl(PR_SET_PDEATHSIG
, SIGTERM
);
3496 * If the mounts have shared propagation then we want to opt out so our
3497 * mount changes don't affect the parent mount namespace.
3499 if (mount(NULL
, "/", NULL
, MS_REC
| MS_SLAVE
, NULL
) < 0) {
3500 fuse_log(FUSE_LOG_ERR
, "mount(/, MS_REC|MS_SLAVE): %m\n");
3504 /* The child must remount /proc to use the new pid namespace */
3505 if (mount("proc", "/proc", "proc",
3506 MS_NODEV
| MS_NOEXEC
| MS_NOSUID
| MS_RELATIME
, NULL
) < 0) {
3507 fuse_log(FUSE_LOG_ERR
, "mount(/proc): %m\n");
3512 * We only need /proc/self/fd. Prevent ".." from accessing parent
3513 * directories of /proc/self/fd by bind-mounting it over /proc. Since / was
3514 * previously remounted with MS_REC | MS_SLAVE this mount change only
3515 * affects our process.
3517 if (mount("/proc/self/fd", "/proc", NULL
, MS_BIND
, NULL
) < 0) {
3518 fuse_log(FUSE_LOG_ERR
, "mount(/proc/self/fd, MS_BIND): %m\n");
3522 /* Get the /proc (actually /proc/self/fd, see above) file descriptor */
3523 lo
->proc_self_fd
= open("/proc", O_PATH
);
3524 if (lo
->proc_self_fd
== -1) {
3525 fuse_log(FUSE_LOG_ERR
, "open(/proc, O_PATH): %m\n");
3531 * Capture the capability state, we'll need to restore this for individual
3532 * threads later; see load_capng.
3534 static void setup_capng(void)
3536 /* Note this accesses /proc so has to happen before the sandbox */
3537 if (capng_get_caps_process()) {
3538 fuse_log(FUSE_LOG_ERR
, "capng_get_caps_process\n");
3541 pthread_mutex_init(&cap
.mutex
, NULL
);
3542 pthread_mutex_lock(&cap
.mutex
);
3543 cap
.saved
= capng_save_state();
3545 fuse_log(FUSE_LOG_ERR
, "capng_save_state\n");
3548 pthread_mutex_unlock(&cap
.mutex
);
3551 static void cleanup_capng(void)
3555 pthread_mutex_destroy(&cap
.mutex
);
3560 * Make the source directory our root so symlinks cannot escape and no other
3561 * files are accessible. Assumes unshare(CLONE_NEWNS) was already called.
3563 static void setup_mounts(const char *source
)
3568 if (mount(source
, source
, NULL
, MS_BIND
| MS_REC
, NULL
) < 0) {
3569 fuse_log(FUSE_LOG_ERR
, "mount(%s, %s, MS_BIND): %m\n", source
, source
);
3573 /* This magic is based on lxc's lxc_pivot_root() */
3574 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
3576 fuse_log(FUSE_LOG_ERR
, "open(/): %m\n");
3580 newroot
= open(source
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
3582 fuse_log(FUSE_LOG_ERR
, "open(%s): %m\n", source
);
3586 if (fchdir(newroot
) < 0) {
3587 fuse_log(FUSE_LOG_ERR
, "fchdir(newroot): %m\n");
3591 if (syscall(__NR_pivot_root
, ".", ".") < 0) {
3592 fuse_log(FUSE_LOG_ERR
, "pivot_root(., .): %m\n");
3596 if (fchdir(oldroot
) < 0) {
3597 fuse_log(FUSE_LOG_ERR
, "fchdir(oldroot): %m\n");
3601 if (mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
) < 0) {
3602 fuse_log(FUSE_LOG_ERR
, "mount(., MS_SLAVE | MS_REC): %m\n");
3606 if (umount2(".", MNT_DETACH
) < 0) {
3607 fuse_log(FUSE_LOG_ERR
, "umount2(., MNT_DETACH): %m\n");
3611 if (fchdir(newroot
) < 0) {
3612 fuse_log(FUSE_LOG_ERR
, "fchdir(newroot): %m\n");
3621 * Only keep capabilities in allowlist that are needed for file system operation
3622 * The (possibly NULL) modcaps_in string passed in is free'd before exit.
3624 static void setup_capabilities(char *modcaps_in
)
3626 char *modcaps
= modcaps_in
;
3627 pthread_mutex_lock(&cap
.mutex
);
3628 capng_restore_state(&cap
.saved
);
3631 * Add to allowlist file system-related capabilities that are needed for a
3632 * file server to act like root. Drop everything else like networking and
3633 * sysadmin capabilities.
3636 * 1. CAP_LINUX_IMMUTABLE is not included because it's only used via ioctl
3637 * and we don't support that.
3638 * 2. CAP_MAC_OVERRIDE is not included because it only seems to be
3639 * used by the Smack LSM. Omit it until there is demand for it.
3641 capng_setpid(syscall(SYS_gettid
));
3642 capng_clear(CAPNG_SELECT_BOTH
);
3643 if (capng_updatev(CAPNG_ADD
, CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
3653 fuse_log(FUSE_LOG_ERR
, "%s: capng_updatev failed\n", __func__
);
3658 * The modcaps option is a colon separated list of caps,
3659 * each preceded by either + or -.
3665 char *next
= strchr(modcaps
, ':');
3671 switch (modcaps
[0]) {
3677 action
= CAPNG_DROP
;
3681 fuse_log(FUSE_LOG_ERR
,
3682 "%s: Expecting '+'/'-' in modcaps but found '%c'\n",
3683 __func__
, modcaps
[0]);
3686 cap
= capng_name_to_capability(modcaps
+ 1);
3688 fuse_log(FUSE_LOG_ERR
, "%s: Unknown capability '%s'\n", __func__
,
3692 if (capng_update(action
, CAPNG_PERMITTED
| CAPNG_EFFECTIVE
, cap
)) {
3693 fuse_log(FUSE_LOG_ERR
, "%s: capng_update failed for '%s'\n",
3702 if (capng_apply(CAPNG_SELECT_BOTH
)) {
3703 fuse_log(FUSE_LOG_ERR
, "%s: capng_apply failed\n", __func__
);
3707 cap
.saved
= capng_save_state();
3709 fuse_log(FUSE_LOG_ERR
, "%s: capng_save_state failed\n", __func__
);
3712 pthread_mutex_unlock(&cap
.mutex
);
3716 * Use chroot as a weaker sandbox for environments where the process is
3717 * launched without CAP_SYS_ADMIN.
3719 static void setup_chroot(struct lo_data
*lo
)
3721 lo
->proc_self_fd
= open("/proc/self/fd", O_PATH
);
3722 if (lo
->proc_self_fd
== -1) {
3723 fuse_log(FUSE_LOG_ERR
, "open(\"/proc/self/fd\", O_PATH): %m\n");
3728 * Make the shared directory the file system root so that FUSE_OPEN
3729 * (lo_open()) cannot escape the shared directory by opening a symlink.
3731 * The chroot(2) syscall is later disabled by seccomp and the
3732 * CAP_SYS_CHROOT capability is dropped so that tampering with the chroot
3735 * However, it's still possible to escape the chroot via lo->proc_self_fd
3736 * but that requires first gaining control of the process.
3738 if (chroot(lo
->source
) != 0) {
3739 fuse_log(FUSE_LOG_ERR
, "chroot(\"%s\"): %m\n", lo
->source
);
3743 /* Move into the chroot */
3744 if (chdir("/") != 0) {
3745 fuse_log(FUSE_LOG_ERR
, "chdir(\"/\"): %m\n");
3751 * Lock down this process to prevent access to other processes or files outside
3752 * source directory. This reduces the impact of arbitrary code execution bugs.
3754 static void setup_sandbox(struct lo_data
*lo
, struct fuse_session
*se
,
3757 if (lo
->sandbox
== SANDBOX_NAMESPACE
) {
3758 setup_namespaces(lo
, se
);
3759 setup_mounts(lo
->source
);
3764 setup_seccomp(enable_syslog
);
3765 setup_capabilities(g_strdup(lo
->modcaps
));
3768 /* Set the maximum number of open file descriptors */
3769 static void setup_nofile_rlimit(unsigned long rlimit_nofile
)
3771 struct rlimit rlim
= {
3772 .rlim_cur
= rlimit_nofile
,
3773 .rlim_max
= rlimit_nofile
,
3776 if (rlimit_nofile
== 0) {
3777 return; /* nothing to do */
3780 if (setrlimit(RLIMIT_NOFILE
, &rlim
) < 0) {
3781 /* Ignore SELinux denials */
3782 if (errno
== EPERM
) {
3786 fuse_log(FUSE_LOG_ERR
, "setrlimit(RLIMIT_NOFILE): %m\n");
3791 static void log_func(enum fuse_log_level level
, const char *fmt
, va_list ap
)
3793 g_autofree
char *localfmt
= NULL
;
3795 if (current_log_level
< level
) {
3799 if (current_log_level
== FUSE_LOG_DEBUG
) {
3801 /* no timestamp needed */
3802 localfmt
= g_strdup_printf("[ID: %08ld] %s", syscall(__NR_gettid
),
3805 g_autoptr(GDateTime
) now
= g_date_time_new_now_utc();
3806 g_autofree
char *nowstr
= g_date_time_format(now
, "%Y-%m-%d %H:%M:%S.%f%z");
3807 localfmt
= g_strdup_printf("[%s] [ID: %08ld] %s",
3808 nowstr
, syscall(__NR_gettid
), fmt
);
3814 int priority
= LOG_ERR
;
3816 case FUSE_LOG_EMERG
:
3817 priority
= LOG_EMERG
;
3819 case FUSE_LOG_ALERT
:
3820 priority
= LOG_ALERT
;
3823 priority
= LOG_CRIT
;
3828 case FUSE_LOG_WARNING
:
3829 priority
= LOG_WARNING
;
3831 case FUSE_LOG_NOTICE
:
3832 priority
= LOG_NOTICE
;
3835 priority
= LOG_INFO
;
3837 case FUSE_LOG_DEBUG
:
3838 priority
= LOG_DEBUG
;
3841 vsyslog(priority
, fmt
, ap
);
3843 vfprintf(stderr
, fmt
, ap
);
3847 static void setup_root(struct lo_data
*lo
, struct lo_inode
*root
)
3853 fd
= open("/", O_PATH
);
3855 fuse_log(FUSE_LOG_ERR
, "open(%s, O_PATH): %m\n", lo
->source
);
3859 res
= do_statx(lo
, fd
, "", &stat
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
,
3862 fuse_log(FUSE_LOG_ERR
, "fstatat(%s): %m\n", lo
->source
);
3866 root
->filetype
= S_IFDIR
;
3868 root
->key
.ino
= stat
.st_ino
;
3869 root
->key
.dev
= stat
.st_dev
;
3870 root
->key
.mnt_id
= mnt_id
;
3872 g_atomic_int_set(&root
->refcount
, 2);
3873 if (lo
->posix_lock
) {
3874 pthread_mutex_init(&root
->plock_mutex
, NULL
);
3875 root
->posix_locks
= g_hash_table_new_full(
3876 g_direct_hash
, g_direct_equal
, NULL
, posix_locks_value_destroy
);
3880 static guint
lo_key_hash(gconstpointer key
)
3882 const struct lo_key
*lkey
= key
;
3884 return (guint
)lkey
->ino
+ (guint
)lkey
->dev
+ (guint
)lkey
->mnt_id
;
3887 static gboolean
lo_key_equal(gconstpointer a
, gconstpointer b
)
3889 const struct lo_key
*la
= a
;
3890 const struct lo_key
*lb
= b
;
3892 return la
->ino
== lb
->ino
&& la
->dev
== lb
->dev
&& la
->mnt_id
== lb
->mnt_id
;
3895 static void fuse_lo_data_cleanup(struct lo_data
*lo
)
3898 g_hash_table_destroy(lo
->inodes
);
3901 if (lo
->root
.posix_locks
) {
3902 g_hash_table_destroy(lo
->root
.posix_locks
);
3904 lo_map_destroy(&lo
->fd_map
);
3905 lo_map_destroy(&lo
->dirp_map
);
3906 lo_map_destroy(&lo
->ino_map
);
3908 if (lo
->proc_self_fd
>= 0) {
3909 close(lo
->proc_self_fd
);
3912 if (lo
->root
.fd
>= 0) {
3918 free(lo
->xattr_security_capability
);
3922 static void qemu_version(void)
3924 printf("virtiofsd version " QEMU_FULL_VERSION
"\n" QEMU_COPYRIGHT
"\n");
3927 int main(int argc
, char *argv
[])
3929 struct fuse_args args
= FUSE_ARGS_INIT(argc
, argv
);
3930 struct fuse_session
*se
;
3931 struct fuse_cmdline_opts opts
;
3932 struct lo_data lo
= {
3933 .sandbox
= SANDBOX_NAMESPACE
,
3937 .allow_direct_io
= 0,
3939 .user_killpriv_v2
= -1,
3940 .user_posix_acl
= -1,
3942 struct lo_map_elem
*root_elem
;
3943 struct lo_map_elem
*reserve_elem
;
3946 /* Initialize time conversion information for localtime_r(). */
3949 /* Don't mask creation mode, kernel already did that */
3952 qemu_init_exec_dir(argv
[0]);
3954 drop_supplementary_groups();
3956 pthread_mutex_init(&lo
.mutex
, NULL
);
3957 lo
.inodes
= g_hash_table_new(lo_key_hash
, lo_key_equal
);
3959 lo
.root
.fuse_ino
= FUSE_ROOT_ID
;
3960 lo
.cache
= CACHE_AUTO
;
3963 * Set up the ino map like this:
3964 * [0] Reserved (will not be used)
3967 lo_map_init(&lo
.ino_map
);
3968 reserve_elem
= lo_map_reserve(&lo
.ino_map
, 0);
3969 if (!reserve_elem
) {
3970 fuse_log(FUSE_LOG_ERR
, "failed to alloc reserve_elem.\n");
3973 reserve_elem
->in_use
= false;
3974 root_elem
= lo_map_reserve(&lo
.ino_map
, lo
.root
.fuse_ino
);
3976 fuse_log(FUSE_LOG_ERR
, "failed to alloc root_elem.\n");
3979 root_elem
->inode
= &lo
.root
;
3981 lo_map_init(&lo
.dirp_map
);
3982 lo_map_init(&lo
.fd_map
);
3984 if (fuse_parse_cmdline(&args
, &opts
) != 0) {
3987 fuse_set_log_func(log_func
);
3988 use_syslog
= opts
.syslog
;
3990 openlog("virtiofsd", LOG_PID
, LOG_DAEMON
);
3993 if (opts
.show_help
) {
3994 printf("usage: %s [options]\n\n", argv
[0]);
3995 fuse_cmdline_help();
3996 printf(" -o source=PATH shared directory tree\n");
3997 fuse_lowlevel_help();
4000 } else if (opts
.show_version
) {
4002 fuse_lowlevel_version();
4005 } else if (opts
.print_capabilities
) {
4006 print_capabilities();
4011 if (fuse_opt_parse(&args
, &lo
, lo_opts
, NULL
) == -1) {
4015 if (opts
.log_level
!= 0) {
4016 current_log_level
= opts
.log_level
;
4018 /* default log level is INFO */
4019 current_log_level
= FUSE_LOG_INFO
;
4021 lo
.debug
= opts
.debug
;
4023 current_log_level
= FUSE_LOG_DEBUG
;
4029 res
= lstat(lo
.source
, &stat
);
4031 fuse_log(FUSE_LOG_ERR
, "failed to stat source (\"%s\"): %m\n",
4035 if (!S_ISDIR(stat
.st_mode
)) {
4036 fuse_log(FUSE_LOG_ERR
, "source is not a directory\n");
4040 lo
.source
= strdup("/");
4042 fuse_log(FUSE_LOG_ERR
, "failed to strdup source\n");
4049 parse_xattrmap(&lo
);
4052 if (!lo
.timeout_set
) {
4063 lo
.timeout
= 86400.0;
4066 } else if (lo
.timeout
< 0) {
4067 fuse_log(FUSE_LOG_ERR
, "timeout is negative (%lf)\n", lo
.timeout
);
4071 if (lo
.user_posix_acl
== 1 && !lo
.xattr
) {
4072 fuse_log(FUSE_LOG_ERR
, "Can't enable posix ACLs. xattrs are disabled."
4077 lo
.use_statx
= true;
4079 se
= fuse_session_new(&args
, &lo_oper
, sizeof(lo_oper
), &lo
);
4084 if (fuse_set_signal_handlers(se
) != 0) {
4088 if (fuse_session_mount(se
) != 0) {
4092 fuse_daemonize(opts
.foreground
);
4094 setup_nofile_rlimit(opts
.rlimit_nofile
);
4096 /* Must be before sandbox since it wants /proc */
4099 setup_sandbox(&lo
, se
, opts
.syslog
);
4101 setup_root(&lo
, &lo
.root
);
4102 /* Block until ctrl+c or fusermount -u */
4103 ret
= virtio_loop(se
);
4105 fuse_session_unmount(se
);
4108 fuse_remove_signal_handlers(se
);
4110 fuse_session_destroy(se
);
4112 fuse_opt_free_args(&args
);
4114 fuse_lo_data_cleanup(&lo
);