2 * FUSE: Filesystem in Userspace
3 * Copyright (C) 2001-2007 Miklos Szeredi <miklos@szeredi.hu>
5 * This program can be distributed under the terms of the GNU GPLv2.
6 * See the file COPYING.
11 * This file system mirrors the existing file system hierarchy of the
12 * system, starting at the root file system. This is implemented by
13 * just "passing through" all requests to the corresponding user-space
14 * libc functions. In contrast to passthrough.c and passthrough_fh.c,
15 * this implementation uses the low-level API. Its performance should
16 * be the least bad among the three, but many operations are not
17 * implemented. In particular, it is not possible to remove files (or
18 * directories) because the code necessary to defer actual removal
19 * until the file is not opened anymore would make the example much
22 * When writeback caching is enabled (-o writeback mount option), it
23 * is only possible to write to files for which the mounting user has
24 * read permissions. This is because the writeback cache requires the
25 * kernel to be able to issue read requests for all files (which the
26 * passthrough filesystem cannot satisfy if it can't read the file in
27 * the underlying filesystem).
31 * gcc -Wall passthrough_ll.c `pkg-config fuse3 --cflags --libs` -o
35 * \include passthrough_ll.c
38 #include "qemu/osdep.h"
39 #include "qemu/timer.h"
40 #include "fuse_virtio.h"
42 #include "fuse_lowlevel.h"
43 #include "standard-headers/linux/fuse.h"
48 #include <sys/mount.h>
49 #include <sys/prctl.h>
50 #include <sys/resource.h>
51 #include <sys/syscall.h>
53 #include <sys/xattr.h>
56 #include "qemu/cutils.h"
57 #include "passthrough_helpers.h"
58 #include "passthrough_seccomp.h"
60 /* Keep track of inode posix locks for each owner. */
61 struct lo_inode_plock
{
63 int fd
; /* fd for OFD locks */
68 struct lo_inode
*inode
;
76 /* Maps FUSE fh or ino values to internal objects */
78 struct lo_map_elem
*elems
;
93 * Atomic reference count for this object. The nlookup field holds a
94 * reference and release it when nlookup reaches 0.
101 * This counter keeps the inode alive during the FUSE session.
102 * Incremented when the FUSE inode number is sent in a reply
103 * (FUSE_LOOKUP, FUSE_READDIRPLUS, etc). Decremented when an inode is
104 * released by a FUSE_FORGET request.
106 * Note that this value is untrusted because the client can manipulate
107 * it arbitrarily using FUSE_FORGET requests.
109 * Protected by lo->mutex.
114 pthread_mutex_t plock_mutex
;
115 GHashTable
*posix_locks
; /* protected by lo_inode->plock_mutex */
136 typedef struct xattr_map_entry
{
143 pthread_mutex_t mutex
;
157 int readdirplus_clear
;
159 int announce_submounts
;
161 struct lo_inode root
;
162 GHashTable
*inodes
; /* protected by lo->mutex */
163 struct lo_map ino_map
; /* protected by lo->mutex */
164 struct lo_map dirp_map
; /* protected by lo->mutex */
165 struct lo_map fd_map
; /* protected by lo->mutex */
166 XattrMapEntry
*xattr_map_list
;
167 size_t xattr_map_nentries
;
169 /* An O_PATH file descriptor to /proc/self/fd/ */
173 static const struct fuse_opt lo_opts
[] = {
174 { "sandbox=namespace",
175 offsetof(struct lo_data
, sandbox
),
178 offsetof(struct lo_data
, sandbox
),
180 { "writeback", offsetof(struct lo_data
, writeback
), 1 },
181 { "no_writeback", offsetof(struct lo_data
, writeback
), 0 },
182 { "source=%s", offsetof(struct lo_data
, source
), 0 },
183 { "flock", offsetof(struct lo_data
, flock
), 1 },
184 { "no_flock", offsetof(struct lo_data
, flock
), 0 },
185 { "posix_lock", offsetof(struct lo_data
, posix_lock
), 1 },
186 { "no_posix_lock", offsetof(struct lo_data
, posix_lock
), 0 },
187 { "xattr", offsetof(struct lo_data
, xattr
), 1 },
188 { "no_xattr", offsetof(struct lo_data
, xattr
), 0 },
189 { "xattrmap=%s", offsetof(struct lo_data
, xattrmap
), 0 },
190 { "modcaps=%s", offsetof(struct lo_data
, modcaps
), 0 },
191 { "timeout=%lf", offsetof(struct lo_data
, timeout
), 0 },
192 { "timeout=", offsetof(struct lo_data
, timeout_set
), 1 },
193 { "cache=none", offsetof(struct lo_data
, cache
), CACHE_NONE
},
194 { "cache=auto", offsetof(struct lo_data
, cache
), CACHE_AUTO
},
195 { "cache=always", offsetof(struct lo_data
, cache
), CACHE_ALWAYS
},
196 { "readdirplus", offsetof(struct lo_data
, readdirplus_set
), 1 },
197 { "no_readdirplus", offsetof(struct lo_data
, readdirplus_clear
), 1 },
198 { "allow_direct_io", offsetof(struct lo_data
, allow_direct_io
), 1 },
199 { "no_allow_direct_io", offsetof(struct lo_data
, allow_direct_io
), 0 },
200 { "announce_submounts", offsetof(struct lo_data
, announce_submounts
), 1 },
203 static bool use_syslog
= false;
204 static int current_log_level
;
205 static void unref_inode_lolocked(struct lo_data
*lo
, struct lo_inode
*inode
,
209 pthread_mutex_t mutex
;
212 /* That we loaded cap-ng in the current thread from the saved */
213 static __thread
bool cap_loaded
= 0;
215 static struct lo_inode
*lo_find(struct lo_data
*lo
, struct stat
*st
,
218 static int is_dot_or_dotdot(const char *name
)
220 return name
[0] == '.' &&
221 (name
[1] == '\0' || (name
[1] == '.' && name
[2] == '\0'));
224 /* Is `path` a single path component that is not "." or ".."? */
225 static int is_safe_path_component(const char *path
)
227 if (strchr(path
, '/')) {
231 return !is_dot_or_dotdot(path
);
234 static struct lo_data
*lo_data(fuse_req_t req
)
236 return (struct lo_data
*)fuse_req_userdata(req
);
240 * Load capng's state from our saved state if the current thread
241 * hadn't previously been loaded.
242 * returns 0 on success
244 static int load_capng(void)
247 pthread_mutex_lock(&cap
.mutex
);
248 capng_restore_state(&cap
.saved
);
250 * restore_state free's the saved copy
253 cap
.saved
= capng_save_state();
255 pthread_mutex_unlock(&cap
.mutex
);
256 fuse_log(FUSE_LOG_ERR
, "capng_save_state (thread)\n");
259 pthread_mutex_unlock(&cap
.mutex
);
262 * We want to use the loaded state for our pid,
265 capng_setpid(syscall(SYS_gettid
));
272 * Helpers for dropping and regaining effective capabilities. Returns 0
273 * on success, error otherwise
275 static int drop_effective_cap(const char *cap_name
, bool *cap_dropped
)
279 cap
= capng_name_to_capability(cap_name
);
282 fuse_log(FUSE_LOG_ERR
, "capng_name_to_capability(%s) failed:%s\n",
283 cap_name
, strerror(errno
));
289 fuse_log(FUSE_LOG_ERR
, "load_capng() failed\n");
293 /* We dont have this capability in effective set already. */
294 if (!capng_have_capability(CAPNG_EFFECTIVE
, cap
)) {
299 if (capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, cap
)) {
301 fuse_log(FUSE_LOG_ERR
, "capng_update(DROP,) failed\n");
305 if (capng_apply(CAPNG_SELECT_CAPS
)) {
307 fuse_log(FUSE_LOG_ERR
, "drop:capng_apply() failed\n");
320 static int gain_effective_cap(const char *cap_name
)
325 cap
= capng_name_to_capability(cap_name
);
328 fuse_log(FUSE_LOG_ERR
, "capng_name_to_capability(%s) failed:%s\n",
329 cap_name
, strerror(errno
));
335 fuse_log(FUSE_LOG_ERR
, "load_capng() failed\n");
339 if (capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, cap
)) {
341 fuse_log(FUSE_LOG_ERR
, "capng_update(ADD,) failed\n");
345 if (capng_apply(CAPNG_SELECT_CAPS
)) {
347 fuse_log(FUSE_LOG_ERR
, "gain:capng_apply() failed\n");
356 static void lo_map_init(struct lo_map
*map
)
363 static void lo_map_destroy(struct lo_map
*map
)
368 static int lo_map_grow(struct lo_map
*map
, size_t new_nelems
)
370 struct lo_map_elem
*new_elems
;
373 if (new_nelems
<= map
->nelems
) {
377 new_elems
= realloc(map
->elems
, sizeof(map
->elems
[0]) * new_nelems
);
382 for (i
= map
->nelems
; i
< new_nelems
; i
++) {
383 new_elems
[i
].freelist
= i
+ 1;
384 new_elems
[i
].in_use
= false;
386 new_elems
[new_nelems
- 1].freelist
= -1;
388 map
->elems
= new_elems
;
389 map
->freelist
= map
->nelems
;
390 map
->nelems
= new_nelems
;
394 static struct lo_map_elem
*lo_map_alloc_elem(struct lo_map
*map
)
396 struct lo_map_elem
*elem
;
398 if (map
->freelist
== -1 && !lo_map_grow(map
, map
->nelems
+ 256)) {
402 elem
= &map
->elems
[map
->freelist
];
403 map
->freelist
= elem
->freelist
;
410 static struct lo_map_elem
*lo_map_reserve(struct lo_map
*map
, size_t key
)
414 if (!lo_map_grow(map
, key
+ 1)) {
418 for (prev
= &map
->freelist
; *prev
!= -1;
419 prev
= &map
->elems
[*prev
].freelist
) {
421 struct lo_map_elem
*elem
= &map
->elems
[key
];
423 *prev
= elem
->freelist
;
431 static struct lo_map_elem
*lo_map_get(struct lo_map
*map
, size_t key
)
433 if (key
>= map
->nelems
) {
436 if (!map
->elems
[key
].in_use
) {
439 return &map
->elems
[key
];
442 static void lo_map_remove(struct lo_map
*map
, size_t key
)
444 struct lo_map_elem
*elem
;
446 if (key
>= map
->nelems
) {
450 elem
= &map
->elems
[key
];
455 elem
->in_use
= false;
457 elem
->freelist
= map
->freelist
;
461 /* Assumes lo->mutex is held */
462 static ssize_t
lo_add_fd_mapping(struct lo_data
*lo
, int fd
)
464 struct lo_map_elem
*elem
;
466 elem
= lo_map_alloc_elem(&lo
->fd_map
);
472 return elem
- lo
->fd_map
.elems
;
475 /* Assumes lo->mutex is held */
476 static ssize_t
lo_add_dirp_mapping(fuse_req_t req
, struct lo_dirp
*dirp
)
478 struct lo_map_elem
*elem
;
480 elem
= lo_map_alloc_elem(&lo_data(req
)->dirp_map
);
486 return elem
- lo_data(req
)->dirp_map
.elems
;
489 /* Assumes lo->mutex is held */
490 static ssize_t
lo_add_inode_mapping(fuse_req_t req
, struct lo_inode
*inode
)
492 struct lo_map_elem
*elem
;
494 elem
= lo_map_alloc_elem(&lo_data(req
)->ino_map
);
500 return elem
- lo_data(req
)->ino_map
.elems
;
503 static void lo_inode_put(struct lo_data
*lo
, struct lo_inode
**inodep
)
505 struct lo_inode
*inode
= *inodep
;
513 if (g_atomic_int_dec_and_test(&inode
->refcount
)) {
519 /* Caller must release refcount using lo_inode_put() */
520 static struct lo_inode
*lo_inode(fuse_req_t req
, fuse_ino_t ino
)
522 struct lo_data
*lo
= lo_data(req
);
523 struct lo_map_elem
*elem
;
525 pthread_mutex_lock(&lo
->mutex
);
526 elem
= lo_map_get(&lo
->ino_map
, ino
);
528 g_atomic_int_inc(&elem
->inode
->refcount
);
530 pthread_mutex_unlock(&lo
->mutex
);
540 * TODO Remove this helper and force callers to hold an inode refcount until
541 * they are done with the fd. This will be done in a later patch to make
544 static int lo_fd(fuse_req_t req
, fuse_ino_t ino
)
546 struct lo_inode
*inode
= lo_inode(req
, ino
);
554 lo_inode_put(lo_data(req
), &inode
);
558 static void lo_init(void *userdata
, struct fuse_conn_info
*conn
)
560 struct lo_data
*lo
= (struct lo_data
*)userdata
;
562 if (conn
->capable
& FUSE_CAP_EXPORT_SUPPORT
) {
563 conn
->want
|= FUSE_CAP_EXPORT_SUPPORT
;
566 if (lo
->writeback
&& conn
->capable
& FUSE_CAP_WRITEBACK_CACHE
) {
567 fuse_log(FUSE_LOG_DEBUG
, "lo_init: activating writeback\n");
568 conn
->want
|= FUSE_CAP_WRITEBACK_CACHE
;
570 if (conn
->capable
& FUSE_CAP_FLOCK_LOCKS
) {
572 fuse_log(FUSE_LOG_DEBUG
, "lo_init: activating flock locks\n");
573 conn
->want
|= FUSE_CAP_FLOCK_LOCKS
;
575 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling flock locks\n");
576 conn
->want
&= ~FUSE_CAP_FLOCK_LOCKS
;
580 if (conn
->capable
& FUSE_CAP_POSIX_LOCKS
) {
581 if (lo
->posix_lock
) {
582 fuse_log(FUSE_LOG_DEBUG
, "lo_init: activating posix locks\n");
583 conn
->want
|= FUSE_CAP_POSIX_LOCKS
;
585 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling posix locks\n");
586 conn
->want
&= ~FUSE_CAP_POSIX_LOCKS
;
590 if ((lo
->cache
== CACHE_NONE
&& !lo
->readdirplus_set
) ||
591 lo
->readdirplus_clear
) {
592 fuse_log(FUSE_LOG_DEBUG
, "lo_init: disabling readdirplus\n");
593 conn
->want
&= ~FUSE_CAP_READDIRPLUS
;
596 if (!(conn
->capable
& FUSE_CAP_SUBMOUNTS
) && lo
->announce_submounts
) {
597 fuse_log(FUSE_LOG_WARNING
, "lo_init: Cannot announce submounts, client "
598 "does not support it\n");
599 lo
->announce_submounts
= false;
603 static void lo_getattr(fuse_req_t req
, fuse_ino_t ino
,
604 struct fuse_file_info
*fi
)
608 struct lo_data
*lo
= lo_data(req
);
613 fstatat(lo_fd(req
, ino
), "", &buf
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
615 return (void)fuse_reply_err(req
, errno
);
618 fuse_reply_attr(req
, &buf
, lo
->timeout
);
621 static int lo_fi_fd(fuse_req_t req
, struct fuse_file_info
*fi
)
623 struct lo_data
*lo
= lo_data(req
);
624 struct lo_map_elem
*elem
;
626 pthread_mutex_lock(&lo
->mutex
);
627 elem
= lo_map_get(&lo
->fd_map
, fi
->fh
);
628 pthread_mutex_unlock(&lo
->mutex
);
637 static void lo_setattr(fuse_req_t req
, fuse_ino_t ino
, struct stat
*attr
,
638 int valid
, struct fuse_file_info
*fi
)
642 struct lo_data
*lo
= lo_data(req
);
643 struct lo_inode
*inode
;
648 inode
= lo_inode(req
, ino
);
650 fuse_reply_err(req
, EBADF
);
656 /* If fi->fh is invalid we'll report EBADF later */
658 fd
= lo_fi_fd(req
, fi
);
661 if (valid
& FUSE_SET_ATTR_MODE
) {
663 res
= fchmod(fd
, attr
->st_mode
);
665 sprintf(procname
, "%i", ifd
);
666 res
= fchmodat(lo
->proc_self_fd
, procname
, attr
->st_mode
, 0);
672 if (valid
& (FUSE_SET_ATTR_UID
| FUSE_SET_ATTR_GID
)) {
673 uid_t uid
= (valid
& FUSE_SET_ATTR_UID
) ? attr
->st_uid
: (uid_t
)-1;
674 gid_t gid
= (valid
& FUSE_SET_ATTR_GID
) ? attr
->st_gid
: (gid_t
)-1;
676 res
= fchownat(ifd
, "", uid
, gid
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
681 if (valid
& FUSE_SET_ATTR_SIZE
) {
687 sprintf(procname
, "%i", ifd
);
688 truncfd
= openat(lo
->proc_self_fd
, procname
, O_RDWR
);
694 res
= ftruncate(truncfd
, attr
->st_size
);
704 if (valid
& (FUSE_SET_ATTR_ATIME
| FUSE_SET_ATTR_MTIME
)) {
705 struct timespec tv
[2];
709 tv
[0].tv_nsec
= UTIME_OMIT
;
710 tv
[1].tv_nsec
= UTIME_OMIT
;
712 if (valid
& FUSE_SET_ATTR_ATIME_NOW
) {
713 tv
[0].tv_nsec
= UTIME_NOW
;
714 } else if (valid
& FUSE_SET_ATTR_ATIME
) {
715 tv
[0] = attr
->st_atim
;
718 if (valid
& FUSE_SET_ATTR_MTIME_NOW
) {
719 tv
[1].tv_nsec
= UTIME_NOW
;
720 } else if (valid
& FUSE_SET_ATTR_MTIME
) {
721 tv
[1] = attr
->st_mtim
;
725 res
= futimens(fd
, tv
);
727 sprintf(procname
, "%i", inode
->fd
);
728 res
= utimensat(lo
->proc_self_fd
, procname
, tv
, 0);
734 lo_inode_put(lo
, &inode
);
736 return lo_getattr(req
, ino
, fi
);
740 lo_inode_put(lo
, &inode
);
741 fuse_reply_err(req
, saverr
);
744 static struct lo_inode
*lo_find(struct lo_data
*lo
, struct stat
*st
,
748 struct lo_key key
= {
754 pthread_mutex_lock(&lo
->mutex
);
755 p
= g_hash_table_lookup(lo
->inodes
, &key
);
757 assert(p
->nlookup
> 0);
759 g_atomic_int_inc(&p
->refcount
);
761 pthread_mutex_unlock(&lo
->mutex
);
766 /* value_destroy_func for posix_locks GHashTable */
767 static void posix_locks_value_destroy(gpointer data
)
769 struct lo_inode_plock
*plock
= data
;
772 * We had used open() for locks and had only one fd. So
773 * closing this fd should release all OFD locks.
779 static int do_statx(struct lo_data
*lo
, int dirfd
, const char *pathname
,
780 struct stat
*statbuf
, int flags
, uint64_t *mnt_id
)
784 #if defined(CONFIG_STATX) && defined(STATX_MNT_ID)
786 struct statx statxbuf
;
788 res
= statx(dirfd
, pathname
, flags
, STATX_BASIC_STATS
| STATX_MNT_ID
,
791 memset(statbuf
, 0, sizeof(*statbuf
));
792 statbuf
->st_dev
= makedev(statxbuf
.stx_dev_major
,
793 statxbuf
.stx_dev_minor
);
794 statbuf
->st_ino
= statxbuf
.stx_ino
;
795 statbuf
->st_mode
= statxbuf
.stx_mode
;
796 statbuf
->st_nlink
= statxbuf
.stx_nlink
;
797 statbuf
->st_uid
= statxbuf
.stx_uid
;
798 statbuf
->st_gid
= statxbuf
.stx_gid
;
799 statbuf
->st_rdev
= makedev(statxbuf
.stx_rdev_major
,
800 statxbuf
.stx_rdev_minor
);
801 statbuf
->st_size
= statxbuf
.stx_size
;
802 statbuf
->st_blksize
= statxbuf
.stx_blksize
;
803 statbuf
->st_blocks
= statxbuf
.stx_blocks
;
804 statbuf
->st_atim
.tv_sec
= statxbuf
.stx_atime
.tv_sec
;
805 statbuf
->st_atim
.tv_nsec
= statxbuf
.stx_atime
.tv_nsec
;
806 statbuf
->st_mtim
.tv_sec
= statxbuf
.stx_mtime
.tv_sec
;
807 statbuf
->st_mtim
.tv_nsec
= statxbuf
.stx_mtime
.tv_nsec
;
808 statbuf
->st_ctim
.tv_sec
= statxbuf
.stx_ctime
.tv_sec
;
809 statbuf
->st_ctim
.tv_nsec
= statxbuf
.stx_ctime
.tv_nsec
;
811 if (statxbuf
.stx_mask
& STATX_MNT_ID
) {
812 *mnt_id
= statxbuf
.stx_mnt_id
;
817 } else if (errno
!= ENOSYS
) {
820 lo
->use_statx
= false;
824 res
= fstatat(dirfd
, pathname
, statbuf
, flags
);
834 * Increments nlookup on the inode on success. unref_inode_lolocked() must be
835 * called eventually to decrement nlookup again. If inodep is non-NULL, the
836 * inode pointer is stored and the caller must call lo_inode_put().
838 static int lo_do_lookup(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
839 struct fuse_entry_param
*e
,
840 struct lo_inode
**inodep
)
846 struct lo_data
*lo
= lo_data(req
);
847 struct lo_inode
*inode
= NULL
;
848 struct lo_inode
*dir
= lo_inode(req
, parent
);
855 * name_to_handle_at() and open_by_handle_at() can reach here with fuse
856 * mount point in guest, but we don't have its inode info in the
863 memset(e
, 0, sizeof(*e
));
864 e
->attr_timeout
= lo
->timeout
;
865 e
->entry_timeout
= lo
->timeout
;
867 /* Do not allow escaping root directory */
868 if (dir
== &lo
->root
&& strcmp(name
, "..") == 0) {
872 newfd
= openat(dir
->fd
, name
, O_PATH
| O_NOFOLLOW
);
877 res
= do_statx(lo
, newfd
, "", &e
->attr
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
,
883 if (S_ISDIR(e
->attr
.st_mode
) && lo
->announce_submounts
&&
884 (e
->attr
.st_dev
!= dir
->key
.dev
|| mnt_id
!= dir
->key
.mnt_id
)) {
885 e
->attr_flags
|= FUSE_ATTR_SUBMOUNT
;
888 inode
= lo_find(lo
, &e
->attr
, mnt_id
);
892 inode
= calloc(1, sizeof(struct lo_inode
));
897 /* cache only filetype */
898 inode
->filetype
= (e
->attr
.st_mode
& S_IFMT
);
901 * One for the caller and one for nlookup (released in
902 * unref_inode_lolocked())
904 g_atomic_int_set(&inode
->refcount
, 2);
908 inode
->key
.ino
= e
->attr
.st_ino
;
909 inode
->key
.dev
= e
->attr
.st_dev
;
910 inode
->key
.mnt_id
= mnt_id
;
911 if (lo
->posix_lock
) {
912 pthread_mutex_init(&inode
->plock_mutex
, NULL
);
913 inode
->posix_locks
= g_hash_table_new_full(
914 g_direct_hash
, g_direct_equal
, NULL
, posix_locks_value_destroy
);
916 pthread_mutex_lock(&lo
->mutex
);
917 inode
->fuse_ino
= lo_add_inode_mapping(req
, inode
);
918 g_hash_table_insert(lo
->inodes
, &inode
->key
, inode
);
919 pthread_mutex_unlock(&lo
->mutex
);
921 e
->ino
= inode
->fuse_ino
;
923 /* Transfer ownership of inode pointer to caller or drop it */
927 lo_inode_put(lo
, &inode
);
930 lo_inode_put(lo
, &dir
);
932 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
933 name
, (unsigned long long)e
->ino
);
942 lo_inode_put(lo
, &inode
);
943 lo_inode_put(lo
, &dir
);
947 static void lo_lookup(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
949 struct fuse_entry_param e
;
952 fuse_log(FUSE_LOG_DEBUG
, "lo_lookup(parent=%" PRIu64
", name=%s)\n", parent
,
956 * Don't use is_safe_path_component(), allow "." and ".." for NFS export
959 if (strchr(name
, '/')) {
960 fuse_reply_err(req
, EINVAL
);
964 err
= lo_do_lookup(req
, parent
, name
, &e
, NULL
);
966 fuse_reply_err(req
, err
);
968 fuse_reply_entry(req
, &e
);
973 * On some archs, setres*id is limited to 2^16 but they
974 * provide setres*id32 variants that allow 2^32.
975 * Others just let setres*id do 2^32 anyway.
977 #ifdef SYS_setresgid32
978 #define OURSYS_setresgid SYS_setresgid32
980 #define OURSYS_setresgid SYS_setresgid
983 #ifdef SYS_setresuid32
984 #define OURSYS_setresuid SYS_setresuid32
986 #define OURSYS_setresuid SYS_setresuid
990 * Change to uid/gid of caller so that file is created with
991 * ownership of caller.
992 * TODO: What about selinux context?
994 static int lo_change_cred(fuse_req_t req
, struct lo_cred
*old
)
998 old
->euid
= geteuid();
999 old
->egid
= getegid();
1001 res
= syscall(OURSYS_setresgid
, -1, fuse_req_ctx(req
)->gid
, -1);
1006 res
= syscall(OURSYS_setresuid
, -1, fuse_req_ctx(req
)->uid
, -1);
1008 int errno_save
= errno
;
1010 syscall(OURSYS_setresgid
, -1, old
->egid
, -1);
1017 /* Regain Privileges */
1018 static void lo_restore_cred(struct lo_cred
*old
)
1022 res
= syscall(OURSYS_setresuid
, -1, old
->euid
, -1);
1024 fuse_log(FUSE_LOG_ERR
, "seteuid(%u): %m\n", old
->euid
);
1028 res
= syscall(OURSYS_setresgid
, -1, old
->egid
, -1);
1030 fuse_log(FUSE_LOG_ERR
, "setegid(%u): %m\n", old
->egid
);
1035 static void lo_mknod_symlink(fuse_req_t req
, fuse_ino_t parent
,
1036 const char *name
, mode_t mode
, dev_t rdev
,
1041 struct lo_data
*lo
= lo_data(req
);
1042 struct lo_inode
*dir
;
1043 struct fuse_entry_param e
;
1044 struct lo_cred old
= {};
1046 if (!is_safe_path_component(name
)) {
1047 fuse_reply_err(req
, EINVAL
);
1051 dir
= lo_inode(req
, parent
);
1053 fuse_reply_err(req
, EBADF
);
1057 saverr
= lo_change_cred(req
, &old
);
1062 res
= mknod_wrapper(dir
->fd
, name
, link
, mode
, rdev
);
1066 lo_restore_cred(&old
);
1072 saverr
= lo_do_lookup(req
, parent
, name
, &e
, NULL
);
1077 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
1078 name
, (unsigned long long)e
.ino
);
1080 fuse_reply_entry(req
, &e
);
1081 lo_inode_put(lo
, &dir
);
1085 lo_inode_put(lo
, &dir
);
1086 fuse_reply_err(req
, saverr
);
1089 static void lo_mknod(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1090 mode_t mode
, dev_t rdev
)
1092 lo_mknod_symlink(req
, parent
, name
, mode
, rdev
, NULL
);
1095 static void lo_mkdir(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1098 lo_mknod_symlink(req
, parent
, name
, S_IFDIR
| mode
, 0, NULL
);
1101 static void lo_symlink(fuse_req_t req
, const char *link
, fuse_ino_t parent
,
1104 lo_mknod_symlink(req
, parent
, name
, S_IFLNK
, 0, link
);
1107 static void lo_link(fuse_req_t req
, fuse_ino_t ino
, fuse_ino_t parent
,
1111 struct lo_data
*lo
= lo_data(req
);
1112 struct lo_inode
*parent_inode
;
1113 struct lo_inode
*inode
;
1114 struct fuse_entry_param e
;
1118 if (!is_safe_path_component(name
)) {
1119 fuse_reply_err(req
, EINVAL
);
1123 parent_inode
= lo_inode(req
, parent
);
1124 inode
= lo_inode(req
, ino
);
1125 if (!parent_inode
|| !inode
) {
1130 memset(&e
, 0, sizeof(struct fuse_entry_param
));
1131 e
.attr_timeout
= lo
->timeout
;
1132 e
.entry_timeout
= lo
->timeout
;
1134 sprintf(procname
, "%i", inode
->fd
);
1135 res
= linkat(lo
->proc_self_fd
, procname
, parent_inode
->fd
, name
,
1141 res
= fstatat(inode
->fd
, "", &e
.attr
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
1146 pthread_mutex_lock(&lo
->mutex
);
1148 pthread_mutex_unlock(&lo
->mutex
);
1149 e
.ino
= inode
->fuse_ino
;
1151 fuse_log(FUSE_LOG_DEBUG
, " %lli/%s -> %lli\n", (unsigned long long)parent
,
1152 name
, (unsigned long long)e
.ino
);
1154 fuse_reply_entry(req
, &e
);
1155 lo_inode_put(lo
, &parent_inode
);
1156 lo_inode_put(lo
, &inode
);
1161 lo_inode_put(lo
, &parent_inode
);
1162 lo_inode_put(lo
, &inode
);
1163 fuse_reply_err(req
, saverr
);
1166 /* Increments nlookup and caller must release refcount using lo_inode_put() */
1167 static struct lo_inode
*lookup_name(fuse_req_t req
, fuse_ino_t parent
,
1173 struct lo_data
*lo
= lo_data(req
);
1174 struct lo_inode
*dir
= lo_inode(req
, parent
);
1180 res
= do_statx(lo
, dir
->fd
, name
, &attr
,
1181 AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
, &mnt_id
);
1182 lo_inode_put(lo
, &dir
);
1187 return lo_find(lo
, &attr
, mnt_id
);
1190 static void lo_rmdir(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
1193 struct lo_inode
*inode
;
1194 struct lo_data
*lo
= lo_data(req
);
1196 if (!is_safe_path_component(name
)) {
1197 fuse_reply_err(req
, EINVAL
);
1201 inode
= lookup_name(req
, parent
, name
);
1203 fuse_reply_err(req
, EIO
);
1207 res
= unlinkat(lo_fd(req
, parent
), name
, AT_REMOVEDIR
);
1209 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1210 unref_inode_lolocked(lo
, inode
, 1);
1211 lo_inode_put(lo
, &inode
);
1214 static void lo_rename(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1215 fuse_ino_t newparent
, const char *newname
,
1219 struct lo_inode
*parent_inode
;
1220 struct lo_inode
*newparent_inode
;
1221 struct lo_inode
*oldinode
= NULL
;
1222 struct lo_inode
*newinode
= NULL
;
1223 struct lo_data
*lo
= lo_data(req
);
1225 if (!is_safe_path_component(name
) || !is_safe_path_component(newname
)) {
1226 fuse_reply_err(req
, EINVAL
);
1230 parent_inode
= lo_inode(req
, parent
);
1231 newparent_inode
= lo_inode(req
, newparent
);
1232 if (!parent_inode
|| !newparent_inode
) {
1233 fuse_reply_err(req
, EBADF
);
1237 oldinode
= lookup_name(req
, parent
, name
);
1238 newinode
= lookup_name(req
, newparent
, newname
);
1241 fuse_reply_err(req
, EIO
);
1246 #ifndef SYS_renameat2
1247 fuse_reply_err(req
, EINVAL
);
1249 res
= syscall(SYS_renameat2
, parent_inode
->fd
, name
,
1250 newparent_inode
->fd
, newname
, flags
);
1251 if (res
== -1 && errno
== ENOSYS
) {
1252 fuse_reply_err(req
, EINVAL
);
1254 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1260 res
= renameat(parent_inode
->fd
, name
, newparent_inode
->fd
, newname
);
1262 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1264 unref_inode_lolocked(lo
, oldinode
, 1);
1265 unref_inode_lolocked(lo
, newinode
, 1);
1266 lo_inode_put(lo
, &oldinode
);
1267 lo_inode_put(lo
, &newinode
);
1268 lo_inode_put(lo
, &parent_inode
);
1269 lo_inode_put(lo
, &newparent_inode
);
1272 static void lo_unlink(fuse_req_t req
, fuse_ino_t parent
, const char *name
)
1275 struct lo_inode
*inode
;
1276 struct lo_data
*lo
= lo_data(req
);
1278 if (!is_safe_path_component(name
)) {
1279 fuse_reply_err(req
, EINVAL
);
1283 inode
= lookup_name(req
, parent
, name
);
1285 fuse_reply_err(req
, EIO
);
1289 res
= unlinkat(lo_fd(req
, parent
), name
, 0);
1291 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1292 unref_inode_lolocked(lo
, inode
, 1);
1293 lo_inode_put(lo
, &inode
);
1296 /* To be called with lo->mutex held */
1297 static void unref_inode(struct lo_data
*lo
, struct lo_inode
*inode
, uint64_t n
)
1303 assert(inode
->nlookup
>= n
);
1304 inode
->nlookup
-= n
;
1305 if (!inode
->nlookup
) {
1306 lo_map_remove(&lo
->ino_map
, inode
->fuse_ino
);
1307 g_hash_table_remove(lo
->inodes
, &inode
->key
);
1308 if (lo
->posix_lock
) {
1309 if (g_hash_table_size(inode
->posix_locks
)) {
1310 fuse_log(FUSE_LOG_WARNING
, "Hash table is not empty\n");
1312 g_hash_table_destroy(inode
->posix_locks
);
1313 pthread_mutex_destroy(&inode
->plock_mutex
);
1315 /* Drop our refcount from lo_do_lookup() */
1316 lo_inode_put(lo
, &inode
);
1320 static void unref_inode_lolocked(struct lo_data
*lo
, struct lo_inode
*inode
,
1327 pthread_mutex_lock(&lo
->mutex
);
1328 unref_inode(lo
, inode
, n
);
1329 pthread_mutex_unlock(&lo
->mutex
);
1332 static void lo_forget_one(fuse_req_t req
, fuse_ino_t ino
, uint64_t nlookup
)
1334 struct lo_data
*lo
= lo_data(req
);
1335 struct lo_inode
*inode
;
1337 inode
= lo_inode(req
, ino
);
1342 fuse_log(FUSE_LOG_DEBUG
, " forget %lli %lli -%lli\n",
1343 (unsigned long long)ino
, (unsigned long long)inode
->nlookup
,
1344 (unsigned long long)nlookup
);
1346 unref_inode_lolocked(lo
, inode
, nlookup
);
1347 lo_inode_put(lo
, &inode
);
1350 static void lo_forget(fuse_req_t req
, fuse_ino_t ino
, uint64_t nlookup
)
1352 lo_forget_one(req
, ino
, nlookup
);
1353 fuse_reply_none(req
);
1356 static void lo_forget_multi(fuse_req_t req
, size_t count
,
1357 struct fuse_forget_data
*forgets
)
1361 for (i
= 0; i
< count
; i
++) {
1362 lo_forget_one(req
, forgets
[i
].ino
, forgets
[i
].nlookup
);
1364 fuse_reply_none(req
);
1367 static void lo_readlink(fuse_req_t req
, fuse_ino_t ino
)
1369 char buf
[PATH_MAX
+ 1];
1372 res
= readlinkat(lo_fd(req
, ino
), "", buf
, sizeof(buf
));
1374 return (void)fuse_reply_err(req
, errno
);
1377 if (res
== sizeof(buf
)) {
1378 return (void)fuse_reply_err(req
, ENAMETOOLONG
);
1383 fuse_reply_readlink(req
, buf
);
1389 struct dirent
*entry
;
1393 static void lo_dirp_put(struct lo_dirp
**dp
)
1395 struct lo_dirp
*d
= *dp
;
1402 if (g_atomic_int_dec_and_test(&d
->refcount
)) {
1408 /* Call lo_dirp_put() on the return value when no longer needed */
1409 static struct lo_dirp
*lo_dirp(fuse_req_t req
, struct fuse_file_info
*fi
)
1411 struct lo_data
*lo
= lo_data(req
);
1412 struct lo_map_elem
*elem
;
1414 pthread_mutex_lock(&lo
->mutex
);
1415 elem
= lo_map_get(&lo
->dirp_map
, fi
->fh
);
1417 g_atomic_int_inc(&elem
->dirp
->refcount
);
1419 pthread_mutex_unlock(&lo
->mutex
);
1427 static void lo_opendir(fuse_req_t req
, fuse_ino_t ino
,
1428 struct fuse_file_info
*fi
)
1431 struct lo_data
*lo
= lo_data(req
);
1436 d
= calloc(1, sizeof(struct lo_dirp
));
1441 fd
= openat(lo_fd(req
, ino
), ".", O_RDONLY
);
1446 d
->dp
= fdopendir(fd
);
1447 if (d
->dp
== NULL
) {
1454 g_atomic_int_set(&d
->refcount
, 1); /* paired with lo_releasedir() */
1455 pthread_mutex_lock(&lo
->mutex
);
1456 fh
= lo_add_dirp_mapping(req
, d
);
1457 pthread_mutex_unlock(&lo
->mutex
);
1463 if (lo
->cache
== CACHE_ALWAYS
) {
1464 fi
->cache_readdir
= 1;
1466 fuse_reply_open(req
, fi
);
1475 } else if (fd
!= -1) {
1480 fuse_reply_err(req
, error
);
1483 static void lo_do_readdir(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
1484 off_t offset
, struct fuse_file_info
*fi
, int plus
)
1486 struct lo_data
*lo
= lo_data(req
);
1487 struct lo_dirp
*d
= NULL
;
1488 struct lo_inode
*dinode
;
1494 dinode
= lo_inode(req
, ino
);
1499 d
= lo_dirp(req
, fi
);
1505 buf
= calloc(1, size
);
1511 if (offset
!= d
->offset
) {
1512 seekdir(d
->dp
, offset
);
1523 d
->entry
= readdir(d
->dp
);
1525 if (errno
) { /* Error */
1528 } else { /* End of stream */
1533 nextoff
= d
->entry
->d_off
;
1534 name
= d
->entry
->d_name
;
1536 fuse_ino_t entry_ino
= 0;
1537 struct fuse_entry_param e
= (struct fuse_entry_param
){
1538 .attr
.st_ino
= d
->entry
->d_ino
,
1539 .attr
.st_mode
= d
->entry
->d_type
<< 12,
1542 /* Hide root's parent directory */
1543 if (dinode
== &lo
->root
&& strcmp(name
, "..") == 0) {
1544 e
.attr
.st_ino
= lo
->root
.key
.ino
;
1545 e
.attr
.st_mode
= DT_DIR
<< 12;
1549 if (!is_dot_or_dotdot(name
)) {
1550 err
= lo_do_lookup(req
, ino
, name
, &e
, NULL
);
1557 entsize
= fuse_add_direntry_plus(req
, p
, rem
, name
, &e
, nextoff
);
1559 entsize
= fuse_add_direntry(req
, p
, rem
, name
, &e
.attr
, nextoff
);
1561 if (entsize
> rem
) {
1562 if (entry_ino
!= 0) {
1563 lo_forget_one(req
, entry_ino
, 1);
1572 d
->offset
= nextoff
;
1578 lo_inode_put(lo
, &dinode
);
1581 * If there's an error, we can only signal it if we haven't stored
1582 * any entries yet - otherwise we'd end up with wrong lookup
1583 * counts for the entries that are already in the buffer. So we
1584 * return what we've collected until that point.
1586 if (err
&& rem
== size
) {
1587 fuse_reply_err(req
, err
);
1589 fuse_reply_buf(req
, buf
, size
- rem
);
1594 static void lo_readdir(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
1595 off_t offset
, struct fuse_file_info
*fi
)
1597 lo_do_readdir(req
, ino
, size
, offset
, fi
, 0);
1600 static void lo_readdirplus(fuse_req_t req
, fuse_ino_t ino
, size_t size
,
1601 off_t offset
, struct fuse_file_info
*fi
)
1603 lo_do_readdir(req
, ino
, size
, offset
, fi
, 1);
1606 static void lo_releasedir(fuse_req_t req
, fuse_ino_t ino
,
1607 struct fuse_file_info
*fi
)
1609 struct lo_data
*lo
= lo_data(req
);
1610 struct lo_map_elem
*elem
;
1615 pthread_mutex_lock(&lo
->mutex
);
1616 elem
= lo_map_get(&lo
->dirp_map
, fi
->fh
);
1618 pthread_mutex_unlock(&lo
->mutex
);
1619 fuse_reply_err(req
, EBADF
);
1624 lo_map_remove(&lo
->dirp_map
, fi
->fh
);
1625 pthread_mutex_unlock(&lo
->mutex
);
1627 lo_dirp_put(&d
); /* paired with lo_opendir() */
1629 fuse_reply_err(req
, 0);
1632 static void update_open_flags(int writeback
, int allow_direct_io
,
1633 struct fuse_file_info
*fi
)
1636 * With writeback cache, kernel may send read requests even
1637 * when userspace opened write-only
1639 if (writeback
&& (fi
->flags
& O_ACCMODE
) == O_WRONLY
) {
1640 fi
->flags
&= ~O_ACCMODE
;
1641 fi
->flags
|= O_RDWR
;
1645 * With writeback cache, O_APPEND is handled by the kernel.
1646 * This breaks atomicity (since the file may change in the
1647 * underlying filesystem, so that the kernel's idea of the
1648 * end of the file isn't accurate anymore). In this example,
1649 * we just accept that. A more rigorous filesystem may want
1650 * to return an error here
1652 if (writeback
&& (fi
->flags
& O_APPEND
)) {
1653 fi
->flags
&= ~O_APPEND
;
1657 * O_DIRECT in guest should not necessarily mean bypassing page
1658 * cache on host as well. Therefore, we discard it by default
1659 * ('-o no_allow_direct_io'). If somebody needs that behavior,
1660 * the '-o allow_direct_io' option should be set.
1662 if (!allow_direct_io
) {
1663 fi
->flags
&= ~O_DIRECT
;
1667 static int lo_do_open(struct lo_data
*lo
, struct lo_inode
*inode
,
1668 struct fuse_file_info
*fi
)
1674 update_open_flags(lo
->writeback
, lo
->allow_direct_io
, fi
);
1676 sprintf(buf
, "%i", inode
->fd
);
1677 fd
= openat(lo
->proc_self_fd
, buf
, fi
->flags
& ~O_NOFOLLOW
);
1682 pthread_mutex_lock(&lo
->mutex
);
1683 fh
= lo_add_fd_mapping(lo
, fd
);
1684 pthread_mutex_unlock(&lo
->mutex
);
1691 if (lo
->cache
== CACHE_NONE
) {
1693 } else if (lo
->cache
== CACHE_ALWAYS
) {
1699 static void lo_create(fuse_req_t req
, fuse_ino_t parent
, const char *name
,
1700 mode_t mode
, struct fuse_file_info
*fi
)
1703 struct lo_data
*lo
= lo_data(req
);
1704 struct lo_inode
*parent_inode
;
1705 struct fuse_entry_param e
;
1707 struct lo_cred old
= {};
1709 fuse_log(FUSE_LOG_DEBUG
, "lo_create(parent=%" PRIu64
", name=%s)\n", parent
,
1712 if (!is_safe_path_component(name
)) {
1713 fuse_reply_err(req
, EINVAL
);
1717 parent_inode
= lo_inode(req
, parent
);
1718 if (!parent_inode
) {
1719 fuse_reply_err(req
, EBADF
);
1723 err
= lo_change_cred(req
, &old
);
1728 update_open_flags(lo
->writeback
, lo
->allow_direct_io
, fi
);
1730 fd
= openat(parent_inode
->fd
, name
, (fi
->flags
| O_CREAT
) & ~O_NOFOLLOW
,
1732 err
= fd
== -1 ? errno
: 0;
1733 lo_restore_cred(&old
);
1738 pthread_mutex_lock(&lo
->mutex
);
1739 fh
= lo_add_fd_mapping(lo
, fd
);
1740 pthread_mutex_unlock(&lo
->mutex
);
1748 err
= lo_do_lookup(req
, parent
, name
, &e
, NULL
);
1750 if (lo
->cache
== CACHE_NONE
) {
1752 } else if (lo
->cache
== CACHE_ALWAYS
) {
1757 lo_inode_put(lo
, &parent_inode
);
1760 fuse_reply_err(req
, err
);
1762 fuse_reply_create(req
, &e
, fi
);
1766 /* Should be called with inode->plock_mutex held */
1767 static struct lo_inode_plock
*lookup_create_plock_ctx(struct lo_data
*lo
,
1768 struct lo_inode
*inode
,
1769 uint64_t lock_owner
,
1770 pid_t pid
, int *err
)
1772 struct lo_inode_plock
*plock
;
1777 g_hash_table_lookup(inode
->posix_locks
, GUINT_TO_POINTER(lock_owner
));
1783 plock
= malloc(sizeof(struct lo_inode_plock
));
1789 /* Open another instance of file which can be used for ofd locks. */
1790 sprintf(procname
, "%i", inode
->fd
);
1792 /* TODO: What if file is not writable? */
1793 fd
= openat(lo
->proc_self_fd
, procname
, O_RDWR
);
1800 plock
->lock_owner
= lock_owner
;
1802 g_hash_table_insert(inode
->posix_locks
, GUINT_TO_POINTER(plock
->lock_owner
),
1807 static void lo_getlk(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
1810 struct lo_data
*lo
= lo_data(req
);
1811 struct lo_inode
*inode
;
1812 struct lo_inode_plock
*plock
;
1813 int ret
, saverr
= 0;
1815 fuse_log(FUSE_LOG_DEBUG
,
1816 "lo_getlk(ino=%" PRIu64
", flags=%d)"
1817 " owner=0x%lx, l_type=%d l_start=0x%lx"
1819 ino
, fi
->flags
, fi
->lock_owner
, lock
->l_type
, lock
->l_start
,
1822 if (!lo
->posix_lock
) {
1823 fuse_reply_err(req
, ENOSYS
);
1827 inode
= lo_inode(req
, ino
);
1829 fuse_reply_err(req
, EBADF
);
1833 pthread_mutex_lock(&inode
->plock_mutex
);
1835 lookup_create_plock_ctx(lo
, inode
, fi
->lock_owner
, lock
->l_pid
, &ret
);
1841 ret
= fcntl(plock
->fd
, F_OFD_GETLK
, lock
);
1847 pthread_mutex_unlock(&inode
->plock_mutex
);
1848 lo_inode_put(lo
, &inode
);
1851 fuse_reply_err(req
, saverr
);
1853 fuse_reply_lock(req
, lock
);
1857 static void lo_setlk(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
1858 struct flock
*lock
, int sleep
)
1860 struct lo_data
*lo
= lo_data(req
);
1861 struct lo_inode
*inode
;
1862 struct lo_inode_plock
*plock
;
1863 int ret
, saverr
= 0;
1865 fuse_log(FUSE_LOG_DEBUG
,
1866 "lo_setlk(ino=%" PRIu64
", flags=%d)"
1867 " cmd=%d pid=%d owner=0x%lx sleep=%d l_whence=%d"
1868 " l_start=0x%lx l_len=0x%lx\n",
1869 ino
, fi
->flags
, lock
->l_type
, lock
->l_pid
, fi
->lock_owner
, sleep
,
1870 lock
->l_whence
, lock
->l_start
, lock
->l_len
);
1872 if (!lo
->posix_lock
) {
1873 fuse_reply_err(req
, ENOSYS
);
1878 fuse_reply_err(req
, EOPNOTSUPP
);
1882 inode
= lo_inode(req
, ino
);
1884 fuse_reply_err(req
, EBADF
);
1888 pthread_mutex_lock(&inode
->plock_mutex
);
1890 lookup_create_plock_ctx(lo
, inode
, fi
->lock_owner
, lock
->l_pid
, &ret
);
1897 /* TODO: Is it alright to modify flock? */
1899 ret
= fcntl(plock
->fd
, F_OFD_SETLK
, lock
);
1905 pthread_mutex_unlock(&inode
->plock_mutex
);
1906 lo_inode_put(lo
, &inode
);
1908 fuse_reply_err(req
, saverr
);
1911 static void lo_fsyncdir(fuse_req_t req
, fuse_ino_t ino
, int datasync
,
1912 struct fuse_file_info
*fi
)
1920 d
= lo_dirp(req
, fi
);
1922 fuse_reply_err(req
, EBADF
);
1928 res
= fdatasync(fd
);
1935 fuse_reply_err(req
, res
== -1 ? errno
: 0);
1938 static void lo_open(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
)
1940 struct lo_data
*lo
= lo_data(req
);
1941 struct lo_inode
*inode
= lo_inode(req
, ino
);
1944 fuse_log(FUSE_LOG_DEBUG
, "lo_open(ino=%" PRIu64
", flags=%d)\n", ino
,
1948 fuse_reply_err(req
, EBADF
);
1952 err
= lo_do_open(lo
, inode
, fi
);
1953 lo_inode_put(lo
, &inode
);
1955 fuse_reply_err(req
, err
);
1957 fuse_reply_open(req
, fi
);
1961 static void lo_release(fuse_req_t req
, fuse_ino_t ino
,
1962 struct fuse_file_info
*fi
)
1964 struct lo_data
*lo
= lo_data(req
);
1965 struct lo_map_elem
*elem
;
1970 pthread_mutex_lock(&lo
->mutex
);
1971 elem
= lo_map_get(&lo
->fd_map
, fi
->fh
);
1975 lo_map_remove(&lo
->fd_map
, fi
->fh
);
1977 pthread_mutex_unlock(&lo
->mutex
);
1980 fuse_reply_err(req
, 0);
1983 static void lo_flush(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
)
1987 struct lo_inode
*inode
;
1988 struct lo_data
*lo
= lo_data(req
);
1990 inode
= lo_inode(req
, ino
);
1992 fuse_reply_err(req
, EBADF
);
1996 if (!S_ISREG(inode
->filetype
)) {
1997 lo_inode_put(lo
, &inode
);
1998 fuse_reply_err(req
, EBADF
);
2002 /* An fd is going away. Cleanup associated posix locks */
2003 if (lo
->posix_lock
) {
2004 pthread_mutex_lock(&inode
->plock_mutex
);
2005 g_hash_table_remove(inode
->posix_locks
,
2006 GUINT_TO_POINTER(fi
->lock_owner
));
2007 pthread_mutex_unlock(&inode
->plock_mutex
);
2009 res
= close(dup(lo_fi_fd(req
, fi
)));
2010 lo_inode_put(lo
, &inode
);
2011 fuse_reply_err(req
, res
== -1 ? errno
: 0);
2014 static void lo_fsync(fuse_req_t req
, fuse_ino_t ino
, int datasync
,
2015 struct fuse_file_info
*fi
)
2021 fuse_log(FUSE_LOG_DEBUG
, "lo_fsync(ino=%" PRIu64
", fi=0x%p)\n", ino
,
2025 struct lo_data
*lo
= lo_data(req
);
2027 res
= asprintf(&buf
, "%i", lo_fd(req
, ino
));
2029 return (void)fuse_reply_err(req
, errno
);
2032 fd
= openat(lo
->proc_self_fd
, buf
, O_RDWR
);
2035 return (void)fuse_reply_err(req
, errno
);
2038 fd
= lo_fi_fd(req
, fi
);
2042 res
= fdatasync(fd
);
2049 fuse_reply_err(req
, res
== -1 ? errno
: 0);
2052 static void lo_read(fuse_req_t req
, fuse_ino_t ino
, size_t size
, off_t offset
,
2053 struct fuse_file_info
*fi
)
2055 struct fuse_bufvec buf
= FUSE_BUFVEC_INIT(size
);
2057 fuse_log(FUSE_LOG_DEBUG
,
2058 "lo_read(ino=%" PRIu64
", size=%zd, "
2060 ino
, size
, (unsigned long)offset
);
2062 buf
.buf
[0].flags
= FUSE_BUF_IS_FD
| FUSE_BUF_FD_SEEK
;
2063 buf
.buf
[0].fd
= lo_fi_fd(req
, fi
);
2064 buf
.buf
[0].pos
= offset
;
2066 fuse_reply_data(req
, &buf
);
2069 static void lo_write_buf(fuse_req_t req
, fuse_ino_t ino
,
2070 struct fuse_bufvec
*in_buf
, off_t off
,
2071 struct fuse_file_info
*fi
)
2075 struct fuse_bufvec out_buf
= FUSE_BUFVEC_INIT(fuse_buf_size(in_buf
));
2076 bool cap_fsetid_dropped
= false;
2078 out_buf
.buf
[0].flags
= FUSE_BUF_IS_FD
| FUSE_BUF_FD_SEEK
;
2079 out_buf
.buf
[0].fd
= lo_fi_fd(req
, fi
);
2080 out_buf
.buf
[0].pos
= off
;
2082 fuse_log(FUSE_LOG_DEBUG
,
2083 "lo_write_buf(ino=%" PRIu64
", size=%zd, off=%lu)\n", ino
,
2084 out_buf
.buf
[0].size
, (unsigned long)off
);
2087 * If kill_priv is set, drop CAP_FSETID which should lead to kernel
2088 * clearing setuid/setgid on file.
2090 if (fi
->kill_priv
) {
2091 res
= drop_effective_cap("FSETID", &cap_fsetid_dropped
);
2093 fuse_reply_err(req
, res
);
2098 res
= fuse_buf_copy(&out_buf
, in_buf
);
2100 fuse_reply_err(req
, -res
);
2102 fuse_reply_write(req
, (size_t)res
);
2105 if (cap_fsetid_dropped
) {
2106 res
= gain_effective_cap("FSETID");
2108 fuse_log(FUSE_LOG_ERR
, "Failed to gain CAP_FSETID\n");
2113 static void lo_statfs(fuse_req_t req
, fuse_ino_t ino
)
2116 struct statvfs stbuf
;
2118 res
= fstatvfs(lo_fd(req
, ino
), &stbuf
);
2120 fuse_reply_err(req
, errno
);
2122 fuse_reply_statfs(req
, &stbuf
);
2126 static void lo_fallocate(fuse_req_t req
, fuse_ino_t ino
, int mode
, off_t offset
,
2127 off_t length
, struct fuse_file_info
*fi
)
2129 int err
= EOPNOTSUPP
;
2132 #ifdef CONFIG_FALLOCATE
2133 err
= fallocate(lo_fi_fd(req
, fi
), mode
, offset
, length
);
2138 #elif defined(CONFIG_POSIX_FALLOCATE)
2140 fuse_reply_err(req
, EOPNOTSUPP
);
2144 err
= posix_fallocate(lo_fi_fd(req
, fi
), offset
, length
);
2147 fuse_reply_err(req
, err
);
2150 static void lo_flock(fuse_req_t req
, fuse_ino_t ino
, struct fuse_file_info
*fi
,
2156 res
= flock(lo_fi_fd(req
, fi
), op
);
2158 fuse_reply_err(req
, res
== -1 ? errno
: 0);
2163 * Exit; process attribute unmodified if matched.
2164 * An empty key applies to all.
2166 #define XATTR_MAP_FLAG_OK (1 << 0)
2168 * The attribute is unwanted;
2169 * EPERM on write, hidden on read.
2171 #define XATTR_MAP_FLAG_BAD (1 << 1)
2173 * For attr that start with 'key' prepend 'prepend'
2174 * 'key' may be empty to prepend for all attrs
2175 * key is defined from set/remove point of view.
2176 * Automatically reversed on read
2178 #define XATTR_MAP_FLAG_PREFIX (1 << 2)
2181 /* Apply rule to get/set/remove */
2182 #define XATTR_MAP_FLAG_CLIENT (1 << 16)
2183 /* Apply rule to list */
2184 #define XATTR_MAP_FLAG_SERVER (1 << 17)
2185 /* Apply rule to all */
2186 #define XATTR_MAP_FLAG_ALL (XATTR_MAP_FLAG_SERVER | XATTR_MAP_FLAG_CLIENT)
2188 static void add_xattrmap_entry(struct lo_data
*lo
,
2189 const XattrMapEntry
*new_entry
)
2191 XattrMapEntry
*res
= g_realloc_n(lo
->xattr_map_list
,
2192 lo
->xattr_map_nentries
+ 1,
2193 sizeof(XattrMapEntry
));
2194 res
[lo
->xattr_map_nentries
++] = *new_entry
;
2196 lo
->xattr_map_list
= res
;
2199 static void free_xattrmap(struct lo_data
*lo
)
2201 XattrMapEntry
*map
= lo
->xattr_map_list
;
2208 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
2210 g_free(map
[i
].prepend
);
2214 lo
->xattr_map_list
= NULL
;
2215 lo
->xattr_map_nentries
= -1;
2219 * Handle the 'map' type, which is sugar for a set of commands
2220 * for the common case of prefixing a subset or everything,
2221 * and allowing anything not prefixed through.
2222 * It must be the last entry in the stream, although there
2223 * can be other entries before it.
2227 * key maybe empty in which case all entries are prefixed.
2229 static void parse_xattrmap_map(struct lo_data
*lo
,
2230 const char *rule
, char sep
)
2235 XattrMapEntry tmp_entry
;
2238 fuse_log(FUSE_LOG_ERR
,
2239 "%s: Expecting '%c' after 'map' keyword, found '%c'\n",
2240 __func__
, sep
, *rule
);
2246 /* At start of 'key' field */
2247 tmp
= strchr(rule
, sep
);
2249 fuse_log(FUSE_LOG_ERR
,
2250 "%s: Missing '%c' at end of key field in map rule\n",
2255 key
= g_strndup(rule
, tmp
- rule
);
2258 /* At start of prefix field */
2259 tmp
= strchr(rule
, sep
);
2261 fuse_log(FUSE_LOG_ERR
,
2262 "%s: Missing '%c' at end of prefix field in map rule\n",
2267 prefix
= g_strndup(rule
, tmp
- rule
);
2271 * This should be the end of the string, we don't allow
2272 * any more commands after 'map'.
2275 fuse_log(FUSE_LOG_ERR
,
2276 "%s: Expecting end of command after map, found '%c'\n",
2281 /* 1st: Prefix matches/everything */
2282 tmp_entry
.flags
= XATTR_MAP_FLAG_PREFIX
| XATTR_MAP_FLAG_ALL
;
2283 tmp_entry
.key
= g_strdup(key
);
2284 tmp_entry
.prepend
= g_strdup(prefix
);
2285 add_xattrmap_entry(lo
, &tmp_entry
);
2288 /* Prefix all case */
2290 /* 2nd: Hide any non-prefixed entries on the host */
2291 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_ALL
;
2292 tmp_entry
.key
= g_strdup("");
2293 tmp_entry
.prepend
= g_strdup("");
2294 add_xattrmap_entry(lo
, &tmp_entry
);
2296 /* Prefix matching case */
2298 /* 2nd: Hide non-prefixed but matching entries on the host */
2299 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_SERVER
;
2300 tmp_entry
.key
= g_strdup(""); /* Not used */
2301 tmp_entry
.prepend
= g_strdup(key
);
2302 add_xattrmap_entry(lo
, &tmp_entry
);
2304 /* 3rd: Stop the client accessing prefixed attributes directly */
2305 tmp_entry
.flags
= XATTR_MAP_FLAG_BAD
| XATTR_MAP_FLAG_CLIENT
;
2306 tmp_entry
.key
= g_strdup(prefix
);
2307 tmp_entry
.prepend
= g_strdup(""); /* Not used */
2308 add_xattrmap_entry(lo
, &tmp_entry
);
2310 /* 4th: Everything else is OK */
2311 tmp_entry
.flags
= XATTR_MAP_FLAG_OK
| XATTR_MAP_FLAG_ALL
;
2312 tmp_entry
.key
= g_strdup("");
2313 tmp_entry
.prepend
= g_strdup("");
2314 add_xattrmap_entry(lo
, &tmp_entry
);
2321 static void parse_xattrmap(struct lo_data
*lo
)
2323 const char *map
= lo
->xattrmap
;
2326 lo
->xattr_map_nentries
= 0;
2328 XattrMapEntry tmp_entry
;
2331 if (isspace(*map
)) {
2335 /* The separator is the first non-space of the rule */
2341 tmp_entry
.flags
= 0;
2342 /* Start of 'type' */
2343 if (strstart(map
, "prefix", &map
)) {
2344 tmp_entry
.flags
|= XATTR_MAP_FLAG_PREFIX
;
2345 } else if (strstart(map
, "ok", &map
)) {
2346 tmp_entry
.flags
|= XATTR_MAP_FLAG_OK
;
2347 } else if (strstart(map
, "bad", &map
)) {
2348 tmp_entry
.flags
|= XATTR_MAP_FLAG_BAD
;
2349 } else if (strstart(map
, "map", &map
)) {
2351 * map is sugar that adds a number of rules, and must be
2354 parse_xattrmap_map(lo
, map
, sep
);
2357 fuse_log(FUSE_LOG_ERR
,
2358 "%s: Unexpected type;"
2359 "Expecting 'prefix', 'ok', 'bad' or 'map' in rule %zu\n",
2360 __func__
, lo
->xattr_map_nentries
);
2364 if (*map
++ != sep
) {
2365 fuse_log(FUSE_LOG_ERR
,
2366 "%s: Missing '%c' at end of type field of rule %zu\n",
2367 __func__
, sep
, lo
->xattr_map_nentries
);
2371 /* Start of 'scope' */
2372 if (strstart(map
, "client", &map
)) {
2373 tmp_entry
.flags
|= XATTR_MAP_FLAG_CLIENT
;
2374 } else if (strstart(map
, "server", &map
)) {
2375 tmp_entry
.flags
|= XATTR_MAP_FLAG_SERVER
;
2376 } else if (strstart(map
, "all", &map
)) {
2377 tmp_entry
.flags
|= XATTR_MAP_FLAG_ALL
;
2379 fuse_log(FUSE_LOG_ERR
,
2380 "%s: Unexpected scope;"
2381 " Expecting 'client', 'server', or 'all', in rule %zu\n",
2382 __func__
, lo
->xattr_map_nentries
);
2386 if (*map
++ != sep
) {
2387 fuse_log(FUSE_LOG_ERR
,
2388 "%s: Expecting '%c' found '%c'"
2389 " after scope in rule %zu\n",
2390 __func__
, sep
, *map
, lo
->xattr_map_nentries
);
2394 /* At start of 'key' field */
2395 tmp
= strchr(map
, sep
);
2397 fuse_log(FUSE_LOG_ERR
,
2398 "%s: Missing '%c' at end of key field of rule %zu",
2399 __func__
, sep
, lo
->xattr_map_nentries
);
2402 tmp_entry
.key
= g_strndup(map
, tmp
- map
);
2405 /* At start of 'prepend' field */
2406 tmp
= strchr(map
, sep
);
2408 fuse_log(FUSE_LOG_ERR
,
2409 "%s: Missing '%c' at end of prepend field of rule %zu",
2410 __func__
, sep
, lo
->xattr_map_nentries
);
2413 tmp_entry
.prepend
= g_strndup(map
, tmp
- map
);
2416 add_xattrmap_entry(lo
, &tmp_entry
);
2417 /* End of rule - go around again for another rule */
2420 if (!lo
->xattr_map_nentries
) {
2421 fuse_log(FUSE_LOG_ERR
, "Empty xattr map\n");
2427 * For use with getxattr/setxattr/removexattr, where the client
2428 * gives us a name and we may need to choose a different one.
2429 * Allocates a buffer for the result placing it in *out_name.
2430 * If there's no change then *out_name is not set.
2431 * Returns 0 on success
2432 * Can return -EPERM to indicate we block a given attribute
2433 * (in which case out_name is not allocated)
2434 * Can return -ENOMEM to indicate out_name couldn't be allocated.
2436 static int xattr_map_client(const struct lo_data
*lo
, const char *client_name
,
2440 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
2441 const XattrMapEntry
*cur_entry
= lo
->xattr_map_list
+ i
;
2443 if ((cur_entry
->flags
& XATTR_MAP_FLAG_CLIENT
) &&
2444 (strstart(client_name
, cur_entry
->key
, NULL
))) {
2445 if (cur_entry
->flags
& XATTR_MAP_FLAG_BAD
) {
2448 if (cur_entry
->flags
& XATTR_MAP_FLAG_OK
) {
2449 /* Unmodified name */
2452 if (cur_entry
->flags
& XATTR_MAP_FLAG_PREFIX
) {
2453 *out_name
= g_try_malloc(strlen(client_name
) +
2454 strlen(cur_entry
->prepend
) + 1);
2458 sprintf(*out_name
, "%s%s", cur_entry
->prepend
, client_name
);
2468 * For use with listxattr where the server fs gives us a name and we may need
2469 * to sanitize this for the client.
2470 * Returns a pointer to the result in *out_name
2471 * This is always the original string or the current string with some prefix
2472 * removed; no reallocation is done.
2473 * Returns 0 on success
2474 * Can return -ENODATA to indicate the name should be dropped from the list.
2476 static int xattr_map_server(const struct lo_data
*lo
, const char *server_name
,
2477 const char **out_name
)
2482 for (i
= 0; i
< lo
->xattr_map_nentries
; i
++) {
2483 const XattrMapEntry
*cur_entry
= lo
->xattr_map_list
+ i
;
2485 if ((cur_entry
->flags
& XATTR_MAP_FLAG_SERVER
) &&
2486 (strstart(server_name
, cur_entry
->prepend
, &end
))) {
2487 if (cur_entry
->flags
& XATTR_MAP_FLAG_BAD
) {
2490 if (cur_entry
->flags
& XATTR_MAP_FLAG_OK
) {
2491 *out_name
= server_name
;
2494 if (cur_entry
->flags
& XATTR_MAP_FLAG_PREFIX
) {
2505 static void lo_getxattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
,
2508 struct lo_data
*lo
= lo_data(req
);
2513 struct lo_inode
*inode
;
2521 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
2523 if (ret
== -EPERM
) {
2526 fuse_reply_err(req
, -ret
);
2534 inode
= lo_inode(req
, ino
);
2536 fuse_reply_err(req
, EBADF
);
2537 g_free(mapped_name
);
2542 if (!lo_data(req
)->xattr
) {
2546 fuse_log(FUSE_LOG_DEBUG
, "lo_getxattr(ino=%" PRIu64
", name=%s size=%zd)\n",
2550 value
= malloc(size
);
2556 sprintf(procname
, "%i", inode
->fd
);
2558 * It is not safe to open() non-regular/non-dir files in file server
2559 * unless O_PATH is used, so use that method for regular files/dir
2560 * only (as it seems giving less performance overhead).
2561 * Otherwise, call fchdir() to avoid open().
2563 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
2564 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
2568 ret
= fgetxattr(fd
, name
, value
, size
);
2570 /* fchdir should not fail here */
2571 assert(fchdir(lo
->proc_self_fd
) == 0);
2572 ret
= getxattr(procname
, name
, value
, size
);
2573 assert(fchdir(lo
->root
.fd
) == 0);
2584 fuse_reply_buf(req
, value
, ret
);
2586 fuse_reply_xattr(req
, ret
);
2595 lo_inode_put(lo
, &inode
);
2601 fuse_reply_err(req
, saverr
);
2602 g_free(mapped_name
);
2606 static void lo_listxattr(fuse_req_t req
, fuse_ino_t ino
, size_t size
)
2608 struct lo_data
*lo
= lo_data(req
);
2611 struct lo_inode
*inode
;
2616 inode
= lo_inode(req
, ino
);
2618 fuse_reply_err(req
, EBADF
);
2623 if (!lo_data(req
)->xattr
) {
2627 fuse_log(FUSE_LOG_DEBUG
, "lo_listxattr(ino=%" PRIu64
", size=%zd)\n", ino
,
2631 value
= malloc(size
);
2637 sprintf(procname
, "%i", inode
->fd
);
2638 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
2639 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
2643 ret
= flistxattr(fd
, value
, size
);
2645 /* fchdir should not fail here */
2646 assert(fchdir(lo
->proc_self_fd
) == 0);
2647 ret
= listxattr(procname
, value
, size
);
2648 assert(fchdir(lo
->root
.fd
) == 0);
2660 if (lo
->xattr_map_list
) {
2662 * Map the names back, some attributes might be dropped,
2663 * some shortened, but not increased, so we shouldn't
2666 size_t out_index
, in_index
;
2669 while (in_index
< ret
) {
2670 const char *map_out
;
2671 char *in_ptr
= value
+ in_index
;
2672 /* Length of current attribute name */
2673 size_t in_len
= strlen(value
+ in_index
) + 1;
2675 int mapret
= xattr_map_server(lo
, in_ptr
, &map_out
);
2676 if (mapret
!= -ENODATA
&& mapret
!= 0) {
2677 /* Shouldn't happen */
2682 /* Either unchanged, or truncated */
2684 if (map_out
!= in_ptr
) {
2685 /* +1 copies the NIL */
2686 out_len
= strlen(map_out
) + 1;
2692 * Move result along, may still be needed for an unchanged
2693 * entry if a previous entry was changed.
2695 memmove(value
+ out_index
, map_out
, out_len
);
2697 out_index
+= out_len
;
2706 fuse_reply_buf(req
, value
, ret
);
2709 * xattrmap only ever shortens the result,
2710 * so we don't need to do anything clever with the
2711 * allocation length here.
2713 fuse_reply_xattr(req
, ret
);
2722 lo_inode_put(lo
, &inode
);
2728 fuse_reply_err(req
, saverr
);
2732 static void lo_setxattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
,
2733 const char *value
, size_t size
, int flags
)
2738 struct lo_data
*lo
= lo_data(req
);
2739 struct lo_inode
*inode
;
2747 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
2749 fuse_reply_err(req
, -ret
);
2757 inode
= lo_inode(req
, ino
);
2759 fuse_reply_err(req
, EBADF
);
2760 g_free(mapped_name
);
2765 if (!lo_data(req
)->xattr
) {
2769 fuse_log(FUSE_LOG_DEBUG
, "lo_setxattr(ino=%" PRIu64
2770 ", name=%s value=%s size=%zd)\n", ino
, name
, value
, size
);
2772 sprintf(procname
, "%i", inode
->fd
);
2773 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
2774 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
2779 ret
= fsetxattr(fd
, name
, value
, size
, flags
);
2781 /* fchdir should not fail here */
2782 assert(fchdir(lo
->proc_self_fd
) == 0);
2783 ret
= setxattr(procname
, name
, value
, size
, flags
);
2784 assert(fchdir(lo
->root
.fd
) == 0);
2787 saverr
= ret
== -1 ? errno
: 0;
2794 lo_inode_put(lo
, &inode
);
2795 g_free(mapped_name
);
2796 fuse_reply_err(req
, saverr
);
2799 static void lo_removexattr(fuse_req_t req
, fuse_ino_t ino
, const char *in_name
)
2804 struct lo_data
*lo
= lo_data(req
);
2805 struct lo_inode
*inode
;
2813 ret
= xattr_map_client(lo
, in_name
, &mapped_name
);
2815 fuse_reply_err(req
, -ret
);
2823 inode
= lo_inode(req
, ino
);
2825 fuse_reply_err(req
, EBADF
);
2826 g_free(mapped_name
);
2831 if (!lo_data(req
)->xattr
) {
2835 fuse_log(FUSE_LOG_DEBUG
, "lo_removexattr(ino=%" PRIu64
", name=%s)\n", ino
,
2838 sprintf(procname
, "%i", inode
->fd
);
2839 if (S_ISREG(inode
->filetype
) || S_ISDIR(inode
->filetype
)) {
2840 fd
= openat(lo
->proc_self_fd
, procname
, O_RDONLY
);
2845 ret
= fremovexattr(fd
, name
);
2847 /* fchdir should not fail here */
2848 assert(fchdir(lo
->proc_self_fd
) == 0);
2849 ret
= removexattr(procname
, name
);
2850 assert(fchdir(lo
->root
.fd
) == 0);
2853 saverr
= ret
== -1 ? errno
: 0;
2860 lo_inode_put(lo
, &inode
);
2861 g_free(mapped_name
);
2862 fuse_reply_err(req
, saverr
);
2865 #ifdef HAVE_COPY_FILE_RANGE
2866 static void lo_copy_file_range(fuse_req_t req
, fuse_ino_t ino_in
, off_t off_in
,
2867 struct fuse_file_info
*fi_in
, fuse_ino_t ino_out
,
2868 off_t off_out
, struct fuse_file_info
*fi_out
,
2869 size_t len
, int flags
)
2874 in_fd
= lo_fi_fd(req
, fi_in
);
2875 out_fd
= lo_fi_fd(req
, fi_out
);
2877 fuse_log(FUSE_LOG_DEBUG
,
2878 "lo_copy_file_range(ino=%" PRIu64
"/fd=%d, "
2879 "off=%lu, ino=%" PRIu64
"/fd=%d, "
2880 "off=%lu, size=%zd, flags=0x%x)\n",
2881 ino_in
, in_fd
, off_in
, ino_out
, out_fd
, off_out
, len
, flags
);
2883 res
= copy_file_range(in_fd
, &off_in
, out_fd
, &off_out
, len
, flags
);
2885 fuse_reply_err(req
, errno
);
2887 fuse_reply_write(req
, res
);
2892 static void lo_lseek(fuse_req_t req
, fuse_ino_t ino
, off_t off
, int whence
,
2893 struct fuse_file_info
*fi
)
2898 res
= lseek(lo_fi_fd(req
, fi
), off
, whence
);
2900 fuse_reply_lseek(req
, res
);
2902 fuse_reply_err(req
, errno
);
2906 static void lo_destroy(void *userdata
)
2908 struct lo_data
*lo
= (struct lo_data
*)userdata
;
2910 pthread_mutex_lock(&lo
->mutex
);
2912 GHashTableIter iter
;
2913 gpointer key
, value
;
2915 g_hash_table_iter_init(&iter
, lo
->inodes
);
2916 if (!g_hash_table_iter_next(&iter
, &key
, &value
)) {
2920 struct lo_inode
*inode
= value
;
2921 unref_inode(lo
, inode
, inode
->nlookup
);
2923 pthread_mutex_unlock(&lo
->mutex
);
2926 static struct fuse_lowlevel_ops lo_oper
= {
2928 .lookup
= lo_lookup
,
2931 .symlink
= lo_symlink
,
2933 .unlink
= lo_unlink
,
2935 .rename
= lo_rename
,
2936 .forget
= lo_forget
,
2937 .forget_multi
= lo_forget_multi
,
2938 .getattr
= lo_getattr
,
2939 .setattr
= lo_setattr
,
2940 .readlink
= lo_readlink
,
2941 .opendir
= lo_opendir
,
2942 .readdir
= lo_readdir
,
2943 .readdirplus
= lo_readdirplus
,
2944 .releasedir
= lo_releasedir
,
2945 .fsyncdir
= lo_fsyncdir
,
2946 .create
= lo_create
,
2950 .release
= lo_release
,
2954 .write_buf
= lo_write_buf
,
2955 .statfs
= lo_statfs
,
2956 .fallocate
= lo_fallocate
,
2958 .getxattr
= lo_getxattr
,
2959 .listxattr
= lo_listxattr
,
2960 .setxattr
= lo_setxattr
,
2961 .removexattr
= lo_removexattr
,
2962 #ifdef HAVE_COPY_FILE_RANGE
2963 .copy_file_range
= lo_copy_file_range
,
2966 .destroy
= lo_destroy
,
2969 /* Print vhost-user.json backend program capabilities */
2970 static void print_capabilities(void)
2973 printf(" \"type\": \"fs\"\n");
2978 * Drop all Linux capabilities because the wait parent process only needs to
2979 * sit in waitpid(2) and terminate.
2981 static void setup_wait_parent_capabilities(void)
2983 capng_setpid(syscall(SYS_gettid
));
2984 capng_clear(CAPNG_SELECT_BOTH
);
2985 capng_apply(CAPNG_SELECT_BOTH
);
2989 * Move to a new mount, net, and pid namespaces to isolate this process.
2991 static void setup_namespaces(struct lo_data
*lo
, struct fuse_session
*se
)
2996 * Create a new pid namespace for *child* processes. We'll have to
2997 * fork in order to enter the new pid namespace. A new mount namespace
2998 * is also needed so that we can remount /proc for the new pid
3001 * Our UNIX domain sockets have been created. Now we can move to
3002 * an empty network namespace to prevent TCP/IP and other network
3003 * activity in case this process is compromised.
3005 if (unshare(CLONE_NEWPID
| CLONE_NEWNS
| CLONE_NEWNET
) != 0) {
3006 fuse_log(FUSE_LOG_ERR
, "unshare(CLONE_NEWPID | CLONE_NEWNS): %m\n");
3012 fuse_log(FUSE_LOG_ERR
, "fork() failed: %m\n");
3019 setup_wait_parent_capabilities();
3021 /* The parent waits for the child */
3023 waited
= waitpid(child
, &wstatus
, 0);
3024 } while (waited
< 0 && errno
== EINTR
&& !se
->exited
);
3026 /* We were terminated by a signal, see fuse_signals.c */
3031 if (WIFEXITED(wstatus
)) {
3032 exit(WEXITSTATUS(wstatus
));
3038 /* Send us SIGTERM when the parent thread terminates, see prctl(2) */
3039 prctl(PR_SET_PDEATHSIG
, SIGTERM
);
3042 * If the mounts have shared propagation then we want to opt out so our
3043 * mount changes don't affect the parent mount namespace.
3045 if (mount(NULL
, "/", NULL
, MS_REC
| MS_SLAVE
, NULL
) < 0) {
3046 fuse_log(FUSE_LOG_ERR
, "mount(/, MS_REC|MS_SLAVE): %m\n");
3050 /* The child must remount /proc to use the new pid namespace */
3051 if (mount("proc", "/proc", "proc",
3052 MS_NODEV
| MS_NOEXEC
| MS_NOSUID
| MS_RELATIME
, NULL
) < 0) {
3053 fuse_log(FUSE_LOG_ERR
, "mount(/proc): %m\n");
3058 * We only need /proc/self/fd. Prevent ".." from accessing parent
3059 * directories of /proc/self/fd by bind-mounting it over /proc. Since / was
3060 * previously remounted with MS_REC | MS_SLAVE this mount change only
3061 * affects our process.
3063 if (mount("/proc/self/fd", "/proc", NULL
, MS_BIND
, NULL
) < 0) {
3064 fuse_log(FUSE_LOG_ERR
, "mount(/proc/self/fd, MS_BIND): %m\n");
3068 /* Get the /proc (actually /proc/self/fd, see above) file descriptor */
3069 lo
->proc_self_fd
= open("/proc", O_PATH
);
3070 if (lo
->proc_self_fd
== -1) {
3071 fuse_log(FUSE_LOG_ERR
, "open(/proc, O_PATH): %m\n");
3077 * Capture the capability state, we'll need to restore this for individual
3078 * threads later; see load_capng.
3080 static void setup_capng(void)
3082 /* Note this accesses /proc so has to happen before the sandbox */
3083 if (capng_get_caps_process()) {
3084 fuse_log(FUSE_LOG_ERR
, "capng_get_caps_process\n");
3087 pthread_mutex_init(&cap
.mutex
, NULL
);
3088 pthread_mutex_lock(&cap
.mutex
);
3089 cap
.saved
= capng_save_state();
3091 fuse_log(FUSE_LOG_ERR
, "capng_save_state\n");
3094 pthread_mutex_unlock(&cap
.mutex
);
3097 static void cleanup_capng(void)
3101 pthread_mutex_destroy(&cap
.mutex
);
3106 * Make the source directory our root so symlinks cannot escape and no other
3107 * files are accessible. Assumes unshare(CLONE_NEWNS) was already called.
3109 static void setup_mounts(const char *source
)
3114 if (mount(source
, source
, NULL
, MS_BIND
| MS_REC
, NULL
) < 0) {
3115 fuse_log(FUSE_LOG_ERR
, "mount(%s, %s, MS_BIND): %m\n", source
, source
);
3119 /* This magic is based on lxc's lxc_pivot_root() */
3120 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
3122 fuse_log(FUSE_LOG_ERR
, "open(/): %m\n");
3126 newroot
= open(source
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
3128 fuse_log(FUSE_LOG_ERR
, "open(%s): %m\n", source
);
3132 if (fchdir(newroot
) < 0) {
3133 fuse_log(FUSE_LOG_ERR
, "fchdir(newroot): %m\n");
3137 if (syscall(__NR_pivot_root
, ".", ".") < 0) {
3138 fuse_log(FUSE_LOG_ERR
, "pivot_root(., .): %m\n");
3142 if (fchdir(oldroot
) < 0) {
3143 fuse_log(FUSE_LOG_ERR
, "fchdir(oldroot): %m\n");
3147 if (mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
) < 0) {
3148 fuse_log(FUSE_LOG_ERR
, "mount(., MS_SLAVE | MS_REC): %m\n");
3152 if (umount2(".", MNT_DETACH
) < 0) {
3153 fuse_log(FUSE_LOG_ERR
, "umount2(., MNT_DETACH): %m\n");
3157 if (fchdir(newroot
) < 0) {
3158 fuse_log(FUSE_LOG_ERR
, "fchdir(newroot): %m\n");
3167 * Only keep whitelisted capabilities that are needed for file system operation
3168 * The (possibly NULL) modcaps_in string passed in is free'd before exit.
3170 static void setup_capabilities(char *modcaps_in
)
3172 char *modcaps
= modcaps_in
;
3173 pthread_mutex_lock(&cap
.mutex
);
3174 capng_restore_state(&cap
.saved
);
3177 * Whitelist file system-related capabilities that are needed for a file
3178 * server to act like root. Drop everything else like networking and
3179 * sysadmin capabilities.
3182 * 1. CAP_LINUX_IMMUTABLE is not included because it's only used via ioctl
3183 * and we don't support that.
3184 * 2. CAP_MAC_OVERRIDE is not included because it only seems to be
3185 * used by the Smack LSM. Omit it until there is demand for it.
3187 capng_setpid(syscall(SYS_gettid
));
3188 capng_clear(CAPNG_SELECT_BOTH
);
3189 if (capng_updatev(CAPNG_ADD
, CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
3199 fuse_log(FUSE_LOG_ERR
, "%s: capng_updatev failed\n", __func__
);
3204 * The modcaps option is a colon separated list of caps,
3205 * each preceded by either + or -.
3211 char *next
= strchr(modcaps
, ':');
3217 switch (modcaps
[0]) {
3223 action
= CAPNG_DROP
;
3227 fuse_log(FUSE_LOG_ERR
,
3228 "%s: Expecting '+'/'-' in modcaps but found '%c'\n",
3229 __func__
, modcaps
[0]);
3232 cap
= capng_name_to_capability(modcaps
+ 1);
3234 fuse_log(FUSE_LOG_ERR
, "%s: Unknown capability '%s'\n", __func__
,
3238 if (capng_update(action
, CAPNG_PERMITTED
| CAPNG_EFFECTIVE
, cap
)) {
3239 fuse_log(FUSE_LOG_ERR
, "%s: capng_update failed for '%s'\n",
3248 if (capng_apply(CAPNG_SELECT_BOTH
)) {
3249 fuse_log(FUSE_LOG_ERR
, "%s: capng_apply failed\n", __func__
);
3253 cap
.saved
= capng_save_state();
3255 fuse_log(FUSE_LOG_ERR
, "%s: capng_save_state failed\n", __func__
);
3258 pthread_mutex_unlock(&cap
.mutex
);
3262 * Use chroot as a weaker sandbox for environments where the process is
3263 * launched without CAP_SYS_ADMIN.
3265 static void setup_chroot(struct lo_data
*lo
)
3267 lo
->proc_self_fd
= open("/proc/self/fd", O_PATH
);
3268 if (lo
->proc_self_fd
== -1) {
3269 fuse_log(FUSE_LOG_ERR
, "open(\"/proc/self/fd\", O_PATH): %m\n");
3274 * Make the shared directory the file system root so that FUSE_OPEN
3275 * (lo_open()) cannot escape the shared directory by opening a symlink.
3277 * The chroot(2) syscall is later disabled by seccomp and the
3278 * CAP_SYS_CHROOT capability is dropped so that tampering with the chroot
3281 * However, it's still possible to escape the chroot via lo->proc_self_fd
3282 * but that requires first gaining control of the process.
3284 if (chroot(lo
->source
) != 0) {
3285 fuse_log(FUSE_LOG_ERR
, "chroot(\"%s\"): %m\n", lo
->source
);
3289 /* Move into the chroot */
3290 if (chdir("/") != 0) {
3291 fuse_log(FUSE_LOG_ERR
, "chdir(\"/\"): %m\n");
3297 * Lock down this process to prevent access to other processes or files outside
3298 * source directory. This reduces the impact of arbitrary code execution bugs.
3300 static void setup_sandbox(struct lo_data
*lo
, struct fuse_session
*se
,
3303 if (lo
->sandbox
== SANDBOX_NAMESPACE
) {
3304 setup_namespaces(lo
, se
);
3305 setup_mounts(lo
->source
);
3310 setup_seccomp(enable_syslog
);
3311 setup_capabilities(g_strdup(lo
->modcaps
));
3314 /* Set the maximum number of open file descriptors */
3315 static void setup_nofile_rlimit(unsigned long rlimit_nofile
)
3317 struct rlimit rlim
= {
3318 .rlim_cur
= rlimit_nofile
,
3319 .rlim_max
= rlimit_nofile
,
3322 if (rlimit_nofile
== 0) {
3323 return; /* nothing to do */
3326 if (setrlimit(RLIMIT_NOFILE
, &rlim
) < 0) {
3327 /* Ignore SELinux denials */
3328 if (errno
== EPERM
) {
3332 fuse_log(FUSE_LOG_ERR
, "setrlimit(RLIMIT_NOFILE): %m\n");
3337 static void log_func(enum fuse_log_level level
, const char *fmt
, va_list ap
)
3339 g_autofree
char *localfmt
= NULL
;
3342 char sec_fmt
[sizeof "2020-12-07 18:17:54"];
3343 char zone_fmt
[sizeof "+0100"];
3345 if (current_log_level
< level
) {
3349 if (current_log_level
== FUSE_LOG_DEBUG
) {
3351 /* no timestamp needed */
3352 localfmt
= g_strdup_printf("[ID: %08ld] %s", syscall(__NR_gettid
),
3355 /* try formatting a broken-down timestamp */
3356 if (clock_gettime(CLOCK_REALTIME
, &ts
) != -1 &&
3357 localtime_r(&ts
.tv_sec
, &tm
) != NULL
&&
3358 strftime(sec_fmt
, sizeof sec_fmt
, "%Y-%m-%d %H:%M:%S",
3360 strftime(zone_fmt
, sizeof zone_fmt
, "%z", &tm
) != 0) {
3361 localfmt
= g_strdup_printf("[%s.%02ld%s] [ID: %08ld] %s",
3363 ts
.tv_nsec
/ (10L * 1000 * 1000),
3364 zone_fmt
, syscall(__NR_gettid
),
3367 /* fall back to a flat timestamp */
3368 localfmt
= g_strdup_printf("[%" PRId64
"] [ID: %08ld] %s",
3369 get_clock(), syscall(__NR_gettid
),
3377 int priority
= LOG_ERR
;
3379 case FUSE_LOG_EMERG
:
3380 priority
= LOG_EMERG
;
3382 case FUSE_LOG_ALERT
:
3383 priority
= LOG_ALERT
;
3386 priority
= LOG_CRIT
;
3391 case FUSE_LOG_WARNING
:
3392 priority
= LOG_WARNING
;
3394 case FUSE_LOG_NOTICE
:
3395 priority
= LOG_NOTICE
;
3398 priority
= LOG_INFO
;
3400 case FUSE_LOG_DEBUG
:
3401 priority
= LOG_DEBUG
;
3404 vsyslog(priority
, fmt
, ap
);
3406 vfprintf(stderr
, fmt
, ap
);
3410 static void setup_root(struct lo_data
*lo
, struct lo_inode
*root
)
3416 fd
= open("/", O_PATH
);
3418 fuse_log(FUSE_LOG_ERR
, "open(%s, O_PATH): %m\n", lo
->source
);
3422 res
= do_statx(lo
, fd
, "", &stat
, AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
,
3425 fuse_log(FUSE_LOG_ERR
, "fstatat(%s): %m\n", lo
->source
);
3429 root
->filetype
= S_IFDIR
;
3431 root
->key
.ino
= stat
.st_ino
;
3432 root
->key
.dev
= stat
.st_dev
;
3433 root
->key
.mnt_id
= mnt_id
;
3435 g_atomic_int_set(&root
->refcount
, 2);
3436 if (lo
->posix_lock
) {
3437 pthread_mutex_init(&root
->plock_mutex
, NULL
);
3438 root
->posix_locks
= g_hash_table_new_full(
3439 g_direct_hash
, g_direct_equal
, NULL
, posix_locks_value_destroy
);
3443 static guint
lo_key_hash(gconstpointer key
)
3445 const struct lo_key
*lkey
= key
;
3447 return (guint
)lkey
->ino
+ (guint
)lkey
->dev
+ (guint
)lkey
->mnt_id
;
3450 static gboolean
lo_key_equal(gconstpointer a
, gconstpointer b
)
3452 const struct lo_key
*la
= a
;
3453 const struct lo_key
*lb
= b
;
3455 return la
->ino
== lb
->ino
&& la
->dev
== lb
->dev
&& la
->mnt_id
== lb
->mnt_id
;
3458 static void fuse_lo_data_cleanup(struct lo_data
*lo
)
3461 g_hash_table_destroy(lo
->inodes
);
3464 if (lo
->root
.posix_locks
) {
3465 g_hash_table_destroy(lo
->root
.posix_locks
);
3467 lo_map_destroy(&lo
->fd_map
);
3468 lo_map_destroy(&lo
->dirp_map
);
3469 lo_map_destroy(&lo
->ino_map
);
3471 if (lo
->proc_self_fd
>= 0) {
3472 close(lo
->proc_self_fd
);
3475 if (lo
->root
.fd
>= 0) {
3484 int main(int argc
, char *argv
[])
3486 struct fuse_args args
= FUSE_ARGS_INIT(argc
, argv
);
3487 struct fuse_session
*se
;
3488 struct fuse_cmdline_opts opts
;
3489 struct lo_data lo
= {
3490 .sandbox
= SANDBOX_NAMESPACE
,
3494 .allow_direct_io
= 0,
3497 struct lo_map_elem
*root_elem
;
3498 struct lo_map_elem
*reserve_elem
;
3501 /* Initialize time conversion information for localtime_r(). */
3504 /* Don't mask creation mode, kernel already did that */
3507 qemu_init_exec_dir(argv
[0]);
3509 pthread_mutex_init(&lo
.mutex
, NULL
);
3510 lo
.inodes
= g_hash_table_new(lo_key_hash
, lo_key_equal
);
3512 lo
.root
.fuse_ino
= FUSE_ROOT_ID
;
3513 lo
.cache
= CACHE_AUTO
;
3516 * Set up the ino map like this:
3517 * [0] Reserved (will not be used)
3520 lo_map_init(&lo
.ino_map
);
3521 reserve_elem
= lo_map_reserve(&lo
.ino_map
, 0);
3522 if (!reserve_elem
) {
3523 fuse_log(FUSE_LOG_ERR
, "failed to alloc reserve_elem.\n");
3526 reserve_elem
->in_use
= false;
3527 root_elem
= lo_map_reserve(&lo
.ino_map
, lo
.root
.fuse_ino
);
3529 fuse_log(FUSE_LOG_ERR
, "failed to alloc root_elem.\n");
3532 root_elem
->inode
= &lo
.root
;
3534 lo_map_init(&lo
.dirp_map
);
3535 lo_map_init(&lo
.fd_map
);
3537 if (fuse_parse_cmdline(&args
, &opts
) != 0) {
3540 fuse_set_log_func(log_func
);
3541 use_syslog
= opts
.syslog
;
3543 openlog("virtiofsd", LOG_PID
, LOG_DAEMON
);
3546 if (opts
.show_help
) {
3547 printf("usage: %s [options]\n\n", argv
[0]);
3548 fuse_cmdline_help();
3549 printf(" -o source=PATH shared directory tree\n");
3550 fuse_lowlevel_help();
3553 } else if (opts
.show_version
) {
3554 fuse_lowlevel_version();
3557 } else if (opts
.print_capabilities
) {
3558 print_capabilities();
3563 if (fuse_opt_parse(&args
, &lo
, lo_opts
, NULL
) == -1) {
3567 if (opts
.log_level
!= 0) {
3568 current_log_level
= opts
.log_level
;
3570 /* default log level is INFO */
3571 current_log_level
= FUSE_LOG_INFO
;
3573 lo
.debug
= opts
.debug
;
3575 current_log_level
= FUSE_LOG_DEBUG
;
3581 res
= lstat(lo
.source
, &stat
);
3583 fuse_log(FUSE_LOG_ERR
, "failed to stat source (\"%s\"): %m\n",
3587 if (!S_ISDIR(stat
.st_mode
)) {
3588 fuse_log(FUSE_LOG_ERR
, "source is not a directory\n");
3592 lo
.source
= strdup("/");
3594 fuse_log(FUSE_LOG_ERR
, "failed to strdup source\n");
3600 parse_xattrmap(&lo
);
3603 if (!lo
.timeout_set
) {
3614 lo
.timeout
= 86400.0;
3617 } else if (lo
.timeout
< 0) {
3618 fuse_log(FUSE_LOG_ERR
, "timeout is negative (%lf)\n", lo
.timeout
);
3622 lo
.use_statx
= true;
3624 se
= fuse_session_new(&args
, &lo_oper
, sizeof(lo_oper
), &lo
);
3629 if (fuse_set_signal_handlers(se
) != 0) {
3633 if (fuse_session_mount(se
) != 0) {
3637 fuse_daemonize(opts
.foreground
);
3639 setup_nofile_rlimit(opts
.rlimit_nofile
);
3641 /* Must be before sandbox since it wants /proc */
3644 setup_sandbox(&lo
, se
, opts
.syslog
);
3646 setup_root(&lo
, &lo
.root
);
3647 /* Block until ctrl+c or fusermount -u */
3648 ret
= virtio_loop(se
);
3650 fuse_session_unmount(se
);
3653 fuse_remove_signal_handlers(se
);
3655 fuse_session_destroy(se
);
3657 fuse_opt_free_args(&args
);
3659 fuse_lo_data_cleanup(&lo
);