meson: Display host binaries information altogether
[qemu/ar7.git] / tools / virtiofsd / passthrough_ll.c
blob5fb36d94074a4e22d9dc8e56e47f597447e26a9b
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;
173 static const struct fuse_opt lo_opts[] = {
174 { "sandbox=namespace",
175 offsetof(struct lo_data, sandbox),
176 SANDBOX_NAMESPACE },
177 { "sandbox=chroot",
178 offsetof(struct lo_data, sandbox),
179 SANDBOX_CHROOT },
180 { "writeback", offsetof(struct lo_data, writeback), 1 },
181 { "no_writeback", offsetof(struct lo_data, writeback), 0 },
182 { "source=%s", offsetof(struct lo_data, source), 0 },
183 { "flock", offsetof(struct lo_data, flock), 1 },
184 { "no_flock", offsetof(struct lo_data, flock), 0 },
185 { "posix_lock", offsetof(struct lo_data, posix_lock), 1 },
186 { "no_posix_lock", offsetof(struct lo_data, posix_lock), 0 },
187 { "xattr", offsetof(struct lo_data, xattr), 1 },
188 { "no_xattr", offsetof(struct lo_data, xattr), 0 },
189 { "xattrmap=%s", offsetof(struct lo_data, xattrmap), 0 },
190 { "modcaps=%s", offsetof(struct lo_data, modcaps), 0 },
191 { "timeout=%lf", offsetof(struct lo_data, timeout), 0 },
192 { "timeout=", offsetof(struct lo_data, timeout_set), 1 },
193 { "cache=none", offsetof(struct lo_data, cache), CACHE_NONE },
194 { "cache=auto", offsetof(struct lo_data, cache), CACHE_AUTO },
195 { "cache=always", offsetof(struct lo_data, cache), CACHE_ALWAYS },
196 { "readdirplus", offsetof(struct lo_data, readdirplus_set), 1 },
197 { "no_readdirplus", offsetof(struct lo_data, readdirplus_clear), 1 },
198 { "allow_direct_io", offsetof(struct lo_data, allow_direct_io), 1 },
199 { "no_allow_direct_io", offsetof(struct lo_data, allow_direct_io), 0 },
200 { "announce_submounts", offsetof(struct lo_data, announce_submounts), 1 },
201 FUSE_OPT_END
203 static bool use_syslog = false;
204 static int current_log_level;
205 static void unref_inode_lolocked(struct lo_data *lo, struct lo_inode *inode,
206 uint64_t n);
208 static struct {
209 pthread_mutex_t mutex;
210 void *saved;
211 } cap;
212 /* That we loaded cap-ng in the current thread from the saved */
213 static __thread bool cap_loaded = 0;
215 static struct lo_inode *lo_find(struct lo_data *lo, struct stat *st,
216 uint64_t mnt_id);
218 static int is_dot_or_dotdot(const char *name)
220 return name[0] == '.' &&
221 (name[1] == '\0' || (name[1] == '.' && name[2] == '\0'));
224 /* Is `path` a single path component that is not "." or ".."? */
225 static int is_safe_path_component(const char *path)
227 if (strchr(path, '/')) {
228 return 0;
231 return !is_dot_or_dotdot(path);
234 static struct lo_data *lo_data(fuse_req_t req)
236 return (struct lo_data *)fuse_req_userdata(req);
240 * Load capng's state from our saved state if the current thread
241 * hadn't previously been loaded.
242 * returns 0 on success
244 static int load_capng(void)
246 if (!cap_loaded) {
247 pthread_mutex_lock(&cap.mutex);
248 capng_restore_state(&cap.saved);
250 * restore_state free's the saved copy
251 * so make another.
253 cap.saved = capng_save_state();
254 if (!cap.saved) {
255 pthread_mutex_unlock(&cap.mutex);
256 fuse_log(FUSE_LOG_ERR, "capng_save_state (thread)\n");
257 return -EINVAL;
259 pthread_mutex_unlock(&cap.mutex);
262 * We want to use the loaded state for our pid,
263 * not the original
265 capng_setpid(syscall(SYS_gettid));
266 cap_loaded = true;
268 return 0;
272 * Helpers for dropping and regaining effective capabilities. Returns 0
273 * on success, error otherwise
275 static int drop_effective_cap(const char *cap_name, bool *cap_dropped)
277 int cap, ret;
279 cap = capng_name_to_capability(cap_name);
280 if (cap < 0) {
281 ret = errno;
282 fuse_log(FUSE_LOG_ERR, "capng_name_to_capability(%s) failed:%s\n",
283 cap_name, strerror(errno));
284 goto out;
287 if (load_capng()) {
288 ret = errno;
289 fuse_log(FUSE_LOG_ERR, "load_capng() failed\n");
290 goto out;
293 /* We dont have this capability in effective set already. */
294 if (!capng_have_capability(CAPNG_EFFECTIVE, cap)) {
295 ret = 0;
296 goto out;
299 if (capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, cap)) {
300 ret = errno;
301 fuse_log(FUSE_LOG_ERR, "capng_update(DROP,) failed\n");
302 goto out;
305 if (capng_apply(CAPNG_SELECT_CAPS)) {
306 ret = errno;
307 fuse_log(FUSE_LOG_ERR, "drop:capng_apply() failed\n");
308 goto out;
311 ret = 0;
312 if (cap_dropped) {
313 *cap_dropped = true;
316 out:
317 return ret;
320 static int gain_effective_cap(const char *cap_name)
322 int cap;
323 int ret = 0;
325 cap = capng_name_to_capability(cap_name);
326 if (cap < 0) {
327 ret = errno;
328 fuse_log(FUSE_LOG_ERR, "capng_name_to_capability(%s) failed:%s\n",
329 cap_name, strerror(errno));
330 goto out;
333 if (load_capng()) {
334 ret = errno;
335 fuse_log(FUSE_LOG_ERR, "load_capng() failed\n");
336 goto out;
339 if (capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, cap)) {
340 ret = errno;
341 fuse_log(FUSE_LOG_ERR, "capng_update(ADD,) failed\n");
342 goto out;
345 if (capng_apply(CAPNG_SELECT_CAPS)) {
346 ret = errno;
347 fuse_log(FUSE_LOG_ERR, "gain:capng_apply() failed\n");
348 goto out;
350 ret = 0;
352 out:
353 return ret;
356 static void lo_map_init(struct lo_map *map)
358 map->elems = NULL;
359 map->nelems = 0;
360 map->freelist = -1;
363 static void lo_map_destroy(struct lo_map *map)
365 free(map->elems);
368 static int lo_map_grow(struct lo_map *map, size_t new_nelems)
370 struct lo_map_elem *new_elems;
371 size_t i;
373 if (new_nelems <= map->nelems) {
374 return 1;
377 new_elems = realloc(map->elems, sizeof(map->elems[0]) * new_nelems);
378 if (!new_elems) {
379 return 0;
382 for (i = map->nelems; i < new_nelems; i++) {
383 new_elems[i].freelist = i + 1;
384 new_elems[i].in_use = false;
386 new_elems[new_nelems - 1].freelist = -1;
388 map->elems = new_elems;
389 map->freelist = map->nelems;
390 map->nelems = new_nelems;
391 return 1;
394 static struct lo_map_elem *lo_map_alloc_elem(struct lo_map *map)
396 struct lo_map_elem *elem;
398 if (map->freelist == -1 && !lo_map_grow(map, map->nelems + 256)) {
399 return NULL;
402 elem = &map->elems[map->freelist];
403 map->freelist = elem->freelist;
405 elem->in_use = true;
407 return elem;
410 static struct lo_map_elem *lo_map_reserve(struct lo_map *map, size_t key)
412 ssize_t *prev;
414 if (!lo_map_grow(map, key + 1)) {
415 return NULL;
418 for (prev = &map->freelist; *prev != -1;
419 prev = &map->elems[*prev].freelist) {
420 if (*prev == key) {
421 struct lo_map_elem *elem = &map->elems[key];
423 *prev = elem->freelist;
424 elem->in_use = true;
425 return elem;
428 return NULL;
431 static struct lo_map_elem *lo_map_get(struct lo_map *map, size_t key)
433 if (key >= map->nelems) {
434 return NULL;
436 if (!map->elems[key].in_use) {
437 return NULL;
439 return &map->elems[key];
442 static void lo_map_remove(struct lo_map *map, size_t key)
444 struct lo_map_elem *elem;
446 if (key >= map->nelems) {
447 return;
450 elem = &map->elems[key];
451 if (!elem->in_use) {
452 return;
455 elem->in_use = false;
457 elem->freelist = map->freelist;
458 map->freelist = key;
461 /* Assumes lo->mutex is held */
462 static ssize_t lo_add_fd_mapping(fuse_req_t req, int fd)
464 struct lo_map_elem *elem;
466 elem = lo_map_alloc_elem(&lo_data(req)->fd_map);
467 if (!elem) {
468 return -1;
471 elem->fd = fd;
472 return elem - lo_data(req)->fd_map.elems;
475 /* Assumes lo->mutex is held */
476 static ssize_t lo_add_dirp_mapping(fuse_req_t req, struct lo_dirp *dirp)
478 struct lo_map_elem *elem;
480 elem = lo_map_alloc_elem(&lo_data(req)->dirp_map);
481 if (!elem) {
482 return -1;
485 elem->dirp = dirp;
486 return elem - lo_data(req)->dirp_map.elems;
489 /* Assumes lo->mutex is held */
490 static ssize_t lo_add_inode_mapping(fuse_req_t req, struct lo_inode *inode)
492 struct lo_map_elem *elem;
494 elem = lo_map_alloc_elem(&lo_data(req)->ino_map);
495 if (!elem) {
496 return -1;
499 elem->inode = inode;
500 return elem - lo_data(req)->ino_map.elems;
503 static void lo_inode_put(struct lo_data *lo, struct lo_inode **inodep)
505 struct lo_inode *inode = *inodep;
507 if (!inode) {
508 return;
511 *inodep = NULL;
513 if (g_atomic_int_dec_and_test(&inode->refcount)) {
514 close(inode->fd);
515 free(inode);
519 /* Caller must release refcount using lo_inode_put() */
520 static struct lo_inode *lo_inode(fuse_req_t req, fuse_ino_t ino)
522 struct lo_data *lo = lo_data(req);
523 struct lo_map_elem *elem;
525 pthread_mutex_lock(&lo->mutex);
526 elem = lo_map_get(&lo->ino_map, ino);
527 if (elem) {
528 g_atomic_int_inc(&elem->inode->refcount);
530 pthread_mutex_unlock(&lo->mutex);
532 if (!elem) {
533 return NULL;
536 return elem->inode;
540 * TODO Remove this helper and force callers to hold an inode refcount until
541 * they are done with the fd. This will be done in a later patch to make
542 * review easier.
544 static int lo_fd(fuse_req_t req, fuse_ino_t ino)
546 struct lo_inode *inode = lo_inode(req, ino);
547 int fd;
549 if (!inode) {
550 return -1;
553 fd = inode->fd;
554 lo_inode_put(lo_data(req), &inode);
555 return fd;
558 static void lo_init(void *userdata, struct fuse_conn_info *conn)
560 struct lo_data *lo = (struct lo_data *)userdata;
562 if (conn->capable & FUSE_CAP_EXPORT_SUPPORT) {
563 conn->want |= FUSE_CAP_EXPORT_SUPPORT;
566 if (lo->writeback && conn->capable & FUSE_CAP_WRITEBACK_CACHE) {
567 fuse_log(FUSE_LOG_DEBUG, "lo_init: activating writeback\n");
568 conn->want |= FUSE_CAP_WRITEBACK_CACHE;
570 if (conn->capable & FUSE_CAP_FLOCK_LOCKS) {
571 if (lo->flock) {
572 fuse_log(FUSE_LOG_DEBUG, "lo_init: activating flock locks\n");
573 conn->want |= FUSE_CAP_FLOCK_LOCKS;
574 } else {
575 fuse_log(FUSE_LOG_DEBUG, "lo_init: disabling flock locks\n");
576 conn->want &= ~FUSE_CAP_FLOCK_LOCKS;
580 if (conn->capable & FUSE_CAP_POSIX_LOCKS) {
581 if (lo->posix_lock) {
582 fuse_log(FUSE_LOG_DEBUG, "lo_init: activating posix locks\n");
583 conn->want |= FUSE_CAP_POSIX_LOCKS;
584 } else {
585 fuse_log(FUSE_LOG_DEBUG, "lo_init: disabling posix locks\n");
586 conn->want &= ~FUSE_CAP_POSIX_LOCKS;
590 if ((lo->cache == CACHE_NONE && !lo->readdirplus_set) ||
591 lo->readdirplus_clear) {
592 fuse_log(FUSE_LOG_DEBUG, "lo_init: disabling readdirplus\n");
593 conn->want &= ~FUSE_CAP_READDIRPLUS;
596 if (!(conn->capable & FUSE_CAP_SUBMOUNTS) && lo->announce_submounts) {
597 fuse_log(FUSE_LOG_WARNING, "lo_init: Cannot announce submounts, client "
598 "does not support it\n");
599 lo->announce_submounts = false;
603 static void lo_getattr(fuse_req_t req, fuse_ino_t ino,
604 struct fuse_file_info *fi)
606 int res;
607 struct stat buf;
608 struct lo_data *lo = lo_data(req);
610 (void)fi;
612 res =
613 fstatat(lo_fd(req, ino), "", &buf, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW);
614 if (res == -1) {
615 return (void)fuse_reply_err(req, errno);
618 fuse_reply_attr(req, &buf, lo->timeout);
621 static int lo_fi_fd(fuse_req_t req, struct fuse_file_info *fi)
623 struct lo_data *lo = lo_data(req);
624 struct lo_map_elem *elem;
626 pthread_mutex_lock(&lo->mutex);
627 elem = lo_map_get(&lo->fd_map, fi->fh);
628 pthread_mutex_unlock(&lo->mutex);
630 if (!elem) {
631 return -1;
634 return elem->fd;
637 static void lo_setattr(fuse_req_t req, fuse_ino_t ino, struct stat *attr,
638 int valid, struct fuse_file_info *fi)
640 int saverr;
641 char procname[64];
642 struct lo_data *lo = lo_data(req);
643 struct lo_inode *inode;
644 int ifd;
645 int res;
646 int fd = -1;
648 inode = lo_inode(req, ino);
649 if (!inode) {
650 fuse_reply_err(req, EBADF);
651 return;
654 ifd = inode->fd;
656 /* If fi->fh is invalid we'll report EBADF later */
657 if (fi) {
658 fd = lo_fi_fd(req, fi);
661 if (valid & FUSE_SET_ATTR_MODE) {
662 if (fi) {
663 res = fchmod(fd, attr->st_mode);
664 } else {
665 sprintf(procname, "%i", ifd);
666 res = fchmodat(lo->proc_self_fd, procname, attr->st_mode, 0);
668 if (res == -1) {
669 goto out_err;
672 if (valid & (FUSE_SET_ATTR_UID | FUSE_SET_ATTR_GID)) {
673 uid_t uid = (valid & FUSE_SET_ATTR_UID) ? attr->st_uid : (uid_t)-1;
674 gid_t gid = (valid & FUSE_SET_ATTR_GID) ? attr->st_gid : (gid_t)-1;
676 res = fchownat(ifd, "", uid, gid, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW);
677 if (res == -1) {
678 goto out_err;
681 if (valid & FUSE_SET_ATTR_SIZE) {
682 int truncfd;
684 if (fi) {
685 truncfd = fd;
686 } else {
687 sprintf(procname, "%i", ifd);
688 truncfd = openat(lo->proc_self_fd, procname, O_RDWR);
689 if (truncfd < 0) {
690 goto out_err;
694 res = ftruncate(truncfd, attr->st_size);
695 if (!fi) {
696 saverr = errno;
697 close(truncfd);
698 errno = saverr;
700 if (res == -1) {
701 goto out_err;
704 if (valid & (FUSE_SET_ATTR_ATIME | FUSE_SET_ATTR_MTIME)) {
705 struct timespec tv[2];
707 tv[0].tv_sec = 0;
708 tv[1].tv_sec = 0;
709 tv[0].tv_nsec = UTIME_OMIT;
710 tv[1].tv_nsec = UTIME_OMIT;
712 if (valid & FUSE_SET_ATTR_ATIME_NOW) {
713 tv[0].tv_nsec = UTIME_NOW;
714 } else if (valid & FUSE_SET_ATTR_ATIME) {
715 tv[0] = attr->st_atim;
718 if (valid & FUSE_SET_ATTR_MTIME_NOW) {
719 tv[1].tv_nsec = UTIME_NOW;
720 } else if (valid & FUSE_SET_ATTR_MTIME) {
721 tv[1] = attr->st_mtim;
724 if (fi) {
725 res = futimens(fd, tv);
726 } else {
727 sprintf(procname, "%i", inode->fd);
728 res = utimensat(lo->proc_self_fd, procname, tv, 0);
730 if (res == -1) {
731 goto out_err;
734 lo_inode_put(lo, &inode);
736 return lo_getattr(req, ino, fi);
738 out_err:
739 saverr = errno;
740 lo_inode_put(lo, &inode);
741 fuse_reply_err(req, saverr);
744 static struct lo_inode *lo_find(struct lo_data *lo, struct stat *st,
745 uint64_t mnt_id)
747 struct lo_inode *p;
748 struct lo_key key = {
749 .ino = st->st_ino,
750 .dev = st->st_dev,
751 .mnt_id = mnt_id,
754 pthread_mutex_lock(&lo->mutex);
755 p = g_hash_table_lookup(lo->inodes, &key);
756 if (p) {
757 assert(p->nlookup > 0);
758 p->nlookup++;
759 g_atomic_int_inc(&p->refcount);
761 pthread_mutex_unlock(&lo->mutex);
763 return p;
766 /* value_destroy_func for posix_locks GHashTable */
767 static void posix_locks_value_destroy(gpointer data)
769 struct lo_inode_plock *plock = data;
772 * We had used open() for locks and had only one fd. So
773 * closing this fd should release all OFD locks.
775 close(plock->fd);
776 free(plock);
779 static int do_statx(struct lo_data *lo, int dirfd, const char *pathname,
780 struct stat *statbuf, int flags, uint64_t *mnt_id)
782 int res;
784 #if defined(CONFIG_STATX) && defined(STATX_MNT_ID)
785 if (lo->use_statx) {
786 struct statx statxbuf;
788 res = statx(dirfd, pathname, flags, STATX_BASIC_STATS | STATX_MNT_ID,
789 &statxbuf);
790 if (!res) {
791 memset(statbuf, 0, sizeof(*statbuf));
792 statbuf->st_dev = makedev(statxbuf.stx_dev_major,
793 statxbuf.stx_dev_minor);
794 statbuf->st_ino = statxbuf.stx_ino;
795 statbuf->st_mode = statxbuf.stx_mode;
796 statbuf->st_nlink = statxbuf.stx_nlink;
797 statbuf->st_uid = statxbuf.stx_uid;
798 statbuf->st_gid = statxbuf.stx_gid;
799 statbuf->st_rdev = makedev(statxbuf.stx_rdev_major,
800 statxbuf.stx_rdev_minor);
801 statbuf->st_size = statxbuf.stx_size;
802 statbuf->st_blksize = statxbuf.stx_blksize;
803 statbuf->st_blocks = statxbuf.stx_blocks;
804 statbuf->st_atim.tv_sec = statxbuf.stx_atime.tv_sec;
805 statbuf->st_atim.tv_nsec = statxbuf.stx_atime.tv_nsec;
806 statbuf->st_mtim.tv_sec = statxbuf.stx_mtime.tv_sec;
807 statbuf->st_mtim.tv_nsec = statxbuf.stx_mtime.tv_nsec;
808 statbuf->st_ctim.tv_sec = statxbuf.stx_ctime.tv_sec;
809 statbuf->st_ctim.tv_nsec = statxbuf.stx_ctime.tv_nsec;
811 if (statxbuf.stx_mask & STATX_MNT_ID) {
812 *mnt_id = statxbuf.stx_mnt_id;
813 } else {
814 *mnt_id = 0;
816 return 0;
817 } else if (errno != ENOSYS) {
818 return -1;
820 lo->use_statx = false;
821 /* fallback */
823 #endif
824 res = fstatat(dirfd, pathname, statbuf, flags);
825 if (res == -1) {
826 return -1;
828 *mnt_id = 0;
830 return 0;
834 * Increments nlookup and caller must release refcount using
835 * lo_inode_put(&parent).
837 static int lo_do_lookup(fuse_req_t req, fuse_ino_t parent, const char *name,
838 struct fuse_entry_param *e)
840 int newfd;
841 int res;
842 int saverr;
843 uint64_t mnt_id;
844 struct lo_data *lo = lo_data(req);
845 struct lo_inode *inode = NULL;
846 struct lo_inode *dir = lo_inode(req, parent);
849 * name_to_handle_at() and open_by_handle_at() can reach here with fuse
850 * mount point in guest, but we don't have its inode info in the
851 * ino_map.
853 if (!dir) {
854 return ENOENT;
857 memset(e, 0, sizeof(*e));
858 e->attr_timeout = lo->timeout;
859 e->entry_timeout = lo->timeout;
861 /* Do not allow escaping root directory */
862 if (dir == &lo->root && strcmp(name, "..") == 0) {
863 name = ".";
866 newfd = openat(dir->fd, name, O_PATH | O_NOFOLLOW);
867 if (newfd == -1) {
868 goto out_err;
871 res = do_statx(lo, newfd, "", &e->attr, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW,
872 &mnt_id);
873 if (res == -1) {
874 goto out_err;
877 if (S_ISDIR(e->attr.st_mode) && lo->announce_submounts &&
878 (e->attr.st_dev != dir->key.dev || mnt_id != dir->key.mnt_id)) {
879 e->attr_flags |= FUSE_ATTR_SUBMOUNT;
882 inode = lo_find(lo, &e->attr, mnt_id);
883 if (inode) {
884 close(newfd);
885 } else {
886 inode = calloc(1, sizeof(struct lo_inode));
887 if (!inode) {
888 goto out_err;
891 /* cache only filetype */
892 inode->filetype = (e->attr.st_mode & S_IFMT);
895 * One for the caller and one for nlookup (released in
896 * unref_inode_lolocked())
898 g_atomic_int_set(&inode->refcount, 2);
900 inode->nlookup = 1;
901 inode->fd = newfd;
902 inode->key.ino = e->attr.st_ino;
903 inode->key.dev = e->attr.st_dev;
904 inode->key.mnt_id = mnt_id;
905 if (lo->posix_lock) {
906 pthread_mutex_init(&inode->plock_mutex, NULL);
907 inode->posix_locks = g_hash_table_new_full(
908 g_direct_hash, g_direct_equal, NULL, posix_locks_value_destroy);
910 pthread_mutex_lock(&lo->mutex);
911 inode->fuse_ino = lo_add_inode_mapping(req, inode);
912 g_hash_table_insert(lo->inodes, &inode->key, inode);
913 pthread_mutex_unlock(&lo->mutex);
915 e->ino = inode->fuse_ino;
916 lo_inode_put(lo, &inode);
917 lo_inode_put(lo, &dir);
919 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
920 name, (unsigned long long)e->ino);
922 return 0;
924 out_err:
925 saverr = errno;
926 if (newfd != -1) {
927 close(newfd);
929 lo_inode_put(lo, &inode);
930 lo_inode_put(lo, &dir);
931 return saverr;
934 static void lo_lookup(fuse_req_t req, fuse_ino_t parent, const char *name)
936 struct fuse_entry_param e;
937 int err;
939 fuse_log(FUSE_LOG_DEBUG, "lo_lookup(parent=%" PRIu64 ", name=%s)\n", parent,
940 name);
943 * Don't use is_safe_path_component(), allow "." and ".." for NFS export
944 * support.
946 if (strchr(name, '/')) {
947 fuse_reply_err(req, EINVAL);
948 return;
951 err = lo_do_lookup(req, parent, name, &e);
952 if (err) {
953 fuse_reply_err(req, err);
954 } else {
955 fuse_reply_entry(req, &e);
960 * On some archs, setres*id is limited to 2^16 but they
961 * provide setres*id32 variants that allow 2^32.
962 * Others just let setres*id do 2^32 anyway.
964 #ifdef SYS_setresgid32
965 #define OURSYS_setresgid SYS_setresgid32
966 #else
967 #define OURSYS_setresgid SYS_setresgid
968 #endif
970 #ifdef SYS_setresuid32
971 #define OURSYS_setresuid SYS_setresuid32
972 #else
973 #define OURSYS_setresuid SYS_setresuid
974 #endif
977 * Change to uid/gid of caller so that file is created with
978 * ownership of caller.
979 * TODO: What about selinux context?
981 static int lo_change_cred(fuse_req_t req, struct lo_cred *old)
983 int res;
985 old->euid = geteuid();
986 old->egid = getegid();
988 res = syscall(OURSYS_setresgid, -1, fuse_req_ctx(req)->gid, -1);
989 if (res == -1) {
990 return errno;
993 res = syscall(OURSYS_setresuid, -1, fuse_req_ctx(req)->uid, -1);
994 if (res == -1) {
995 int errno_save = errno;
997 syscall(OURSYS_setresgid, -1, old->egid, -1);
998 return errno_save;
1001 return 0;
1004 /* Regain Privileges */
1005 static void lo_restore_cred(struct lo_cred *old)
1007 int res;
1009 res = syscall(OURSYS_setresuid, -1, old->euid, -1);
1010 if (res == -1) {
1011 fuse_log(FUSE_LOG_ERR, "seteuid(%u): %m\n", old->euid);
1012 exit(1);
1015 res = syscall(OURSYS_setresgid, -1, old->egid, -1);
1016 if (res == -1) {
1017 fuse_log(FUSE_LOG_ERR, "setegid(%u): %m\n", old->egid);
1018 exit(1);
1022 static void lo_mknod_symlink(fuse_req_t req, fuse_ino_t parent,
1023 const char *name, mode_t mode, dev_t rdev,
1024 const char *link)
1026 int res;
1027 int saverr;
1028 struct lo_data *lo = lo_data(req);
1029 struct lo_inode *dir;
1030 struct fuse_entry_param e;
1031 struct lo_cred old = {};
1033 if (!is_safe_path_component(name)) {
1034 fuse_reply_err(req, EINVAL);
1035 return;
1038 dir = lo_inode(req, parent);
1039 if (!dir) {
1040 fuse_reply_err(req, EBADF);
1041 return;
1044 saverr = lo_change_cred(req, &old);
1045 if (saverr) {
1046 goto out;
1049 res = mknod_wrapper(dir->fd, name, link, mode, rdev);
1051 saverr = errno;
1053 lo_restore_cred(&old);
1055 if (res == -1) {
1056 goto out;
1059 saverr = lo_do_lookup(req, parent, name, &e);
1060 if (saverr) {
1061 goto out;
1064 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
1065 name, (unsigned long long)e.ino);
1067 fuse_reply_entry(req, &e);
1068 lo_inode_put(lo, &dir);
1069 return;
1071 out:
1072 lo_inode_put(lo, &dir);
1073 fuse_reply_err(req, saverr);
1076 static void lo_mknod(fuse_req_t req, fuse_ino_t parent, const char *name,
1077 mode_t mode, dev_t rdev)
1079 lo_mknod_symlink(req, parent, name, mode, rdev, NULL);
1082 static void lo_mkdir(fuse_req_t req, fuse_ino_t parent, const char *name,
1083 mode_t mode)
1085 lo_mknod_symlink(req, parent, name, S_IFDIR | mode, 0, NULL);
1088 static void lo_symlink(fuse_req_t req, const char *link, fuse_ino_t parent,
1089 const char *name)
1091 lo_mknod_symlink(req, parent, name, S_IFLNK, 0, link);
1094 static void lo_link(fuse_req_t req, fuse_ino_t ino, fuse_ino_t parent,
1095 const char *name)
1097 int res;
1098 struct lo_data *lo = lo_data(req);
1099 struct lo_inode *parent_inode;
1100 struct lo_inode *inode;
1101 struct fuse_entry_param e;
1102 char procname[64];
1103 int saverr;
1105 if (!is_safe_path_component(name)) {
1106 fuse_reply_err(req, EINVAL);
1107 return;
1110 parent_inode = lo_inode(req, parent);
1111 inode = lo_inode(req, ino);
1112 if (!parent_inode || !inode) {
1113 errno = EBADF;
1114 goto out_err;
1117 memset(&e, 0, sizeof(struct fuse_entry_param));
1118 e.attr_timeout = lo->timeout;
1119 e.entry_timeout = lo->timeout;
1121 sprintf(procname, "%i", inode->fd);
1122 res = linkat(lo->proc_self_fd, procname, parent_inode->fd, name,
1123 AT_SYMLINK_FOLLOW);
1124 if (res == -1) {
1125 goto out_err;
1128 res = fstatat(inode->fd, "", &e.attr, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW);
1129 if (res == -1) {
1130 goto out_err;
1133 pthread_mutex_lock(&lo->mutex);
1134 inode->nlookup++;
1135 pthread_mutex_unlock(&lo->mutex);
1136 e.ino = inode->fuse_ino;
1138 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
1139 name, (unsigned long long)e.ino);
1141 fuse_reply_entry(req, &e);
1142 lo_inode_put(lo, &parent_inode);
1143 lo_inode_put(lo, &inode);
1144 return;
1146 out_err:
1147 saverr = errno;
1148 lo_inode_put(lo, &parent_inode);
1149 lo_inode_put(lo, &inode);
1150 fuse_reply_err(req, saverr);
1153 /* Increments nlookup and caller must release refcount using lo_inode_put() */
1154 static struct lo_inode *lookup_name(fuse_req_t req, fuse_ino_t parent,
1155 const char *name)
1157 int res;
1158 uint64_t mnt_id;
1159 struct stat attr;
1160 struct lo_data *lo = lo_data(req);
1161 struct lo_inode *dir = lo_inode(req, parent);
1163 if (!dir) {
1164 return NULL;
1167 res = do_statx(lo, dir->fd, name, &attr,
1168 AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW, &mnt_id);
1169 lo_inode_put(lo, &dir);
1170 if (res == -1) {
1171 return NULL;
1174 return lo_find(lo, &attr, mnt_id);
1177 static void lo_rmdir(fuse_req_t req, fuse_ino_t parent, const char *name)
1179 int res;
1180 struct lo_inode *inode;
1181 struct lo_data *lo = lo_data(req);
1183 if (!is_safe_path_component(name)) {
1184 fuse_reply_err(req, EINVAL);
1185 return;
1188 inode = lookup_name(req, parent, name);
1189 if (!inode) {
1190 fuse_reply_err(req, EIO);
1191 return;
1194 res = unlinkat(lo_fd(req, parent), name, AT_REMOVEDIR);
1196 fuse_reply_err(req, res == -1 ? errno : 0);
1197 unref_inode_lolocked(lo, inode, 1);
1198 lo_inode_put(lo, &inode);
1201 static void lo_rename(fuse_req_t req, fuse_ino_t parent, const char *name,
1202 fuse_ino_t newparent, const char *newname,
1203 unsigned int flags)
1205 int res;
1206 struct lo_inode *parent_inode;
1207 struct lo_inode *newparent_inode;
1208 struct lo_inode *oldinode = NULL;
1209 struct lo_inode *newinode = NULL;
1210 struct lo_data *lo = lo_data(req);
1212 if (!is_safe_path_component(name) || !is_safe_path_component(newname)) {
1213 fuse_reply_err(req, EINVAL);
1214 return;
1217 parent_inode = lo_inode(req, parent);
1218 newparent_inode = lo_inode(req, newparent);
1219 if (!parent_inode || !newparent_inode) {
1220 fuse_reply_err(req, EBADF);
1221 goto out;
1224 oldinode = lookup_name(req, parent, name);
1225 newinode = lookup_name(req, newparent, newname);
1227 if (!oldinode) {
1228 fuse_reply_err(req, EIO);
1229 goto out;
1232 if (flags) {
1233 #ifndef SYS_renameat2
1234 fuse_reply_err(req, EINVAL);
1235 #else
1236 res = syscall(SYS_renameat2, parent_inode->fd, name,
1237 newparent_inode->fd, newname, flags);
1238 if (res == -1 && errno == ENOSYS) {
1239 fuse_reply_err(req, EINVAL);
1240 } else {
1241 fuse_reply_err(req, res == -1 ? errno : 0);
1243 #endif
1244 goto out;
1247 res = renameat(parent_inode->fd, name, newparent_inode->fd, newname);
1249 fuse_reply_err(req, res == -1 ? errno : 0);
1250 out:
1251 unref_inode_lolocked(lo, oldinode, 1);
1252 unref_inode_lolocked(lo, newinode, 1);
1253 lo_inode_put(lo, &oldinode);
1254 lo_inode_put(lo, &newinode);
1255 lo_inode_put(lo, &parent_inode);
1256 lo_inode_put(lo, &newparent_inode);
1259 static void lo_unlink(fuse_req_t req, fuse_ino_t parent, const char *name)
1261 int res;
1262 struct lo_inode *inode;
1263 struct lo_data *lo = lo_data(req);
1265 if (!is_safe_path_component(name)) {
1266 fuse_reply_err(req, EINVAL);
1267 return;
1270 inode = lookup_name(req, parent, name);
1271 if (!inode) {
1272 fuse_reply_err(req, EIO);
1273 return;
1276 res = unlinkat(lo_fd(req, parent), name, 0);
1278 fuse_reply_err(req, res == -1 ? errno : 0);
1279 unref_inode_lolocked(lo, inode, 1);
1280 lo_inode_put(lo, &inode);
1283 /* To be called with lo->mutex held */
1284 static void unref_inode(struct lo_data *lo, struct lo_inode *inode, uint64_t n)
1286 if (!inode) {
1287 return;
1290 assert(inode->nlookup >= n);
1291 inode->nlookup -= n;
1292 if (!inode->nlookup) {
1293 lo_map_remove(&lo->ino_map, inode->fuse_ino);
1294 g_hash_table_remove(lo->inodes, &inode->key);
1295 if (lo->posix_lock) {
1296 if (g_hash_table_size(inode->posix_locks)) {
1297 fuse_log(FUSE_LOG_WARNING, "Hash table is not empty\n");
1299 g_hash_table_destroy(inode->posix_locks);
1300 pthread_mutex_destroy(&inode->plock_mutex);
1302 /* Drop our refcount from lo_do_lookup() */
1303 lo_inode_put(lo, &inode);
1307 static void unref_inode_lolocked(struct lo_data *lo, struct lo_inode *inode,
1308 uint64_t n)
1310 if (!inode) {
1311 return;
1314 pthread_mutex_lock(&lo->mutex);
1315 unref_inode(lo, inode, n);
1316 pthread_mutex_unlock(&lo->mutex);
1319 static void lo_forget_one(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup)
1321 struct lo_data *lo = lo_data(req);
1322 struct lo_inode *inode;
1324 inode = lo_inode(req, ino);
1325 if (!inode) {
1326 return;
1329 fuse_log(FUSE_LOG_DEBUG, " forget %lli %lli -%lli\n",
1330 (unsigned long long)ino, (unsigned long long)inode->nlookup,
1331 (unsigned long long)nlookup);
1333 unref_inode_lolocked(lo, inode, nlookup);
1334 lo_inode_put(lo, &inode);
1337 static void lo_forget(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup)
1339 lo_forget_one(req, ino, nlookup);
1340 fuse_reply_none(req);
1343 static void lo_forget_multi(fuse_req_t req, size_t count,
1344 struct fuse_forget_data *forgets)
1346 int i;
1348 for (i = 0; i < count; i++) {
1349 lo_forget_one(req, forgets[i].ino, forgets[i].nlookup);
1351 fuse_reply_none(req);
1354 static void lo_readlink(fuse_req_t req, fuse_ino_t ino)
1356 char buf[PATH_MAX + 1];
1357 int res;
1359 res = readlinkat(lo_fd(req, ino), "", buf, sizeof(buf));
1360 if (res == -1) {
1361 return (void)fuse_reply_err(req, errno);
1364 if (res == sizeof(buf)) {
1365 return (void)fuse_reply_err(req, ENAMETOOLONG);
1368 buf[res] = '\0';
1370 fuse_reply_readlink(req, buf);
1373 struct lo_dirp {
1374 gint refcount;
1375 DIR *dp;
1376 struct dirent *entry;
1377 off_t offset;
1380 static void lo_dirp_put(struct lo_dirp **dp)
1382 struct lo_dirp *d = *dp;
1384 if (!d) {
1385 return;
1387 *dp = NULL;
1389 if (g_atomic_int_dec_and_test(&d->refcount)) {
1390 closedir(d->dp);
1391 free(d);
1395 /* Call lo_dirp_put() on the return value when no longer needed */
1396 static struct lo_dirp *lo_dirp(fuse_req_t req, struct fuse_file_info *fi)
1398 struct lo_data *lo = lo_data(req);
1399 struct lo_map_elem *elem;
1401 pthread_mutex_lock(&lo->mutex);
1402 elem = lo_map_get(&lo->dirp_map, fi->fh);
1403 if (elem) {
1404 g_atomic_int_inc(&elem->dirp->refcount);
1406 pthread_mutex_unlock(&lo->mutex);
1407 if (!elem) {
1408 return NULL;
1411 return elem->dirp;
1414 static void lo_opendir(fuse_req_t req, fuse_ino_t ino,
1415 struct fuse_file_info *fi)
1417 int error = ENOMEM;
1418 struct lo_data *lo = lo_data(req);
1419 struct lo_dirp *d;
1420 int fd;
1421 ssize_t fh;
1423 d = calloc(1, sizeof(struct lo_dirp));
1424 if (d == NULL) {
1425 goto out_err;
1428 fd = openat(lo_fd(req, ino), ".", O_RDONLY);
1429 if (fd == -1) {
1430 goto out_errno;
1433 d->dp = fdopendir(fd);
1434 if (d->dp == NULL) {
1435 goto out_errno;
1438 d->offset = 0;
1439 d->entry = NULL;
1441 g_atomic_int_set(&d->refcount, 1); /* paired with lo_releasedir() */
1442 pthread_mutex_lock(&lo->mutex);
1443 fh = lo_add_dirp_mapping(req, d);
1444 pthread_mutex_unlock(&lo->mutex);
1445 if (fh == -1) {
1446 goto out_err;
1449 fi->fh = fh;
1450 if (lo->cache == CACHE_ALWAYS) {
1451 fi->cache_readdir = 1;
1453 fuse_reply_open(req, fi);
1454 return;
1456 out_errno:
1457 error = errno;
1458 out_err:
1459 if (d) {
1460 if (d->dp) {
1461 closedir(d->dp);
1462 } else if (fd != -1) {
1463 close(fd);
1465 free(d);
1467 fuse_reply_err(req, error);
1470 static void lo_do_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
1471 off_t offset, struct fuse_file_info *fi, int plus)
1473 struct lo_data *lo = lo_data(req);
1474 struct lo_dirp *d = NULL;
1475 struct lo_inode *dinode;
1476 char *buf = NULL;
1477 char *p;
1478 size_t rem = size;
1479 int err = EBADF;
1481 dinode = lo_inode(req, ino);
1482 if (!dinode) {
1483 goto error;
1486 d = lo_dirp(req, fi);
1487 if (!d) {
1488 goto error;
1491 err = ENOMEM;
1492 buf = calloc(1, size);
1493 if (!buf) {
1494 goto error;
1496 p = buf;
1498 if (offset != d->offset) {
1499 seekdir(d->dp, offset);
1500 d->entry = NULL;
1501 d->offset = offset;
1503 while (1) {
1504 size_t entsize;
1505 off_t nextoff;
1506 const char *name;
1508 if (!d->entry) {
1509 errno = 0;
1510 d->entry = readdir(d->dp);
1511 if (!d->entry) {
1512 if (errno) { /* Error */
1513 err = errno;
1514 goto error;
1515 } else { /* End of stream */
1516 break;
1520 nextoff = d->entry->d_off;
1521 name = d->entry->d_name;
1523 fuse_ino_t entry_ino = 0;
1524 struct fuse_entry_param e = (struct fuse_entry_param){
1525 .attr.st_ino = d->entry->d_ino,
1526 .attr.st_mode = d->entry->d_type << 12,
1529 /* Hide root's parent directory */
1530 if (dinode == &lo->root && strcmp(name, "..") == 0) {
1531 e.attr.st_ino = lo->root.key.ino;
1532 e.attr.st_mode = DT_DIR << 12;
1535 if (plus) {
1536 if (!is_dot_or_dotdot(name)) {
1537 err = lo_do_lookup(req, ino, name, &e);
1538 if (err) {
1539 goto error;
1541 entry_ino = e.ino;
1544 entsize = fuse_add_direntry_plus(req, p, rem, name, &e, nextoff);
1545 } else {
1546 entsize = fuse_add_direntry(req, p, rem, name, &e.attr, nextoff);
1548 if (entsize > rem) {
1549 if (entry_ino != 0) {
1550 lo_forget_one(req, entry_ino, 1);
1552 break;
1555 p += entsize;
1556 rem -= entsize;
1558 d->entry = NULL;
1559 d->offset = nextoff;
1562 err = 0;
1563 error:
1564 lo_dirp_put(&d);
1565 lo_inode_put(lo, &dinode);
1568 * If there's an error, we can only signal it if we haven't stored
1569 * any entries yet - otherwise we'd end up with wrong lookup
1570 * counts for the entries that are already in the buffer. So we
1571 * return what we've collected until that point.
1573 if (err && rem == size) {
1574 fuse_reply_err(req, err);
1575 } else {
1576 fuse_reply_buf(req, buf, size - rem);
1578 free(buf);
1581 static void lo_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
1582 off_t offset, struct fuse_file_info *fi)
1584 lo_do_readdir(req, ino, size, offset, fi, 0);
1587 static void lo_readdirplus(fuse_req_t req, fuse_ino_t ino, size_t size,
1588 off_t offset, struct fuse_file_info *fi)
1590 lo_do_readdir(req, ino, size, offset, fi, 1);
1593 static void lo_releasedir(fuse_req_t req, fuse_ino_t ino,
1594 struct fuse_file_info *fi)
1596 struct lo_data *lo = lo_data(req);
1597 struct lo_map_elem *elem;
1598 struct lo_dirp *d;
1600 (void)ino;
1602 pthread_mutex_lock(&lo->mutex);
1603 elem = lo_map_get(&lo->dirp_map, fi->fh);
1604 if (!elem) {
1605 pthread_mutex_unlock(&lo->mutex);
1606 fuse_reply_err(req, EBADF);
1607 return;
1610 d = elem->dirp;
1611 lo_map_remove(&lo->dirp_map, fi->fh);
1612 pthread_mutex_unlock(&lo->mutex);
1614 lo_dirp_put(&d); /* paired with lo_opendir() */
1616 fuse_reply_err(req, 0);
1619 static void update_open_flags(int writeback, int allow_direct_io,
1620 struct fuse_file_info *fi)
1623 * With writeback cache, kernel may send read requests even
1624 * when userspace opened write-only
1626 if (writeback && (fi->flags & O_ACCMODE) == O_WRONLY) {
1627 fi->flags &= ~O_ACCMODE;
1628 fi->flags |= O_RDWR;
1632 * With writeback cache, O_APPEND is handled by the kernel.
1633 * This breaks atomicity (since the file may change in the
1634 * underlying filesystem, so that the kernel's idea of the
1635 * end of the file isn't accurate anymore). In this example,
1636 * we just accept that. A more rigorous filesystem may want
1637 * to return an error here
1639 if (writeback && (fi->flags & O_APPEND)) {
1640 fi->flags &= ~O_APPEND;
1644 * O_DIRECT in guest should not necessarily mean bypassing page
1645 * cache on host as well. Therefore, we discard it by default
1646 * ('-o no_allow_direct_io'). If somebody needs that behavior,
1647 * the '-o allow_direct_io' option should be set.
1649 if (!allow_direct_io) {
1650 fi->flags &= ~O_DIRECT;
1654 static void lo_create(fuse_req_t req, fuse_ino_t parent, const char *name,
1655 mode_t mode, struct fuse_file_info *fi)
1657 int fd;
1658 struct lo_data *lo = lo_data(req);
1659 struct lo_inode *parent_inode;
1660 struct fuse_entry_param e;
1661 int err;
1662 struct lo_cred old = {};
1664 fuse_log(FUSE_LOG_DEBUG, "lo_create(parent=%" PRIu64 ", name=%s)\n", parent,
1665 name);
1667 if (!is_safe_path_component(name)) {
1668 fuse_reply_err(req, EINVAL);
1669 return;
1672 parent_inode = lo_inode(req, parent);
1673 if (!parent_inode) {
1674 fuse_reply_err(req, EBADF);
1675 return;
1678 err = lo_change_cred(req, &old);
1679 if (err) {
1680 goto out;
1683 update_open_flags(lo->writeback, lo->allow_direct_io, fi);
1685 fd = openat(parent_inode->fd, name, (fi->flags | O_CREAT) & ~O_NOFOLLOW,
1686 mode);
1687 err = fd == -1 ? errno : 0;
1688 lo_restore_cred(&old);
1690 if (!err) {
1691 ssize_t fh;
1693 pthread_mutex_lock(&lo->mutex);
1694 fh = lo_add_fd_mapping(req, fd);
1695 pthread_mutex_unlock(&lo->mutex);
1696 if (fh == -1) {
1697 close(fd);
1698 err = ENOMEM;
1699 goto out;
1702 fi->fh = fh;
1703 err = lo_do_lookup(req, parent, name, &e);
1705 if (lo->cache == CACHE_NONE) {
1706 fi->direct_io = 1;
1707 } else if (lo->cache == CACHE_ALWAYS) {
1708 fi->keep_cache = 1;
1711 out:
1712 lo_inode_put(lo, &parent_inode);
1714 if (err) {
1715 fuse_reply_err(req, err);
1716 } else {
1717 fuse_reply_create(req, &e, fi);
1721 /* Should be called with inode->plock_mutex held */
1722 static struct lo_inode_plock *lookup_create_plock_ctx(struct lo_data *lo,
1723 struct lo_inode *inode,
1724 uint64_t lock_owner,
1725 pid_t pid, int *err)
1727 struct lo_inode_plock *plock;
1728 char procname[64];
1729 int fd;
1731 plock =
1732 g_hash_table_lookup(inode->posix_locks, GUINT_TO_POINTER(lock_owner));
1734 if (plock) {
1735 return plock;
1738 plock = malloc(sizeof(struct lo_inode_plock));
1739 if (!plock) {
1740 *err = ENOMEM;
1741 return NULL;
1744 /* Open another instance of file which can be used for ofd locks. */
1745 sprintf(procname, "%i", inode->fd);
1747 /* TODO: What if file is not writable? */
1748 fd = openat(lo->proc_self_fd, procname, O_RDWR);
1749 if (fd == -1) {
1750 *err = errno;
1751 free(plock);
1752 return NULL;
1755 plock->lock_owner = lock_owner;
1756 plock->fd = fd;
1757 g_hash_table_insert(inode->posix_locks, GUINT_TO_POINTER(plock->lock_owner),
1758 plock);
1759 return plock;
1762 static void lo_getlk(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
1763 struct flock *lock)
1765 struct lo_data *lo = lo_data(req);
1766 struct lo_inode *inode;
1767 struct lo_inode_plock *plock;
1768 int ret, saverr = 0;
1770 fuse_log(FUSE_LOG_DEBUG,
1771 "lo_getlk(ino=%" PRIu64 ", flags=%d)"
1772 " owner=0x%lx, l_type=%d l_start=0x%lx"
1773 " l_len=0x%lx\n",
1774 ino, fi->flags, fi->lock_owner, lock->l_type, lock->l_start,
1775 lock->l_len);
1777 if (!lo->posix_lock) {
1778 fuse_reply_err(req, ENOSYS);
1779 return;
1782 inode = lo_inode(req, ino);
1783 if (!inode) {
1784 fuse_reply_err(req, EBADF);
1785 return;
1788 pthread_mutex_lock(&inode->plock_mutex);
1789 plock =
1790 lookup_create_plock_ctx(lo, inode, fi->lock_owner, lock->l_pid, &ret);
1791 if (!plock) {
1792 saverr = ret;
1793 goto out;
1796 ret = fcntl(plock->fd, F_OFD_GETLK, lock);
1797 if (ret == -1) {
1798 saverr = errno;
1801 out:
1802 pthread_mutex_unlock(&inode->plock_mutex);
1803 lo_inode_put(lo, &inode);
1805 if (saverr) {
1806 fuse_reply_err(req, saverr);
1807 } else {
1808 fuse_reply_lock(req, lock);
1812 static void lo_setlk(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
1813 struct flock *lock, int sleep)
1815 struct lo_data *lo = lo_data(req);
1816 struct lo_inode *inode;
1817 struct lo_inode_plock *plock;
1818 int ret, saverr = 0;
1820 fuse_log(FUSE_LOG_DEBUG,
1821 "lo_setlk(ino=%" PRIu64 ", flags=%d)"
1822 " cmd=%d pid=%d owner=0x%lx sleep=%d l_whence=%d"
1823 " l_start=0x%lx l_len=0x%lx\n",
1824 ino, fi->flags, lock->l_type, lock->l_pid, fi->lock_owner, sleep,
1825 lock->l_whence, lock->l_start, lock->l_len);
1827 if (!lo->posix_lock) {
1828 fuse_reply_err(req, ENOSYS);
1829 return;
1832 if (sleep) {
1833 fuse_reply_err(req, EOPNOTSUPP);
1834 return;
1837 inode = lo_inode(req, ino);
1838 if (!inode) {
1839 fuse_reply_err(req, EBADF);
1840 return;
1843 pthread_mutex_lock(&inode->plock_mutex);
1844 plock =
1845 lookup_create_plock_ctx(lo, inode, fi->lock_owner, lock->l_pid, &ret);
1847 if (!plock) {
1848 saverr = ret;
1849 goto out;
1852 /* TODO: Is it alright to modify flock? */
1853 lock->l_pid = 0;
1854 ret = fcntl(plock->fd, F_OFD_SETLK, lock);
1855 if (ret == -1) {
1856 saverr = errno;
1859 out:
1860 pthread_mutex_unlock(&inode->plock_mutex);
1861 lo_inode_put(lo, &inode);
1863 fuse_reply_err(req, saverr);
1866 static void lo_fsyncdir(fuse_req_t req, fuse_ino_t ino, int datasync,
1867 struct fuse_file_info *fi)
1869 int res;
1870 struct lo_dirp *d;
1871 int fd;
1873 (void)ino;
1875 d = lo_dirp(req, fi);
1876 if (!d) {
1877 fuse_reply_err(req, EBADF);
1878 return;
1881 fd = dirfd(d->dp);
1882 if (datasync) {
1883 res = fdatasync(fd);
1884 } else {
1885 res = fsync(fd);
1888 lo_dirp_put(&d);
1890 fuse_reply_err(req, res == -1 ? errno : 0);
1893 static void lo_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi)
1895 int fd;
1896 ssize_t fh;
1897 char buf[64];
1898 struct lo_data *lo = lo_data(req);
1900 fuse_log(FUSE_LOG_DEBUG, "lo_open(ino=%" PRIu64 ", flags=%d)\n", ino,
1901 fi->flags);
1903 update_open_flags(lo->writeback, lo->allow_direct_io, fi);
1905 sprintf(buf, "%i", lo_fd(req, ino));
1906 fd = openat(lo->proc_self_fd, buf, fi->flags & ~O_NOFOLLOW);
1907 if (fd == -1) {
1908 return (void)fuse_reply_err(req, errno);
1911 pthread_mutex_lock(&lo->mutex);
1912 fh = lo_add_fd_mapping(req, fd);
1913 pthread_mutex_unlock(&lo->mutex);
1914 if (fh == -1) {
1915 close(fd);
1916 fuse_reply_err(req, ENOMEM);
1917 return;
1920 fi->fh = fh;
1921 if (lo->cache == CACHE_NONE) {
1922 fi->direct_io = 1;
1923 } else if (lo->cache == CACHE_ALWAYS) {
1924 fi->keep_cache = 1;
1926 fuse_reply_open(req, fi);
1929 static void lo_release(fuse_req_t req, fuse_ino_t ino,
1930 struct fuse_file_info *fi)
1932 struct lo_data *lo = lo_data(req);
1933 struct lo_map_elem *elem;
1934 int fd = -1;
1936 (void)ino;
1938 pthread_mutex_lock(&lo->mutex);
1939 elem = lo_map_get(&lo->fd_map, fi->fh);
1940 if (elem) {
1941 fd = elem->fd;
1942 elem = NULL;
1943 lo_map_remove(&lo->fd_map, fi->fh);
1945 pthread_mutex_unlock(&lo->mutex);
1947 close(fd);
1948 fuse_reply_err(req, 0);
1951 static void lo_flush(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi)
1953 int res;
1954 (void)ino;
1955 struct lo_inode *inode;
1956 struct lo_data *lo = lo_data(req);
1958 inode = lo_inode(req, ino);
1959 if (!inode) {
1960 fuse_reply_err(req, EBADF);
1961 return;
1964 if (!S_ISREG(inode->filetype)) {
1965 lo_inode_put(lo, &inode);
1966 fuse_reply_err(req, EBADF);
1967 return;
1970 /* An fd is going away. Cleanup associated posix locks */
1971 if (lo->posix_lock) {
1972 pthread_mutex_lock(&inode->plock_mutex);
1973 g_hash_table_remove(inode->posix_locks,
1974 GUINT_TO_POINTER(fi->lock_owner));
1975 pthread_mutex_unlock(&inode->plock_mutex);
1977 res = close(dup(lo_fi_fd(req, fi)));
1978 lo_inode_put(lo, &inode);
1979 fuse_reply_err(req, res == -1 ? errno : 0);
1982 static void lo_fsync(fuse_req_t req, fuse_ino_t ino, int datasync,
1983 struct fuse_file_info *fi)
1985 int res;
1986 int fd;
1987 char *buf;
1989 fuse_log(FUSE_LOG_DEBUG, "lo_fsync(ino=%" PRIu64 ", fi=0x%p)\n", ino,
1990 (void *)fi);
1992 if (!fi) {
1993 struct lo_data *lo = lo_data(req);
1995 res = asprintf(&buf, "%i", lo_fd(req, ino));
1996 if (res == -1) {
1997 return (void)fuse_reply_err(req, errno);
2000 fd = openat(lo->proc_self_fd, buf, O_RDWR);
2001 free(buf);
2002 if (fd == -1) {
2003 return (void)fuse_reply_err(req, errno);
2005 } else {
2006 fd = lo_fi_fd(req, fi);
2009 if (datasync) {
2010 res = fdatasync(fd);
2011 } else {
2012 res = fsync(fd);
2014 if (!fi) {
2015 close(fd);
2017 fuse_reply_err(req, res == -1 ? errno : 0);
2020 static void lo_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t offset,
2021 struct fuse_file_info *fi)
2023 struct fuse_bufvec buf = FUSE_BUFVEC_INIT(size);
2025 fuse_log(FUSE_LOG_DEBUG,
2026 "lo_read(ino=%" PRIu64 ", size=%zd, "
2027 "off=%lu)\n",
2028 ino, size, (unsigned long)offset);
2030 buf.buf[0].flags = FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK;
2031 buf.buf[0].fd = lo_fi_fd(req, fi);
2032 buf.buf[0].pos = offset;
2034 fuse_reply_data(req, &buf);
2037 static void lo_write_buf(fuse_req_t req, fuse_ino_t ino,
2038 struct fuse_bufvec *in_buf, off_t off,
2039 struct fuse_file_info *fi)
2041 (void)ino;
2042 ssize_t res;
2043 struct fuse_bufvec out_buf = FUSE_BUFVEC_INIT(fuse_buf_size(in_buf));
2044 bool cap_fsetid_dropped = false;
2046 out_buf.buf[0].flags = FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK;
2047 out_buf.buf[0].fd = lo_fi_fd(req, fi);
2048 out_buf.buf[0].pos = off;
2050 fuse_log(FUSE_LOG_DEBUG,
2051 "lo_write_buf(ino=%" PRIu64 ", size=%zd, off=%lu)\n", ino,
2052 out_buf.buf[0].size, (unsigned long)off);
2055 * If kill_priv is set, drop CAP_FSETID which should lead to kernel
2056 * clearing setuid/setgid on file.
2058 if (fi->kill_priv) {
2059 res = drop_effective_cap("FSETID", &cap_fsetid_dropped);
2060 if (res != 0) {
2061 fuse_reply_err(req, res);
2062 return;
2066 res = fuse_buf_copy(&out_buf, in_buf);
2067 if (res < 0) {
2068 fuse_reply_err(req, -res);
2069 } else {
2070 fuse_reply_write(req, (size_t)res);
2073 if (cap_fsetid_dropped) {
2074 res = gain_effective_cap("FSETID");
2075 if (res) {
2076 fuse_log(FUSE_LOG_ERR, "Failed to gain CAP_FSETID\n");
2081 static void lo_statfs(fuse_req_t req, fuse_ino_t ino)
2083 int res;
2084 struct statvfs stbuf;
2086 res = fstatvfs(lo_fd(req, ino), &stbuf);
2087 if (res == -1) {
2088 fuse_reply_err(req, errno);
2089 } else {
2090 fuse_reply_statfs(req, &stbuf);
2094 static void lo_fallocate(fuse_req_t req, fuse_ino_t ino, int mode, off_t offset,
2095 off_t length, struct fuse_file_info *fi)
2097 int err = EOPNOTSUPP;
2098 (void)ino;
2100 #ifdef CONFIG_FALLOCATE
2101 err = fallocate(lo_fi_fd(req, fi), mode, offset, length);
2102 if (err < 0) {
2103 err = errno;
2106 #elif defined(CONFIG_POSIX_FALLOCATE)
2107 if (mode) {
2108 fuse_reply_err(req, EOPNOTSUPP);
2109 return;
2112 err = posix_fallocate(lo_fi_fd(req, fi), offset, length);
2113 #endif
2115 fuse_reply_err(req, err);
2118 static void lo_flock(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
2119 int op)
2121 int res;
2122 (void)ino;
2124 res = flock(lo_fi_fd(req, fi), op);
2126 fuse_reply_err(req, res == -1 ? errno : 0);
2129 /* types */
2131 * Exit; process attribute unmodified if matched.
2132 * An empty key applies to all.
2134 #define XATTR_MAP_FLAG_OK (1 << 0)
2136 * The attribute is unwanted;
2137 * EPERM on write, hidden on read.
2139 #define XATTR_MAP_FLAG_BAD (1 << 1)
2141 * For attr that start with 'key' prepend 'prepend'
2142 * 'key' may be empty to prepend for all attrs
2143 * key is defined from set/remove point of view.
2144 * Automatically reversed on read
2146 #define XATTR_MAP_FLAG_PREFIX (1 << 2)
2148 /* scopes */
2149 /* Apply rule to get/set/remove */
2150 #define XATTR_MAP_FLAG_CLIENT (1 << 16)
2151 /* Apply rule to list */
2152 #define XATTR_MAP_FLAG_SERVER (1 << 17)
2153 /* Apply rule to all */
2154 #define XATTR_MAP_FLAG_ALL (XATTR_MAP_FLAG_SERVER | XATTR_MAP_FLAG_CLIENT)
2156 static void add_xattrmap_entry(struct lo_data *lo,
2157 const XattrMapEntry *new_entry)
2159 XattrMapEntry *res = g_realloc_n(lo->xattr_map_list,
2160 lo->xattr_map_nentries + 1,
2161 sizeof(XattrMapEntry));
2162 res[lo->xattr_map_nentries++] = *new_entry;
2164 lo->xattr_map_list = res;
2167 static void free_xattrmap(struct lo_data *lo)
2169 XattrMapEntry *map = lo->xattr_map_list;
2170 size_t i;
2172 if (!map) {
2173 return;
2176 for (i = 0; i < lo->xattr_map_nentries; i++) {
2177 g_free(map[i].key);
2178 g_free(map[i].prepend);
2181 g_free(map);
2182 lo->xattr_map_list = NULL;
2183 lo->xattr_map_nentries = -1;
2187 * Handle the 'map' type, which is sugar for a set of commands
2188 * for the common case of prefixing a subset or everything,
2189 * and allowing anything not prefixed through.
2190 * It must be the last entry in the stream, although there
2191 * can be other entries before it.
2192 * The form is:
2193 * :map:key:prefix:
2195 * key maybe empty in which case all entries are prefixed.
2197 static void parse_xattrmap_map(struct lo_data *lo,
2198 const char *rule, char sep)
2200 const char *tmp;
2201 char *key;
2202 char *prefix;
2203 XattrMapEntry tmp_entry;
2205 if (*rule != sep) {
2206 fuse_log(FUSE_LOG_ERR,
2207 "%s: Expecting '%c' after 'map' keyword, found '%c'\n",
2208 __func__, sep, *rule);
2209 exit(1);
2212 rule++;
2214 /* At start of 'key' field */
2215 tmp = strchr(rule, sep);
2216 if (!tmp) {
2217 fuse_log(FUSE_LOG_ERR,
2218 "%s: Missing '%c' at end of key field in map rule\n",
2219 __func__, sep);
2220 exit(1);
2223 key = g_strndup(rule, tmp - rule);
2224 rule = tmp + 1;
2226 /* At start of prefix field */
2227 tmp = strchr(rule, sep);
2228 if (!tmp) {
2229 fuse_log(FUSE_LOG_ERR,
2230 "%s: Missing '%c' at end of prefix field in map rule\n",
2231 __func__, sep);
2232 exit(1);
2235 prefix = g_strndup(rule, tmp - rule);
2236 rule = tmp + 1;
2239 * This should be the end of the string, we don't allow
2240 * any more commands after 'map'.
2242 if (*rule) {
2243 fuse_log(FUSE_LOG_ERR,
2244 "%s: Expecting end of command after map, found '%c'\n",
2245 __func__, *rule);
2246 exit(1);
2249 /* 1st: Prefix matches/everything */
2250 tmp_entry.flags = XATTR_MAP_FLAG_PREFIX | XATTR_MAP_FLAG_ALL;
2251 tmp_entry.key = g_strdup(key);
2252 tmp_entry.prepend = g_strdup(prefix);
2253 add_xattrmap_entry(lo, &tmp_entry);
2255 if (!*key) {
2256 /* Prefix all case */
2258 /* 2nd: Hide any non-prefixed entries on the host */
2259 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_ALL;
2260 tmp_entry.key = g_strdup("");
2261 tmp_entry.prepend = g_strdup("");
2262 add_xattrmap_entry(lo, &tmp_entry);
2263 } else {
2264 /* Prefix matching case */
2266 /* 2nd: Hide non-prefixed but matching entries on the host */
2267 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_SERVER;
2268 tmp_entry.key = g_strdup(""); /* Not used */
2269 tmp_entry.prepend = g_strdup(key);
2270 add_xattrmap_entry(lo, &tmp_entry);
2272 /* 3rd: Stop the client accessing prefixed attributes directly */
2273 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_CLIENT;
2274 tmp_entry.key = g_strdup(prefix);
2275 tmp_entry.prepend = g_strdup(""); /* Not used */
2276 add_xattrmap_entry(lo, &tmp_entry);
2278 /* 4th: Everything else is OK */
2279 tmp_entry.flags = XATTR_MAP_FLAG_OK | XATTR_MAP_FLAG_ALL;
2280 tmp_entry.key = g_strdup("");
2281 tmp_entry.prepend = g_strdup("");
2282 add_xattrmap_entry(lo, &tmp_entry);
2285 g_free(key);
2286 g_free(prefix);
2289 static void parse_xattrmap(struct lo_data *lo)
2291 const char *map = lo->xattrmap;
2292 const char *tmp;
2294 lo->xattr_map_nentries = 0;
2295 while (*map) {
2296 XattrMapEntry tmp_entry;
2297 char sep;
2299 if (isspace(*map)) {
2300 map++;
2301 continue;
2303 /* The separator is the first non-space of the rule */
2304 sep = *map++;
2305 if (!sep) {
2306 break;
2309 tmp_entry.flags = 0;
2310 /* Start of 'type' */
2311 if (strstart(map, "prefix", &map)) {
2312 tmp_entry.flags |= XATTR_MAP_FLAG_PREFIX;
2313 } else if (strstart(map, "ok", &map)) {
2314 tmp_entry.flags |= XATTR_MAP_FLAG_OK;
2315 } else if (strstart(map, "bad", &map)) {
2316 tmp_entry.flags |= XATTR_MAP_FLAG_BAD;
2317 } else if (strstart(map, "map", &map)) {
2319 * map is sugar that adds a number of rules, and must be
2320 * the last entry.
2322 parse_xattrmap_map(lo, map, sep);
2323 return;
2324 } else {
2325 fuse_log(FUSE_LOG_ERR,
2326 "%s: Unexpected type;"
2327 "Expecting 'prefix', 'ok', 'bad' or 'map' in rule %zu\n",
2328 __func__, lo->xattr_map_nentries);
2329 exit(1);
2332 if (*map++ != sep) {
2333 fuse_log(FUSE_LOG_ERR,
2334 "%s: Missing '%c' at end of type field of rule %zu\n",
2335 __func__, sep, lo->xattr_map_nentries);
2336 exit(1);
2339 /* Start of 'scope' */
2340 if (strstart(map, "client", &map)) {
2341 tmp_entry.flags |= XATTR_MAP_FLAG_CLIENT;
2342 } else if (strstart(map, "server", &map)) {
2343 tmp_entry.flags |= XATTR_MAP_FLAG_SERVER;
2344 } else if (strstart(map, "all", &map)) {
2345 tmp_entry.flags |= XATTR_MAP_FLAG_ALL;
2346 } else {
2347 fuse_log(FUSE_LOG_ERR,
2348 "%s: Unexpected scope;"
2349 " Expecting 'client', 'server', or 'all', in rule %zu\n",
2350 __func__, lo->xattr_map_nentries);
2351 exit(1);
2354 if (*map++ != sep) {
2355 fuse_log(FUSE_LOG_ERR,
2356 "%s: Expecting '%c' found '%c'"
2357 " after scope in rule %zu\n",
2358 __func__, sep, *map, lo->xattr_map_nentries);
2359 exit(1);
2362 /* At start of 'key' field */
2363 tmp = strchr(map, sep);
2364 if (!tmp) {
2365 fuse_log(FUSE_LOG_ERR,
2366 "%s: Missing '%c' at end of key field of rule %zu",
2367 __func__, sep, lo->xattr_map_nentries);
2368 exit(1);
2370 tmp_entry.key = g_strndup(map, tmp - map);
2371 map = tmp + 1;
2373 /* At start of 'prepend' field */
2374 tmp = strchr(map, sep);
2375 if (!tmp) {
2376 fuse_log(FUSE_LOG_ERR,
2377 "%s: Missing '%c' at end of prepend field of rule %zu",
2378 __func__, sep, lo->xattr_map_nentries);
2379 exit(1);
2381 tmp_entry.prepend = g_strndup(map, tmp - map);
2382 map = tmp + 1;
2384 add_xattrmap_entry(lo, &tmp_entry);
2385 /* End of rule - go around again for another rule */
2388 if (!lo->xattr_map_nentries) {
2389 fuse_log(FUSE_LOG_ERR, "Empty xattr map\n");
2390 exit(1);
2395 * For use with getxattr/setxattr/removexattr, where the client
2396 * gives us a name and we may need to choose a different one.
2397 * Allocates a buffer for the result placing it in *out_name.
2398 * If there's no change then *out_name is not set.
2399 * Returns 0 on success
2400 * Can return -EPERM to indicate we block a given attribute
2401 * (in which case out_name is not allocated)
2402 * Can return -ENOMEM to indicate out_name couldn't be allocated.
2404 static int xattr_map_client(const struct lo_data *lo, const char *client_name,
2405 char **out_name)
2407 size_t i;
2408 for (i = 0; i < lo->xattr_map_nentries; i++) {
2409 const XattrMapEntry *cur_entry = lo->xattr_map_list + i;
2411 if ((cur_entry->flags & XATTR_MAP_FLAG_CLIENT) &&
2412 (strstart(client_name, cur_entry->key, NULL))) {
2413 if (cur_entry->flags & XATTR_MAP_FLAG_BAD) {
2414 return -EPERM;
2416 if (cur_entry->flags & XATTR_MAP_FLAG_OK) {
2417 /* Unmodified name */
2418 return 0;
2420 if (cur_entry->flags & XATTR_MAP_FLAG_PREFIX) {
2421 *out_name = g_try_malloc(strlen(client_name) +
2422 strlen(cur_entry->prepend) + 1);
2423 if (!*out_name) {
2424 return -ENOMEM;
2426 sprintf(*out_name, "%s%s", cur_entry->prepend, client_name);
2427 return 0;
2432 return -EPERM;
2436 * For use with listxattr where the server fs gives us a name and we may need
2437 * to sanitize this for the client.
2438 * Returns a pointer to the result in *out_name
2439 * This is always the original string or the current string with some prefix
2440 * removed; no reallocation is done.
2441 * Returns 0 on success
2442 * Can return -ENODATA to indicate the name should be dropped from the list.
2444 static int xattr_map_server(const struct lo_data *lo, const char *server_name,
2445 const char **out_name)
2447 size_t i;
2448 const char *end;
2450 for (i = 0; i < lo->xattr_map_nentries; i++) {
2451 const XattrMapEntry *cur_entry = lo->xattr_map_list + i;
2453 if ((cur_entry->flags & XATTR_MAP_FLAG_SERVER) &&
2454 (strstart(server_name, cur_entry->prepend, &end))) {
2455 if (cur_entry->flags & XATTR_MAP_FLAG_BAD) {
2456 return -ENODATA;
2458 if (cur_entry->flags & XATTR_MAP_FLAG_OK) {
2459 *out_name = server_name;
2460 return 0;
2462 if (cur_entry->flags & XATTR_MAP_FLAG_PREFIX) {
2463 /* Remove prefix */
2464 *out_name = end;
2465 return 0;
2470 return -ENODATA;
2473 static void lo_getxattr(fuse_req_t req, fuse_ino_t ino, const char *in_name,
2474 size_t size)
2476 struct lo_data *lo = lo_data(req);
2477 char *value = NULL;
2478 char procname[64];
2479 const char *name;
2480 char *mapped_name;
2481 struct lo_inode *inode;
2482 ssize_t ret;
2483 int saverr;
2484 int fd = -1;
2486 mapped_name = NULL;
2487 name = in_name;
2488 if (lo->xattrmap) {
2489 ret = xattr_map_client(lo, in_name, &mapped_name);
2490 if (ret < 0) {
2491 if (ret == -EPERM) {
2492 ret = -ENODATA;
2494 fuse_reply_err(req, -ret);
2495 return;
2497 if (mapped_name) {
2498 name = mapped_name;
2502 inode = lo_inode(req, ino);
2503 if (!inode) {
2504 fuse_reply_err(req, EBADF);
2505 g_free(mapped_name);
2506 return;
2509 saverr = ENOSYS;
2510 if (!lo_data(req)->xattr) {
2511 goto out;
2514 fuse_log(FUSE_LOG_DEBUG, "lo_getxattr(ino=%" PRIu64 ", name=%s size=%zd)\n",
2515 ino, name, size);
2517 if (size) {
2518 value = malloc(size);
2519 if (!value) {
2520 goto out_err;
2524 sprintf(procname, "%i", inode->fd);
2526 * It is not safe to open() non-regular/non-dir files in file server
2527 * unless O_PATH is used, so use that method for regular files/dir
2528 * only (as it seems giving less performance overhead).
2529 * Otherwise, call fchdir() to avoid open().
2531 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2532 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2533 if (fd < 0) {
2534 goto out_err;
2536 ret = fgetxattr(fd, name, value, size);
2537 } else {
2538 /* fchdir should not fail here */
2539 assert(fchdir(lo->proc_self_fd) == 0);
2540 ret = getxattr(procname, name, value, size);
2541 assert(fchdir(lo->root.fd) == 0);
2544 if (ret == -1) {
2545 goto out_err;
2547 if (size) {
2548 saverr = 0;
2549 if (ret == 0) {
2550 goto out;
2552 fuse_reply_buf(req, value, ret);
2553 } else {
2554 fuse_reply_xattr(req, ret);
2556 out_free:
2557 free(value);
2559 if (fd >= 0) {
2560 close(fd);
2563 lo_inode_put(lo, &inode);
2564 return;
2566 out_err:
2567 saverr = errno;
2568 out:
2569 fuse_reply_err(req, saverr);
2570 g_free(mapped_name);
2571 goto out_free;
2574 static void lo_listxattr(fuse_req_t req, fuse_ino_t ino, size_t size)
2576 struct lo_data *lo = lo_data(req);
2577 char *value = NULL;
2578 char procname[64];
2579 struct lo_inode *inode;
2580 ssize_t ret;
2581 int saverr;
2582 int fd = -1;
2584 inode = lo_inode(req, ino);
2585 if (!inode) {
2586 fuse_reply_err(req, EBADF);
2587 return;
2590 saverr = ENOSYS;
2591 if (!lo_data(req)->xattr) {
2592 goto out;
2595 fuse_log(FUSE_LOG_DEBUG, "lo_listxattr(ino=%" PRIu64 ", size=%zd)\n", ino,
2596 size);
2598 if (size) {
2599 value = malloc(size);
2600 if (!value) {
2601 goto out_err;
2605 sprintf(procname, "%i", inode->fd);
2606 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2607 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2608 if (fd < 0) {
2609 goto out_err;
2611 ret = flistxattr(fd, value, size);
2612 } else {
2613 /* fchdir should not fail here */
2614 assert(fchdir(lo->proc_self_fd) == 0);
2615 ret = listxattr(procname, value, size);
2616 assert(fchdir(lo->root.fd) == 0);
2619 if (ret == -1) {
2620 goto out_err;
2622 if (size) {
2623 saverr = 0;
2624 if (ret == 0) {
2625 goto out;
2628 if (lo->xattr_map_list) {
2630 * Map the names back, some attributes might be dropped,
2631 * some shortened, but not increased, so we shouldn't
2632 * run out of room.
2634 size_t out_index, in_index;
2635 out_index = 0;
2636 in_index = 0;
2637 while (in_index < ret) {
2638 const char *map_out;
2639 char *in_ptr = value + in_index;
2640 /* Length of current attribute name */
2641 size_t in_len = strlen(value + in_index) + 1;
2643 int mapret = xattr_map_server(lo, in_ptr, &map_out);
2644 if (mapret != -ENODATA && mapret != 0) {
2645 /* Shouldn't happen */
2646 saverr = -mapret;
2647 goto out;
2649 if (mapret == 0) {
2650 /* Either unchanged, or truncated */
2651 size_t out_len;
2652 if (map_out != in_ptr) {
2653 /* +1 copies the NIL */
2654 out_len = strlen(map_out) + 1;
2655 } else {
2656 /* No change */
2657 out_len = in_len;
2660 * Move result along, may still be needed for an unchanged
2661 * entry if a previous entry was changed.
2663 memmove(value + out_index, map_out, out_len);
2665 out_index += out_len;
2667 in_index += in_len;
2669 ret = out_index;
2670 if (ret == 0) {
2671 goto out;
2674 fuse_reply_buf(req, value, ret);
2675 } else {
2677 * xattrmap only ever shortens the result,
2678 * so we don't need to do anything clever with the
2679 * allocation length here.
2681 fuse_reply_xattr(req, ret);
2683 out_free:
2684 free(value);
2686 if (fd >= 0) {
2687 close(fd);
2690 lo_inode_put(lo, &inode);
2691 return;
2693 out_err:
2694 saverr = errno;
2695 out:
2696 fuse_reply_err(req, saverr);
2697 goto out_free;
2700 static void lo_setxattr(fuse_req_t req, fuse_ino_t ino, const char *in_name,
2701 const char *value, size_t size, int flags)
2703 char procname[64];
2704 const char *name;
2705 char *mapped_name;
2706 struct lo_data *lo = lo_data(req);
2707 struct lo_inode *inode;
2708 ssize_t ret;
2709 int saverr;
2710 int fd = -1;
2712 mapped_name = NULL;
2713 name = in_name;
2714 if (lo->xattrmap) {
2715 ret = xattr_map_client(lo, in_name, &mapped_name);
2716 if (ret < 0) {
2717 fuse_reply_err(req, -ret);
2718 return;
2720 if (mapped_name) {
2721 name = mapped_name;
2725 inode = lo_inode(req, ino);
2726 if (!inode) {
2727 fuse_reply_err(req, EBADF);
2728 g_free(mapped_name);
2729 return;
2732 saverr = ENOSYS;
2733 if (!lo_data(req)->xattr) {
2734 goto out;
2737 fuse_log(FUSE_LOG_DEBUG, "lo_setxattr(ino=%" PRIu64
2738 ", name=%s value=%s size=%zd)\n", ino, name, value, size);
2740 sprintf(procname, "%i", inode->fd);
2741 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2742 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2743 if (fd < 0) {
2744 saverr = errno;
2745 goto out;
2747 ret = fsetxattr(fd, name, value, size, flags);
2748 } else {
2749 /* fchdir should not fail here */
2750 assert(fchdir(lo->proc_self_fd) == 0);
2751 ret = setxattr(procname, name, value, size, flags);
2752 assert(fchdir(lo->root.fd) == 0);
2755 saverr = ret == -1 ? errno : 0;
2757 out:
2758 if (fd >= 0) {
2759 close(fd);
2762 lo_inode_put(lo, &inode);
2763 g_free(mapped_name);
2764 fuse_reply_err(req, saverr);
2767 static void lo_removexattr(fuse_req_t req, fuse_ino_t ino, const char *in_name)
2769 char procname[64];
2770 const char *name;
2771 char *mapped_name;
2772 struct lo_data *lo = lo_data(req);
2773 struct lo_inode *inode;
2774 ssize_t ret;
2775 int saverr;
2776 int fd = -1;
2778 mapped_name = NULL;
2779 name = in_name;
2780 if (lo->xattrmap) {
2781 ret = xattr_map_client(lo, in_name, &mapped_name);
2782 if (ret < 0) {
2783 fuse_reply_err(req, -ret);
2784 return;
2786 if (mapped_name) {
2787 name = mapped_name;
2791 inode = lo_inode(req, ino);
2792 if (!inode) {
2793 fuse_reply_err(req, EBADF);
2794 g_free(mapped_name);
2795 return;
2798 saverr = ENOSYS;
2799 if (!lo_data(req)->xattr) {
2800 goto out;
2803 fuse_log(FUSE_LOG_DEBUG, "lo_removexattr(ino=%" PRIu64 ", name=%s)\n", ino,
2804 name);
2806 sprintf(procname, "%i", inode->fd);
2807 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2808 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2809 if (fd < 0) {
2810 saverr = errno;
2811 goto out;
2813 ret = fremovexattr(fd, name);
2814 } else {
2815 /* fchdir should not fail here */
2816 assert(fchdir(lo->proc_self_fd) == 0);
2817 ret = removexattr(procname, name);
2818 assert(fchdir(lo->root.fd) == 0);
2821 saverr = ret == -1 ? errno : 0;
2823 out:
2824 if (fd >= 0) {
2825 close(fd);
2828 lo_inode_put(lo, &inode);
2829 g_free(mapped_name);
2830 fuse_reply_err(req, saverr);
2833 #ifdef HAVE_COPY_FILE_RANGE
2834 static void lo_copy_file_range(fuse_req_t req, fuse_ino_t ino_in, off_t off_in,
2835 struct fuse_file_info *fi_in, fuse_ino_t ino_out,
2836 off_t off_out, struct fuse_file_info *fi_out,
2837 size_t len, int flags)
2839 int in_fd, out_fd;
2840 ssize_t res;
2842 in_fd = lo_fi_fd(req, fi_in);
2843 out_fd = lo_fi_fd(req, fi_out);
2845 fuse_log(FUSE_LOG_DEBUG,
2846 "lo_copy_file_range(ino=%" PRIu64 "/fd=%d, "
2847 "off=%lu, ino=%" PRIu64 "/fd=%d, "
2848 "off=%lu, size=%zd, flags=0x%x)\n",
2849 ino_in, in_fd, off_in, ino_out, out_fd, off_out, len, flags);
2851 res = copy_file_range(in_fd, &off_in, out_fd, &off_out, len, flags);
2852 if (res < 0) {
2853 fuse_reply_err(req, errno);
2854 } else {
2855 fuse_reply_write(req, res);
2858 #endif
2860 static void lo_lseek(fuse_req_t req, fuse_ino_t ino, off_t off, int whence,
2861 struct fuse_file_info *fi)
2863 off_t res;
2865 (void)ino;
2866 res = lseek(lo_fi_fd(req, fi), off, whence);
2867 if (res != -1) {
2868 fuse_reply_lseek(req, res);
2869 } else {
2870 fuse_reply_err(req, errno);
2874 static void lo_destroy(void *userdata)
2876 struct lo_data *lo = (struct lo_data *)userdata;
2878 pthread_mutex_lock(&lo->mutex);
2879 while (true) {
2880 GHashTableIter iter;
2881 gpointer key, value;
2883 g_hash_table_iter_init(&iter, lo->inodes);
2884 if (!g_hash_table_iter_next(&iter, &key, &value)) {
2885 break;
2888 struct lo_inode *inode = value;
2889 unref_inode(lo, inode, inode->nlookup);
2891 pthread_mutex_unlock(&lo->mutex);
2894 static struct fuse_lowlevel_ops lo_oper = {
2895 .init = lo_init,
2896 .lookup = lo_lookup,
2897 .mkdir = lo_mkdir,
2898 .mknod = lo_mknod,
2899 .symlink = lo_symlink,
2900 .link = lo_link,
2901 .unlink = lo_unlink,
2902 .rmdir = lo_rmdir,
2903 .rename = lo_rename,
2904 .forget = lo_forget,
2905 .forget_multi = lo_forget_multi,
2906 .getattr = lo_getattr,
2907 .setattr = lo_setattr,
2908 .readlink = lo_readlink,
2909 .opendir = lo_opendir,
2910 .readdir = lo_readdir,
2911 .readdirplus = lo_readdirplus,
2912 .releasedir = lo_releasedir,
2913 .fsyncdir = lo_fsyncdir,
2914 .create = lo_create,
2915 .getlk = lo_getlk,
2916 .setlk = lo_setlk,
2917 .open = lo_open,
2918 .release = lo_release,
2919 .flush = lo_flush,
2920 .fsync = lo_fsync,
2921 .read = lo_read,
2922 .write_buf = lo_write_buf,
2923 .statfs = lo_statfs,
2924 .fallocate = lo_fallocate,
2925 .flock = lo_flock,
2926 .getxattr = lo_getxattr,
2927 .listxattr = lo_listxattr,
2928 .setxattr = lo_setxattr,
2929 .removexattr = lo_removexattr,
2930 #ifdef HAVE_COPY_FILE_RANGE
2931 .copy_file_range = lo_copy_file_range,
2932 #endif
2933 .lseek = lo_lseek,
2934 .destroy = lo_destroy,
2937 /* Print vhost-user.json backend program capabilities */
2938 static void print_capabilities(void)
2940 printf("{\n");
2941 printf(" \"type\": \"fs\"\n");
2942 printf("}\n");
2946 * Drop all Linux capabilities because the wait parent process only needs to
2947 * sit in waitpid(2) and terminate.
2949 static void setup_wait_parent_capabilities(void)
2951 capng_setpid(syscall(SYS_gettid));
2952 capng_clear(CAPNG_SELECT_BOTH);
2953 capng_apply(CAPNG_SELECT_BOTH);
2957 * Move to a new mount, net, and pid namespaces to isolate this process.
2959 static void setup_namespaces(struct lo_data *lo, struct fuse_session *se)
2961 pid_t child;
2964 * Create a new pid namespace for *child* processes. We'll have to
2965 * fork in order to enter the new pid namespace. A new mount namespace
2966 * is also needed so that we can remount /proc for the new pid
2967 * namespace.
2969 * Our UNIX domain sockets have been created. Now we can move to
2970 * an empty network namespace to prevent TCP/IP and other network
2971 * activity in case this process is compromised.
2973 if (unshare(CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWNET) != 0) {
2974 fuse_log(FUSE_LOG_ERR, "unshare(CLONE_NEWPID | CLONE_NEWNS): %m\n");
2975 exit(1);
2978 child = fork();
2979 if (child < 0) {
2980 fuse_log(FUSE_LOG_ERR, "fork() failed: %m\n");
2981 exit(1);
2983 if (child > 0) {
2984 pid_t waited;
2985 int wstatus;
2987 setup_wait_parent_capabilities();
2989 /* The parent waits for the child */
2990 do {
2991 waited = waitpid(child, &wstatus, 0);
2992 } while (waited < 0 && errno == EINTR && !se->exited);
2994 /* We were terminated by a signal, see fuse_signals.c */
2995 if (se->exited) {
2996 exit(0);
2999 if (WIFEXITED(wstatus)) {
3000 exit(WEXITSTATUS(wstatus));
3003 exit(1);
3006 /* Send us SIGTERM when the parent thread terminates, see prctl(2) */
3007 prctl(PR_SET_PDEATHSIG, SIGTERM);
3010 * If the mounts have shared propagation then we want to opt out so our
3011 * mount changes don't affect the parent mount namespace.
3013 if (mount(NULL, "/", NULL, MS_REC | MS_SLAVE, NULL) < 0) {
3014 fuse_log(FUSE_LOG_ERR, "mount(/, MS_REC|MS_SLAVE): %m\n");
3015 exit(1);
3018 /* The child must remount /proc to use the new pid namespace */
3019 if (mount("proc", "/proc", "proc",
3020 MS_NODEV | MS_NOEXEC | MS_NOSUID | MS_RELATIME, NULL) < 0) {
3021 fuse_log(FUSE_LOG_ERR, "mount(/proc): %m\n");
3022 exit(1);
3026 * We only need /proc/self/fd. Prevent ".." from accessing parent
3027 * directories of /proc/self/fd by bind-mounting it over /proc. Since / was
3028 * previously remounted with MS_REC | MS_SLAVE this mount change only
3029 * affects our process.
3031 if (mount("/proc/self/fd", "/proc", NULL, MS_BIND, NULL) < 0) {
3032 fuse_log(FUSE_LOG_ERR, "mount(/proc/self/fd, MS_BIND): %m\n");
3033 exit(1);
3036 /* Get the /proc (actually /proc/self/fd, see above) file descriptor */
3037 lo->proc_self_fd = open("/proc", O_PATH);
3038 if (lo->proc_self_fd == -1) {
3039 fuse_log(FUSE_LOG_ERR, "open(/proc, O_PATH): %m\n");
3040 exit(1);
3045 * Capture the capability state, we'll need to restore this for individual
3046 * threads later; see load_capng.
3048 static void setup_capng(void)
3050 /* Note this accesses /proc so has to happen before the sandbox */
3051 if (capng_get_caps_process()) {
3052 fuse_log(FUSE_LOG_ERR, "capng_get_caps_process\n");
3053 exit(1);
3055 pthread_mutex_init(&cap.mutex, NULL);
3056 pthread_mutex_lock(&cap.mutex);
3057 cap.saved = capng_save_state();
3058 if (!cap.saved) {
3059 fuse_log(FUSE_LOG_ERR, "capng_save_state\n");
3060 exit(1);
3062 pthread_mutex_unlock(&cap.mutex);
3065 static void cleanup_capng(void)
3067 free(cap.saved);
3068 cap.saved = NULL;
3069 pthread_mutex_destroy(&cap.mutex);
3074 * Make the source directory our root so symlinks cannot escape and no other
3075 * files are accessible. Assumes unshare(CLONE_NEWNS) was already called.
3077 static void setup_mounts(const char *source)
3079 int oldroot;
3080 int newroot;
3082 if (mount(source, source, NULL, MS_BIND | MS_REC, NULL) < 0) {
3083 fuse_log(FUSE_LOG_ERR, "mount(%s, %s, MS_BIND): %m\n", source, source);
3084 exit(1);
3087 /* This magic is based on lxc's lxc_pivot_root() */
3088 oldroot = open("/", O_DIRECTORY | O_RDONLY | O_CLOEXEC);
3089 if (oldroot < 0) {
3090 fuse_log(FUSE_LOG_ERR, "open(/): %m\n");
3091 exit(1);
3094 newroot = open(source, O_DIRECTORY | O_RDONLY | O_CLOEXEC);
3095 if (newroot < 0) {
3096 fuse_log(FUSE_LOG_ERR, "open(%s): %m\n", source);
3097 exit(1);
3100 if (fchdir(newroot) < 0) {
3101 fuse_log(FUSE_LOG_ERR, "fchdir(newroot): %m\n");
3102 exit(1);
3105 if (syscall(__NR_pivot_root, ".", ".") < 0) {
3106 fuse_log(FUSE_LOG_ERR, "pivot_root(., .): %m\n");
3107 exit(1);
3110 if (fchdir(oldroot) < 0) {
3111 fuse_log(FUSE_LOG_ERR, "fchdir(oldroot): %m\n");
3112 exit(1);
3115 if (mount("", ".", "", MS_SLAVE | MS_REC, NULL) < 0) {
3116 fuse_log(FUSE_LOG_ERR, "mount(., MS_SLAVE | MS_REC): %m\n");
3117 exit(1);
3120 if (umount2(".", MNT_DETACH) < 0) {
3121 fuse_log(FUSE_LOG_ERR, "umount2(., MNT_DETACH): %m\n");
3122 exit(1);
3125 if (fchdir(newroot) < 0) {
3126 fuse_log(FUSE_LOG_ERR, "fchdir(newroot): %m\n");
3127 exit(1);
3130 close(newroot);
3131 close(oldroot);
3135 * Only keep whitelisted capabilities that are needed for file system operation
3136 * The (possibly NULL) modcaps_in string passed in is free'd before exit.
3138 static void setup_capabilities(char *modcaps_in)
3140 char *modcaps = modcaps_in;
3141 pthread_mutex_lock(&cap.mutex);
3142 capng_restore_state(&cap.saved);
3145 * Whitelist file system-related capabilities that are needed for a file
3146 * server to act like root. Drop everything else like networking and
3147 * sysadmin capabilities.
3149 * Exclusions:
3150 * 1. CAP_LINUX_IMMUTABLE is not included because it's only used via ioctl
3151 * and we don't support that.
3152 * 2. CAP_MAC_OVERRIDE is not included because it only seems to be
3153 * used by the Smack LSM. Omit it until there is demand for it.
3155 capng_setpid(syscall(SYS_gettid));
3156 capng_clear(CAPNG_SELECT_BOTH);
3157 if (capng_updatev(CAPNG_ADD, CAPNG_PERMITTED | CAPNG_EFFECTIVE,
3158 CAP_CHOWN,
3159 CAP_DAC_OVERRIDE,
3160 CAP_FOWNER,
3161 CAP_FSETID,
3162 CAP_SETGID,
3163 CAP_SETUID,
3164 CAP_MKNOD,
3165 CAP_SETFCAP,
3166 -1)) {
3167 fuse_log(FUSE_LOG_ERR, "%s: capng_updatev failed\n", __func__);
3168 exit(1);
3172 * The modcaps option is a colon separated list of caps,
3173 * each preceded by either + or -.
3175 while (modcaps) {
3176 capng_act_t action;
3177 int cap;
3179 char *next = strchr(modcaps, ':');
3180 if (next) {
3181 *next = '\0';
3182 next++;
3185 switch (modcaps[0]) {
3186 case '+':
3187 action = CAPNG_ADD;
3188 break;
3190 case '-':
3191 action = CAPNG_DROP;
3192 break;
3194 default:
3195 fuse_log(FUSE_LOG_ERR,
3196 "%s: Expecting '+'/'-' in modcaps but found '%c'\n",
3197 __func__, modcaps[0]);
3198 exit(1);
3200 cap = capng_name_to_capability(modcaps + 1);
3201 if (cap < 0) {
3202 fuse_log(FUSE_LOG_ERR, "%s: Unknown capability '%s'\n", __func__,
3203 modcaps);
3204 exit(1);
3206 if (capng_update(action, CAPNG_PERMITTED | CAPNG_EFFECTIVE, cap)) {
3207 fuse_log(FUSE_LOG_ERR, "%s: capng_update failed for '%s'\n",
3208 __func__, modcaps);
3209 exit(1);
3212 modcaps = next;
3214 g_free(modcaps_in);
3216 if (capng_apply(CAPNG_SELECT_BOTH)) {
3217 fuse_log(FUSE_LOG_ERR, "%s: capng_apply failed\n", __func__);
3218 exit(1);
3221 cap.saved = capng_save_state();
3222 if (!cap.saved) {
3223 fuse_log(FUSE_LOG_ERR, "%s: capng_save_state failed\n", __func__);
3224 exit(1);
3226 pthread_mutex_unlock(&cap.mutex);
3230 * Use chroot as a weaker sandbox for environments where the process is
3231 * launched without CAP_SYS_ADMIN.
3233 static void setup_chroot(struct lo_data *lo)
3235 lo->proc_self_fd = open("/proc/self/fd", O_PATH);
3236 if (lo->proc_self_fd == -1) {
3237 fuse_log(FUSE_LOG_ERR, "open(\"/proc/self/fd\", O_PATH): %m\n");
3238 exit(1);
3242 * Make the shared directory the file system root so that FUSE_OPEN
3243 * (lo_open()) cannot escape the shared directory by opening a symlink.
3245 * The chroot(2) syscall is later disabled by seccomp and the
3246 * CAP_SYS_CHROOT capability is dropped so that tampering with the chroot
3247 * is not possible.
3249 * However, it's still possible to escape the chroot via lo->proc_self_fd
3250 * but that requires first gaining control of the process.
3252 if (chroot(lo->source) != 0) {
3253 fuse_log(FUSE_LOG_ERR, "chroot(\"%s\"): %m\n", lo->source);
3254 exit(1);
3257 /* Move into the chroot */
3258 if (chdir("/") != 0) {
3259 fuse_log(FUSE_LOG_ERR, "chdir(\"/\"): %m\n");
3260 exit(1);
3265 * Lock down this process to prevent access to other processes or files outside
3266 * source directory. This reduces the impact of arbitrary code execution bugs.
3268 static void setup_sandbox(struct lo_data *lo, struct fuse_session *se,
3269 bool enable_syslog)
3271 if (lo->sandbox == SANDBOX_NAMESPACE) {
3272 setup_namespaces(lo, se);
3273 setup_mounts(lo->source);
3274 } else {
3275 setup_chroot(lo);
3278 setup_seccomp(enable_syslog);
3279 setup_capabilities(g_strdup(lo->modcaps));
3282 /* Set the maximum number of open file descriptors */
3283 static void setup_nofile_rlimit(unsigned long rlimit_nofile)
3285 struct rlimit rlim = {
3286 .rlim_cur = rlimit_nofile,
3287 .rlim_max = rlimit_nofile,
3290 if (rlimit_nofile == 0) {
3291 return; /* nothing to do */
3294 if (setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
3295 /* Ignore SELinux denials */
3296 if (errno == EPERM) {
3297 return;
3300 fuse_log(FUSE_LOG_ERR, "setrlimit(RLIMIT_NOFILE): %m\n");
3301 exit(1);
3305 static void log_func(enum fuse_log_level level, const char *fmt, va_list ap)
3307 g_autofree char *localfmt = NULL;
3308 struct timespec ts;
3309 struct tm tm;
3310 char sec_fmt[sizeof "2020-12-07 18:17:54"];
3311 char zone_fmt[sizeof "+0100"];
3313 if (current_log_level < level) {
3314 return;
3317 if (current_log_level == FUSE_LOG_DEBUG) {
3318 if (use_syslog) {
3319 /* no timestamp needed */
3320 localfmt = g_strdup_printf("[ID: %08ld] %s", syscall(__NR_gettid),
3321 fmt);
3322 } else {
3323 /* try formatting a broken-down timestamp */
3324 if (clock_gettime(CLOCK_REALTIME, &ts) != -1 &&
3325 localtime_r(&ts.tv_sec, &tm) != NULL &&
3326 strftime(sec_fmt, sizeof sec_fmt, "%Y-%m-%d %H:%M:%S",
3327 &tm) != 0 &&
3328 strftime(zone_fmt, sizeof zone_fmt, "%z", &tm) != 0) {
3329 localfmt = g_strdup_printf("[%s.%02ld%s] [ID: %08ld] %s",
3330 sec_fmt,
3331 ts.tv_nsec / (10L * 1000 * 1000),
3332 zone_fmt, syscall(__NR_gettid),
3333 fmt);
3334 } else {
3335 /* fall back to a flat timestamp */
3336 localfmt = g_strdup_printf("[%" PRId64 "] [ID: %08ld] %s",
3337 get_clock(), syscall(__NR_gettid),
3338 fmt);
3341 fmt = localfmt;
3344 if (use_syslog) {
3345 int priority = LOG_ERR;
3346 switch (level) {
3347 case FUSE_LOG_EMERG:
3348 priority = LOG_EMERG;
3349 break;
3350 case FUSE_LOG_ALERT:
3351 priority = LOG_ALERT;
3352 break;
3353 case FUSE_LOG_CRIT:
3354 priority = LOG_CRIT;
3355 break;
3356 case FUSE_LOG_ERR:
3357 priority = LOG_ERR;
3358 break;
3359 case FUSE_LOG_WARNING:
3360 priority = LOG_WARNING;
3361 break;
3362 case FUSE_LOG_NOTICE:
3363 priority = LOG_NOTICE;
3364 break;
3365 case FUSE_LOG_INFO:
3366 priority = LOG_INFO;
3367 break;
3368 case FUSE_LOG_DEBUG:
3369 priority = LOG_DEBUG;
3370 break;
3372 vsyslog(priority, fmt, ap);
3373 } else {
3374 vfprintf(stderr, fmt, ap);
3378 static void setup_root(struct lo_data *lo, struct lo_inode *root)
3380 int fd, res;
3381 struct stat stat;
3382 uint64_t mnt_id;
3384 fd = open("/", O_PATH);
3385 if (fd == -1) {
3386 fuse_log(FUSE_LOG_ERR, "open(%s, O_PATH): %m\n", lo->source);
3387 exit(1);
3390 res = do_statx(lo, fd, "", &stat, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW,
3391 &mnt_id);
3392 if (res == -1) {
3393 fuse_log(FUSE_LOG_ERR, "fstatat(%s): %m\n", lo->source);
3394 exit(1);
3397 root->filetype = S_IFDIR;
3398 root->fd = fd;
3399 root->key.ino = stat.st_ino;
3400 root->key.dev = stat.st_dev;
3401 root->key.mnt_id = mnt_id;
3402 root->nlookup = 2;
3403 g_atomic_int_set(&root->refcount, 2);
3404 if (lo->posix_lock) {
3405 pthread_mutex_init(&root->plock_mutex, NULL);
3406 root->posix_locks = g_hash_table_new_full(
3407 g_direct_hash, g_direct_equal, NULL, posix_locks_value_destroy);
3411 static guint lo_key_hash(gconstpointer key)
3413 const struct lo_key *lkey = key;
3415 return (guint)lkey->ino + (guint)lkey->dev + (guint)lkey->mnt_id;
3418 static gboolean lo_key_equal(gconstpointer a, gconstpointer b)
3420 const struct lo_key *la = a;
3421 const struct lo_key *lb = b;
3423 return la->ino == lb->ino && la->dev == lb->dev && la->mnt_id == lb->mnt_id;
3426 static void fuse_lo_data_cleanup(struct lo_data *lo)
3428 if (lo->inodes) {
3429 g_hash_table_destroy(lo->inodes);
3432 if (lo->root.posix_locks) {
3433 g_hash_table_destroy(lo->root.posix_locks);
3435 lo_map_destroy(&lo->fd_map);
3436 lo_map_destroy(&lo->dirp_map);
3437 lo_map_destroy(&lo->ino_map);
3439 if (lo->proc_self_fd >= 0) {
3440 close(lo->proc_self_fd);
3443 if (lo->root.fd >= 0) {
3444 close(lo->root.fd);
3447 free(lo->xattrmap);
3448 free_xattrmap(lo);
3449 free(lo->source);
3452 int main(int argc, char *argv[])
3454 struct fuse_args args = FUSE_ARGS_INIT(argc, argv);
3455 struct fuse_session *se;
3456 struct fuse_cmdline_opts opts;
3457 struct lo_data lo = {
3458 .sandbox = SANDBOX_NAMESPACE,
3459 .debug = 0,
3460 .writeback = 0,
3461 .posix_lock = 0,
3462 .allow_direct_io = 0,
3463 .proc_self_fd = -1,
3465 struct lo_map_elem *root_elem;
3466 struct lo_map_elem *reserve_elem;
3467 int ret = -1;
3469 /* Initialize time conversion information for localtime_r(). */
3470 tzset();
3472 /* Don't mask creation mode, kernel already did that */
3473 umask(0);
3475 qemu_init_exec_dir(argv[0]);
3477 pthread_mutex_init(&lo.mutex, NULL);
3478 lo.inodes = g_hash_table_new(lo_key_hash, lo_key_equal);
3479 lo.root.fd = -1;
3480 lo.root.fuse_ino = FUSE_ROOT_ID;
3481 lo.cache = CACHE_AUTO;
3484 * Set up the ino map like this:
3485 * [0] Reserved (will not be used)
3486 * [1] Root inode
3488 lo_map_init(&lo.ino_map);
3489 reserve_elem = lo_map_reserve(&lo.ino_map, 0);
3490 if (!reserve_elem) {
3491 fuse_log(FUSE_LOG_ERR, "failed to alloc reserve_elem.\n");
3492 goto err_out1;
3494 reserve_elem->in_use = false;
3495 root_elem = lo_map_reserve(&lo.ino_map, lo.root.fuse_ino);
3496 if (!root_elem) {
3497 fuse_log(FUSE_LOG_ERR, "failed to alloc root_elem.\n");
3498 goto err_out1;
3500 root_elem->inode = &lo.root;
3502 lo_map_init(&lo.dirp_map);
3503 lo_map_init(&lo.fd_map);
3505 if (fuse_parse_cmdline(&args, &opts) != 0) {
3506 goto err_out1;
3508 fuse_set_log_func(log_func);
3509 use_syslog = opts.syslog;
3510 if (use_syslog) {
3511 openlog("virtiofsd", LOG_PID, LOG_DAEMON);
3514 if (opts.show_help) {
3515 printf("usage: %s [options]\n\n", argv[0]);
3516 fuse_cmdline_help();
3517 printf(" -o source=PATH shared directory tree\n");
3518 fuse_lowlevel_help();
3519 ret = 0;
3520 goto err_out1;
3521 } else if (opts.show_version) {
3522 fuse_lowlevel_version();
3523 ret = 0;
3524 goto err_out1;
3525 } else if (opts.print_capabilities) {
3526 print_capabilities();
3527 ret = 0;
3528 goto err_out1;
3531 if (fuse_opt_parse(&args, &lo, lo_opts, NULL) == -1) {
3532 goto err_out1;
3535 if (opts.log_level != 0) {
3536 current_log_level = opts.log_level;
3537 } else {
3538 /* default log level is INFO */
3539 current_log_level = FUSE_LOG_INFO;
3541 lo.debug = opts.debug;
3542 if (lo.debug) {
3543 current_log_level = FUSE_LOG_DEBUG;
3545 if (lo.source) {
3546 struct stat stat;
3547 int res;
3549 res = lstat(lo.source, &stat);
3550 if (res == -1) {
3551 fuse_log(FUSE_LOG_ERR, "failed to stat source (\"%s\"): %m\n",
3552 lo.source);
3553 exit(1);
3555 if (!S_ISDIR(stat.st_mode)) {
3556 fuse_log(FUSE_LOG_ERR, "source is not a directory\n");
3557 exit(1);
3559 } else {
3560 lo.source = strdup("/");
3561 if (!lo.source) {
3562 fuse_log(FUSE_LOG_ERR, "failed to strdup source\n");
3563 goto err_out1;
3567 if (lo.xattrmap) {
3568 parse_xattrmap(&lo);
3571 if (!lo.timeout_set) {
3572 switch (lo.cache) {
3573 case CACHE_NONE:
3574 lo.timeout = 0.0;
3575 break;
3577 case CACHE_AUTO:
3578 lo.timeout = 1.0;
3579 break;
3581 case CACHE_ALWAYS:
3582 lo.timeout = 86400.0;
3583 break;
3585 } else if (lo.timeout < 0) {
3586 fuse_log(FUSE_LOG_ERR, "timeout is negative (%lf)\n", lo.timeout);
3587 exit(1);
3590 lo.use_statx = true;
3592 se = fuse_session_new(&args, &lo_oper, sizeof(lo_oper), &lo);
3593 if (se == NULL) {
3594 goto err_out1;
3597 if (fuse_set_signal_handlers(se) != 0) {
3598 goto err_out2;
3601 if (fuse_session_mount(se) != 0) {
3602 goto err_out3;
3605 fuse_daemonize(opts.foreground);
3607 setup_nofile_rlimit(opts.rlimit_nofile);
3609 /* Must be before sandbox since it wants /proc */
3610 setup_capng();
3612 setup_sandbox(&lo, se, opts.syslog);
3614 setup_root(&lo, &lo.root);
3615 /* Block until ctrl+c or fusermount -u */
3616 ret = virtio_loop(se);
3618 fuse_session_unmount(se);
3619 cleanup_capng();
3620 err_out3:
3621 fuse_remove_signal_handlers(se);
3622 err_out2:
3623 fuse_session_destroy(se);
3624 err_out1:
3625 fuse_opt_free_args(&args);
3627 fuse_lo_data_cleanup(&lo);
3629 return ret ? 1 : 0;