target/ppc: cpu_init: Decouple G2 SPR registration from 755
[qemu.git] / tools / virtiofsd / passthrough_ll.c
blobb3d0674f6d2f267664d1c45588568783199b41b8
1 /*
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.
7 */
9 /*
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
20 * more complicated.
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).
29 * Compile with:
31 * gcc -Wall passthrough_ll.c `pkg-config fuse3 --cflags --libs` -o
32 * passthrough_ll
34 * ## Source code ##
35 * \include passthrough_ll.c
38 #include "qemu/osdep.h"
39 #include "qemu/timer.h"
40 #include "qemu-version.h"
41 #include "qemu-common.h"
42 #include "fuse_virtio.h"
43 #include "fuse_log.h"
44 #include "fuse_lowlevel.h"
45 #include "standard-headers/linux/fuse.h"
46 #include <cap-ng.h>
47 #include <dirent.h>
48 #include <pthread.h>
49 #include <sys/file.h>
50 #include <sys/mount.h>
51 #include <sys/prctl.h>
52 #include <sys/resource.h>
53 #include <sys/syscall.h>
54 #include <sys/wait.h>
55 #include <sys/xattr.h>
56 #include <syslog.h>
57 #include <grp.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 {
65 uint64_t lock_owner;
66 int fd; /* fd for OFD locks */
69 struct lo_map_elem {
70 union {
71 struct lo_inode *inode;
72 struct lo_dirp *dirp;
73 int fd;
74 ssize_t freelist;
76 bool in_use;
79 /* Maps FUSE fh or ino values to internal objects */
80 struct lo_map {
81 struct lo_map_elem *elems;
82 size_t nelems;
83 ssize_t freelist;
86 struct lo_key {
87 ino_t ino;
88 dev_t dev;
89 uint64_t mnt_id;
92 struct lo_inode {
93 int fd;
96 * Atomic reference count for this object. The nlookup field holds a
97 * reference and release it when nlookup reaches 0.
99 gint refcount;
101 struct lo_key key;
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.
114 uint64_t nlookup;
116 fuse_ino_t fuse_ino;
117 pthread_mutex_t plock_mutex;
118 GHashTable *posix_locks; /* protected by lo_inode->plock_mutex */
120 mode_t filetype;
123 struct lo_cred {
124 uid_t euid;
125 gid_t egid;
126 mode_t umask;
129 enum {
130 CACHE_NONE,
131 CACHE_AUTO,
132 CACHE_ALWAYS,
135 enum {
136 SANDBOX_NAMESPACE,
137 SANDBOX_CHROOT,
140 typedef struct xattr_map_entry {
141 char *key;
142 char *prepend;
143 unsigned int flags;
144 } XattrMapEntry;
146 struct lo_data {
147 pthread_mutex_t mutex;
148 int sandbox;
149 int debug;
150 int writeback;
151 int flock;
152 int posix_lock;
153 int xattr;
154 char *xattrmap;
155 char *xattr_security_capability;
156 char *source;
157 char *modcaps;
158 double timeout;
159 int cache;
160 int timeout_set;
161 int readdirplus_set;
162 int readdirplus_clear;
163 int allow_direct_io;
164 int announce_submounts;
165 bool use_statx;
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/ */
175 int proc_self_fd;
176 int user_killpriv_v2, killpriv_v2;
177 /* If set, virtiofsd is responsible for setting umask during creation */
178 bool change_umask;
179 int user_posix_acl, posix_acl;
182 static const struct fuse_opt lo_opts[] = {
183 { "sandbox=namespace",
184 offsetof(struct lo_data, sandbox),
185 SANDBOX_NAMESPACE },
186 { "sandbox=chroot",
187 offsetof(struct lo_data, sandbox),
188 SANDBOX_CHROOT },
189 { "writeback", offsetof(struct lo_data, writeback), 1 },
190 { "no_writeback", offsetof(struct lo_data, writeback), 0 },
191 { "source=%s", offsetof(struct lo_data, source), 0 },
192 { "flock", offsetof(struct lo_data, flock), 1 },
193 { "no_flock", offsetof(struct lo_data, flock), 0 },
194 { "posix_lock", offsetof(struct lo_data, posix_lock), 1 },
195 { "no_posix_lock", offsetof(struct lo_data, posix_lock), 0 },
196 { "xattr", offsetof(struct lo_data, xattr), 1 },
197 { "no_xattr", offsetof(struct lo_data, xattr), 0 },
198 { "xattrmap=%s", offsetof(struct lo_data, xattrmap), 0 },
199 { "modcaps=%s", offsetof(struct lo_data, modcaps), 0 },
200 { "timeout=%lf", offsetof(struct lo_data, timeout), 0 },
201 { "timeout=", offsetof(struct lo_data, timeout_set), 1 },
202 { "cache=none", offsetof(struct lo_data, cache), CACHE_NONE },
203 { "cache=auto", offsetof(struct lo_data, cache), CACHE_AUTO },
204 { "cache=always", offsetof(struct lo_data, cache), CACHE_ALWAYS },
205 { "readdirplus", offsetof(struct lo_data, readdirplus_set), 1 },
206 { "no_readdirplus", offsetof(struct lo_data, readdirplus_clear), 1 },
207 { "allow_direct_io", offsetof(struct lo_data, allow_direct_io), 1 },
208 { "no_allow_direct_io", offsetof(struct lo_data, allow_direct_io), 0 },
209 { "announce_submounts", offsetof(struct lo_data, announce_submounts), 1 },
210 { "killpriv_v2", offsetof(struct lo_data, user_killpriv_v2), 1 },
211 { "no_killpriv_v2", offsetof(struct lo_data, user_killpriv_v2), 0 },
212 { "posix_acl", offsetof(struct lo_data, user_posix_acl), 1 },
213 { "no_posix_acl", offsetof(struct lo_data, user_posix_acl), 0 },
214 FUSE_OPT_END
216 static bool use_syslog = false;
217 static int current_log_level;
218 static void unref_inode_lolocked(struct lo_data *lo, struct lo_inode *inode,
219 uint64_t n);
221 static struct {
222 pthread_mutex_t mutex;
223 void *saved;
224 } cap;
225 /* That we loaded cap-ng in the current thread from the saved */
226 static __thread bool cap_loaded = 0;
228 static struct lo_inode *lo_find(struct lo_data *lo, struct stat *st,
229 uint64_t mnt_id);
230 static int xattr_map_client(const struct lo_data *lo, const char *client_name,
231 char **out_name);
233 static bool is_dot_or_dotdot(const char *name)
235 return name[0] == '.' &&
236 (name[1] == '\0' || (name[1] == '.' && name[2] == '\0'));
239 /* Is `path` a single path component that is not "." or ".."? */
240 static bool is_safe_path_component(const char *path)
242 if (strchr(path, '/')) {
243 return false;
246 return !is_dot_or_dotdot(path);
249 static bool is_empty(const char *name)
251 return name[0] == '\0';
254 static struct lo_data *lo_data(fuse_req_t req)
256 return (struct lo_data *)fuse_req_userdata(req);
260 * Load capng's state from our saved state if the current thread
261 * hadn't previously been loaded.
262 * returns 0 on success
264 static int load_capng(void)
266 if (!cap_loaded) {
267 pthread_mutex_lock(&cap.mutex);
268 capng_restore_state(&cap.saved);
270 * restore_state free's the saved copy
271 * so make another.
273 cap.saved = capng_save_state();
274 if (!cap.saved) {
275 pthread_mutex_unlock(&cap.mutex);
276 fuse_log(FUSE_LOG_ERR, "capng_save_state (thread)\n");
277 return -EINVAL;
279 pthread_mutex_unlock(&cap.mutex);
282 * We want to use the loaded state for our pid,
283 * not the original
285 capng_setpid(syscall(SYS_gettid));
286 cap_loaded = true;
288 return 0;
292 * Helpers for dropping and regaining effective capabilities. Returns 0
293 * on success, error otherwise
295 static int drop_effective_cap(const char *cap_name, bool *cap_dropped)
297 int cap, ret;
299 cap = capng_name_to_capability(cap_name);
300 if (cap < 0) {
301 ret = errno;
302 fuse_log(FUSE_LOG_ERR, "capng_name_to_capability(%s) failed:%s\n",
303 cap_name, strerror(errno));
304 goto out;
307 if (load_capng()) {
308 ret = errno;
309 fuse_log(FUSE_LOG_ERR, "load_capng() failed\n");
310 goto out;
313 /* We dont have this capability in effective set already. */
314 if (!capng_have_capability(CAPNG_EFFECTIVE, cap)) {
315 ret = 0;
316 goto out;
319 if (capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, cap)) {
320 ret = errno;
321 fuse_log(FUSE_LOG_ERR, "capng_update(DROP,) failed\n");
322 goto out;
325 if (capng_apply(CAPNG_SELECT_CAPS)) {
326 ret = errno;
327 fuse_log(FUSE_LOG_ERR, "drop:capng_apply() failed\n");
328 goto out;
331 ret = 0;
332 if (cap_dropped) {
333 *cap_dropped = true;
336 out:
337 return ret;
340 static int gain_effective_cap(const char *cap_name)
342 int cap;
343 int ret = 0;
345 cap = capng_name_to_capability(cap_name);
346 if (cap < 0) {
347 ret = errno;
348 fuse_log(FUSE_LOG_ERR, "capng_name_to_capability(%s) failed:%s\n",
349 cap_name, strerror(errno));
350 goto out;
353 if (load_capng()) {
354 ret = errno;
355 fuse_log(FUSE_LOG_ERR, "load_capng() failed\n");
356 goto out;
359 if (capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, cap)) {
360 ret = errno;
361 fuse_log(FUSE_LOG_ERR, "capng_update(ADD,) failed\n");
362 goto out;
365 if (capng_apply(CAPNG_SELECT_CAPS)) {
366 ret = errno;
367 fuse_log(FUSE_LOG_ERR, "gain:capng_apply() failed\n");
368 goto out;
370 ret = 0;
372 out:
373 return ret;
377 * The host kernel normally drops security.capability xattr's on
378 * any write, however if we're remapping xattr names we need to drop
379 * whatever the clients security.capability is actually stored as.
381 static int drop_security_capability(const struct lo_data *lo, int fd)
383 if (!lo->xattr_security_capability) {
384 /* We didn't remap the name, let the host kernel do it */
385 return 0;
387 if (!fremovexattr(fd, lo->xattr_security_capability)) {
388 /* All good */
389 return 0;
392 switch (errno) {
393 case ENODATA:
394 /* Attribute didn't exist, that's fine */
395 return 0;
397 case ENOTSUP:
398 /* FS didn't support attribute anyway, also fine */
399 return 0;
401 default:
402 /* Hmm other error */
403 return errno;
407 static void lo_map_init(struct lo_map *map)
409 map->elems = NULL;
410 map->nelems = 0;
411 map->freelist = -1;
414 static void lo_map_destroy(struct lo_map *map)
416 g_free(map->elems);
419 static int lo_map_grow(struct lo_map *map, size_t new_nelems)
421 struct lo_map_elem *new_elems;
422 size_t i;
424 if (new_nelems <= map->nelems) {
425 return 1;
428 new_elems = g_try_realloc_n(map->elems, new_nelems, sizeof(map->elems[0]));
429 if (!new_elems) {
430 return 0;
433 for (i = map->nelems; i < new_nelems; i++) {
434 new_elems[i].freelist = i + 1;
435 new_elems[i].in_use = false;
437 new_elems[new_nelems - 1].freelist = -1;
439 map->elems = new_elems;
440 map->freelist = map->nelems;
441 map->nelems = new_nelems;
442 return 1;
445 static struct lo_map_elem *lo_map_alloc_elem(struct lo_map *map)
447 struct lo_map_elem *elem;
449 if (map->freelist == -1 && !lo_map_grow(map, map->nelems + 256)) {
450 return NULL;
453 elem = &map->elems[map->freelist];
454 map->freelist = elem->freelist;
456 elem->in_use = true;
458 return elem;
461 static struct lo_map_elem *lo_map_reserve(struct lo_map *map, size_t key)
463 ssize_t *prev;
465 if (!lo_map_grow(map, key + 1)) {
466 return NULL;
469 for (prev = &map->freelist; *prev != -1;
470 prev = &map->elems[*prev].freelist) {
471 if (*prev == key) {
472 struct lo_map_elem *elem = &map->elems[key];
474 *prev = elem->freelist;
475 elem->in_use = true;
476 return elem;
479 return NULL;
482 static struct lo_map_elem *lo_map_get(struct lo_map *map, size_t key)
484 if (key >= map->nelems) {
485 return NULL;
487 if (!map->elems[key].in_use) {
488 return NULL;
490 return &map->elems[key];
493 static void lo_map_remove(struct lo_map *map, size_t key)
495 struct lo_map_elem *elem;
497 if (key >= map->nelems) {
498 return;
501 elem = &map->elems[key];
502 if (!elem->in_use) {
503 return;
506 elem->in_use = false;
508 elem->freelist = map->freelist;
509 map->freelist = key;
512 /* Assumes lo->mutex is held */
513 static ssize_t lo_add_fd_mapping(struct lo_data *lo, int fd)
515 struct lo_map_elem *elem;
517 elem = lo_map_alloc_elem(&lo->fd_map);
518 if (!elem) {
519 return -1;
522 elem->fd = fd;
523 return elem - lo->fd_map.elems;
526 /* Assumes lo->mutex is held */
527 static ssize_t lo_add_dirp_mapping(fuse_req_t req, struct lo_dirp *dirp)
529 struct lo_map_elem *elem;
531 elem = lo_map_alloc_elem(&lo_data(req)->dirp_map);
532 if (!elem) {
533 return -1;
536 elem->dirp = dirp;
537 return elem - lo_data(req)->dirp_map.elems;
540 /* Assumes lo->mutex is held */
541 static ssize_t lo_add_inode_mapping(fuse_req_t req, struct lo_inode *inode)
543 struct lo_map_elem *elem;
545 elem = lo_map_alloc_elem(&lo_data(req)->ino_map);
546 if (!elem) {
547 return -1;
550 elem->inode = inode;
551 return elem - lo_data(req)->ino_map.elems;
554 static void lo_inode_put(struct lo_data *lo, struct lo_inode **inodep)
556 struct lo_inode *inode = *inodep;
558 if (!inode) {
559 return;
562 *inodep = NULL;
564 if (g_atomic_int_dec_and_test(&inode->refcount)) {
565 close(inode->fd);
566 free(inode);
570 /* Caller must release refcount using lo_inode_put() */
571 static struct lo_inode *lo_inode(fuse_req_t req, fuse_ino_t ino)
573 struct lo_data *lo = lo_data(req);
574 struct lo_map_elem *elem;
576 pthread_mutex_lock(&lo->mutex);
577 elem = lo_map_get(&lo->ino_map, ino);
578 if (elem) {
579 g_atomic_int_inc(&elem->inode->refcount);
581 pthread_mutex_unlock(&lo->mutex);
583 if (!elem) {
584 return NULL;
587 return elem->inode;
591 * TODO Remove this helper and force callers to hold an inode refcount until
592 * they are done with the fd. This will be done in a later patch to make
593 * review easier.
595 static int lo_fd(fuse_req_t req, fuse_ino_t ino)
597 struct lo_inode *inode = lo_inode(req, ino);
598 int fd;
600 if (!inode) {
601 return -1;
604 fd = inode->fd;
605 lo_inode_put(lo_data(req), &inode);
606 return fd;
610 * Open a file descriptor for an inode. Returns -EBADF if the inode is not a
611 * regular file or a directory.
613 * Use this helper function instead of raw openat(2) to prevent security issues
614 * when a malicious client opens special files such as block device nodes.
615 * Symlink inodes are also rejected since symlinks must already have been
616 * traversed on the client side.
618 static int lo_inode_open(struct lo_data *lo, struct lo_inode *inode,
619 int open_flags)
621 g_autofree char *fd_str = g_strdup_printf("%d", inode->fd);
622 int fd;
624 if (!S_ISREG(inode->filetype) && !S_ISDIR(inode->filetype)) {
625 return -EBADF;
629 * The file is a symlink so O_NOFOLLOW must be ignored. We checked earlier
630 * that the inode is not a special file but if an external process races
631 * with us then symlinks are traversed here. It is not possible to escape
632 * the shared directory since it is mounted as "/" though.
634 fd = openat(lo->proc_self_fd, fd_str, open_flags & ~O_NOFOLLOW);
635 if (fd < 0) {
636 return -errno;
638 return fd;
641 static void lo_init(void *userdata, struct fuse_conn_info *conn)
643 struct lo_data *lo = (struct lo_data *)userdata;
645 if (conn->capable & FUSE_CAP_EXPORT_SUPPORT) {
646 conn->want |= FUSE_CAP_EXPORT_SUPPORT;
649 if (lo->writeback && conn->capable & FUSE_CAP_WRITEBACK_CACHE) {
650 fuse_log(FUSE_LOG_DEBUG, "lo_init: activating writeback\n");
651 conn->want |= FUSE_CAP_WRITEBACK_CACHE;
653 if (conn->capable & FUSE_CAP_FLOCK_LOCKS) {
654 if (lo->flock) {
655 fuse_log(FUSE_LOG_DEBUG, "lo_init: activating flock locks\n");
656 conn->want |= FUSE_CAP_FLOCK_LOCKS;
657 } else {
658 fuse_log(FUSE_LOG_DEBUG, "lo_init: disabling flock locks\n");
659 conn->want &= ~FUSE_CAP_FLOCK_LOCKS;
663 if (conn->capable & FUSE_CAP_POSIX_LOCKS) {
664 if (lo->posix_lock) {
665 fuse_log(FUSE_LOG_DEBUG, "lo_init: activating posix locks\n");
666 conn->want |= FUSE_CAP_POSIX_LOCKS;
667 } else {
668 fuse_log(FUSE_LOG_DEBUG, "lo_init: disabling posix locks\n");
669 conn->want &= ~FUSE_CAP_POSIX_LOCKS;
673 if ((lo->cache == CACHE_NONE && !lo->readdirplus_set) ||
674 lo->readdirplus_clear) {
675 fuse_log(FUSE_LOG_DEBUG, "lo_init: disabling readdirplus\n");
676 conn->want &= ~FUSE_CAP_READDIRPLUS;
679 if (!(conn->capable & FUSE_CAP_SUBMOUNTS) && lo->announce_submounts) {
680 fuse_log(FUSE_LOG_WARNING, "lo_init: Cannot announce submounts, client "
681 "does not support it\n");
682 lo->announce_submounts = false;
685 if (lo->user_killpriv_v2 == 1) {
687 * User explicitly asked for this option. Enable it unconditionally.
688 * If connection does not have this capability, it should fail
689 * in fuse_lowlevel.c
691 fuse_log(FUSE_LOG_DEBUG, "lo_init: enabling killpriv_v2\n");
692 conn->want |= FUSE_CAP_HANDLE_KILLPRIV_V2;
693 lo->killpriv_v2 = 1;
694 } else if (lo->user_killpriv_v2 == -1 &&
695 conn->capable & FUSE_CAP_HANDLE_KILLPRIV_V2) {
697 * User did not specify a value for killpriv_v2. By default enable it
698 * if connection offers this capability
700 fuse_log(FUSE_LOG_DEBUG, "lo_init: enabling killpriv_v2\n");
701 conn->want |= FUSE_CAP_HANDLE_KILLPRIV_V2;
702 lo->killpriv_v2 = 1;
703 } else {
705 * Either user specified to disable killpriv_v2, or connection does
706 * not offer this capability. Disable killpriv_v2 in both the cases
708 fuse_log(FUSE_LOG_DEBUG, "lo_init: disabling killpriv_v2\n");
709 conn->want &= ~FUSE_CAP_HANDLE_KILLPRIV_V2;
710 lo->killpriv_v2 = 0;
713 if (lo->user_posix_acl == 1) {
715 * User explicitly asked for this option. Enable it unconditionally.
716 * If connection does not have this capability, print error message
717 * now. It will fail later in fuse_lowlevel.c
719 if (!(conn->capable & FUSE_CAP_POSIX_ACL) ||
720 !(conn->capable & FUSE_CAP_DONT_MASK) ||
721 !(conn->capable & FUSE_CAP_SETXATTR_EXT)) {
722 fuse_log(FUSE_LOG_ERR, "lo_init: Can not enable posix acl."
723 " kernel does not support FUSE_POSIX_ACL, FUSE_DONT_MASK"
724 " or FUSE_SETXATTR_EXT capability.\n");
725 } else {
726 fuse_log(FUSE_LOG_DEBUG, "lo_init: enabling posix acl\n");
729 conn->want |= FUSE_CAP_POSIX_ACL | FUSE_CAP_DONT_MASK |
730 FUSE_CAP_SETXATTR_EXT;
731 lo->change_umask = true;
732 lo->posix_acl = true;
733 } else {
734 /* User either did not specify anything or wants it disabled */
735 fuse_log(FUSE_LOG_DEBUG, "lo_init: disabling posix_acl\n");
736 conn->want &= ~FUSE_CAP_POSIX_ACL;
740 static void lo_getattr(fuse_req_t req, fuse_ino_t ino,
741 struct fuse_file_info *fi)
743 int res;
744 struct stat buf;
745 struct lo_data *lo = lo_data(req);
747 (void)fi;
749 res =
750 fstatat(lo_fd(req, ino), "", &buf, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW);
751 if (res == -1) {
752 return (void)fuse_reply_err(req, errno);
755 fuse_reply_attr(req, &buf, lo->timeout);
758 static int lo_fi_fd(fuse_req_t req, struct fuse_file_info *fi)
760 struct lo_data *lo = lo_data(req);
761 struct lo_map_elem *elem;
763 pthread_mutex_lock(&lo->mutex);
764 elem = lo_map_get(&lo->fd_map, fi->fh);
765 pthread_mutex_unlock(&lo->mutex);
767 if (!elem) {
768 return -1;
771 return elem->fd;
774 static void lo_setattr(fuse_req_t req, fuse_ino_t ino, struct stat *attr,
775 int valid, struct fuse_file_info *fi)
777 int saverr;
778 char procname[64];
779 struct lo_data *lo = lo_data(req);
780 struct lo_inode *inode;
781 int ifd;
782 int res;
783 int fd = -1;
785 inode = lo_inode(req, ino);
786 if (!inode) {
787 fuse_reply_err(req, EBADF);
788 return;
791 ifd = inode->fd;
793 /* If fi->fh is invalid we'll report EBADF later */
794 if (fi) {
795 fd = lo_fi_fd(req, fi);
798 if (valid & FUSE_SET_ATTR_MODE) {
799 if (fi) {
800 res = fchmod(fd, attr->st_mode);
801 } else {
802 sprintf(procname, "%i", ifd);
803 res = fchmodat(lo->proc_self_fd, procname, attr->st_mode, 0);
805 if (res == -1) {
806 saverr = errno;
807 goto out_err;
810 if (valid & (FUSE_SET_ATTR_UID | FUSE_SET_ATTR_GID)) {
811 uid_t uid = (valid & FUSE_SET_ATTR_UID) ? attr->st_uid : (uid_t)-1;
812 gid_t gid = (valid & FUSE_SET_ATTR_GID) ? attr->st_gid : (gid_t)-1;
814 saverr = drop_security_capability(lo, ifd);
815 if (saverr) {
816 goto out_err;
819 res = fchownat(ifd, "", uid, gid, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW);
820 if (res == -1) {
821 saverr = errno;
822 goto out_err;
825 if (valid & FUSE_SET_ATTR_SIZE) {
826 int truncfd;
827 bool kill_suidgid;
828 bool cap_fsetid_dropped = false;
830 kill_suidgid = lo->killpriv_v2 && (valid & FUSE_SET_ATTR_KILL_SUIDGID);
831 if (fi) {
832 truncfd = fd;
833 } else {
834 truncfd = lo_inode_open(lo, inode, O_RDWR);
835 if (truncfd < 0) {
836 saverr = -truncfd;
837 goto out_err;
841 saverr = drop_security_capability(lo, truncfd);
842 if (saverr) {
843 if (!fi) {
844 close(truncfd);
846 goto out_err;
849 if (kill_suidgid) {
850 res = drop_effective_cap("FSETID", &cap_fsetid_dropped);
851 if (res != 0) {
852 saverr = res;
853 if (!fi) {
854 close(truncfd);
856 goto out_err;
860 res = ftruncate(truncfd, attr->st_size);
861 saverr = res == -1 ? errno : 0;
863 if (cap_fsetid_dropped) {
864 if (gain_effective_cap("FSETID")) {
865 fuse_log(FUSE_LOG_ERR, "Failed to gain CAP_FSETID\n");
868 if (!fi) {
869 close(truncfd);
871 if (res == -1) {
872 goto out_err;
875 if (valid & (FUSE_SET_ATTR_ATIME | FUSE_SET_ATTR_MTIME)) {
876 struct timespec tv[2];
878 tv[0].tv_sec = 0;
879 tv[1].tv_sec = 0;
880 tv[0].tv_nsec = UTIME_OMIT;
881 tv[1].tv_nsec = UTIME_OMIT;
883 if (valid & FUSE_SET_ATTR_ATIME_NOW) {
884 tv[0].tv_nsec = UTIME_NOW;
885 } else if (valid & FUSE_SET_ATTR_ATIME) {
886 tv[0] = attr->st_atim;
889 if (valid & FUSE_SET_ATTR_MTIME_NOW) {
890 tv[1].tv_nsec = UTIME_NOW;
891 } else if (valid & FUSE_SET_ATTR_MTIME) {
892 tv[1] = attr->st_mtim;
895 if (fi) {
896 res = futimens(fd, tv);
897 } else {
898 sprintf(procname, "%i", inode->fd);
899 res = utimensat(lo->proc_self_fd, procname, tv, 0);
901 if (res == -1) {
902 saverr = errno;
903 goto out_err;
906 lo_inode_put(lo, &inode);
908 return lo_getattr(req, ino, fi);
910 out_err:
911 lo_inode_put(lo, &inode);
912 fuse_reply_err(req, saverr);
915 static struct lo_inode *lo_find(struct lo_data *lo, struct stat *st,
916 uint64_t mnt_id)
918 struct lo_inode *p;
919 struct lo_key key = {
920 .ino = st->st_ino,
921 .dev = st->st_dev,
922 .mnt_id = mnt_id,
925 pthread_mutex_lock(&lo->mutex);
926 p = g_hash_table_lookup(lo->inodes, &key);
927 if (p) {
928 assert(p->nlookup > 0);
929 p->nlookup++;
930 g_atomic_int_inc(&p->refcount);
932 pthread_mutex_unlock(&lo->mutex);
934 return p;
937 /* value_destroy_func for posix_locks GHashTable */
938 static void posix_locks_value_destroy(gpointer data)
940 struct lo_inode_plock *plock = data;
943 * We had used open() for locks and had only one fd. So
944 * closing this fd should release all OFD locks.
946 close(plock->fd);
947 free(plock);
950 static int do_statx(struct lo_data *lo, int dirfd, const char *pathname,
951 struct stat *statbuf, int flags, uint64_t *mnt_id)
953 int res;
955 #if defined(CONFIG_STATX) && defined(STATX_MNT_ID)
956 if (lo->use_statx) {
957 struct statx statxbuf;
959 res = statx(dirfd, pathname, flags, STATX_BASIC_STATS | STATX_MNT_ID,
960 &statxbuf);
961 if (!res) {
962 memset(statbuf, 0, sizeof(*statbuf));
963 statbuf->st_dev = makedev(statxbuf.stx_dev_major,
964 statxbuf.stx_dev_minor);
965 statbuf->st_ino = statxbuf.stx_ino;
966 statbuf->st_mode = statxbuf.stx_mode;
967 statbuf->st_nlink = statxbuf.stx_nlink;
968 statbuf->st_uid = statxbuf.stx_uid;
969 statbuf->st_gid = statxbuf.stx_gid;
970 statbuf->st_rdev = makedev(statxbuf.stx_rdev_major,
971 statxbuf.stx_rdev_minor);
972 statbuf->st_size = statxbuf.stx_size;
973 statbuf->st_blksize = statxbuf.stx_blksize;
974 statbuf->st_blocks = statxbuf.stx_blocks;
975 statbuf->st_atim.tv_sec = statxbuf.stx_atime.tv_sec;
976 statbuf->st_atim.tv_nsec = statxbuf.stx_atime.tv_nsec;
977 statbuf->st_mtim.tv_sec = statxbuf.stx_mtime.tv_sec;
978 statbuf->st_mtim.tv_nsec = statxbuf.stx_mtime.tv_nsec;
979 statbuf->st_ctim.tv_sec = statxbuf.stx_ctime.tv_sec;
980 statbuf->st_ctim.tv_nsec = statxbuf.stx_ctime.tv_nsec;
982 if (statxbuf.stx_mask & STATX_MNT_ID) {
983 *mnt_id = statxbuf.stx_mnt_id;
984 } else {
985 *mnt_id = 0;
987 return 0;
988 } else if (errno != ENOSYS) {
989 return -1;
991 lo->use_statx = false;
992 /* fallback */
994 #endif
995 res = fstatat(dirfd, pathname, statbuf, flags);
996 if (res == -1) {
997 return -1;
999 *mnt_id = 0;
1001 return 0;
1005 * Increments nlookup on the inode on success. unref_inode_lolocked() must be
1006 * called eventually to decrement nlookup again. If inodep is non-NULL, the
1007 * inode pointer is stored and the caller must call lo_inode_put().
1009 static int lo_do_lookup(fuse_req_t req, fuse_ino_t parent, const char *name,
1010 struct fuse_entry_param *e,
1011 struct lo_inode **inodep)
1013 int newfd;
1014 int res;
1015 int saverr;
1016 uint64_t mnt_id;
1017 struct lo_data *lo = lo_data(req);
1018 struct lo_inode *inode = NULL;
1019 struct lo_inode *dir = lo_inode(req, parent);
1021 if (inodep) {
1022 *inodep = NULL; /* in case there is an error */
1026 * name_to_handle_at() and open_by_handle_at() can reach here with fuse
1027 * mount point in guest, but we don't have its inode info in the
1028 * ino_map.
1030 if (!dir) {
1031 return ENOENT;
1034 memset(e, 0, sizeof(*e));
1035 e->attr_timeout = lo->timeout;
1036 e->entry_timeout = lo->timeout;
1038 /* Do not allow escaping root directory */
1039 if (dir == &lo->root && strcmp(name, "..") == 0) {
1040 name = ".";
1043 newfd = openat(dir->fd, name, O_PATH | O_NOFOLLOW);
1044 if (newfd == -1) {
1045 goto out_err;
1048 res = do_statx(lo, newfd, "", &e->attr, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW,
1049 &mnt_id);
1050 if (res == -1) {
1051 goto out_err;
1054 if (S_ISDIR(e->attr.st_mode) && lo->announce_submounts &&
1055 (e->attr.st_dev != dir->key.dev || mnt_id != dir->key.mnt_id)) {
1056 e->attr_flags |= FUSE_ATTR_SUBMOUNT;
1059 inode = lo_find(lo, &e->attr, mnt_id);
1060 if (inode) {
1061 close(newfd);
1062 } else {
1063 inode = calloc(1, sizeof(struct lo_inode));
1064 if (!inode) {
1065 goto out_err;
1068 /* cache only filetype */
1069 inode->filetype = (e->attr.st_mode & S_IFMT);
1072 * One for the caller and one for nlookup (released in
1073 * unref_inode_lolocked())
1075 g_atomic_int_set(&inode->refcount, 2);
1077 inode->nlookup = 1;
1078 inode->fd = newfd;
1079 inode->key.ino = e->attr.st_ino;
1080 inode->key.dev = e->attr.st_dev;
1081 inode->key.mnt_id = mnt_id;
1082 if (lo->posix_lock) {
1083 pthread_mutex_init(&inode->plock_mutex, NULL);
1084 inode->posix_locks = g_hash_table_new_full(
1085 g_direct_hash, g_direct_equal, NULL, posix_locks_value_destroy);
1087 pthread_mutex_lock(&lo->mutex);
1088 inode->fuse_ino = lo_add_inode_mapping(req, inode);
1089 g_hash_table_insert(lo->inodes, &inode->key, inode);
1090 pthread_mutex_unlock(&lo->mutex);
1092 e->ino = inode->fuse_ino;
1094 /* Transfer ownership of inode pointer to caller or drop it */
1095 if (inodep) {
1096 *inodep = inode;
1097 } else {
1098 lo_inode_put(lo, &inode);
1101 lo_inode_put(lo, &dir);
1103 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
1104 name, (unsigned long long)e->ino);
1106 return 0;
1108 out_err:
1109 saverr = errno;
1110 if (newfd != -1) {
1111 close(newfd);
1113 lo_inode_put(lo, &inode);
1114 lo_inode_put(lo, &dir);
1115 return saverr;
1118 static void lo_lookup(fuse_req_t req, fuse_ino_t parent, const char *name)
1120 struct fuse_entry_param e;
1121 int err;
1123 fuse_log(FUSE_LOG_DEBUG, "lo_lookup(parent=%" PRIu64 ", name=%s)\n", parent,
1124 name);
1126 if (is_empty(name)) {
1127 fuse_reply_err(req, ENOENT);
1128 return;
1132 * Don't use is_safe_path_component(), allow "." and ".." for NFS export
1133 * support.
1135 if (strchr(name, '/')) {
1136 fuse_reply_err(req, EINVAL);
1137 return;
1140 err = lo_do_lookup(req, parent, name, &e, NULL);
1141 if (err) {
1142 fuse_reply_err(req, err);
1143 } else {
1144 fuse_reply_entry(req, &e);
1149 * On some archs, setres*id is limited to 2^16 but they
1150 * provide setres*id32 variants that allow 2^32.
1151 * Others just let setres*id do 2^32 anyway.
1153 #ifdef SYS_setresgid32
1154 #define OURSYS_setresgid SYS_setresgid32
1155 #else
1156 #define OURSYS_setresgid SYS_setresgid
1157 #endif
1159 #ifdef SYS_setresuid32
1160 #define OURSYS_setresuid SYS_setresuid32
1161 #else
1162 #define OURSYS_setresuid SYS_setresuid
1163 #endif
1165 static void drop_supplementary_groups(void)
1167 int ret;
1169 ret = getgroups(0, NULL);
1170 if (ret == -1) {
1171 fuse_log(FUSE_LOG_ERR, "getgroups() failed with error=%d:%s\n",
1172 errno, strerror(errno));
1173 exit(1);
1176 if (!ret) {
1177 return;
1180 /* Drop all supplementary groups. We should not need it */
1181 ret = setgroups(0, NULL);
1182 if (ret == -1) {
1183 fuse_log(FUSE_LOG_ERR, "setgroups() failed with error=%d:%s\n",
1184 errno, strerror(errno));
1185 exit(1);
1190 * Change to uid/gid of caller so that file is created with
1191 * ownership of caller.
1192 * TODO: What about selinux context?
1194 static int lo_change_cred(fuse_req_t req, struct lo_cred *old,
1195 bool change_umask)
1197 int res;
1199 old->euid = geteuid();
1200 old->egid = getegid();
1202 res = syscall(OURSYS_setresgid, -1, fuse_req_ctx(req)->gid, -1);
1203 if (res == -1) {
1204 return errno;
1207 res = syscall(OURSYS_setresuid, -1, fuse_req_ctx(req)->uid, -1);
1208 if (res == -1) {
1209 int errno_save = errno;
1211 syscall(OURSYS_setresgid, -1, old->egid, -1);
1212 return errno_save;
1215 if (change_umask) {
1216 old->umask = umask(req->ctx.umask);
1218 return 0;
1221 /* Regain Privileges */
1222 static void lo_restore_cred(struct lo_cred *old, bool restore_umask)
1224 int res;
1226 res = syscall(OURSYS_setresuid, -1, old->euid, -1);
1227 if (res == -1) {
1228 fuse_log(FUSE_LOG_ERR, "seteuid(%u): %m\n", old->euid);
1229 exit(1);
1232 res = syscall(OURSYS_setresgid, -1, old->egid, -1);
1233 if (res == -1) {
1234 fuse_log(FUSE_LOG_ERR, "setegid(%u): %m\n", old->egid);
1235 exit(1);
1238 if (restore_umask)
1239 umask(old->umask);
1243 * A helper to change cred and drop capability. Returns 0 on success and
1244 * errno on error
1246 static int lo_drop_cap_change_cred(fuse_req_t req, struct lo_cred *old,
1247 bool change_umask, const char *cap_name,
1248 bool *cap_dropped)
1250 int ret;
1251 bool __cap_dropped;
1253 assert(cap_name);
1255 ret = drop_effective_cap(cap_name, &__cap_dropped);
1256 if (ret) {
1257 return ret;
1260 ret = lo_change_cred(req, old, change_umask);
1261 if (ret) {
1262 if (__cap_dropped) {
1263 if (gain_effective_cap(cap_name)) {
1264 fuse_log(FUSE_LOG_ERR, "Failed to gain CAP_%s\n", cap_name);
1269 if (cap_dropped) {
1270 *cap_dropped = __cap_dropped;
1272 return ret;
1275 static void lo_restore_cred_gain_cap(struct lo_cred *old, bool restore_umask,
1276 const char *cap_name)
1278 assert(cap_name);
1280 lo_restore_cred(old, restore_umask);
1282 if (gain_effective_cap(cap_name)) {
1283 fuse_log(FUSE_LOG_ERR, "Failed to gain CAP_%s\n", cap_name);
1287 static void lo_mknod_symlink(fuse_req_t req, fuse_ino_t parent,
1288 const char *name, mode_t mode, dev_t rdev,
1289 const char *link)
1291 int res;
1292 int saverr;
1293 struct lo_data *lo = lo_data(req);
1294 struct lo_inode *dir;
1295 struct fuse_entry_param e;
1296 struct lo_cred old = {};
1298 if (is_empty(name)) {
1299 fuse_reply_err(req, ENOENT);
1300 return;
1303 if (!is_safe_path_component(name)) {
1304 fuse_reply_err(req, EINVAL);
1305 return;
1308 dir = lo_inode(req, parent);
1309 if (!dir) {
1310 fuse_reply_err(req, EBADF);
1311 return;
1314 saverr = lo_change_cred(req, &old, lo->change_umask && !S_ISLNK(mode));
1315 if (saverr) {
1316 goto out;
1319 res = mknod_wrapper(dir->fd, name, link, mode, rdev);
1321 saverr = errno;
1323 lo_restore_cred(&old, lo->change_umask && !S_ISLNK(mode));
1325 if (res == -1) {
1326 goto out;
1329 saverr = lo_do_lookup(req, parent, name, &e, NULL);
1330 if (saverr) {
1331 goto out;
1334 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
1335 name, (unsigned long long)e.ino);
1337 fuse_reply_entry(req, &e);
1338 lo_inode_put(lo, &dir);
1339 return;
1341 out:
1342 lo_inode_put(lo, &dir);
1343 fuse_reply_err(req, saverr);
1346 static void lo_mknod(fuse_req_t req, fuse_ino_t parent, const char *name,
1347 mode_t mode, dev_t rdev)
1349 lo_mknod_symlink(req, parent, name, mode, rdev, NULL);
1352 static void lo_mkdir(fuse_req_t req, fuse_ino_t parent, const char *name,
1353 mode_t mode)
1355 lo_mknod_symlink(req, parent, name, S_IFDIR | mode, 0, NULL);
1358 static void lo_symlink(fuse_req_t req, const char *link, fuse_ino_t parent,
1359 const char *name)
1361 lo_mknod_symlink(req, parent, name, S_IFLNK, 0, link);
1364 static void lo_link(fuse_req_t req, fuse_ino_t ino, fuse_ino_t parent,
1365 const char *name)
1367 int res;
1368 struct lo_data *lo = lo_data(req);
1369 struct lo_inode *parent_inode;
1370 struct lo_inode *inode;
1371 struct fuse_entry_param e;
1372 char procname[64];
1373 int saverr;
1375 if (is_empty(name)) {
1376 fuse_reply_err(req, ENOENT);
1377 return;
1380 if (!is_safe_path_component(name)) {
1381 fuse_reply_err(req, EINVAL);
1382 return;
1385 parent_inode = lo_inode(req, parent);
1386 inode = lo_inode(req, ino);
1387 if (!parent_inode || !inode) {
1388 errno = EBADF;
1389 goto out_err;
1392 memset(&e, 0, sizeof(struct fuse_entry_param));
1393 e.attr_timeout = lo->timeout;
1394 e.entry_timeout = lo->timeout;
1396 sprintf(procname, "%i", inode->fd);
1397 res = linkat(lo->proc_self_fd, procname, parent_inode->fd, name,
1398 AT_SYMLINK_FOLLOW);
1399 if (res == -1) {
1400 goto out_err;
1403 res = fstatat(inode->fd, "", &e.attr, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW);
1404 if (res == -1) {
1405 goto out_err;
1408 pthread_mutex_lock(&lo->mutex);
1409 inode->nlookup++;
1410 pthread_mutex_unlock(&lo->mutex);
1411 e.ino = inode->fuse_ino;
1413 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
1414 name, (unsigned long long)e.ino);
1416 fuse_reply_entry(req, &e);
1417 lo_inode_put(lo, &parent_inode);
1418 lo_inode_put(lo, &inode);
1419 return;
1421 out_err:
1422 saverr = errno;
1423 lo_inode_put(lo, &parent_inode);
1424 lo_inode_put(lo, &inode);
1425 fuse_reply_err(req, saverr);
1428 /* Increments nlookup and caller must release refcount using lo_inode_put() */
1429 static struct lo_inode *lookup_name(fuse_req_t req, fuse_ino_t parent,
1430 const char *name)
1432 int res;
1433 uint64_t mnt_id;
1434 struct stat attr;
1435 struct lo_data *lo = lo_data(req);
1436 struct lo_inode *dir = lo_inode(req, parent);
1438 if (!dir) {
1439 return NULL;
1442 res = do_statx(lo, dir->fd, name, &attr, AT_SYMLINK_NOFOLLOW, &mnt_id);
1443 lo_inode_put(lo, &dir);
1444 if (res == -1) {
1445 return NULL;
1448 return lo_find(lo, &attr, mnt_id);
1451 static void lo_rmdir(fuse_req_t req, fuse_ino_t parent, const char *name)
1453 int res;
1454 struct lo_inode *inode;
1455 struct lo_data *lo = lo_data(req);
1457 if (is_empty(name)) {
1458 fuse_reply_err(req, ENOENT);
1459 return;
1462 if (!is_safe_path_component(name)) {
1463 fuse_reply_err(req, EINVAL);
1464 return;
1467 inode = lookup_name(req, parent, name);
1468 if (!inode) {
1469 fuse_reply_err(req, EIO);
1470 return;
1473 res = unlinkat(lo_fd(req, parent), name, AT_REMOVEDIR);
1475 fuse_reply_err(req, res == -1 ? errno : 0);
1476 unref_inode_lolocked(lo, inode, 1);
1477 lo_inode_put(lo, &inode);
1480 static void lo_rename(fuse_req_t req, fuse_ino_t parent, const char *name,
1481 fuse_ino_t newparent, const char *newname,
1482 unsigned int flags)
1484 int res;
1485 struct lo_inode *parent_inode;
1486 struct lo_inode *newparent_inode;
1487 struct lo_inode *oldinode = NULL;
1488 struct lo_inode *newinode = NULL;
1489 struct lo_data *lo = lo_data(req);
1491 if (is_empty(name) || is_empty(newname)) {
1492 fuse_reply_err(req, ENOENT);
1493 return;
1496 if (!is_safe_path_component(name) || !is_safe_path_component(newname)) {
1497 fuse_reply_err(req, EINVAL);
1498 return;
1501 parent_inode = lo_inode(req, parent);
1502 newparent_inode = lo_inode(req, newparent);
1503 if (!parent_inode || !newparent_inode) {
1504 fuse_reply_err(req, EBADF);
1505 goto out;
1508 oldinode = lookup_name(req, parent, name);
1509 newinode = lookup_name(req, newparent, newname);
1511 if (!oldinode) {
1512 fuse_reply_err(req, EIO);
1513 goto out;
1516 if (flags) {
1517 #ifndef SYS_renameat2
1518 fuse_reply_err(req, EINVAL);
1519 #else
1520 res = syscall(SYS_renameat2, parent_inode->fd, name,
1521 newparent_inode->fd, newname, flags);
1522 if (res == -1 && errno == ENOSYS) {
1523 fuse_reply_err(req, EINVAL);
1524 } else {
1525 fuse_reply_err(req, res == -1 ? errno : 0);
1527 #endif
1528 goto out;
1531 res = renameat(parent_inode->fd, name, newparent_inode->fd, newname);
1533 fuse_reply_err(req, res == -1 ? errno : 0);
1534 out:
1535 unref_inode_lolocked(lo, oldinode, 1);
1536 unref_inode_lolocked(lo, newinode, 1);
1537 lo_inode_put(lo, &oldinode);
1538 lo_inode_put(lo, &newinode);
1539 lo_inode_put(lo, &parent_inode);
1540 lo_inode_put(lo, &newparent_inode);
1543 static void lo_unlink(fuse_req_t req, fuse_ino_t parent, const char *name)
1545 int res;
1546 struct lo_inode *inode;
1547 struct lo_data *lo = lo_data(req);
1549 if (is_empty(name)) {
1550 fuse_reply_err(req, ENOENT);
1551 return;
1554 if (!is_safe_path_component(name)) {
1555 fuse_reply_err(req, EINVAL);
1556 return;
1559 inode = lookup_name(req, parent, name);
1560 if (!inode) {
1561 fuse_reply_err(req, EIO);
1562 return;
1565 res = unlinkat(lo_fd(req, parent), name, 0);
1567 fuse_reply_err(req, res == -1 ? errno : 0);
1568 unref_inode_lolocked(lo, inode, 1);
1569 lo_inode_put(lo, &inode);
1572 /* To be called with lo->mutex held */
1573 static void unref_inode(struct lo_data *lo, struct lo_inode *inode, uint64_t n)
1575 if (!inode) {
1576 return;
1579 assert(inode->nlookup >= n);
1580 inode->nlookup -= n;
1581 if (!inode->nlookup) {
1582 lo_map_remove(&lo->ino_map, inode->fuse_ino);
1583 g_hash_table_remove(lo->inodes, &inode->key);
1584 if (lo->posix_lock) {
1585 if (g_hash_table_size(inode->posix_locks)) {
1586 fuse_log(FUSE_LOG_WARNING, "Hash table is not empty\n");
1588 g_hash_table_destroy(inode->posix_locks);
1589 pthread_mutex_destroy(&inode->plock_mutex);
1591 /* Drop our refcount from lo_do_lookup() */
1592 lo_inode_put(lo, &inode);
1596 static void unref_inode_lolocked(struct lo_data *lo, struct lo_inode *inode,
1597 uint64_t n)
1599 if (!inode) {
1600 return;
1603 pthread_mutex_lock(&lo->mutex);
1604 unref_inode(lo, inode, n);
1605 pthread_mutex_unlock(&lo->mutex);
1608 static void lo_forget_one(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup)
1610 struct lo_data *lo = lo_data(req);
1611 struct lo_inode *inode;
1613 inode = lo_inode(req, ino);
1614 if (!inode) {
1615 return;
1618 fuse_log(FUSE_LOG_DEBUG, " forget %lli %lli -%lli\n",
1619 (unsigned long long)ino, (unsigned long long)inode->nlookup,
1620 (unsigned long long)nlookup);
1622 unref_inode_lolocked(lo, inode, nlookup);
1623 lo_inode_put(lo, &inode);
1626 static void lo_forget(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup)
1628 lo_forget_one(req, ino, nlookup);
1629 fuse_reply_none(req);
1632 static void lo_forget_multi(fuse_req_t req, size_t count,
1633 struct fuse_forget_data *forgets)
1635 int i;
1637 for (i = 0; i < count; i++) {
1638 lo_forget_one(req, forgets[i].ino, forgets[i].nlookup);
1640 fuse_reply_none(req);
1643 static void lo_readlink(fuse_req_t req, fuse_ino_t ino)
1645 char buf[PATH_MAX + 1];
1646 int res;
1648 res = readlinkat(lo_fd(req, ino), "", buf, sizeof(buf));
1649 if (res == -1) {
1650 return (void)fuse_reply_err(req, errno);
1653 if (res == sizeof(buf)) {
1654 return (void)fuse_reply_err(req, ENAMETOOLONG);
1657 buf[res] = '\0';
1659 fuse_reply_readlink(req, buf);
1662 struct lo_dirp {
1663 gint refcount;
1664 DIR *dp;
1665 struct dirent *entry;
1666 off_t offset;
1669 static void lo_dirp_put(struct lo_dirp **dp)
1671 struct lo_dirp *d = *dp;
1673 if (!d) {
1674 return;
1676 *dp = NULL;
1678 if (g_atomic_int_dec_and_test(&d->refcount)) {
1679 closedir(d->dp);
1680 free(d);
1684 /* Call lo_dirp_put() on the return value when no longer needed */
1685 static struct lo_dirp *lo_dirp(fuse_req_t req, struct fuse_file_info *fi)
1687 struct lo_data *lo = lo_data(req);
1688 struct lo_map_elem *elem;
1690 pthread_mutex_lock(&lo->mutex);
1691 elem = lo_map_get(&lo->dirp_map, fi->fh);
1692 if (elem) {
1693 g_atomic_int_inc(&elem->dirp->refcount);
1695 pthread_mutex_unlock(&lo->mutex);
1696 if (!elem) {
1697 return NULL;
1700 return elem->dirp;
1703 static void lo_opendir(fuse_req_t req, fuse_ino_t ino,
1704 struct fuse_file_info *fi)
1706 int error = ENOMEM;
1707 struct lo_data *lo = lo_data(req);
1708 struct lo_dirp *d;
1709 int fd;
1710 ssize_t fh;
1712 d = calloc(1, sizeof(struct lo_dirp));
1713 if (d == NULL) {
1714 goto out_err;
1717 fd = openat(lo_fd(req, ino), ".", O_RDONLY);
1718 if (fd == -1) {
1719 goto out_errno;
1722 d->dp = fdopendir(fd);
1723 if (d->dp == NULL) {
1724 goto out_errno;
1727 d->offset = 0;
1728 d->entry = NULL;
1730 g_atomic_int_set(&d->refcount, 1); /* paired with lo_releasedir() */
1731 pthread_mutex_lock(&lo->mutex);
1732 fh = lo_add_dirp_mapping(req, d);
1733 pthread_mutex_unlock(&lo->mutex);
1734 if (fh == -1) {
1735 goto out_err;
1738 fi->fh = fh;
1739 if (lo->cache == CACHE_ALWAYS) {
1740 fi->cache_readdir = 1;
1742 fuse_reply_open(req, fi);
1743 return;
1745 out_errno:
1746 error = errno;
1747 out_err:
1748 if (d) {
1749 if (d->dp) {
1750 closedir(d->dp);
1751 } else if (fd != -1) {
1752 close(fd);
1754 free(d);
1756 fuse_reply_err(req, error);
1759 static void lo_do_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
1760 off_t offset, struct fuse_file_info *fi, int plus)
1762 struct lo_data *lo = lo_data(req);
1763 struct lo_dirp *d = NULL;
1764 struct lo_inode *dinode;
1765 g_autofree char *buf = NULL;
1766 char *p;
1767 size_t rem = size;
1768 int err = EBADF;
1770 dinode = lo_inode(req, ino);
1771 if (!dinode) {
1772 goto error;
1775 d = lo_dirp(req, fi);
1776 if (!d) {
1777 goto error;
1780 err = ENOMEM;
1781 buf = g_try_malloc0(size);
1782 if (!buf) {
1783 goto error;
1785 p = buf;
1787 if (offset != d->offset) {
1788 seekdir(d->dp, offset);
1789 d->entry = NULL;
1790 d->offset = offset;
1792 while (1) {
1793 size_t entsize;
1794 off_t nextoff;
1795 const char *name;
1797 if (!d->entry) {
1798 errno = 0;
1799 d->entry = readdir(d->dp);
1800 if (!d->entry) {
1801 if (errno) { /* Error */
1802 err = errno;
1803 goto error;
1804 } else { /* End of stream */
1805 break;
1809 nextoff = d->entry->d_off;
1810 name = d->entry->d_name;
1812 fuse_ino_t entry_ino = 0;
1813 struct fuse_entry_param e = (struct fuse_entry_param){
1814 .attr.st_ino = d->entry->d_ino,
1815 .attr.st_mode = d->entry->d_type << 12,
1818 /* Hide root's parent directory */
1819 if (dinode == &lo->root && strcmp(name, "..") == 0) {
1820 e.attr.st_ino = lo->root.key.ino;
1821 e.attr.st_mode = DT_DIR << 12;
1824 if (plus) {
1825 if (!is_dot_or_dotdot(name)) {
1826 err = lo_do_lookup(req, ino, name, &e, NULL);
1827 if (err) {
1828 goto error;
1830 entry_ino = e.ino;
1833 entsize = fuse_add_direntry_plus(req, p, rem, name, &e, nextoff);
1834 } else {
1835 entsize = fuse_add_direntry(req, p, rem, name, &e.attr, nextoff);
1837 if (entsize > rem) {
1838 if (entry_ino != 0) {
1839 lo_forget_one(req, entry_ino, 1);
1841 break;
1844 p += entsize;
1845 rem -= entsize;
1847 d->entry = NULL;
1848 d->offset = nextoff;
1851 err = 0;
1852 error:
1853 lo_dirp_put(&d);
1854 lo_inode_put(lo, &dinode);
1857 * If there's an error, we can only signal it if we haven't stored
1858 * any entries yet - otherwise we'd end up with wrong lookup
1859 * counts for the entries that are already in the buffer. So we
1860 * return what we've collected until that point.
1862 if (err && rem == size) {
1863 fuse_reply_err(req, err);
1864 } else {
1865 fuse_reply_buf(req, buf, size - rem);
1869 static void lo_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
1870 off_t offset, struct fuse_file_info *fi)
1872 lo_do_readdir(req, ino, size, offset, fi, 0);
1875 static void lo_readdirplus(fuse_req_t req, fuse_ino_t ino, size_t size,
1876 off_t offset, struct fuse_file_info *fi)
1878 lo_do_readdir(req, ino, size, offset, fi, 1);
1881 static void lo_releasedir(fuse_req_t req, fuse_ino_t ino,
1882 struct fuse_file_info *fi)
1884 struct lo_data *lo = lo_data(req);
1885 struct lo_map_elem *elem;
1886 struct lo_dirp *d;
1888 (void)ino;
1890 pthread_mutex_lock(&lo->mutex);
1891 elem = lo_map_get(&lo->dirp_map, fi->fh);
1892 if (!elem) {
1893 pthread_mutex_unlock(&lo->mutex);
1894 fuse_reply_err(req, EBADF);
1895 return;
1898 d = elem->dirp;
1899 lo_map_remove(&lo->dirp_map, fi->fh);
1900 pthread_mutex_unlock(&lo->mutex);
1902 lo_dirp_put(&d); /* paired with lo_opendir() */
1904 fuse_reply_err(req, 0);
1907 static void update_open_flags(int writeback, int allow_direct_io,
1908 struct fuse_file_info *fi)
1911 * With writeback cache, kernel may send read requests even
1912 * when userspace opened write-only
1914 if (writeback && (fi->flags & O_ACCMODE) == O_WRONLY) {
1915 fi->flags &= ~O_ACCMODE;
1916 fi->flags |= O_RDWR;
1920 * With writeback cache, O_APPEND is handled by the kernel.
1921 * This breaks atomicity (since the file may change in the
1922 * underlying filesystem, so that the kernel's idea of the
1923 * end of the file isn't accurate anymore). In this example,
1924 * we just accept that. A more rigorous filesystem may want
1925 * to return an error here
1927 if (writeback && (fi->flags & O_APPEND)) {
1928 fi->flags &= ~O_APPEND;
1932 * O_DIRECT in guest should not necessarily mean bypassing page
1933 * cache on host as well. Therefore, we discard it by default
1934 * ('-o no_allow_direct_io'). If somebody needs that behavior,
1935 * the '-o allow_direct_io' option should be set.
1937 if (!allow_direct_io) {
1938 fi->flags &= ~O_DIRECT;
1943 * Open a regular file, set up an fd mapping, and fill out the struct
1944 * fuse_file_info for it. If existing_fd is not negative, use that fd instead
1945 * opening a new one. Takes ownership of existing_fd.
1947 * Returns 0 on success or a positive errno.
1949 static int lo_do_open(struct lo_data *lo, struct lo_inode *inode,
1950 int existing_fd, struct fuse_file_info *fi)
1952 ssize_t fh;
1953 int fd = existing_fd;
1954 int err;
1955 bool cap_fsetid_dropped = false;
1956 bool kill_suidgid = lo->killpriv_v2 && fi->kill_priv;
1958 update_open_flags(lo->writeback, lo->allow_direct_io, fi);
1960 if (fd < 0) {
1961 if (kill_suidgid) {
1962 err = drop_effective_cap("FSETID", &cap_fsetid_dropped);
1963 if (err) {
1964 return err;
1968 fd = lo_inode_open(lo, inode, fi->flags);
1970 if (cap_fsetid_dropped) {
1971 if (gain_effective_cap("FSETID")) {
1972 fuse_log(FUSE_LOG_ERR, "Failed to gain CAP_FSETID\n");
1975 if (fd < 0) {
1976 return -fd;
1978 if (fi->flags & (O_TRUNC)) {
1979 int err = drop_security_capability(lo, fd);
1980 if (err) {
1981 close(fd);
1982 return err;
1987 pthread_mutex_lock(&lo->mutex);
1988 fh = lo_add_fd_mapping(lo, fd);
1989 pthread_mutex_unlock(&lo->mutex);
1990 if (fh == -1) {
1991 close(fd);
1992 return ENOMEM;
1995 fi->fh = fh;
1996 if (lo->cache == CACHE_NONE) {
1997 fi->direct_io = 1;
1998 } else if (lo->cache == CACHE_ALWAYS) {
1999 fi->keep_cache = 1;
2001 return 0;
2004 static void lo_create(fuse_req_t req, fuse_ino_t parent, const char *name,
2005 mode_t mode, struct fuse_file_info *fi)
2007 int fd = -1;
2008 struct lo_data *lo = lo_data(req);
2009 struct lo_inode *parent_inode;
2010 struct lo_inode *inode = NULL;
2011 struct fuse_entry_param e;
2012 int err;
2013 struct lo_cred old = {};
2015 fuse_log(FUSE_LOG_DEBUG, "lo_create(parent=%" PRIu64 ", name=%s)"
2016 " kill_priv=%d\n", parent, name, fi->kill_priv);
2018 if (!is_safe_path_component(name)) {
2019 fuse_reply_err(req, EINVAL);
2020 return;
2023 parent_inode = lo_inode(req, parent);
2024 if (!parent_inode) {
2025 fuse_reply_err(req, EBADF);
2026 return;
2029 err = lo_change_cred(req, &old, lo->change_umask);
2030 if (err) {
2031 goto out;
2034 update_open_flags(lo->writeback, lo->allow_direct_io, fi);
2036 /* Try to create a new file but don't open existing files */
2037 fd = openat(parent_inode->fd, name, fi->flags | O_CREAT | O_EXCL, mode);
2038 err = fd == -1 ? errno : 0;
2040 lo_restore_cred(&old, lo->change_umask);
2042 /* Ignore the error if file exists and O_EXCL was not given */
2043 if (err && (err != EEXIST || (fi->flags & O_EXCL))) {
2044 goto out;
2047 err = lo_do_lookup(req, parent, name, &e, &inode);
2048 if (err) {
2049 goto out;
2052 err = lo_do_open(lo, inode, fd, fi);
2053 fd = -1; /* lo_do_open() takes ownership of fd */
2054 if (err) {
2055 /* Undo lo_do_lookup() nlookup ref */
2056 unref_inode_lolocked(lo, inode, 1);
2059 out:
2060 lo_inode_put(lo, &inode);
2061 lo_inode_put(lo, &parent_inode);
2063 if (err) {
2064 if (fd >= 0) {
2065 close(fd);
2068 fuse_reply_err(req, err);
2069 } else {
2070 fuse_reply_create(req, &e, fi);
2074 /* Should be called with inode->plock_mutex held */
2075 static struct lo_inode_plock *lookup_create_plock_ctx(struct lo_data *lo,
2076 struct lo_inode *inode,
2077 uint64_t lock_owner,
2078 pid_t pid, int *err)
2080 struct lo_inode_plock *plock;
2081 int fd;
2083 plock =
2084 g_hash_table_lookup(inode->posix_locks, GUINT_TO_POINTER(lock_owner));
2086 if (plock) {
2087 return plock;
2090 plock = malloc(sizeof(struct lo_inode_plock));
2091 if (!plock) {
2092 *err = ENOMEM;
2093 return NULL;
2096 /* Open another instance of file which can be used for ofd locks. */
2097 /* TODO: What if file is not writable? */
2098 fd = lo_inode_open(lo, inode, O_RDWR);
2099 if (fd < 0) {
2100 *err = -fd;
2101 free(plock);
2102 return NULL;
2105 plock->lock_owner = lock_owner;
2106 plock->fd = fd;
2107 g_hash_table_insert(inode->posix_locks, GUINT_TO_POINTER(plock->lock_owner),
2108 plock);
2109 return plock;
2112 static void lo_getlk(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
2113 struct flock *lock)
2115 struct lo_data *lo = lo_data(req);
2116 struct lo_inode *inode;
2117 struct lo_inode_plock *plock;
2118 int ret, saverr = 0;
2120 fuse_log(FUSE_LOG_DEBUG,
2121 "lo_getlk(ino=%" PRIu64 ", flags=%d)"
2122 " owner=0x%" PRIx64 ", l_type=%d l_start=0x%" PRIx64
2123 " l_len=0x%" PRIx64 "\n",
2124 ino, fi->flags, fi->lock_owner, lock->l_type,
2125 (uint64_t)lock->l_start, (uint64_t)lock->l_len);
2127 if (!lo->posix_lock) {
2128 fuse_reply_err(req, ENOSYS);
2129 return;
2132 inode = lo_inode(req, ino);
2133 if (!inode) {
2134 fuse_reply_err(req, EBADF);
2135 return;
2138 pthread_mutex_lock(&inode->plock_mutex);
2139 plock =
2140 lookup_create_plock_ctx(lo, inode, fi->lock_owner, lock->l_pid, &ret);
2141 if (!plock) {
2142 saverr = ret;
2143 goto out;
2146 ret = fcntl(plock->fd, F_OFD_GETLK, lock);
2147 if (ret == -1) {
2148 saverr = errno;
2151 out:
2152 pthread_mutex_unlock(&inode->plock_mutex);
2153 lo_inode_put(lo, &inode);
2155 if (saverr) {
2156 fuse_reply_err(req, saverr);
2157 } else {
2158 fuse_reply_lock(req, lock);
2162 static void lo_setlk(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
2163 struct flock *lock, int sleep)
2165 struct lo_data *lo = lo_data(req);
2166 struct lo_inode *inode;
2167 struct lo_inode_plock *plock;
2168 int ret, saverr = 0;
2170 fuse_log(FUSE_LOG_DEBUG,
2171 "lo_setlk(ino=%" PRIu64 ", flags=%d)"
2172 " cmd=%d pid=%d owner=0x%" PRIx64 " sleep=%d l_whence=%d"
2173 " l_start=0x%" PRIx64 " l_len=0x%" PRIx64 "\n",
2174 ino, fi->flags, lock->l_type, lock->l_pid, fi->lock_owner, sleep,
2175 lock->l_whence, (uint64_t)lock->l_start, (uint64_t)lock->l_len);
2177 if (!lo->posix_lock) {
2178 fuse_reply_err(req, ENOSYS);
2179 return;
2182 if (sleep) {
2183 fuse_reply_err(req, EOPNOTSUPP);
2184 return;
2187 inode = lo_inode(req, ino);
2188 if (!inode) {
2189 fuse_reply_err(req, EBADF);
2190 return;
2193 pthread_mutex_lock(&inode->plock_mutex);
2194 plock =
2195 lookup_create_plock_ctx(lo, inode, fi->lock_owner, lock->l_pid, &ret);
2197 if (!plock) {
2198 saverr = ret;
2199 goto out;
2202 /* TODO: Is it alright to modify flock? */
2203 lock->l_pid = 0;
2204 ret = fcntl(plock->fd, F_OFD_SETLK, lock);
2205 if (ret == -1) {
2206 saverr = errno;
2209 out:
2210 pthread_mutex_unlock(&inode->plock_mutex);
2211 lo_inode_put(lo, &inode);
2213 fuse_reply_err(req, saverr);
2216 static void lo_fsyncdir(fuse_req_t req, fuse_ino_t ino, int datasync,
2217 struct fuse_file_info *fi)
2219 int res;
2220 struct lo_dirp *d;
2221 int fd;
2223 (void)ino;
2225 d = lo_dirp(req, fi);
2226 if (!d) {
2227 fuse_reply_err(req, EBADF);
2228 return;
2231 fd = dirfd(d->dp);
2232 if (datasync) {
2233 res = fdatasync(fd);
2234 } else {
2235 res = fsync(fd);
2238 lo_dirp_put(&d);
2240 fuse_reply_err(req, res == -1 ? errno : 0);
2243 static void lo_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi)
2245 struct lo_data *lo = lo_data(req);
2246 struct lo_inode *inode = lo_inode(req, ino);
2247 int err;
2249 fuse_log(FUSE_LOG_DEBUG, "lo_open(ino=%" PRIu64 ", flags=%d, kill_priv=%d)"
2250 "\n", ino, fi->flags, fi->kill_priv);
2252 if (!inode) {
2253 fuse_reply_err(req, EBADF);
2254 return;
2257 err = lo_do_open(lo, inode, -1, fi);
2258 lo_inode_put(lo, &inode);
2259 if (err) {
2260 fuse_reply_err(req, err);
2261 } else {
2262 fuse_reply_open(req, fi);
2266 static void lo_release(fuse_req_t req, fuse_ino_t ino,
2267 struct fuse_file_info *fi)
2269 struct lo_data *lo = lo_data(req);
2270 struct lo_map_elem *elem;
2271 int fd = -1;
2273 (void)ino;
2275 pthread_mutex_lock(&lo->mutex);
2276 elem = lo_map_get(&lo->fd_map, fi->fh);
2277 if (elem) {
2278 fd = elem->fd;
2279 elem = NULL;
2280 lo_map_remove(&lo->fd_map, fi->fh);
2282 pthread_mutex_unlock(&lo->mutex);
2284 close(fd);
2285 fuse_reply_err(req, 0);
2288 static void lo_flush(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi)
2290 int res;
2291 (void)ino;
2292 struct lo_inode *inode;
2293 struct lo_data *lo = lo_data(req);
2295 inode = lo_inode(req, ino);
2296 if (!inode) {
2297 fuse_reply_err(req, EBADF);
2298 return;
2301 if (!S_ISREG(inode->filetype)) {
2302 lo_inode_put(lo, &inode);
2303 fuse_reply_err(req, EBADF);
2304 return;
2307 /* An fd is going away. Cleanup associated posix locks */
2308 if (lo->posix_lock) {
2309 pthread_mutex_lock(&inode->plock_mutex);
2310 g_hash_table_remove(inode->posix_locks,
2311 GUINT_TO_POINTER(fi->lock_owner));
2312 pthread_mutex_unlock(&inode->plock_mutex);
2314 res = close(dup(lo_fi_fd(req, fi)));
2315 lo_inode_put(lo, &inode);
2316 fuse_reply_err(req, res == -1 ? errno : 0);
2319 static void lo_fsync(fuse_req_t req, fuse_ino_t ino, int datasync,
2320 struct fuse_file_info *fi)
2322 struct lo_inode *inode = lo_inode(req, ino);
2323 struct lo_data *lo = lo_data(req);
2324 int res;
2325 int fd;
2327 fuse_log(FUSE_LOG_DEBUG, "lo_fsync(ino=%" PRIu64 ", fi=0x%p)\n", ino,
2328 (void *)fi);
2330 if (!inode) {
2331 fuse_reply_err(req, EBADF);
2332 return;
2335 if (!fi) {
2336 fd = lo_inode_open(lo, inode, O_RDWR);
2337 if (fd < 0) {
2338 res = -fd;
2339 goto out;
2341 } else {
2342 fd = lo_fi_fd(req, fi);
2345 if (datasync) {
2346 res = fdatasync(fd) == -1 ? errno : 0;
2347 } else {
2348 res = fsync(fd) == -1 ? errno : 0;
2350 if (!fi) {
2351 close(fd);
2353 out:
2354 lo_inode_put(lo, &inode);
2355 fuse_reply_err(req, res);
2358 static void lo_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t offset,
2359 struct fuse_file_info *fi)
2361 struct fuse_bufvec buf = FUSE_BUFVEC_INIT(size);
2363 fuse_log(FUSE_LOG_DEBUG,
2364 "lo_read(ino=%" PRIu64 ", size=%zd, "
2365 "off=%lu)\n",
2366 ino, size, (unsigned long)offset);
2368 buf.buf[0].flags = FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK;
2369 buf.buf[0].fd = lo_fi_fd(req, fi);
2370 buf.buf[0].pos = offset;
2372 fuse_reply_data(req, &buf);
2375 static void lo_write_buf(fuse_req_t req, fuse_ino_t ino,
2376 struct fuse_bufvec *in_buf, off_t off,
2377 struct fuse_file_info *fi)
2379 (void)ino;
2380 ssize_t res;
2381 struct fuse_bufvec out_buf = FUSE_BUFVEC_INIT(fuse_buf_size(in_buf));
2382 bool cap_fsetid_dropped = false;
2384 out_buf.buf[0].flags = FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK;
2385 out_buf.buf[0].fd = lo_fi_fd(req, fi);
2386 out_buf.buf[0].pos = off;
2388 fuse_log(FUSE_LOG_DEBUG,
2389 "lo_write_buf(ino=%" PRIu64 ", size=%zd, off=%lu kill_priv=%d)\n",
2390 ino, out_buf.buf[0].size, (unsigned long)off, fi->kill_priv);
2392 res = drop_security_capability(lo_data(req), out_buf.buf[0].fd);
2393 if (res) {
2394 fuse_reply_err(req, res);
2395 return;
2399 * If kill_priv is set, drop CAP_FSETID which should lead to kernel
2400 * clearing setuid/setgid on file. Note, for WRITE, we need to do
2401 * this even if killpriv_v2 is not enabled. fuse direct write path
2402 * relies on this.
2404 if (fi->kill_priv) {
2405 res = drop_effective_cap("FSETID", &cap_fsetid_dropped);
2406 if (res != 0) {
2407 fuse_reply_err(req, res);
2408 return;
2412 res = fuse_buf_copy(&out_buf, in_buf);
2413 if (res < 0) {
2414 fuse_reply_err(req, -res);
2415 } else {
2416 fuse_reply_write(req, (size_t)res);
2419 if (cap_fsetid_dropped) {
2420 res = gain_effective_cap("FSETID");
2421 if (res) {
2422 fuse_log(FUSE_LOG_ERR, "Failed to gain CAP_FSETID\n");
2427 static void lo_statfs(fuse_req_t req, fuse_ino_t ino)
2429 int res;
2430 struct statvfs stbuf;
2432 res = fstatvfs(lo_fd(req, ino), &stbuf);
2433 if (res == -1) {
2434 fuse_reply_err(req, errno);
2435 } else {
2436 fuse_reply_statfs(req, &stbuf);
2440 static void lo_fallocate(fuse_req_t req, fuse_ino_t ino, int mode, off_t offset,
2441 off_t length, struct fuse_file_info *fi)
2443 int err = EOPNOTSUPP;
2444 (void)ino;
2446 #ifdef CONFIG_FALLOCATE
2447 err = fallocate(lo_fi_fd(req, fi), mode, offset, length);
2448 if (err < 0) {
2449 err = errno;
2452 #elif defined(CONFIG_POSIX_FALLOCATE)
2453 if (mode) {
2454 fuse_reply_err(req, EOPNOTSUPP);
2455 return;
2458 err = posix_fallocate(lo_fi_fd(req, fi), offset, length);
2459 #endif
2461 fuse_reply_err(req, err);
2464 static void lo_flock(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
2465 int op)
2467 int res;
2468 (void)ino;
2470 res = flock(lo_fi_fd(req, fi), op);
2472 fuse_reply_err(req, res == -1 ? errno : 0);
2475 /* types */
2477 * Exit; process attribute unmodified if matched.
2478 * An empty key applies to all.
2480 #define XATTR_MAP_FLAG_OK (1 << 0)
2482 * The attribute is unwanted;
2483 * EPERM on write, hidden on read.
2485 #define XATTR_MAP_FLAG_BAD (1 << 1)
2487 * For attr that start with 'key' prepend 'prepend'
2488 * 'key' may be empty to prepend for all attrs
2489 * key is defined from set/remove point of view.
2490 * Automatically reversed on read
2492 #define XATTR_MAP_FLAG_PREFIX (1 << 2)
2494 * The attribute is unsupported;
2495 * ENOTSUP on write, hidden on read.
2497 #define XATTR_MAP_FLAG_UNSUPPORTED (1 << 3)
2499 /* scopes */
2500 /* Apply rule to get/set/remove */
2501 #define XATTR_MAP_FLAG_CLIENT (1 << 16)
2502 /* Apply rule to list */
2503 #define XATTR_MAP_FLAG_SERVER (1 << 17)
2504 /* Apply rule to all */
2505 #define XATTR_MAP_FLAG_ALL (XATTR_MAP_FLAG_SERVER | XATTR_MAP_FLAG_CLIENT)
2507 static void add_xattrmap_entry(struct lo_data *lo,
2508 const XattrMapEntry *new_entry)
2510 XattrMapEntry *res = g_realloc_n(lo->xattr_map_list,
2511 lo->xattr_map_nentries + 1,
2512 sizeof(XattrMapEntry));
2513 res[lo->xattr_map_nentries++] = *new_entry;
2515 lo->xattr_map_list = res;
2518 static void free_xattrmap(struct lo_data *lo)
2520 XattrMapEntry *map = lo->xattr_map_list;
2521 size_t i;
2523 if (!map) {
2524 return;
2527 for (i = 0; i < lo->xattr_map_nentries; i++) {
2528 g_free(map[i].key);
2529 g_free(map[i].prepend);
2532 g_free(map);
2533 lo->xattr_map_list = NULL;
2534 lo->xattr_map_nentries = -1;
2538 * Handle the 'map' type, which is sugar for a set of commands
2539 * for the common case of prefixing a subset or everything,
2540 * and allowing anything not prefixed through.
2541 * It must be the last entry in the stream, although there
2542 * can be other entries before it.
2543 * The form is:
2544 * :map:key:prefix:
2546 * key maybe empty in which case all entries are prefixed.
2548 static void parse_xattrmap_map(struct lo_data *lo,
2549 const char *rule, char sep)
2551 const char *tmp;
2552 char *key;
2553 char *prefix;
2554 XattrMapEntry tmp_entry;
2556 if (*rule != sep) {
2557 fuse_log(FUSE_LOG_ERR,
2558 "%s: Expecting '%c' after 'map' keyword, found '%c'\n",
2559 __func__, sep, *rule);
2560 exit(1);
2563 rule++;
2565 /* At start of 'key' field */
2566 tmp = strchr(rule, sep);
2567 if (!tmp) {
2568 fuse_log(FUSE_LOG_ERR,
2569 "%s: Missing '%c' at end of key field in map rule\n",
2570 __func__, sep);
2571 exit(1);
2574 key = g_strndup(rule, tmp - rule);
2575 rule = tmp + 1;
2577 /* At start of prefix field */
2578 tmp = strchr(rule, sep);
2579 if (!tmp) {
2580 fuse_log(FUSE_LOG_ERR,
2581 "%s: Missing '%c' at end of prefix field in map rule\n",
2582 __func__, sep);
2583 exit(1);
2586 prefix = g_strndup(rule, tmp - rule);
2587 rule = tmp + 1;
2590 * This should be the end of the string, we don't allow
2591 * any more commands after 'map'.
2593 if (*rule) {
2594 fuse_log(FUSE_LOG_ERR,
2595 "%s: Expecting end of command after map, found '%c'\n",
2596 __func__, *rule);
2597 exit(1);
2600 /* 1st: Prefix matches/everything */
2601 tmp_entry.flags = XATTR_MAP_FLAG_PREFIX | XATTR_MAP_FLAG_ALL;
2602 tmp_entry.key = g_strdup(key);
2603 tmp_entry.prepend = g_strdup(prefix);
2604 add_xattrmap_entry(lo, &tmp_entry);
2606 if (!*key) {
2607 /* Prefix all case */
2609 /* 2nd: Hide any non-prefixed entries on the host */
2610 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_ALL;
2611 tmp_entry.key = g_strdup("");
2612 tmp_entry.prepend = g_strdup("");
2613 add_xattrmap_entry(lo, &tmp_entry);
2614 } else {
2615 /* Prefix matching case */
2617 /* 2nd: Hide non-prefixed but matching entries on the host */
2618 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_SERVER;
2619 tmp_entry.key = g_strdup(""); /* Not used */
2620 tmp_entry.prepend = g_strdup(key);
2621 add_xattrmap_entry(lo, &tmp_entry);
2623 /* 3rd: Stop the client accessing prefixed attributes directly */
2624 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_CLIENT;
2625 tmp_entry.key = g_strdup(prefix);
2626 tmp_entry.prepend = g_strdup(""); /* Not used */
2627 add_xattrmap_entry(lo, &tmp_entry);
2629 /* 4th: Everything else is OK */
2630 tmp_entry.flags = XATTR_MAP_FLAG_OK | XATTR_MAP_FLAG_ALL;
2631 tmp_entry.key = g_strdup("");
2632 tmp_entry.prepend = g_strdup("");
2633 add_xattrmap_entry(lo, &tmp_entry);
2636 g_free(key);
2637 g_free(prefix);
2640 static void parse_xattrmap(struct lo_data *lo)
2642 const char *map = lo->xattrmap;
2643 const char *tmp;
2644 int ret;
2646 lo->xattr_map_nentries = 0;
2647 while (*map) {
2648 XattrMapEntry tmp_entry;
2649 char sep;
2651 if (isspace(*map)) {
2652 map++;
2653 continue;
2655 /* The separator is the first non-space of the rule */
2656 sep = *map++;
2657 if (!sep) {
2658 break;
2661 tmp_entry.flags = 0;
2662 /* Start of 'type' */
2663 if (strstart(map, "prefix", &map)) {
2664 tmp_entry.flags |= XATTR_MAP_FLAG_PREFIX;
2665 } else if (strstart(map, "ok", &map)) {
2666 tmp_entry.flags |= XATTR_MAP_FLAG_OK;
2667 } else if (strstart(map, "bad", &map)) {
2668 tmp_entry.flags |= XATTR_MAP_FLAG_BAD;
2669 } else if (strstart(map, "unsupported", &map)) {
2670 tmp_entry.flags |= XATTR_MAP_FLAG_UNSUPPORTED;
2671 } else if (strstart(map, "map", &map)) {
2673 * map is sugar that adds a number of rules, and must be
2674 * the last entry.
2676 parse_xattrmap_map(lo, map, sep);
2677 break;
2678 } else {
2679 fuse_log(FUSE_LOG_ERR,
2680 "%s: Unexpected type;"
2681 "Expecting 'prefix', 'ok', 'bad', 'unsupported' or 'map'"
2682 " in rule %zu\n", __func__, lo->xattr_map_nentries);
2683 exit(1);
2686 if (*map++ != sep) {
2687 fuse_log(FUSE_LOG_ERR,
2688 "%s: Missing '%c' at end of type field of rule %zu\n",
2689 __func__, sep, lo->xattr_map_nentries);
2690 exit(1);
2693 /* Start of 'scope' */
2694 if (strstart(map, "client", &map)) {
2695 tmp_entry.flags |= XATTR_MAP_FLAG_CLIENT;
2696 } else if (strstart(map, "server", &map)) {
2697 tmp_entry.flags |= XATTR_MAP_FLAG_SERVER;
2698 } else if (strstart(map, "all", &map)) {
2699 tmp_entry.flags |= XATTR_MAP_FLAG_ALL;
2700 } else {
2701 fuse_log(FUSE_LOG_ERR,
2702 "%s: Unexpected scope;"
2703 " Expecting 'client', 'server', or 'all', in rule %zu\n",
2704 __func__, lo->xattr_map_nentries);
2705 exit(1);
2708 if (*map++ != sep) {
2709 fuse_log(FUSE_LOG_ERR,
2710 "%s: Expecting '%c' found '%c'"
2711 " after scope in rule %zu\n",
2712 __func__, sep, *map, lo->xattr_map_nentries);
2713 exit(1);
2716 /* At start of 'key' field */
2717 tmp = strchr(map, sep);
2718 if (!tmp) {
2719 fuse_log(FUSE_LOG_ERR,
2720 "%s: Missing '%c' at end of key field of rule %zu",
2721 __func__, sep, lo->xattr_map_nentries);
2722 exit(1);
2724 tmp_entry.key = g_strndup(map, tmp - map);
2725 map = tmp + 1;
2727 /* At start of 'prepend' field */
2728 tmp = strchr(map, sep);
2729 if (!tmp) {
2730 fuse_log(FUSE_LOG_ERR,
2731 "%s: Missing '%c' at end of prepend field of rule %zu",
2732 __func__, sep, lo->xattr_map_nentries);
2733 exit(1);
2735 tmp_entry.prepend = g_strndup(map, tmp - map);
2736 map = tmp + 1;
2738 add_xattrmap_entry(lo, &tmp_entry);
2739 /* End of rule - go around again for another rule */
2742 if (!lo->xattr_map_nentries) {
2743 fuse_log(FUSE_LOG_ERR, "Empty xattr map\n");
2744 exit(1);
2747 ret = xattr_map_client(lo, "security.capability",
2748 &lo->xattr_security_capability);
2749 if (ret) {
2750 fuse_log(FUSE_LOG_ERR, "Failed to map security.capability: %s\n",
2751 strerror(ret));
2752 exit(1);
2754 if (!lo->xattr_security_capability ||
2755 !strcmp(lo->xattr_security_capability, "security.capability")) {
2756 /* 1-1 mapping, don't need to do anything */
2757 free(lo->xattr_security_capability);
2758 lo->xattr_security_capability = NULL;
2763 * For use with getxattr/setxattr/removexattr, where the client
2764 * gives us a name and we may need to choose a different one.
2765 * Allocates a buffer for the result placing it in *out_name.
2766 * If there's no change then *out_name is not set.
2767 * Returns 0 on success
2768 * Can return -EPERM to indicate we block a given attribute
2769 * (in which case out_name is not allocated)
2770 * Can return -ENOMEM to indicate out_name couldn't be allocated.
2772 static int xattr_map_client(const struct lo_data *lo, const char *client_name,
2773 char **out_name)
2775 size_t i;
2776 for (i = 0; i < lo->xattr_map_nentries; i++) {
2777 const XattrMapEntry *cur_entry = lo->xattr_map_list + i;
2779 if ((cur_entry->flags & XATTR_MAP_FLAG_CLIENT) &&
2780 (strstart(client_name, cur_entry->key, NULL))) {
2781 if (cur_entry->flags & XATTR_MAP_FLAG_BAD) {
2782 return -EPERM;
2784 if (cur_entry->flags & XATTR_MAP_FLAG_UNSUPPORTED) {
2785 return -ENOTSUP;
2787 if (cur_entry->flags & XATTR_MAP_FLAG_OK) {
2788 /* Unmodified name */
2789 return 0;
2791 if (cur_entry->flags & XATTR_MAP_FLAG_PREFIX) {
2792 *out_name = g_try_malloc(strlen(client_name) +
2793 strlen(cur_entry->prepend) + 1);
2794 if (!*out_name) {
2795 return -ENOMEM;
2797 sprintf(*out_name, "%s%s", cur_entry->prepend, client_name);
2798 return 0;
2803 return -EPERM;
2807 * For use with listxattr where the server fs gives us a name and we may need
2808 * to sanitize this for the client.
2809 * Returns a pointer to the result in *out_name
2810 * This is always the original string or the current string with some prefix
2811 * removed; no reallocation is done.
2812 * Returns 0 on success
2813 * Can return -ENODATA to indicate the name should be dropped from the list.
2815 static int xattr_map_server(const struct lo_data *lo, const char *server_name,
2816 const char **out_name)
2818 size_t i;
2819 const char *end;
2821 for (i = 0; i < lo->xattr_map_nentries; i++) {
2822 const XattrMapEntry *cur_entry = lo->xattr_map_list + i;
2824 if ((cur_entry->flags & XATTR_MAP_FLAG_SERVER) &&
2825 (strstart(server_name, cur_entry->prepend, &end))) {
2826 if (cur_entry->flags & XATTR_MAP_FLAG_BAD ||
2827 cur_entry->flags & XATTR_MAP_FLAG_UNSUPPORTED) {
2828 return -ENODATA;
2830 if (cur_entry->flags & XATTR_MAP_FLAG_OK) {
2831 *out_name = server_name;
2832 return 0;
2834 if (cur_entry->flags & XATTR_MAP_FLAG_PREFIX) {
2835 /* Remove prefix */
2836 *out_name = end;
2837 return 0;
2842 return -ENODATA;
2845 #define FCHDIR_NOFAIL(fd) do { \
2846 int fchdir_res = fchdir(fd); \
2847 assert(fchdir_res == 0); \
2848 } while (0)
2850 static bool block_xattr(struct lo_data *lo, const char *name)
2853 * If user explicitly enabled posix_acl or did not provide any option,
2854 * do not block acl. Otherwise block system.posix_acl_access and
2855 * system.posix_acl_default xattrs.
2857 if (lo->user_posix_acl) {
2858 return false;
2860 if (!strcmp(name, "system.posix_acl_access") ||
2861 !strcmp(name, "system.posix_acl_default"))
2862 return true;
2864 return false;
2868 * Returns number of bytes in xattr_list after filtering on success. This
2869 * could be zero as well if nothing is left after filtering.
2871 * Returns negative error code on failure.
2872 * xattr_list is modified in place.
2874 static int remove_blocked_xattrs(struct lo_data *lo, char *xattr_list,
2875 unsigned in_size)
2877 size_t out_index, in_index;
2880 * As of now we only filter out acl xattrs. If acls are enabled or
2881 * they have not been explicitly disabled, there is nothing to
2882 * filter.
2884 if (lo->user_posix_acl) {
2885 return in_size;
2888 out_index = 0;
2889 in_index = 0;
2890 while (in_index < in_size) {
2891 char *in_ptr = xattr_list + in_index;
2893 /* Length of current attribute name */
2894 size_t in_len = strlen(xattr_list + in_index) + 1;
2896 if (!block_xattr(lo, in_ptr)) {
2897 if (in_index != out_index) {
2898 memmove(xattr_list + out_index, xattr_list + in_index, in_len);
2900 out_index += in_len;
2902 in_index += in_len;
2904 return out_index;
2907 static void lo_getxattr(fuse_req_t req, fuse_ino_t ino, const char *in_name,
2908 size_t size)
2910 struct lo_data *lo = lo_data(req);
2911 g_autofree char *value = NULL;
2912 char procname[64];
2913 const char *name;
2914 char *mapped_name;
2915 struct lo_inode *inode;
2916 ssize_t ret;
2917 int saverr;
2918 int fd = -1;
2920 if (block_xattr(lo, in_name)) {
2921 fuse_reply_err(req, EOPNOTSUPP);
2922 return;
2925 mapped_name = NULL;
2926 name = in_name;
2927 if (lo->xattrmap) {
2928 ret = xattr_map_client(lo, in_name, &mapped_name);
2929 if (ret < 0) {
2930 if (ret == -EPERM) {
2931 ret = -ENODATA;
2933 fuse_reply_err(req, -ret);
2934 return;
2936 if (mapped_name) {
2937 name = mapped_name;
2941 inode = lo_inode(req, ino);
2942 if (!inode) {
2943 fuse_reply_err(req, EBADF);
2944 g_free(mapped_name);
2945 return;
2948 saverr = ENOSYS;
2949 if (!lo_data(req)->xattr) {
2950 goto out;
2953 fuse_log(FUSE_LOG_DEBUG, "lo_getxattr(ino=%" PRIu64 ", name=%s size=%zd)\n",
2954 ino, name, size);
2956 if (size) {
2957 value = g_try_malloc(size);
2958 if (!value) {
2959 goto out_err;
2963 sprintf(procname, "%i", inode->fd);
2965 * It is not safe to open() non-regular/non-dir files in file server
2966 * unless O_PATH is used, so use that method for regular files/dir
2967 * only (as it seems giving less performance overhead).
2968 * Otherwise, call fchdir() to avoid open().
2970 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2971 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2972 if (fd < 0) {
2973 goto out_err;
2975 ret = fgetxattr(fd, name, value, size);
2976 saverr = ret == -1 ? errno : 0;
2977 } else {
2978 /* fchdir should not fail here */
2979 FCHDIR_NOFAIL(lo->proc_self_fd);
2980 ret = getxattr(procname, name, value, size);
2981 saverr = ret == -1 ? errno : 0;
2982 FCHDIR_NOFAIL(lo->root.fd);
2985 if (ret == -1) {
2986 goto out;
2988 if (size) {
2989 saverr = 0;
2990 if (ret == 0) {
2991 goto out;
2993 fuse_reply_buf(req, value, ret);
2994 } else {
2995 fuse_reply_xattr(req, ret);
2997 out_free:
2998 if (fd >= 0) {
2999 close(fd);
3002 lo_inode_put(lo, &inode);
3003 return;
3005 out_err:
3006 saverr = errno;
3007 out:
3008 fuse_reply_err(req, saverr);
3009 g_free(mapped_name);
3010 goto out_free;
3013 static void lo_listxattr(fuse_req_t req, fuse_ino_t ino, size_t size)
3015 struct lo_data *lo = lo_data(req);
3016 g_autofree char *value = NULL;
3017 char procname[64];
3018 struct lo_inode *inode;
3019 ssize_t ret;
3020 int saverr;
3021 int fd = -1;
3023 inode = lo_inode(req, ino);
3024 if (!inode) {
3025 fuse_reply_err(req, EBADF);
3026 return;
3029 saverr = ENOSYS;
3030 if (!lo_data(req)->xattr) {
3031 goto out;
3034 fuse_log(FUSE_LOG_DEBUG, "lo_listxattr(ino=%" PRIu64 ", size=%zd)\n", ino,
3035 size);
3037 if (size) {
3038 value = g_try_malloc(size);
3039 if (!value) {
3040 goto out_err;
3044 sprintf(procname, "%i", inode->fd);
3045 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
3046 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
3047 if (fd < 0) {
3048 goto out_err;
3050 ret = flistxattr(fd, value, size);
3051 saverr = ret == -1 ? errno : 0;
3052 } else {
3053 /* fchdir should not fail here */
3054 FCHDIR_NOFAIL(lo->proc_self_fd);
3055 ret = listxattr(procname, value, size);
3056 saverr = ret == -1 ? errno : 0;
3057 FCHDIR_NOFAIL(lo->root.fd);
3060 if (ret == -1) {
3061 goto out;
3063 if (size) {
3064 saverr = 0;
3065 if (ret == 0) {
3066 goto out;
3069 if (lo->xattr_map_list) {
3071 * Map the names back, some attributes might be dropped,
3072 * some shortened, but not increased, so we shouldn't
3073 * run out of room.
3075 size_t out_index, in_index;
3076 out_index = 0;
3077 in_index = 0;
3078 while (in_index < ret) {
3079 const char *map_out;
3080 char *in_ptr = value + in_index;
3081 /* Length of current attribute name */
3082 size_t in_len = strlen(value + in_index) + 1;
3084 int mapret = xattr_map_server(lo, in_ptr, &map_out);
3085 if (mapret != -ENODATA && mapret != 0) {
3086 /* Shouldn't happen */
3087 saverr = -mapret;
3088 goto out;
3090 if (mapret == 0) {
3091 /* Either unchanged, or truncated */
3092 size_t out_len;
3093 if (map_out != in_ptr) {
3094 /* +1 copies the NIL */
3095 out_len = strlen(map_out) + 1;
3096 } else {
3097 /* No change */
3098 out_len = in_len;
3101 * Move result along, may still be needed for an unchanged
3102 * entry if a previous entry was changed.
3104 memmove(value + out_index, map_out, out_len);
3106 out_index += out_len;
3108 in_index += in_len;
3110 ret = out_index;
3111 if (ret == 0) {
3112 goto out;
3116 ret = remove_blocked_xattrs(lo, value, ret);
3117 if (ret <= 0) {
3118 saverr = -ret;
3119 goto out;
3121 fuse_reply_buf(req, value, ret);
3122 } else {
3124 * xattrmap only ever shortens the result,
3125 * so we don't need to do anything clever with the
3126 * allocation length here.
3128 fuse_reply_xattr(req, ret);
3130 out_free:
3131 if (fd >= 0) {
3132 close(fd);
3135 lo_inode_put(lo, &inode);
3136 return;
3138 out_err:
3139 saverr = errno;
3140 out:
3141 fuse_reply_err(req, saverr);
3142 goto out_free;
3145 static void lo_setxattr(fuse_req_t req, fuse_ino_t ino, const char *in_name,
3146 const char *value, size_t size, int flags,
3147 uint32_t extra_flags)
3149 char procname[64];
3150 const char *name;
3151 char *mapped_name;
3152 struct lo_data *lo = lo_data(req);
3153 struct lo_inode *inode;
3154 ssize_t ret;
3155 int saverr;
3156 int fd = -1;
3157 bool switched_creds = false;
3158 bool cap_fsetid_dropped = false;
3159 struct lo_cred old = {};
3161 if (block_xattr(lo, in_name)) {
3162 fuse_reply_err(req, EOPNOTSUPP);
3163 return;
3166 mapped_name = NULL;
3167 name = in_name;
3168 if (lo->xattrmap) {
3169 ret = xattr_map_client(lo, in_name, &mapped_name);
3170 if (ret < 0) {
3171 fuse_reply_err(req, -ret);
3172 return;
3174 if (mapped_name) {
3175 name = mapped_name;
3179 inode = lo_inode(req, ino);
3180 if (!inode) {
3181 fuse_reply_err(req, EBADF);
3182 g_free(mapped_name);
3183 return;
3186 saverr = ENOSYS;
3187 if (!lo_data(req)->xattr) {
3188 goto out;
3191 fuse_log(FUSE_LOG_DEBUG, "lo_setxattr(ino=%" PRIu64
3192 ", name=%s value=%s size=%zd)\n", ino, name, value, size);
3194 sprintf(procname, "%i", inode->fd);
3196 * If we are setting posix access acl and if SGID needs to be
3197 * cleared, then switch to caller's gid and drop CAP_FSETID
3198 * and that should make sure host kernel clears SGID.
3200 * This probably will not work when we support idmapped mounts.
3201 * In that case we will need to find a non-root gid and switch
3202 * to it. (Instead of gid in request). Fix it when we support
3203 * idmapped mounts.
3205 if (lo->posix_acl && !strcmp(name, "system.posix_acl_access")
3206 && (extra_flags & FUSE_SETXATTR_ACL_KILL_SGID)) {
3207 ret = lo_drop_cap_change_cred(req, &old, false, "FSETID",
3208 &cap_fsetid_dropped);
3209 if (ret) {
3210 saverr = ret;
3211 goto out;
3213 switched_creds = true;
3215 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
3216 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
3217 if (fd < 0) {
3218 saverr = errno;
3219 goto out;
3221 ret = fsetxattr(fd, name, value, size, flags);
3222 saverr = ret == -1 ? errno : 0;
3223 } else {
3224 /* fchdir should not fail here */
3225 FCHDIR_NOFAIL(lo->proc_self_fd);
3226 ret = setxattr(procname, name, value, size, flags);
3227 saverr = ret == -1 ? errno : 0;
3228 FCHDIR_NOFAIL(lo->root.fd);
3230 if (switched_creds) {
3231 if (cap_fsetid_dropped)
3232 lo_restore_cred_gain_cap(&old, false, "FSETID");
3233 else
3234 lo_restore_cred(&old, false);
3237 out:
3238 if (fd >= 0) {
3239 close(fd);
3242 lo_inode_put(lo, &inode);
3243 g_free(mapped_name);
3244 fuse_reply_err(req, saverr);
3247 static void lo_removexattr(fuse_req_t req, fuse_ino_t ino, const char *in_name)
3249 char procname[64];
3250 const char *name;
3251 char *mapped_name;
3252 struct lo_data *lo = lo_data(req);
3253 struct lo_inode *inode;
3254 ssize_t ret;
3255 int saverr;
3256 int fd = -1;
3258 if (block_xattr(lo, in_name)) {
3259 fuse_reply_err(req, EOPNOTSUPP);
3260 return;
3263 mapped_name = NULL;
3264 name = in_name;
3265 if (lo->xattrmap) {
3266 ret = xattr_map_client(lo, in_name, &mapped_name);
3267 if (ret < 0) {
3268 fuse_reply_err(req, -ret);
3269 return;
3271 if (mapped_name) {
3272 name = mapped_name;
3276 inode = lo_inode(req, ino);
3277 if (!inode) {
3278 fuse_reply_err(req, EBADF);
3279 g_free(mapped_name);
3280 return;
3283 saverr = ENOSYS;
3284 if (!lo_data(req)->xattr) {
3285 goto out;
3288 fuse_log(FUSE_LOG_DEBUG, "lo_removexattr(ino=%" PRIu64 ", name=%s)\n", ino,
3289 name);
3291 sprintf(procname, "%i", inode->fd);
3292 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
3293 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
3294 if (fd < 0) {
3295 saverr = errno;
3296 goto out;
3298 ret = fremovexattr(fd, name);
3299 saverr = ret == -1 ? errno : 0;
3300 } else {
3301 /* fchdir should not fail here */
3302 FCHDIR_NOFAIL(lo->proc_self_fd);
3303 ret = removexattr(procname, name);
3304 saverr = ret == -1 ? errno : 0;
3305 FCHDIR_NOFAIL(lo->root.fd);
3308 out:
3309 if (fd >= 0) {
3310 close(fd);
3313 lo_inode_put(lo, &inode);
3314 g_free(mapped_name);
3315 fuse_reply_err(req, saverr);
3318 #ifdef HAVE_COPY_FILE_RANGE
3319 static void lo_copy_file_range(fuse_req_t req, fuse_ino_t ino_in, off_t off_in,
3320 struct fuse_file_info *fi_in, fuse_ino_t ino_out,
3321 off_t off_out, struct fuse_file_info *fi_out,
3322 size_t len, int flags)
3324 int in_fd, out_fd;
3325 ssize_t res;
3327 in_fd = lo_fi_fd(req, fi_in);
3328 out_fd = lo_fi_fd(req, fi_out);
3330 fuse_log(FUSE_LOG_DEBUG,
3331 "lo_copy_file_range(ino=%" PRIu64 "/fd=%d, "
3332 "off=%ju, ino=%" PRIu64 "/fd=%d, "
3333 "off=%ju, size=%zd, flags=0x%x)\n",
3334 ino_in, in_fd, (intmax_t)off_in,
3335 ino_out, out_fd, (intmax_t)off_out, len, flags);
3337 res = copy_file_range(in_fd, &off_in, out_fd, &off_out, len, flags);
3338 if (res < 0) {
3339 fuse_reply_err(req, errno);
3340 } else {
3341 fuse_reply_write(req, res);
3344 #endif
3346 static void lo_lseek(fuse_req_t req, fuse_ino_t ino, off_t off, int whence,
3347 struct fuse_file_info *fi)
3349 off_t res;
3351 (void)ino;
3352 res = lseek(lo_fi_fd(req, fi), off, whence);
3353 if (res != -1) {
3354 fuse_reply_lseek(req, res);
3355 } else {
3356 fuse_reply_err(req, errno);
3360 static void lo_destroy(void *userdata)
3362 struct lo_data *lo = (struct lo_data *)userdata;
3364 pthread_mutex_lock(&lo->mutex);
3365 while (true) {
3366 GHashTableIter iter;
3367 gpointer key, value;
3369 g_hash_table_iter_init(&iter, lo->inodes);
3370 if (!g_hash_table_iter_next(&iter, &key, &value)) {
3371 break;
3374 struct lo_inode *inode = value;
3375 unref_inode(lo, inode, inode->nlookup);
3377 pthread_mutex_unlock(&lo->mutex);
3380 static struct fuse_lowlevel_ops lo_oper = {
3381 .init = lo_init,
3382 .lookup = lo_lookup,
3383 .mkdir = lo_mkdir,
3384 .mknod = lo_mknod,
3385 .symlink = lo_symlink,
3386 .link = lo_link,
3387 .unlink = lo_unlink,
3388 .rmdir = lo_rmdir,
3389 .rename = lo_rename,
3390 .forget = lo_forget,
3391 .forget_multi = lo_forget_multi,
3392 .getattr = lo_getattr,
3393 .setattr = lo_setattr,
3394 .readlink = lo_readlink,
3395 .opendir = lo_opendir,
3396 .readdir = lo_readdir,
3397 .readdirplus = lo_readdirplus,
3398 .releasedir = lo_releasedir,
3399 .fsyncdir = lo_fsyncdir,
3400 .create = lo_create,
3401 .getlk = lo_getlk,
3402 .setlk = lo_setlk,
3403 .open = lo_open,
3404 .release = lo_release,
3405 .flush = lo_flush,
3406 .fsync = lo_fsync,
3407 .read = lo_read,
3408 .write_buf = lo_write_buf,
3409 .statfs = lo_statfs,
3410 .fallocate = lo_fallocate,
3411 .flock = lo_flock,
3412 .getxattr = lo_getxattr,
3413 .listxattr = lo_listxattr,
3414 .setxattr = lo_setxattr,
3415 .removexattr = lo_removexattr,
3416 #ifdef HAVE_COPY_FILE_RANGE
3417 .copy_file_range = lo_copy_file_range,
3418 #endif
3419 .lseek = lo_lseek,
3420 .destroy = lo_destroy,
3423 /* Print vhost-user.json backend program capabilities */
3424 static void print_capabilities(void)
3426 printf("{\n");
3427 printf(" \"type\": \"fs\"\n");
3428 printf("}\n");
3432 * Drop all Linux capabilities because the wait parent process only needs to
3433 * sit in waitpid(2) and terminate.
3435 static void setup_wait_parent_capabilities(void)
3437 capng_setpid(syscall(SYS_gettid));
3438 capng_clear(CAPNG_SELECT_BOTH);
3439 capng_apply(CAPNG_SELECT_BOTH);
3443 * Move to a new mount, net, and pid namespaces to isolate this process.
3445 static void setup_namespaces(struct lo_data *lo, struct fuse_session *se)
3447 pid_t child;
3450 * Create a new pid namespace for *child* processes. We'll have to
3451 * fork in order to enter the new pid namespace. A new mount namespace
3452 * is also needed so that we can remount /proc for the new pid
3453 * namespace.
3455 * Our UNIX domain sockets have been created. Now we can move to
3456 * an empty network namespace to prevent TCP/IP and other network
3457 * activity in case this process is compromised.
3459 if (unshare(CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWNET) != 0) {
3460 fuse_log(FUSE_LOG_ERR, "unshare(CLONE_NEWPID | CLONE_NEWNS): %m\n");
3461 exit(1);
3464 child = fork();
3465 if (child < 0) {
3466 fuse_log(FUSE_LOG_ERR, "fork() failed: %m\n");
3467 exit(1);
3469 if (child > 0) {
3470 pid_t waited;
3471 int wstatus;
3473 setup_wait_parent_capabilities();
3475 /* The parent waits for the child */
3476 do {
3477 waited = waitpid(child, &wstatus, 0);
3478 } while (waited < 0 && errno == EINTR && !se->exited);
3480 /* We were terminated by a signal, see fuse_signals.c */
3481 if (se->exited) {
3482 exit(0);
3485 if (WIFEXITED(wstatus)) {
3486 exit(WEXITSTATUS(wstatus));
3489 exit(1);
3492 /* Send us SIGTERM when the parent thread terminates, see prctl(2) */
3493 prctl(PR_SET_PDEATHSIG, SIGTERM);
3496 * If the mounts have shared propagation then we want to opt out so our
3497 * mount changes don't affect the parent mount namespace.
3499 if (mount(NULL, "/", NULL, MS_REC | MS_SLAVE, NULL) < 0) {
3500 fuse_log(FUSE_LOG_ERR, "mount(/, MS_REC|MS_SLAVE): %m\n");
3501 exit(1);
3504 /* The child must remount /proc to use the new pid namespace */
3505 if (mount("proc", "/proc", "proc",
3506 MS_NODEV | MS_NOEXEC | MS_NOSUID | MS_RELATIME, NULL) < 0) {
3507 fuse_log(FUSE_LOG_ERR, "mount(/proc): %m\n");
3508 exit(1);
3512 * We only need /proc/self/fd. Prevent ".." from accessing parent
3513 * directories of /proc/self/fd by bind-mounting it over /proc. Since / was
3514 * previously remounted with MS_REC | MS_SLAVE this mount change only
3515 * affects our process.
3517 if (mount("/proc/self/fd", "/proc", NULL, MS_BIND, NULL) < 0) {
3518 fuse_log(FUSE_LOG_ERR, "mount(/proc/self/fd, MS_BIND): %m\n");
3519 exit(1);
3522 /* Get the /proc (actually /proc/self/fd, see above) file descriptor */
3523 lo->proc_self_fd = open("/proc", O_PATH);
3524 if (lo->proc_self_fd == -1) {
3525 fuse_log(FUSE_LOG_ERR, "open(/proc, O_PATH): %m\n");
3526 exit(1);
3531 * Capture the capability state, we'll need to restore this for individual
3532 * threads later; see load_capng.
3534 static void setup_capng(void)
3536 /* Note this accesses /proc so has to happen before the sandbox */
3537 if (capng_get_caps_process()) {
3538 fuse_log(FUSE_LOG_ERR, "capng_get_caps_process\n");
3539 exit(1);
3541 pthread_mutex_init(&cap.mutex, NULL);
3542 pthread_mutex_lock(&cap.mutex);
3543 cap.saved = capng_save_state();
3544 if (!cap.saved) {
3545 fuse_log(FUSE_LOG_ERR, "capng_save_state\n");
3546 exit(1);
3548 pthread_mutex_unlock(&cap.mutex);
3551 static void cleanup_capng(void)
3553 free(cap.saved);
3554 cap.saved = NULL;
3555 pthread_mutex_destroy(&cap.mutex);
3560 * Make the source directory our root so symlinks cannot escape and no other
3561 * files are accessible. Assumes unshare(CLONE_NEWNS) was already called.
3563 static void setup_mounts(const char *source)
3565 int oldroot;
3566 int newroot;
3568 if (mount(source, source, NULL, MS_BIND | MS_REC, NULL) < 0) {
3569 fuse_log(FUSE_LOG_ERR, "mount(%s, %s, MS_BIND): %m\n", source, source);
3570 exit(1);
3573 /* This magic is based on lxc's lxc_pivot_root() */
3574 oldroot = open("/", O_DIRECTORY | O_RDONLY | O_CLOEXEC);
3575 if (oldroot < 0) {
3576 fuse_log(FUSE_LOG_ERR, "open(/): %m\n");
3577 exit(1);
3580 newroot = open(source, O_DIRECTORY | O_RDONLY | O_CLOEXEC);
3581 if (newroot < 0) {
3582 fuse_log(FUSE_LOG_ERR, "open(%s): %m\n", source);
3583 exit(1);
3586 if (fchdir(newroot) < 0) {
3587 fuse_log(FUSE_LOG_ERR, "fchdir(newroot): %m\n");
3588 exit(1);
3591 if (syscall(__NR_pivot_root, ".", ".") < 0) {
3592 fuse_log(FUSE_LOG_ERR, "pivot_root(., .): %m\n");
3593 exit(1);
3596 if (fchdir(oldroot) < 0) {
3597 fuse_log(FUSE_LOG_ERR, "fchdir(oldroot): %m\n");
3598 exit(1);
3601 if (mount("", ".", "", MS_SLAVE | MS_REC, NULL) < 0) {
3602 fuse_log(FUSE_LOG_ERR, "mount(., MS_SLAVE | MS_REC): %m\n");
3603 exit(1);
3606 if (umount2(".", MNT_DETACH) < 0) {
3607 fuse_log(FUSE_LOG_ERR, "umount2(., MNT_DETACH): %m\n");
3608 exit(1);
3611 if (fchdir(newroot) < 0) {
3612 fuse_log(FUSE_LOG_ERR, "fchdir(newroot): %m\n");
3613 exit(1);
3616 close(newroot);
3617 close(oldroot);
3621 * Only keep capabilities in allowlist that are needed for file system operation
3622 * The (possibly NULL) modcaps_in string passed in is free'd before exit.
3624 static void setup_capabilities(char *modcaps_in)
3626 char *modcaps = modcaps_in;
3627 pthread_mutex_lock(&cap.mutex);
3628 capng_restore_state(&cap.saved);
3631 * Add to allowlist file system-related capabilities that are needed for a
3632 * file server to act like root. Drop everything else like networking and
3633 * sysadmin capabilities.
3635 * Exclusions:
3636 * 1. CAP_LINUX_IMMUTABLE is not included because it's only used via ioctl
3637 * and we don't support that.
3638 * 2. CAP_MAC_OVERRIDE is not included because it only seems to be
3639 * used by the Smack LSM. Omit it until there is demand for it.
3641 capng_setpid(syscall(SYS_gettid));
3642 capng_clear(CAPNG_SELECT_BOTH);
3643 if (capng_updatev(CAPNG_ADD, CAPNG_PERMITTED | CAPNG_EFFECTIVE,
3644 CAP_CHOWN,
3645 CAP_DAC_OVERRIDE,
3646 CAP_FOWNER,
3647 CAP_FSETID,
3648 CAP_SETGID,
3649 CAP_SETUID,
3650 CAP_MKNOD,
3651 CAP_SETFCAP,
3652 -1)) {
3653 fuse_log(FUSE_LOG_ERR, "%s: capng_updatev failed\n", __func__);
3654 exit(1);
3658 * The modcaps option is a colon separated list of caps,
3659 * each preceded by either + or -.
3661 while (modcaps) {
3662 capng_act_t action;
3663 int cap;
3665 char *next = strchr(modcaps, ':');
3666 if (next) {
3667 *next = '\0';
3668 next++;
3671 switch (modcaps[0]) {
3672 case '+':
3673 action = CAPNG_ADD;
3674 break;
3676 case '-':
3677 action = CAPNG_DROP;
3678 break;
3680 default:
3681 fuse_log(FUSE_LOG_ERR,
3682 "%s: Expecting '+'/'-' in modcaps but found '%c'\n",
3683 __func__, modcaps[0]);
3684 exit(1);
3686 cap = capng_name_to_capability(modcaps + 1);
3687 if (cap < 0) {
3688 fuse_log(FUSE_LOG_ERR, "%s: Unknown capability '%s'\n", __func__,
3689 modcaps);
3690 exit(1);
3692 if (capng_update(action, CAPNG_PERMITTED | CAPNG_EFFECTIVE, cap)) {
3693 fuse_log(FUSE_LOG_ERR, "%s: capng_update failed for '%s'\n",
3694 __func__, modcaps);
3695 exit(1);
3698 modcaps = next;
3700 g_free(modcaps_in);
3702 if (capng_apply(CAPNG_SELECT_BOTH)) {
3703 fuse_log(FUSE_LOG_ERR, "%s: capng_apply failed\n", __func__);
3704 exit(1);
3707 cap.saved = capng_save_state();
3708 if (!cap.saved) {
3709 fuse_log(FUSE_LOG_ERR, "%s: capng_save_state failed\n", __func__);
3710 exit(1);
3712 pthread_mutex_unlock(&cap.mutex);
3716 * Use chroot as a weaker sandbox for environments where the process is
3717 * launched without CAP_SYS_ADMIN.
3719 static void setup_chroot(struct lo_data *lo)
3721 lo->proc_self_fd = open("/proc/self/fd", O_PATH);
3722 if (lo->proc_self_fd == -1) {
3723 fuse_log(FUSE_LOG_ERR, "open(\"/proc/self/fd\", O_PATH): %m\n");
3724 exit(1);
3728 * Make the shared directory the file system root so that FUSE_OPEN
3729 * (lo_open()) cannot escape the shared directory by opening a symlink.
3731 * The chroot(2) syscall is later disabled by seccomp and the
3732 * CAP_SYS_CHROOT capability is dropped so that tampering with the chroot
3733 * is not possible.
3735 * However, it's still possible to escape the chroot via lo->proc_self_fd
3736 * but that requires first gaining control of the process.
3738 if (chroot(lo->source) != 0) {
3739 fuse_log(FUSE_LOG_ERR, "chroot(\"%s\"): %m\n", lo->source);
3740 exit(1);
3743 /* Move into the chroot */
3744 if (chdir("/") != 0) {
3745 fuse_log(FUSE_LOG_ERR, "chdir(\"/\"): %m\n");
3746 exit(1);
3751 * Lock down this process to prevent access to other processes or files outside
3752 * source directory. This reduces the impact of arbitrary code execution bugs.
3754 static void setup_sandbox(struct lo_data *lo, struct fuse_session *se,
3755 bool enable_syslog)
3757 if (lo->sandbox == SANDBOX_NAMESPACE) {
3758 setup_namespaces(lo, se);
3759 setup_mounts(lo->source);
3760 } else {
3761 setup_chroot(lo);
3764 setup_seccomp(enable_syslog);
3765 setup_capabilities(g_strdup(lo->modcaps));
3768 /* Set the maximum number of open file descriptors */
3769 static void setup_nofile_rlimit(unsigned long rlimit_nofile)
3771 struct rlimit rlim = {
3772 .rlim_cur = rlimit_nofile,
3773 .rlim_max = rlimit_nofile,
3776 if (rlimit_nofile == 0) {
3777 return; /* nothing to do */
3780 if (setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
3781 /* Ignore SELinux denials */
3782 if (errno == EPERM) {
3783 return;
3786 fuse_log(FUSE_LOG_ERR, "setrlimit(RLIMIT_NOFILE): %m\n");
3787 exit(1);
3791 static void log_func(enum fuse_log_level level, const char *fmt, va_list ap)
3793 g_autofree char *localfmt = NULL;
3795 if (current_log_level < level) {
3796 return;
3799 if (current_log_level == FUSE_LOG_DEBUG) {
3800 if (use_syslog) {
3801 /* no timestamp needed */
3802 localfmt = g_strdup_printf("[ID: %08ld] %s", syscall(__NR_gettid),
3803 fmt);
3804 } else {
3805 g_autoptr(GDateTime) now = g_date_time_new_now_utc();
3806 g_autofree char *nowstr = g_date_time_format(now, "%Y-%m-%d %H:%M:%S.%f%z");
3807 localfmt = g_strdup_printf("[%s] [ID: %08ld] %s",
3808 nowstr, syscall(__NR_gettid), fmt);
3810 fmt = localfmt;
3813 if (use_syslog) {
3814 int priority = LOG_ERR;
3815 switch (level) {
3816 case FUSE_LOG_EMERG:
3817 priority = LOG_EMERG;
3818 break;
3819 case FUSE_LOG_ALERT:
3820 priority = LOG_ALERT;
3821 break;
3822 case FUSE_LOG_CRIT:
3823 priority = LOG_CRIT;
3824 break;
3825 case FUSE_LOG_ERR:
3826 priority = LOG_ERR;
3827 break;
3828 case FUSE_LOG_WARNING:
3829 priority = LOG_WARNING;
3830 break;
3831 case FUSE_LOG_NOTICE:
3832 priority = LOG_NOTICE;
3833 break;
3834 case FUSE_LOG_INFO:
3835 priority = LOG_INFO;
3836 break;
3837 case FUSE_LOG_DEBUG:
3838 priority = LOG_DEBUG;
3839 break;
3841 vsyslog(priority, fmt, ap);
3842 } else {
3843 vfprintf(stderr, fmt, ap);
3847 static void setup_root(struct lo_data *lo, struct lo_inode *root)
3849 int fd, res;
3850 struct stat stat;
3851 uint64_t mnt_id;
3853 fd = open("/", O_PATH);
3854 if (fd == -1) {
3855 fuse_log(FUSE_LOG_ERR, "open(%s, O_PATH): %m\n", lo->source);
3856 exit(1);
3859 res = do_statx(lo, fd, "", &stat, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW,
3860 &mnt_id);
3861 if (res == -1) {
3862 fuse_log(FUSE_LOG_ERR, "fstatat(%s): %m\n", lo->source);
3863 exit(1);
3866 root->filetype = S_IFDIR;
3867 root->fd = fd;
3868 root->key.ino = stat.st_ino;
3869 root->key.dev = stat.st_dev;
3870 root->key.mnt_id = mnt_id;
3871 root->nlookup = 2;
3872 g_atomic_int_set(&root->refcount, 2);
3873 if (lo->posix_lock) {
3874 pthread_mutex_init(&root->plock_mutex, NULL);
3875 root->posix_locks = g_hash_table_new_full(
3876 g_direct_hash, g_direct_equal, NULL, posix_locks_value_destroy);
3880 static guint lo_key_hash(gconstpointer key)
3882 const struct lo_key *lkey = key;
3884 return (guint)lkey->ino + (guint)lkey->dev + (guint)lkey->mnt_id;
3887 static gboolean lo_key_equal(gconstpointer a, gconstpointer b)
3889 const struct lo_key *la = a;
3890 const struct lo_key *lb = b;
3892 return la->ino == lb->ino && la->dev == lb->dev && la->mnt_id == lb->mnt_id;
3895 static void fuse_lo_data_cleanup(struct lo_data *lo)
3897 if (lo->inodes) {
3898 g_hash_table_destroy(lo->inodes);
3901 if (lo->root.posix_locks) {
3902 g_hash_table_destroy(lo->root.posix_locks);
3904 lo_map_destroy(&lo->fd_map);
3905 lo_map_destroy(&lo->dirp_map);
3906 lo_map_destroy(&lo->ino_map);
3908 if (lo->proc_self_fd >= 0) {
3909 close(lo->proc_self_fd);
3912 if (lo->root.fd >= 0) {
3913 close(lo->root.fd);
3916 free(lo->xattrmap);
3917 free_xattrmap(lo);
3918 free(lo->xattr_security_capability);
3919 free(lo->source);
3922 static void qemu_version(void)
3924 printf("virtiofsd version " QEMU_FULL_VERSION "\n" QEMU_COPYRIGHT "\n");
3927 int main(int argc, char *argv[])
3929 struct fuse_args args = FUSE_ARGS_INIT(argc, argv);
3930 struct fuse_session *se;
3931 struct fuse_cmdline_opts opts;
3932 struct lo_data lo = {
3933 .sandbox = SANDBOX_NAMESPACE,
3934 .debug = 0,
3935 .writeback = 0,
3936 .posix_lock = 0,
3937 .allow_direct_io = 0,
3938 .proc_self_fd = -1,
3939 .user_killpriv_v2 = -1,
3940 .user_posix_acl = -1,
3942 struct lo_map_elem *root_elem;
3943 struct lo_map_elem *reserve_elem;
3944 int ret = -1;
3946 /* Initialize time conversion information for localtime_r(). */
3947 tzset();
3949 /* Don't mask creation mode, kernel already did that */
3950 umask(0);
3952 qemu_init_exec_dir(argv[0]);
3954 drop_supplementary_groups();
3956 pthread_mutex_init(&lo.mutex, NULL);
3957 lo.inodes = g_hash_table_new(lo_key_hash, lo_key_equal);
3958 lo.root.fd = -1;
3959 lo.root.fuse_ino = FUSE_ROOT_ID;
3960 lo.cache = CACHE_AUTO;
3963 * Set up the ino map like this:
3964 * [0] Reserved (will not be used)
3965 * [1] Root inode
3967 lo_map_init(&lo.ino_map);
3968 reserve_elem = lo_map_reserve(&lo.ino_map, 0);
3969 if (!reserve_elem) {
3970 fuse_log(FUSE_LOG_ERR, "failed to alloc reserve_elem.\n");
3971 goto err_out1;
3973 reserve_elem->in_use = false;
3974 root_elem = lo_map_reserve(&lo.ino_map, lo.root.fuse_ino);
3975 if (!root_elem) {
3976 fuse_log(FUSE_LOG_ERR, "failed to alloc root_elem.\n");
3977 goto err_out1;
3979 root_elem->inode = &lo.root;
3981 lo_map_init(&lo.dirp_map);
3982 lo_map_init(&lo.fd_map);
3984 if (fuse_parse_cmdline(&args, &opts) != 0) {
3985 goto err_out1;
3987 fuse_set_log_func(log_func);
3988 use_syslog = opts.syslog;
3989 if (use_syslog) {
3990 openlog("virtiofsd", LOG_PID, LOG_DAEMON);
3993 if (opts.show_help) {
3994 printf("usage: %s [options]\n\n", argv[0]);
3995 fuse_cmdline_help();
3996 printf(" -o source=PATH shared directory tree\n");
3997 fuse_lowlevel_help();
3998 ret = 0;
3999 goto err_out1;
4000 } else if (opts.show_version) {
4001 qemu_version();
4002 fuse_lowlevel_version();
4003 ret = 0;
4004 goto err_out1;
4005 } else if (opts.print_capabilities) {
4006 print_capabilities();
4007 ret = 0;
4008 goto err_out1;
4011 if (fuse_opt_parse(&args, &lo, lo_opts, NULL) == -1) {
4012 goto err_out1;
4015 if (opts.log_level != 0) {
4016 current_log_level = opts.log_level;
4017 } else {
4018 /* default log level is INFO */
4019 current_log_level = FUSE_LOG_INFO;
4021 lo.debug = opts.debug;
4022 if (lo.debug) {
4023 current_log_level = FUSE_LOG_DEBUG;
4025 if (lo.source) {
4026 struct stat stat;
4027 int res;
4029 res = lstat(lo.source, &stat);
4030 if (res == -1) {
4031 fuse_log(FUSE_LOG_ERR, "failed to stat source (\"%s\"): %m\n",
4032 lo.source);
4033 exit(1);
4035 if (!S_ISDIR(stat.st_mode)) {
4036 fuse_log(FUSE_LOG_ERR, "source is not a directory\n");
4037 exit(1);
4039 } else {
4040 lo.source = strdup("/");
4041 if (!lo.source) {
4042 fuse_log(FUSE_LOG_ERR, "failed to strdup source\n");
4043 goto err_out1;
4047 if (lo.xattrmap) {
4048 lo.xattr = 1;
4049 parse_xattrmap(&lo);
4052 if (!lo.timeout_set) {
4053 switch (lo.cache) {
4054 case CACHE_NONE:
4055 lo.timeout = 0.0;
4056 break;
4058 case CACHE_AUTO:
4059 lo.timeout = 1.0;
4060 break;
4062 case CACHE_ALWAYS:
4063 lo.timeout = 86400.0;
4064 break;
4066 } else if (lo.timeout < 0) {
4067 fuse_log(FUSE_LOG_ERR, "timeout is negative (%lf)\n", lo.timeout);
4068 exit(1);
4071 if (lo.user_posix_acl == 1 && !lo.xattr) {
4072 fuse_log(FUSE_LOG_ERR, "Can't enable posix ACLs. xattrs are disabled."
4073 "\n");
4074 exit(1);
4077 lo.use_statx = true;
4079 se = fuse_session_new(&args, &lo_oper, sizeof(lo_oper), &lo);
4080 if (se == NULL) {
4081 goto err_out1;
4084 if (fuse_set_signal_handlers(se) != 0) {
4085 goto err_out2;
4088 if (fuse_session_mount(se) != 0) {
4089 goto err_out3;
4092 fuse_daemonize(opts.foreground);
4094 setup_nofile_rlimit(opts.rlimit_nofile);
4096 /* Must be before sandbox since it wants /proc */
4097 setup_capng();
4099 setup_sandbox(&lo, se, opts.syslog);
4101 setup_root(&lo, &lo.root);
4102 /* Block until ctrl+c or fusermount -u */
4103 ret = virtio_loop(se);
4105 fuse_session_unmount(se);
4106 cleanup_capng();
4107 err_out3:
4108 fuse_remove_signal_handlers(se);
4109 err_out2:
4110 fuse_session_destroy(se);
4111 err_out1:
4112 fuse_opt_free_args(&args);
4114 fuse_lo_data_cleanup(&lo);
4116 return ret ? 1 : 0;