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/help-texts.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 /* An O_PATH file descriptor to /proc/self/task/ */
178 int user_killpriv_v2
, killpriv_v2
;
179 /* If set, virtiofsd is responsible for setting umask during creation */
181 int user_posix_acl
, posix_acl
;
182 /* Keeps track if /proc/<pid>/attr/fscreate should be used or not */
184 int user_security_label
;
187 static const struct fuse_opt lo_opts
[] = {
188 { "sandbox=namespace",
189 offsetof(struct lo_data
, sandbox
),
192 offsetof(struct lo_data
, sandbox
),
194 { "writeback", offsetof(struct lo_data
, writeback
), 1 },
195 { "no_writeback", offsetof(struct lo_data
, writeback
), 0 },
196 { "source=%s", offsetof(struct lo_data
, source
), 0 },
197 { "flock", offsetof(struct lo_data
, flock
), 1 },
198 { "no_flock", offsetof(struct lo_data
, flock
), 0 },
199 { "posix_lock", offsetof(struct lo_data
, posix_lock
), 1 },
200 { "no_posix_lock", offsetof(struct lo_data
, posix_lock
), 0 },
201 { "xattr", offsetof(struct lo_data
, xattr
), 1 },
202 { "no_xattr", offsetof(struct lo_data
, xattr
), 0 },
203 { "xattrmap=%s", offsetof(struct lo_data
, xattrmap
), 0 },
204 { "modcaps=%s", offsetof(struct lo_data
, modcaps
), 0 },
205 { "timeout=%lf", offsetof(struct lo_data
, timeout
), 0 },
206 { "timeout=", offsetof(struct lo_data
, timeout_set
), 1 },
207 { "cache=none", offsetof(struct lo_data
, cache
), CACHE_NONE
},
208 { "cache=auto", offsetof(struct lo_data
, cache
), CACHE_AUTO
},
209 { "cache=always", offsetof(struct lo_data
, cache
), CACHE_ALWAYS
},
210 { "readdirplus", offsetof(struct lo_data
, readdirplus_set
), 1 },
211 { "no_readdirplus", offsetof(struct lo_data
, readdirplus_clear
), 1 },
212 { "allow_direct_io", offsetof(struct lo_data
, allow_direct_io
), 1 },
213 { "no_allow_direct_io", offsetof(struct lo_data
, allow_direct_io
), 0 },
214 { "announce_submounts", offsetof(struct lo_data
, announce_submounts
), 1 },
215 { "killpriv_v2", offsetof(struct lo_data
, user_killpriv_v2
), 1 },
216 { "no_killpriv_v2", offsetof(struct lo_data
, user_killpriv_v2
), 0 },
217 { "posix_acl", offsetof(struct lo_data
, user_posix_acl
), 1 },
218 { "no_posix_acl", offsetof(struct lo_data
, user_posix_acl
), 0 },
219 { "security_label", offsetof(struct lo_data
, user_security_label
), 1 },
220 { "no_security_label", offsetof(struct lo_data
, user_security_label
), 0 },
223 static bool use_syslog
= false;
224 static int current_log_level
;
225 static void unref_inode_lolocked(struct lo_data
*lo
, struct lo_inode
*inode
,
229 pthread_mutex_t mutex
;
232 /* That we loaded cap-ng in the current thread from the saved */
233 static __thread
bool cap_loaded
= 0;
235 static struct lo_inode
*lo_find(struct lo_data
*lo
, struct stat
*st
,
237 static int xattr_map_client(const struct lo_data
*lo
, const char *client_name
,
240 #define FCHDIR_NOFAIL(fd) do { \
241 int fchdir_res = fchdir(fd); \
242 assert(fchdir_res == 0); \
245 static bool is_dot_or_dotdot(const char *name
)
247 return name
[0] == '.' &&
248 (name
[1] == '\0' || (name
[1] == '.' && name
[2] == '\0'));
251 /* Is `path` a single path component that is not "." or ".."? */
252 static bool is_safe_path_component(const char *path
)
254 if (strchr(path
, '/')) {
258 return !is_dot_or_dotdot(path
);
261 static bool is_empty(const char *name
)
263 return name
[0] == '\0';
266 static struct lo_data
*lo_data(fuse_req_t req
)
268 return (struct lo_data
*)fuse_req_userdata(req
);
272 * Tries to figure out if /proc/<pid>/attr/fscreate is usable or not. With
273 * selinux=0, read from fscreate returns -EINVAL.
275 * TODO: Link with libselinux and use is_selinux_enabled() instead down
276 * the line. It probably will be more reliable indicator.
278 static bool is_fscreate_usable(struct lo_data
*lo
)
284 sprintf(procname
, "%ld/attr/fscreate", syscall(SYS_gettid
));
285 fscreate_fd
= openat(lo
->proc_self_task
, procname
, O_RDWR
);
286 if (fscreate_fd
== -1) {
290 bytes_read
= read(fscreate_fd
, procname
, 64);
292 if (bytes_read
== -1) {
298 /* Helpers to set/reset fscreate */
299 static int open_set_proc_fscreate(struct lo_data
*lo
, const void *ctx
,
300 size_t ctxlen
, int *fd
)
303 int fscreate_fd
, err
= 0;
306 sprintf(procname
, "%ld/attr/fscreate", syscall(SYS_gettid
));
307 fscreate_fd
= openat(lo
->proc_self_task
, procname
, O_WRONLY
);
308 err
= fscreate_fd
== -1 ? errno
: 0;
313 written
= write(fscreate_fd
, ctx
, ctxlen
);
314 err
= written
== -1 ? errno
: 0;
326 static void close_reset_proc_fscreate(int fd
)
328 if ((write(fd
, NULL
, 0)) == -1) {
329 fuse_log(FUSE_LOG_WARNING
, "Failed to reset fscreate. err=%d\n", errno
);
336 * Load capng's state from our saved state if the current thread
337 * hadn't previously been loaded.
338 * returns 0 on success
340 static int load_capng(void)
343 pthread_mutex_lock(&cap
.mutex
);
344 capng_restore_state(&cap
.saved
);
346 * restore_state free's the saved copy
349 cap
.saved
= capng_save_state();
351 pthread_mutex_unlock(&cap
.mutex
);
352 fuse_log(FUSE_LOG_ERR
, "capng_save_state (thread)\n");
355 pthread_mutex_unlock(&cap
.mutex
);
358 * We want to use the loaded state for our pid,
361 capng_setpid(syscall(SYS_gettid
));
368 * Helpers for dropping and regaining effective capabilities. Returns 0
369 * on success, error otherwise
371 static int drop_effective_cap(const char *cap_name
, bool *cap_dropped
)
375 cap
= capng_name_to_capability(cap_name
);
378 fuse_log(FUSE_LOG_ERR
, "capng_name_to_capability(%s) failed:%s\n",
379 cap_name
, strerror(errno
));
385 fuse_log(FUSE_LOG_ERR
, "load_capng() failed\n");
389 /* We dont have this capability in effective set already. */
390 if (!capng_have_capability(CAPNG_EFFECTIVE
, cap
)) {
395 if (capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, cap
)) {
397 fuse_log(FUSE_LOG_ERR
, "capng_update(DROP,) failed\n");
401 if (capng_apply(CAPNG_SELECT_CAPS
)) {
403 fuse_log(FUSE_LOG_ERR
, "drop:capng_apply() failed\n");
416 static int gain_effective_cap(const char *cap_name
)
421 cap
= capng_name_to_capability(cap_name
);
424 fuse_log(FUSE_LOG_ERR
, "capng_name_to_capability(%s) failed:%s\n",
425 cap_name
, strerror(errno
));
431 fuse_log(FUSE_LOG_ERR
, "load_capng() failed\n");
435 if (capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, cap
)) {
437 fuse_log(FUSE_LOG_ERR
, "capng_update(ADD,) failed\n");
441 if (capng_apply(CAPNG_SELECT_CAPS
)) {
443 fuse_log(FUSE_LOG_ERR
, "gain:capng_apply() failed\n");
453 * The host kernel normally drops security.capability xattr's on
454 * any write, however if we're remapping xattr names we need to drop
455 * whatever the clients security.capability is actually stored as.
457 static int drop_security_capability(const struct lo_data
*lo
, int fd
)
459 if (!lo
->xattr_security_capability
) {
460 /* We didn't remap the name, let the host kernel do it */
463 if (!fremovexattr(fd
, lo
->xattr_security_capability
)) {
470 /* Attribute didn't exist, that's fine */
474 /* FS didn't support attribute anyway, also fine */
478 /* Hmm other error */
483 static void lo_map_init(struct lo_map
*map
)
490 static void lo_map_destroy(struct lo_map
*map
)
495 static int lo_map_grow(struct lo_map
*map
, size_t new_nelems
)
497 struct lo_map_elem
*new_elems
;
500 if (new_nelems
<= map
->nelems
) {
504 new_elems
= g_try_realloc_n(map
->elems
, new_nelems
, sizeof(map
->elems
[0]));
509 for (i
= map
->nelems
; i
< new_nelems
; i
++) {
510 new_elems
[i
].freelist
= i
+ 1;
511 new_elems
[i
].in_use
= false;
513 new_elems
[new_nelems
- 1].freelist
= -1;
515 map
->elems
= new_elems
;
516 map
->freelist
= map
->nelems
;
517 map
->nelems
= new_nelems
;
521 static struct lo_map_elem
*lo_map_alloc_elem(struct lo_map
*map
)
523 struct lo_map_elem
*elem
;
525 if (map
->freelist
== -1 && !lo_map_grow(map
, map
->nelems
+ 256)) {
529 elem
= &map
->elems
[map
->freelist
];
530 map
->freelist
= elem
->freelist
;
537 static struct lo_map_elem
*lo_map_reserve(struct lo_map
*map
, size_t key
)
541 if (!lo_map_grow(map
, key
+ 1)) {
545 for (prev
= &map
->freelist
; *prev
!= -1;
546 prev
= &map
->elems
[*prev
].freelist
) {
548 struct lo_map_elem
*elem
= &map
->elems
[key
];
550 *prev
= elem
->freelist
;
558 static struct lo_map_elem
*lo_map_get(struct lo_map
*map
, size_t key
)
560 if (key
>= map
->nelems
) {
563 if (!map
->elems
[key
].in_use
) {
566 return &map
->elems
[key
];
569 static void lo_map_remove(struct lo_map
*map
, size_t key
)
571 struct lo_map_elem
*elem
;
573 if (key
>= map
->nelems
) {
577 elem
= &map
->elems
[key
];
582 elem
->in_use
= false;
584 elem
->freelist
= map
->freelist
;
588 /* Assumes lo->mutex is held */
589 static ssize_t
lo_add_fd_mapping(struct lo_data
*lo
, int fd
)
591 struct lo_map_elem
*elem
;
593 elem
= lo_map_alloc_elem(&lo
->fd_map
);
599 return elem
- lo
->fd_map
.elems
;
602 /* Assumes lo->mutex is held */
603 static ssize_t
lo_add_dirp_mapping(fuse_req_t req
, struct lo_dirp
*dirp
)
605 struct lo_map_elem
*elem
;
607 elem
= lo_map_alloc_elem(&lo_data(req
)->dirp_map
);
613 return elem
- lo_data(req
)->dirp_map
.elems
;
616 /* Assumes lo->mutex is held */
617 static ssize_t
lo_add_inode_mapping(fuse_req_t req
, struct lo_inode
*inode
)
619 struct lo_map_elem
*elem
;
621 elem
= lo_map_alloc_elem(&lo_data(req
)->ino_map
);
627 return elem
- lo_data(req
)->ino_map
.elems
;
630 static void lo_inode_put(struct lo_data
*lo
, struct lo_inode
**inodep
)
632 struct lo_inode
*inode
= *inodep
;
640 if (g_atomic_int_dec_and_test(&inode
->refcount
)) {
646 /* Caller must release refcount using lo_inode_put() */
647 static struct lo_inode
*lo_inode(fuse_req_t req
, fuse_ino_t ino
)
649 struct lo_data
*lo
= lo_data(req
);
650 struct lo_map_elem
*elem
;
652 pthread_mutex_lock(&lo
->mutex
);
653 elem
= lo_map_get(&lo
->ino_map
, ino
);
655 g_atomic_int_inc(&elem
->inode
->refcount
);
657 pthread_mutex_unlock(&lo
->mutex
);
667 * TODO Remove this helper and force callers to hold an inode refcount until
668 * they are done with the fd. This will be done in a later patch to make
671 static int lo_fd(fuse_req_t req
, fuse_ino_t ino
)
673 struct lo_inode
*inode
= lo_inode(req
, ino
);
681 lo_inode_put(lo_data(req
), &inode
);
686 * Open a file descriptor for an inode. Returns -EBADF if the inode is not a
687 * regular file or a directory.
689 * Use this helper function instead of raw openat(2) to prevent security issues
690 * when a malicious client opens special files such as block device nodes.
691 * Symlink inodes are also rejected since symlinks must already have been
692 * traversed on the client side.
694 static int lo_inode_open(struct lo_data
*lo
, struct lo_inode
*inode
,
697 g_autofree
char *fd_str
= g_strdup_printf("%d", inode
->fd
);
700 if (!S_ISREG(inode
->filetype
) && !S_ISDIR(inode
->filetype
)) {
705 * The file is a symlink so O_NOFOLLOW must be ignored. We checked earlier
706 * that the inode is not a special file but if an external process races
707 * with us then symlinks are traversed here. It is not possible to escape
708 * the shared directory since it is mounted as "/" though.
710 fd
= openat(lo
->proc_self_fd
, fd_str
, open_flags
& ~O_NOFOLLOW
);
717 static void lo_init(void *userdata
, struct fuse_conn_info
*conn
)
719 struct lo_data
*lo
= (struct lo_data
*)userdata
;
721 if (conn
->capable
& FUSE_CAP_EXPORT_SUPPORT
) {
722 conn
->want
|= FUSE_CAP_EXPORT_SUPPORT
;
725 if (lo
->writeback
&& conn
->capable
& FUSE_CAP_WRITEBACK_CACHE
) {
726 fuse_log(FUSE_LOG_DEBUG
, "lo_init: activating writeback\n");
727 conn
->want
|= FUSE_CAP_WRITEBACK_CACHE
;
729 if (conn
->capable
& FUSE_CAP_FLOCK_LOCKS
) {
731 fuse_log(FUSE_LOG_DEBUG
, "lo_init: activating flock locks\n");
732 conn
->want
|= FUSE_CAP_FLOCK_LOCKS
;
734 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling flock locks\n");
735 conn
->want
&= ~FUSE_CAP_FLOCK_LOCKS
;
739 if (conn
->capable
& FUSE_CAP_POSIX_LOCKS
) {
740 if (lo
->posix_lock
) {
741 fuse_log(FUSE_LOG_DEBUG
, "lo_init: activating posix locks\n");
742 conn
->want
|= FUSE_CAP_POSIX_LOCKS
;
744 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling posix locks\n");
745 conn
->want
&= ~FUSE_CAP_POSIX_LOCKS
;
749 if ((lo
->cache
== CACHE_NONE
&& !lo
->readdirplus_set
) ||
750 lo
->readdirplus_clear
) {
751 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling readdirplus\n");
752 conn
->want
&= ~FUSE_CAP_READDIRPLUS
;
755 if (!(conn
->capable
& FUSE_CAP_SUBMOUNTS
) && lo
->announce_submounts
) {
756 fuse_log(FUSE_LOG_WARNING
, "lo_init: Cannot announce submounts, client "
757 "does not support it\n");
758 lo
->announce_submounts
= false;
761 if (lo
->user_killpriv_v2
== 1) {
763 * User explicitly asked for this option. Enable it unconditionally.
764 * If connection does not have this capability, it should fail
767 fuse_log(FUSE_LOG_DEBUG
, "lo_init: enabling killpriv_v2\n");
768 conn
->want
|= FUSE_CAP_HANDLE_KILLPRIV_V2
;
772 * Either user specified to disable killpriv_v2, or did not
773 * specify anything. Disable killpriv_v2 in both the cases.
775 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling killpriv_v2\n");
776 conn
->want
&= ~FUSE_CAP_HANDLE_KILLPRIV_V2
;
780 if (lo
->user_posix_acl
== 1) {
782 * User explicitly asked for this option. Enable it unconditionally.
783 * If connection does not have this capability, print error message
784 * now. It will fail later in fuse_lowlevel.c
786 if (!(conn
->capable
& FUSE_CAP_POSIX_ACL
) ||
787 !(conn
->capable
& FUSE_CAP_DONT_MASK
) ||
788 !(conn
->capable
& FUSE_CAP_SETXATTR_EXT
)) {
789 fuse_log(FUSE_LOG_ERR
, "lo_init: Can not enable posix acl."
790 " kernel does not support FUSE_POSIX_ACL, FUSE_DONT_MASK"
791 " or FUSE_SETXATTR_EXT capability.\n");
793 fuse_log(FUSE_LOG_DEBUG
, "lo_init: enabling posix acl\n");
796 conn
->want
|= FUSE_CAP_POSIX_ACL
| FUSE_CAP_DONT_MASK
|
797 FUSE_CAP_SETXATTR_EXT
;
798 lo
->change_umask
= true;
799 lo
->posix_acl
= true;
801 /* User either did not specify anything or wants it disabled */
802 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling posix_acl\n");
803 conn
->want
&= ~FUSE_CAP_POSIX_ACL
;
806 if (lo
->user_security_label
== 1) {
807 if (!(conn
->capable
& FUSE_CAP_SECURITY_CTX
)) {
808 fuse_log(FUSE_LOG_ERR
, "lo_init: Can not enable security label."
809 " kernel does not support FUSE_SECURITY_CTX capability.\n");
811 conn
->want
|= FUSE_CAP_SECURITY_CTX
;
813 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling security label\n");
814 conn
->want
&= ~FUSE_CAP_SECURITY_CTX
;
818 static void lo_getattr(fuse_req_t req
, fuse_ino_t ino
,
819 struct fuse_file_info
*fi
)
823 struct lo_data
*lo
= lo_data(req
);
828 fstatat(lo_fd(req
, ino
), "", &buf
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
830 return (void)fuse_reply_err(req
, errno
);
833 fuse_reply_attr(req
, &buf
, lo
->timeout
);
836 static int lo_fi_fd(fuse_req_t req
, struct fuse_file_info
*fi
)
838 struct lo_data
*lo
= lo_data(req
);
839 struct lo_map_elem
*elem
;
841 pthread_mutex_lock(&lo
->mutex
);
842 elem
= lo_map_get(&lo
->fd_map
, fi
->fh
);
843 pthread_mutex_unlock(&lo
->mutex
);
852 static void lo_setattr(fuse_req_t req
, fuse_ino_t ino
, struct stat
*attr
,
853 int valid
, struct fuse_file_info
*fi
)
857 struct lo_data
*lo
= lo_data(req
);
858 struct lo_inode
*inode
;
863 inode
= lo_inode(req
, ino
);
865 fuse_reply_err(req
, EBADF
);
871 /* If fi->fh is invalid we'll report EBADF later */
873 fd
= lo_fi_fd(req
, fi
);
876 if (valid
& FUSE_SET_ATTR_MODE
) {
878 res
= fchmod(fd
, attr
->st_mode
);
880 sprintf(procname
, "%i", ifd
);
881 res
= fchmodat(lo
->proc_self_fd
, procname
, attr
->st_mode
, 0);
888 if (valid
& (FUSE_SET_ATTR_UID
| FUSE_SET_ATTR_GID
)) {
889 uid_t uid
= (valid
& FUSE_SET_ATTR_UID
) ? attr
->st_uid
: (uid_t
)-1;
890 gid_t gid
= (valid
& FUSE_SET_ATTR_GID
) ? attr
->st_gid
: (gid_t
)-1;
892 saverr
= drop_security_capability(lo
, ifd
);
897 res
= fchownat(ifd
, "", uid
, gid
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
903 if (valid
& FUSE_SET_ATTR_SIZE
) {
906 bool cap_fsetid_dropped
= false;
908 kill_suidgid
= lo
->killpriv_v2
&& (valid
& FUSE_SET_ATTR_KILL_SUIDGID
);
912 truncfd
= lo_inode_open(lo
, inode
, O_RDWR
);
919 saverr
= drop_security_capability(lo
, truncfd
);
928 res
= drop_effective_cap("FSETID", &cap_fsetid_dropped
);
938 res
= ftruncate(truncfd
, attr
->st_size
);
939 saverr
= res
== -1 ? errno
: 0;
941 if (cap_fsetid_dropped
) {
942 if (gain_effective_cap("FSETID")) {
943 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_FSETID\n");
953 if (valid
& (FUSE_SET_ATTR_ATIME
| FUSE_SET_ATTR_MTIME
)) {
954 struct timespec tv
[2];
958 tv
[0].tv_nsec
= UTIME_OMIT
;
959 tv
[1].tv_nsec
= UTIME_OMIT
;
961 if (valid
& FUSE_SET_ATTR_ATIME_NOW
) {
962 tv
[0].tv_nsec
= UTIME_NOW
;
963 } else if (valid
& FUSE_SET_ATTR_ATIME
) {
964 tv
[0] = attr
->st_atim
;
967 if (valid
& FUSE_SET_ATTR_MTIME_NOW
) {
968 tv
[1].tv_nsec
= UTIME_NOW
;
969 } else if (valid
& FUSE_SET_ATTR_MTIME
) {
970 tv
[1] = attr
->st_mtim
;
974 res
= futimens(fd
, tv
);
976 sprintf(procname
, "%i", inode
->fd
);
977 res
= utimensat(lo
->proc_self_fd
, procname
, tv
, 0);
984 lo_inode_put(lo
, &inode
);
986 return lo_getattr(req
, ino
, fi
);
989 lo_inode_put(lo
, &inode
);
990 fuse_reply_err(req
, saverr
);
993 static struct lo_inode
*lo_find(struct lo_data
*lo
, struct stat
*st
,
997 struct lo_key key
= {
1003 pthread_mutex_lock(&lo
->mutex
);
1004 p
= g_hash_table_lookup(lo
->inodes
, &key
);
1006 assert(p
->nlookup
> 0);
1008 g_atomic_int_inc(&p
->refcount
);
1010 pthread_mutex_unlock(&lo
->mutex
);
1015 /* value_destroy_func for posix_locks GHashTable */
1016 static void posix_locks_value_destroy(gpointer data
)
1018 struct lo_inode_plock
*plock
= data
;
1021 * We had used open() for locks and had only one fd. So
1022 * closing this fd should release all OFD locks.
1028 static int do_statx(struct lo_data
*lo
, int dirfd
, const char *pathname
,
1029 struct stat
*statbuf
, int flags
, uint64_t *mnt_id
)
1033 #if defined(CONFIG_STATX) && defined(CONFIG_STATX_MNT_ID)
1034 if (lo
->use_statx
) {
1035 struct statx statxbuf
;
1037 res
= statx(dirfd
, pathname
, flags
, STATX_BASIC_STATS
| STATX_MNT_ID
,
1040 memset(statbuf
, 0, sizeof(*statbuf
));
1041 statbuf
->st_dev
= makedev(statxbuf
.stx_dev_major
,
1042 statxbuf
.stx_dev_minor
);
1043 statbuf
->st_ino
= statxbuf
.stx_ino
;
1044 statbuf
->st_mode
= statxbuf
.stx_mode
;
1045 statbuf
->st_nlink
= statxbuf
.stx_nlink
;
1046 statbuf
->st_uid
= statxbuf
.stx_uid
;
1047 statbuf
->st_gid
= statxbuf
.stx_gid
;
1048 statbuf
->st_rdev
= makedev(statxbuf
.stx_rdev_major
,
1049 statxbuf
.stx_rdev_minor
);
1050 statbuf
->st_size
= statxbuf
.stx_size
;
1051 statbuf
->st_blksize
= statxbuf
.stx_blksize
;
1052 statbuf
->st_blocks
= statxbuf
.stx_blocks
;
1053 statbuf
->st_atim
.tv_sec
= statxbuf
.stx_atime
.tv_sec
;
1054 statbuf
->st_atim
.tv_nsec
= statxbuf
.stx_atime
.tv_nsec
;
1055 statbuf
->st_mtim
.tv_sec
= statxbuf
.stx_mtime
.tv_sec
;
1056 statbuf
->st_mtim
.tv_nsec
= statxbuf
.stx_mtime
.tv_nsec
;
1057 statbuf
->st_ctim
.tv_sec
= statxbuf
.stx_ctime
.tv_sec
;
1058 statbuf
->st_ctim
.tv_nsec
= statxbuf
.stx_ctime
.tv_nsec
;
1060 if (statxbuf
.stx_mask
& STATX_MNT_ID
) {
1061 *mnt_id
= statxbuf
.stx_mnt_id
;
1066 } else if (errno
!= ENOSYS
) {
1069 lo
->use_statx
= false;
1073 res
= fstatat(dirfd
, pathname
, statbuf
, flags
);
1083 * Increments nlookup on the inode on success. unref_inode_lolocked() must be
1084 * called eventually to decrement nlookup again. If inodep is non-NULL, the
1085 * inode pointer is stored and the caller must call lo_inode_put().
1087 static int lo_do_lookup(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1088 struct fuse_entry_param
*e
,
1089 struct lo_inode
**inodep
)
1095 struct lo_data
*lo
= lo_data(req
);
1096 struct lo_inode
*inode
= NULL
;
1097 struct lo_inode
*dir
= lo_inode(req
, parent
);
1100 *inodep
= NULL
; /* in case there is an error */
1104 * name_to_handle_at() and open_by_handle_at() can reach here with fuse
1105 * mount point in guest, but we don't have its inode info in the
1112 memset(e
, 0, sizeof(*e
));
1113 e
->attr_timeout
= lo
->timeout
;
1114 e
->entry_timeout
= lo
->timeout
;
1116 /* Do not allow escaping root directory */
1117 if (dir
== &lo
->root
&& strcmp(name
, "..") == 0) {
1121 newfd
= openat(dir
->fd
, name
, O_PATH
| O_NOFOLLOW
);
1126 res
= do_statx(lo
, newfd
, "", &e
->attr
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
,
1132 if (S_ISDIR(e
->attr
.st_mode
) && lo
->announce_submounts
&&
1133 (e
->attr
.st_dev
!= dir
->key
.dev
|| mnt_id
!= dir
->key
.mnt_id
)) {
1134 e
->attr_flags
|= FUSE_ATTR_SUBMOUNT
;
1137 inode
= lo_find(lo
, &e
->attr
, mnt_id
);
1141 inode
= calloc(1, sizeof(struct lo_inode
));
1146 /* cache only filetype */
1147 inode
->filetype
= (e
->attr
.st_mode
& S_IFMT
);
1150 * One for the caller and one for nlookup (released in
1151 * unref_inode_lolocked())
1153 g_atomic_int_set(&inode
->refcount
, 2);
1157 inode
->key
.ino
= e
->attr
.st_ino
;
1158 inode
->key
.dev
= e
->attr
.st_dev
;
1159 inode
->key
.mnt_id
= mnt_id
;
1160 if (lo
->posix_lock
) {
1161 pthread_mutex_init(&inode
->plock_mutex
, NULL
);
1162 inode
->posix_locks
= g_hash_table_new_full(
1163 g_direct_hash
, g_direct_equal
, NULL
, posix_locks_value_destroy
);
1165 pthread_mutex_lock(&lo
->mutex
);
1166 inode
->fuse_ino
= lo_add_inode_mapping(req
, inode
);
1167 g_hash_table_insert(lo
->inodes
, &inode
->key
, inode
);
1168 pthread_mutex_unlock(&lo
->mutex
);
1170 e
->ino
= inode
->fuse_ino
;
1172 /* Transfer ownership of inode pointer to caller or drop it */
1176 lo_inode_put(lo
, &inode
);
1179 lo_inode_put(lo
, &dir
);
1181 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
1182 name
, (unsigned long long)e
->ino
);
1191 lo_inode_put(lo
, &inode
);
1192 lo_inode_put(lo
, &dir
);
1196 static void lo_lookup(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
1198 struct fuse_entry_param e
;
1201 fuse_log(FUSE_LOG_DEBUG
, "lo_lookup(parent=%" PRIu64
", name=%s)\n", parent
,
1204 if (is_empty(name
)) {
1205 fuse_reply_err(req
, ENOENT
);
1210 * Don't use is_safe_path_component(), allow "." and ".." for NFS export
1213 if (strchr(name
, '/')) {
1214 fuse_reply_err(req
, EINVAL
);
1218 err
= lo_do_lookup(req
, parent
, name
, &e
, NULL
);
1220 fuse_reply_err(req
, err
);
1222 fuse_reply_entry(req
, &e
);
1227 * On some archs, setres*id is limited to 2^16 but they
1228 * provide setres*id32 variants that allow 2^32.
1229 * Others just let setres*id do 2^32 anyway.
1231 #ifdef SYS_setresgid32
1232 #define OURSYS_setresgid SYS_setresgid32
1234 #define OURSYS_setresgid SYS_setresgid
1237 #ifdef SYS_setresuid32
1238 #define OURSYS_setresuid SYS_setresuid32
1240 #define OURSYS_setresuid SYS_setresuid
1243 static void drop_supplementary_groups(void)
1247 ret
= getgroups(0, NULL
);
1249 fuse_log(FUSE_LOG_ERR
, "getgroups() failed with error=%d:%s\n",
1250 errno
, strerror(errno
));
1258 /* Drop all supplementary groups. We should not need it */
1259 ret
= setgroups(0, NULL
);
1261 fuse_log(FUSE_LOG_ERR
, "setgroups() failed with error=%d:%s\n",
1262 errno
, strerror(errno
));
1268 * Change to uid/gid of caller so that file is created with
1269 * ownership of caller.
1270 * TODO: What about selinux context?
1272 static int lo_change_cred(fuse_req_t req
, struct lo_cred
*old
,
1277 old
->euid
= geteuid();
1278 old
->egid
= getegid();
1280 res
= syscall(OURSYS_setresgid
, -1, fuse_req_ctx(req
)->gid
, -1);
1285 res
= syscall(OURSYS_setresuid
, -1, fuse_req_ctx(req
)->uid
, -1);
1287 int errno_save
= errno
;
1289 syscall(OURSYS_setresgid
, -1, old
->egid
, -1);
1294 old
->umask
= umask(req
->ctx
.umask
);
1299 /* Regain Privileges */
1300 static void lo_restore_cred(struct lo_cred
*old
, bool restore_umask
)
1304 res
= syscall(OURSYS_setresuid
, -1, old
->euid
, -1);
1306 fuse_log(FUSE_LOG_ERR
, "seteuid(%u): %m\n", old
->euid
);
1310 res
= syscall(OURSYS_setresgid
, -1, old
->egid
, -1);
1312 fuse_log(FUSE_LOG_ERR
, "setegid(%u): %m\n", old
->egid
);
1321 * A helper to change cred and drop capability. Returns 0 on success and
1324 static int lo_drop_cap_change_cred(fuse_req_t req
, struct lo_cred
*old
,
1325 bool change_umask
, const char *cap_name
,
1333 ret
= drop_effective_cap(cap_name
, &__cap_dropped
);
1338 ret
= lo_change_cred(req
, old
, change_umask
);
1340 if (__cap_dropped
) {
1341 if (gain_effective_cap(cap_name
)) {
1342 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_%s\n", cap_name
);
1348 *cap_dropped
= __cap_dropped
;
1353 static void lo_restore_cred_gain_cap(struct lo_cred
*old
, bool restore_umask
,
1354 const char *cap_name
)
1358 lo_restore_cred(old
, restore_umask
);
1360 if (gain_effective_cap(cap_name
)) {
1361 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_%s\n", cap_name
);
1365 static int do_mknod_symlink_secctx(fuse_req_t req
, struct lo_inode
*dir
,
1366 const char *name
, const char *secctx_name
)
1370 struct lo_data
*lo
= lo_data(req
);
1372 if (!req
->secctx
.ctxlen
) {
1376 /* Open newly created element with O_PATH */
1377 path_fd
= openat(dir
->fd
, name
, O_PATH
| O_NOFOLLOW
);
1378 err
= path_fd
== -1 ? errno
: 0;
1382 sprintf(procname
, "%i", path_fd
);
1383 FCHDIR_NOFAIL(lo
->proc_self_fd
);
1384 /* Set security context. This is not atomic w.r.t file creation */
1385 err
= setxattr(procname
, secctx_name
, req
->secctx
.ctx
, req
->secctx
.ctxlen
,
1390 FCHDIR_NOFAIL(lo
->root
.fd
);
1395 static int do_mknod_symlink(fuse_req_t req
, struct lo_inode
*dir
,
1396 const char *name
, mode_t mode
, dev_t rdev
,
1399 int err
, fscreate_fd
= -1;
1400 const char *secctx_name
= req
->secctx
.name
;
1401 struct lo_cred old
= {};
1402 struct lo_data
*lo
= lo_data(req
);
1403 char *mapped_name
= NULL
;
1404 bool secctx_enabled
= req
->secctx
.ctxlen
;
1405 bool do_fscreate
= false;
1407 if (secctx_enabled
&& lo
->xattrmap
) {
1408 err
= xattr_map_client(lo
, req
->secctx
.name
, &mapped_name
);
1412 secctx_name
= mapped_name
;
1416 * If security xattr has not been remapped and selinux is enabled on
1417 * host, set fscreate and no need to do a setxattr() after file creation
1419 if (secctx_enabled
&& !mapped_name
&& lo
->use_fscreate
) {
1421 err
= open_set_proc_fscreate(lo
, req
->secctx
.ctx
, req
->secctx
.ctxlen
,
1428 err
= lo_change_cred(req
, &old
, lo
->change_umask
&& !S_ISLNK(mode
));
1433 err
= mknod_wrapper(dir
->fd
, name
, link
, mode
, rdev
);
1434 err
= err
== -1 ? errno
: 0;
1435 lo_restore_cred(&old
, lo
->change_umask
&& !S_ISLNK(mode
));
1441 err
= do_mknod_symlink_secctx(req
, dir
, name
, secctx_name
);
1443 unlinkat(dir
->fd
, name
, S_ISDIR(mode
) ? AT_REMOVEDIR
: 0);
1447 if (fscreate_fd
!= -1) {
1448 close_reset_proc_fscreate(fscreate_fd
);
1450 g_free(mapped_name
);
1454 static void lo_mknod_symlink(fuse_req_t req
, fuse_ino_t parent
,
1455 const char *name
, mode_t mode
, dev_t rdev
,
1459 struct lo_data
*lo
= lo_data(req
);
1460 struct lo_inode
*dir
;
1461 struct fuse_entry_param e
;
1463 if (is_empty(name
)) {
1464 fuse_reply_err(req
, ENOENT
);
1468 if (!is_safe_path_component(name
)) {
1469 fuse_reply_err(req
, EINVAL
);
1473 dir
= lo_inode(req
, parent
);
1475 fuse_reply_err(req
, EBADF
);
1479 saverr
= do_mknod_symlink(req
, dir
, name
, mode
, rdev
, link
);
1484 saverr
= lo_do_lookup(req
, parent
, name
, &e
, NULL
);
1489 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
1490 name
, (unsigned long long)e
.ino
);
1492 fuse_reply_entry(req
, &e
);
1493 lo_inode_put(lo
, &dir
);
1497 lo_inode_put(lo
, &dir
);
1498 fuse_reply_err(req
, saverr
);
1501 static void lo_mknod(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1502 mode_t mode
, dev_t rdev
)
1504 lo_mknod_symlink(req
, parent
, name
, mode
, rdev
, NULL
);
1507 static void lo_mkdir(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1510 lo_mknod_symlink(req
, parent
, name
, S_IFDIR
| mode
, 0, NULL
);
1513 static void lo_symlink(fuse_req_t req
, const char *link
, fuse_ino_t parent
,
1516 lo_mknod_symlink(req
, parent
, name
, S_IFLNK
, 0, link
);
1519 static void lo_link(fuse_req_t req
, fuse_ino_t ino
, fuse_ino_t parent
,
1523 struct lo_data
*lo
= lo_data(req
);
1524 struct lo_inode
*parent_inode
;
1525 struct lo_inode
*inode
;
1526 struct fuse_entry_param e
;
1530 if (is_empty(name
)) {
1531 fuse_reply_err(req
, ENOENT
);
1535 if (!is_safe_path_component(name
)) {
1536 fuse_reply_err(req
, EINVAL
);
1540 parent_inode
= lo_inode(req
, parent
);
1541 inode
= lo_inode(req
, ino
);
1542 if (!parent_inode
|| !inode
) {
1547 memset(&e
, 0, sizeof(struct fuse_entry_param
));
1548 e
.attr_timeout
= lo
->timeout
;
1549 e
.entry_timeout
= lo
->timeout
;
1551 sprintf(procname
, "%i", inode
->fd
);
1552 res
= linkat(lo
->proc_self_fd
, procname
, parent_inode
->fd
, name
,
1558 res
= fstatat(inode
->fd
, "", &e
.attr
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
1563 pthread_mutex_lock(&lo
->mutex
);
1565 pthread_mutex_unlock(&lo
->mutex
);
1566 e
.ino
= inode
->fuse_ino
;
1568 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
1569 name
, (unsigned long long)e
.ino
);
1571 fuse_reply_entry(req
, &e
);
1572 lo_inode_put(lo
, &parent_inode
);
1573 lo_inode_put(lo
, &inode
);
1578 lo_inode_put(lo
, &parent_inode
);
1579 lo_inode_put(lo
, &inode
);
1580 fuse_reply_err(req
, saverr
);
1583 /* Increments nlookup and caller must release refcount using lo_inode_put() */
1584 static struct lo_inode
*lookup_name(fuse_req_t req
, fuse_ino_t parent
,
1590 struct lo_data
*lo
= lo_data(req
);
1591 struct lo_inode
*dir
= lo_inode(req
, parent
);
1597 res
= do_statx(lo
, dir
->fd
, name
, &attr
, AT_SYMLINK_NOFOLLOW
, &mnt_id
);
1598 lo_inode_put(lo
, &dir
);
1603 return lo_find(lo
, &attr
, mnt_id
);
1606 static void lo_rmdir(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
1609 struct lo_inode
*inode
;
1610 struct lo_data
*lo
= lo_data(req
);
1612 if (is_empty(name
)) {
1613 fuse_reply_err(req
, ENOENT
);
1617 if (!is_safe_path_component(name
)) {
1618 fuse_reply_err(req
, EINVAL
);
1622 inode
= lookup_name(req
, parent
, name
);
1624 fuse_reply_err(req
, EIO
);
1628 res
= unlinkat(lo_fd(req
, parent
), name
, AT_REMOVEDIR
);
1630 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1631 unref_inode_lolocked(lo
, inode
, 1);
1632 lo_inode_put(lo
, &inode
);
1635 static void lo_rename(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1636 fuse_ino_t newparent
, const char *newname
,
1640 struct lo_inode
*parent_inode
;
1641 struct lo_inode
*newparent_inode
;
1642 struct lo_inode
*oldinode
= NULL
;
1643 struct lo_inode
*newinode
= NULL
;
1644 struct lo_data
*lo
= lo_data(req
);
1646 if (is_empty(name
) || is_empty(newname
)) {
1647 fuse_reply_err(req
, ENOENT
);
1651 if (!is_safe_path_component(name
) || !is_safe_path_component(newname
)) {
1652 fuse_reply_err(req
, EINVAL
);
1656 parent_inode
= lo_inode(req
, parent
);
1657 newparent_inode
= lo_inode(req
, newparent
);
1658 if (!parent_inode
|| !newparent_inode
) {
1659 fuse_reply_err(req
, EBADF
);
1663 oldinode
= lookup_name(req
, parent
, name
);
1664 newinode
= lookup_name(req
, newparent
, newname
);
1667 fuse_reply_err(req
, EIO
);
1672 #ifndef SYS_renameat2
1673 fuse_reply_err(req
, EINVAL
);
1675 res
= syscall(SYS_renameat2
, parent_inode
->fd
, name
,
1676 newparent_inode
->fd
, newname
, flags
);
1677 if (res
== -1 && errno
== ENOSYS
) {
1678 fuse_reply_err(req
, EINVAL
);
1680 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1686 res
= renameat(parent_inode
->fd
, name
, newparent_inode
->fd
, newname
);
1688 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1690 unref_inode_lolocked(lo
, oldinode
, 1);
1691 unref_inode_lolocked(lo
, newinode
, 1);
1692 lo_inode_put(lo
, &oldinode
);
1693 lo_inode_put(lo
, &newinode
);
1694 lo_inode_put(lo
, &parent_inode
);
1695 lo_inode_put(lo
, &newparent_inode
);
1698 static void lo_unlink(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
1701 struct lo_inode
*inode
;
1702 struct lo_data
*lo
= lo_data(req
);
1704 if (is_empty(name
)) {
1705 fuse_reply_err(req
, ENOENT
);
1709 if (!is_safe_path_component(name
)) {
1710 fuse_reply_err(req
, EINVAL
);
1714 inode
= lookup_name(req
, parent
, name
);
1716 fuse_reply_err(req
, EIO
);
1720 res
= unlinkat(lo_fd(req
, parent
), name
, 0);
1722 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1723 unref_inode_lolocked(lo
, inode
, 1);
1724 lo_inode_put(lo
, &inode
);
1727 /* To be called with lo->mutex held */
1728 static void unref_inode(struct lo_data
*lo
, struct lo_inode
*inode
, uint64_t n
)
1734 assert(inode
->nlookup
>= n
);
1735 inode
->nlookup
-= n
;
1736 if (!inode
->nlookup
) {
1737 lo_map_remove(&lo
->ino_map
, inode
->fuse_ino
);
1738 g_hash_table_remove(lo
->inodes
, &inode
->key
);
1739 if (lo
->posix_lock
) {
1740 if (g_hash_table_size(inode
->posix_locks
)) {
1741 fuse_log(FUSE_LOG_WARNING
, "Hash table is not empty\n");
1743 g_hash_table_destroy(inode
->posix_locks
);
1744 pthread_mutex_destroy(&inode
->plock_mutex
);
1746 /* Drop our refcount from lo_do_lookup() */
1747 lo_inode_put(lo
, &inode
);
1751 static void unref_inode_lolocked(struct lo_data
*lo
, struct lo_inode
*inode
,
1758 pthread_mutex_lock(&lo
->mutex
);
1759 unref_inode(lo
, inode
, n
);
1760 pthread_mutex_unlock(&lo
->mutex
);
1763 static void lo_forget_one(fuse_req_t req
, fuse_ino_t ino
, uint64_t nlookup
)
1765 struct lo_data
*lo
= lo_data(req
);
1766 struct lo_inode
*inode
;
1768 inode
= lo_inode(req
, ino
);
1773 fuse_log(FUSE_LOG_DEBUG
, " forget %lli %lli -%lli\n",
1774 (unsigned long long)ino
, (unsigned long long)inode
->nlookup
,
1775 (unsigned long long)nlookup
);
1777 unref_inode_lolocked(lo
, inode
, nlookup
);
1778 lo_inode_put(lo
, &inode
);
1781 static void lo_forget(fuse_req_t req
, fuse_ino_t ino
, uint64_t nlookup
)
1783 lo_forget_one(req
, ino
, nlookup
);
1784 fuse_reply_none(req
);
1787 static void lo_forget_multi(fuse_req_t req
, size_t count
,
1788 struct fuse_forget_data
*forgets
)
1792 for (i
= 0; i
< count
; i
++) {
1793 lo_forget_one(req
, forgets
[i
].ino
, forgets
[i
].nlookup
);
1795 fuse_reply_none(req
);
1798 static void lo_readlink(fuse_req_t req
, fuse_ino_t ino
)
1800 char buf
[PATH_MAX
+ 1];
1803 res
= readlinkat(lo_fd(req
, ino
), "", buf
, sizeof(buf
));
1805 return (void)fuse_reply_err(req
, errno
);
1808 if (res
== sizeof(buf
)) {
1809 return (void)fuse_reply_err(req
, ENAMETOOLONG
);
1814 fuse_reply_readlink(req
, buf
);
1820 struct dirent
*entry
;
1824 static void lo_dirp_put(struct lo_dirp
**dp
)
1826 struct lo_dirp
*d
= *dp
;
1833 if (g_atomic_int_dec_and_test(&d
->refcount
)) {
1839 /* Call lo_dirp_put() on the return value when no longer needed */
1840 static struct lo_dirp
*lo_dirp(fuse_req_t req
, struct fuse_file_info
*fi
)
1842 struct lo_data
*lo
= lo_data(req
);
1843 struct lo_map_elem
*elem
;
1845 pthread_mutex_lock(&lo
->mutex
);
1846 elem
= lo_map_get(&lo
->dirp_map
, fi
->fh
);
1848 g_atomic_int_inc(&elem
->dirp
->refcount
);
1850 pthread_mutex_unlock(&lo
->mutex
);
1858 static void lo_opendir(fuse_req_t req
, fuse_ino_t ino
,
1859 struct fuse_file_info
*fi
)
1862 struct lo_data
*lo
= lo_data(req
);
1867 d
= calloc(1, sizeof(struct lo_dirp
));
1872 fd
= openat(lo_fd(req
, ino
), ".", O_RDONLY
);
1877 d
->dp
= fdopendir(fd
);
1878 if (d
->dp
== NULL
) {
1885 g_atomic_int_set(&d
->refcount
, 1); /* paired with lo_releasedir() */
1886 pthread_mutex_lock(&lo
->mutex
);
1887 fh
= lo_add_dirp_mapping(req
, d
);
1888 pthread_mutex_unlock(&lo
->mutex
);
1894 if (lo
->cache
== CACHE_ALWAYS
) {
1895 fi
->cache_readdir
= 1;
1897 fuse_reply_open(req
, fi
);
1906 } else if (fd
!= -1) {
1911 fuse_reply_err(req
, error
);
1914 static void lo_do_readdir(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
1915 off_t offset
, struct fuse_file_info
*fi
, int plus
)
1917 struct lo_data
*lo
= lo_data(req
);
1918 struct lo_dirp
*d
= NULL
;
1919 struct lo_inode
*dinode
;
1920 g_autofree
char *buf
= NULL
;
1925 dinode
= lo_inode(req
, ino
);
1930 d
= lo_dirp(req
, fi
);
1936 buf
= g_try_malloc0(size
);
1942 if (offset
!= d
->offset
) {
1943 seekdir(d
->dp
, offset
);
1954 d
->entry
= readdir(d
->dp
);
1956 if (errno
) { /* Error */
1959 } else { /* End of stream */
1964 nextoff
= d
->entry
->d_off
;
1965 name
= d
->entry
->d_name
;
1967 fuse_ino_t entry_ino
= 0;
1968 struct fuse_entry_param e
= (struct fuse_entry_param
){
1969 .attr
.st_ino
= d
->entry
->d_ino
,
1970 .attr
.st_mode
= d
->entry
->d_type
<< 12,
1973 /* Hide root's parent directory */
1974 if (dinode
== &lo
->root
&& strcmp(name
, "..") == 0) {
1975 e
.attr
.st_ino
= lo
->root
.key
.ino
;
1976 e
.attr
.st_mode
= DT_DIR
<< 12;
1980 if (!is_dot_or_dotdot(name
)) {
1981 err
= lo_do_lookup(req
, ino
, name
, &e
, NULL
);
1988 entsize
= fuse_add_direntry_plus(req
, p
, rem
, name
, &e
, nextoff
);
1990 entsize
= fuse_add_direntry(req
, p
, rem
, name
, &e
.attr
, nextoff
);
1992 if (entsize
> rem
) {
1993 if (entry_ino
!= 0) {
1994 lo_forget_one(req
, entry_ino
, 1);
2003 d
->offset
= nextoff
;
2009 lo_inode_put(lo
, &dinode
);
2012 * If there's an error, we can only signal it if we haven't stored
2013 * any entries yet - otherwise we'd end up with wrong lookup
2014 * counts for the entries that are already in the buffer. So we
2015 * return what we've collected until that point.
2017 if (err
&& rem
== size
) {
2018 fuse_reply_err(req
, err
);
2020 fuse_reply_buf(req
, buf
, size
- rem
);
2024 static void lo_readdir(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
2025 off_t offset
, struct fuse_file_info
*fi
)
2027 lo_do_readdir(req
, ino
, size
, offset
, fi
, 0);
2030 static void lo_readdirplus(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
2031 off_t offset
, struct fuse_file_info
*fi
)
2033 lo_do_readdir(req
, ino
, size
, offset
, fi
, 1);
2036 static void lo_releasedir(fuse_req_t req
, fuse_ino_t ino
,
2037 struct fuse_file_info
*fi
)
2039 struct lo_data
*lo
= lo_data(req
);
2040 struct lo_map_elem
*elem
;
2045 pthread_mutex_lock(&lo
->mutex
);
2046 elem
= lo_map_get(&lo
->dirp_map
, fi
->fh
);
2048 pthread_mutex_unlock(&lo
->mutex
);
2049 fuse_reply_err(req
, EBADF
);
2054 lo_map_remove(&lo
->dirp_map
, fi
->fh
);
2055 pthread_mutex_unlock(&lo
->mutex
);
2057 lo_dirp_put(&d
); /* paired with lo_opendir() */
2059 fuse_reply_err(req
, 0);
2062 static void update_open_flags(int writeback
, int allow_direct_io
,
2063 struct fuse_file_info
*fi
)
2066 * With writeback cache, kernel may send read requests even
2067 * when userspace opened write-only
2069 if (writeback
&& (fi
->flags
& O_ACCMODE
) == O_WRONLY
) {
2070 fi
->flags
&= ~O_ACCMODE
;
2071 fi
->flags
|= O_RDWR
;
2075 * With writeback cache, O_APPEND is handled by the kernel.
2076 * This breaks atomicity (since the file may change in the
2077 * underlying filesystem, so that the kernel's idea of the
2078 * end of the file isn't accurate anymore). In this example,
2079 * we just accept that. A more rigorous filesystem may want
2080 * to return an error here
2082 if (writeback
&& (fi
->flags
& O_APPEND
)) {
2083 fi
->flags
&= ~O_APPEND
;
2087 * O_DIRECT in guest should not necessarily mean bypassing page
2088 * cache on host as well. Therefore, we discard it by default
2089 * ('-o no_allow_direct_io'). If somebody needs that behavior,
2090 * the '-o allow_direct_io' option should be set.
2092 if (!allow_direct_io
) {
2093 fi
->flags
&= ~O_DIRECT
;
2098 * Open a regular file, set up an fd mapping, and fill out the struct
2099 * fuse_file_info for it. If existing_fd is not negative, use that fd instead
2100 * opening a new one. Takes ownership of existing_fd.
2102 * Returns 0 on success or a positive errno.
2104 static int lo_do_open(struct lo_data
*lo
, struct lo_inode
*inode
,
2105 int existing_fd
, struct fuse_file_info
*fi
)
2108 int fd
= existing_fd
;
2110 bool cap_fsetid_dropped
= false;
2111 bool kill_suidgid
= lo
->killpriv_v2
&& fi
->kill_priv
;
2113 update_open_flags(lo
->writeback
, lo
->allow_direct_io
, fi
);
2117 err
= drop_effective_cap("FSETID", &cap_fsetid_dropped
);
2123 fd
= lo_inode_open(lo
, inode
, fi
->flags
);
2125 if (cap_fsetid_dropped
) {
2126 if (gain_effective_cap("FSETID")) {
2127 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_FSETID\n");
2133 if (fi
->flags
& (O_TRUNC
)) {
2134 int err
= drop_security_capability(lo
, fd
);
2142 pthread_mutex_lock(&lo
->mutex
);
2143 fh
= lo_add_fd_mapping(lo
, fd
);
2144 pthread_mutex_unlock(&lo
->mutex
);
2151 if (lo
->cache
== CACHE_NONE
) {
2153 } else if (lo
->cache
== CACHE_ALWAYS
) {
2159 static int do_create_nosecctx(fuse_req_t req
, struct lo_inode
*parent_inode
,
2160 const char *name
, mode_t mode
,
2161 struct fuse_file_info
*fi
, int *open_fd
,
2165 struct lo_cred old
= {};
2166 struct lo_data
*lo
= lo_data(req
);
2170 flags
= fi
->flags
| O_TMPFILE
;
2172 * Don't use O_EXCL as we want to link file later. Also reset O_CREAT
2173 * otherwise openat() returns -EINVAL.
2175 flags
&= ~(O_CREAT
| O_EXCL
);
2177 /* O_TMPFILE needs either O_RDWR or O_WRONLY */
2178 if ((flags
& O_ACCMODE
) == O_RDONLY
) {
2182 flags
= fi
->flags
| O_CREAT
| O_EXCL
;
2185 err
= lo_change_cred(req
, &old
, lo
->change_umask
);
2190 /* Try to create a new file but don't open existing files */
2191 fd
= openat(parent_inode
->fd
, name
, flags
, mode
);
2192 err
= fd
== -1 ? errno
: 0;
2193 lo_restore_cred(&old
, lo
->change_umask
);
2200 static int do_create_secctx_fscreate(fuse_req_t req
,
2201 struct lo_inode
*parent_inode
,
2202 const char *name
, mode_t mode
,
2203 struct fuse_file_info
*fi
, int *open_fd
)
2205 int err
= 0, fd
= -1, fscreate_fd
= -1;
2206 struct lo_data
*lo
= lo_data(req
);
2208 err
= open_set_proc_fscreate(lo
, req
->secctx
.ctx
, req
->secctx
.ctxlen
,
2214 err
= do_create_nosecctx(req
, parent_inode
, name
, mode
, fi
, &fd
, false);
2216 close_reset_proc_fscreate(fscreate_fd
);
2223 static int do_create_secctx_tmpfile(fuse_req_t req
,
2224 struct lo_inode
*parent_inode
,
2225 const char *name
, mode_t mode
,
2226 struct fuse_file_info
*fi
,
2227 const char *secctx_name
, int *open_fd
)
2230 struct lo_data
*lo
= lo_data(req
);
2233 err
= do_create_nosecctx(req
, parent_inode
, ".", mode
, fi
, &fd
, true);
2238 err
= fsetxattr(fd
, secctx_name
, req
->secctx
.ctx
, req
->secctx
.ctxlen
, 0);
2244 /* Security context set on file. Link it in place */
2245 sprintf(procname
, "%d", fd
);
2246 FCHDIR_NOFAIL(lo
->proc_self_fd
);
2247 err
= linkat(AT_FDCWD
, procname
, parent_inode
->fd
, name
,
2249 err
= err
== -1 ? errno
: 0;
2250 FCHDIR_NOFAIL(lo
->root
.fd
);
2255 } else if (fd
!= -1) {
2261 static int do_create_secctx_noatomic(fuse_req_t req
,
2262 struct lo_inode
*parent_inode
,
2263 const char *name
, mode_t mode
,
2264 struct fuse_file_info
*fi
,
2265 const char *secctx_name
, int *open_fd
)
2267 int err
= 0, fd
= -1;
2269 err
= do_create_nosecctx(req
, parent_inode
, name
, mode
, fi
, &fd
, false);
2274 /* Set security context. This is not atomic w.r.t file creation */
2275 err
= fsetxattr(fd
, secctx_name
, req
->secctx
.ctx
, req
->secctx
.ctxlen
, 0);
2276 err
= err
== -1 ? errno
: 0;
2283 unlinkat(parent_inode
->fd
, name
, 0);
2289 static int do_lo_create(fuse_req_t req
, struct lo_inode
*parent_inode
,
2290 const char *name
, mode_t mode
,
2291 struct fuse_file_info
*fi
, int *open_fd
)
2293 struct lo_data
*lo
= lo_data(req
);
2294 char *mapped_name
= NULL
;
2296 const char *ctxname
= req
->secctx
.name
;
2297 bool secctx_enabled
= req
->secctx
.ctxlen
;
2299 if (secctx_enabled
&& lo
->xattrmap
) {
2300 err
= xattr_map_client(lo
, req
->secctx
.name
, &mapped_name
);
2305 ctxname
= mapped_name
;
2308 if (secctx_enabled
) {
2310 * If security.selinux has not been remapped and selinux is enabled,
2311 * use fscreate to set context before file creation. If not, use
2312 * tmpfile method for regular files. Otherwise fallback to
2313 * non-atomic method of file creation and xattr setting.
2315 if (!mapped_name
&& lo
->use_fscreate
) {
2316 err
= do_create_secctx_fscreate(req
, parent_inode
, name
, mode
, fi
,
2319 } else if (S_ISREG(mode
)) {
2320 err
= do_create_secctx_tmpfile(req
, parent_inode
, name
, mode
, fi
,
2323 * If filesystem does not support O_TMPFILE, fallback to non-atomic
2326 if (!err
|| err
!= EOPNOTSUPP
) {
2331 err
= do_create_secctx_noatomic(req
, parent_inode
, name
, mode
, fi
,
2334 err
= do_create_nosecctx(req
, parent_inode
, name
, mode
, fi
, open_fd
,
2339 g_free(mapped_name
);
2343 static void lo_create(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
2344 mode_t mode
, struct fuse_file_info
*fi
)
2347 struct lo_data
*lo
= lo_data(req
);
2348 struct lo_inode
*parent_inode
;
2349 struct lo_inode
*inode
= NULL
;
2350 struct fuse_entry_param e
;
2353 fuse_log(FUSE_LOG_DEBUG
, "lo_create(parent=%" PRIu64
", name=%s)"
2354 " kill_priv=%d\n", parent
, name
, fi
->kill_priv
);
2356 if (!is_safe_path_component(name
)) {
2357 fuse_reply_err(req
, EINVAL
);
2361 parent_inode
= lo_inode(req
, parent
);
2362 if (!parent_inode
) {
2363 fuse_reply_err(req
, EBADF
);
2367 update_open_flags(lo
->writeback
, lo
->allow_direct_io
, fi
);
2369 err
= do_lo_create(req
, parent_inode
, name
, mode
, fi
, &fd
);
2371 /* Ignore the error if file exists and O_EXCL was not given */
2372 if (err
&& (err
!= EEXIST
|| (fi
->flags
& O_EXCL
))) {
2376 err
= lo_do_lookup(req
, parent
, name
, &e
, &inode
);
2381 err
= lo_do_open(lo
, inode
, fd
, fi
);
2382 fd
= -1; /* lo_do_open() takes ownership of fd */
2384 /* Undo lo_do_lookup() nlookup ref */
2385 unref_inode_lolocked(lo
, inode
, 1);
2389 lo_inode_put(lo
, &inode
);
2390 lo_inode_put(lo
, &parent_inode
);
2397 fuse_reply_err(req
, err
);
2399 fuse_reply_create(req
, &e
, fi
);
2403 /* Should be called with inode->plock_mutex held */
2404 static struct lo_inode_plock
*lookup_create_plock_ctx(struct lo_data
*lo
,
2405 struct lo_inode
*inode
,
2406 uint64_t lock_owner
,
2407 pid_t pid
, int *err
)
2409 struct lo_inode_plock
*plock
;
2413 g_hash_table_lookup(inode
->posix_locks
, GUINT_TO_POINTER(lock_owner
));
2419 plock
= malloc(sizeof(struct lo_inode_plock
));
2425 /* Open another instance of file which can be used for ofd locks. */
2426 /* TODO: What if file is not writable? */
2427 fd
= lo_inode_open(lo
, inode
, O_RDWR
);
2434 plock
->lock_owner
= lock_owner
;
2436 g_hash_table_insert(inode
->posix_locks
, GUINT_TO_POINTER(plock
->lock_owner
),
2441 static void lo_getlk(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
2444 struct lo_data
*lo
= lo_data(req
);
2445 struct lo_inode
*inode
;
2446 struct lo_inode_plock
*plock
;
2447 int ret
, saverr
= 0;
2449 fuse_log(FUSE_LOG_DEBUG
,
2450 "lo_getlk(ino=%" PRIu64
", flags=%d)"
2451 " owner=0x%" PRIx64
", l_type=%d l_start=0x%" PRIx64
2452 " l_len=0x%" PRIx64
"\n",
2453 ino
, fi
->flags
, fi
->lock_owner
, lock
->l_type
,
2454 (uint64_t)lock
->l_start
, (uint64_t)lock
->l_len
);
2456 if (!lo
->posix_lock
) {
2457 fuse_reply_err(req
, ENOSYS
);
2461 inode
= lo_inode(req
, ino
);
2463 fuse_reply_err(req
, EBADF
);
2467 pthread_mutex_lock(&inode
->plock_mutex
);
2469 lookup_create_plock_ctx(lo
, inode
, fi
->lock_owner
, lock
->l_pid
, &ret
);
2475 ret
= fcntl(plock
->fd
, F_OFD_GETLK
, lock
);
2481 pthread_mutex_unlock(&inode
->plock_mutex
);
2482 lo_inode_put(lo
, &inode
);
2485 fuse_reply_err(req
, saverr
);
2487 fuse_reply_lock(req
, lock
);
2491 static void lo_setlk(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
2492 struct flock
*lock
, int sleep
)
2494 struct lo_data
*lo
= lo_data(req
);
2495 struct lo_inode
*inode
;
2496 struct lo_inode_plock
*plock
;
2497 int ret
, saverr
= 0;
2499 fuse_log(FUSE_LOG_DEBUG
,
2500 "lo_setlk(ino=%" PRIu64
", flags=%d)"
2501 " cmd=%d pid=%d owner=0x%" PRIx64
" sleep=%d l_whence=%d"
2502 " l_start=0x%" PRIx64
" l_len=0x%" PRIx64
"\n",
2503 ino
, fi
->flags
, lock
->l_type
, lock
->l_pid
, fi
->lock_owner
, sleep
,
2504 lock
->l_whence
, (uint64_t)lock
->l_start
, (uint64_t)lock
->l_len
);
2506 if (!lo
->posix_lock
) {
2507 fuse_reply_err(req
, ENOSYS
);
2512 fuse_reply_err(req
, EOPNOTSUPP
);
2516 inode
= lo_inode(req
, ino
);
2518 fuse_reply_err(req
, EBADF
);
2522 pthread_mutex_lock(&inode
->plock_mutex
);
2524 lookup_create_plock_ctx(lo
, inode
, fi
->lock_owner
, lock
->l_pid
, &ret
);
2531 /* TODO: Is it alright to modify flock? */
2533 ret
= fcntl(plock
->fd
, F_OFD_SETLK
, lock
);
2539 pthread_mutex_unlock(&inode
->plock_mutex
);
2540 lo_inode_put(lo
, &inode
);
2542 fuse_reply_err(req
, saverr
);
2545 static void lo_fsyncdir(fuse_req_t req
, fuse_ino_t ino
, int datasync
,
2546 struct fuse_file_info
*fi
)
2554 d
= lo_dirp(req
, fi
);
2556 fuse_reply_err(req
, EBADF
);
2562 res
= fdatasync(fd
);
2569 fuse_reply_err(req
, res
== -1 ? errno
: 0);
2572 static void lo_open(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
)
2574 struct lo_data
*lo
= lo_data(req
);
2575 struct lo_inode
*inode
= lo_inode(req
, ino
);
2578 fuse_log(FUSE_LOG_DEBUG
, "lo_open(ino=%" PRIu64
", flags=%d, kill_priv=%d)"
2579 "\n", ino
, fi
->flags
, fi
->kill_priv
);
2582 fuse_reply_err(req
, EBADF
);
2586 err
= lo_do_open(lo
, inode
, -1, fi
);
2587 lo_inode_put(lo
, &inode
);
2589 fuse_reply_err(req
, err
);
2591 fuse_reply_open(req
, fi
);
2595 static void lo_release(fuse_req_t req
, fuse_ino_t ino
,
2596 struct fuse_file_info
*fi
)
2598 struct lo_data
*lo
= lo_data(req
);
2599 struct lo_map_elem
*elem
;
2604 pthread_mutex_lock(&lo
->mutex
);
2605 elem
= lo_map_get(&lo
->fd_map
, fi
->fh
);
2609 lo_map_remove(&lo
->fd_map
, fi
->fh
);
2611 pthread_mutex_unlock(&lo
->mutex
);
2614 fuse_reply_err(req
, 0);
2617 static void lo_flush(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
)
2621 struct lo_inode
*inode
;
2622 struct lo_data
*lo
= lo_data(req
);
2624 inode
= lo_inode(req
, ino
);
2626 fuse_reply_err(req
, EBADF
);
2630 if (!S_ISREG(inode
->filetype
)) {
2631 lo_inode_put(lo
, &inode
);
2632 fuse_reply_err(req
, EBADF
);
2636 /* An fd is going away. Cleanup associated posix locks */
2637 if (lo
->posix_lock
) {
2638 pthread_mutex_lock(&inode
->plock_mutex
);
2639 g_hash_table_remove(inode
->posix_locks
,
2640 GUINT_TO_POINTER(fi
->lock_owner
));
2641 pthread_mutex_unlock(&inode
->plock_mutex
);
2643 res
= close(dup(lo_fi_fd(req
, fi
)));
2644 lo_inode_put(lo
, &inode
);
2645 fuse_reply_err(req
, res
== -1 ? errno
: 0);
2648 static void lo_fsync(fuse_req_t req
, fuse_ino_t ino
, int datasync
,
2649 struct fuse_file_info
*fi
)
2651 struct lo_inode
*inode
= lo_inode(req
, ino
);
2652 struct lo_data
*lo
= lo_data(req
);
2656 fuse_log(FUSE_LOG_DEBUG
, "lo_fsync(ino=%" PRIu64
", fi=0x%p)\n", ino
,
2660 fuse_reply_err(req
, EBADF
);
2665 fd
= lo_inode_open(lo
, inode
, O_RDWR
);
2671 fd
= lo_fi_fd(req
, fi
);
2675 res
= fdatasync(fd
) == -1 ? errno
: 0;
2677 res
= fsync(fd
) == -1 ? errno
: 0;
2683 lo_inode_put(lo
, &inode
);
2684 fuse_reply_err(req
, res
);
2687 static void lo_read(fuse_req_t req
, fuse_ino_t ino
, size_t size
, off_t offset
,
2688 struct fuse_file_info
*fi
)
2690 struct fuse_bufvec buf
= FUSE_BUFVEC_INIT(size
);
2692 fuse_log(FUSE_LOG_DEBUG
,
2693 "lo_read(ino=%" PRIu64
", size=%zd, "
2695 ino
, size
, (unsigned long)offset
);
2697 buf
.buf
[0].flags
= FUSE_BUF_IS_FD
| FUSE_BUF_FD_SEEK
;
2698 buf
.buf
[0].fd
= lo_fi_fd(req
, fi
);
2699 buf
.buf
[0].pos
= offset
;
2701 fuse_reply_data(req
, &buf
);
2704 static void lo_write_buf(fuse_req_t req
, fuse_ino_t ino
,
2705 struct fuse_bufvec
*in_buf
, off_t off
,
2706 struct fuse_file_info
*fi
)
2710 struct fuse_bufvec out_buf
= FUSE_BUFVEC_INIT(fuse_buf_size(in_buf
));
2711 bool cap_fsetid_dropped
= false;
2713 out_buf
.buf
[0].flags
= FUSE_BUF_IS_FD
| FUSE_BUF_FD_SEEK
;
2714 out_buf
.buf
[0].fd
= lo_fi_fd(req
, fi
);
2715 out_buf
.buf
[0].pos
= off
;
2717 fuse_log(FUSE_LOG_DEBUG
,
2718 "lo_write_buf(ino=%" PRIu64
", size=%zd, off=%lu kill_priv=%d)\n",
2719 ino
, out_buf
.buf
[0].size
, (unsigned long)off
, fi
->kill_priv
);
2721 res
= drop_security_capability(lo_data(req
), out_buf
.buf
[0].fd
);
2723 fuse_reply_err(req
, res
);
2728 * If kill_priv is set, drop CAP_FSETID which should lead to kernel
2729 * clearing setuid/setgid on file. Note, for WRITE, we need to do
2730 * this even if killpriv_v2 is not enabled. fuse direct write path
2733 if (fi
->kill_priv
) {
2734 res
= drop_effective_cap("FSETID", &cap_fsetid_dropped
);
2736 fuse_reply_err(req
, res
);
2741 res
= fuse_buf_copy(&out_buf
, in_buf
);
2743 fuse_reply_err(req
, -res
);
2745 fuse_reply_write(req
, (size_t)res
);
2748 if (cap_fsetid_dropped
) {
2749 res
= gain_effective_cap("FSETID");
2751 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_FSETID\n");
2756 static void lo_statfs(fuse_req_t req
, fuse_ino_t ino
)
2759 struct statvfs stbuf
;
2761 res
= fstatvfs(lo_fd(req
, ino
), &stbuf
);
2763 fuse_reply_err(req
, errno
);
2765 fuse_reply_statfs(req
, &stbuf
);
2769 static void lo_fallocate(fuse_req_t req
, fuse_ino_t ino
, int mode
, off_t offset
,
2770 off_t length
, struct fuse_file_info
*fi
)
2772 int err
= EOPNOTSUPP
;
2775 #ifdef CONFIG_FALLOCATE
2776 err
= fallocate(lo_fi_fd(req
, fi
), mode
, offset
, length
);
2781 #elif defined(CONFIG_POSIX_FALLOCATE)
2783 fuse_reply_err(req
, EOPNOTSUPP
);
2787 err
= posix_fallocate(lo_fi_fd(req
, fi
), offset
, length
);
2790 fuse_reply_err(req
, err
);
2793 static void lo_flock(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
2799 if (!(op
& LOCK_NB
)) {
2801 * Blocking flock can deadlock as there is only one thread
2802 * serving the queue.
2804 fuse_reply_err(req
, EOPNOTSUPP
);
2808 res
= flock(lo_fi_fd(req
, fi
), op
);
2810 fuse_reply_err(req
, res
== -1 ? errno
: 0);
2815 * Exit; process attribute unmodified if matched.
2816 * An empty key applies to all.
2818 #define XATTR_MAP_FLAG_OK (1 << 0)
2820 * The attribute is unwanted;
2821 * EPERM on write, hidden on read.
2823 #define XATTR_MAP_FLAG_BAD (1 << 1)
2825 * For attr that start with 'key' prepend 'prepend'
2826 * 'key' may be empty to prepend for all attrs
2827 * key is defined from set/remove point of view.
2828 * Automatically reversed on read
2830 #define XATTR_MAP_FLAG_PREFIX (1 << 2)
2832 * The attribute is unsupported;
2833 * ENOTSUP on write, hidden on read.
2835 #define XATTR_MAP_FLAG_UNSUPPORTED (1 << 3)
2838 /* Apply rule to get/set/remove */
2839 #define XATTR_MAP_FLAG_CLIENT (1 << 16)
2840 /* Apply rule to list */
2841 #define XATTR_MAP_FLAG_SERVER (1 << 17)
2842 /* Apply rule to all */
2843 #define XATTR_MAP_FLAG_ALL (XATTR_MAP_FLAG_SERVER | XATTR_MAP_FLAG_CLIENT)
2845 static void add_xattrmap_entry(struct lo_data
*lo
,
2846 const XattrMapEntry
*new_entry
)
2848 XattrMapEntry
*res
= g_realloc_n(lo
->xattr_map_list
,
2849 lo
->xattr_map_nentries
+ 1,
2850 sizeof(XattrMapEntry
));
2851 res
[lo
->xattr_map_nentries
++] = *new_entry
;
2853 lo
->xattr_map_list
= res
;
2856 static void free_xattrmap(struct lo_data
*lo
)
2858 XattrMapEntry
*map
= lo
->xattr_map_list
;
2865 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
2867 g_free(map
[i
].prepend
);
2871 lo
->xattr_map_list
= NULL
;
2872 lo
->xattr_map_nentries
= -1;
2876 * Handle the 'map' type, which is sugar for a set of commands
2877 * for the common case of prefixing a subset or everything,
2878 * and allowing anything not prefixed through.
2879 * It must be the last entry in the stream, although there
2880 * can be other entries before it.
2884 * key maybe empty in which case all entries are prefixed.
2886 static void parse_xattrmap_map(struct lo_data
*lo
,
2887 const char *rule
, char sep
)
2892 XattrMapEntry tmp_entry
;
2895 fuse_log(FUSE_LOG_ERR
,
2896 "%s: Expecting '%c' after 'map' keyword, found '%c'\n",
2897 __func__
, sep
, *rule
);
2903 /* At start of 'key' field */
2904 tmp
= strchr(rule
, sep
);
2906 fuse_log(FUSE_LOG_ERR
,
2907 "%s: Missing '%c' at end of key field in map rule\n",
2912 key
= g_strndup(rule
, tmp
- rule
);
2915 /* At start of prefix field */
2916 tmp
= strchr(rule
, sep
);
2918 fuse_log(FUSE_LOG_ERR
,
2919 "%s: Missing '%c' at end of prefix field in map rule\n",
2924 prefix
= g_strndup(rule
, tmp
- rule
);
2928 * This should be the end of the string, we don't allow
2929 * any more commands after 'map'.
2932 fuse_log(FUSE_LOG_ERR
,
2933 "%s: Expecting end of command after map, found '%c'\n",
2938 /* 1st: Prefix matches/everything */
2939 tmp_entry
.flags
= XATTR_MAP_FLAG_PREFIX
| XATTR_MAP_FLAG_ALL
;
2940 tmp_entry
.key
= g_strdup(key
);
2941 tmp_entry
.prepend
= g_strdup(prefix
);
2942 add_xattrmap_entry(lo
, &tmp_entry
);
2945 /* Prefix all case */
2947 /* 2nd: Hide any non-prefixed entries on the host */
2948 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_ALL
;
2949 tmp_entry
.key
= g_strdup("");
2950 tmp_entry
.prepend
= g_strdup("");
2951 add_xattrmap_entry(lo
, &tmp_entry
);
2953 /* Prefix matching case */
2955 /* 2nd: Hide non-prefixed but matching entries on the host */
2956 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_SERVER
;
2957 tmp_entry
.key
= g_strdup(""); /* Not used */
2958 tmp_entry
.prepend
= g_strdup(key
);
2959 add_xattrmap_entry(lo
, &tmp_entry
);
2961 /* 3rd: Stop the client accessing prefixed attributes directly */
2962 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_CLIENT
;
2963 tmp_entry
.key
= g_strdup(prefix
);
2964 tmp_entry
.prepend
= g_strdup(""); /* Not used */
2965 add_xattrmap_entry(lo
, &tmp_entry
);
2967 /* 4th: Everything else is OK */
2968 tmp_entry
.flags
= XATTR_MAP_FLAG_OK
| XATTR_MAP_FLAG_ALL
;
2969 tmp_entry
.key
= g_strdup("");
2970 tmp_entry
.prepend
= g_strdup("");
2971 add_xattrmap_entry(lo
, &tmp_entry
);
2978 static void parse_xattrmap(struct lo_data
*lo
)
2980 const char *map
= lo
->xattrmap
;
2984 lo
->xattr_map_nentries
= 0;
2986 XattrMapEntry tmp_entry
;
2989 if (isspace(*map
)) {
2993 /* The separator is the first non-space of the rule */
2999 tmp_entry
.flags
= 0;
3000 /* Start of 'type' */
3001 if (strstart(map
, "prefix", &map
)) {
3002 tmp_entry
.flags
|= XATTR_MAP_FLAG_PREFIX
;
3003 } else if (strstart(map
, "ok", &map
)) {
3004 tmp_entry
.flags
|= XATTR_MAP_FLAG_OK
;
3005 } else if (strstart(map
, "bad", &map
)) {
3006 tmp_entry
.flags
|= XATTR_MAP_FLAG_BAD
;
3007 } else if (strstart(map
, "unsupported", &map
)) {
3008 tmp_entry
.flags
|= XATTR_MAP_FLAG_UNSUPPORTED
;
3009 } else if (strstart(map
, "map", &map
)) {
3011 * map is sugar that adds a number of rules, and must be
3014 parse_xattrmap_map(lo
, map
, sep
);
3017 fuse_log(FUSE_LOG_ERR
,
3018 "%s: Unexpected type;"
3019 "Expecting 'prefix', 'ok', 'bad', 'unsupported' or 'map'"
3020 " in rule %zu\n", __func__
, lo
->xattr_map_nentries
);
3024 if (*map
++ != sep
) {
3025 fuse_log(FUSE_LOG_ERR
,
3026 "%s: Missing '%c' at end of type field of rule %zu\n",
3027 __func__
, sep
, lo
->xattr_map_nentries
);
3031 /* Start of 'scope' */
3032 if (strstart(map
, "client", &map
)) {
3033 tmp_entry
.flags
|= XATTR_MAP_FLAG_CLIENT
;
3034 } else if (strstart(map
, "server", &map
)) {
3035 tmp_entry
.flags
|= XATTR_MAP_FLAG_SERVER
;
3036 } else if (strstart(map
, "all", &map
)) {
3037 tmp_entry
.flags
|= XATTR_MAP_FLAG_ALL
;
3039 fuse_log(FUSE_LOG_ERR
,
3040 "%s: Unexpected scope;"
3041 " Expecting 'client', 'server', or 'all', in rule %zu\n",
3042 __func__
, lo
->xattr_map_nentries
);
3046 if (*map
++ != sep
) {
3047 fuse_log(FUSE_LOG_ERR
,
3048 "%s: Expecting '%c' found '%c'"
3049 " after scope in rule %zu\n",
3050 __func__
, sep
, *map
, lo
->xattr_map_nentries
);
3054 /* At start of 'key' field */
3055 tmp
= strchr(map
, sep
);
3057 fuse_log(FUSE_LOG_ERR
,
3058 "%s: Missing '%c' at end of key field of rule %zu",
3059 __func__
, sep
, lo
->xattr_map_nentries
);
3062 tmp_entry
.key
= g_strndup(map
, tmp
- map
);
3065 /* At start of 'prepend' field */
3066 tmp
= strchr(map
, sep
);
3068 fuse_log(FUSE_LOG_ERR
,
3069 "%s: Missing '%c' at end of prepend field of rule %zu",
3070 __func__
, sep
, lo
->xattr_map_nentries
);
3073 tmp_entry
.prepend
= g_strndup(map
, tmp
- map
);
3076 add_xattrmap_entry(lo
, &tmp_entry
);
3077 /* End of rule - go around again for another rule */
3080 if (!lo
->xattr_map_nentries
) {
3081 fuse_log(FUSE_LOG_ERR
, "Empty xattr map\n");
3085 ret
= xattr_map_client(lo
, "security.capability",
3086 &lo
->xattr_security_capability
);
3088 fuse_log(FUSE_LOG_ERR
, "Failed to map security.capability: %s\n",
3092 if (!lo
->xattr_security_capability
||
3093 !strcmp(lo
->xattr_security_capability
, "security.capability")) {
3094 /* 1-1 mapping, don't need to do anything */
3095 free(lo
->xattr_security_capability
);
3096 lo
->xattr_security_capability
= NULL
;
3101 * For use with getxattr/setxattr/removexattr, where the client
3102 * gives us a name and we may need to choose a different one.
3103 * Allocates a buffer for the result placing it in *out_name.
3104 * If there's no change then *out_name is not set.
3105 * Returns 0 on success
3106 * Can return -EPERM to indicate we block a given attribute
3107 * (in which case out_name is not allocated)
3108 * Can return -ENOMEM to indicate out_name couldn't be allocated.
3110 static int xattr_map_client(const struct lo_data
*lo
, const char *client_name
,
3114 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
3115 const XattrMapEntry
*cur_entry
= lo
->xattr_map_list
+ i
;
3117 if ((cur_entry
->flags
& XATTR_MAP_FLAG_CLIENT
) &&
3118 (strstart(client_name
, cur_entry
->key
, NULL
))) {
3119 if (cur_entry
->flags
& XATTR_MAP_FLAG_BAD
) {
3122 if (cur_entry
->flags
& XATTR_MAP_FLAG_UNSUPPORTED
) {
3125 if (cur_entry
->flags
& XATTR_MAP_FLAG_OK
) {
3126 /* Unmodified name */
3129 if (cur_entry
->flags
& XATTR_MAP_FLAG_PREFIX
) {
3130 *out_name
= g_try_malloc(strlen(client_name
) +
3131 strlen(cur_entry
->prepend
) + 1);
3135 sprintf(*out_name
, "%s%s", cur_entry
->prepend
, client_name
);
3145 * For use with listxattr where the server fs gives us a name and we may need
3146 * to sanitize this for the client.
3147 * Returns a pointer to the result in *out_name
3148 * This is always the original string or the current string with some prefix
3149 * removed; no reallocation is done.
3150 * Returns 0 on success
3151 * Can return -ENODATA to indicate the name should be dropped from the list.
3153 static int xattr_map_server(const struct lo_data
*lo
, const char *server_name
,
3154 const char **out_name
)
3159 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
3160 const XattrMapEntry
*cur_entry
= lo
->xattr_map_list
+ i
;
3162 if ((cur_entry
->flags
& XATTR_MAP_FLAG_SERVER
) &&
3163 (strstart(server_name
, cur_entry
->prepend
, &end
))) {
3164 if (cur_entry
->flags
& XATTR_MAP_FLAG_BAD
||
3165 cur_entry
->flags
& XATTR_MAP_FLAG_UNSUPPORTED
) {
3168 if (cur_entry
->flags
& XATTR_MAP_FLAG_OK
) {
3169 *out_name
= server_name
;
3172 if (cur_entry
->flags
& XATTR_MAP_FLAG_PREFIX
) {
3183 static bool block_xattr(struct lo_data
*lo
, const char *name
)
3186 * If user explicitly enabled posix_acl or did not provide any option,
3187 * do not block acl. Otherwise block system.posix_acl_access and
3188 * system.posix_acl_default xattrs.
3190 if (lo
->user_posix_acl
) {
3193 if (!strcmp(name
, "system.posix_acl_access") ||
3194 !strcmp(name
, "system.posix_acl_default"))
3201 * Returns number of bytes in xattr_list after filtering on success. This
3202 * could be zero as well if nothing is left after filtering.
3204 * Returns negative error code on failure.
3205 * xattr_list is modified in place.
3207 static int remove_blocked_xattrs(struct lo_data
*lo
, char *xattr_list
,
3210 size_t out_index
, in_index
;
3213 * As of now we only filter out acl xattrs. If acls are enabled or
3214 * they have not been explicitly disabled, there is nothing to
3217 if (lo
->user_posix_acl
) {
3223 while (in_index
< in_size
) {
3224 char *in_ptr
= xattr_list
+ in_index
;
3226 /* Length of current attribute name */
3227 size_t in_len
= strlen(xattr_list
+ in_index
) + 1;
3229 if (!block_xattr(lo
, in_ptr
)) {
3230 if (in_index
!= out_index
) {
3231 memmove(xattr_list
+ out_index
, xattr_list
+ in_index
, in_len
);
3233 out_index
+= in_len
;
3240 static void lo_getxattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
,
3243 struct lo_data
*lo
= lo_data(req
);
3244 g_autofree
char *value
= NULL
;
3248 struct lo_inode
*inode
;
3253 if (block_xattr(lo
, in_name
)) {
3254 fuse_reply_err(req
, EOPNOTSUPP
);
3261 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
3263 if (ret
== -EPERM
) {
3266 fuse_reply_err(req
, -ret
);
3274 inode
= lo_inode(req
, ino
);
3276 fuse_reply_err(req
, EBADF
);
3277 g_free(mapped_name
);
3282 if (!lo_data(req
)->xattr
) {
3286 fuse_log(FUSE_LOG_DEBUG
, "lo_getxattr(ino=%" PRIu64
", name=%s size=%zd)\n",
3290 value
= g_try_malloc(size
);
3296 sprintf(procname
, "%i", inode
->fd
);
3298 * It is not safe to open() non-regular/non-dir files in file server
3299 * unless O_PATH is used, so use that method for regular files/dir
3300 * only (as it seems giving less performance overhead).
3301 * Otherwise, call fchdir() to avoid open().
3303 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
3304 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
3308 ret
= fgetxattr(fd
, name
, value
, size
);
3309 saverr
= ret
== -1 ? errno
: 0;
3311 /* fchdir should not fail here */
3312 FCHDIR_NOFAIL(lo
->proc_self_fd
);
3313 ret
= getxattr(procname
, name
, value
, size
);
3314 saverr
= ret
== -1 ? errno
: 0;
3315 FCHDIR_NOFAIL(lo
->root
.fd
);
3326 fuse_reply_buf(req
, value
, ret
);
3328 fuse_reply_xattr(req
, ret
);
3335 lo_inode_put(lo
, &inode
);
3341 fuse_reply_err(req
, saverr
);
3342 g_free(mapped_name
);
3346 static void lo_listxattr(fuse_req_t req
, fuse_ino_t ino
, size_t size
)
3348 struct lo_data
*lo
= lo_data(req
);
3349 g_autofree
char *value
= NULL
;
3351 struct lo_inode
*inode
;
3356 inode
= lo_inode(req
, ino
);
3358 fuse_reply_err(req
, EBADF
);
3363 if (!lo_data(req
)->xattr
) {
3367 fuse_log(FUSE_LOG_DEBUG
, "lo_listxattr(ino=%" PRIu64
", size=%zd)\n", ino
,
3371 value
= g_try_malloc(size
);
3377 sprintf(procname
, "%i", inode
->fd
);
3378 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
3379 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
3383 ret
= flistxattr(fd
, value
, size
);
3384 saverr
= ret
== -1 ? errno
: 0;
3386 /* fchdir should not fail here */
3387 FCHDIR_NOFAIL(lo
->proc_self_fd
);
3388 ret
= listxattr(procname
, value
, size
);
3389 saverr
= ret
== -1 ? errno
: 0;
3390 FCHDIR_NOFAIL(lo
->root
.fd
);
3402 if (lo
->xattr_map_list
) {
3404 * Map the names back, some attributes might be dropped,
3405 * some shortened, but not increased, so we shouldn't
3408 size_t out_index
, in_index
;
3411 while (in_index
< ret
) {
3412 const char *map_out
;
3413 char *in_ptr
= value
+ in_index
;
3414 /* Length of current attribute name */
3415 size_t in_len
= strlen(value
+ in_index
) + 1;
3417 int mapret
= xattr_map_server(lo
, in_ptr
, &map_out
);
3418 if (mapret
!= -ENODATA
&& mapret
!= 0) {
3419 /* Shouldn't happen */
3424 /* Either unchanged, or truncated */
3426 if (map_out
!= in_ptr
) {
3427 /* +1 copies the NIL */
3428 out_len
= strlen(map_out
) + 1;
3434 * Move result along, may still be needed for an unchanged
3435 * entry if a previous entry was changed.
3437 memmove(value
+ out_index
, map_out
, out_len
);
3439 out_index
+= out_len
;
3449 ret
= remove_blocked_xattrs(lo
, value
, ret
);
3454 fuse_reply_buf(req
, value
, ret
);
3457 * xattrmap only ever shortens the result,
3458 * so we don't need to do anything clever with the
3459 * allocation length here.
3461 fuse_reply_xattr(req
, ret
);
3468 lo_inode_put(lo
, &inode
);
3474 fuse_reply_err(req
, saverr
);
3478 static void lo_setxattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
,
3479 const char *value
, size_t size
, int flags
,
3480 uint32_t extra_flags
)
3485 struct lo_data
*lo
= lo_data(req
);
3486 struct lo_inode
*inode
;
3490 bool switched_creds
= false;
3491 bool cap_fsetid_dropped
= false;
3492 struct lo_cred old
= {};
3494 if (block_xattr(lo
, in_name
)) {
3495 fuse_reply_err(req
, EOPNOTSUPP
);
3502 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
3504 fuse_reply_err(req
, -ret
);
3512 inode
= lo_inode(req
, ino
);
3514 fuse_reply_err(req
, EBADF
);
3515 g_free(mapped_name
);
3520 if (!lo_data(req
)->xattr
) {
3524 fuse_log(FUSE_LOG_DEBUG
, "lo_setxattr(ino=%" PRIu64
3525 ", name=%s value=%s size=%zd)\n", ino
, name
, value
, size
);
3527 sprintf(procname
, "%i", inode
->fd
);
3529 * If we are setting posix access acl and if SGID needs to be
3530 * cleared, then switch to caller's gid and drop CAP_FSETID
3531 * and that should make sure host kernel clears SGID.
3533 * This probably will not work when we support idmapped mounts.
3534 * In that case we will need to find a non-root gid and switch
3535 * to it. (Instead of gid in request). Fix it when we support
3538 if (lo
->posix_acl
&& !strcmp(name
, "system.posix_acl_access")
3539 && (extra_flags
& FUSE_SETXATTR_ACL_KILL_SGID
)) {
3540 ret
= lo_drop_cap_change_cred(req
, &old
, false, "FSETID",
3541 &cap_fsetid_dropped
);
3546 switched_creds
= true;
3548 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
3549 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
3554 ret
= fsetxattr(fd
, name
, value
, size
, flags
);
3555 saverr
= ret
== -1 ? errno
: 0;
3557 /* fchdir should not fail here */
3558 FCHDIR_NOFAIL(lo
->proc_self_fd
);
3559 ret
= setxattr(procname
, name
, value
, size
, flags
);
3560 saverr
= ret
== -1 ? errno
: 0;
3561 FCHDIR_NOFAIL(lo
->root
.fd
);
3563 if (switched_creds
) {
3564 if (cap_fsetid_dropped
)
3565 lo_restore_cred_gain_cap(&old
, false, "FSETID");
3567 lo_restore_cred(&old
, false);
3575 lo_inode_put(lo
, &inode
);
3576 g_free(mapped_name
);
3577 fuse_reply_err(req
, saverr
);
3580 static void lo_removexattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
)
3585 struct lo_data
*lo
= lo_data(req
);
3586 struct lo_inode
*inode
;
3591 if (block_xattr(lo
, in_name
)) {
3592 fuse_reply_err(req
, EOPNOTSUPP
);
3599 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
3601 fuse_reply_err(req
, -ret
);
3609 inode
= lo_inode(req
, ino
);
3611 fuse_reply_err(req
, EBADF
);
3612 g_free(mapped_name
);
3617 if (!lo_data(req
)->xattr
) {
3621 fuse_log(FUSE_LOG_DEBUG
, "lo_removexattr(ino=%" PRIu64
", name=%s)\n", ino
,
3624 sprintf(procname
, "%i", inode
->fd
);
3625 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
3626 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
3631 ret
= fremovexattr(fd
, name
);
3632 saverr
= ret
== -1 ? errno
: 0;
3634 /* fchdir should not fail here */
3635 FCHDIR_NOFAIL(lo
->proc_self_fd
);
3636 ret
= removexattr(procname
, name
);
3637 saverr
= ret
== -1 ? errno
: 0;
3638 FCHDIR_NOFAIL(lo
->root
.fd
);
3646 lo_inode_put(lo
, &inode
);
3647 g_free(mapped_name
);
3648 fuse_reply_err(req
, saverr
);
3651 #ifdef HAVE_COPY_FILE_RANGE
3652 static void lo_copy_file_range(fuse_req_t req
, fuse_ino_t ino_in
, off_t off_in
,
3653 struct fuse_file_info
*fi_in
, fuse_ino_t ino_out
,
3654 off_t off_out
, struct fuse_file_info
*fi_out
,
3655 size_t len
, int flags
)
3660 in_fd
= lo_fi_fd(req
, fi_in
);
3661 out_fd
= lo_fi_fd(req
, fi_out
);
3663 fuse_log(FUSE_LOG_DEBUG
,
3664 "lo_copy_file_range(ino=%" PRIu64
"/fd=%d, "
3665 "off=%ju, ino=%" PRIu64
"/fd=%d, "
3666 "off=%ju, size=%zd, flags=0x%x)\n",
3667 ino_in
, in_fd
, (intmax_t)off_in
,
3668 ino_out
, out_fd
, (intmax_t)off_out
, len
, flags
);
3670 res
= copy_file_range(in_fd
, &off_in
, out_fd
, &off_out
, len
, flags
);
3672 fuse_reply_err(req
, errno
);
3674 fuse_reply_write(req
, res
);
3679 static void lo_lseek(fuse_req_t req
, fuse_ino_t ino
, off_t off
, int whence
,
3680 struct fuse_file_info
*fi
)
3685 res
= lseek(lo_fi_fd(req
, fi
), off
, whence
);
3687 fuse_reply_lseek(req
, res
);
3689 fuse_reply_err(req
, errno
);
3693 static int lo_do_syncfs(struct lo_data
*lo
, struct lo_inode
*inode
)
3697 fuse_log(FUSE_LOG_DEBUG
, "lo_do_syncfs(ino=%" PRIu64
")\n",
3700 fd
= lo_inode_open(lo
, inode
, O_RDONLY
);
3705 if (syncfs(fd
) < 0) {
3713 static void lo_syncfs(fuse_req_t req
, fuse_ino_t ino
)
3715 struct lo_data
*lo
= lo_data(req
);
3716 struct lo_inode
*inode
= lo_inode(req
, ino
);
3720 fuse_reply_err(req
, EBADF
);
3724 err
= lo_do_syncfs(lo
, inode
);
3725 lo_inode_put(lo
, &inode
);
3728 * If submounts aren't announced, the client only sends a request to
3729 * sync the root inode. TODO: Track submounts internally and iterate
3730 * over them as well.
3733 fuse_reply_err(req
, err
);
3736 static void lo_destroy(void *userdata
)
3738 struct lo_data
*lo
= (struct lo_data
*)userdata
;
3740 pthread_mutex_lock(&lo
->mutex
);
3742 GHashTableIter iter
;
3743 gpointer key
, value
;
3745 g_hash_table_iter_init(&iter
, lo
->inodes
);
3746 if (!g_hash_table_iter_next(&iter
, &key
, &value
)) {
3750 struct lo_inode
*inode
= value
;
3751 unref_inode(lo
, inode
, inode
->nlookup
);
3753 pthread_mutex_unlock(&lo
->mutex
);
3756 static struct fuse_lowlevel_ops lo_oper
= {
3758 .lookup
= lo_lookup
,
3761 .symlink
= lo_symlink
,
3763 .unlink
= lo_unlink
,
3765 .rename
= lo_rename
,
3766 .forget
= lo_forget
,
3767 .forget_multi
= lo_forget_multi
,
3768 .getattr
= lo_getattr
,
3769 .setattr
= lo_setattr
,
3770 .readlink
= lo_readlink
,
3771 .opendir
= lo_opendir
,
3772 .readdir
= lo_readdir
,
3773 .readdirplus
= lo_readdirplus
,
3774 .releasedir
= lo_releasedir
,
3775 .fsyncdir
= lo_fsyncdir
,
3776 .create
= lo_create
,
3780 .release
= lo_release
,
3784 .write_buf
= lo_write_buf
,
3785 .statfs
= lo_statfs
,
3786 .fallocate
= lo_fallocate
,
3788 .getxattr
= lo_getxattr
,
3789 .listxattr
= lo_listxattr
,
3790 .setxattr
= lo_setxattr
,
3791 .removexattr
= lo_removexattr
,
3792 #ifdef HAVE_COPY_FILE_RANGE
3793 .copy_file_range
= lo_copy_file_range
,
3796 .syncfs
= lo_syncfs
,
3797 .destroy
= lo_destroy
,
3800 /* Print vhost-user.json backend program capabilities */
3801 static void print_capabilities(void)
3804 printf(" \"type\": \"fs\"\n");
3809 * Drop all Linux capabilities because the wait parent process only needs to
3810 * sit in waitpid(2) and terminate.
3812 static void setup_wait_parent_capabilities(void)
3814 capng_setpid(syscall(SYS_gettid
));
3815 capng_clear(CAPNG_SELECT_BOTH
);
3816 capng_apply(CAPNG_SELECT_BOTH
);
3820 * Move to a new mount, net, and pid namespaces to isolate this process.
3822 static void setup_namespaces(struct lo_data
*lo
, struct fuse_session
*se
)
3827 * Create a new pid namespace for *child* processes. We'll have to
3828 * fork in order to enter the new pid namespace. A new mount namespace
3829 * is also needed so that we can remount /proc for the new pid
3832 * Our UNIX domain sockets have been created. Now we can move to
3833 * an empty network namespace to prevent TCP/IP and other network
3834 * activity in case this process is compromised.
3836 if (unshare(CLONE_NEWPID
| CLONE_NEWNS
| CLONE_NEWNET
) != 0) {
3837 fuse_log(FUSE_LOG_ERR
, "unshare(CLONE_NEWPID | CLONE_NEWNS): %m\n");
3843 fuse_log(FUSE_LOG_ERR
, "fork() failed: %m\n");
3850 setup_wait_parent_capabilities();
3852 /* The parent waits for the child */
3854 waited
= waitpid(child
, &wstatus
, 0);
3855 } while (waited
< 0 && errno
== EINTR
&& !se
->exited
);
3857 /* We were terminated by a signal, see fuse_signals.c */
3862 if (WIFEXITED(wstatus
)) {
3863 exit(WEXITSTATUS(wstatus
));
3869 /* Send us SIGTERM when the parent thread terminates, see prctl(2) */
3870 prctl(PR_SET_PDEATHSIG
, SIGTERM
);
3873 * If the mounts have shared propagation then we want to opt out so our
3874 * mount changes don't affect the parent mount namespace.
3876 if (mount(NULL
, "/", NULL
, MS_REC
| MS_SLAVE
, NULL
) < 0) {
3877 fuse_log(FUSE_LOG_ERR
, "mount(/, MS_REC|MS_SLAVE): %m\n");
3881 /* The child must remount /proc to use the new pid namespace */
3882 if (mount("proc", "/proc", "proc",
3883 MS_NODEV
| MS_NOEXEC
| MS_NOSUID
| MS_RELATIME
, NULL
) < 0) {
3884 fuse_log(FUSE_LOG_ERR
, "mount(/proc): %m\n");
3888 /* Get the /proc/self/task descriptor */
3889 lo
->proc_self_task
= open("/proc/self/task/", O_PATH
);
3890 if (lo
->proc_self_task
== -1) {
3891 fuse_log(FUSE_LOG_ERR
, "open(/proc/self/task, O_PATH): %m\n");
3895 lo
->use_fscreate
= is_fscreate_usable(lo
);
3898 * We only need /proc/self/fd. Prevent ".." from accessing parent
3899 * directories of /proc/self/fd by bind-mounting it over /proc. Since / was
3900 * previously remounted with MS_REC | MS_SLAVE this mount change only
3901 * affects our process.
3903 if (mount("/proc/self/fd", "/proc", NULL
, MS_BIND
, NULL
) < 0) {
3904 fuse_log(FUSE_LOG_ERR
, "mount(/proc/self/fd, MS_BIND): %m\n");
3908 /* Get the /proc (actually /proc/self/fd, see above) file descriptor */
3909 lo
->proc_self_fd
= open("/proc", O_PATH
);
3910 if (lo
->proc_self_fd
== -1) {
3911 fuse_log(FUSE_LOG_ERR
, "open(/proc, O_PATH): %m\n");
3917 * Capture the capability state, we'll need to restore this for individual
3918 * threads later; see load_capng.
3920 static void setup_capng(void)
3922 /* Note this accesses /proc so has to happen before the sandbox */
3923 if (capng_get_caps_process()) {
3924 fuse_log(FUSE_LOG_ERR
, "capng_get_caps_process\n");
3927 pthread_mutex_init(&cap
.mutex
, NULL
);
3928 pthread_mutex_lock(&cap
.mutex
);
3929 cap
.saved
= capng_save_state();
3931 fuse_log(FUSE_LOG_ERR
, "capng_save_state\n");
3934 pthread_mutex_unlock(&cap
.mutex
);
3937 static void cleanup_capng(void)
3941 pthread_mutex_destroy(&cap
.mutex
);
3946 * Make the source directory our root so symlinks cannot escape and no other
3947 * files are accessible. Assumes unshare(CLONE_NEWNS) was already called.
3949 static void setup_mounts(const char *source
)
3954 if (mount(source
, source
, NULL
, MS_BIND
| MS_REC
, NULL
) < 0) {
3955 fuse_log(FUSE_LOG_ERR
, "mount(%s, %s, MS_BIND): %m\n", source
, source
);
3959 /* This magic is based on lxc's lxc_pivot_root() */
3960 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
3962 fuse_log(FUSE_LOG_ERR
, "open(/): %m\n");
3966 newroot
= open(source
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
3968 fuse_log(FUSE_LOG_ERR
, "open(%s): %m\n", source
);
3972 if (fchdir(newroot
) < 0) {
3973 fuse_log(FUSE_LOG_ERR
, "fchdir(newroot): %m\n");
3977 if (syscall(__NR_pivot_root
, ".", ".") < 0) {
3978 fuse_log(FUSE_LOG_ERR
, "pivot_root(., .): %m\n");
3982 if (fchdir(oldroot
) < 0) {
3983 fuse_log(FUSE_LOG_ERR
, "fchdir(oldroot): %m\n");
3987 if (mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
) < 0) {
3988 fuse_log(FUSE_LOG_ERR
, "mount(., MS_SLAVE | MS_REC): %m\n");
3992 if (umount2(".", MNT_DETACH
) < 0) {
3993 fuse_log(FUSE_LOG_ERR
, "umount2(., MNT_DETACH): %m\n");
3997 if (fchdir(newroot
) < 0) {
3998 fuse_log(FUSE_LOG_ERR
, "fchdir(newroot): %m\n");
4007 * Only keep capabilities in allowlist that are needed for file system operation
4008 * The (possibly NULL) modcaps_in string passed in is free'd before exit.
4010 static void setup_capabilities(char *modcaps_in
)
4012 char *modcaps
= modcaps_in
;
4013 pthread_mutex_lock(&cap
.mutex
);
4014 capng_restore_state(&cap
.saved
);
4017 * Add to allowlist file system-related capabilities that are needed for a
4018 * file server to act like root. Drop everything else like networking and
4019 * sysadmin capabilities.
4022 * 1. CAP_LINUX_IMMUTABLE is not included because it's only used via ioctl
4023 * and we don't support that.
4024 * 2. CAP_MAC_OVERRIDE is not included because it only seems to be
4025 * used by the Smack LSM. Omit it until there is demand for it.
4027 capng_setpid(syscall(SYS_gettid
));
4028 capng_clear(CAPNG_SELECT_BOTH
);
4029 if (capng_updatev(CAPNG_ADD
, CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
4039 fuse_log(FUSE_LOG_ERR
, "%s: capng_updatev failed\n", __func__
);
4044 * The modcaps option is a colon separated list of caps,
4045 * each preceded by either + or -.
4051 char *next
= strchr(modcaps
, ':');
4057 switch (modcaps
[0]) {
4063 action
= CAPNG_DROP
;
4067 fuse_log(FUSE_LOG_ERR
,
4068 "%s: Expecting '+'/'-' in modcaps but found '%c'\n",
4069 __func__
, modcaps
[0]);
4072 cap
= capng_name_to_capability(modcaps
+ 1);
4074 fuse_log(FUSE_LOG_ERR
, "%s: Unknown capability '%s'\n", __func__
,
4078 if (capng_update(action
, CAPNG_PERMITTED
| CAPNG_EFFECTIVE
, cap
)) {
4079 fuse_log(FUSE_LOG_ERR
, "%s: capng_update failed for '%s'\n",
4088 if (capng_apply(CAPNG_SELECT_BOTH
)) {
4089 fuse_log(FUSE_LOG_ERR
, "%s: capng_apply failed\n", __func__
);
4093 cap
.saved
= capng_save_state();
4095 fuse_log(FUSE_LOG_ERR
, "%s: capng_save_state failed\n", __func__
);
4098 pthread_mutex_unlock(&cap
.mutex
);
4102 * Use chroot as a weaker sandbox for environments where the process is
4103 * launched without CAP_SYS_ADMIN.
4105 static void setup_chroot(struct lo_data
*lo
)
4107 lo
->proc_self_fd
= open("/proc/self/fd", O_PATH
);
4108 if (lo
->proc_self_fd
== -1) {
4109 fuse_log(FUSE_LOG_ERR
, "open(\"/proc/self/fd\", O_PATH): %m\n");
4113 lo
->proc_self_task
= open("/proc/self/task", O_PATH
);
4114 if (lo
->proc_self_fd
== -1) {
4115 fuse_log(FUSE_LOG_ERR
, "open(\"/proc/self/task\", O_PATH): %m\n");
4119 lo
->use_fscreate
= is_fscreate_usable(lo
);
4122 * Make the shared directory the file system root so that FUSE_OPEN
4123 * (lo_open()) cannot escape the shared directory by opening a symlink.
4125 * The chroot(2) syscall is later disabled by seccomp and the
4126 * CAP_SYS_CHROOT capability is dropped so that tampering with the chroot
4129 * However, it's still possible to escape the chroot via lo->proc_self_fd
4130 * but that requires first gaining control of the process.
4132 if (chroot(lo
->source
) != 0) {
4133 fuse_log(FUSE_LOG_ERR
, "chroot(\"%s\"): %m\n", lo
->source
);
4137 /* Move into the chroot */
4138 if (chdir("/") != 0) {
4139 fuse_log(FUSE_LOG_ERR
, "chdir(\"/\"): %m\n");
4145 * Lock down this process to prevent access to other processes or files outside
4146 * source directory. This reduces the impact of arbitrary code execution bugs.
4148 static void setup_sandbox(struct lo_data
*lo
, struct fuse_session
*se
,
4151 if (lo
->sandbox
== SANDBOX_NAMESPACE
) {
4152 setup_namespaces(lo
, se
);
4153 setup_mounts(lo
->source
);
4158 setup_seccomp(enable_syslog
);
4159 setup_capabilities(g_strdup(lo
->modcaps
));
4162 /* Set the maximum number of open file descriptors */
4163 static void setup_nofile_rlimit(unsigned long rlimit_nofile
)
4165 struct rlimit rlim
= {
4166 .rlim_cur
= rlimit_nofile
,
4167 .rlim_max
= rlimit_nofile
,
4170 if (rlimit_nofile
== 0) {
4171 return; /* nothing to do */
4174 if (setrlimit(RLIMIT_NOFILE
, &rlim
) < 0) {
4175 /* Ignore SELinux denials */
4176 if (errno
== EPERM
) {
4180 fuse_log(FUSE_LOG_ERR
, "setrlimit(RLIMIT_NOFILE): %m\n");
4186 static void log_func(enum fuse_log_level level
, const char *fmt
, va_list ap
)
4188 g_autofree
char *localfmt
= NULL
;
4191 if (current_log_level
< level
) {
4195 if (current_log_level
== FUSE_LOG_DEBUG
) {
4197 /* no timestamp needed */
4198 localfmt
= g_strdup_printf("[ID: %08ld] %s", syscall(__NR_gettid
),
4201 g_autoptr(GDateTime
) now
= g_date_time_new_now_utc();
4202 g_autofree
char *nowstr
= g_date_time_format(now
,
4203 "%Y-%m-%d %H:%M:%S.%%06d%z");
4204 snprintf(buf
, 64, nowstr
, g_date_time_get_microsecond(now
));
4205 localfmt
= g_strdup_printf("[%s] [ID: %08ld] %s",
4206 buf
, syscall(__NR_gettid
), fmt
);
4212 int priority
= LOG_ERR
;
4214 case FUSE_LOG_EMERG
:
4215 priority
= LOG_EMERG
;
4217 case FUSE_LOG_ALERT
:
4218 priority
= LOG_ALERT
;
4221 priority
= LOG_CRIT
;
4226 case FUSE_LOG_WARNING
:
4227 priority
= LOG_WARNING
;
4229 case FUSE_LOG_NOTICE
:
4230 priority
= LOG_NOTICE
;
4233 priority
= LOG_INFO
;
4235 case FUSE_LOG_DEBUG
:
4236 priority
= LOG_DEBUG
;
4239 vsyslog(priority
, fmt
, ap
);
4241 vfprintf(stderr
, fmt
, ap
);
4245 static void setup_root(struct lo_data
*lo
, struct lo_inode
*root
)
4251 fd
= open("/", O_PATH
);
4253 fuse_log(FUSE_LOG_ERR
, "open(%s, O_PATH): %m\n", lo
->source
);
4257 res
= do_statx(lo
, fd
, "", &stat
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
,
4260 fuse_log(FUSE_LOG_ERR
, "fstatat(%s): %m\n", lo
->source
);
4264 root
->filetype
= S_IFDIR
;
4266 root
->key
.ino
= stat
.st_ino
;
4267 root
->key
.dev
= stat
.st_dev
;
4268 root
->key
.mnt_id
= mnt_id
;
4270 g_atomic_int_set(&root
->refcount
, 2);
4271 if (lo
->posix_lock
) {
4272 pthread_mutex_init(&root
->plock_mutex
, NULL
);
4273 root
->posix_locks
= g_hash_table_new_full(
4274 g_direct_hash
, g_direct_equal
, NULL
, posix_locks_value_destroy
);
4278 static guint
lo_key_hash(gconstpointer key
)
4280 const struct lo_key
*lkey
= key
;
4282 return (guint
)lkey
->ino
+ (guint
)lkey
->dev
+ (guint
)lkey
->mnt_id
;
4285 static gboolean
lo_key_equal(gconstpointer a
, gconstpointer b
)
4287 const struct lo_key
*la
= a
;
4288 const struct lo_key
*lb
= b
;
4290 return la
->ino
== lb
->ino
&& la
->dev
== lb
->dev
&& la
->mnt_id
== lb
->mnt_id
;
4293 static void fuse_lo_data_cleanup(struct lo_data
*lo
)
4296 g_hash_table_destroy(lo
->inodes
);
4299 if (lo
->root
.posix_locks
) {
4300 g_hash_table_destroy(lo
->root
.posix_locks
);
4302 lo_map_destroy(&lo
->fd_map
);
4303 lo_map_destroy(&lo
->dirp_map
);
4304 lo_map_destroy(&lo
->ino_map
);
4306 if (lo
->proc_self_fd
>= 0) {
4307 close(lo
->proc_self_fd
);
4310 if (lo
->proc_self_task
>= 0) {
4311 close(lo
->proc_self_task
);
4314 if (lo
->root
.fd
>= 0) {
4320 free(lo
->xattr_security_capability
);
4324 static void qemu_version(void)
4326 printf("virtiofsd version " QEMU_FULL_VERSION
"\n" QEMU_COPYRIGHT
"\n");
4329 int main(int argc
, char *argv
[])
4331 struct fuse_args args
= FUSE_ARGS_INIT(argc
, argv
);
4332 struct fuse_session
*se
;
4333 struct fuse_cmdline_opts opts
;
4334 struct lo_data lo
= {
4335 .sandbox
= SANDBOX_NAMESPACE
,
4339 .allow_direct_io
= 0,
4341 .proc_self_task
= -1,
4342 .user_killpriv_v2
= -1,
4343 .user_posix_acl
= -1,
4344 .user_security_label
= -1,
4346 struct lo_map_elem
*root_elem
;
4347 struct lo_map_elem
*reserve_elem
;
4350 /* Initialize time conversion information for localtime_r(). */
4353 /* Don't mask creation mode, kernel already did that */
4356 qemu_init_exec_dir(argv
[0]);
4358 drop_supplementary_groups();
4360 pthread_mutex_init(&lo
.mutex
, NULL
);
4361 lo
.inodes
= g_hash_table_new(lo_key_hash
, lo_key_equal
);
4363 lo
.root
.fuse_ino
= FUSE_ROOT_ID
;
4364 lo
.cache
= CACHE_AUTO
;
4367 * Set up the ino map like this:
4368 * [0] Reserved (will not be used)
4371 lo_map_init(&lo
.ino_map
);
4372 reserve_elem
= lo_map_reserve(&lo
.ino_map
, 0);
4373 if (!reserve_elem
) {
4374 fuse_log(FUSE_LOG_ERR
, "failed to alloc reserve_elem.\n");
4377 reserve_elem
->in_use
= false;
4378 root_elem
= lo_map_reserve(&lo
.ino_map
, lo
.root
.fuse_ino
);
4380 fuse_log(FUSE_LOG_ERR
, "failed to alloc root_elem.\n");
4383 root_elem
->inode
= &lo
.root
;
4385 lo_map_init(&lo
.dirp_map
);
4386 lo_map_init(&lo
.fd_map
);
4388 if (fuse_parse_cmdline(&args
, &opts
) != 0) {
4391 fuse_set_log_func(log_func
);
4392 use_syslog
= opts
.syslog
;
4394 openlog("virtiofsd", LOG_PID
, LOG_DAEMON
);
4397 if (opts
.show_help
) {
4398 printf("usage: %s [options]\n\n", argv
[0]);
4399 fuse_cmdline_help();
4400 printf(" -o source=PATH shared directory tree\n");
4401 fuse_lowlevel_help();
4404 } else if (opts
.show_version
) {
4406 fuse_lowlevel_version();
4409 } else if (opts
.print_capabilities
) {
4410 print_capabilities();
4415 if (fuse_opt_parse(&args
, &lo
, lo_opts
, NULL
) == -1) {
4419 if (opts
.log_level
!= 0) {
4420 current_log_level
= opts
.log_level
;
4422 /* default log level is INFO */
4423 current_log_level
= FUSE_LOG_INFO
;
4425 lo
.debug
= opts
.debug
;
4427 current_log_level
= FUSE_LOG_DEBUG
;
4433 res
= lstat(lo
.source
, &stat
);
4435 fuse_log(FUSE_LOG_ERR
, "failed to stat source (\"%s\"): %m\n",
4439 if (!S_ISDIR(stat
.st_mode
)) {
4440 fuse_log(FUSE_LOG_ERR
, "source is not a directory\n");
4444 lo
.source
= strdup("/");
4446 fuse_log(FUSE_LOG_ERR
, "failed to strdup source\n");
4453 parse_xattrmap(&lo
);
4456 if (!lo
.timeout_set
) {
4467 lo
.timeout
= 86400.0;
4470 } else if (lo
.timeout
< 0) {
4471 fuse_log(FUSE_LOG_ERR
, "timeout is negative (%lf)\n", lo
.timeout
);
4475 if (lo
.user_posix_acl
== 1 && !lo
.xattr
) {
4476 fuse_log(FUSE_LOG_ERR
, "Can't enable posix ACLs. xattrs are disabled."
4481 lo
.use_statx
= true;
4483 se
= fuse_session_new(&args
, &lo_oper
, sizeof(lo_oper
), &lo
);
4488 if (fuse_set_signal_handlers(se
) != 0) {
4492 if (fuse_session_mount(se
) != 0) {
4496 fuse_daemonize(opts
.foreground
);
4498 setup_nofile_rlimit(opts
.rlimit_nofile
);
4500 /* Must be before sandbox since it wants /proc */
4503 setup_sandbox(&lo
, se
, opts
.syslog
);
4505 setup_root(&lo
, &lo
.root
);
4506 /* Block until ctrl+c or fusermount -u */
4507 ret
= virtio_loop(se
);
4509 fuse_session_unmount(se
);
4512 fuse_remove_signal_handlers(se
);
4514 fuse_session_destroy(se
);
4516 fuse_opt_free_args(&args
);
4518 fuse_lo_data_cleanup(&lo
);