target/i386: Add bus lock debug exception support
[qemu/ar7.git] / tools / virtiofsd / passthrough_ll.c
blob58d24c001082ed7d3216c973ee5136b038f83f44
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 "fuse_virtio.h"
41 #include "fuse_log.h"
42 #include "fuse_lowlevel.h"
43 #include "standard-headers/linux/fuse.h"
44 #include <cap-ng.h>
45 #include <dirent.h>
46 #include <pthread.h>
47 #include <sys/file.h>
48 #include <sys/mount.h>
49 #include <sys/prctl.h>
50 #include <sys/resource.h>
51 #include <sys/syscall.h>
52 #include <sys/wait.h>
53 #include <sys/xattr.h>
54 #include <syslog.h>
56 #include "qemu/cutils.h"
57 #include "passthrough_helpers.h"
58 #include "passthrough_seccomp.h"
60 /* Keep track of inode posix locks for each owner. */
61 struct lo_inode_plock {
62 uint64_t lock_owner;
63 int fd; /* fd for OFD locks */
66 struct lo_map_elem {
67 union {
68 struct lo_inode *inode;
69 struct lo_dirp *dirp;
70 int fd;
71 ssize_t freelist;
73 bool in_use;
76 /* Maps FUSE fh or ino values to internal objects */
77 struct lo_map {
78 struct lo_map_elem *elems;
79 size_t nelems;
80 ssize_t freelist;
83 struct lo_key {
84 ino_t ino;
85 dev_t dev;
86 uint64_t mnt_id;
89 struct lo_inode {
90 int fd;
93 * Atomic reference count for this object. The nlookup field holds a
94 * reference and release it when nlookup reaches 0.
96 gint refcount;
98 struct lo_key key;
101 * This counter keeps the inode alive during the FUSE session.
102 * Incremented when the FUSE inode number is sent in a reply
103 * (FUSE_LOOKUP, FUSE_READDIRPLUS, etc). Decremented when an inode is
104 * released by a FUSE_FORGET request.
106 * Note that this value is untrusted because the client can manipulate
107 * it arbitrarily using FUSE_FORGET requests.
109 * Protected by lo->mutex.
111 uint64_t nlookup;
113 fuse_ino_t fuse_ino;
114 pthread_mutex_t plock_mutex;
115 GHashTable *posix_locks; /* protected by lo_inode->plock_mutex */
117 mode_t filetype;
120 struct lo_cred {
121 uid_t euid;
122 gid_t egid;
125 enum {
126 CACHE_NONE,
127 CACHE_AUTO,
128 CACHE_ALWAYS,
131 enum {
132 SANDBOX_NAMESPACE,
133 SANDBOX_CHROOT,
136 typedef struct xattr_map_entry {
137 char *key;
138 char *prepend;
139 unsigned int flags;
140 } XattrMapEntry;
142 struct lo_data {
143 pthread_mutex_t mutex;
144 int sandbox;
145 int debug;
146 int writeback;
147 int flock;
148 int posix_lock;
149 int xattr;
150 char *xattrmap;
151 char *source;
152 char *modcaps;
153 double timeout;
154 int cache;
155 int timeout_set;
156 int readdirplus_set;
157 int readdirplus_clear;
158 int allow_direct_io;
159 int announce_submounts;
160 bool use_statx;
161 struct lo_inode root;
162 GHashTable *inodes; /* protected by lo->mutex */
163 struct lo_map ino_map; /* protected by lo->mutex */
164 struct lo_map dirp_map; /* protected by lo->mutex */
165 struct lo_map fd_map; /* protected by lo->mutex */
166 XattrMapEntry *xattr_map_list;
167 size_t xattr_map_nentries;
169 /* An O_PATH file descriptor to /proc/self/fd/ */
170 int proc_self_fd;
171 int user_killpriv_v2, killpriv_v2;
174 static const struct fuse_opt lo_opts[] = {
175 { "sandbox=namespace",
176 offsetof(struct lo_data, sandbox),
177 SANDBOX_NAMESPACE },
178 { "sandbox=chroot",
179 offsetof(struct lo_data, sandbox),
180 SANDBOX_CHROOT },
181 { "writeback", offsetof(struct lo_data, writeback), 1 },
182 { "no_writeback", offsetof(struct lo_data, writeback), 0 },
183 { "source=%s", offsetof(struct lo_data, source), 0 },
184 { "flock", offsetof(struct lo_data, flock), 1 },
185 { "no_flock", offsetof(struct lo_data, flock), 0 },
186 { "posix_lock", offsetof(struct lo_data, posix_lock), 1 },
187 { "no_posix_lock", offsetof(struct lo_data, posix_lock), 0 },
188 { "xattr", offsetof(struct lo_data, xattr), 1 },
189 { "no_xattr", offsetof(struct lo_data, xattr), 0 },
190 { "xattrmap=%s", offsetof(struct lo_data, xattrmap), 0 },
191 { "modcaps=%s", offsetof(struct lo_data, modcaps), 0 },
192 { "timeout=%lf", offsetof(struct lo_data, timeout), 0 },
193 { "timeout=", offsetof(struct lo_data, timeout_set), 1 },
194 { "cache=none", offsetof(struct lo_data, cache), CACHE_NONE },
195 { "cache=auto", offsetof(struct lo_data, cache), CACHE_AUTO },
196 { "cache=always", offsetof(struct lo_data, cache), CACHE_ALWAYS },
197 { "readdirplus", offsetof(struct lo_data, readdirplus_set), 1 },
198 { "no_readdirplus", offsetof(struct lo_data, readdirplus_clear), 1 },
199 { "allow_direct_io", offsetof(struct lo_data, allow_direct_io), 1 },
200 { "no_allow_direct_io", offsetof(struct lo_data, allow_direct_io), 0 },
201 { "announce_submounts", offsetof(struct lo_data, announce_submounts), 1 },
202 { "killpriv_v2", offsetof(struct lo_data, user_killpriv_v2), 1 },
203 { "no_killpriv_v2", offsetof(struct lo_data, user_killpriv_v2), 0 },
204 FUSE_OPT_END
206 static bool use_syslog = false;
207 static int current_log_level;
208 static void unref_inode_lolocked(struct lo_data *lo, struct lo_inode *inode,
209 uint64_t n);
211 static struct {
212 pthread_mutex_t mutex;
213 void *saved;
214 } cap;
215 /* That we loaded cap-ng in the current thread from the saved */
216 static __thread bool cap_loaded = 0;
218 static struct lo_inode *lo_find(struct lo_data *lo, struct stat *st,
219 uint64_t mnt_id);
221 static int is_dot_or_dotdot(const char *name)
223 return name[0] == '.' &&
224 (name[1] == '\0' || (name[1] == '.' && name[2] == '\0'));
227 /* Is `path` a single path component that is not "." or ".."? */
228 static int is_safe_path_component(const char *path)
230 if (strchr(path, '/')) {
231 return 0;
234 return !is_dot_or_dotdot(path);
237 static struct lo_data *lo_data(fuse_req_t req)
239 return (struct lo_data *)fuse_req_userdata(req);
243 * Load capng's state from our saved state if the current thread
244 * hadn't previously been loaded.
245 * returns 0 on success
247 static int load_capng(void)
249 if (!cap_loaded) {
250 pthread_mutex_lock(&cap.mutex);
251 capng_restore_state(&cap.saved);
253 * restore_state free's the saved copy
254 * so make another.
256 cap.saved = capng_save_state();
257 if (!cap.saved) {
258 pthread_mutex_unlock(&cap.mutex);
259 fuse_log(FUSE_LOG_ERR, "capng_save_state (thread)\n");
260 return -EINVAL;
262 pthread_mutex_unlock(&cap.mutex);
265 * We want to use the loaded state for our pid,
266 * not the original
268 capng_setpid(syscall(SYS_gettid));
269 cap_loaded = true;
271 return 0;
275 * Helpers for dropping and regaining effective capabilities. Returns 0
276 * on success, error otherwise
278 static int drop_effective_cap(const char *cap_name, bool *cap_dropped)
280 int cap, ret;
282 cap = capng_name_to_capability(cap_name);
283 if (cap < 0) {
284 ret = errno;
285 fuse_log(FUSE_LOG_ERR, "capng_name_to_capability(%s) failed:%s\n",
286 cap_name, strerror(errno));
287 goto out;
290 if (load_capng()) {
291 ret = errno;
292 fuse_log(FUSE_LOG_ERR, "load_capng() failed\n");
293 goto out;
296 /* We dont have this capability in effective set already. */
297 if (!capng_have_capability(CAPNG_EFFECTIVE, cap)) {
298 ret = 0;
299 goto out;
302 if (capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, cap)) {
303 ret = errno;
304 fuse_log(FUSE_LOG_ERR, "capng_update(DROP,) failed\n");
305 goto out;
308 if (capng_apply(CAPNG_SELECT_CAPS)) {
309 ret = errno;
310 fuse_log(FUSE_LOG_ERR, "drop:capng_apply() failed\n");
311 goto out;
314 ret = 0;
315 if (cap_dropped) {
316 *cap_dropped = true;
319 out:
320 return ret;
323 static int gain_effective_cap(const char *cap_name)
325 int cap;
326 int ret = 0;
328 cap = capng_name_to_capability(cap_name);
329 if (cap < 0) {
330 ret = errno;
331 fuse_log(FUSE_LOG_ERR, "capng_name_to_capability(%s) failed:%s\n",
332 cap_name, strerror(errno));
333 goto out;
336 if (load_capng()) {
337 ret = errno;
338 fuse_log(FUSE_LOG_ERR, "load_capng() failed\n");
339 goto out;
342 if (capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, cap)) {
343 ret = errno;
344 fuse_log(FUSE_LOG_ERR, "capng_update(ADD,) failed\n");
345 goto out;
348 if (capng_apply(CAPNG_SELECT_CAPS)) {
349 ret = errno;
350 fuse_log(FUSE_LOG_ERR, "gain:capng_apply() failed\n");
351 goto out;
353 ret = 0;
355 out:
356 return ret;
359 static void lo_map_init(struct lo_map *map)
361 map->elems = NULL;
362 map->nelems = 0;
363 map->freelist = -1;
366 static void lo_map_destroy(struct lo_map *map)
368 free(map->elems);
371 static int lo_map_grow(struct lo_map *map, size_t new_nelems)
373 struct lo_map_elem *new_elems;
374 size_t i;
376 if (new_nelems <= map->nelems) {
377 return 1;
380 new_elems = realloc(map->elems, sizeof(map->elems[0]) * new_nelems);
381 if (!new_elems) {
382 return 0;
385 for (i = map->nelems; i < new_nelems; i++) {
386 new_elems[i].freelist = i + 1;
387 new_elems[i].in_use = false;
389 new_elems[new_nelems - 1].freelist = -1;
391 map->elems = new_elems;
392 map->freelist = map->nelems;
393 map->nelems = new_nelems;
394 return 1;
397 static struct lo_map_elem *lo_map_alloc_elem(struct lo_map *map)
399 struct lo_map_elem *elem;
401 if (map->freelist == -1 && !lo_map_grow(map, map->nelems + 256)) {
402 return NULL;
405 elem = &map->elems[map->freelist];
406 map->freelist = elem->freelist;
408 elem->in_use = true;
410 return elem;
413 static struct lo_map_elem *lo_map_reserve(struct lo_map *map, size_t key)
415 ssize_t *prev;
417 if (!lo_map_grow(map, key + 1)) {
418 return NULL;
421 for (prev = &map->freelist; *prev != -1;
422 prev = &map->elems[*prev].freelist) {
423 if (*prev == key) {
424 struct lo_map_elem *elem = &map->elems[key];
426 *prev = elem->freelist;
427 elem->in_use = true;
428 return elem;
431 return NULL;
434 static struct lo_map_elem *lo_map_get(struct lo_map *map, size_t key)
436 if (key >= map->nelems) {
437 return NULL;
439 if (!map->elems[key].in_use) {
440 return NULL;
442 return &map->elems[key];
445 static void lo_map_remove(struct lo_map *map, size_t key)
447 struct lo_map_elem *elem;
449 if (key >= map->nelems) {
450 return;
453 elem = &map->elems[key];
454 if (!elem->in_use) {
455 return;
458 elem->in_use = false;
460 elem->freelist = map->freelist;
461 map->freelist = key;
464 /* Assumes lo->mutex is held */
465 static ssize_t lo_add_fd_mapping(struct lo_data *lo, int fd)
467 struct lo_map_elem *elem;
469 elem = lo_map_alloc_elem(&lo->fd_map);
470 if (!elem) {
471 return -1;
474 elem->fd = fd;
475 return elem - lo->fd_map.elems;
478 /* Assumes lo->mutex is held */
479 static ssize_t lo_add_dirp_mapping(fuse_req_t req, struct lo_dirp *dirp)
481 struct lo_map_elem *elem;
483 elem = lo_map_alloc_elem(&lo_data(req)->dirp_map);
484 if (!elem) {
485 return -1;
488 elem->dirp = dirp;
489 return elem - lo_data(req)->dirp_map.elems;
492 /* Assumes lo->mutex is held */
493 static ssize_t lo_add_inode_mapping(fuse_req_t req, struct lo_inode *inode)
495 struct lo_map_elem *elem;
497 elem = lo_map_alloc_elem(&lo_data(req)->ino_map);
498 if (!elem) {
499 return -1;
502 elem->inode = inode;
503 return elem - lo_data(req)->ino_map.elems;
506 static void lo_inode_put(struct lo_data *lo, struct lo_inode **inodep)
508 struct lo_inode *inode = *inodep;
510 if (!inode) {
511 return;
514 *inodep = NULL;
516 if (g_atomic_int_dec_and_test(&inode->refcount)) {
517 close(inode->fd);
518 free(inode);
522 /* Caller must release refcount using lo_inode_put() */
523 static struct lo_inode *lo_inode(fuse_req_t req, fuse_ino_t ino)
525 struct lo_data *lo = lo_data(req);
526 struct lo_map_elem *elem;
528 pthread_mutex_lock(&lo->mutex);
529 elem = lo_map_get(&lo->ino_map, ino);
530 if (elem) {
531 g_atomic_int_inc(&elem->inode->refcount);
533 pthread_mutex_unlock(&lo->mutex);
535 if (!elem) {
536 return NULL;
539 return elem->inode;
543 * TODO Remove this helper and force callers to hold an inode refcount until
544 * they are done with the fd. This will be done in a later patch to make
545 * review easier.
547 static int lo_fd(fuse_req_t req, fuse_ino_t ino)
549 struct lo_inode *inode = lo_inode(req, ino);
550 int fd;
552 if (!inode) {
553 return -1;
556 fd = inode->fd;
557 lo_inode_put(lo_data(req), &inode);
558 return fd;
562 * Open a file descriptor for an inode. Returns -EBADF if the inode is not a
563 * regular file or a directory.
565 * Use this helper function instead of raw openat(2) to prevent security issues
566 * when a malicious client opens special files such as block device nodes.
567 * Symlink inodes are also rejected since symlinks must already have been
568 * traversed on the client side.
570 static int lo_inode_open(struct lo_data *lo, struct lo_inode *inode,
571 int open_flags)
573 g_autofree char *fd_str = g_strdup_printf("%d", inode->fd);
574 int fd;
576 if (!S_ISREG(inode->filetype) && !S_ISDIR(inode->filetype)) {
577 return -EBADF;
581 * The file is a symlink so O_NOFOLLOW must be ignored. We checked earlier
582 * that the inode is not a special file but if an external process races
583 * with us then symlinks are traversed here. It is not possible to escape
584 * the shared directory since it is mounted as "/" though.
586 fd = openat(lo->proc_self_fd, fd_str, open_flags & ~O_NOFOLLOW);
587 if (fd < 0) {
588 return -errno;
590 return fd;
593 static void lo_init(void *userdata, struct fuse_conn_info *conn)
595 struct lo_data *lo = (struct lo_data *)userdata;
597 if (conn->capable & FUSE_CAP_EXPORT_SUPPORT) {
598 conn->want |= FUSE_CAP_EXPORT_SUPPORT;
601 if (lo->writeback && conn->capable & FUSE_CAP_WRITEBACK_CACHE) {
602 fuse_log(FUSE_LOG_DEBUG, "lo_init: activating writeback\n");
603 conn->want |= FUSE_CAP_WRITEBACK_CACHE;
605 if (conn->capable & FUSE_CAP_FLOCK_LOCKS) {
606 if (lo->flock) {
607 fuse_log(FUSE_LOG_DEBUG, "lo_init: activating flock locks\n");
608 conn->want |= FUSE_CAP_FLOCK_LOCKS;
609 } else {
610 fuse_log(FUSE_LOG_DEBUG, "lo_init: disabling flock locks\n");
611 conn->want &= ~FUSE_CAP_FLOCK_LOCKS;
615 if (conn->capable & FUSE_CAP_POSIX_LOCKS) {
616 if (lo->posix_lock) {
617 fuse_log(FUSE_LOG_DEBUG, "lo_init: activating posix locks\n");
618 conn->want |= FUSE_CAP_POSIX_LOCKS;
619 } else {
620 fuse_log(FUSE_LOG_DEBUG, "lo_init: disabling posix locks\n");
621 conn->want &= ~FUSE_CAP_POSIX_LOCKS;
625 if ((lo->cache == CACHE_NONE && !lo->readdirplus_set) ||
626 lo->readdirplus_clear) {
627 fuse_log(FUSE_LOG_DEBUG, "lo_init: disabling readdirplus\n");
628 conn->want &= ~FUSE_CAP_READDIRPLUS;
631 if (!(conn->capable & FUSE_CAP_SUBMOUNTS) && lo->announce_submounts) {
632 fuse_log(FUSE_LOG_WARNING, "lo_init: Cannot announce submounts, client "
633 "does not support it\n");
634 lo->announce_submounts = false;
637 if (lo->user_killpriv_v2 == 1) {
639 * User explicitly asked for this option. Enable it unconditionally.
640 * If connection does not have this capability, it should fail
641 * in fuse_lowlevel.c
643 fuse_log(FUSE_LOG_DEBUG, "lo_init: enabling killpriv_v2\n");
644 conn->want |= FUSE_CAP_HANDLE_KILLPRIV_V2;
645 lo->killpriv_v2 = 1;
646 } else if (lo->user_killpriv_v2 == -1 &&
647 conn->capable & FUSE_CAP_HANDLE_KILLPRIV_V2) {
649 * User did not specify a value for killpriv_v2. By default enable it
650 * if connection offers this capability
652 fuse_log(FUSE_LOG_DEBUG, "lo_init: enabling killpriv_v2\n");
653 conn->want |= FUSE_CAP_HANDLE_KILLPRIV_V2;
654 lo->killpriv_v2 = 1;
655 } else {
657 * Either user specified to disable killpriv_v2, or connection does
658 * not offer this capability. Disable killpriv_v2 in both the cases
660 fuse_log(FUSE_LOG_DEBUG, "lo_init: disabling killpriv_v2\n");
661 conn->want &= ~FUSE_CAP_HANDLE_KILLPRIV_V2;
662 lo->killpriv_v2 = 0;
666 static void lo_getattr(fuse_req_t req, fuse_ino_t ino,
667 struct fuse_file_info *fi)
669 int res;
670 struct stat buf;
671 struct lo_data *lo = lo_data(req);
673 (void)fi;
675 res =
676 fstatat(lo_fd(req, ino), "", &buf, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW);
677 if (res == -1) {
678 return (void)fuse_reply_err(req, errno);
681 fuse_reply_attr(req, &buf, lo->timeout);
684 static int lo_fi_fd(fuse_req_t req, struct fuse_file_info *fi)
686 struct lo_data *lo = lo_data(req);
687 struct lo_map_elem *elem;
689 pthread_mutex_lock(&lo->mutex);
690 elem = lo_map_get(&lo->fd_map, fi->fh);
691 pthread_mutex_unlock(&lo->mutex);
693 if (!elem) {
694 return -1;
697 return elem->fd;
700 static void lo_setattr(fuse_req_t req, fuse_ino_t ino, struct stat *attr,
701 int valid, struct fuse_file_info *fi)
703 int saverr;
704 char procname[64];
705 struct lo_data *lo = lo_data(req);
706 struct lo_inode *inode;
707 int ifd;
708 int res;
709 int fd = -1;
711 inode = lo_inode(req, ino);
712 if (!inode) {
713 fuse_reply_err(req, EBADF);
714 return;
717 ifd = inode->fd;
719 /* If fi->fh is invalid we'll report EBADF later */
720 if (fi) {
721 fd = lo_fi_fd(req, fi);
724 if (valid & FUSE_SET_ATTR_MODE) {
725 if (fi) {
726 res = fchmod(fd, attr->st_mode);
727 } else {
728 sprintf(procname, "%i", ifd);
729 res = fchmodat(lo->proc_self_fd, procname, attr->st_mode, 0);
731 if (res == -1) {
732 saverr = errno;
733 goto out_err;
736 if (valid & (FUSE_SET_ATTR_UID | FUSE_SET_ATTR_GID)) {
737 uid_t uid = (valid & FUSE_SET_ATTR_UID) ? attr->st_uid : (uid_t)-1;
738 gid_t gid = (valid & FUSE_SET_ATTR_GID) ? attr->st_gid : (gid_t)-1;
740 res = fchownat(ifd, "", uid, gid, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW);
741 if (res == -1) {
742 saverr = errno;
743 goto out_err;
746 if (valid & FUSE_SET_ATTR_SIZE) {
747 int truncfd;
748 bool kill_suidgid;
749 bool cap_fsetid_dropped = false;
751 kill_suidgid = lo->killpriv_v2 && (valid & FUSE_SET_ATTR_KILL_SUIDGID);
752 if (fi) {
753 truncfd = fd;
754 } else {
755 truncfd = lo_inode_open(lo, inode, O_RDWR);
756 if (truncfd < 0) {
757 saverr = -truncfd;
758 goto out_err;
762 if (kill_suidgid) {
763 res = drop_effective_cap("FSETID", &cap_fsetid_dropped);
764 if (res != 0) {
765 saverr = res;
766 if (!fi) {
767 close(truncfd);
769 goto out_err;
773 res = ftruncate(truncfd, attr->st_size);
774 saverr = res == -1 ? errno : 0;
776 if (cap_fsetid_dropped) {
777 if (gain_effective_cap("FSETID")) {
778 fuse_log(FUSE_LOG_ERR, "Failed to gain CAP_FSETID\n");
781 if (!fi) {
782 close(truncfd);
784 if (res == -1) {
785 goto out_err;
788 if (valid & (FUSE_SET_ATTR_ATIME | FUSE_SET_ATTR_MTIME)) {
789 struct timespec tv[2];
791 tv[0].tv_sec = 0;
792 tv[1].tv_sec = 0;
793 tv[0].tv_nsec = UTIME_OMIT;
794 tv[1].tv_nsec = UTIME_OMIT;
796 if (valid & FUSE_SET_ATTR_ATIME_NOW) {
797 tv[0].tv_nsec = UTIME_NOW;
798 } else if (valid & FUSE_SET_ATTR_ATIME) {
799 tv[0] = attr->st_atim;
802 if (valid & FUSE_SET_ATTR_MTIME_NOW) {
803 tv[1].tv_nsec = UTIME_NOW;
804 } else if (valid & FUSE_SET_ATTR_MTIME) {
805 tv[1] = attr->st_mtim;
808 if (fi) {
809 res = futimens(fd, tv);
810 } else {
811 sprintf(procname, "%i", inode->fd);
812 res = utimensat(lo->proc_self_fd, procname, tv, 0);
814 if (res == -1) {
815 saverr = errno;
816 goto out_err;
819 lo_inode_put(lo, &inode);
821 return lo_getattr(req, ino, fi);
823 out_err:
824 lo_inode_put(lo, &inode);
825 fuse_reply_err(req, saverr);
828 static struct lo_inode *lo_find(struct lo_data *lo, struct stat *st,
829 uint64_t mnt_id)
831 struct lo_inode *p;
832 struct lo_key key = {
833 .ino = st->st_ino,
834 .dev = st->st_dev,
835 .mnt_id = mnt_id,
838 pthread_mutex_lock(&lo->mutex);
839 p = g_hash_table_lookup(lo->inodes, &key);
840 if (p) {
841 assert(p->nlookup > 0);
842 p->nlookup++;
843 g_atomic_int_inc(&p->refcount);
845 pthread_mutex_unlock(&lo->mutex);
847 return p;
850 /* value_destroy_func for posix_locks GHashTable */
851 static void posix_locks_value_destroy(gpointer data)
853 struct lo_inode_plock *plock = data;
856 * We had used open() for locks and had only one fd. So
857 * closing this fd should release all OFD locks.
859 close(plock->fd);
860 free(plock);
863 static int do_statx(struct lo_data *lo, int dirfd, const char *pathname,
864 struct stat *statbuf, int flags, uint64_t *mnt_id)
866 int res;
868 #if defined(CONFIG_STATX) && defined(STATX_MNT_ID)
869 if (lo->use_statx) {
870 struct statx statxbuf;
872 res = statx(dirfd, pathname, flags, STATX_BASIC_STATS | STATX_MNT_ID,
873 &statxbuf);
874 if (!res) {
875 memset(statbuf, 0, sizeof(*statbuf));
876 statbuf->st_dev = makedev(statxbuf.stx_dev_major,
877 statxbuf.stx_dev_minor);
878 statbuf->st_ino = statxbuf.stx_ino;
879 statbuf->st_mode = statxbuf.stx_mode;
880 statbuf->st_nlink = statxbuf.stx_nlink;
881 statbuf->st_uid = statxbuf.stx_uid;
882 statbuf->st_gid = statxbuf.stx_gid;
883 statbuf->st_rdev = makedev(statxbuf.stx_rdev_major,
884 statxbuf.stx_rdev_minor);
885 statbuf->st_size = statxbuf.stx_size;
886 statbuf->st_blksize = statxbuf.stx_blksize;
887 statbuf->st_blocks = statxbuf.stx_blocks;
888 statbuf->st_atim.tv_sec = statxbuf.stx_atime.tv_sec;
889 statbuf->st_atim.tv_nsec = statxbuf.stx_atime.tv_nsec;
890 statbuf->st_mtim.tv_sec = statxbuf.stx_mtime.tv_sec;
891 statbuf->st_mtim.tv_nsec = statxbuf.stx_mtime.tv_nsec;
892 statbuf->st_ctim.tv_sec = statxbuf.stx_ctime.tv_sec;
893 statbuf->st_ctim.tv_nsec = statxbuf.stx_ctime.tv_nsec;
895 if (statxbuf.stx_mask & STATX_MNT_ID) {
896 *mnt_id = statxbuf.stx_mnt_id;
897 } else {
898 *mnt_id = 0;
900 return 0;
901 } else if (errno != ENOSYS) {
902 return -1;
904 lo->use_statx = false;
905 /* fallback */
907 #endif
908 res = fstatat(dirfd, pathname, statbuf, flags);
909 if (res == -1) {
910 return -1;
912 *mnt_id = 0;
914 return 0;
918 * Increments nlookup on the inode on success. unref_inode_lolocked() must be
919 * called eventually to decrement nlookup again. If inodep is non-NULL, the
920 * inode pointer is stored and the caller must call lo_inode_put().
922 static int lo_do_lookup(fuse_req_t req, fuse_ino_t parent, const char *name,
923 struct fuse_entry_param *e,
924 struct lo_inode **inodep)
926 int newfd;
927 int res;
928 int saverr;
929 uint64_t mnt_id;
930 struct lo_data *lo = lo_data(req);
931 struct lo_inode *inode = NULL;
932 struct lo_inode *dir = lo_inode(req, parent);
934 if (inodep) {
935 *inodep = NULL; /* in case there is an error */
939 * name_to_handle_at() and open_by_handle_at() can reach here with fuse
940 * mount point in guest, but we don't have its inode info in the
941 * ino_map.
943 if (!dir) {
944 return ENOENT;
947 memset(e, 0, sizeof(*e));
948 e->attr_timeout = lo->timeout;
949 e->entry_timeout = lo->timeout;
951 /* Do not allow escaping root directory */
952 if (dir == &lo->root && strcmp(name, "..") == 0) {
953 name = ".";
956 newfd = openat(dir->fd, name, O_PATH | O_NOFOLLOW);
957 if (newfd == -1) {
958 goto out_err;
961 res = do_statx(lo, newfd, "", &e->attr, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW,
962 &mnt_id);
963 if (res == -1) {
964 goto out_err;
967 if (S_ISDIR(e->attr.st_mode) && lo->announce_submounts &&
968 (e->attr.st_dev != dir->key.dev || mnt_id != dir->key.mnt_id)) {
969 e->attr_flags |= FUSE_ATTR_SUBMOUNT;
972 inode = lo_find(lo, &e->attr, mnt_id);
973 if (inode) {
974 close(newfd);
975 } else {
976 inode = calloc(1, sizeof(struct lo_inode));
977 if (!inode) {
978 goto out_err;
981 /* cache only filetype */
982 inode->filetype = (e->attr.st_mode & S_IFMT);
985 * One for the caller and one for nlookup (released in
986 * unref_inode_lolocked())
988 g_atomic_int_set(&inode->refcount, 2);
990 inode->nlookup = 1;
991 inode->fd = newfd;
992 inode->key.ino = e->attr.st_ino;
993 inode->key.dev = e->attr.st_dev;
994 inode->key.mnt_id = mnt_id;
995 if (lo->posix_lock) {
996 pthread_mutex_init(&inode->plock_mutex, NULL);
997 inode->posix_locks = g_hash_table_new_full(
998 g_direct_hash, g_direct_equal, NULL, posix_locks_value_destroy);
1000 pthread_mutex_lock(&lo->mutex);
1001 inode->fuse_ino = lo_add_inode_mapping(req, inode);
1002 g_hash_table_insert(lo->inodes, &inode->key, inode);
1003 pthread_mutex_unlock(&lo->mutex);
1005 e->ino = inode->fuse_ino;
1007 /* Transfer ownership of inode pointer to caller or drop it */
1008 if (inodep) {
1009 *inodep = inode;
1010 } else {
1011 lo_inode_put(lo, &inode);
1014 lo_inode_put(lo, &dir);
1016 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
1017 name, (unsigned long long)e->ino);
1019 return 0;
1021 out_err:
1022 saverr = errno;
1023 if (newfd != -1) {
1024 close(newfd);
1026 lo_inode_put(lo, &inode);
1027 lo_inode_put(lo, &dir);
1028 return saverr;
1031 static void lo_lookup(fuse_req_t req, fuse_ino_t parent, const char *name)
1033 struct fuse_entry_param e;
1034 int err;
1036 fuse_log(FUSE_LOG_DEBUG, "lo_lookup(parent=%" PRIu64 ", name=%s)\n", parent,
1037 name);
1040 * Don't use is_safe_path_component(), allow "." and ".." for NFS export
1041 * support.
1043 if (strchr(name, '/')) {
1044 fuse_reply_err(req, EINVAL);
1045 return;
1048 err = lo_do_lookup(req, parent, name, &e, NULL);
1049 if (err) {
1050 fuse_reply_err(req, err);
1051 } else {
1052 fuse_reply_entry(req, &e);
1057 * On some archs, setres*id is limited to 2^16 but they
1058 * provide setres*id32 variants that allow 2^32.
1059 * Others just let setres*id do 2^32 anyway.
1061 #ifdef SYS_setresgid32
1062 #define OURSYS_setresgid SYS_setresgid32
1063 #else
1064 #define OURSYS_setresgid SYS_setresgid
1065 #endif
1067 #ifdef SYS_setresuid32
1068 #define OURSYS_setresuid SYS_setresuid32
1069 #else
1070 #define OURSYS_setresuid SYS_setresuid
1071 #endif
1074 * Change to uid/gid of caller so that file is created with
1075 * ownership of caller.
1076 * TODO: What about selinux context?
1078 static int lo_change_cred(fuse_req_t req, struct lo_cred *old)
1080 int res;
1082 old->euid = geteuid();
1083 old->egid = getegid();
1085 res = syscall(OURSYS_setresgid, -1, fuse_req_ctx(req)->gid, -1);
1086 if (res == -1) {
1087 return errno;
1090 res = syscall(OURSYS_setresuid, -1, fuse_req_ctx(req)->uid, -1);
1091 if (res == -1) {
1092 int errno_save = errno;
1094 syscall(OURSYS_setresgid, -1, old->egid, -1);
1095 return errno_save;
1098 return 0;
1101 /* Regain Privileges */
1102 static void lo_restore_cred(struct lo_cred *old)
1104 int res;
1106 res = syscall(OURSYS_setresuid, -1, old->euid, -1);
1107 if (res == -1) {
1108 fuse_log(FUSE_LOG_ERR, "seteuid(%u): %m\n", old->euid);
1109 exit(1);
1112 res = syscall(OURSYS_setresgid, -1, old->egid, -1);
1113 if (res == -1) {
1114 fuse_log(FUSE_LOG_ERR, "setegid(%u): %m\n", old->egid);
1115 exit(1);
1119 static void lo_mknod_symlink(fuse_req_t req, fuse_ino_t parent,
1120 const char *name, mode_t mode, dev_t rdev,
1121 const char *link)
1123 int res;
1124 int saverr;
1125 struct lo_data *lo = lo_data(req);
1126 struct lo_inode *dir;
1127 struct fuse_entry_param e;
1128 struct lo_cred old = {};
1130 if (!is_safe_path_component(name)) {
1131 fuse_reply_err(req, EINVAL);
1132 return;
1135 dir = lo_inode(req, parent);
1136 if (!dir) {
1137 fuse_reply_err(req, EBADF);
1138 return;
1141 saverr = lo_change_cred(req, &old);
1142 if (saverr) {
1143 goto out;
1146 res = mknod_wrapper(dir->fd, name, link, mode, rdev);
1148 saverr = errno;
1150 lo_restore_cred(&old);
1152 if (res == -1) {
1153 goto out;
1156 saverr = lo_do_lookup(req, parent, name, &e, NULL);
1157 if (saverr) {
1158 goto out;
1161 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
1162 name, (unsigned long long)e.ino);
1164 fuse_reply_entry(req, &e);
1165 lo_inode_put(lo, &dir);
1166 return;
1168 out:
1169 lo_inode_put(lo, &dir);
1170 fuse_reply_err(req, saverr);
1173 static void lo_mknod(fuse_req_t req, fuse_ino_t parent, const char *name,
1174 mode_t mode, dev_t rdev)
1176 lo_mknod_symlink(req, parent, name, mode, rdev, NULL);
1179 static void lo_mkdir(fuse_req_t req, fuse_ino_t parent, const char *name,
1180 mode_t mode)
1182 lo_mknod_symlink(req, parent, name, S_IFDIR | mode, 0, NULL);
1185 static void lo_symlink(fuse_req_t req, const char *link, fuse_ino_t parent,
1186 const char *name)
1188 lo_mknod_symlink(req, parent, name, S_IFLNK, 0, link);
1191 static void lo_link(fuse_req_t req, fuse_ino_t ino, fuse_ino_t parent,
1192 const char *name)
1194 int res;
1195 struct lo_data *lo = lo_data(req);
1196 struct lo_inode *parent_inode;
1197 struct lo_inode *inode;
1198 struct fuse_entry_param e;
1199 char procname[64];
1200 int saverr;
1202 if (!is_safe_path_component(name)) {
1203 fuse_reply_err(req, EINVAL);
1204 return;
1207 parent_inode = lo_inode(req, parent);
1208 inode = lo_inode(req, ino);
1209 if (!parent_inode || !inode) {
1210 errno = EBADF;
1211 goto out_err;
1214 memset(&e, 0, sizeof(struct fuse_entry_param));
1215 e.attr_timeout = lo->timeout;
1216 e.entry_timeout = lo->timeout;
1218 sprintf(procname, "%i", inode->fd);
1219 res = linkat(lo->proc_self_fd, procname, parent_inode->fd, name,
1220 AT_SYMLINK_FOLLOW);
1221 if (res == -1) {
1222 goto out_err;
1225 res = fstatat(inode->fd, "", &e.attr, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW);
1226 if (res == -1) {
1227 goto out_err;
1230 pthread_mutex_lock(&lo->mutex);
1231 inode->nlookup++;
1232 pthread_mutex_unlock(&lo->mutex);
1233 e.ino = inode->fuse_ino;
1235 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
1236 name, (unsigned long long)e.ino);
1238 fuse_reply_entry(req, &e);
1239 lo_inode_put(lo, &parent_inode);
1240 lo_inode_put(lo, &inode);
1241 return;
1243 out_err:
1244 saverr = errno;
1245 lo_inode_put(lo, &parent_inode);
1246 lo_inode_put(lo, &inode);
1247 fuse_reply_err(req, saverr);
1250 /* Increments nlookup and caller must release refcount using lo_inode_put() */
1251 static struct lo_inode *lookup_name(fuse_req_t req, fuse_ino_t parent,
1252 const char *name)
1254 int res;
1255 uint64_t mnt_id;
1256 struct stat attr;
1257 struct lo_data *lo = lo_data(req);
1258 struct lo_inode *dir = lo_inode(req, parent);
1260 if (!dir) {
1261 return NULL;
1264 res = do_statx(lo, dir->fd, name, &attr,
1265 AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW, &mnt_id);
1266 lo_inode_put(lo, &dir);
1267 if (res == -1) {
1268 return NULL;
1271 return lo_find(lo, &attr, mnt_id);
1274 static void lo_rmdir(fuse_req_t req, fuse_ino_t parent, const char *name)
1276 int res;
1277 struct lo_inode *inode;
1278 struct lo_data *lo = lo_data(req);
1280 if (!is_safe_path_component(name)) {
1281 fuse_reply_err(req, EINVAL);
1282 return;
1285 inode = lookup_name(req, parent, name);
1286 if (!inode) {
1287 fuse_reply_err(req, EIO);
1288 return;
1291 res = unlinkat(lo_fd(req, parent), name, AT_REMOVEDIR);
1293 fuse_reply_err(req, res == -1 ? errno : 0);
1294 unref_inode_lolocked(lo, inode, 1);
1295 lo_inode_put(lo, &inode);
1298 static void lo_rename(fuse_req_t req, fuse_ino_t parent, const char *name,
1299 fuse_ino_t newparent, const char *newname,
1300 unsigned int flags)
1302 int res;
1303 struct lo_inode *parent_inode;
1304 struct lo_inode *newparent_inode;
1305 struct lo_inode *oldinode = NULL;
1306 struct lo_inode *newinode = NULL;
1307 struct lo_data *lo = lo_data(req);
1309 if (!is_safe_path_component(name) || !is_safe_path_component(newname)) {
1310 fuse_reply_err(req, EINVAL);
1311 return;
1314 parent_inode = lo_inode(req, parent);
1315 newparent_inode = lo_inode(req, newparent);
1316 if (!parent_inode || !newparent_inode) {
1317 fuse_reply_err(req, EBADF);
1318 goto out;
1321 oldinode = lookup_name(req, parent, name);
1322 newinode = lookup_name(req, newparent, newname);
1324 if (!oldinode) {
1325 fuse_reply_err(req, EIO);
1326 goto out;
1329 if (flags) {
1330 #ifndef SYS_renameat2
1331 fuse_reply_err(req, EINVAL);
1332 #else
1333 res = syscall(SYS_renameat2, parent_inode->fd, name,
1334 newparent_inode->fd, newname, flags);
1335 if (res == -1 && errno == ENOSYS) {
1336 fuse_reply_err(req, EINVAL);
1337 } else {
1338 fuse_reply_err(req, res == -1 ? errno : 0);
1340 #endif
1341 goto out;
1344 res = renameat(parent_inode->fd, name, newparent_inode->fd, newname);
1346 fuse_reply_err(req, res == -1 ? errno : 0);
1347 out:
1348 unref_inode_lolocked(lo, oldinode, 1);
1349 unref_inode_lolocked(lo, newinode, 1);
1350 lo_inode_put(lo, &oldinode);
1351 lo_inode_put(lo, &newinode);
1352 lo_inode_put(lo, &parent_inode);
1353 lo_inode_put(lo, &newparent_inode);
1356 static void lo_unlink(fuse_req_t req, fuse_ino_t parent, const char *name)
1358 int res;
1359 struct lo_inode *inode;
1360 struct lo_data *lo = lo_data(req);
1362 if (!is_safe_path_component(name)) {
1363 fuse_reply_err(req, EINVAL);
1364 return;
1367 inode = lookup_name(req, parent, name);
1368 if (!inode) {
1369 fuse_reply_err(req, EIO);
1370 return;
1373 res = unlinkat(lo_fd(req, parent), name, 0);
1375 fuse_reply_err(req, res == -1 ? errno : 0);
1376 unref_inode_lolocked(lo, inode, 1);
1377 lo_inode_put(lo, &inode);
1380 /* To be called with lo->mutex held */
1381 static void unref_inode(struct lo_data *lo, struct lo_inode *inode, uint64_t n)
1383 if (!inode) {
1384 return;
1387 assert(inode->nlookup >= n);
1388 inode->nlookup -= n;
1389 if (!inode->nlookup) {
1390 lo_map_remove(&lo->ino_map, inode->fuse_ino);
1391 g_hash_table_remove(lo->inodes, &inode->key);
1392 if (lo->posix_lock) {
1393 if (g_hash_table_size(inode->posix_locks)) {
1394 fuse_log(FUSE_LOG_WARNING, "Hash table is not empty\n");
1396 g_hash_table_destroy(inode->posix_locks);
1397 pthread_mutex_destroy(&inode->plock_mutex);
1399 /* Drop our refcount from lo_do_lookup() */
1400 lo_inode_put(lo, &inode);
1404 static void unref_inode_lolocked(struct lo_data *lo, struct lo_inode *inode,
1405 uint64_t n)
1407 if (!inode) {
1408 return;
1411 pthread_mutex_lock(&lo->mutex);
1412 unref_inode(lo, inode, n);
1413 pthread_mutex_unlock(&lo->mutex);
1416 static void lo_forget_one(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup)
1418 struct lo_data *lo = lo_data(req);
1419 struct lo_inode *inode;
1421 inode = lo_inode(req, ino);
1422 if (!inode) {
1423 return;
1426 fuse_log(FUSE_LOG_DEBUG, " forget %lli %lli -%lli\n",
1427 (unsigned long long)ino, (unsigned long long)inode->nlookup,
1428 (unsigned long long)nlookup);
1430 unref_inode_lolocked(lo, inode, nlookup);
1431 lo_inode_put(lo, &inode);
1434 static void lo_forget(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup)
1436 lo_forget_one(req, ino, nlookup);
1437 fuse_reply_none(req);
1440 static void lo_forget_multi(fuse_req_t req, size_t count,
1441 struct fuse_forget_data *forgets)
1443 int i;
1445 for (i = 0; i < count; i++) {
1446 lo_forget_one(req, forgets[i].ino, forgets[i].nlookup);
1448 fuse_reply_none(req);
1451 static void lo_readlink(fuse_req_t req, fuse_ino_t ino)
1453 char buf[PATH_MAX + 1];
1454 int res;
1456 res = readlinkat(lo_fd(req, ino), "", buf, sizeof(buf));
1457 if (res == -1) {
1458 return (void)fuse_reply_err(req, errno);
1461 if (res == sizeof(buf)) {
1462 return (void)fuse_reply_err(req, ENAMETOOLONG);
1465 buf[res] = '\0';
1467 fuse_reply_readlink(req, buf);
1470 struct lo_dirp {
1471 gint refcount;
1472 DIR *dp;
1473 struct dirent *entry;
1474 off_t offset;
1477 static void lo_dirp_put(struct lo_dirp **dp)
1479 struct lo_dirp *d = *dp;
1481 if (!d) {
1482 return;
1484 *dp = NULL;
1486 if (g_atomic_int_dec_and_test(&d->refcount)) {
1487 closedir(d->dp);
1488 free(d);
1492 /* Call lo_dirp_put() on the return value when no longer needed */
1493 static struct lo_dirp *lo_dirp(fuse_req_t req, struct fuse_file_info *fi)
1495 struct lo_data *lo = lo_data(req);
1496 struct lo_map_elem *elem;
1498 pthread_mutex_lock(&lo->mutex);
1499 elem = lo_map_get(&lo->dirp_map, fi->fh);
1500 if (elem) {
1501 g_atomic_int_inc(&elem->dirp->refcount);
1503 pthread_mutex_unlock(&lo->mutex);
1504 if (!elem) {
1505 return NULL;
1508 return elem->dirp;
1511 static void lo_opendir(fuse_req_t req, fuse_ino_t ino,
1512 struct fuse_file_info *fi)
1514 int error = ENOMEM;
1515 struct lo_data *lo = lo_data(req);
1516 struct lo_dirp *d;
1517 int fd;
1518 ssize_t fh;
1520 d = calloc(1, sizeof(struct lo_dirp));
1521 if (d == NULL) {
1522 goto out_err;
1525 fd = openat(lo_fd(req, ino), ".", O_RDONLY);
1526 if (fd == -1) {
1527 goto out_errno;
1530 d->dp = fdopendir(fd);
1531 if (d->dp == NULL) {
1532 goto out_errno;
1535 d->offset = 0;
1536 d->entry = NULL;
1538 g_atomic_int_set(&d->refcount, 1); /* paired with lo_releasedir() */
1539 pthread_mutex_lock(&lo->mutex);
1540 fh = lo_add_dirp_mapping(req, d);
1541 pthread_mutex_unlock(&lo->mutex);
1542 if (fh == -1) {
1543 goto out_err;
1546 fi->fh = fh;
1547 if (lo->cache == CACHE_ALWAYS) {
1548 fi->cache_readdir = 1;
1550 fuse_reply_open(req, fi);
1551 return;
1553 out_errno:
1554 error = errno;
1555 out_err:
1556 if (d) {
1557 if (d->dp) {
1558 closedir(d->dp);
1559 } else if (fd != -1) {
1560 close(fd);
1562 free(d);
1564 fuse_reply_err(req, error);
1567 static void lo_do_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
1568 off_t offset, struct fuse_file_info *fi, int plus)
1570 struct lo_data *lo = lo_data(req);
1571 struct lo_dirp *d = NULL;
1572 struct lo_inode *dinode;
1573 char *buf = NULL;
1574 char *p;
1575 size_t rem = size;
1576 int err = EBADF;
1578 dinode = lo_inode(req, ino);
1579 if (!dinode) {
1580 goto error;
1583 d = lo_dirp(req, fi);
1584 if (!d) {
1585 goto error;
1588 err = ENOMEM;
1589 buf = calloc(1, size);
1590 if (!buf) {
1591 goto error;
1593 p = buf;
1595 if (offset != d->offset) {
1596 seekdir(d->dp, offset);
1597 d->entry = NULL;
1598 d->offset = offset;
1600 while (1) {
1601 size_t entsize;
1602 off_t nextoff;
1603 const char *name;
1605 if (!d->entry) {
1606 errno = 0;
1607 d->entry = readdir(d->dp);
1608 if (!d->entry) {
1609 if (errno) { /* Error */
1610 err = errno;
1611 goto error;
1612 } else { /* End of stream */
1613 break;
1617 nextoff = d->entry->d_off;
1618 name = d->entry->d_name;
1620 fuse_ino_t entry_ino = 0;
1621 struct fuse_entry_param e = (struct fuse_entry_param){
1622 .attr.st_ino = d->entry->d_ino,
1623 .attr.st_mode = d->entry->d_type << 12,
1626 /* Hide root's parent directory */
1627 if (dinode == &lo->root && strcmp(name, "..") == 0) {
1628 e.attr.st_ino = lo->root.key.ino;
1629 e.attr.st_mode = DT_DIR << 12;
1632 if (plus) {
1633 if (!is_dot_or_dotdot(name)) {
1634 err = lo_do_lookup(req, ino, name, &e, NULL);
1635 if (err) {
1636 goto error;
1638 entry_ino = e.ino;
1641 entsize = fuse_add_direntry_plus(req, p, rem, name, &e, nextoff);
1642 } else {
1643 entsize = fuse_add_direntry(req, p, rem, name, &e.attr, nextoff);
1645 if (entsize > rem) {
1646 if (entry_ino != 0) {
1647 lo_forget_one(req, entry_ino, 1);
1649 break;
1652 p += entsize;
1653 rem -= entsize;
1655 d->entry = NULL;
1656 d->offset = nextoff;
1659 err = 0;
1660 error:
1661 lo_dirp_put(&d);
1662 lo_inode_put(lo, &dinode);
1665 * If there's an error, we can only signal it if we haven't stored
1666 * any entries yet - otherwise we'd end up with wrong lookup
1667 * counts for the entries that are already in the buffer. So we
1668 * return what we've collected until that point.
1670 if (err && rem == size) {
1671 fuse_reply_err(req, err);
1672 } else {
1673 fuse_reply_buf(req, buf, size - rem);
1675 free(buf);
1678 static void lo_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
1679 off_t offset, struct fuse_file_info *fi)
1681 lo_do_readdir(req, ino, size, offset, fi, 0);
1684 static void lo_readdirplus(fuse_req_t req, fuse_ino_t ino, size_t size,
1685 off_t offset, struct fuse_file_info *fi)
1687 lo_do_readdir(req, ino, size, offset, fi, 1);
1690 static void lo_releasedir(fuse_req_t req, fuse_ino_t ino,
1691 struct fuse_file_info *fi)
1693 struct lo_data *lo = lo_data(req);
1694 struct lo_map_elem *elem;
1695 struct lo_dirp *d;
1697 (void)ino;
1699 pthread_mutex_lock(&lo->mutex);
1700 elem = lo_map_get(&lo->dirp_map, fi->fh);
1701 if (!elem) {
1702 pthread_mutex_unlock(&lo->mutex);
1703 fuse_reply_err(req, EBADF);
1704 return;
1707 d = elem->dirp;
1708 lo_map_remove(&lo->dirp_map, fi->fh);
1709 pthread_mutex_unlock(&lo->mutex);
1711 lo_dirp_put(&d); /* paired with lo_opendir() */
1713 fuse_reply_err(req, 0);
1716 static void update_open_flags(int writeback, int allow_direct_io,
1717 struct fuse_file_info *fi)
1720 * With writeback cache, kernel may send read requests even
1721 * when userspace opened write-only
1723 if (writeback && (fi->flags & O_ACCMODE) == O_WRONLY) {
1724 fi->flags &= ~O_ACCMODE;
1725 fi->flags |= O_RDWR;
1729 * With writeback cache, O_APPEND is handled by the kernel.
1730 * This breaks atomicity (since the file may change in the
1731 * underlying filesystem, so that the kernel's idea of the
1732 * end of the file isn't accurate anymore). In this example,
1733 * we just accept that. A more rigorous filesystem may want
1734 * to return an error here
1736 if (writeback && (fi->flags & O_APPEND)) {
1737 fi->flags &= ~O_APPEND;
1741 * O_DIRECT in guest should not necessarily mean bypassing page
1742 * cache on host as well. Therefore, we discard it by default
1743 * ('-o no_allow_direct_io'). If somebody needs that behavior,
1744 * the '-o allow_direct_io' option should be set.
1746 if (!allow_direct_io) {
1747 fi->flags &= ~O_DIRECT;
1752 * Open a regular file, set up an fd mapping, and fill out the struct
1753 * fuse_file_info for it. If existing_fd is not negative, use that fd instead
1754 * opening a new one. Takes ownership of existing_fd.
1756 * Returns 0 on success or a positive errno.
1758 static int lo_do_open(struct lo_data *lo, struct lo_inode *inode,
1759 int existing_fd, struct fuse_file_info *fi)
1761 ssize_t fh;
1762 int fd = existing_fd;
1763 int err;
1764 bool cap_fsetid_dropped = false;
1765 bool kill_suidgid = lo->killpriv_v2 && fi->kill_priv;
1767 update_open_flags(lo->writeback, lo->allow_direct_io, fi);
1769 if (fd < 0) {
1770 if (kill_suidgid) {
1771 err = drop_effective_cap("FSETID", &cap_fsetid_dropped);
1772 if (err) {
1773 return err;
1777 fd = lo_inode_open(lo, inode, fi->flags);
1779 if (cap_fsetid_dropped) {
1780 if (gain_effective_cap("FSETID")) {
1781 fuse_log(FUSE_LOG_ERR, "Failed to gain CAP_FSETID\n");
1784 if (fd < 0) {
1785 return -fd;
1789 pthread_mutex_lock(&lo->mutex);
1790 fh = lo_add_fd_mapping(lo, fd);
1791 pthread_mutex_unlock(&lo->mutex);
1792 if (fh == -1) {
1793 close(fd);
1794 return ENOMEM;
1797 fi->fh = fh;
1798 if (lo->cache == CACHE_NONE) {
1799 fi->direct_io = 1;
1800 } else if (lo->cache == CACHE_ALWAYS) {
1801 fi->keep_cache = 1;
1803 return 0;
1806 static void lo_create(fuse_req_t req, fuse_ino_t parent, const char *name,
1807 mode_t mode, struct fuse_file_info *fi)
1809 int fd = -1;
1810 struct lo_data *lo = lo_data(req);
1811 struct lo_inode *parent_inode;
1812 struct lo_inode *inode = NULL;
1813 struct fuse_entry_param e;
1814 int err;
1815 struct lo_cred old = {};
1817 fuse_log(FUSE_LOG_DEBUG, "lo_create(parent=%" PRIu64 ", name=%s)"
1818 " kill_priv=%d\n", parent, name, fi->kill_priv);
1820 if (!is_safe_path_component(name)) {
1821 fuse_reply_err(req, EINVAL);
1822 return;
1825 parent_inode = lo_inode(req, parent);
1826 if (!parent_inode) {
1827 fuse_reply_err(req, EBADF);
1828 return;
1831 err = lo_change_cred(req, &old);
1832 if (err) {
1833 goto out;
1836 update_open_flags(lo->writeback, lo->allow_direct_io, fi);
1838 /* Try to create a new file but don't open existing files */
1839 fd = openat(parent_inode->fd, name, fi->flags | O_CREAT | O_EXCL, mode);
1840 err = fd == -1 ? errno : 0;
1842 lo_restore_cred(&old);
1844 /* Ignore the error if file exists and O_EXCL was not given */
1845 if (err && (err != EEXIST || (fi->flags & O_EXCL))) {
1846 goto out;
1849 err = lo_do_lookup(req, parent, name, &e, &inode);
1850 if (err) {
1851 goto out;
1854 err = lo_do_open(lo, inode, fd, fi);
1855 fd = -1; /* lo_do_open() takes ownership of fd */
1856 if (err) {
1857 /* Undo lo_do_lookup() nlookup ref */
1858 unref_inode_lolocked(lo, inode, 1);
1861 out:
1862 lo_inode_put(lo, &inode);
1863 lo_inode_put(lo, &parent_inode);
1865 if (err) {
1866 if (fd >= 0) {
1867 close(fd);
1870 fuse_reply_err(req, err);
1871 } else {
1872 fuse_reply_create(req, &e, fi);
1876 /* Should be called with inode->plock_mutex held */
1877 static struct lo_inode_plock *lookup_create_plock_ctx(struct lo_data *lo,
1878 struct lo_inode *inode,
1879 uint64_t lock_owner,
1880 pid_t pid, int *err)
1882 struct lo_inode_plock *plock;
1883 int fd;
1885 plock =
1886 g_hash_table_lookup(inode->posix_locks, GUINT_TO_POINTER(lock_owner));
1888 if (plock) {
1889 return plock;
1892 plock = malloc(sizeof(struct lo_inode_plock));
1893 if (!plock) {
1894 *err = ENOMEM;
1895 return NULL;
1898 /* Open another instance of file which can be used for ofd locks. */
1899 /* TODO: What if file is not writable? */
1900 fd = lo_inode_open(lo, inode, O_RDWR);
1901 if (fd < 0) {
1902 *err = -fd;
1903 free(plock);
1904 return NULL;
1907 plock->lock_owner = lock_owner;
1908 plock->fd = fd;
1909 g_hash_table_insert(inode->posix_locks, GUINT_TO_POINTER(plock->lock_owner),
1910 plock);
1911 return plock;
1914 static void lo_getlk(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
1915 struct flock *lock)
1917 struct lo_data *lo = lo_data(req);
1918 struct lo_inode *inode;
1919 struct lo_inode_plock *plock;
1920 int ret, saverr = 0;
1922 fuse_log(FUSE_LOG_DEBUG,
1923 "lo_getlk(ino=%" PRIu64 ", flags=%d)"
1924 " owner=0x%lx, l_type=%d l_start=0x%lx"
1925 " l_len=0x%lx\n",
1926 ino, fi->flags, fi->lock_owner, lock->l_type, lock->l_start,
1927 lock->l_len);
1929 if (!lo->posix_lock) {
1930 fuse_reply_err(req, ENOSYS);
1931 return;
1934 inode = lo_inode(req, ino);
1935 if (!inode) {
1936 fuse_reply_err(req, EBADF);
1937 return;
1940 pthread_mutex_lock(&inode->plock_mutex);
1941 plock =
1942 lookup_create_plock_ctx(lo, inode, fi->lock_owner, lock->l_pid, &ret);
1943 if (!plock) {
1944 saverr = ret;
1945 goto out;
1948 ret = fcntl(plock->fd, F_OFD_GETLK, lock);
1949 if (ret == -1) {
1950 saverr = errno;
1953 out:
1954 pthread_mutex_unlock(&inode->plock_mutex);
1955 lo_inode_put(lo, &inode);
1957 if (saverr) {
1958 fuse_reply_err(req, saverr);
1959 } else {
1960 fuse_reply_lock(req, lock);
1964 static void lo_setlk(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
1965 struct flock *lock, int sleep)
1967 struct lo_data *lo = lo_data(req);
1968 struct lo_inode *inode;
1969 struct lo_inode_plock *plock;
1970 int ret, saverr = 0;
1972 fuse_log(FUSE_LOG_DEBUG,
1973 "lo_setlk(ino=%" PRIu64 ", flags=%d)"
1974 " cmd=%d pid=%d owner=0x%lx sleep=%d l_whence=%d"
1975 " l_start=0x%lx l_len=0x%lx\n",
1976 ino, fi->flags, lock->l_type, lock->l_pid, fi->lock_owner, sleep,
1977 lock->l_whence, lock->l_start, lock->l_len);
1979 if (!lo->posix_lock) {
1980 fuse_reply_err(req, ENOSYS);
1981 return;
1984 if (sleep) {
1985 fuse_reply_err(req, EOPNOTSUPP);
1986 return;
1989 inode = lo_inode(req, ino);
1990 if (!inode) {
1991 fuse_reply_err(req, EBADF);
1992 return;
1995 pthread_mutex_lock(&inode->plock_mutex);
1996 plock =
1997 lookup_create_plock_ctx(lo, inode, fi->lock_owner, lock->l_pid, &ret);
1999 if (!plock) {
2000 saverr = ret;
2001 goto out;
2004 /* TODO: Is it alright to modify flock? */
2005 lock->l_pid = 0;
2006 ret = fcntl(plock->fd, F_OFD_SETLK, lock);
2007 if (ret == -1) {
2008 saverr = errno;
2011 out:
2012 pthread_mutex_unlock(&inode->plock_mutex);
2013 lo_inode_put(lo, &inode);
2015 fuse_reply_err(req, saverr);
2018 static void lo_fsyncdir(fuse_req_t req, fuse_ino_t ino, int datasync,
2019 struct fuse_file_info *fi)
2021 int res;
2022 struct lo_dirp *d;
2023 int fd;
2025 (void)ino;
2027 d = lo_dirp(req, fi);
2028 if (!d) {
2029 fuse_reply_err(req, EBADF);
2030 return;
2033 fd = dirfd(d->dp);
2034 if (datasync) {
2035 res = fdatasync(fd);
2036 } else {
2037 res = fsync(fd);
2040 lo_dirp_put(&d);
2042 fuse_reply_err(req, res == -1 ? errno : 0);
2045 static void lo_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi)
2047 struct lo_data *lo = lo_data(req);
2048 struct lo_inode *inode = lo_inode(req, ino);
2049 int err;
2051 fuse_log(FUSE_LOG_DEBUG, "lo_open(ino=%" PRIu64 ", flags=%d, kill_priv=%d)"
2052 "\n", ino, fi->flags, fi->kill_priv);
2054 if (!inode) {
2055 fuse_reply_err(req, EBADF);
2056 return;
2059 err = lo_do_open(lo, inode, -1, fi);
2060 lo_inode_put(lo, &inode);
2061 if (err) {
2062 fuse_reply_err(req, err);
2063 } else {
2064 fuse_reply_open(req, fi);
2068 static void lo_release(fuse_req_t req, fuse_ino_t ino,
2069 struct fuse_file_info *fi)
2071 struct lo_data *lo = lo_data(req);
2072 struct lo_map_elem *elem;
2073 int fd = -1;
2075 (void)ino;
2077 pthread_mutex_lock(&lo->mutex);
2078 elem = lo_map_get(&lo->fd_map, fi->fh);
2079 if (elem) {
2080 fd = elem->fd;
2081 elem = NULL;
2082 lo_map_remove(&lo->fd_map, fi->fh);
2084 pthread_mutex_unlock(&lo->mutex);
2086 close(fd);
2087 fuse_reply_err(req, 0);
2090 static void lo_flush(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi)
2092 int res;
2093 (void)ino;
2094 struct lo_inode *inode;
2095 struct lo_data *lo = lo_data(req);
2097 inode = lo_inode(req, ino);
2098 if (!inode) {
2099 fuse_reply_err(req, EBADF);
2100 return;
2103 if (!S_ISREG(inode->filetype)) {
2104 lo_inode_put(lo, &inode);
2105 fuse_reply_err(req, EBADF);
2106 return;
2109 /* An fd is going away. Cleanup associated posix locks */
2110 if (lo->posix_lock) {
2111 pthread_mutex_lock(&inode->plock_mutex);
2112 g_hash_table_remove(inode->posix_locks,
2113 GUINT_TO_POINTER(fi->lock_owner));
2114 pthread_mutex_unlock(&inode->plock_mutex);
2116 res = close(dup(lo_fi_fd(req, fi)));
2117 lo_inode_put(lo, &inode);
2118 fuse_reply_err(req, res == -1 ? errno : 0);
2121 static void lo_fsync(fuse_req_t req, fuse_ino_t ino, int datasync,
2122 struct fuse_file_info *fi)
2124 struct lo_inode *inode = lo_inode(req, ino);
2125 struct lo_data *lo = lo_data(req);
2126 int res;
2127 int fd;
2129 fuse_log(FUSE_LOG_DEBUG, "lo_fsync(ino=%" PRIu64 ", fi=0x%p)\n", ino,
2130 (void *)fi);
2132 if (!inode) {
2133 fuse_reply_err(req, EBADF);
2134 return;
2137 if (!fi) {
2138 fd = lo_inode_open(lo, inode, O_RDWR);
2139 if (fd < 0) {
2140 res = -fd;
2141 goto out;
2143 } else {
2144 fd = lo_fi_fd(req, fi);
2147 if (datasync) {
2148 res = fdatasync(fd) == -1 ? errno : 0;
2149 } else {
2150 res = fsync(fd) == -1 ? errno : 0;
2152 if (!fi) {
2153 close(fd);
2155 out:
2156 lo_inode_put(lo, &inode);
2157 fuse_reply_err(req, res);
2160 static void lo_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t offset,
2161 struct fuse_file_info *fi)
2163 struct fuse_bufvec buf = FUSE_BUFVEC_INIT(size);
2165 fuse_log(FUSE_LOG_DEBUG,
2166 "lo_read(ino=%" PRIu64 ", size=%zd, "
2167 "off=%lu)\n",
2168 ino, size, (unsigned long)offset);
2170 buf.buf[0].flags = FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK;
2171 buf.buf[0].fd = lo_fi_fd(req, fi);
2172 buf.buf[0].pos = offset;
2174 fuse_reply_data(req, &buf);
2177 static void lo_write_buf(fuse_req_t req, fuse_ino_t ino,
2178 struct fuse_bufvec *in_buf, off_t off,
2179 struct fuse_file_info *fi)
2181 (void)ino;
2182 ssize_t res;
2183 struct fuse_bufvec out_buf = FUSE_BUFVEC_INIT(fuse_buf_size(in_buf));
2184 bool cap_fsetid_dropped = false;
2186 out_buf.buf[0].flags = FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK;
2187 out_buf.buf[0].fd = lo_fi_fd(req, fi);
2188 out_buf.buf[0].pos = off;
2190 fuse_log(FUSE_LOG_DEBUG,
2191 "lo_write_buf(ino=%" PRIu64 ", size=%zd, off=%lu kill_priv=%d)\n",
2192 ino, out_buf.buf[0].size, (unsigned long)off, fi->kill_priv);
2195 * If kill_priv is set, drop CAP_FSETID which should lead to kernel
2196 * clearing setuid/setgid on file. Note, for WRITE, we need to do
2197 * this even if killpriv_v2 is not enabled. fuse direct write path
2198 * relies on this.
2200 if (fi->kill_priv) {
2201 res = drop_effective_cap("FSETID", &cap_fsetid_dropped);
2202 if (res != 0) {
2203 fuse_reply_err(req, res);
2204 return;
2208 res = fuse_buf_copy(&out_buf, in_buf);
2209 if (res < 0) {
2210 fuse_reply_err(req, -res);
2211 } else {
2212 fuse_reply_write(req, (size_t)res);
2215 if (cap_fsetid_dropped) {
2216 res = gain_effective_cap("FSETID");
2217 if (res) {
2218 fuse_log(FUSE_LOG_ERR, "Failed to gain CAP_FSETID\n");
2223 static void lo_statfs(fuse_req_t req, fuse_ino_t ino)
2225 int res;
2226 struct statvfs stbuf;
2228 res = fstatvfs(lo_fd(req, ino), &stbuf);
2229 if (res == -1) {
2230 fuse_reply_err(req, errno);
2231 } else {
2232 fuse_reply_statfs(req, &stbuf);
2236 static void lo_fallocate(fuse_req_t req, fuse_ino_t ino, int mode, off_t offset,
2237 off_t length, struct fuse_file_info *fi)
2239 int err = EOPNOTSUPP;
2240 (void)ino;
2242 #ifdef CONFIG_FALLOCATE
2243 err = fallocate(lo_fi_fd(req, fi), mode, offset, length);
2244 if (err < 0) {
2245 err = errno;
2248 #elif defined(CONFIG_POSIX_FALLOCATE)
2249 if (mode) {
2250 fuse_reply_err(req, EOPNOTSUPP);
2251 return;
2254 err = posix_fallocate(lo_fi_fd(req, fi), offset, length);
2255 #endif
2257 fuse_reply_err(req, err);
2260 static void lo_flock(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
2261 int op)
2263 int res;
2264 (void)ino;
2266 res = flock(lo_fi_fd(req, fi), op);
2268 fuse_reply_err(req, res == -1 ? errno : 0);
2271 /* types */
2273 * Exit; process attribute unmodified if matched.
2274 * An empty key applies to all.
2276 #define XATTR_MAP_FLAG_OK (1 << 0)
2278 * The attribute is unwanted;
2279 * EPERM on write, hidden on read.
2281 #define XATTR_MAP_FLAG_BAD (1 << 1)
2283 * For attr that start with 'key' prepend 'prepend'
2284 * 'key' may be empty to prepend for all attrs
2285 * key is defined from set/remove point of view.
2286 * Automatically reversed on read
2288 #define XATTR_MAP_FLAG_PREFIX (1 << 2)
2290 /* scopes */
2291 /* Apply rule to get/set/remove */
2292 #define XATTR_MAP_FLAG_CLIENT (1 << 16)
2293 /* Apply rule to list */
2294 #define XATTR_MAP_FLAG_SERVER (1 << 17)
2295 /* Apply rule to all */
2296 #define XATTR_MAP_FLAG_ALL (XATTR_MAP_FLAG_SERVER | XATTR_MAP_FLAG_CLIENT)
2298 static void add_xattrmap_entry(struct lo_data *lo,
2299 const XattrMapEntry *new_entry)
2301 XattrMapEntry *res = g_realloc_n(lo->xattr_map_list,
2302 lo->xattr_map_nentries + 1,
2303 sizeof(XattrMapEntry));
2304 res[lo->xattr_map_nentries++] = *new_entry;
2306 lo->xattr_map_list = res;
2309 static void free_xattrmap(struct lo_data *lo)
2311 XattrMapEntry *map = lo->xattr_map_list;
2312 size_t i;
2314 if (!map) {
2315 return;
2318 for (i = 0; i < lo->xattr_map_nentries; i++) {
2319 g_free(map[i].key);
2320 g_free(map[i].prepend);
2323 g_free(map);
2324 lo->xattr_map_list = NULL;
2325 lo->xattr_map_nentries = -1;
2329 * Handle the 'map' type, which is sugar for a set of commands
2330 * for the common case of prefixing a subset or everything,
2331 * and allowing anything not prefixed through.
2332 * It must be the last entry in the stream, although there
2333 * can be other entries before it.
2334 * The form is:
2335 * :map:key:prefix:
2337 * key maybe empty in which case all entries are prefixed.
2339 static void parse_xattrmap_map(struct lo_data *lo,
2340 const char *rule, char sep)
2342 const char *tmp;
2343 char *key;
2344 char *prefix;
2345 XattrMapEntry tmp_entry;
2347 if (*rule != sep) {
2348 fuse_log(FUSE_LOG_ERR,
2349 "%s: Expecting '%c' after 'map' keyword, found '%c'\n",
2350 __func__, sep, *rule);
2351 exit(1);
2354 rule++;
2356 /* At start of 'key' field */
2357 tmp = strchr(rule, sep);
2358 if (!tmp) {
2359 fuse_log(FUSE_LOG_ERR,
2360 "%s: Missing '%c' at end of key field in map rule\n",
2361 __func__, sep);
2362 exit(1);
2365 key = g_strndup(rule, tmp - rule);
2366 rule = tmp + 1;
2368 /* At start of prefix field */
2369 tmp = strchr(rule, sep);
2370 if (!tmp) {
2371 fuse_log(FUSE_LOG_ERR,
2372 "%s: Missing '%c' at end of prefix field in map rule\n",
2373 __func__, sep);
2374 exit(1);
2377 prefix = g_strndup(rule, tmp - rule);
2378 rule = tmp + 1;
2381 * This should be the end of the string, we don't allow
2382 * any more commands after 'map'.
2384 if (*rule) {
2385 fuse_log(FUSE_LOG_ERR,
2386 "%s: Expecting end of command after map, found '%c'\n",
2387 __func__, *rule);
2388 exit(1);
2391 /* 1st: Prefix matches/everything */
2392 tmp_entry.flags = XATTR_MAP_FLAG_PREFIX | XATTR_MAP_FLAG_ALL;
2393 tmp_entry.key = g_strdup(key);
2394 tmp_entry.prepend = g_strdup(prefix);
2395 add_xattrmap_entry(lo, &tmp_entry);
2397 if (!*key) {
2398 /* Prefix all case */
2400 /* 2nd: Hide any non-prefixed entries on the host */
2401 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_ALL;
2402 tmp_entry.key = g_strdup("");
2403 tmp_entry.prepend = g_strdup("");
2404 add_xattrmap_entry(lo, &tmp_entry);
2405 } else {
2406 /* Prefix matching case */
2408 /* 2nd: Hide non-prefixed but matching entries on the host */
2409 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_SERVER;
2410 tmp_entry.key = g_strdup(""); /* Not used */
2411 tmp_entry.prepend = g_strdup(key);
2412 add_xattrmap_entry(lo, &tmp_entry);
2414 /* 3rd: Stop the client accessing prefixed attributes directly */
2415 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_CLIENT;
2416 tmp_entry.key = g_strdup(prefix);
2417 tmp_entry.prepend = g_strdup(""); /* Not used */
2418 add_xattrmap_entry(lo, &tmp_entry);
2420 /* 4th: Everything else is OK */
2421 tmp_entry.flags = XATTR_MAP_FLAG_OK | XATTR_MAP_FLAG_ALL;
2422 tmp_entry.key = g_strdup("");
2423 tmp_entry.prepend = g_strdup("");
2424 add_xattrmap_entry(lo, &tmp_entry);
2427 g_free(key);
2428 g_free(prefix);
2431 static void parse_xattrmap(struct lo_data *lo)
2433 const char *map = lo->xattrmap;
2434 const char *tmp;
2436 lo->xattr_map_nentries = 0;
2437 while (*map) {
2438 XattrMapEntry tmp_entry;
2439 char sep;
2441 if (isspace(*map)) {
2442 map++;
2443 continue;
2445 /* The separator is the first non-space of the rule */
2446 sep = *map++;
2447 if (!sep) {
2448 break;
2451 tmp_entry.flags = 0;
2452 /* Start of 'type' */
2453 if (strstart(map, "prefix", &map)) {
2454 tmp_entry.flags |= XATTR_MAP_FLAG_PREFIX;
2455 } else if (strstart(map, "ok", &map)) {
2456 tmp_entry.flags |= XATTR_MAP_FLAG_OK;
2457 } else if (strstart(map, "bad", &map)) {
2458 tmp_entry.flags |= XATTR_MAP_FLAG_BAD;
2459 } else if (strstart(map, "map", &map)) {
2461 * map is sugar that adds a number of rules, and must be
2462 * the last entry.
2464 parse_xattrmap_map(lo, map, sep);
2465 return;
2466 } else {
2467 fuse_log(FUSE_LOG_ERR,
2468 "%s: Unexpected type;"
2469 "Expecting 'prefix', 'ok', 'bad' or 'map' in rule %zu\n",
2470 __func__, lo->xattr_map_nentries);
2471 exit(1);
2474 if (*map++ != sep) {
2475 fuse_log(FUSE_LOG_ERR,
2476 "%s: Missing '%c' at end of type field of rule %zu\n",
2477 __func__, sep, lo->xattr_map_nentries);
2478 exit(1);
2481 /* Start of 'scope' */
2482 if (strstart(map, "client", &map)) {
2483 tmp_entry.flags |= XATTR_MAP_FLAG_CLIENT;
2484 } else if (strstart(map, "server", &map)) {
2485 tmp_entry.flags |= XATTR_MAP_FLAG_SERVER;
2486 } else if (strstart(map, "all", &map)) {
2487 tmp_entry.flags |= XATTR_MAP_FLAG_ALL;
2488 } else {
2489 fuse_log(FUSE_LOG_ERR,
2490 "%s: Unexpected scope;"
2491 " Expecting 'client', 'server', or 'all', in rule %zu\n",
2492 __func__, lo->xattr_map_nentries);
2493 exit(1);
2496 if (*map++ != sep) {
2497 fuse_log(FUSE_LOG_ERR,
2498 "%s: Expecting '%c' found '%c'"
2499 " after scope in rule %zu\n",
2500 __func__, sep, *map, lo->xattr_map_nentries);
2501 exit(1);
2504 /* At start of 'key' field */
2505 tmp = strchr(map, sep);
2506 if (!tmp) {
2507 fuse_log(FUSE_LOG_ERR,
2508 "%s: Missing '%c' at end of key field of rule %zu",
2509 __func__, sep, lo->xattr_map_nentries);
2510 exit(1);
2512 tmp_entry.key = g_strndup(map, tmp - map);
2513 map = tmp + 1;
2515 /* At start of 'prepend' field */
2516 tmp = strchr(map, sep);
2517 if (!tmp) {
2518 fuse_log(FUSE_LOG_ERR,
2519 "%s: Missing '%c' at end of prepend field of rule %zu",
2520 __func__, sep, lo->xattr_map_nentries);
2521 exit(1);
2523 tmp_entry.prepend = g_strndup(map, tmp - map);
2524 map = tmp + 1;
2526 add_xattrmap_entry(lo, &tmp_entry);
2527 /* End of rule - go around again for another rule */
2530 if (!lo->xattr_map_nentries) {
2531 fuse_log(FUSE_LOG_ERR, "Empty xattr map\n");
2532 exit(1);
2537 * For use with getxattr/setxattr/removexattr, where the client
2538 * gives us a name and we may need to choose a different one.
2539 * Allocates a buffer for the result placing it in *out_name.
2540 * If there's no change then *out_name is not set.
2541 * Returns 0 on success
2542 * Can return -EPERM to indicate we block a given attribute
2543 * (in which case out_name is not allocated)
2544 * Can return -ENOMEM to indicate out_name couldn't be allocated.
2546 static int xattr_map_client(const struct lo_data *lo, const char *client_name,
2547 char **out_name)
2549 size_t i;
2550 for (i = 0; i < lo->xattr_map_nentries; i++) {
2551 const XattrMapEntry *cur_entry = lo->xattr_map_list + i;
2553 if ((cur_entry->flags & XATTR_MAP_FLAG_CLIENT) &&
2554 (strstart(client_name, cur_entry->key, NULL))) {
2555 if (cur_entry->flags & XATTR_MAP_FLAG_BAD) {
2556 return -EPERM;
2558 if (cur_entry->flags & XATTR_MAP_FLAG_OK) {
2559 /* Unmodified name */
2560 return 0;
2562 if (cur_entry->flags & XATTR_MAP_FLAG_PREFIX) {
2563 *out_name = g_try_malloc(strlen(client_name) +
2564 strlen(cur_entry->prepend) + 1);
2565 if (!*out_name) {
2566 return -ENOMEM;
2568 sprintf(*out_name, "%s%s", cur_entry->prepend, client_name);
2569 return 0;
2574 return -EPERM;
2578 * For use with listxattr where the server fs gives us a name and we may need
2579 * to sanitize this for the client.
2580 * Returns a pointer to the result in *out_name
2581 * This is always the original string or the current string with some prefix
2582 * removed; no reallocation is done.
2583 * Returns 0 on success
2584 * Can return -ENODATA to indicate the name should be dropped from the list.
2586 static int xattr_map_server(const struct lo_data *lo, const char *server_name,
2587 const char **out_name)
2589 size_t i;
2590 const char *end;
2592 for (i = 0; i < lo->xattr_map_nentries; i++) {
2593 const XattrMapEntry *cur_entry = lo->xattr_map_list + i;
2595 if ((cur_entry->flags & XATTR_MAP_FLAG_SERVER) &&
2596 (strstart(server_name, cur_entry->prepend, &end))) {
2597 if (cur_entry->flags & XATTR_MAP_FLAG_BAD) {
2598 return -ENODATA;
2600 if (cur_entry->flags & XATTR_MAP_FLAG_OK) {
2601 *out_name = server_name;
2602 return 0;
2604 if (cur_entry->flags & XATTR_MAP_FLAG_PREFIX) {
2605 /* Remove prefix */
2606 *out_name = end;
2607 return 0;
2612 return -ENODATA;
2615 static void lo_getxattr(fuse_req_t req, fuse_ino_t ino, const char *in_name,
2616 size_t size)
2618 struct lo_data *lo = lo_data(req);
2619 char *value = NULL;
2620 char procname[64];
2621 const char *name;
2622 char *mapped_name;
2623 struct lo_inode *inode;
2624 ssize_t ret;
2625 int saverr;
2626 int fd = -1;
2628 mapped_name = NULL;
2629 name = in_name;
2630 if (lo->xattrmap) {
2631 ret = xattr_map_client(lo, in_name, &mapped_name);
2632 if (ret < 0) {
2633 if (ret == -EPERM) {
2634 ret = -ENODATA;
2636 fuse_reply_err(req, -ret);
2637 return;
2639 if (mapped_name) {
2640 name = mapped_name;
2644 inode = lo_inode(req, ino);
2645 if (!inode) {
2646 fuse_reply_err(req, EBADF);
2647 g_free(mapped_name);
2648 return;
2651 saverr = ENOSYS;
2652 if (!lo_data(req)->xattr) {
2653 goto out;
2656 fuse_log(FUSE_LOG_DEBUG, "lo_getxattr(ino=%" PRIu64 ", name=%s size=%zd)\n",
2657 ino, name, size);
2659 if (size) {
2660 value = malloc(size);
2661 if (!value) {
2662 goto out_err;
2666 sprintf(procname, "%i", inode->fd);
2668 * It is not safe to open() non-regular/non-dir files in file server
2669 * unless O_PATH is used, so use that method for regular files/dir
2670 * only (as it seems giving less performance overhead).
2671 * Otherwise, call fchdir() to avoid open().
2673 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2674 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2675 if (fd < 0) {
2676 goto out_err;
2678 ret = fgetxattr(fd, name, value, size);
2679 } else {
2680 /* fchdir should not fail here */
2681 assert(fchdir(lo->proc_self_fd) == 0);
2682 ret = getxattr(procname, name, value, size);
2683 assert(fchdir(lo->root.fd) == 0);
2686 if (ret == -1) {
2687 goto out_err;
2689 if (size) {
2690 saverr = 0;
2691 if (ret == 0) {
2692 goto out;
2694 fuse_reply_buf(req, value, ret);
2695 } else {
2696 fuse_reply_xattr(req, ret);
2698 out_free:
2699 free(value);
2701 if (fd >= 0) {
2702 close(fd);
2705 lo_inode_put(lo, &inode);
2706 return;
2708 out_err:
2709 saverr = errno;
2710 out:
2711 fuse_reply_err(req, saverr);
2712 g_free(mapped_name);
2713 goto out_free;
2716 static void lo_listxattr(fuse_req_t req, fuse_ino_t ino, size_t size)
2718 struct lo_data *lo = lo_data(req);
2719 char *value = NULL;
2720 char procname[64];
2721 struct lo_inode *inode;
2722 ssize_t ret;
2723 int saverr;
2724 int fd = -1;
2726 inode = lo_inode(req, ino);
2727 if (!inode) {
2728 fuse_reply_err(req, EBADF);
2729 return;
2732 saverr = ENOSYS;
2733 if (!lo_data(req)->xattr) {
2734 goto out;
2737 fuse_log(FUSE_LOG_DEBUG, "lo_listxattr(ino=%" PRIu64 ", size=%zd)\n", ino,
2738 size);
2740 if (size) {
2741 value = malloc(size);
2742 if (!value) {
2743 goto out_err;
2747 sprintf(procname, "%i", inode->fd);
2748 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2749 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2750 if (fd < 0) {
2751 goto out_err;
2753 ret = flistxattr(fd, value, size);
2754 } else {
2755 /* fchdir should not fail here */
2756 assert(fchdir(lo->proc_self_fd) == 0);
2757 ret = listxattr(procname, value, size);
2758 assert(fchdir(lo->root.fd) == 0);
2761 if (ret == -1) {
2762 goto out_err;
2764 if (size) {
2765 saverr = 0;
2766 if (ret == 0) {
2767 goto out;
2770 if (lo->xattr_map_list) {
2772 * Map the names back, some attributes might be dropped,
2773 * some shortened, but not increased, so we shouldn't
2774 * run out of room.
2776 size_t out_index, in_index;
2777 out_index = 0;
2778 in_index = 0;
2779 while (in_index < ret) {
2780 const char *map_out;
2781 char *in_ptr = value + in_index;
2782 /* Length of current attribute name */
2783 size_t in_len = strlen(value + in_index) + 1;
2785 int mapret = xattr_map_server(lo, in_ptr, &map_out);
2786 if (mapret != -ENODATA && mapret != 0) {
2787 /* Shouldn't happen */
2788 saverr = -mapret;
2789 goto out;
2791 if (mapret == 0) {
2792 /* Either unchanged, or truncated */
2793 size_t out_len;
2794 if (map_out != in_ptr) {
2795 /* +1 copies the NIL */
2796 out_len = strlen(map_out) + 1;
2797 } else {
2798 /* No change */
2799 out_len = in_len;
2802 * Move result along, may still be needed for an unchanged
2803 * entry if a previous entry was changed.
2805 memmove(value + out_index, map_out, out_len);
2807 out_index += out_len;
2809 in_index += in_len;
2811 ret = out_index;
2812 if (ret == 0) {
2813 goto out;
2816 fuse_reply_buf(req, value, ret);
2817 } else {
2819 * xattrmap only ever shortens the result,
2820 * so we don't need to do anything clever with the
2821 * allocation length here.
2823 fuse_reply_xattr(req, ret);
2825 out_free:
2826 free(value);
2828 if (fd >= 0) {
2829 close(fd);
2832 lo_inode_put(lo, &inode);
2833 return;
2835 out_err:
2836 saverr = errno;
2837 out:
2838 fuse_reply_err(req, saverr);
2839 goto out_free;
2842 static void lo_setxattr(fuse_req_t req, fuse_ino_t ino, const char *in_name,
2843 const char *value, size_t size, int flags)
2845 char procname[64];
2846 const char *name;
2847 char *mapped_name;
2848 struct lo_data *lo = lo_data(req);
2849 struct lo_inode *inode;
2850 ssize_t ret;
2851 int saverr;
2852 int fd = -1;
2854 mapped_name = NULL;
2855 name = in_name;
2856 if (lo->xattrmap) {
2857 ret = xattr_map_client(lo, in_name, &mapped_name);
2858 if (ret < 0) {
2859 fuse_reply_err(req, -ret);
2860 return;
2862 if (mapped_name) {
2863 name = mapped_name;
2867 inode = lo_inode(req, ino);
2868 if (!inode) {
2869 fuse_reply_err(req, EBADF);
2870 g_free(mapped_name);
2871 return;
2874 saverr = ENOSYS;
2875 if (!lo_data(req)->xattr) {
2876 goto out;
2879 fuse_log(FUSE_LOG_DEBUG, "lo_setxattr(ino=%" PRIu64
2880 ", name=%s value=%s size=%zd)\n", ino, name, value, size);
2882 sprintf(procname, "%i", inode->fd);
2883 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2884 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2885 if (fd < 0) {
2886 saverr = errno;
2887 goto out;
2889 ret = fsetxattr(fd, name, value, size, flags);
2890 } else {
2891 /* fchdir should not fail here */
2892 assert(fchdir(lo->proc_self_fd) == 0);
2893 ret = setxattr(procname, name, value, size, flags);
2894 assert(fchdir(lo->root.fd) == 0);
2897 saverr = ret == -1 ? errno : 0;
2899 out:
2900 if (fd >= 0) {
2901 close(fd);
2904 lo_inode_put(lo, &inode);
2905 g_free(mapped_name);
2906 fuse_reply_err(req, saverr);
2909 static void lo_removexattr(fuse_req_t req, fuse_ino_t ino, const char *in_name)
2911 char procname[64];
2912 const char *name;
2913 char *mapped_name;
2914 struct lo_data *lo = lo_data(req);
2915 struct lo_inode *inode;
2916 ssize_t ret;
2917 int saverr;
2918 int fd = -1;
2920 mapped_name = NULL;
2921 name = in_name;
2922 if (lo->xattrmap) {
2923 ret = xattr_map_client(lo, in_name, &mapped_name);
2924 if (ret < 0) {
2925 fuse_reply_err(req, -ret);
2926 return;
2928 if (mapped_name) {
2929 name = mapped_name;
2933 inode = lo_inode(req, ino);
2934 if (!inode) {
2935 fuse_reply_err(req, EBADF);
2936 g_free(mapped_name);
2937 return;
2940 saverr = ENOSYS;
2941 if (!lo_data(req)->xattr) {
2942 goto out;
2945 fuse_log(FUSE_LOG_DEBUG, "lo_removexattr(ino=%" PRIu64 ", name=%s)\n", ino,
2946 name);
2948 sprintf(procname, "%i", inode->fd);
2949 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2950 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2951 if (fd < 0) {
2952 saverr = errno;
2953 goto out;
2955 ret = fremovexattr(fd, name);
2956 } else {
2957 /* fchdir should not fail here */
2958 assert(fchdir(lo->proc_self_fd) == 0);
2959 ret = removexattr(procname, name);
2960 assert(fchdir(lo->root.fd) == 0);
2963 saverr = ret == -1 ? errno : 0;
2965 out:
2966 if (fd >= 0) {
2967 close(fd);
2970 lo_inode_put(lo, &inode);
2971 g_free(mapped_name);
2972 fuse_reply_err(req, saverr);
2975 #ifdef HAVE_COPY_FILE_RANGE
2976 static void lo_copy_file_range(fuse_req_t req, fuse_ino_t ino_in, off_t off_in,
2977 struct fuse_file_info *fi_in, fuse_ino_t ino_out,
2978 off_t off_out, struct fuse_file_info *fi_out,
2979 size_t len, int flags)
2981 int in_fd, out_fd;
2982 ssize_t res;
2984 in_fd = lo_fi_fd(req, fi_in);
2985 out_fd = lo_fi_fd(req, fi_out);
2987 fuse_log(FUSE_LOG_DEBUG,
2988 "lo_copy_file_range(ino=%" PRIu64 "/fd=%d, "
2989 "off=%lu, ino=%" PRIu64 "/fd=%d, "
2990 "off=%lu, size=%zd, flags=0x%x)\n",
2991 ino_in, in_fd, off_in, ino_out, out_fd, off_out, len, flags);
2993 res = copy_file_range(in_fd, &off_in, out_fd, &off_out, len, flags);
2994 if (res < 0) {
2995 fuse_reply_err(req, errno);
2996 } else {
2997 fuse_reply_write(req, res);
3000 #endif
3002 static void lo_lseek(fuse_req_t req, fuse_ino_t ino, off_t off, int whence,
3003 struct fuse_file_info *fi)
3005 off_t res;
3007 (void)ino;
3008 res = lseek(lo_fi_fd(req, fi), off, whence);
3009 if (res != -1) {
3010 fuse_reply_lseek(req, res);
3011 } else {
3012 fuse_reply_err(req, errno);
3016 static void lo_destroy(void *userdata)
3018 struct lo_data *lo = (struct lo_data *)userdata;
3020 pthread_mutex_lock(&lo->mutex);
3021 while (true) {
3022 GHashTableIter iter;
3023 gpointer key, value;
3025 g_hash_table_iter_init(&iter, lo->inodes);
3026 if (!g_hash_table_iter_next(&iter, &key, &value)) {
3027 break;
3030 struct lo_inode *inode = value;
3031 unref_inode(lo, inode, inode->nlookup);
3033 pthread_mutex_unlock(&lo->mutex);
3036 static struct fuse_lowlevel_ops lo_oper = {
3037 .init = lo_init,
3038 .lookup = lo_lookup,
3039 .mkdir = lo_mkdir,
3040 .mknod = lo_mknod,
3041 .symlink = lo_symlink,
3042 .link = lo_link,
3043 .unlink = lo_unlink,
3044 .rmdir = lo_rmdir,
3045 .rename = lo_rename,
3046 .forget = lo_forget,
3047 .forget_multi = lo_forget_multi,
3048 .getattr = lo_getattr,
3049 .setattr = lo_setattr,
3050 .readlink = lo_readlink,
3051 .opendir = lo_opendir,
3052 .readdir = lo_readdir,
3053 .readdirplus = lo_readdirplus,
3054 .releasedir = lo_releasedir,
3055 .fsyncdir = lo_fsyncdir,
3056 .create = lo_create,
3057 .getlk = lo_getlk,
3058 .setlk = lo_setlk,
3059 .open = lo_open,
3060 .release = lo_release,
3061 .flush = lo_flush,
3062 .fsync = lo_fsync,
3063 .read = lo_read,
3064 .write_buf = lo_write_buf,
3065 .statfs = lo_statfs,
3066 .fallocate = lo_fallocate,
3067 .flock = lo_flock,
3068 .getxattr = lo_getxattr,
3069 .listxattr = lo_listxattr,
3070 .setxattr = lo_setxattr,
3071 .removexattr = lo_removexattr,
3072 #ifdef HAVE_COPY_FILE_RANGE
3073 .copy_file_range = lo_copy_file_range,
3074 #endif
3075 .lseek = lo_lseek,
3076 .destroy = lo_destroy,
3079 /* Print vhost-user.json backend program capabilities */
3080 static void print_capabilities(void)
3082 printf("{\n");
3083 printf(" \"type\": \"fs\"\n");
3084 printf("}\n");
3088 * Drop all Linux capabilities because the wait parent process only needs to
3089 * sit in waitpid(2) and terminate.
3091 static void setup_wait_parent_capabilities(void)
3093 capng_setpid(syscall(SYS_gettid));
3094 capng_clear(CAPNG_SELECT_BOTH);
3095 capng_apply(CAPNG_SELECT_BOTH);
3099 * Move to a new mount, net, and pid namespaces to isolate this process.
3101 static void setup_namespaces(struct lo_data *lo, struct fuse_session *se)
3103 pid_t child;
3106 * Create a new pid namespace for *child* processes. We'll have to
3107 * fork in order to enter the new pid namespace. A new mount namespace
3108 * is also needed so that we can remount /proc for the new pid
3109 * namespace.
3111 * Our UNIX domain sockets have been created. Now we can move to
3112 * an empty network namespace to prevent TCP/IP and other network
3113 * activity in case this process is compromised.
3115 if (unshare(CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWNET) != 0) {
3116 fuse_log(FUSE_LOG_ERR, "unshare(CLONE_NEWPID | CLONE_NEWNS): %m\n");
3117 exit(1);
3120 child = fork();
3121 if (child < 0) {
3122 fuse_log(FUSE_LOG_ERR, "fork() failed: %m\n");
3123 exit(1);
3125 if (child > 0) {
3126 pid_t waited;
3127 int wstatus;
3129 setup_wait_parent_capabilities();
3131 /* The parent waits for the child */
3132 do {
3133 waited = waitpid(child, &wstatus, 0);
3134 } while (waited < 0 && errno == EINTR && !se->exited);
3136 /* We were terminated by a signal, see fuse_signals.c */
3137 if (se->exited) {
3138 exit(0);
3141 if (WIFEXITED(wstatus)) {
3142 exit(WEXITSTATUS(wstatus));
3145 exit(1);
3148 /* Send us SIGTERM when the parent thread terminates, see prctl(2) */
3149 prctl(PR_SET_PDEATHSIG, SIGTERM);
3152 * If the mounts have shared propagation then we want to opt out so our
3153 * mount changes don't affect the parent mount namespace.
3155 if (mount(NULL, "/", NULL, MS_REC | MS_SLAVE, NULL) < 0) {
3156 fuse_log(FUSE_LOG_ERR, "mount(/, MS_REC|MS_SLAVE): %m\n");
3157 exit(1);
3160 /* The child must remount /proc to use the new pid namespace */
3161 if (mount("proc", "/proc", "proc",
3162 MS_NODEV | MS_NOEXEC | MS_NOSUID | MS_RELATIME, NULL) < 0) {
3163 fuse_log(FUSE_LOG_ERR, "mount(/proc): %m\n");
3164 exit(1);
3168 * We only need /proc/self/fd. Prevent ".." from accessing parent
3169 * directories of /proc/self/fd by bind-mounting it over /proc. Since / was
3170 * previously remounted with MS_REC | MS_SLAVE this mount change only
3171 * affects our process.
3173 if (mount("/proc/self/fd", "/proc", NULL, MS_BIND, NULL) < 0) {
3174 fuse_log(FUSE_LOG_ERR, "mount(/proc/self/fd, MS_BIND): %m\n");
3175 exit(1);
3178 /* Get the /proc (actually /proc/self/fd, see above) file descriptor */
3179 lo->proc_self_fd = open("/proc", O_PATH);
3180 if (lo->proc_self_fd == -1) {
3181 fuse_log(FUSE_LOG_ERR, "open(/proc, O_PATH): %m\n");
3182 exit(1);
3187 * Capture the capability state, we'll need to restore this for individual
3188 * threads later; see load_capng.
3190 static void setup_capng(void)
3192 /* Note this accesses /proc so has to happen before the sandbox */
3193 if (capng_get_caps_process()) {
3194 fuse_log(FUSE_LOG_ERR, "capng_get_caps_process\n");
3195 exit(1);
3197 pthread_mutex_init(&cap.mutex, NULL);
3198 pthread_mutex_lock(&cap.mutex);
3199 cap.saved = capng_save_state();
3200 if (!cap.saved) {
3201 fuse_log(FUSE_LOG_ERR, "capng_save_state\n");
3202 exit(1);
3204 pthread_mutex_unlock(&cap.mutex);
3207 static void cleanup_capng(void)
3209 free(cap.saved);
3210 cap.saved = NULL;
3211 pthread_mutex_destroy(&cap.mutex);
3216 * Make the source directory our root so symlinks cannot escape and no other
3217 * files are accessible. Assumes unshare(CLONE_NEWNS) was already called.
3219 static void setup_mounts(const char *source)
3221 int oldroot;
3222 int newroot;
3224 if (mount(source, source, NULL, MS_BIND | MS_REC, NULL) < 0) {
3225 fuse_log(FUSE_LOG_ERR, "mount(%s, %s, MS_BIND): %m\n", source, source);
3226 exit(1);
3229 /* This magic is based on lxc's lxc_pivot_root() */
3230 oldroot = open("/", O_DIRECTORY | O_RDONLY | O_CLOEXEC);
3231 if (oldroot < 0) {
3232 fuse_log(FUSE_LOG_ERR, "open(/): %m\n");
3233 exit(1);
3236 newroot = open(source, O_DIRECTORY | O_RDONLY | O_CLOEXEC);
3237 if (newroot < 0) {
3238 fuse_log(FUSE_LOG_ERR, "open(%s): %m\n", source);
3239 exit(1);
3242 if (fchdir(newroot) < 0) {
3243 fuse_log(FUSE_LOG_ERR, "fchdir(newroot): %m\n");
3244 exit(1);
3247 if (syscall(__NR_pivot_root, ".", ".") < 0) {
3248 fuse_log(FUSE_LOG_ERR, "pivot_root(., .): %m\n");
3249 exit(1);
3252 if (fchdir(oldroot) < 0) {
3253 fuse_log(FUSE_LOG_ERR, "fchdir(oldroot): %m\n");
3254 exit(1);
3257 if (mount("", ".", "", MS_SLAVE | MS_REC, NULL) < 0) {
3258 fuse_log(FUSE_LOG_ERR, "mount(., MS_SLAVE | MS_REC): %m\n");
3259 exit(1);
3262 if (umount2(".", MNT_DETACH) < 0) {
3263 fuse_log(FUSE_LOG_ERR, "umount2(., MNT_DETACH): %m\n");
3264 exit(1);
3267 if (fchdir(newroot) < 0) {
3268 fuse_log(FUSE_LOG_ERR, "fchdir(newroot): %m\n");
3269 exit(1);
3272 close(newroot);
3273 close(oldroot);
3277 * Only keep capabilities in allowlist that are needed for file system operation
3278 * The (possibly NULL) modcaps_in string passed in is free'd before exit.
3280 static void setup_capabilities(char *modcaps_in)
3282 char *modcaps = modcaps_in;
3283 pthread_mutex_lock(&cap.mutex);
3284 capng_restore_state(&cap.saved);
3287 * Add to allowlist file system-related capabilities that are needed for a
3288 * file server to act like root. Drop everything else like networking and
3289 * sysadmin capabilities.
3291 * Exclusions:
3292 * 1. CAP_LINUX_IMMUTABLE is not included because it's only used via ioctl
3293 * and we don't support that.
3294 * 2. CAP_MAC_OVERRIDE is not included because it only seems to be
3295 * used by the Smack LSM. Omit it until there is demand for it.
3297 capng_setpid(syscall(SYS_gettid));
3298 capng_clear(CAPNG_SELECT_BOTH);
3299 if (capng_updatev(CAPNG_ADD, CAPNG_PERMITTED | CAPNG_EFFECTIVE,
3300 CAP_CHOWN,
3301 CAP_DAC_OVERRIDE,
3302 CAP_FOWNER,
3303 CAP_FSETID,
3304 CAP_SETGID,
3305 CAP_SETUID,
3306 CAP_MKNOD,
3307 CAP_SETFCAP,
3308 -1)) {
3309 fuse_log(FUSE_LOG_ERR, "%s: capng_updatev failed\n", __func__);
3310 exit(1);
3314 * The modcaps option is a colon separated list of caps,
3315 * each preceded by either + or -.
3317 while (modcaps) {
3318 capng_act_t action;
3319 int cap;
3321 char *next = strchr(modcaps, ':');
3322 if (next) {
3323 *next = '\0';
3324 next++;
3327 switch (modcaps[0]) {
3328 case '+':
3329 action = CAPNG_ADD;
3330 break;
3332 case '-':
3333 action = CAPNG_DROP;
3334 break;
3336 default:
3337 fuse_log(FUSE_LOG_ERR,
3338 "%s: Expecting '+'/'-' in modcaps but found '%c'\n",
3339 __func__, modcaps[0]);
3340 exit(1);
3342 cap = capng_name_to_capability(modcaps + 1);
3343 if (cap < 0) {
3344 fuse_log(FUSE_LOG_ERR, "%s: Unknown capability '%s'\n", __func__,
3345 modcaps);
3346 exit(1);
3348 if (capng_update(action, CAPNG_PERMITTED | CAPNG_EFFECTIVE, cap)) {
3349 fuse_log(FUSE_LOG_ERR, "%s: capng_update failed for '%s'\n",
3350 __func__, modcaps);
3351 exit(1);
3354 modcaps = next;
3356 g_free(modcaps_in);
3358 if (capng_apply(CAPNG_SELECT_BOTH)) {
3359 fuse_log(FUSE_LOG_ERR, "%s: capng_apply failed\n", __func__);
3360 exit(1);
3363 cap.saved = capng_save_state();
3364 if (!cap.saved) {
3365 fuse_log(FUSE_LOG_ERR, "%s: capng_save_state failed\n", __func__);
3366 exit(1);
3368 pthread_mutex_unlock(&cap.mutex);
3372 * Use chroot as a weaker sandbox for environments where the process is
3373 * launched without CAP_SYS_ADMIN.
3375 static void setup_chroot(struct lo_data *lo)
3377 lo->proc_self_fd = open("/proc/self/fd", O_PATH);
3378 if (lo->proc_self_fd == -1) {
3379 fuse_log(FUSE_LOG_ERR, "open(\"/proc/self/fd\", O_PATH): %m\n");
3380 exit(1);
3384 * Make the shared directory the file system root so that FUSE_OPEN
3385 * (lo_open()) cannot escape the shared directory by opening a symlink.
3387 * The chroot(2) syscall is later disabled by seccomp and the
3388 * CAP_SYS_CHROOT capability is dropped so that tampering with the chroot
3389 * is not possible.
3391 * However, it's still possible to escape the chroot via lo->proc_self_fd
3392 * but that requires first gaining control of the process.
3394 if (chroot(lo->source) != 0) {
3395 fuse_log(FUSE_LOG_ERR, "chroot(\"%s\"): %m\n", lo->source);
3396 exit(1);
3399 /* Move into the chroot */
3400 if (chdir("/") != 0) {
3401 fuse_log(FUSE_LOG_ERR, "chdir(\"/\"): %m\n");
3402 exit(1);
3407 * Lock down this process to prevent access to other processes or files outside
3408 * source directory. This reduces the impact of arbitrary code execution bugs.
3410 static void setup_sandbox(struct lo_data *lo, struct fuse_session *se,
3411 bool enable_syslog)
3413 if (lo->sandbox == SANDBOX_NAMESPACE) {
3414 setup_namespaces(lo, se);
3415 setup_mounts(lo->source);
3416 } else {
3417 setup_chroot(lo);
3420 setup_seccomp(enable_syslog);
3421 setup_capabilities(g_strdup(lo->modcaps));
3424 /* Set the maximum number of open file descriptors */
3425 static void setup_nofile_rlimit(unsigned long rlimit_nofile)
3427 struct rlimit rlim = {
3428 .rlim_cur = rlimit_nofile,
3429 .rlim_max = rlimit_nofile,
3432 if (rlimit_nofile == 0) {
3433 return; /* nothing to do */
3436 if (setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
3437 /* Ignore SELinux denials */
3438 if (errno == EPERM) {
3439 return;
3442 fuse_log(FUSE_LOG_ERR, "setrlimit(RLIMIT_NOFILE): %m\n");
3443 exit(1);
3447 static void log_func(enum fuse_log_level level, const char *fmt, va_list ap)
3449 g_autofree char *localfmt = NULL;
3450 struct timespec ts;
3451 struct tm tm;
3452 char sec_fmt[sizeof "2020-12-07 18:17:54"];
3453 char zone_fmt[sizeof "+0100"];
3455 if (current_log_level < level) {
3456 return;
3459 if (current_log_level == FUSE_LOG_DEBUG) {
3460 if (use_syslog) {
3461 /* no timestamp needed */
3462 localfmt = g_strdup_printf("[ID: %08ld] %s", syscall(__NR_gettid),
3463 fmt);
3464 } else {
3465 /* try formatting a broken-down timestamp */
3466 if (clock_gettime(CLOCK_REALTIME, &ts) != -1 &&
3467 localtime_r(&ts.tv_sec, &tm) != NULL &&
3468 strftime(sec_fmt, sizeof sec_fmt, "%Y-%m-%d %H:%M:%S",
3469 &tm) != 0 &&
3470 strftime(zone_fmt, sizeof zone_fmt, "%z", &tm) != 0) {
3471 localfmt = g_strdup_printf("[%s.%02ld%s] [ID: %08ld] %s",
3472 sec_fmt,
3473 ts.tv_nsec / (10L * 1000 * 1000),
3474 zone_fmt, syscall(__NR_gettid),
3475 fmt);
3476 } else {
3477 /* fall back to a flat timestamp */
3478 localfmt = g_strdup_printf("[%" PRId64 "] [ID: %08ld] %s",
3479 get_clock(), syscall(__NR_gettid),
3480 fmt);
3483 fmt = localfmt;
3486 if (use_syslog) {
3487 int priority = LOG_ERR;
3488 switch (level) {
3489 case FUSE_LOG_EMERG:
3490 priority = LOG_EMERG;
3491 break;
3492 case FUSE_LOG_ALERT:
3493 priority = LOG_ALERT;
3494 break;
3495 case FUSE_LOG_CRIT:
3496 priority = LOG_CRIT;
3497 break;
3498 case FUSE_LOG_ERR:
3499 priority = LOG_ERR;
3500 break;
3501 case FUSE_LOG_WARNING:
3502 priority = LOG_WARNING;
3503 break;
3504 case FUSE_LOG_NOTICE:
3505 priority = LOG_NOTICE;
3506 break;
3507 case FUSE_LOG_INFO:
3508 priority = LOG_INFO;
3509 break;
3510 case FUSE_LOG_DEBUG:
3511 priority = LOG_DEBUG;
3512 break;
3514 vsyslog(priority, fmt, ap);
3515 } else {
3516 vfprintf(stderr, fmt, ap);
3520 static void setup_root(struct lo_data *lo, struct lo_inode *root)
3522 int fd, res;
3523 struct stat stat;
3524 uint64_t mnt_id;
3526 fd = open("/", O_PATH);
3527 if (fd == -1) {
3528 fuse_log(FUSE_LOG_ERR, "open(%s, O_PATH): %m\n", lo->source);
3529 exit(1);
3532 res = do_statx(lo, fd, "", &stat, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW,
3533 &mnt_id);
3534 if (res == -1) {
3535 fuse_log(FUSE_LOG_ERR, "fstatat(%s): %m\n", lo->source);
3536 exit(1);
3539 root->filetype = S_IFDIR;
3540 root->fd = fd;
3541 root->key.ino = stat.st_ino;
3542 root->key.dev = stat.st_dev;
3543 root->key.mnt_id = mnt_id;
3544 root->nlookup = 2;
3545 g_atomic_int_set(&root->refcount, 2);
3546 if (lo->posix_lock) {
3547 pthread_mutex_init(&root->plock_mutex, NULL);
3548 root->posix_locks = g_hash_table_new_full(
3549 g_direct_hash, g_direct_equal, NULL, posix_locks_value_destroy);
3553 static guint lo_key_hash(gconstpointer key)
3555 const struct lo_key *lkey = key;
3557 return (guint)lkey->ino + (guint)lkey->dev + (guint)lkey->mnt_id;
3560 static gboolean lo_key_equal(gconstpointer a, gconstpointer b)
3562 const struct lo_key *la = a;
3563 const struct lo_key *lb = b;
3565 return la->ino == lb->ino && la->dev == lb->dev && la->mnt_id == lb->mnt_id;
3568 static void fuse_lo_data_cleanup(struct lo_data *lo)
3570 if (lo->inodes) {
3571 g_hash_table_destroy(lo->inodes);
3574 if (lo->root.posix_locks) {
3575 g_hash_table_destroy(lo->root.posix_locks);
3577 lo_map_destroy(&lo->fd_map);
3578 lo_map_destroy(&lo->dirp_map);
3579 lo_map_destroy(&lo->ino_map);
3581 if (lo->proc_self_fd >= 0) {
3582 close(lo->proc_self_fd);
3585 if (lo->root.fd >= 0) {
3586 close(lo->root.fd);
3589 free(lo->xattrmap);
3590 free_xattrmap(lo);
3591 free(lo->source);
3594 int main(int argc, char *argv[])
3596 struct fuse_args args = FUSE_ARGS_INIT(argc, argv);
3597 struct fuse_session *se;
3598 struct fuse_cmdline_opts opts;
3599 struct lo_data lo = {
3600 .sandbox = SANDBOX_NAMESPACE,
3601 .debug = 0,
3602 .writeback = 0,
3603 .posix_lock = 0,
3604 .allow_direct_io = 0,
3605 .proc_self_fd = -1,
3606 .user_killpriv_v2 = -1,
3608 struct lo_map_elem *root_elem;
3609 struct lo_map_elem *reserve_elem;
3610 int ret = -1;
3612 /* Initialize time conversion information for localtime_r(). */
3613 tzset();
3615 /* Don't mask creation mode, kernel already did that */
3616 umask(0);
3618 qemu_init_exec_dir(argv[0]);
3620 pthread_mutex_init(&lo.mutex, NULL);
3621 lo.inodes = g_hash_table_new(lo_key_hash, lo_key_equal);
3622 lo.root.fd = -1;
3623 lo.root.fuse_ino = FUSE_ROOT_ID;
3624 lo.cache = CACHE_AUTO;
3627 * Set up the ino map like this:
3628 * [0] Reserved (will not be used)
3629 * [1] Root inode
3631 lo_map_init(&lo.ino_map);
3632 reserve_elem = lo_map_reserve(&lo.ino_map, 0);
3633 if (!reserve_elem) {
3634 fuse_log(FUSE_LOG_ERR, "failed to alloc reserve_elem.\n");
3635 goto err_out1;
3637 reserve_elem->in_use = false;
3638 root_elem = lo_map_reserve(&lo.ino_map, lo.root.fuse_ino);
3639 if (!root_elem) {
3640 fuse_log(FUSE_LOG_ERR, "failed to alloc root_elem.\n");
3641 goto err_out1;
3643 root_elem->inode = &lo.root;
3645 lo_map_init(&lo.dirp_map);
3646 lo_map_init(&lo.fd_map);
3648 if (fuse_parse_cmdline(&args, &opts) != 0) {
3649 goto err_out1;
3651 fuse_set_log_func(log_func);
3652 use_syslog = opts.syslog;
3653 if (use_syslog) {
3654 openlog("virtiofsd", LOG_PID, LOG_DAEMON);
3657 if (opts.show_help) {
3658 printf("usage: %s [options]\n\n", argv[0]);
3659 fuse_cmdline_help();
3660 printf(" -o source=PATH shared directory tree\n");
3661 fuse_lowlevel_help();
3662 ret = 0;
3663 goto err_out1;
3664 } else if (opts.show_version) {
3665 fuse_lowlevel_version();
3666 ret = 0;
3667 goto err_out1;
3668 } else if (opts.print_capabilities) {
3669 print_capabilities();
3670 ret = 0;
3671 goto err_out1;
3674 if (fuse_opt_parse(&args, &lo, lo_opts, NULL) == -1) {
3675 goto err_out1;
3678 if (opts.log_level != 0) {
3679 current_log_level = opts.log_level;
3680 } else {
3681 /* default log level is INFO */
3682 current_log_level = FUSE_LOG_INFO;
3684 lo.debug = opts.debug;
3685 if (lo.debug) {
3686 current_log_level = FUSE_LOG_DEBUG;
3688 if (lo.source) {
3689 struct stat stat;
3690 int res;
3692 res = lstat(lo.source, &stat);
3693 if (res == -1) {
3694 fuse_log(FUSE_LOG_ERR, "failed to stat source (\"%s\"): %m\n",
3695 lo.source);
3696 exit(1);
3698 if (!S_ISDIR(stat.st_mode)) {
3699 fuse_log(FUSE_LOG_ERR, "source is not a directory\n");
3700 exit(1);
3702 } else {
3703 lo.source = strdup("/");
3704 if (!lo.source) {
3705 fuse_log(FUSE_LOG_ERR, "failed to strdup source\n");
3706 goto err_out1;
3710 if (lo.xattrmap) {
3711 parse_xattrmap(&lo);
3714 if (!lo.timeout_set) {
3715 switch (lo.cache) {
3716 case CACHE_NONE:
3717 lo.timeout = 0.0;
3718 break;
3720 case CACHE_AUTO:
3721 lo.timeout = 1.0;
3722 break;
3724 case CACHE_ALWAYS:
3725 lo.timeout = 86400.0;
3726 break;
3728 } else if (lo.timeout < 0) {
3729 fuse_log(FUSE_LOG_ERR, "timeout is negative (%lf)\n", lo.timeout);
3730 exit(1);
3733 lo.use_statx = true;
3735 se = fuse_session_new(&args, &lo_oper, sizeof(lo_oper), &lo);
3736 if (se == NULL) {
3737 goto err_out1;
3740 if (fuse_set_signal_handlers(se) != 0) {
3741 goto err_out2;
3744 if (fuse_session_mount(se) != 0) {
3745 goto err_out3;
3748 fuse_daemonize(opts.foreground);
3750 setup_nofile_rlimit(opts.rlimit_nofile);
3752 /* Must be before sandbox since it wants /proc */
3753 setup_capng();
3755 setup_sandbox(&lo, se, opts.syslog);
3757 setup_root(&lo, &lo.root);
3758 /* Block until ctrl+c or fusermount -u */
3759 ret = virtio_loop(se);
3761 fuse_session_unmount(se);
3762 cleanup_capng();
3763 err_out3:
3764 fuse_remove_signal_handlers(se);
3765 err_out2:
3766 fuse_session_destroy(se);
3767 err_out1:
3768 fuse_opt_free_args(&args);
3770 fuse_lo_data_cleanup(&lo);
3772 return ret ? 1 : 0;