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>
58 #include "qemu/cutils.h"
59 #include "passthrough_helpers.h"
60 #include "passthrough_seccomp.h"
62 /* Keep track of inode posix locks for each owner. */
63 struct lo_inode_plock
{
65 int fd
; /* fd for OFD locks */
70 struct lo_inode
*inode
;
78 /* Maps FUSE fh or ino values to internal objects */
80 struct lo_map_elem
*elems
;
95 * Atomic reference count for this object. The nlookup field holds a
96 * reference and release it when nlookup reaches 0.
103 * This counter keeps the inode alive during the FUSE session.
104 * Incremented when the FUSE inode number is sent in a reply
105 * (FUSE_LOOKUP, FUSE_READDIRPLUS, etc). Decremented when an inode is
106 * released by a FUSE_FORGET request.
108 * Note that this value is untrusted because the client can manipulate
109 * it arbitrarily using FUSE_FORGET requests.
111 * Protected by lo->mutex.
116 pthread_mutex_t plock_mutex
;
117 GHashTable
*posix_locks
; /* protected by lo_inode->plock_mutex */
139 typedef struct xattr_map_entry
{
146 pthread_mutex_t mutex
;
154 char *xattr_security_capability
;
161 int readdirplus_clear
;
163 int announce_submounts
;
165 struct lo_inode root
;
166 GHashTable
*inodes
; /* protected by lo->mutex */
167 struct lo_map ino_map
; /* protected by lo->mutex */
168 struct lo_map dirp_map
; /* protected by lo->mutex */
169 struct lo_map fd_map
; /* protected by lo->mutex */
170 XattrMapEntry
*xattr_map_list
;
171 size_t xattr_map_nentries
;
173 /* An O_PATH file descriptor to /proc/self/fd/ */
175 int user_killpriv_v2
, killpriv_v2
;
176 /* If set, virtiofsd is responsible for setting umask during creation */
178 int user_posix_acl
, posix_acl
;
181 static const struct fuse_opt lo_opts
[] = {
182 { "sandbox=namespace",
183 offsetof(struct lo_data
, sandbox
),
186 offsetof(struct lo_data
, sandbox
),
188 { "writeback", offsetof(struct lo_data
, writeback
), 1 },
189 { "no_writeback", offsetof(struct lo_data
, writeback
), 0 },
190 { "source=%s", offsetof(struct lo_data
, source
), 0 },
191 { "flock", offsetof(struct lo_data
, flock
), 1 },
192 { "no_flock", offsetof(struct lo_data
, flock
), 0 },
193 { "posix_lock", offsetof(struct lo_data
, posix_lock
), 1 },
194 { "no_posix_lock", offsetof(struct lo_data
, posix_lock
), 0 },
195 { "xattr", offsetof(struct lo_data
, xattr
), 1 },
196 { "no_xattr", offsetof(struct lo_data
, xattr
), 0 },
197 { "xattrmap=%s", offsetof(struct lo_data
, xattrmap
), 0 },
198 { "modcaps=%s", offsetof(struct lo_data
, modcaps
), 0 },
199 { "timeout=%lf", offsetof(struct lo_data
, timeout
), 0 },
200 { "timeout=", offsetof(struct lo_data
, timeout_set
), 1 },
201 { "cache=none", offsetof(struct lo_data
, cache
), CACHE_NONE
},
202 { "cache=auto", offsetof(struct lo_data
, cache
), CACHE_AUTO
},
203 { "cache=always", offsetof(struct lo_data
, cache
), CACHE_ALWAYS
},
204 { "readdirplus", offsetof(struct lo_data
, readdirplus_set
), 1 },
205 { "no_readdirplus", offsetof(struct lo_data
, readdirplus_clear
), 1 },
206 { "allow_direct_io", offsetof(struct lo_data
, allow_direct_io
), 1 },
207 { "no_allow_direct_io", offsetof(struct lo_data
, allow_direct_io
), 0 },
208 { "announce_submounts", offsetof(struct lo_data
, announce_submounts
), 1 },
209 { "killpriv_v2", offsetof(struct lo_data
, user_killpriv_v2
), 1 },
210 { "no_killpriv_v2", offsetof(struct lo_data
, user_killpriv_v2
), 0 },
211 { "posix_acl", offsetof(struct lo_data
, user_posix_acl
), 1 },
212 { "no_posix_acl", offsetof(struct lo_data
, user_posix_acl
), 0 },
215 static bool use_syslog
= false;
216 static int current_log_level
;
217 static void unref_inode_lolocked(struct lo_data
*lo
, struct lo_inode
*inode
,
221 pthread_mutex_t mutex
;
224 /* That we loaded cap-ng in the current thread from the saved */
225 static __thread
bool cap_loaded
= 0;
227 static struct lo_inode
*lo_find(struct lo_data
*lo
, struct stat
*st
,
229 static int xattr_map_client(const struct lo_data
*lo
, const char *client_name
,
232 static bool is_dot_or_dotdot(const char *name
)
234 return name
[0] == '.' &&
235 (name
[1] == '\0' || (name
[1] == '.' && name
[2] == '\0'));
238 /* Is `path` a single path component that is not "." or ".."? */
239 static bool is_safe_path_component(const char *path
)
241 if (strchr(path
, '/')) {
245 return !is_dot_or_dotdot(path
);
248 static bool is_empty(const char *name
)
250 return name
[0] == '\0';
253 static struct lo_data
*lo_data(fuse_req_t req
)
255 return (struct lo_data
*)fuse_req_userdata(req
);
259 * Load capng's state from our saved state if the current thread
260 * hadn't previously been loaded.
261 * returns 0 on success
263 static int load_capng(void)
266 pthread_mutex_lock(&cap
.mutex
);
267 capng_restore_state(&cap
.saved
);
269 * restore_state free's the saved copy
272 cap
.saved
= capng_save_state();
274 pthread_mutex_unlock(&cap
.mutex
);
275 fuse_log(FUSE_LOG_ERR
, "capng_save_state (thread)\n");
278 pthread_mutex_unlock(&cap
.mutex
);
281 * We want to use the loaded state for our pid,
284 capng_setpid(syscall(SYS_gettid
));
291 * Helpers for dropping and regaining effective capabilities. Returns 0
292 * on success, error otherwise
294 static int drop_effective_cap(const char *cap_name
, bool *cap_dropped
)
298 cap
= capng_name_to_capability(cap_name
);
301 fuse_log(FUSE_LOG_ERR
, "capng_name_to_capability(%s) failed:%s\n",
302 cap_name
, strerror(errno
));
308 fuse_log(FUSE_LOG_ERR
, "load_capng() failed\n");
312 /* We dont have this capability in effective set already. */
313 if (!capng_have_capability(CAPNG_EFFECTIVE
, cap
)) {
318 if (capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, cap
)) {
320 fuse_log(FUSE_LOG_ERR
, "capng_update(DROP,) failed\n");
324 if (capng_apply(CAPNG_SELECT_CAPS
)) {
326 fuse_log(FUSE_LOG_ERR
, "drop:capng_apply() failed\n");
339 static int gain_effective_cap(const char *cap_name
)
344 cap
= capng_name_to_capability(cap_name
);
347 fuse_log(FUSE_LOG_ERR
, "capng_name_to_capability(%s) failed:%s\n",
348 cap_name
, strerror(errno
));
354 fuse_log(FUSE_LOG_ERR
, "load_capng() failed\n");
358 if (capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, cap
)) {
360 fuse_log(FUSE_LOG_ERR
, "capng_update(ADD,) failed\n");
364 if (capng_apply(CAPNG_SELECT_CAPS
)) {
366 fuse_log(FUSE_LOG_ERR
, "gain:capng_apply() failed\n");
376 * The host kernel normally drops security.capability xattr's on
377 * any write, however if we're remapping xattr names we need to drop
378 * whatever the clients security.capability is actually stored as.
380 static int drop_security_capability(const struct lo_data
*lo
, int fd
)
382 if (!lo
->xattr_security_capability
) {
383 /* We didn't remap the name, let the host kernel do it */
386 if (!fremovexattr(fd
, lo
->xattr_security_capability
)) {
393 /* Attribute didn't exist, that's fine */
397 /* FS didn't support attribute anyway, also fine */
401 /* Hmm other error */
406 static void lo_map_init(struct lo_map
*map
)
413 static void lo_map_destroy(struct lo_map
*map
)
418 static int lo_map_grow(struct lo_map
*map
, size_t new_nelems
)
420 struct lo_map_elem
*new_elems
;
423 if (new_nelems
<= map
->nelems
) {
427 new_elems
= g_try_realloc_n(map
->elems
, new_nelems
, sizeof(map
->elems
[0]));
432 for (i
= map
->nelems
; i
< new_nelems
; i
++) {
433 new_elems
[i
].freelist
= i
+ 1;
434 new_elems
[i
].in_use
= false;
436 new_elems
[new_nelems
- 1].freelist
= -1;
438 map
->elems
= new_elems
;
439 map
->freelist
= map
->nelems
;
440 map
->nelems
= new_nelems
;
444 static struct lo_map_elem
*lo_map_alloc_elem(struct lo_map
*map
)
446 struct lo_map_elem
*elem
;
448 if (map
->freelist
== -1 && !lo_map_grow(map
, map
->nelems
+ 256)) {
452 elem
= &map
->elems
[map
->freelist
];
453 map
->freelist
= elem
->freelist
;
460 static struct lo_map_elem
*lo_map_reserve(struct lo_map
*map
, size_t key
)
464 if (!lo_map_grow(map
, key
+ 1)) {
468 for (prev
= &map
->freelist
; *prev
!= -1;
469 prev
= &map
->elems
[*prev
].freelist
) {
471 struct lo_map_elem
*elem
= &map
->elems
[key
];
473 *prev
= elem
->freelist
;
481 static struct lo_map_elem
*lo_map_get(struct lo_map
*map
, size_t key
)
483 if (key
>= map
->nelems
) {
486 if (!map
->elems
[key
].in_use
) {
489 return &map
->elems
[key
];
492 static void lo_map_remove(struct lo_map
*map
, size_t key
)
494 struct lo_map_elem
*elem
;
496 if (key
>= map
->nelems
) {
500 elem
= &map
->elems
[key
];
505 elem
->in_use
= false;
507 elem
->freelist
= map
->freelist
;
511 /* Assumes lo->mutex is held */
512 static ssize_t
lo_add_fd_mapping(struct lo_data
*lo
, int fd
)
514 struct lo_map_elem
*elem
;
516 elem
= lo_map_alloc_elem(&lo
->fd_map
);
522 return elem
- lo
->fd_map
.elems
;
525 /* Assumes lo->mutex is held */
526 static ssize_t
lo_add_dirp_mapping(fuse_req_t req
, struct lo_dirp
*dirp
)
528 struct lo_map_elem
*elem
;
530 elem
= lo_map_alloc_elem(&lo_data(req
)->dirp_map
);
536 return elem
- lo_data(req
)->dirp_map
.elems
;
539 /* Assumes lo->mutex is held */
540 static ssize_t
lo_add_inode_mapping(fuse_req_t req
, struct lo_inode
*inode
)
542 struct lo_map_elem
*elem
;
544 elem
= lo_map_alloc_elem(&lo_data(req
)->ino_map
);
550 return elem
- lo_data(req
)->ino_map
.elems
;
553 static void lo_inode_put(struct lo_data
*lo
, struct lo_inode
**inodep
)
555 struct lo_inode
*inode
= *inodep
;
563 if (g_atomic_int_dec_and_test(&inode
->refcount
)) {
569 /* Caller must release refcount using lo_inode_put() */
570 static struct lo_inode
*lo_inode(fuse_req_t req
, fuse_ino_t ino
)
572 struct lo_data
*lo
= lo_data(req
);
573 struct lo_map_elem
*elem
;
575 pthread_mutex_lock(&lo
->mutex
);
576 elem
= lo_map_get(&lo
->ino_map
, ino
);
578 g_atomic_int_inc(&elem
->inode
->refcount
);
580 pthread_mutex_unlock(&lo
->mutex
);
590 * TODO Remove this helper and force callers to hold an inode refcount until
591 * they are done with the fd. This will be done in a later patch to make
594 static int lo_fd(fuse_req_t req
, fuse_ino_t ino
)
596 struct lo_inode
*inode
= lo_inode(req
, ino
);
604 lo_inode_put(lo_data(req
), &inode
);
609 * Open a file descriptor for an inode. Returns -EBADF if the inode is not a
610 * regular file or a directory.
612 * Use this helper function instead of raw openat(2) to prevent security issues
613 * when a malicious client opens special files such as block device nodes.
614 * Symlink inodes are also rejected since symlinks must already have been
615 * traversed on the client side.
617 static int lo_inode_open(struct lo_data
*lo
, struct lo_inode
*inode
,
620 g_autofree
char *fd_str
= g_strdup_printf("%d", inode
->fd
);
623 if (!S_ISREG(inode
->filetype
) && !S_ISDIR(inode
->filetype
)) {
628 * The file is a symlink so O_NOFOLLOW must be ignored. We checked earlier
629 * that the inode is not a special file but if an external process races
630 * with us then symlinks are traversed here. It is not possible to escape
631 * the shared directory since it is mounted as "/" though.
633 fd
= openat(lo
->proc_self_fd
, fd_str
, open_flags
& ~O_NOFOLLOW
);
640 static void lo_init(void *userdata
, struct fuse_conn_info
*conn
)
642 struct lo_data
*lo
= (struct lo_data
*)userdata
;
644 if (conn
->capable
& FUSE_CAP_EXPORT_SUPPORT
) {
645 conn
->want
|= FUSE_CAP_EXPORT_SUPPORT
;
648 if (lo
->writeback
&& conn
->capable
& FUSE_CAP_WRITEBACK_CACHE
) {
649 fuse_log(FUSE_LOG_DEBUG
, "lo_init: activating writeback\n");
650 conn
->want
|= FUSE_CAP_WRITEBACK_CACHE
;
652 if (conn
->capable
& FUSE_CAP_FLOCK_LOCKS
) {
654 fuse_log(FUSE_LOG_DEBUG
, "lo_init: activating flock locks\n");
655 conn
->want
|= FUSE_CAP_FLOCK_LOCKS
;
657 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling flock locks\n");
658 conn
->want
&= ~FUSE_CAP_FLOCK_LOCKS
;
662 if (conn
->capable
& FUSE_CAP_POSIX_LOCKS
) {
663 if (lo
->posix_lock
) {
664 fuse_log(FUSE_LOG_DEBUG
, "lo_init: activating posix locks\n");
665 conn
->want
|= FUSE_CAP_POSIX_LOCKS
;
667 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling posix locks\n");
668 conn
->want
&= ~FUSE_CAP_POSIX_LOCKS
;
672 if ((lo
->cache
== CACHE_NONE
&& !lo
->readdirplus_set
) ||
673 lo
->readdirplus_clear
) {
674 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling readdirplus\n");
675 conn
->want
&= ~FUSE_CAP_READDIRPLUS
;
678 if (!(conn
->capable
& FUSE_CAP_SUBMOUNTS
) && lo
->announce_submounts
) {
679 fuse_log(FUSE_LOG_WARNING
, "lo_init: Cannot announce submounts, client "
680 "does not support it\n");
681 lo
->announce_submounts
= false;
684 if (lo
->user_killpriv_v2
== 1) {
686 * User explicitly asked for this option. Enable it unconditionally.
687 * If connection does not have this capability, it should fail
690 fuse_log(FUSE_LOG_DEBUG
, "lo_init: enabling killpriv_v2\n");
691 conn
->want
|= FUSE_CAP_HANDLE_KILLPRIV_V2
;
693 } else if (lo
->user_killpriv_v2
== -1 &&
694 conn
->capable
& FUSE_CAP_HANDLE_KILLPRIV_V2
) {
696 * User did not specify a value for killpriv_v2. By default enable it
697 * if connection offers this capability
699 fuse_log(FUSE_LOG_DEBUG
, "lo_init: enabling killpriv_v2\n");
700 conn
->want
|= FUSE_CAP_HANDLE_KILLPRIV_V2
;
704 * Either user specified to disable killpriv_v2, or connection does
705 * not offer this capability. Disable killpriv_v2 in both the cases
707 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling killpriv_v2\n");
708 conn
->want
&= ~FUSE_CAP_HANDLE_KILLPRIV_V2
;
712 if (lo
->user_posix_acl
== 1) {
714 * User explicitly asked for this option. Enable it unconditionally.
715 * If connection does not have this capability, print error message
716 * now. It will fail later in fuse_lowlevel.c
718 if (!(conn
->capable
& FUSE_CAP_POSIX_ACL
) ||
719 !(conn
->capable
& FUSE_CAP_DONT_MASK
) ||
720 !(conn
->capable
& FUSE_CAP_SETXATTR_EXT
)) {
721 fuse_log(FUSE_LOG_ERR
, "lo_init: Can not enable posix acl."
722 " kernel does not support FUSE_POSIX_ACL, FUSE_DONT_MASK"
723 " or FUSE_SETXATTR_EXT capability.\n");
725 fuse_log(FUSE_LOG_DEBUG
, "lo_init: enabling posix acl\n");
728 conn
->want
|= FUSE_CAP_POSIX_ACL
| FUSE_CAP_DONT_MASK
|
729 FUSE_CAP_SETXATTR_EXT
;
730 lo
->change_umask
= true;
731 lo
->posix_acl
= true;
733 /* User either did not specify anything or wants it disabled */
734 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling posix_acl\n");
735 conn
->want
&= ~FUSE_CAP_POSIX_ACL
;
739 static void lo_getattr(fuse_req_t req
, fuse_ino_t ino
,
740 struct fuse_file_info
*fi
)
744 struct lo_data
*lo
= lo_data(req
);
749 fstatat(lo_fd(req
, ino
), "", &buf
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
751 return (void)fuse_reply_err(req
, errno
);
754 fuse_reply_attr(req
, &buf
, lo
->timeout
);
757 static int lo_fi_fd(fuse_req_t req
, struct fuse_file_info
*fi
)
759 struct lo_data
*lo
= lo_data(req
);
760 struct lo_map_elem
*elem
;
762 pthread_mutex_lock(&lo
->mutex
);
763 elem
= lo_map_get(&lo
->fd_map
, fi
->fh
);
764 pthread_mutex_unlock(&lo
->mutex
);
773 static void lo_setattr(fuse_req_t req
, fuse_ino_t ino
, struct stat
*attr
,
774 int valid
, struct fuse_file_info
*fi
)
778 struct lo_data
*lo
= lo_data(req
);
779 struct lo_inode
*inode
;
784 inode
= lo_inode(req
, ino
);
786 fuse_reply_err(req
, EBADF
);
792 /* If fi->fh is invalid we'll report EBADF later */
794 fd
= lo_fi_fd(req
, fi
);
797 if (valid
& FUSE_SET_ATTR_MODE
) {
799 res
= fchmod(fd
, attr
->st_mode
);
801 sprintf(procname
, "%i", ifd
);
802 res
= fchmodat(lo
->proc_self_fd
, procname
, attr
->st_mode
, 0);
809 if (valid
& (FUSE_SET_ATTR_UID
| FUSE_SET_ATTR_GID
)) {
810 uid_t uid
= (valid
& FUSE_SET_ATTR_UID
) ? attr
->st_uid
: (uid_t
)-1;
811 gid_t gid
= (valid
& FUSE_SET_ATTR_GID
) ? attr
->st_gid
: (gid_t
)-1;
813 saverr
= drop_security_capability(lo
, ifd
);
818 res
= fchownat(ifd
, "", uid
, gid
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
824 if (valid
& FUSE_SET_ATTR_SIZE
) {
827 bool cap_fsetid_dropped
= false;
829 kill_suidgid
= lo
->killpriv_v2
&& (valid
& FUSE_SET_ATTR_KILL_SUIDGID
);
833 truncfd
= lo_inode_open(lo
, inode
, O_RDWR
);
840 saverr
= drop_security_capability(lo
, truncfd
);
849 res
= drop_effective_cap("FSETID", &cap_fsetid_dropped
);
859 res
= ftruncate(truncfd
, attr
->st_size
);
860 saverr
= res
== -1 ? errno
: 0;
862 if (cap_fsetid_dropped
) {
863 if (gain_effective_cap("FSETID")) {
864 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_FSETID\n");
874 if (valid
& (FUSE_SET_ATTR_ATIME
| FUSE_SET_ATTR_MTIME
)) {
875 struct timespec tv
[2];
879 tv
[0].tv_nsec
= UTIME_OMIT
;
880 tv
[1].tv_nsec
= UTIME_OMIT
;
882 if (valid
& FUSE_SET_ATTR_ATIME_NOW
) {
883 tv
[0].tv_nsec
= UTIME_NOW
;
884 } else if (valid
& FUSE_SET_ATTR_ATIME
) {
885 tv
[0] = attr
->st_atim
;
888 if (valid
& FUSE_SET_ATTR_MTIME_NOW
) {
889 tv
[1].tv_nsec
= UTIME_NOW
;
890 } else if (valid
& FUSE_SET_ATTR_MTIME
) {
891 tv
[1] = attr
->st_mtim
;
895 res
= futimens(fd
, tv
);
897 sprintf(procname
, "%i", inode
->fd
);
898 res
= utimensat(lo
->proc_self_fd
, procname
, tv
, 0);
905 lo_inode_put(lo
, &inode
);
907 return lo_getattr(req
, ino
, fi
);
910 lo_inode_put(lo
, &inode
);
911 fuse_reply_err(req
, saverr
);
914 static struct lo_inode
*lo_find(struct lo_data
*lo
, struct stat
*st
,
918 struct lo_key key
= {
924 pthread_mutex_lock(&lo
->mutex
);
925 p
= g_hash_table_lookup(lo
->inodes
, &key
);
927 assert(p
->nlookup
> 0);
929 g_atomic_int_inc(&p
->refcount
);
931 pthread_mutex_unlock(&lo
->mutex
);
936 /* value_destroy_func for posix_locks GHashTable */
937 static void posix_locks_value_destroy(gpointer data
)
939 struct lo_inode_plock
*plock
= data
;
942 * We had used open() for locks and had only one fd. So
943 * closing this fd should release all OFD locks.
949 static int do_statx(struct lo_data
*lo
, int dirfd
, const char *pathname
,
950 struct stat
*statbuf
, int flags
, uint64_t *mnt_id
)
954 #if defined(CONFIG_STATX) && defined(STATX_MNT_ID)
956 struct statx statxbuf
;
958 res
= statx(dirfd
, pathname
, flags
, STATX_BASIC_STATS
| STATX_MNT_ID
,
961 memset(statbuf
, 0, sizeof(*statbuf
));
962 statbuf
->st_dev
= makedev(statxbuf
.stx_dev_major
,
963 statxbuf
.stx_dev_minor
);
964 statbuf
->st_ino
= statxbuf
.stx_ino
;
965 statbuf
->st_mode
= statxbuf
.stx_mode
;
966 statbuf
->st_nlink
= statxbuf
.stx_nlink
;
967 statbuf
->st_uid
= statxbuf
.stx_uid
;
968 statbuf
->st_gid
= statxbuf
.stx_gid
;
969 statbuf
->st_rdev
= makedev(statxbuf
.stx_rdev_major
,
970 statxbuf
.stx_rdev_minor
);
971 statbuf
->st_size
= statxbuf
.stx_size
;
972 statbuf
->st_blksize
= statxbuf
.stx_blksize
;
973 statbuf
->st_blocks
= statxbuf
.stx_blocks
;
974 statbuf
->st_atim
.tv_sec
= statxbuf
.stx_atime
.tv_sec
;
975 statbuf
->st_atim
.tv_nsec
= statxbuf
.stx_atime
.tv_nsec
;
976 statbuf
->st_mtim
.tv_sec
= statxbuf
.stx_mtime
.tv_sec
;
977 statbuf
->st_mtim
.tv_nsec
= statxbuf
.stx_mtime
.tv_nsec
;
978 statbuf
->st_ctim
.tv_sec
= statxbuf
.stx_ctime
.tv_sec
;
979 statbuf
->st_ctim
.tv_nsec
= statxbuf
.stx_ctime
.tv_nsec
;
981 if (statxbuf
.stx_mask
& STATX_MNT_ID
) {
982 *mnt_id
= statxbuf
.stx_mnt_id
;
987 } else if (errno
!= ENOSYS
) {
990 lo
->use_statx
= false;
994 res
= fstatat(dirfd
, pathname
, statbuf
, flags
);
1004 * Increments nlookup on the inode on success. unref_inode_lolocked() must be
1005 * called eventually to decrement nlookup again. If inodep is non-NULL, the
1006 * inode pointer is stored and the caller must call lo_inode_put().
1008 static int lo_do_lookup(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1009 struct fuse_entry_param
*e
,
1010 struct lo_inode
**inodep
)
1016 struct lo_data
*lo
= lo_data(req
);
1017 struct lo_inode
*inode
= NULL
;
1018 struct lo_inode
*dir
= lo_inode(req
, parent
);
1021 *inodep
= NULL
; /* in case there is an error */
1025 * name_to_handle_at() and open_by_handle_at() can reach here with fuse
1026 * mount point in guest, but we don't have its inode info in the
1033 memset(e
, 0, sizeof(*e
));
1034 e
->attr_timeout
= lo
->timeout
;
1035 e
->entry_timeout
= lo
->timeout
;
1037 /* Do not allow escaping root directory */
1038 if (dir
== &lo
->root
&& strcmp(name
, "..") == 0) {
1042 newfd
= openat(dir
->fd
, name
, O_PATH
| O_NOFOLLOW
);
1047 res
= do_statx(lo
, newfd
, "", &e
->attr
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
,
1053 if (S_ISDIR(e
->attr
.st_mode
) && lo
->announce_submounts
&&
1054 (e
->attr
.st_dev
!= dir
->key
.dev
|| mnt_id
!= dir
->key
.mnt_id
)) {
1055 e
->attr_flags
|= FUSE_ATTR_SUBMOUNT
;
1058 inode
= lo_find(lo
, &e
->attr
, mnt_id
);
1062 inode
= calloc(1, sizeof(struct lo_inode
));
1067 /* cache only filetype */
1068 inode
->filetype
= (e
->attr
.st_mode
& S_IFMT
);
1071 * One for the caller and one for nlookup (released in
1072 * unref_inode_lolocked())
1074 g_atomic_int_set(&inode
->refcount
, 2);
1078 inode
->key
.ino
= e
->attr
.st_ino
;
1079 inode
->key
.dev
= e
->attr
.st_dev
;
1080 inode
->key
.mnt_id
= mnt_id
;
1081 if (lo
->posix_lock
) {
1082 pthread_mutex_init(&inode
->plock_mutex
, NULL
);
1083 inode
->posix_locks
= g_hash_table_new_full(
1084 g_direct_hash
, g_direct_equal
, NULL
, posix_locks_value_destroy
);
1086 pthread_mutex_lock(&lo
->mutex
);
1087 inode
->fuse_ino
= lo_add_inode_mapping(req
, inode
);
1088 g_hash_table_insert(lo
->inodes
, &inode
->key
, inode
);
1089 pthread_mutex_unlock(&lo
->mutex
);
1091 e
->ino
= inode
->fuse_ino
;
1093 /* Transfer ownership of inode pointer to caller or drop it */
1097 lo_inode_put(lo
, &inode
);
1100 lo_inode_put(lo
, &dir
);
1102 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
1103 name
, (unsigned long long)e
->ino
);
1112 lo_inode_put(lo
, &inode
);
1113 lo_inode_put(lo
, &dir
);
1117 static void lo_lookup(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
1119 struct fuse_entry_param e
;
1122 fuse_log(FUSE_LOG_DEBUG
, "lo_lookup(parent=%" PRIu64
", name=%s)\n", parent
,
1125 if (is_empty(name
)) {
1126 fuse_reply_err(req
, ENOENT
);
1131 * Don't use is_safe_path_component(), allow "." and ".." for NFS export
1134 if (strchr(name
, '/')) {
1135 fuse_reply_err(req
, EINVAL
);
1139 err
= lo_do_lookup(req
, parent
, name
, &e
, NULL
);
1141 fuse_reply_err(req
, err
);
1143 fuse_reply_entry(req
, &e
);
1148 * On some archs, setres*id is limited to 2^16 but they
1149 * provide setres*id32 variants that allow 2^32.
1150 * Others just let setres*id do 2^32 anyway.
1152 #ifdef SYS_setresgid32
1153 #define OURSYS_setresgid SYS_setresgid32
1155 #define OURSYS_setresgid SYS_setresgid
1158 #ifdef SYS_setresuid32
1159 #define OURSYS_setresuid SYS_setresuid32
1161 #define OURSYS_setresuid SYS_setresuid
1165 * Change to uid/gid of caller so that file is created with
1166 * ownership of caller.
1167 * TODO: What about selinux context?
1169 static int lo_change_cred(fuse_req_t req
, struct lo_cred
*old
,
1174 old
->euid
= geteuid();
1175 old
->egid
= getegid();
1177 res
= syscall(OURSYS_setresgid
, -1, fuse_req_ctx(req
)->gid
, -1);
1182 res
= syscall(OURSYS_setresuid
, -1, fuse_req_ctx(req
)->uid
, -1);
1184 int errno_save
= errno
;
1186 syscall(OURSYS_setresgid
, -1, old
->egid
, -1);
1191 old
->umask
= umask(req
->ctx
.umask
);
1196 /* Regain Privileges */
1197 static void lo_restore_cred(struct lo_cred
*old
, bool restore_umask
)
1201 res
= syscall(OURSYS_setresuid
, -1, old
->euid
, -1);
1203 fuse_log(FUSE_LOG_ERR
, "seteuid(%u): %m\n", old
->euid
);
1207 res
= syscall(OURSYS_setresgid
, -1, old
->egid
, -1);
1209 fuse_log(FUSE_LOG_ERR
, "setegid(%u): %m\n", old
->egid
);
1218 * A helper to change cred and drop capability. Returns 0 on success and
1221 static int lo_drop_cap_change_cred(fuse_req_t req
, struct lo_cred
*old
,
1222 bool change_umask
, const char *cap_name
,
1230 ret
= drop_effective_cap(cap_name
, &__cap_dropped
);
1235 ret
= lo_change_cred(req
, old
, change_umask
);
1237 if (__cap_dropped
) {
1238 if (gain_effective_cap(cap_name
)) {
1239 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_%s\n", cap_name
);
1245 *cap_dropped
= __cap_dropped
;
1250 static void lo_restore_cred_gain_cap(struct lo_cred
*old
, bool restore_umask
,
1251 const char *cap_name
)
1255 lo_restore_cred(old
, restore_umask
);
1257 if (gain_effective_cap(cap_name
)) {
1258 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_%s\n", cap_name
);
1262 static void lo_mknod_symlink(fuse_req_t req
, fuse_ino_t parent
,
1263 const char *name
, mode_t mode
, dev_t rdev
,
1268 struct lo_data
*lo
= lo_data(req
);
1269 struct lo_inode
*dir
;
1270 struct fuse_entry_param e
;
1271 struct lo_cred old
= {};
1273 if (is_empty(name
)) {
1274 fuse_reply_err(req
, ENOENT
);
1278 if (!is_safe_path_component(name
)) {
1279 fuse_reply_err(req
, EINVAL
);
1283 dir
= lo_inode(req
, parent
);
1285 fuse_reply_err(req
, EBADF
);
1289 saverr
= lo_change_cred(req
, &old
, lo
->change_umask
&& !S_ISLNK(mode
));
1294 res
= mknod_wrapper(dir
->fd
, name
, link
, mode
, rdev
);
1298 lo_restore_cred(&old
, lo
->change_umask
&& !S_ISLNK(mode
));
1304 saverr
= lo_do_lookup(req
, parent
, name
, &e
, NULL
);
1309 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
1310 name
, (unsigned long long)e
.ino
);
1312 fuse_reply_entry(req
, &e
);
1313 lo_inode_put(lo
, &dir
);
1317 lo_inode_put(lo
, &dir
);
1318 fuse_reply_err(req
, saverr
);
1321 static void lo_mknod(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1322 mode_t mode
, dev_t rdev
)
1324 lo_mknod_symlink(req
, parent
, name
, mode
, rdev
, NULL
);
1327 static void lo_mkdir(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1330 lo_mknod_symlink(req
, parent
, name
, S_IFDIR
| mode
, 0, NULL
);
1333 static void lo_symlink(fuse_req_t req
, const char *link
, fuse_ino_t parent
,
1336 lo_mknod_symlink(req
, parent
, name
, S_IFLNK
, 0, link
);
1339 static void lo_link(fuse_req_t req
, fuse_ino_t ino
, fuse_ino_t parent
,
1343 struct lo_data
*lo
= lo_data(req
);
1344 struct lo_inode
*parent_inode
;
1345 struct lo_inode
*inode
;
1346 struct fuse_entry_param e
;
1350 if (is_empty(name
)) {
1351 fuse_reply_err(req
, ENOENT
);
1355 if (!is_safe_path_component(name
)) {
1356 fuse_reply_err(req
, EINVAL
);
1360 parent_inode
= lo_inode(req
, parent
);
1361 inode
= lo_inode(req
, ino
);
1362 if (!parent_inode
|| !inode
) {
1367 memset(&e
, 0, sizeof(struct fuse_entry_param
));
1368 e
.attr_timeout
= lo
->timeout
;
1369 e
.entry_timeout
= lo
->timeout
;
1371 sprintf(procname
, "%i", inode
->fd
);
1372 res
= linkat(lo
->proc_self_fd
, procname
, parent_inode
->fd
, name
,
1378 res
= fstatat(inode
->fd
, "", &e
.attr
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
1383 pthread_mutex_lock(&lo
->mutex
);
1385 pthread_mutex_unlock(&lo
->mutex
);
1386 e
.ino
= inode
->fuse_ino
;
1388 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
1389 name
, (unsigned long long)e
.ino
);
1391 fuse_reply_entry(req
, &e
);
1392 lo_inode_put(lo
, &parent_inode
);
1393 lo_inode_put(lo
, &inode
);
1398 lo_inode_put(lo
, &parent_inode
);
1399 lo_inode_put(lo
, &inode
);
1400 fuse_reply_err(req
, saverr
);
1403 /* Increments nlookup and caller must release refcount using lo_inode_put() */
1404 static struct lo_inode
*lookup_name(fuse_req_t req
, fuse_ino_t parent
,
1410 struct lo_data
*lo
= lo_data(req
);
1411 struct lo_inode
*dir
= lo_inode(req
, parent
);
1417 res
= do_statx(lo
, dir
->fd
, name
, &attr
, AT_SYMLINK_NOFOLLOW
, &mnt_id
);
1418 lo_inode_put(lo
, &dir
);
1423 return lo_find(lo
, &attr
, mnt_id
);
1426 static void lo_rmdir(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
1429 struct lo_inode
*inode
;
1430 struct lo_data
*lo
= lo_data(req
);
1432 if (is_empty(name
)) {
1433 fuse_reply_err(req
, ENOENT
);
1437 if (!is_safe_path_component(name
)) {
1438 fuse_reply_err(req
, EINVAL
);
1442 inode
= lookup_name(req
, parent
, name
);
1444 fuse_reply_err(req
, EIO
);
1448 res
= unlinkat(lo_fd(req
, parent
), name
, AT_REMOVEDIR
);
1450 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1451 unref_inode_lolocked(lo
, inode
, 1);
1452 lo_inode_put(lo
, &inode
);
1455 static void lo_rename(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1456 fuse_ino_t newparent
, const char *newname
,
1460 struct lo_inode
*parent_inode
;
1461 struct lo_inode
*newparent_inode
;
1462 struct lo_inode
*oldinode
= NULL
;
1463 struct lo_inode
*newinode
= NULL
;
1464 struct lo_data
*lo
= lo_data(req
);
1466 if (is_empty(name
) || is_empty(newname
)) {
1467 fuse_reply_err(req
, ENOENT
);
1471 if (!is_safe_path_component(name
) || !is_safe_path_component(newname
)) {
1472 fuse_reply_err(req
, EINVAL
);
1476 parent_inode
= lo_inode(req
, parent
);
1477 newparent_inode
= lo_inode(req
, newparent
);
1478 if (!parent_inode
|| !newparent_inode
) {
1479 fuse_reply_err(req
, EBADF
);
1483 oldinode
= lookup_name(req
, parent
, name
);
1484 newinode
= lookup_name(req
, newparent
, newname
);
1487 fuse_reply_err(req
, EIO
);
1492 #ifndef SYS_renameat2
1493 fuse_reply_err(req
, EINVAL
);
1495 res
= syscall(SYS_renameat2
, parent_inode
->fd
, name
,
1496 newparent_inode
->fd
, newname
, flags
);
1497 if (res
== -1 && errno
== ENOSYS
) {
1498 fuse_reply_err(req
, EINVAL
);
1500 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1506 res
= renameat(parent_inode
->fd
, name
, newparent_inode
->fd
, newname
);
1508 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1510 unref_inode_lolocked(lo
, oldinode
, 1);
1511 unref_inode_lolocked(lo
, newinode
, 1);
1512 lo_inode_put(lo
, &oldinode
);
1513 lo_inode_put(lo
, &newinode
);
1514 lo_inode_put(lo
, &parent_inode
);
1515 lo_inode_put(lo
, &newparent_inode
);
1518 static void lo_unlink(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
1521 struct lo_inode
*inode
;
1522 struct lo_data
*lo
= lo_data(req
);
1524 if (is_empty(name
)) {
1525 fuse_reply_err(req
, ENOENT
);
1529 if (!is_safe_path_component(name
)) {
1530 fuse_reply_err(req
, EINVAL
);
1534 inode
= lookup_name(req
, parent
, name
);
1536 fuse_reply_err(req
, EIO
);
1540 res
= unlinkat(lo_fd(req
, parent
), name
, 0);
1542 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1543 unref_inode_lolocked(lo
, inode
, 1);
1544 lo_inode_put(lo
, &inode
);
1547 /* To be called with lo->mutex held */
1548 static void unref_inode(struct lo_data
*lo
, struct lo_inode
*inode
, uint64_t n
)
1554 assert(inode
->nlookup
>= n
);
1555 inode
->nlookup
-= n
;
1556 if (!inode
->nlookup
) {
1557 lo_map_remove(&lo
->ino_map
, inode
->fuse_ino
);
1558 g_hash_table_remove(lo
->inodes
, &inode
->key
);
1559 if (lo
->posix_lock
) {
1560 if (g_hash_table_size(inode
->posix_locks
)) {
1561 fuse_log(FUSE_LOG_WARNING
, "Hash table is not empty\n");
1563 g_hash_table_destroy(inode
->posix_locks
);
1564 pthread_mutex_destroy(&inode
->plock_mutex
);
1566 /* Drop our refcount from lo_do_lookup() */
1567 lo_inode_put(lo
, &inode
);
1571 static void unref_inode_lolocked(struct lo_data
*lo
, struct lo_inode
*inode
,
1578 pthread_mutex_lock(&lo
->mutex
);
1579 unref_inode(lo
, inode
, n
);
1580 pthread_mutex_unlock(&lo
->mutex
);
1583 static void lo_forget_one(fuse_req_t req
, fuse_ino_t ino
, uint64_t nlookup
)
1585 struct lo_data
*lo
= lo_data(req
);
1586 struct lo_inode
*inode
;
1588 inode
= lo_inode(req
, ino
);
1593 fuse_log(FUSE_LOG_DEBUG
, " forget %lli %lli -%lli\n",
1594 (unsigned long long)ino
, (unsigned long long)inode
->nlookup
,
1595 (unsigned long long)nlookup
);
1597 unref_inode_lolocked(lo
, inode
, nlookup
);
1598 lo_inode_put(lo
, &inode
);
1601 static void lo_forget(fuse_req_t req
, fuse_ino_t ino
, uint64_t nlookup
)
1603 lo_forget_one(req
, ino
, nlookup
);
1604 fuse_reply_none(req
);
1607 static void lo_forget_multi(fuse_req_t req
, size_t count
,
1608 struct fuse_forget_data
*forgets
)
1612 for (i
= 0; i
< count
; i
++) {
1613 lo_forget_one(req
, forgets
[i
].ino
, forgets
[i
].nlookup
);
1615 fuse_reply_none(req
);
1618 static void lo_readlink(fuse_req_t req
, fuse_ino_t ino
)
1620 char buf
[PATH_MAX
+ 1];
1623 res
= readlinkat(lo_fd(req
, ino
), "", buf
, sizeof(buf
));
1625 return (void)fuse_reply_err(req
, errno
);
1628 if (res
== sizeof(buf
)) {
1629 return (void)fuse_reply_err(req
, ENAMETOOLONG
);
1634 fuse_reply_readlink(req
, buf
);
1640 struct dirent
*entry
;
1644 static void lo_dirp_put(struct lo_dirp
**dp
)
1646 struct lo_dirp
*d
= *dp
;
1653 if (g_atomic_int_dec_and_test(&d
->refcount
)) {
1659 /* Call lo_dirp_put() on the return value when no longer needed */
1660 static struct lo_dirp
*lo_dirp(fuse_req_t req
, struct fuse_file_info
*fi
)
1662 struct lo_data
*lo
= lo_data(req
);
1663 struct lo_map_elem
*elem
;
1665 pthread_mutex_lock(&lo
->mutex
);
1666 elem
= lo_map_get(&lo
->dirp_map
, fi
->fh
);
1668 g_atomic_int_inc(&elem
->dirp
->refcount
);
1670 pthread_mutex_unlock(&lo
->mutex
);
1678 static void lo_opendir(fuse_req_t req
, fuse_ino_t ino
,
1679 struct fuse_file_info
*fi
)
1682 struct lo_data
*lo
= lo_data(req
);
1687 d
= calloc(1, sizeof(struct lo_dirp
));
1692 fd
= openat(lo_fd(req
, ino
), ".", O_RDONLY
);
1697 d
->dp
= fdopendir(fd
);
1698 if (d
->dp
== NULL
) {
1705 g_atomic_int_set(&d
->refcount
, 1); /* paired with lo_releasedir() */
1706 pthread_mutex_lock(&lo
->mutex
);
1707 fh
= lo_add_dirp_mapping(req
, d
);
1708 pthread_mutex_unlock(&lo
->mutex
);
1714 if (lo
->cache
== CACHE_ALWAYS
) {
1715 fi
->cache_readdir
= 1;
1717 fuse_reply_open(req
, fi
);
1726 } else if (fd
!= -1) {
1731 fuse_reply_err(req
, error
);
1734 static void lo_do_readdir(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
1735 off_t offset
, struct fuse_file_info
*fi
, int plus
)
1737 struct lo_data
*lo
= lo_data(req
);
1738 struct lo_dirp
*d
= NULL
;
1739 struct lo_inode
*dinode
;
1740 g_autofree
char *buf
= NULL
;
1745 dinode
= lo_inode(req
, ino
);
1750 d
= lo_dirp(req
, fi
);
1756 buf
= g_try_malloc0(size
);
1762 if (offset
!= d
->offset
) {
1763 seekdir(d
->dp
, offset
);
1774 d
->entry
= readdir(d
->dp
);
1776 if (errno
) { /* Error */
1779 } else { /* End of stream */
1784 nextoff
= d
->entry
->d_off
;
1785 name
= d
->entry
->d_name
;
1787 fuse_ino_t entry_ino
= 0;
1788 struct fuse_entry_param e
= (struct fuse_entry_param
){
1789 .attr
.st_ino
= d
->entry
->d_ino
,
1790 .attr
.st_mode
= d
->entry
->d_type
<< 12,
1793 /* Hide root's parent directory */
1794 if (dinode
== &lo
->root
&& strcmp(name
, "..") == 0) {
1795 e
.attr
.st_ino
= lo
->root
.key
.ino
;
1796 e
.attr
.st_mode
= DT_DIR
<< 12;
1800 if (!is_dot_or_dotdot(name
)) {
1801 err
= lo_do_lookup(req
, ino
, name
, &e
, NULL
);
1808 entsize
= fuse_add_direntry_plus(req
, p
, rem
, name
, &e
, nextoff
);
1810 entsize
= fuse_add_direntry(req
, p
, rem
, name
, &e
.attr
, nextoff
);
1812 if (entsize
> rem
) {
1813 if (entry_ino
!= 0) {
1814 lo_forget_one(req
, entry_ino
, 1);
1823 d
->offset
= nextoff
;
1829 lo_inode_put(lo
, &dinode
);
1832 * If there's an error, we can only signal it if we haven't stored
1833 * any entries yet - otherwise we'd end up with wrong lookup
1834 * counts for the entries that are already in the buffer. So we
1835 * return what we've collected until that point.
1837 if (err
&& rem
== size
) {
1838 fuse_reply_err(req
, err
);
1840 fuse_reply_buf(req
, buf
, size
- rem
);
1844 static void lo_readdir(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
1845 off_t offset
, struct fuse_file_info
*fi
)
1847 lo_do_readdir(req
, ino
, size
, offset
, fi
, 0);
1850 static void lo_readdirplus(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
1851 off_t offset
, struct fuse_file_info
*fi
)
1853 lo_do_readdir(req
, ino
, size
, offset
, fi
, 1);
1856 static void lo_releasedir(fuse_req_t req
, fuse_ino_t ino
,
1857 struct fuse_file_info
*fi
)
1859 struct lo_data
*lo
= lo_data(req
);
1860 struct lo_map_elem
*elem
;
1865 pthread_mutex_lock(&lo
->mutex
);
1866 elem
= lo_map_get(&lo
->dirp_map
, fi
->fh
);
1868 pthread_mutex_unlock(&lo
->mutex
);
1869 fuse_reply_err(req
, EBADF
);
1874 lo_map_remove(&lo
->dirp_map
, fi
->fh
);
1875 pthread_mutex_unlock(&lo
->mutex
);
1877 lo_dirp_put(&d
); /* paired with lo_opendir() */
1879 fuse_reply_err(req
, 0);
1882 static void update_open_flags(int writeback
, int allow_direct_io
,
1883 struct fuse_file_info
*fi
)
1886 * With writeback cache, kernel may send read requests even
1887 * when userspace opened write-only
1889 if (writeback
&& (fi
->flags
& O_ACCMODE
) == O_WRONLY
) {
1890 fi
->flags
&= ~O_ACCMODE
;
1891 fi
->flags
|= O_RDWR
;
1895 * With writeback cache, O_APPEND is handled by the kernel.
1896 * This breaks atomicity (since the file may change in the
1897 * underlying filesystem, so that the kernel's idea of the
1898 * end of the file isn't accurate anymore). In this example,
1899 * we just accept that. A more rigorous filesystem may want
1900 * to return an error here
1902 if (writeback
&& (fi
->flags
& O_APPEND
)) {
1903 fi
->flags
&= ~O_APPEND
;
1907 * O_DIRECT in guest should not necessarily mean bypassing page
1908 * cache on host as well. Therefore, we discard it by default
1909 * ('-o no_allow_direct_io'). If somebody needs that behavior,
1910 * the '-o allow_direct_io' option should be set.
1912 if (!allow_direct_io
) {
1913 fi
->flags
&= ~O_DIRECT
;
1918 * Open a regular file, set up an fd mapping, and fill out the struct
1919 * fuse_file_info for it. If existing_fd is not negative, use that fd instead
1920 * opening a new one. Takes ownership of existing_fd.
1922 * Returns 0 on success or a positive errno.
1924 static int lo_do_open(struct lo_data
*lo
, struct lo_inode
*inode
,
1925 int existing_fd
, struct fuse_file_info
*fi
)
1928 int fd
= existing_fd
;
1930 bool cap_fsetid_dropped
= false;
1931 bool kill_suidgid
= lo
->killpriv_v2
&& fi
->kill_priv
;
1933 update_open_flags(lo
->writeback
, lo
->allow_direct_io
, fi
);
1937 err
= drop_effective_cap("FSETID", &cap_fsetid_dropped
);
1943 fd
= lo_inode_open(lo
, inode
, fi
->flags
);
1945 if (cap_fsetid_dropped
) {
1946 if (gain_effective_cap("FSETID")) {
1947 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_FSETID\n");
1953 if (fi
->flags
& (O_TRUNC
)) {
1954 int err
= drop_security_capability(lo
, fd
);
1962 pthread_mutex_lock(&lo
->mutex
);
1963 fh
= lo_add_fd_mapping(lo
, fd
);
1964 pthread_mutex_unlock(&lo
->mutex
);
1971 if (lo
->cache
== CACHE_NONE
) {
1973 } else if (lo
->cache
== CACHE_ALWAYS
) {
1979 static void lo_create(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1980 mode_t mode
, struct fuse_file_info
*fi
)
1983 struct lo_data
*lo
= lo_data(req
);
1984 struct lo_inode
*parent_inode
;
1985 struct lo_inode
*inode
= NULL
;
1986 struct fuse_entry_param e
;
1988 struct lo_cred old
= {};
1990 fuse_log(FUSE_LOG_DEBUG
, "lo_create(parent=%" PRIu64
", name=%s)"
1991 " kill_priv=%d\n", parent
, name
, fi
->kill_priv
);
1993 if (!is_safe_path_component(name
)) {
1994 fuse_reply_err(req
, EINVAL
);
1998 parent_inode
= lo_inode(req
, parent
);
1999 if (!parent_inode
) {
2000 fuse_reply_err(req
, EBADF
);
2004 err
= lo_change_cred(req
, &old
, lo
->change_umask
);
2009 update_open_flags(lo
->writeback
, lo
->allow_direct_io
, fi
);
2011 /* Try to create a new file but don't open existing files */
2012 fd
= openat(parent_inode
->fd
, name
, fi
->flags
| O_CREAT
| O_EXCL
, mode
);
2013 err
= fd
== -1 ? errno
: 0;
2015 lo_restore_cred(&old
, lo
->change_umask
);
2017 /* Ignore the error if file exists and O_EXCL was not given */
2018 if (err
&& (err
!= EEXIST
|| (fi
->flags
& O_EXCL
))) {
2022 err
= lo_do_lookup(req
, parent
, name
, &e
, &inode
);
2027 err
= lo_do_open(lo
, inode
, fd
, fi
);
2028 fd
= -1; /* lo_do_open() takes ownership of fd */
2030 /* Undo lo_do_lookup() nlookup ref */
2031 unref_inode_lolocked(lo
, inode
, 1);
2035 lo_inode_put(lo
, &inode
);
2036 lo_inode_put(lo
, &parent_inode
);
2043 fuse_reply_err(req
, err
);
2045 fuse_reply_create(req
, &e
, fi
);
2049 /* Should be called with inode->plock_mutex held */
2050 static struct lo_inode_plock
*lookup_create_plock_ctx(struct lo_data
*lo
,
2051 struct lo_inode
*inode
,
2052 uint64_t lock_owner
,
2053 pid_t pid
, int *err
)
2055 struct lo_inode_plock
*plock
;
2059 g_hash_table_lookup(inode
->posix_locks
, GUINT_TO_POINTER(lock_owner
));
2065 plock
= malloc(sizeof(struct lo_inode_plock
));
2071 /* Open another instance of file which can be used for ofd locks. */
2072 /* TODO: What if file is not writable? */
2073 fd
= lo_inode_open(lo
, inode
, O_RDWR
);
2080 plock
->lock_owner
= lock_owner
;
2082 g_hash_table_insert(inode
->posix_locks
, GUINT_TO_POINTER(plock
->lock_owner
),
2087 static void lo_getlk(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
2090 struct lo_data
*lo
= lo_data(req
);
2091 struct lo_inode
*inode
;
2092 struct lo_inode_plock
*plock
;
2093 int ret
, saverr
= 0;
2095 fuse_log(FUSE_LOG_DEBUG
,
2096 "lo_getlk(ino=%" PRIu64
", flags=%d)"
2097 " owner=0x%" PRIx64
", l_type=%d l_start=0x%" PRIx64
2098 " l_len=0x%" PRIx64
"\n",
2099 ino
, fi
->flags
, fi
->lock_owner
, lock
->l_type
,
2100 (uint64_t)lock
->l_start
, (uint64_t)lock
->l_len
);
2102 if (!lo
->posix_lock
) {
2103 fuse_reply_err(req
, ENOSYS
);
2107 inode
= lo_inode(req
, ino
);
2109 fuse_reply_err(req
, EBADF
);
2113 pthread_mutex_lock(&inode
->plock_mutex
);
2115 lookup_create_plock_ctx(lo
, inode
, fi
->lock_owner
, lock
->l_pid
, &ret
);
2121 ret
= fcntl(plock
->fd
, F_OFD_GETLK
, lock
);
2127 pthread_mutex_unlock(&inode
->plock_mutex
);
2128 lo_inode_put(lo
, &inode
);
2131 fuse_reply_err(req
, saverr
);
2133 fuse_reply_lock(req
, lock
);
2137 static void lo_setlk(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
2138 struct flock
*lock
, int sleep
)
2140 struct lo_data
*lo
= lo_data(req
);
2141 struct lo_inode
*inode
;
2142 struct lo_inode_plock
*plock
;
2143 int ret
, saverr
= 0;
2145 fuse_log(FUSE_LOG_DEBUG
,
2146 "lo_setlk(ino=%" PRIu64
", flags=%d)"
2147 " cmd=%d pid=%d owner=0x%" PRIx64
" sleep=%d l_whence=%d"
2148 " l_start=0x%" PRIx64
" l_len=0x%" PRIx64
"\n",
2149 ino
, fi
->flags
, lock
->l_type
, lock
->l_pid
, fi
->lock_owner
, sleep
,
2150 lock
->l_whence
, (uint64_t)lock
->l_start
, (uint64_t)lock
->l_len
);
2152 if (!lo
->posix_lock
) {
2153 fuse_reply_err(req
, ENOSYS
);
2158 fuse_reply_err(req
, EOPNOTSUPP
);
2162 inode
= lo_inode(req
, ino
);
2164 fuse_reply_err(req
, EBADF
);
2168 pthread_mutex_lock(&inode
->plock_mutex
);
2170 lookup_create_plock_ctx(lo
, inode
, fi
->lock_owner
, lock
->l_pid
, &ret
);
2177 /* TODO: Is it alright to modify flock? */
2179 ret
= fcntl(plock
->fd
, F_OFD_SETLK
, lock
);
2185 pthread_mutex_unlock(&inode
->plock_mutex
);
2186 lo_inode_put(lo
, &inode
);
2188 fuse_reply_err(req
, saverr
);
2191 static void lo_fsyncdir(fuse_req_t req
, fuse_ino_t ino
, int datasync
,
2192 struct fuse_file_info
*fi
)
2200 d
= lo_dirp(req
, fi
);
2202 fuse_reply_err(req
, EBADF
);
2208 res
= fdatasync(fd
);
2215 fuse_reply_err(req
, res
== -1 ? errno
: 0);
2218 static void lo_open(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
)
2220 struct lo_data
*lo
= lo_data(req
);
2221 struct lo_inode
*inode
= lo_inode(req
, ino
);
2224 fuse_log(FUSE_LOG_DEBUG
, "lo_open(ino=%" PRIu64
", flags=%d, kill_priv=%d)"
2225 "\n", ino
, fi
->flags
, fi
->kill_priv
);
2228 fuse_reply_err(req
, EBADF
);
2232 err
= lo_do_open(lo
, inode
, -1, fi
);
2233 lo_inode_put(lo
, &inode
);
2235 fuse_reply_err(req
, err
);
2237 fuse_reply_open(req
, fi
);
2241 static void lo_release(fuse_req_t req
, fuse_ino_t ino
,
2242 struct fuse_file_info
*fi
)
2244 struct lo_data
*lo
= lo_data(req
);
2245 struct lo_map_elem
*elem
;
2250 pthread_mutex_lock(&lo
->mutex
);
2251 elem
= lo_map_get(&lo
->fd_map
, fi
->fh
);
2255 lo_map_remove(&lo
->fd_map
, fi
->fh
);
2257 pthread_mutex_unlock(&lo
->mutex
);
2260 fuse_reply_err(req
, 0);
2263 static void lo_flush(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
)
2267 struct lo_inode
*inode
;
2268 struct lo_data
*lo
= lo_data(req
);
2270 inode
= lo_inode(req
, ino
);
2272 fuse_reply_err(req
, EBADF
);
2276 if (!S_ISREG(inode
->filetype
)) {
2277 lo_inode_put(lo
, &inode
);
2278 fuse_reply_err(req
, EBADF
);
2282 /* An fd is going away. Cleanup associated posix locks */
2283 if (lo
->posix_lock
) {
2284 pthread_mutex_lock(&inode
->plock_mutex
);
2285 g_hash_table_remove(inode
->posix_locks
,
2286 GUINT_TO_POINTER(fi
->lock_owner
));
2287 pthread_mutex_unlock(&inode
->plock_mutex
);
2289 res
= close(dup(lo_fi_fd(req
, fi
)));
2290 lo_inode_put(lo
, &inode
);
2291 fuse_reply_err(req
, res
== -1 ? errno
: 0);
2294 static void lo_fsync(fuse_req_t req
, fuse_ino_t ino
, int datasync
,
2295 struct fuse_file_info
*fi
)
2297 struct lo_inode
*inode
= lo_inode(req
, ino
);
2298 struct lo_data
*lo
= lo_data(req
);
2302 fuse_log(FUSE_LOG_DEBUG
, "lo_fsync(ino=%" PRIu64
", fi=0x%p)\n", ino
,
2306 fuse_reply_err(req
, EBADF
);
2311 fd
= lo_inode_open(lo
, inode
, O_RDWR
);
2317 fd
= lo_fi_fd(req
, fi
);
2321 res
= fdatasync(fd
) == -1 ? errno
: 0;
2323 res
= fsync(fd
) == -1 ? errno
: 0;
2329 lo_inode_put(lo
, &inode
);
2330 fuse_reply_err(req
, res
);
2333 static void lo_read(fuse_req_t req
, fuse_ino_t ino
, size_t size
, off_t offset
,
2334 struct fuse_file_info
*fi
)
2336 struct fuse_bufvec buf
= FUSE_BUFVEC_INIT(size
);
2338 fuse_log(FUSE_LOG_DEBUG
,
2339 "lo_read(ino=%" PRIu64
", size=%zd, "
2341 ino
, size
, (unsigned long)offset
);
2343 buf
.buf
[0].flags
= FUSE_BUF_IS_FD
| FUSE_BUF_FD_SEEK
;
2344 buf
.buf
[0].fd
= lo_fi_fd(req
, fi
);
2345 buf
.buf
[0].pos
= offset
;
2347 fuse_reply_data(req
, &buf
);
2350 static void lo_write_buf(fuse_req_t req
, fuse_ino_t ino
,
2351 struct fuse_bufvec
*in_buf
, off_t off
,
2352 struct fuse_file_info
*fi
)
2356 struct fuse_bufvec out_buf
= FUSE_BUFVEC_INIT(fuse_buf_size(in_buf
));
2357 bool cap_fsetid_dropped
= false;
2359 out_buf
.buf
[0].flags
= FUSE_BUF_IS_FD
| FUSE_BUF_FD_SEEK
;
2360 out_buf
.buf
[0].fd
= lo_fi_fd(req
, fi
);
2361 out_buf
.buf
[0].pos
= off
;
2363 fuse_log(FUSE_LOG_DEBUG
,
2364 "lo_write_buf(ino=%" PRIu64
", size=%zd, off=%lu kill_priv=%d)\n",
2365 ino
, out_buf
.buf
[0].size
, (unsigned long)off
, fi
->kill_priv
);
2367 res
= drop_security_capability(lo_data(req
), out_buf
.buf
[0].fd
);
2369 fuse_reply_err(req
, res
);
2374 * If kill_priv is set, drop CAP_FSETID which should lead to kernel
2375 * clearing setuid/setgid on file. Note, for WRITE, we need to do
2376 * this even if killpriv_v2 is not enabled. fuse direct write path
2379 if (fi
->kill_priv
) {
2380 res
= drop_effective_cap("FSETID", &cap_fsetid_dropped
);
2382 fuse_reply_err(req
, res
);
2387 res
= fuse_buf_copy(&out_buf
, in_buf
);
2389 fuse_reply_err(req
, -res
);
2391 fuse_reply_write(req
, (size_t)res
);
2394 if (cap_fsetid_dropped
) {
2395 res
= gain_effective_cap("FSETID");
2397 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_FSETID\n");
2402 static void lo_statfs(fuse_req_t req
, fuse_ino_t ino
)
2405 struct statvfs stbuf
;
2407 res
= fstatvfs(lo_fd(req
, ino
), &stbuf
);
2409 fuse_reply_err(req
, errno
);
2411 fuse_reply_statfs(req
, &stbuf
);
2415 static void lo_fallocate(fuse_req_t req
, fuse_ino_t ino
, int mode
, off_t offset
,
2416 off_t length
, struct fuse_file_info
*fi
)
2418 int err
= EOPNOTSUPP
;
2421 #ifdef CONFIG_FALLOCATE
2422 err
= fallocate(lo_fi_fd(req
, fi
), mode
, offset
, length
);
2427 #elif defined(CONFIG_POSIX_FALLOCATE)
2429 fuse_reply_err(req
, EOPNOTSUPP
);
2433 err
= posix_fallocate(lo_fi_fd(req
, fi
), offset
, length
);
2436 fuse_reply_err(req
, err
);
2439 static void lo_flock(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
2445 res
= flock(lo_fi_fd(req
, fi
), op
);
2447 fuse_reply_err(req
, res
== -1 ? errno
: 0);
2452 * Exit; process attribute unmodified if matched.
2453 * An empty key applies to all.
2455 #define XATTR_MAP_FLAG_OK (1 << 0)
2457 * The attribute is unwanted;
2458 * EPERM on write, hidden on read.
2460 #define XATTR_MAP_FLAG_BAD (1 << 1)
2462 * For attr that start with 'key' prepend 'prepend'
2463 * 'key' may be empty to prepend for all attrs
2464 * key is defined from set/remove point of view.
2465 * Automatically reversed on read
2467 #define XATTR_MAP_FLAG_PREFIX (1 << 2)
2470 /* Apply rule to get/set/remove */
2471 #define XATTR_MAP_FLAG_CLIENT (1 << 16)
2472 /* Apply rule to list */
2473 #define XATTR_MAP_FLAG_SERVER (1 << 17)
2474 /* Apply rule to all */
2475 #define XATTR_MAP_FLAG_ALL (XATTR_MAP_FLAG_SERVER | XATTR_MAP_FLAG_CLIENT)
2477 static void add_xattrmap_entry(struct lo_data
*lo
,
2478 const XattrMapEntry
*new_entry
)
2480 XattrMapEntry
*res
= g_realloc_n(lo
->xattr_map_list
,
2481 lo
->xattr_map_nentries
+ 1,
2482 sizeof(XattrMapEntry
));
2483 res
[lo
->xattr_map_nentries
++] = *new_entry
;
2485 lo
->xattr_map_list
= res
;
2488 static void free_xattrmap(struct lo_data
*lo
)
2490 XattrMapEntry
*map
= lo
->xattr_map_list
;
2497 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
2499 g_free(map
[i
].prepend
);
2503 lo
->xattr_map_list
= NULL
;
2504 lo
->xattr_map_nentries
= -1;
2508 * Handle the 'map' type, which is sugar for a set of commands
2509 * for the common case of prefixing a subset or everything,
2510 * and allowing anything not prefixed through.
2511 * It must be the last entry in the stream, although there
2512 * can be other entries before it.
2516 * key maybe empty in which case all entries are prefixed.
2518 static void parse_xattrmap_map(struct lo_data
*lo
,
2519 const char *rule
, char sep
)
2524 XattrMapEntry tmp_entry
;
2527 fuse_log(FUSE_LOG_ERR
,
2528 "%s: Expecting '%c' after 'map' keyword, found '%c'\n",
2529 __func__
, sep
, *rule
);
2535 /* At start of 'key' field */
2536 tmp
= strchr(rule
, sep
);
2538 fuse_log(FUSE_LOG_ERR
,
2539 "%s: Missing '%c' at end of key field in map rule\n",
2544 key
= g_strndup(rule
, tmp
- rule
);
2547 /* At start of prefix field */
2548 tmp
= strchr(rule
, sep
);
2550 fuse_log(FUSE_LOG_ERR
,
2551 "%s: Missing '%c' at end of prefix field in map rule\n",
2556 prefix
= g_strndup(rule
, tmp
- rule
);
2560 * This should be the end of the string, we don't allow
2561 * any more commands after 'map'.
2564 fuse_log(FUSE_LOG_ERR
,
2565 "%s: Expecting end of command after map, found '%c'\n",
2570 /* 1st: Prefix matches/everything */
2571 tmp_entry
.flags
= XATTR_MAP_FLAG_PREFIX
| XATTR_MAP_FLAG_ALL
;
2572 tmp_entry
.key
= g_strdup(key
);
2573 tmp_entry
.prepend
= g_strdup(prefix
);
2574 add_xattrmap_entry(lo
, &tmp_entry
);
2577 /* Prefix all case */
2579 /* 2nd: Hide any non-prefixed entries on the host */
2580 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_ALL
;
2581 tmp_entry
.key
= g_strdup("");
2582 tmp_entry
.prepend
= g_strdup("");
2583 add_xattrmap_entry(lo
, &tmp_entry
);
2585 /* Prefix matching case */
2587 /* 2nd: Hide non-prefixed but matching entries on the host */
2588 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_SERVER
;
2589 tmp_entry
.key
= g_strdup(""); /* Not used */
2590 tmp_entry
.prepend
= g_strdup(key
);
2591 add_xattrmap_entry(lo
, &tmp_entry
);
2593 /* 3rd: Stop the client accessing prefixed attributes directly */
2594 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_CLIENT
;
2595 tmp_entry
.key
= g_strdup(prefix
);
2596 tmp_entry
.prepend
= g_strdup(""); /* Not used */
2597 add_xattrmap_entry(lo
, &tmp_entry
);
2599 /* 4th: Everything else is OK */
2600 tmp_entry
.flags
= XATTR_MAP_FLAG_OK
| XATTR_MAP_FLAG_ALL
;
2601 tmp_entry
.key
= g_strdup("");
2602 tmp_entry
.prepend
= g_strdup("");
2603 add_xattrmap_entry(lo
, &tmp_entry
);
2610 static void parse_xattrmap(struct lo_data
*lo
)
2612 const char *map
= lo
->xattrmap
;
2616 lo
->xattr_map_nentries
= 0;
2618 XattrMapEntry tmp_entry
;
2621 if (isspace(*map
)) {
2625 /* The separator is the first non-space of the rule */
2631 tmp_entry
.flags
= 0;
2632 /* Start of 'type' */
2633 if (strstart(map
, "prefix", &map
)) {
2634 tmp_entry
.flags
|= XATTR_MAP_FLAG_PREFIX
;
2635 } else if (strstart(map
, "ok", &map
)) {
2636 tmp_entry
.flags
|= XATTR_MAP_FLAG_OK
;
2637 } else if (strstart(map
, "bad", &map
)) {
2638 tmp_entry
.flags
|= XATTR_MAP_FLAG_BAD
;
2639 } else if (strstart(map
, "map", &map
)) {
2641 * map is sugar that adds a number of rules, and must be
2644 parse_xattrmap_map(lo
, map
, sep
);
2647 fuse_log(FUSE_LOG_ERR
,
2648 "%s: Unexpected type;"
2649 "Expecting 'prefix', 'ok', 'bad' or 'map' in rule %zu\n",
2650 __func__
, lo
->xattr_map_nentries
);
2654 if (*map
++ != sep
) {
2655 fuse_log(FUSE_LOG_ERR
,
2656 "%s: Missing '%c' at end of type field of rule %zu\n",
2657 __func__
, sep
, lo
->xattr_map_nentries
);
2661 /* Start of 'scope' */
2662 if (strstart(map
, "client", &map
)) {
2663 tmp_entry
.flags
|= XATTR_MAP_FLAG_CLIENT
;
2664 } else if (strstart(map
, "server", &map
)) {
2665 tmp_entry
.flags
|= XATTR_MAP_FLAG_SERVER
;
2666 } else if (strstart(map
, "all", &map
)) {
2667 tmp_entry
.flags
|= XATTR_MAP_FLAG_ALL
;
2669 fuse_log(FUSE_LOG_ERR
,
2670 "%s: Unexpected scope;"
2671 " Expecting 'client', 'server', or 'all', in rule %zu\n",
2672 __func__
, lo
->xattr_map_nentries
);
2676 if (*map
++ != sep
) {
2677 fuse_log(FUSE_LOG_ERR
,
2678 "%s: Expecting '%c' found '%c'"
2679 " after scope in rule %zu\n",
2680 __func__
, sep
, *map
, lo
->xattr_map_nentries
);
2684 /* At start of 'key' field */
2685 tmp
= strchr(map
, sep
);
2687 fuse_log(FUSE_LOG_ERR
,
2688 "%s: Missing '%c' at end of key field of rule %zu",
2689 __func__
, sep
, lo
->xattr_map_nentries
);
2692 tmp_entry
.key
= g_strndup(map
, tmp
- map
);
2695 /* At start of 'prepend' field */
2696 tmp
= strchr(map
, sep
);
2698 fuse_log(FUSE_LOG_ERR
,
2699 "%s: Missing '%c' at end of prepend field of rule %zu",
2700 __func__
, sep
, lo
->xattr_map_nentries
);
2703 tmp_entry
.prepend
= g_strndup(map
, tmp
- map
);
2706 add_xattrmap_entry(lo
, &tmp_entry
);
2707 /* End of rule - go around again for another rule */
2710 if (!lo
->xattr_map_nentries
) {
2711 fuse_log(FUSE_LOG_ERR
, "Empty xattr map\n");
2715 ret
= xattr_map_client(lo
, "security.capability",
2716 &lo
->xattr_security_capability
);
2718 fuse_log(FUSE_LOG_ERR
, "Failed to map security.capability: %s\n",
2722 if (!lo
->xattr_security_capability
||
2723 !strcmp(lo
->xattr_security_capability
, "security.capability")) {
2724 /* 1-1 mapping, don't need to do anything */
2725 free(lo
->xattr_security_capability
);
2726 lo
->xattr_security_capability
= NULL
;
2731 * For use with getxattr/setxattr/removexattr, where the client
2732 * gives us a name and we may need to choose a different one.
2733 * Allocates a buffer for the result placing it in *out_name.
2734 * If there's no change then *out_name is not set.
2735 * Returns 0 on success
2736 * Can return -EPERM to indicate we block a given attribute
2737 * (in which case out_name is not allocated)
2738 * Can return -ENOMEM to indicate out_name couldn't be allocated.
2740 static int xattr_map_client(const struct lo_data
*lo
, const char *client_name
,
2744 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
2745 const XattrMapEntry
*cur_entry
= lo
->xattr_map_list
+ i
;
2747 if ((cur_entry
->flags
& XATTR_MAP_FLAG_CLIENT
) &&
2748 (strstart(client_name
, cur_entry
->key
, NULL
))) {
2749 if (cur_entry
->flags
& XATTR_MAP_FLAG_BAD
) {
2752 if (cur_entry
->flags
& XATTR_MAP_FLAG_OK
) {
2753 /* Unmodified name */
2756 if (cur_entry
->flags
& XATTR_MAP_FLAG_PREFIX
) {
2757 *out_name
= g_try_malloc(strlen(client_name
) +
2758 strlen(cur_entry
->prepend
) + 1);
2762 sprintf(*out_name
, "%s%s", cur_entry
->prepend
, client_name
);
2772 * For use with listxattr where the server fs gives us a name and we may need
2773 * to sanitize this for the client.
2774 * Returns a pointer to the result in *out_name
2775 * This is always the original string or the current string with some prefix
2776 * removed; no reallocation is done.
2777 * Returns 0 on success
2778 * Can return -ENODATA to indicate the name should be dropped from the list.
2780 static int xattr_map_server(const struct lo_data
*lo
, const char *server_name
,
2781 const char **out_name
)
2786 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
2787 const XattrMapEntry
*cur_entry
= lo
->xattr_map_list
+ i
;
2789 if ((cur_entry
->flags
& XATTR_MAP_FLAG_SERVER
) &&
2790 (strstart(server_name
, cur_entry
->prepend
, &end
))) {
2791 if (cur_entry
->flags
& XATTR_MAP_FLAG_BAD
) {
2794 if (cur_entry
->flags
& XATTR_MAP_FLAG_OK
) {
2795 *out_name
= server_name
;
2798 if (cur_entry
->flags
& XATTR_MAP_FLAG_PREFIX
) {
2809 #define FCHDIR_NOFAIL(fd) do { \
2810 int fchdir_res = fchdir(fd); \
2811 assert(fchdir_res == 0); \
2814 static bool block_xattr(struct lo_data
*lo
, const char *name
)
2817 * If user explicitly enabled posix_acl or did not provide any option,
2818 * do not block acl. Otherwise block system.posix_acl_access and
2819 * system.posix_acl_default xattrs.
2821 if (lo
->user_posix_acl
) {
2824 if (!strcmp(name
, "system.posix_acl_access") ||
2825 !strcmp(name
, "system.posix_acl_default"))
2832 * Returns number of bytes in xattr_list after filtering on success. This
2833 * could be zero as well if nothing is left after filtering.
2835 * Returns negative error code on failure.
2836 * xattr_list is modified in place.
2838 static int remove_blocked_xattrs(struct lo_data
*lo
, char *xattr_list
,
2841 size_t out_index
, in_index
;
2844 * As of now we only filter out acl xattrs. If acls are enabled or
2845 * they have not been explicitly disabled, there is nothing to
2848 if (lo
->user_posix_acl
) {
2854 while (in_index
< in_size
) {
2855 char *in_ptr
= xattr_list
+ in_index
;
2857 /* Length of current attribute name */
2858 size_t in_len
= strlen(xattr_list
+ in_index
) + 1;
2860 if (!block_xattr(lo
, in_ptr
)) {
2861 if (in_index
!= out_index
) {
2862 memmove(xattr_list
+ out_index
, xattr_list
+ in_index
, in_len
);
2864 out_index
+= in_len
;
2871 static void lo_getxattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
,
2874 struct lo_data
*lo
= lo_data(req
);
2875 g_autofree
char *value
= NULL
;
2879 struct lo_inode
*inode
;
2884 if (block_xattr(lo
, in_name
)) {
2885 fuse_reply_err(req
, EOPNOTSUPP
);
2892 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
2894 if (ret
== -EPERM
) {
2897 fuse_reply_err(req
, -ret
);
2905 inode
= lo_inode(req
, ino
);
2907 fuse_reply_err(req
, EBADF
);
2908 g_free(mapped_name
);
2913 if (!lo_data(req
)->xattr
) {
2917 fuse_log(FUSE_LOG_DEBUG
, "lo_getxattr(ino=%" PRIu64
", name=%s size=%zd)\n",
2921 value
= g_try_malloc(size
);
2927 sprintf(procname
, "%i", inode
->fd
);
2929 * It is not safe to open() non-regular/non-dir files in file server
2930 * unless O_PATH is used, so use that method for regular files/dir
2931 * only (as it seems giving less performance overhead).
2932 * Otherwise, call fchdir() to avoid open().
2934 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
2935 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
2939 ret
= fgetxattr(fd
, name
, value
, size
);
2940 saverr
= ret
== -1 ? errno
: 0;
2942 /* fchdir should not fail here */
2943 FCHDIR_NOFAIL(lo
->proc_self_fd
);
2944 ret
= getxattr(procname
, name
, value
, size
);
2945 saverr
= ret
== -1 ? errno
: 0;
2946 FCHDIR_NOFAIL(lo
->root
.fd
);
2957 fuse_reply_buf(req
, value
, ret
);
2959 fuse_reply_xattr(req
, ret
);
2966 lo_inode_put(lo
, &inode
);
2972 fuse_reply_err(req
, saverr
);
2973 g_free(mapped_name
);
2977 static void lo_listxattr(fuse_req_t req
, fuse_ino_t ino
, size_t size
)
2979 struct lo_data
*lo
= lo_data(req
);
2980 g_autofree
char *value
= NULL
;
2982 struct lo_inode
*inode
;
2987 inode
= lo_inode(req
, ino
);
2989 fuse_reply_err(req
, EBADF
);
2994 if (!lo_data(req
)->xattr
) {
2998 fuse_log(FUSE_LOG_DEBUG
, "lo_listxattr(ino=%" PRIu64
", size=%zd)\n", ino
,
3002 value
= g_try_malloc(size
);
3008 sprintf(procname
, "%i", inode
->fd
);
3009 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
3010 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
3014 ret
= flistxattr(fd
, value
, size
);
3015 saverr
= ret
== -1 ? errno
: 0;
3017 /* fchdir should not fail here */
3018 FCHDIR_NOFAIL(lo
->proc_self_fd
);
3019 ret
= listxattr(procname
, value
, size
);
3020 saverr
= ret
== -1 ? errno
: 0;
3021 FCHDIR_NOFAIL(lo
->root
.fd
);
3033 if (lo
->xattr_map_list
) {
3035 * Map the names back, some attributes might be dropped,
3036 * some shortened, but not increased, so we shouldn't
3039 size_t out_index
, in_index
;
3042 while (in_index
< ret
) {
3043 const char *map_out
;
3044 char *in_ptr
= value
+ in_index
;
3045 /* Length of current attribute name */
3046 size_t in_len
= strlen(value
+ in_index
) + 1;
3048 int mapret
= xattr_map_server(lo
, in_ptr
, &map_out
);
3049 if (mapret
!= -ENODATA
&& mapret
!= 0) {
3050 /* Shouldn't happen */
3055 /* Either unchanged, or truncated */
3057 if (map_out
!= in_ptr
) {
3058 /* +1 copies the NIL */
3059 out_len
= strlen(map_out
) + 1;
3065 * Move result along, may still be needed for an unchanged
3066 * entry if a previous entry was changed.
3068 memmove(value
+ out_index
, map_out
, out_len
);
3070 out_index
+= out_len
;
3080 ret
= remove_blocked_xattrs(lo
, value
, ret
);
3085 fuse_reply_buf(req
, value
, ret
);
3088 * xattrmap only ever shortens the result,
3089 * so we don't need to do anything clever with the
3090 * allocation length here.
3092 fuse_reply_xattr(req
, ret
);
3099 lo_inode_put(lo
, &inode
);
3105 fuse_reply_err(req
, saverr
);
3109 static void lo_setxattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
,
3110 const char *value
, size_t size
, int flags
,
3111 uint32_t extra_flags
)
3116 struct lo_data
*lo
= lo_data(req
);
3117 struct lo_inode
*inode
;
3121 bool switched_creds
= false;
3122 bool cap_fsetid_dropped
= false;
3123 struct lo_cred old
= {};
3125 if (block_xattr(lo
, in_name
)) {
3126 fuse_reply_err(req
, EOPNOTSUPP
);
3133 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
3135 fuse_reply_err(req
, -ret
);
3143 inode
= lo_inode(req
, ino
);
3145 fuse_reply_err(req
, EBADF
);
3146 g_free(mapped_name
);
3151 if (!lo_data(req
)->xattr
) {
3155 fuse_log(FUSE_LOG_DEBUG
, "lo_setxattr(ino=%" PRIu64
3156 ", name=%s value=%s size=%zd)\n", ino
, name
, value
, size
);
3158 sprintf(procname
, "%i", inode
->fd
);
3160 * If we are setting posix access acl and if SGID needs to be
3161 * cleared, then switch to caller's gid and drop CAP_FSETID
3162 * and that should make sure host kernel clears SGID.
3164 * This probably will not work when we support idmapped mounts.
3165 * In that case we will need to find a non-root gid and switch
3166 * to it. (Instead of gid in request). Fix it when we support
3169 if (lo
->posix_acl
&& !strcmp(name
, "system.posix_acl_access")
3170 && (extra_flags
& FUSE_SETXATTR_ACL_KILL_SGID
)) {
3171 ret
= lo_drop_cap_change_cred(req
, &old
, false, "FSETID",
3172 &cap_fsetid_dropped
);
3177 switched_creds
= true;
3179 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
3180 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
3185 ret
= fsetxattr(fd
, name
, value
, size
, flags
);
3186 saverr
= ret
== -1 ? errno
: 0;
3188 /* fchdir should not fail here */
3189 FCHDIR_NOFAIL(lo
->proc_self_fd
);
3190 ret
= setxattr(procname
, name
, value
, size
, flags
);
3191 saverr
= ret
== -1 ? errno
: 0;
3192 FCHDIR_NOFAIL(lo
->root
.fd
);
3194 if (switched_creds
) {
3195 if (cap_fsetid_dropped
)
3196 lo_restore_cred_gain_cap(&old
, false, "FSETID");
3198 lo_restore_cred(&old
, false);
3206 lo_inode_put(lo
, &inode
);
3207 g_free(mapped_name
);
3208 fuse_reply_err(req
, saverr
);
3211 static void lo_removexattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
)
3216 struct lo_data
*lo
= lo_data(req
);
3217 struct lo_inode
*inode
;
3222 if (block_xattr(lo
, in_name
)) {
3223 fuse_reply_err(req
, EOPNOTSUPP
);
3230 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
3232 fuse_reply_err(req
, -ret
);
3240 inode
= lo_inode(req
, ino
);
3242 fuse_reply_err(req
, EBADF
);
3243 g_free(mapped_name
);
3248 if (!lo_data(req
)->xattr
) {
3252 fuse_log(FUSE_LOG_DEBUG
, "lo_removexattr(ino=%" PRIu64
", name=%s)\n", ino
,
3255 sprintf(procname
, "%i", inode
->fd
);
3256 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
3257 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
3262 ret
= fremovexattr(fd
, name
);
3263 saverr
= ret
== -1 ? errno
: 0;
3265 /* fchdir should not fail here */
3266 FCHDIR_NOFAIL(lo
->proc_self_fd
);
3267 ret
= removexattr(procname
, name
);
3268 saverr
= ret
== -1 ? errno
: 0;
3269 FCHDIR_NOFAIL(lo
->root
.fd
);
3277 lo_inode_put(lo
, &inode
);
3278 g_free(mapped_name
);
3279 fuse_reply_err(req
, saverr
);
3282 #ifdef HAVE_COPY_FILE_RANGE
3283 static void lo_copy_file_range(fuse_req_t req
, fuse_ino_t ino_in
, off_t off_in
,
3284 struct fuse_file_info
*fi_in
, fuse_ino_t ino_out
,
3285 off_t off_out
, struct fuse_file_info
*fi_out
,
3286 size_t len
, int flags
)
3291 in_fd
= lo_fi_fd(req
, fi_in
);
3292 out_fd
= lo_fi_fd(req
, fi_out
);
3294 fuse_log(FUSE_LOG_DEBUG
,
3295 "lo_copy_file_range(ino=%" PRIu64
"/fd=%d, "
3296 "off=%ju, ino=%" PRIu64
"/fd=%d, "
3297 "off=%ju, size=%zd, flags=0x%x)\n",
3298 ino_in
, in_fd
, (intmax_t)off_in
,
3299 ino_out
, out_fd
, (intmax_t)off_out
, len
, flags
);
3301 res
= copy_file_range(in_fd
, &off_in
, out_fd
, &off_out
, len
, flags
);
3303 fuse_reply_err(req
, errno
);
3305 fuse_reply_write(req
, res
);
3310 static void lo_lseek(fuse_req_t req
, fuse_ino_t ino
, off_t off
, int whence
,
3311 struct fuse_file_info
*fi
)
3316 res
= lseek(lo_fi_fd(req
, fi
), off
, whence
);
3318 fuse_reply_lseek(req
, res
);
3320 fuse_reply_err(req
, errno
);
3324 static void lo_destroy(void *userdata
)
3326 struct lo_data
*lo
= (struct lo_data
*)userdata
;
3328 pthread_mutex_lock(&lo
->mutex
);
3330 GHashTableIter iter
;
3331 gpointer key
, value
;
3333 g_hash_table_iter_init(&iter
, lo
->inodes
);
3334 if (!g_hash_table_iter_next(&iter
, &key
, &value
)) {
3338 struct lo_inode
*inode
= value
;
3339 unref_inode(lo
, inode
, inode
->nlookup
);
3341 pthread_mutex_unlock(&lo
->mutex
);
3344 static struct fuse_lowlevel_ops lo_oper
= {
3346 .lookup
= lo_lookup
,
3349 .symlink
= lo_symlink
,
3351 .unlink
= lo_unlink
,
3353 .rename
= lo_rename
,
3354 .forget
= lo_forget
,
3355 .forget_multi
= lo_forget_multi
,
3356 .getattr
= lo_getattr
,
3357 .setattr
= lo_setattr
,
3358 .readlink
= lo_readlink
,
3359 .opendir
= lo_opendir
,
3360 .readdir
= lo_readdir
,
3361 .readdirplus
= lo_readdirplus
,
3362 .releasedir
= lo_releasedir
,
3363 .fsyncdir
= lo_fsyncdir
,
3364 .create
= lo_create
,
3368 .release
= lo_release
,
3372 .write_buf
= lo_write_buf
,
3373 .statfs
= lo_statfs
,
3374 .fallocate
= lo_fallocate
,
3376 .getxattr
= lo_getxattr
,
3377 .listxattr
= lo_listxattr
,
3378 .setxattr
= lo_setxattr
,
3379 .removexattr
= lo_removexattr
,
3380 #ifdef HAVE_COPY_FILE_RANGE
3381 .copy_file_range
= lo_copy_file_range
,
3384 .destroy
= lo_destroy
,
3387 /* Print vhost-user.json backend program capabilities */
3388 static void print_capabilities(void)
3391 printf(" \"type\": \"fs\"\n");
3396 * Drop all Linux capabilities because the wait parent process only needs to
3397 * sit in waitpid(2) and terminate.
3399 static void setup_wait_parent_capabilities(void)
3401 capng_setpid(syscall(SYS_gettid
));
3402 capng_clear(CAPNG_SELECT_BOTH
);
3403 capng_apply(CAPNG_SELECT_BOTH
);
3407 * Move to a new mount, net, and pid namespaces to isolate this process.
3409 static void setup_namespaces(struct lo_data
*lo
, struct fuse_session
*se
)
3414 * Create a new pid namespace for *child* processes. We'll have to
3415 * fork in order to enter the new pid namespace. A new mount namespace
3416 * is also needed so that we can remount /proc for the new pid
3419 * Our UNIX domain sockets have been created. Now we can move to
3420 * an empty network namespace to prevent TCP/IP and other network
3421 * activity in case this process is compromised.
3423 if (unshare(CLONE_NEWPID
| CLONE_NEWNS
| CLONE_NEWNET
) != 0) {
3424 fuse_log(FUSE_LOG_ERR
, "unshare(CLONE_NEWPID | CLONE_NEWNS): %m\n");
3430 fuse_log(FUSE_LOG_ERR
, "fork() failed: %m\n");
3437 setup_wait_parent_capabilities();
3439 /* The parent waits for the child */
3441 waited
= waitpid(child
, &wstatus
, 0);
3442 } while (waited
< 0 && errno
== EINTR
&& !se
->exited
);
3444 /* We were terminated by a signal, see fuse_signals.c */
3449 if (WIFEXITED(wstatus
)) {
3450 exit(WEXITSTATUS(wstatus
));
3456 /* Send us SIGTERM when the parent thread terminates, see prctl(2) */
3457 prctl(PR_SET_PDEATHSIG
, SIGTERM
);
3460 * If the mounts have shared propagation then we want to opt out so our
3461 * mount changes don't affect the parent mount namespace.
3463 if (mount(NULL
, "/", NULL
, MS_REC
| MS_SLAVE
, NULL
) < 0) {
3464 fuse_log(FUSE_LOG_ERR
, "mount(/, MS_REC|MS_SLAVE): %m\n");
3468 /* The child must remount /proc to use the new pid namespace */
3469 if (mount("proc", "/proc", "proc",
3470 MS_NODEV
| MS_NOEXEC
| MS_NOSUID
| MS_RELATIME
, NULL
) < 0) {
3471 fuse_log(FUSE_LOG_ERR
, "mount(/proc): %m\n");
3476 * We only need /proc/self/fd. Prevent ".." from accessing parent
3477 * directories of /proc/self/fd by bind-mounting it over /proc. Since / was
3478 * previously remounted with MS_REC | MS_SLAVE this mount change only
3479 * affects our process.
3481 if (mount("/proc/self/fd", "/proc", NULL
, MS_BIND
, NULL
) < 0) {
3482 fuse_log(FUSE_LOG_ERR
, "mount(/proc/self/fd, MS_BIND): %m\n");
3486 /* Get the /proc (actually /proc/self/fd, see above) file descriptor */
3487 lo
->proc_self_fd
= open("/proc", O_PATH
);
3488 if (lo
->proc_self_fd
== -1) {
3489 fuse_log(FUSE_LOG_ERR
, "open(/proc, O_PATH): %m\n");
3495 * Capture the capability state, we'll need to restore this for individual
3496 * threads later; see load_capng.
3498 static void setup_capng(void)
3500 /* Note this accesses /proc so has to happen before the sandbox */
3501 if (capng_get_caps_process()) {
3502 fuse_log(FUSE_LOG_ERR
, "capng_get_caps_process\n");
3505 pthread_mutex_init(&cap
.mutex
, NULL
);
3506 pthread_mutex_lock(&cap
.mutex
);
3507 cap
.saved
= capng_save_state();
3509 fuse_log(FUSE_LOG_ERR
, "capng_save_state\n");
3512 pthread_mutex_unlock(&cap
.mutex
);
3515 static void cleanup_capng(void)
3519 pthread_mutex_destroy(&cap
.mutex
);
3524 * Make the source directory our root so symlinks cannot escape and no other
3525 * files are accessible. Assumes unshare(CLONE_NEWNS) was already called.
3527 static void setup_mounts(const char *source
)
3532 if (mount(source
, source
, NULL
, MS_BIND
| MS_REC
, NULL
) < 0) {
3533 fuse_log(FUSE_LOG_ERR
, "mount(%s, %s, MS_BIND): %m\n", source
, source
);
3537 /* This magic is based on lxc's lxc_pivot_root() */
3538 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
3540 fuse_log(FUSE_LOG_ERR
, "open(/): %m\n");
3544 newroot
= open(source
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
3546 fuse_log(FUSE_LOG_ERR
, "open(%s): %m\n", source
);
3550 if (fchdir(newroot
) < 0) {
3551 fuse_log(FUSE_LOG_ERR
, "fchdir(newroot): %m\n");
3555 if (syscall(__NR_pivot_root
, ".", ".") < 0) {
3556 fuse_log(FUSE_LOG_ERR
, "pivot_root(., .): %m\n");
3560 if (fchdir(oldroot
) < 0) {
3561 fuse_log(FUSE_LOG_ERR
, "fchdir(oldroot): %m\n");
3565 if (mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
) < 0) {
3566 fuse_log(FUSE_LOG_ERR
, "mount(., MS_SLAVE | MS_REC): %m\n");
3570 if (umount2(".", MNT_DETACH
) < 0) {
3571 fuse_log(FUSE_LOG_ERR
, "umount2(., MNT_DETACH): %m\n");
3575 if (fchdir(newroot
) < 0) {
3576 fuse_log(FUSE_LOG_ERR
, "fchdir(newroot): %m\n");
3585 * Only keep capabilities in allowlist that are needed for file system operation
3586 * The (possibly NULL) modcaps_in string passed in is free'd before exit.
3588 static void setup_capabilities(char *modcaps_in
)
3590 char *modcaps
= modcaps_in
;
3591 pthread_mutex_lock(&cap
.mutex
);
3592 capng_restore_state(&cap
.saved
);
3595 * Add to allowlist file system-related capabilities that are needed for a
3596 * file server to act like root. Drop everything else like networking and
3597 * sysadmin capabilities.
3600 * 1. CAP_LINUX_IMMUTABLE is not included because it's only used via ioctl
3601 * and we don't support that.
3602 * 2. CAP_MAC_OVERRIDE is not included because it only seems to be
3603 * used by the Smack LSM. Omit it until there is demand for it.
3605 capng_setpid(syscall(SYS_gettid
));
3606 capng_clear(CAPNG_SELECT_BOTH
);
3607 if (capng_updatev(CAPNG_ADD
, CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
3617 fuse_log(FUSE_LOG_ERR
, "%s: capng_updatev failed\n", __func__
);
3622 * The modcaps option is a colon separated list of caps,
3623 * each preceded by either + or -.
3629 char *next
= strchr(modcaps
, ':');
3635 switch (modcaps
[0]) {
3641 action
= CAPNG_DROP
;
3645 fuse_log(FUSE_LOG_ERR
,
3646 "%s: Expecting '+'/'-' in modcaps but found '%c'\n",
3647 __func__
, modcaps
[0]);
3650 cap
= capng_name_to_capability(modcaps
+ 1);
3652 fuse_log(FUSE_LOG_ERR
, "%s: Unknown capability '%s'\n", __func__
,
3656 if (capng_update(action
, CAPNG_PERMITTED
| CAPNG_EFFECTIVE
, cap
)) {
3657 fuse_log(FUSE_LOG_ERR
, "%s: capng_update failed for '%s'\n",
3666 if (capng_apply(CAPNG_SELECT_BOTH
)) {
3667 fuse_log(FUSE_LOG_ERR
, "%s: capng_apply failed\n", __func__
);
3671 cap
.saved
= capng_save_state();
3673 fuse_log(FUSE_LOG_ERR
, "%s: capng_save_state failed\n", __func__
);
3676 pthread_mutex_unlock(&cap
.mutex
);
3680 * Use chroot as a weaker sandbox for environments where the process is
3681 * launched without CAP_SYS_ADMIN.
3683 static void setup_chroot(struct lo_data
*lo
)
3685 lo
->proc_self_fd
= open("/proc/self/fd", O_PATH
);
3686 if (lo
->proc_self_fd
== -1) {
3687 fuse_log(FUSE_LOG_ERR
, "open(\"/proc/self/fd\", O_PATH): %m\n");
3692 * Make the shared directory the file system root so that FUSE_OPEN
3693 * (lo_open()) cannot escape the shared directory by opening a symlink.
3695 * The chroot(2) syscall is later disabled by seccomp and the
3696 * CAP_SYS_CHROOT capability is dropped so that tampering with the chroot
3699 * However, it's still possible to escape the chroot via lo->proc_self_fd
3700 * but that requires first gaining control of the process.
3702 if (chroot(lo
->source
) != 0) {
3703 fuse_log(FUSE_LOG_ERR
, "chroot(\"%s\"): %m\n", lo
->source
);
3707 /* Move into the chroot */
3708 if (chdir("/") != 0) {
3709 fuse_log(FUSE_LOG_ERR
, "chdir(\"/\"): %m\n");
3715 * Lock down this process to prevent access to other processes or files outside
3716 * source directory. This reduces the impact of arbitrary code execution bugs.
3718 static void setup_sandbox(struct lo_data
*lo
, struct fuse_session
*se
,
3721 if (lo
->sandbox
== SANDBOX_NAMESPACE
) {
3722 setup_namespaces(lo
, se
);
3723 setup_mounts(lo
->source
);
3728 setup_seccomp(enable_syslog
);
3729 setup_capabilities(g_strdup(lo
->modcaps
));
3732 /* Set the maximum number of open file descriptors */
3733 static void setup_nofile_rlimit(unsigned long rlimit_nofile
)
3735 struct rlimit rlim
= {
3736 .rlim_cur
= rlimit_nofile
,
3737 .rlim_max
= rlimit_nofile
,
3740 if (rlimit_nofile
== 0) {
3741 return; /* nothing to do */
3744 if (setrlimit(RLIMIT_NOFILE
, &rlim
) < 0) {
3745 /* Ignore SELinux denials */
3746 if (errno
== EPERM
) {
3750 fuse_log(FUSE_LOG_ERR
, "setrlimit(RLIMIT_NOFILE): %m\n");
3755 static void log_func(enum fuse_log_level level
, const char *fmt
, va_list ap
)
3757 g_autofree
char *localfmt
= NULL
;
3759 if (current_log_level
< level
) {
3763 if (current_log_level
== FUSE_LOG_DEBUG
) {
3765 /* no timestamp needed */
3766 localfmt
= g_strdup_printf("[ID: %08ld] %s", syscall(__NR_gettid
),
3769 g_autoptr(GDateTime
) now
= g_date_time_new_now_utc();
3770 g_autofree
char *nowstr
= g_date_time_format(now
, "%Y-%m-%d %H:%M:%S.%f%z");
3771 localfmt
= g_strdup_printf("[%s] [ID: %08ld] %s",
3772 nowstr
, syscall(__NR_gettid
), fmt
);
3778 int priority
= LOG_ERR
;
3780 case FUSE_LOG_EMERG
:
3781 priority
= LOG_EMERG
;
3783 case FUSE_LOG_ALERT
:
3784 priority
= LOG_ALERT
;
3787 priority
= LOG_CRIT
;
3792 case FUSE_LOG_WARNING
:
3793 priority
= LOG_WARNING
;
3795 case FUSE_LOG_NOTICE
:
3796 priority
= LOG_NOTICE
;
3799 priority
= LOG_INFO
;
3801 case FUSE_LOG_DEBUG
:
3802 priority
= LOG_DEBUG
;
3805 vsyslog(priority
, fmt
, ap
);
3807 vfprintf(stderr
, fmt
, ap
);
3811 static void setup_root(struct lo_data
*lo
, struct lo_inode
*root
)
3817 fd
= open("/", O_PATH
);
3819 fuse_log(FUSE_LOG_ERR
, "open(%s, O_PATH): %m\n", lo
->source
);
3823 res
= do_statx(lo
, fd
, "", &stat
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
,
3826 fuse_log(FUSE_LOG_ERR
, "fstatat(%s): %m\n", lo
->source
);
3830 root
->filetype
= S_IFDIR
;
3832 root
->key
.ino
= stat
.st_ino
;
3833 root
->key
.dev
= stat
.st_dev
;
3834 root
->key
.mnt_id
= mnt_id
;
3836 g_atomic_int_set(&root
->refcount
, 2);
3837 if (lo
->posix_lock
) {
3838 pthread_mutex_init(&root
->plock_mutex
, NULL
);
3839 root
->posix_locks
= g_hash_table_new_full(
3840 g_direct_hash
, g_direct_equal
, NULL
, posix_locks_value_destroy
);
3844 static guint
lo_key_hash(gconstpointer key
)
3846 const struct lo_key
*lkey
= key
;
3848 return (guint
)lkey
->ino
+ (guint
)lkey
->dev
+ (guint
)lkey
->mnt_id
;
3851 static gboolean
lo_key_equal(gconstpointer a
, gconstpointer b
)
3853 const struct lo_key
*la
= a
;
3854 const struct lo_key
*lb
= b
;
3856 return la
->ino
== lb
->ino
&& la
->dev
== lb
->dev
&& la
->mnt_id
== lb
->mnt_id
;
3859 static void fuse_lo_data_cleanup(struct lo_data
*lo
)
3862 g_hash_table_destroy(lo
->inodes
);
3865 if (lo
->root
.posix_locks
) {
3866 g_hash_table_destroy(lo
->root
.posix_locks
);
3868 lo_map_destroy(&lo
->fd_map
);
3869 lo_map_destroy(&lo
->dirp_map
);
3870 lo_map_destroy(&lo
->ino_map
);
3872 if (lo
->proc_self_fd
>= 0) {
3873 close(lo
->proc_self_fd
);
3876 if (lo
->root
.fd
>= 0) {
3882 free(lo
->xattr_security_capability
);
3886 static void qemu_version(void)
3888 printf("virtiofsd version " QEMU_FULL_VERSION
"\n" QEMU_COPYRIGHT
"\n");
3891 int main(int argc
, char *argv
[])
3893 struct fuse_args args
= FUSE_ARGS_INIT(argc
, argv
);
3894 struct fuse_session
*se
;
3895 struct fuse_cmdline_opts opts
;
3896 struct lo_data lo
= {
3897 .sandbox
= SANDBOX_NAMESPACE
,
3901 .allow_direct_io
= 0,
3903 .user_killpriv_v2
= -1,
3904 .user_posix_acl
= -1,
3906 struct lo_map_elem
*root_elem
;
3907 struct lo_map_elem
*reserve_elem
;
3910 /* Initialize time conversion information for localtime_r(). */
3913 /* Don't mask creation mode, kernel already did that */
3916 qemu_init_exec_dir(argv
[0]);
3918 pthread_mutex_init(&lo
.mutex
, NULL
);
3919 lo
.inodes
= g_hash_table_new(lo_key_hash
, lo_key_equal
);
3921 lo
.root
.fuse_ino
= FUSE_ROOT_ID
;
3922 lo
.cache
= CACHE_AUTO
;
3925 * Set up the ino map like this:
3926 * [0] Reserved (will not be used)
3929 lo_map_init(&lo
.ino_map
);
3930 reserve_elem
= lo_map_reserve(&lo
.ino_map
, 0);
3931 if (!reserve_elem
) {
3932 fuse_log(FUSE_LOG_ERR
, "failed to alloc reserve_elem.\n");
3935 reserve_elem
->in_use
= false;
3936 root_elem
= lo_map_reserve(&lo
.ino_map
, lo
.root
.fuse_ino
);
3938 fuse_log(FUSE_LOG_ERR
, "failed to alloc root_elem.\n");
3941 root_elem
->inode
= &lo
.root
;
3943 lo_map_init(&lo
.dirp_map
);
3944 lo_map_init(&lo
.fd_map
);
3946 if (fuse_parse_cmdline(&args
, &opts
) != 0) {
3949 fuse_set_log_func(log_func
);
3950 use_syslog
= opts
.syslog
;
3952 openlog("virtiofsd", LOG_PID
, LOG_DAEMON
);
3955 if (opts
.show_help
) {
3956 printf("usage: %s [options]\n\n", argv
[0]);
3957 fuse_cmdline_help();
3958 printf(" -o source=PATH shared directory tree\n");
3959 fuse_lowlevel_help();
3962 } else if (opts
.show_version
) {
3964 fuse_lowlevel_version();
3967 } else if (opts
.print_capabilities
) {
3968 print_capabilities();
3973 if (fuse_opt_parse(&args
, &lo
, lo_opts
, NULL
) == -1) {
3977 if (opts
.log_level
!= 0) {
3978 current_log_level
= opts
.log_level
;
3980 /* default log level is INFO */
3981 current_log_level
= FUSE_LOG_INFO
;
3983 lo
.debug
= opts
.debug
;
3985 current_log_level
= FUSE_LOG_DEBUG
;
3991 res
= lstat(lo
.source
, &stat
);
3993 fuse_log(FUSE_LOG_ERR
, "failed to stat source (\"%s\"): %m\n",
3997 if (!S_ISDIR(stat
.st_mode
)) {
3998 fuse_log(FUSE_LOG_ERR
, "source is not a directory\n");
4002 lo
.source
= strdup("/");
4004 fuse_log(FUSE_LOG_ERR
, "failed to strdup source\n");
4011 parse_xattrmap(&lo
);
4014 if (!lo
.timeout_set
) {
4025 lo
.timeout
= 86400.0;
4028 } else if (lo
.timeout
< 0) {
4029 fuse_log(FUSE_LOG_ERR
, "timeout is negative (%lf)\n", lo
.timeout
);
4033 if (lo
.user_posix_acl
== 1 && !lo
.xattr
) {
4034 fuse_log(FUSE_LOG_ERR
, "Can't enable posix ACLs. xattrs are disabled."
4039 lo
.use_statx
= true;
4041 se
= fuse_session_new(&args
, &lo_oper
, sizeof(lo_oper
), &lo
);
4046 if (fuse_set_signal_handlers(se
) != 0) {
4050 if (fuse_session_mount(se
) != 0) {
4054 fuse_daemonize(opts
.foreground
);
4056 setup_nofile_rlimit(opts
.rlimit_nofile
);
4058 /* Must be before sandbox since it wants /proc */
4061 setup_sandbox(&lo
, se
, opts
.syslog
);
4063 setup_root(&lo
, &lo
.root
);
4064 /* Block until ctrl+c or fusermount -u */
4065 ret
= virtio_loop(se
);
4067 fuse_session_unmount(se
);
4070 fuse_remove_signal_handlers(se
);
4072 fuse_session_destroy(se
);
4074 fuse_opt_free_args(&args
);
4076 fuse_lo_data_cleanup(&lo
);