Merge remote-tracking branch 'remotes/bonzini-gitlab/tags/for-upstream' into staging
[qemu/ar7.git] / tools / virtiofsd / passthrough_ll.c
blob12de321745304d61495a306001bc7c1e3222a989
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 requests like FUSE_FORGET, FUSE_RMDIR, FUSE_RENAME, etc.
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 pthread_mutex_init(&inode->plock_mutex, NULL);
906 inode->posix_locks = g_hash_table_new_full(
907 g_direct_hash, g_direct_equal, NULL, posix_locks_value_destroy);
909 pthread_mutex_lock(&lo->mutex);
910 inode->fuse_ino = lo_add_inode_mapping(req, inode);
911 g_hash_table_insert(lo->inodes, &inode->key, inode);
912 pthread_mutex_unlock(&lo->mutex);
914 e->ino = inode->fuse_ino;
915 lo_inode_put(lo, &inode);
916 lo_inode_put(lo, &dir);
918 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
919 name, (unsigned long long)e->ino);
921 return 0;
923 out_err:
924 saverr = errno;
925 if (newfd != -1) {
926 close(newfd);
928 lo_inode_put(lo, &inode);
929 lo_inode_put(lo, &dir);
930 return saverr;
933 static void lo_lookup(fuse_req_t req, fuse_ino_t parent, const char *name)
935 struct fuse_entry_param e;
936 int err;
938 fuse_log(FUSE_LOG_DEBUG, "lo_lookup(parent=%" PRIu64 ", name=%s)\n", parent,
939 name);
942 * Don't use is_safe_path_component(), allow "." and ".." for NFS export
943 * support.
945 if (strchr(name, '/')) {
946 fuse_reply_err(req, EINVAL);
947 return;
950 err = lo_do_lookup(req, parent, name, &e);
951 if (err) {
952 fuse_reply_err(req, err);
953 } else {
954 fuse_reply_entry(req, &e);
959 * On some archs, setres*id is limited to 2^16 but they
960 * provide setres*id32 variants that allow 2^32.
961 * Others just let setres*id do 2^32 anyway.
963 #ifdef SYS_setresgid32
964 #define OURSYS_setresgid SYS_setresgid32
965 #else
966 #define OURSYS_setresgid SYS_setresgid
967 #endif
969 #ifdef SYS_setresuid32
970 #define OURSYS_setresuid SYS_setresuid32
971 #else
972 #define OURSYS_setresuid SYS_setresuid
973 #endif
976 * Change to uid/gid of caller so that file is created with
977 * ownership of caller.
978 * TODO: What about selinux context?
980 static int lo_change_cred(fuse_req_t req, struct lo_cred *old)
982 int res;
984 old->euid = geteuid();
985 old->egid = getegid();
987 res = syscall(OURSYS_setresgid, -1, fuse_req_ctx(req)->gid, -1);
988 if (res == -1) {
989 return errno;
992 res = syscall(OURSYS_setresuid, -1, fuse_req_ctx(req)->uid, -1);
993 if (res == -1) {
994 int errno_save = errno;
996 syscall(OURSYS_setresgid, -1, old->egid, -1);
997 return errno_save;
1000 return 0;
1003 /* Regain Privileges */
1004 static void lo_restore_cred(struct lo_cred *old)
1006 int res;
1008 res = syscall(OURSYS_setresuid, -1, old->euid, -1);
1009 if (res == -1) {
1010 fuse_log(FUSE_LOG_ERR, "seteuid(%u): %m\n", old->euid);
1011 exit(1);
1014 res = syscall(OURSYS_setresgid, -1, old->egid, -1);
1015 if (res == -1) {
1016 fuse_log(FUSE_LOG_ERR, "setegid(%u): %m\n", old->egid);
1017 exit(1);
1021 static void lo_mknod_symlink(fuse_req_t req, fuse_ino_t parent,
1022 const char *name, mode_t mode, dev_t rdev,
1023 const char *link)
1025 int res;
1026 int saverr;
1027 struct lo_data *lo = lo_data(req);
1028 struct lo_inode *dir;
1029 struct fuse_entry_param e;
1030 struct lo_cred old = {};
1032 if (!is_safe_path_component(name)) {
1033 fuse_reply_err(req, EINVAL);
1034 return;
1037 dir = lo_inode(req, parent);
1038 if (!dir) {
1039 fuse_reply_err(req, EBADF);
1040 return;
1043 saverr = lo_change_cred(req, &old);
1044 if (saverr) {
1045 goto out;
1048 res = mknod_wrapper(dir->fd, name, link, mode, rdev);
1050 saverr = errno;
1052 lo_restore_cred(&old);
1054 if (res == -1) {
1055 goto out;
1058 saverr = lo_do_lookup(req, parent, name, &e);
1059 if (saverr) {
1060 goto out;
1063 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
1064 name, (unsigned long long)e.ino);
1066 fuse_reply_entry(req, &e);
1067 lo_inode_put(lo, &dir);
1068 return;
1070 out:
1071 lo_inode_put(lo, &dir);
1072 fuse_reply_err(req, saverr);
1075 static void lo_mknod(fuse_req_t req, fuse_ino_t parent, const char *name,
1076 mode_t mode, dev_t rdev)
1078 lo_mknod_symlink(req, parent, name, mode, rdev, NULL);
1081 static void lo_mkdir(fuse_req_t req, fuse_ino_t parent, const char *name,
1082 mode_t mode)
1084 lo_mknod_symlink(req, parent, name, S_IFDIR | mode, 0, NULL);
1087 static void lo_symlink(fuse_req_t req, const char *link, fuse_ino_t parent,
1088 const char *name)
1090 lo_mknod_symlink(req, parent, name, S_IFLNK, 0, link);
1093 static void lo_link(fuse_req_t req, fuse_ino_t ino, fuse_ino_t parent,
1094 const char *name)
1096 int res;
1097 struct lo_data *lo = lo_data(req);
1098 struct lo_inode *parent_inode;
1099 struct lo_inode *inode;
1100 struct fuse_entry_param e;
1101 char procname[64];
1102 int saverr;
1104 if (!is_safe_path_component(name)) {
1105 fuse_reply_err(req, EINVAL);
1106 return;
1109 parent_inode = lo_inode(req, parent);
1110 inode = lo_inode(req, ino);
1111 if (!parent_inode || !inode) {
1112 errno = EBADF;
1113 goto out_err;
1116 memset(&e, 0, sizeof(struct fuse_entry_param));
1117 e.attr_timeout = lo->timeout;
1118 e.entry_timeout = lo->timeout;
1120 sprintf(procname, "%i", inode->fd);
1121 res = linkat(lo->proc_self_fd, procname, parent_inode->fd, name,
1122 AT_SYMLINK_FOLLOW);
1123 if (res == -1) {
1124 goto out_err;
1127 res = fstatat(inode->fd, "", &e.attr, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW);
1128 if (res == -1) {
1129 goto out_err;
1132 pthread_mutex_lock(&lo->mutex);
1133 inode->nlookup++;
1134 pthread_mutex_unlock(&lo->mutex);
1135 e.ino = inode->fuse_ino;
1137 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
1138 name, (unsigned long long)e.ino);
1140 fuse_reply_entry(req, &e);
1141 lo_inode_put(lo, &parent_inode);
1142 lo_inode_put(lo, &inode);
1143 return;
1145 out_err:
1146 saverr = errno;
1147 lo_inode_put(lo, &parent_inode);
1148 lo_inode_put(lo, &inode);
1149 fuse_reply_err(req, saverr);
1152 /* Increments nlookup and caller must release refcount using lo_inode_put() */
1153 static struct lo_inode *lookup_name(fuse_req_t req, fuse_ino_t parent,
1154 const char *name)
1156 int res;
1157 uint64_t mnt_id;
1158 struct stat attr;
1159 struct lo_data *lo = lo_data(req);
1160 struct lo_inode *dir = lo_inode(req, parent);
1162 if (!dir) {
1163 return NULL;
1166 res = do_statx(lo, dir->fd, name, &attr,
1167 AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW, &mnt_id);
1168 lo_inode_put(lo, &dir);
1169 if (res == -1) {
1170 return NULL;
1173 return lo_find(lo, &attr, mnt_id);
1176 static void lo_rmdir(fuse_req_t req, fuse_ino_t parent, const char *name)
1178 int res;
1179 struct lo_inode *inode;
1180 struct lo_data *lo = lo_data(req);
1182 if (!is_safe_path_component(name)) {
1183 fuse_reply_err(req, EINVAL);
1184 return;
1187 inode = lookup_name(req, parent, name);
1188 if (!inode) {
1189 fuse_reply_err(req, EIO);
1190 return;
1193 res = unlinkat(lo_fd(req, parent), name, AT_REMOVEDIR);
1195 fuse_reply_err(req, res == -1 ? errno : 0);
1196 unref_inode_lolocked(lo, inode, 1);
1197 lo_inode_put(lo, &inode);
1200 static void lo_rename(fuse_req_t req, fuse_ino_t parent, const char *name,
1201 fuse_ino_t newparent, const char *newname,
1202 unsigned int flags)
1204 int res;
1205 struct lo_inode *parent_inode;
1206 struct lo_inode *newparent_inode;
1207 struct lo_inode *oldinode = NULL;
1208 struct lo_inode *newinode = NULL;
1209 struct lo_data *lo = lo_data(req);
1211 if (!is_safe_path_component(name) || !is_safe_path_component(newname)) {
1212 fuse_reply_err(req, EINVAL);
1213 return;
1216 parent_inode = lo_inode(req, parent);
1217 newparent_inode = lo_inode(req, newparent);
1218 if (!parent_inode || !newparent_inode) {
1219 fuse_reply_err(req, EBADF);
1220 goto out;
1223 oldinode = lookup_name(req, parent, name);
1224 newinode = lookup_name(req, newparent, newname);
1226 if (!oldinode) {
1227 fuse_reply_err(req, EIO);
1228 goto out;
1231 if (flags) {
1232 #ifndef SYS_renameat2
1233 fuse_reply_err(req, EINVAL);
1234 #else
1235 res = syscall(SYS_renameat2, parent_inode->fd, name,
1236 newparent_inode->fd, newname, flags);
1237 if (res == -1 && errno == ENOSYS) {
1238 fuse_reply_err(req, EINVAL);
1239 } else {
1240 fuse_reply_err(req, res == -1 ? errno : 0);
1242 #endif
1243 goto out;
1246 res = renameat(parent_inode->fd, name, newparent_inode->fd, newname);
1248 fuse_reply_err(req, res == -1 ? errno : 0);
1249 out:
1250 unref_inode_lolocked(lo, oldinode, 1);
1251 unref_inode_lolocked(lo, newinode, 1);
1252 lo_inode_put(lo, &oldinode);
1253 lo_inode_put(lo, &newinode);
1254 lo_inode_put(lo, &parent_inode);
1255 lo_inode_put(lo, &newparent_inode);
1258 static void lo_unlink(fuse_req_t req, fuse_ino_t parent, const char *name)
1260 int res;
1261 struct lo_inode *inode;
1262 struct lo_data *lo = lo_data(req);
1264 if (!is_safe_path_component(name)) {
1265 fuse_reply_err(req, EINVAL);
1266 return;
1269 inode = lookup_name(req, parent, name);
1270 if (!inode) {
1271 fuse_reply_err(req, EIO);
1272 return;
1275 res = unlinkat(lo_fd(req, parent), name, 0);
1277 fuse_reply_err(req, res == -1 ? errno : 0);
1278 unref_inode_lolocked(lo, inode, 1);
1279 lo_inode_put(lo, &inode);
1282 /* To be called with lo->mutex held */
1283 static void unref_inode(struct lo_data *lo, struct lo_inode *inode, uint64_t n)
1285 if (!inode) {
1286 return;
1289 assert(inode->nlookup >= n);
1290 inode->nlookup -= n;
1291 if (!inode->nlookup) {
1292 lo_map_remove(&lo->ino_map, inode->fuse_ino);
1293 g_hash_table_remove(lo->inodes, &inode->key);
1294 if (g_hash_table_size(inode->posix_locks)) {
1295 fuse_log(FUSE_LOG_WARNING, "Hash table is not empty\n");
1297 g_hash_table_destroy(inode->posix_locks);
1298 pthread_mutex_destroy(&inode->plock_mutex);
1300 /* Drop our refcount from lo_do_lookup() */
1301 lo_inode_put(lo, &inode);
1305 static void unref_inode_lolocked(struct lo_data *lo, struct lo_inode *inode,
1306 uint64_t n)
1308 if (!inode) {
1309 return;
1312 pthread_mutex_lock(&lo->mutex);
1313 unref_inode(lo, inode, n);
1314 pthread_mutex_unlock(&lo->mutex);
1317 static void lo_forget_one(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup)
1319 struct lo_data *lo = lo_data(req);
1320 struct lo_inode *inode;
1322 inode = lo_inode(req, ino);
1323 if (!inode) {
1324 return;
1327 fuse_log(FUSE_LOG_DEBUG, " forget %lli %lli -%lli\n",
1328 (unsigned long long)ino, (unsigned long long)inode->nlookup,
1329 (unsigned long long)nlookup);
1331 unref_inode_lolocked(lo, inode, nlookup);
1332 lo_inode_put(lo, &inode);
1335 static void lo_forget(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup)
1337 lo_forget_one(req, ino, nlookup);
1338 fuse_reply_none(req);
1341 static void lo_forget_multi(fuse_req_t req, size_t count,
1342 struct fuse_forget_data *forgets)
1344 int i;
1346 for (i = 0; i < count; i++) {
1347 lo_forget_one(req, forgets[i].ino, forgets[i].nlookup);
1349 fuse_reply_none(req);
1352 static void lo_readlink(fuse_req_t req, fuse_ino_t ino)
1354 char buf[PATH_MAX + 1];
1355 int res;
1357 res = readlinkat(lo_fd(req, ino), "", buf, sizeof(buf));
1358 if (res == -1) {
1359 return (void)fuse_reply_err(req, errno);
1362 if (res == sizeof(buf)) {
1363 return (void)fuse_reply_err(req, ENAMETOOLONG);
1366 buf[res] = '\0';
1368 fuse_reply_readlink(req, buf);
1371 struct lo_dirp {
1372 gint refcount;
1373 DIR *dp;
1374 struct dirent *entry;
1375 off_t offset;
1378 static void lo_dirp_put(struct lo_dirp **dp)
1380 struct lo_dirp *d = *dp;
1382 if (!d) {
1383 return;
1385 *dp = NULL;
1387 if (g_atomic_int_dec_and_test(&d->refcount)) {
1388 closedir(d->dp);
1389 free(d);
1393 /* Call lo_dirp_put() on the return value when no longer needed */
1394 static struct lo_dirp *lo_dirp(fuse_req_t req, struct fuse_file_info *fi)
1396 struct lo_data *lo = lo_data(req);
1397 struct lo_map_elem *elem;
1399 pthread_mutex_lock(&lo->mutex);
1400 elem = lo_map_get(&lo->dirp_map, fi->fh);
1401 if (elem) {
1402 g_atomic_int_inc(&elem->dirp->refcount);
1404 pthread_mutex_unlock(&lo->mutex);
1405 if (!elem) {
1406 return NULL;
1409 return elem->dirp;
1412 static void lo_opendir(fuse_req_t req, fuse_ino_t ino,
1413 struct fuse_file_info *fi)
1415 int error = ENOMEM;
1416 struct lo_data *lo = lo_data(req);
1417 struct lo_dirp *d;
1418 int fd;
1419 ssize_t fh;
1421 d = calloc(1, sizeof(struct lo_dirp));
1422 if (d == NULL) {
1423 goto out_err;
1426 fd = openat(lo_fd(req, ino), ".", O_RDONLY);
1427 if (fd == -1) {
1428 goto out_errno;
1431 d->dp = fdopendir(fd);
1432 if (d->dp == NULL) {
1433 goto out_errno;
1436 d->offset = 0;
1437 d->entry = NULL;
1439 g_atomic_int_set(&d->refcount, 1); /* paired with lo_releasedir() */
1440 pthread_mutex_lock(&lo->mutex);
1441 fh = lo_add_dirp_mapping(req, d);
1442 pthread_mutex_unlock(&lo->mutex);
1443 if (fh == -1) {
1444 goto out_err;
1447 fi->fh = fh;
1448 if (lo->cache == CACHE_ALWAYS) {
1449 fi->cache_readdir = 1;
1451 fuse_reply_open(req, fi);
1452 return;
1454 out_errno:
1455 error = errno;
1456 out_err:
1457 if (d) {
1458 if (d->dp) {
1459 closedir(d->dp);
1460 } else if (fd != -1) {
1461 close(fd);
1463 free(d);
1465 fuse_reply_err(req, error);
1468 static void lo_do_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
1469 off_t offset, struct fuse_file_info *fi, int plus)
1471 struct lo_data *lo = lo_data(req);
1472 struct lo_dirp *d = NULL;
1473 struct lo_inode *dinode;
1474 char *buf = NULL;
1475 char *p;
1476 size_t rem = size;
1477 int err = EBADF;
1479 dinode = lo_inode(req, ino);
1480 if (!dinode) {
1481 goto error;
1484 d = lo_dirp(req, fi);
1485 if (!d) {
1486 goto error;
1489 err = ENOMEM;
1490 buf = calloc(1, size);
1491 if (!buf) {
1492 goto error;
1494 p = buf;
1496 if (offset != d->offset) {
1497 seekdir(d->dp, offset);
1498 d->entry = NULL;
1499 d->offset = offset;
1501 while (1) {
1502 size_t entsize;
1503 off_t nextoff;
1504 const char *name;
1506 if (!d->entry) {
1507 errno = 0;
1508 d->entry = readdir(d->dp);
1509 if (!d->entry) {
1510 if (errno) { /* Error */
1511 err = errno;
1512 goto error;
1513 } else { /* End of stream */
1514 break;
1518 nextoff = d->entry->d_off;
1519 name = d->entry->d_name;
1521 fuse_ino_t entry_ino = 0;
1522 struct fuse_entry_param e = (struct fuse_entry_param){
1523 .attr.st_ino = d->entry->d_ino,
1524 .attr.st_mode = d->entry->d_type << 12,
1527 /* Hide root's parent directory */
1528 if (dinode == &lo->root && strcmp(name, "..") == 0) {
1529 e.attr.st_ino = lo->root.key.ino;
1530 e.attr.st_mode = DT_DIR << 12;
1533 if (plus) {
1534 if (!is_dot_or_dotdot(name)) {
1535 err = lo_do_lookup(req, ino, name, &e);
1536 if (err) {
1537 goto error;
1539 entry_ino = e.ino;
1542 entsize = fuse_add_direntry_plus(req, p, rem, name, &e, nextoff);
1543 } else {
1544 entsize = fuse_add_direntry(req, p, rem, name, &e.attr, nextoff);
1546 if (entsize > rem) {
1547 if (entry_ino != 0) {
1548 lo_forget_one(req, entry_ino, 1);
1550 break;
1553 p += entsize;
1554 rem -= entsize;
1556 d->entry = NULL;
1557 d->offset = nextoff;
1560 err = 0;
1561 error:
1562 lo_dirp_put(&d);
1563 lo_inode_put(lo, &dinode);
1566 * If there's an error, we can only signal it if we haven't stored
1567 * any entries yet - otherwise we'd end up with wrong lookup
1568 * counts for the entries that are already in the buffer. So we
1569 * return what we've collected until that point.
1571 if (err && rem == size) {
1572 fuse_reply_err(req, err);
1573 } else {
1574 fuse_reply_buf(req, buf, size - rem);
1576 free(buf);
1579 static void lo_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
1580 off_t offset, struct fuse_file_info *fi)
1582 lo_do_readdir(req, ino, size, offset, fi, 0);
1585 static void lo_readdirplus(fuse_req_t req, fuse_ino_t ino, size_t size,
1586 off_t offset, struct fuse_file_info *fi)
1588 lo_do_readdir(req, ino, size, offset, fi, 1);
1591 static void lo_releasedir(fuse_req_t req, fuse_ino_t ino,
1592 struct fuse_file_info *fi)
1594 struct lo_data *lo = lo_data(req);
1595 struct lo_map_elem *elem;
1596 struct lo_dirp *d;
1598 (void)ino;
1600 pthread_mutex_lock(&lo->mutex);
1601 elem = lo_map_get(&lo->dirp_map, fi->fh);
1602 if (!elem) {
1603 pthread_mutex_unlock(&lo->mutex);
1604 fuse_reply_err(req, EBADF);
1605 return;
1608 d = elem->dirp;
1609 lo_map_remove(&lo->dirp_map, fi->fh);
1610 pthread_mutex_unlock(&lo->mutex);
1612 lo_dirp_put(&d); /* paired with lo_opendir() */
1614 fuse_reply_err(req, 0);
1617 static void update_open_flags(int writeback, int allow_direct_io,
1618 struct fuse_file_info *fi)
1621 * With writeback cache, kernel may send read requests even
1622 * when userspace opened write-only
1624 if (writeback && (fi->flags & O_ACCMODE) == O_WRONLY) {
1625 fi->flags &= ~O_ACCMODE;
1626 fi->flags |= O_RDWR;
1630 * With writeback cache, O_APPEND is handled by the kernel.
1631 * This breaks atomicity (since the file may change in the
1632 * underlying filesystem, so that the kernel's idea of the
1633 * end of the file isn't accurate anymore). In this example,
1634 * we just accept that. A more rigorous filesystem may want
1635 * to return an error here
1637 if (writeback && (fi->flags & O_APPEND)) {
1638 fi->flags &= ~O_APPEND;
1642 * O_DIRECT in guest should not necessarily mean bypassing page
1643 * cache on host as well. Therefore, we discard it by default
1644 * ('-o no_allow_direct_io'). If somebody needs that behavior,
1645 * the '-o allow_direct_io' option should be set.
1647 if (!allow_direct_io) {
1648 fi->flags &= ~O_DIRECT;
1652 static void lo_create(fuse_req_t req, fuse_ino_t parent, const char *name,
1653 mode_t mode, struct fuse_file_info *fi)
1655 int fd;
1656 struct lo_data *lo = lo_data(req);
1657 struct lo_inode *parent_inode;
1658 struct fuse_entry_param e;
1659 int err;
1660 struct lo_cred old = {};
1662 fuse_log(FUSE_LOG_DEBUG, "lo_create(parent=%" PRIu64 ", name=%s)\n", parent,
1663 name);
1665 if (!is_safe_path_component(name)) {
1666 fuse_reply_err(req, EINVAL);
1667 return;
1670 parent_inode = lo_inode(req, parent);
1671 if (!parent_inode) {
1672 fuse_reply_err(req, EBADF);
1673 return;
1676 err = lo_change_cred(req, &old);
1677 if (err) {
1678 goto out;
1681 update_open_flags(lo->writeback, lo->allow_direct_io, fi);
1683 fd = openat(parent_inode->fd, name, (fi->flags | O_CREAT) & ~O_NOFOLLOW,
1684 mode);
1685 err = fd == -1 ? errno : 0;
1686 lo_restore_cred(&old);
1688 if (!err) {
1689 ssize_t fh;
1691 pthread_mutex_lock(&lo->mutex);
1692 fh = lo_add_fd_mapping(req, fd);
1693 pthread_mutex_unlock(&lo->mutex);
1694 if (fh == -1) {
1695 close(fd);
1696 err = ENOMEM;
1697 goto out;
1700 fi->fh = fh;
1701 err = lo_do_lookup(req, parent, name, &e);
1703 if (lo->cache == CACHE_NONE) {
1704 fi->direct_io = 1;
1705 } else if (lo->cache == CACHE_ALWAYS) {
1706 fi->keep_cache = 1;
1709 out:
1710 lo_inode_put(lo, &parent_inode);
1712 if (err) {
1713 fuse_reply_err(req, err);
1714 } else {
1715 fuse_reply_create(req, &e, fi);
1719 /* Should be called with inode->plock_mutex held */
1720 static struct lo_inode_plock *lookup_create_plock_ctx(struct lo_data *lo,
1721 struct lo_inode *inode,
1722 uint64_t lock_owner,
1723 pid_t pid, int *err)
1725 struct lo_inode_plock *plock;
1726 char procname[64];
1727 int fd;
1729 plock =
1730 g_hash_table_lookup(inode->posix_locks, GUINT_TO_POINTER(lock_owner));
1732 if (plock) {
1733 return plock;
1736 plock = malloc(sizeof(struct lo_inode_plock));
1737 if (!plock) {
1738 *err = ENOMEM;
1739 return NULL;
1742 /* Open another instance of file which can be used for ofd locks. */
1743 sprintf(procname, "%i", inode->fd);
1745 /* TODO: What if file is not writable? */
1746 fd = openat(lo->proc_self_fd, procname, O_RDWR);
1747 if (fd == -1) {
1748 *err = errno;
1749 free(plock);
1750 return NULL;
1753 plock->lock_owner = lock_owner;
1754 plock->fd = fd;
1755 g_hash_table_insert(inode->posix_locks, GUINT_TO_POINTER(plock->lock_owner),
1756 plock);
1757 return plock;
1760 static void lo_getlk(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
1761 struct flock *lock)
1763 struct lo_data *lo = lo_data(req);
1764 struct lo_inode *inode;
1765 struct lo_inode_plock *plock;
1766 int ret, saverr = 0;
1768 fuse_log(FUSE_LOG_DEBUG,
1769 "lo_getlk(ino=%" PRIu64 ", flags=%d)"
1770 " owner=0x%lx, l_type=%d l_start=0x%lx"
1771 " l_len=0x%lx\n",
1772 ino, fi->flags, fi->lock_owner, lock->l_type, lock->l_start,
1773 lock->l_len);
1775 inode = lo_inode(req, ino);
1776 if (!inode) {
1777 fuse_reply_err(req, EBADF);
1778 return;
1781 pthread_mutex_lock(&inode->plock_mutex);
1782 plock =
1783 lookup_create_plock_ctx(lo, inode, fi->lock_owner, lock->l_pid, &ret);
1784 if (!plock) {
1785 saverr = ret;
1786 goto out;
1789 ret = fcntl(plock->fd, F_OFD_GETLK, lock);
1790 if (ret == -1) {
1791 saverr = errno;
1794 out:
1795 pthread_mutex_unlock(&inode->plock_mutex);
1796 lo_inode_put(lo, &inode);
1798 if (saverr) {
1799 fuse_reply_err(req, saverr);
1800 } else {
1801 fuse_reply_lock(req, lock);
1805 static void lo_setlk(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
1806 struct flock *lock, int sleep)
1808 struct lo_data *lo = lo_data(req);
1809 struct lo_inode *inode;
1810 struct lo_inode_plock *plock;
1811 int ret, saverr = 0;
1813 fuse_log(FUSE_LOG_DEBUG,
1814 "lo_setlk(ino=%" PRIu64 ", flags=%d)"
1815 " cmd=%d pid=%d owner=0x%lx sleep=%d l_whence=%d"
1816 " l_start=0x%lx l_len=0x%lx\n",
1817 ino, fi->flags, lock->l_type, lock->l_pid, fi->lock_owner, sleep,
1818 lock->l_whence, lock->l_start, lock->l_len);
1820 if (sleep) {
1821 fuse_reply_err(req, EOPNOTSUPP);
1822 return;
1825 inode = lo_inode(req, ino);
1826 if (!inode) {
1827 fuse_reply_err(req, EBADF);
1828 return;
1831 pthread_mutex_lock(&inode->plock_mutex);
1832 plock =
1833 lookup_create_plock_ctx(lo, inode, fi->lock_owner, lock->l_pid, &ret);
1835 if (!plock) {
1836 saverr = ret;
1837 goto out;
1840 /* TODO: Is it alright to modify flock? */
1841 lock->l_pid = 0;
1842 ret = fcntl(plock->fd, F_OFD_SETLK, lock);
1843 if (ret == -1) {
1844 saverr = errno;
1847 out:
1848 pthread_mutex_unlock(&inode->plock_mutex);
1849 lo_inode_put(lo, &inode);
1851 fuse_reply_err(req, saverr);
1854 static void lo_fsyncdir(fuse_req_t req, fuse_ino_t ino, int datasync,
1855 struct fuse_file_info *fi)
1857 int res;
1858 struct lo_dirp *d;
1859 int fd;
1861 (void)ino;
1863 d = lo_dirp(req, fi);
1864 if (!d) {
1865 fuse_reply_err(req, EBADF);
1866 return;
1869 fd = dirfd(d->dp);
1870 if (datasync) {
1871 res = fdatasync(fd);
1872 } else {
1873 res = fsync(fd);
1876 lo_dirp_put(&d);
1878 fuse_reply_err(req, res == -1 ? errno : 0);
1881 static void lo_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi)
1883 int fd;
1884 ssize_t fh;
1885 char buf[64];
1886 struct lo_data *lo = lo_data(req);
1888 fuse_log(FUSE_LOG_DEBUG, "lo_open(ino=%" PRIu64 ", flags=%d)\n", ino,
1889 fi->flags);
1891 update_open_flags(lo->writeback, lo->allow_direct_io, fi);
1893 sprintf(buf, "%i", lo_fd(req, ino));
1894 fd = openat(lo->proc_self_fd, buf, fi->flags & ~O_NOFOLLOW);
1895 if (fd == -1) {
1896 return (void)fuse_reply_err(req, errno);
1899 pthread_mutex_lock(&lo->mutex);
1900 fh = lo_add_fd_mapping(req, fd);
1901 pthread_mutex_unlock(&lo->mutex);
1902 if (fh == -1) {
1903 close(fd);
1904 fuse_reply_err(req, ENOMEM);
1905 return;
1908 fi->fh = fh;
1909 if (lo->cache == CACHE_NONE) {
1910 fi->direct_io = 1;
1911 } else if (lo->cache == CACHE_ALWAYS) {
1912 fi->keep_cache = 1;
1914 fuse_reply_open(req, fi);
1917 static void lo_release(fuse_req_t req, fuse_ino_t ino,
1918 struct fuse_file_info *fi)
1920 struct lo_data *lo = lo_data(req);
1921 struct lo_map_elem *elem;
1922 int fd = -1;
1924 (void)ino;
1926 pthread_mutex_lock(&lo->mutex);
1927 elem = lo_map_get(&lo->fd_map, fi->fh);
1928 if (elem) {
1929 fd = elem->fd;
1930 elem = NULL;
1931 lo_map_remove(&lo->fd_map, fi->fh);
1933 pthread_mutex_unlock(&lo->mutex);
1935 close(fd);
1936 fuse_reply_err(req, 0);
1939 static void lo_flush(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi)
1941 int res;
1942 (void)ino;
1943 struct lo_inode *inode;
1945 inode = lo_inode(req, ino);
1946 if (!inode) {
1947 fuse_reply_err(req, EBADF);
1948 return;
1951 /* An fd is going away. Cleanup associated posix locks */
1952 pthread_mutex_lock(&inode->plock_mutex);
1953 g_hash_table_remove(inode->posix_locks, GUINT_TO_POINTER(fi->lock_owner));
1954 pthread_mutex_unlock(&inode->plock_mutex);
1956 res = close(dup(lo_fi_fd(req, fi)));
1957 lo_inode_put(lo_data(req), &inode);
1958 fuse_reply_err(req, res == -1 ? errno : 0);
1961 static void lo_fsync(fuse_req_t req, fuse_ino_t ino, int datasync,
1962 struct fuse_file_info *fi)
1964 int res;
1965 int fd;
1966 char *buf;
1968 fuse_log(FUSE_LOG_DEBUG, "lo_fsync(ino=%" PRIu64 ", fi=0x%p)\n", ino,
1969 (void *)fi);
1971 if (!fi) {
1972 struct lo_data *lo = lo_data(req);
1974 res = asprintf(&buf, "%i", lo_fd(req, ino));
1975 if (res == -1) {
1976 return (void)fuse_reply_err(req, errno);
1979 fd = openat(lo->proc_self_fd, buf, O_RDWR);
1980 free(buf);
1981 if (fd == -1) {
1982 return (void)fuse_reply_err(req, errno);
1984 } else {
1985 fd = lo_fi_fd(req, fi);
1988 if (datasync) {
1989 res = fdatasync(fd);
1990 } else {
1991 res = fsync(fd);
1993 if (!fi) {
1994 close(fd);
1996 fuse_reply_err(req, res == -1 ? errno : 0);
1999 static void lo_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t offset,
2000 struct fuse_file_info *fi)
2002 struct fuse_bufvec buf = FUSE_BUFVEC_INIT(size);
2004 fuse_log(FUSE_LOG_DEBUG,
2005 "lo_read(ino=%" PRIu64 ", size=%zd, "
2006 "off=%lu)\n",
2007 ino, size, (unsigned long)offset);
2009 buf.buf[0].flags = FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK;
2010 buf.buf[0].fd = lo_fi_fd(req, fi);
2011 buf.buf[0].pos = offset;
2013 fuse_reply_data(req, &buf);
2016 static void lo_write_buf(fuse_req_t req, fuse_ino_t ino,
2017 struct fuse_bufvec *in_buf, off_t off,
2018 struct fuse_file_info *fi)
2020 (void)ino;
2021 ssize_t res;
2022 struct fuse_bufvec out_buf = FUSE_BUFVEC_INIT(fuse_buf_size(in_buf));
2023 bool cap_fsetid_dropped = false;
2025 out_buf.buf[0].flags = FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK;
2026 out_buf.buf[0].fd = lo_fi_fd(req, fi);
2027 out_buf.buf[0].pos = off;
2029 fuse_log(FUSE_LOG_DEBUG,
2030 "lo_write_buf(ino=%" PRIu64 ", size=%zd, off=%lu)\n", ino,
2031 out_buf.buf[0].size, (unsigned long)off);
2034 * If kill_priv is set, drop CAP_FSETID which should lead to kernel
2035 * clearing setuid/setgid on file.
2037 if (fi->kill_priv) {
2038 res = drop_effective_cap("FSETID", &cap_fsetid_dropped);
2039 if (res != 0) {
2040 fuse_reply_err(req, res);
2041 return;
2045 res = fuse_buf_copy(&out_buf, in_buf);
2046 if (res < 0) {
2047 fuse_reply_err(req, -res);
2048 } else {
2049 fuse_reply_write(req, (size_t)res);
2052 if (cap_fsetid_dropped) {
2053 res = gain_effective_cap("FSETID");
2054 if (res) {
2055 fuse_log(FUSE_LOG_ERR, "Failed to gain CAP_FSETID\n");
2060 static void lo_statfs(fuse_req_t req, fuse_ino_t ino)
2062 int res;
2063 struct statvfs stbuf;
2065 res = fstatvfs(lo_fd(req, ino), &stbuf);
2066 if (res == -1) {
2067 fuse_reply_err(req, errno);
2068 } else {
2069 fuse_reply_statfs(req, &stbuf);
2073 static void lo_fallocate(fuse_req_t req, fuse_ino_t ino, int mode, off_t offset,
2074 off_t length, struct fuse_file_info *fi)
2076 int err = EOPNOTSUPP;
2077 (void)ino;
2079 #ifdef CONFIG_FALLOCATE
2080 err = fallocate(lo_fi_fd(req, fi), mode, offset, length);
2081 if (err < 0) {
2082 err = errno;
2085 #elif defined(CONFIG_POSIX_FALLOCATE)
2086 if (mode) {
2087 fuse_reply_err(req, EOPNOTSUPP);
2088 return;
2091 err = posix_fallocate(lo_fi_fd(req, fi), offset, length);
2092 #endif
2094 fuse_reply_err(req, err);
2097 static void lo_flock(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
2098 int op)
2100 int res;
2101 (void)ino;
2103 res = flock(lo_fi_fd(req, fi), op);
2105 fuse_reply_err(req, res == -1 ? errno : 0);
2108 /* types */
2110 * Exit; process attribute unmodified if matched.
2111 * An empty key applies to all.
2113 #define XATTR_MAP_FLAG_OK (1 << 0)
2115 * The attribute is unwanted;
2116 * EPERM on write, hidden on read.
2118 #define XATTR_MAP_FLAG_BAD (1 << 1)
2120 * For attr that start with 'key' prepend 'prepend'
2121 * 'key' may be empty to prepend for all attrs
2122 * key is defined from set/remove point of view.
2123 * Automatically reversed on read
2125 #define XATTR_MAP_FLAG_PREFIX (1 << 2)
2127 /* scopes */
2128 /* Apply rule to get/set/remove */
2129 #define XATTR_MAP_FLAG_CLIENT (1 << 16)
2130 /* Apply rule to list */
2131 #define XATTR_MAP_FLAG_SERVER (1 << 17)
2132 /* Apply rule to all */
2133 #define XATTR_MAP_FLAG_ALL (XATTR_MAP_FLAG_SERVER | XATTR_MAP_FLAG_CLIENT)
2135 static void add_xattrmap_entry(struct lo_data *lo,
2136 const XattrMapEntry *new_entry)
2138 XattrMapEntry *res = g_realloc_n(lo->xattr_map_list,
2139 lo->xattr_map_nentries + 1,
2140 sizeof(XattrMapEntry));
2141 res[lo->xattr_map_nentries++] = *new_entry;
2143 lo->xattr_map_list = res;
2146 static void free_xattrmap(struct lo_data *lo)
2148 XattrMapEntry *map = lo->xattr_map_list;
2149 size_t i;
2151 if (!map) {
2152 return;
2155 for (i = 0; i < lo->xattr_map_nentries; i++) {
2156 g_free(map[i].key);
2157 g_free(map[i].prepend);
2160 g_free(map);
2161 lo->xattr_map_list = NULL;
2162 lo->xattr_map_nentries = -1;
2166 * Handle the 'map' type, which is sugar for a set of commands
2167 * for the common case of prefixing a subset or everything,
2168 * and allowing anything not prefixed through.
2169 * It must be the last entry in the stream, although there
2170 * can be other entries before it.
2171 * The form is:
2172 * :map:key:prefix:
2174 * key maybe empty in which case all entries are prefixed.
2176 static void parse_xattrmap_map(struct lo_data *lo,
2177 const char *rule, char sep)
2179 const char *tmp;
2180 char *key;
2181 char *prefix;
2182 XattrMapEntry tmp_entry;
2184 if (*rule != sep) {
2185 fuse_log(FUSE_LOG_ERR,
2186 "%s: Expecting '%c' after 'map' keyword, found '%c'\n",
2187 __func__, sep, *rule);
2188 exit(1);
2191 rule++;
2193 /* At start of 'key' field */
2194 tmp = strchr(rule, sep);
2195 if (!tmp) {
2196 fuse_log(FUSE_LOG_ERR,
2197 "%s: Missing '%c' at end of key field in map rule\n",
2198 __func__, sep);
2199 exit(1);
2202 key = g_strndup(rule, tmp - rule);
2203 rule = tmp + 1;
2205 /* At start of prefix field */
2206 tmp = strchr(rule, sep);
2207 if (!tmp) {
2208 fuse_log(FUSE_LOG_ERR,
2209 "%s: Missing '%c' at end of prefix field in map rule\n",
2210 __func__, sep);
2211 exit(1);
2214 prefix = g_strndup(rule, tmp - rule);
2215 rule = tmp + 1;
2218 * This should be the end of the string, we don't allow
2219 * any more commands after 'map'.
2221 if (*rule) {
2222 fuse_log(FUSE_LOG_ERR,
2223 "%s: Expecting end of command after map, found '%c'\n",
2224 __func__, *rule);
2225 exit(1);
2228 /* 1st: Prefix matches/everything */
2229 tmp_entry.flags = XATTR_MAP_FLAG_PREFIX | XATTR_MAP_FLAG_ALL;
2230 tmp_entry.key = g_strdup(key);
2231 tmp_entry.prepend = g_strdup(prefix);
2232 add_xattrmap_entry(lo, &tmp_entry);
2234 if (!*key) {
2235 /* Prefix all case */
2237 /* 2nd: Hide any non-prefixed entries on the host */
2238 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_ALL;
2239 tmp_entry.key = g_strdup("");
2240 tmp_entry.prepend = g_strdup("");
2241 add_xattrmap_entry(lo, &tmp_entry);
2242 } else {
2243 /* Prefix matching case */
2245 /* 2nd: Hide non-prefixed but matching entries on the host */
2246 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_SERVER;
2247 tmp_entry.key = g_strdup(""); /* Not used */
2248 tmp_entry.prepend = g_strdup(key);
2249 add_xattrmap_entry(lo, &tmp_entry);
2251 /* 3rd: Stop the client accessing prefixed attributes directly */
2252 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_CLIENT;
2253 tmp_entry.key = g_strdup(prefix);
2254 tmp_entry.prepend = g_strdup(""); /* Not used */
2255 add_xattrmap_entry(lo, &tmp_entry);
2257 /* 4th: Everything else is OK */
2258 tmp_entry.flags = XATTR_MAP_FLAG_OK | XATTR_MAP_FLAG_ALL;
2259 tmp_entry.key = g_strdup("");
2260 tmp_entry.prepend = g_strdup("");
2261 add_xattrmap_entry(lo, &tmp_entry);
2264 g_free(key);
2265 g_free(prefix);
2268 static void parse_xattrmap(struct lo_data *lo)
2270 const char *map = lo->xattrmap;
2271 const char *tmp;
2273 lo->xattr_map_nentries = 0;
2274 while (*map) {
2275 XattrMapEntry tmp_entry;
2276 char sep;
2278 if (isspace(*map)) {
2279 map++;
2280 continue;
2282 /* The separator is the first non-space of the rule */
2283 sep = *map++;
2284 if (!sep) {
2285 break;
2288 tmp_entry.flags = 0;
2289 /* Start of 'type' */
2290 if (strstart(map, "prefix", &map)) {
2291 tmp_entry.flags |= XATTR_MAP_FLAG_PREFIX;
2292 } else if (strstart(map, "ok", &map)) {
2293 tmp_entry.flags |= XATTR_MAP_FLAG_OK;
2294 } else if (strstart(map, "bad", &map)) {
2295 tmp_entry.flags |= XATTR_MAP_FLAG_BAD;
2296 } else if (strstart(map, "map", &map)) {
2298 * map is sugar that adds a number of rules, and must be
2299 * the last entry.
2301 parse_xattrmap_map(lo, map, sep);
2302 return;
2303 } else {
2304 fuse_log(FUSE_LOG_ERR,
2305 "%s: Unexpected type;"
2306 "Expecting 'prefix', 'ok', 'bad' or 'map' in rule %zu\n",
2307 __func__, lo->xattr_map_nentries);
2308 exit(1);
2311 if (*map++ != sep) {
2312 fuse_log(FUSE_LOG_ERR,
2313 "%s: Missing '%c' at end of type field of rule %zu\n",
2314 __func__, sep, lo->xattr_map_nentries);
2315 exit(1);
2318 /* Start of 'scope' */
2319 if (strstart(map, "client", &map)) {
2320 tmp_entry.flags |= XATTR_MAP_FLAG_CLIENT;
2321 } else if (strstart(map, "server", &map)) {
2322 tmp_entry.flags |= XATTR_MAP_FLAG_SERVER;
2323 } else if (strstart(map, "all", &map)) {
2324 tmp_entry.flags |= XATTR_MAP_FLAG_ALL;
2325 } else {
2326 fuse_log(FUSE_LOG_ERR,
2327 "%s: Unexpected scope;"
2328 " Expecting 'client', 'server', or 'all', in rule %zu\n",
2329 __func__, lo->xattr_map_nentries);
2330 exit(1);
2333 if (*map++ != sep) {
2334 fuse_log(FUSE_LOG_ERR,
2335 "%s: Expecting '%c' found '%c'"
2336 " after scope in rule %zu\n",
2337 __func__, sep, *map, lo->xattr_map_nentries);
2338 exit(1);
2341 /* At start of 'key' field */
2342 tmp = strchr(map, sep);
2343 if (!tmp) {
2344 fuse_log(FUSE_LOG_ERR,
2345 "%s: Missing '%c' at end of key field of rule %zu",
2346 __func__, sep, lo->xattr_map_nentries);
2347 exit(1);
2349 tmp_entry.key = g_strndup(map, tmp - map);
2350 map = tmp + 1;
2352 /* At start of 'prepend' field */
2353 tmp = strchr(map, sep);
2354 if (!tmp) {
2355 fuse_log(FUSE_LOG_ERR,
2356 "%s: Missing '%c' at end of prepend field of rule %zu",
2357 __func__, sep, lo->xattr_map_nentries);
2358 exit(1);
2360 tmp_entry.prepend = g_strndup(map, tmp - map);
2361 map = tmp + 1;
2363 add_xattrmap_entry(lo, &tmp_entry);
2364 /* End of rule - go around again for another rule */
2367 if (!lo->xattr_map_nentries) {
2368 fuse_log(FUSE_LOG_ERR, "Empty xattr map\n");
2369 exit(1);
2374 * For use with getxattr/setxattr/removexattr, where the client
2375 * gives us a name and we may need to choose a different one.
2376 * Allocates a buffer for the result placing it in *out_name.
2377 * If there's no change then *out_name is not set.
2378 * Returns 0 on success
2379 * Can return -EPERM to indicate we block a given attribute
2380 * (in which case out_name is not allocated)
2381 * Can return -ENOMEM to indicate out_name couldn't be allocated.
2383 static int xattr_map_client(const struct lo_data *lo, const char *client_name,
2384 char **out_name)
2386 size_t i;
2387 for (i = 0; i < lo->xattr_map_nentries; i++) {
2388 const XattrMapEntry *cur_entry = lo->xattr_map_list + i;
2390 if ((cur_entry->flags & XATTR_MAP_FLAG_CLIENT) &&
2391 (strstart(client_name, cur_entry->key, NULL))) {
2392 if (cur_entry->flags & XATTR_MAP_FLAG_BAD) {
2393 return -EPERM;
2395 if (cur_entry->flags & XATTR_MAP_FLAG_OK) {
2396 /* Unmodified name */
2397 return 0;
2399 if (cur_entry->flags & XATTR_MAP_FLAG_PREFIX) {
2400 *out_name = g_try_malloc(strlen(client_name) +
2401 strlen(cur_entry->prepend) + 1);
2402 if (!*out_name) {
2403 return -ENOMEM;
2405 sprintf(*out_name, "%s%s", cur_entry->prepend, client_name);
2406 return 0;
2411 return -EPERM;
2415 * For use with listxattr where the server fs gives us a name and we may need
2416 * to sanitize this for the client.
2417 * Returns a pointer to the result in *out_name
2418 * This is always the original string or the current string with some prefix
2419 * removed; no reallocation is done.
2420 * Returns 0 on success
2421 * Can return -ENODATA to indicate the name should be dropped from the list.
2423 static int xattr_map_server(const struct lo_data *lo, const char *server_name,
2424 const char **out_name)
2426 size_t i;
2427 const char *end;
2429 for (i = 0; i < lo->xattr_map_nentries; i++) {
2430 const XattrMapEntry *cur_entry = lo->xattr_map_list + i;
2432 if ((cur_entry->flags & XATTR_MAP_FLAG_SERVER) &&
2433 (strstart(server_name, cur_entry->prepend, &end))) {
2434 if (cur_entry->flags & XATTR_MAP_FLAG_BAD) {
2435 return -ENODATA;
2437 if (cur_entry->flags & XATTR_MAP_FLAG_OK) {
2438 *out_name = server_name;
2439 return 0;
2441 if (cur_entry->flags & XATTR_MAP_FLAG_PREFIX) {
2442 /* Remove prefix */
2443 *out_name = end;
2444 return 0;
2449 return -ENODATA;
2452 static void lo_getxattr(fuse_req_t req, fuse_ino_t ino, const char *in_name,
2453 size_t size)
2455 struct lo_data *lo = lo_data(req);
2456 char *value = NULL;
2457 char procname[64];
2458 const char *name;
2459 char *mapped_name;
2460 struct lo_inode *inode;
2461 ssize_t ret;
2462 int saverr;
2463 int fd = -1;
2465 mapped_name = NULL;
2466 name = in_name;
2467 if (lo->xattrmap) {
2468 ret = xattr_map_client(lo, in_name, &mapped_name);
2469 if (ret < 0) {
2470 if (ret == -EPERM) {
2471 ret = -ENODATA;
2473 fuse_reply_err(req, -ret);
2474 return;
2476 if (mapped_name) {
2477 name = mapped_name;
2481 inode = lo_inode(req, ino);
2482 if (!inode) {
2483 fuse_reply_err(req, EBADF);
2484 g_free(mapped_name);
2485 return;
2488 saverr = ENOSYS;
2489 if (!lo_data(req)->xattr) {
2490 goto out;
2493 fuse_log(FUSE_LOG_DEBUG, "lo_getxattr(ino=%" PRIu64 ", name=%s size=%zd)\n",
2494 ino, name, size);
2496 if (size) {
2497 value = malloc(size);
2498 if (!value) {
2499 goto out_err;
2503 sprintf(procname, "%i", inode->fd);
2505 * It is not safe to open() non-regular/non-dir files in file server
2506 * unless O_PATH is used, so use that method for regular files/dir
2507 * only (as it seems giving less performance overhead).
2508 * Otherwise, call fchdir() to avoid open().
2510 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2511 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2512 if (fd < 0) {
2513 goto out_err;
2515 ret = fgetxattr(fd, name, value, size);
2516 } else {
2517 /* fchdir should not fail here */
2518 assert(fchdir(lo->proc_self_fd) == 0);
2519 ret = getxattr(procname, name, value, size);
2520 assert(fchdir(lo->root.fd) == 0);
2523 if (ret == -1) {
2524 goto out_err;
2526 if (size) {
2527 saverr = 0;
2528 if (ret == 0) {
2529 goto out;
2531 fuse_reply_buf(req, value, ret);
2532 } else {
2533 fuse_reply_xattr(req, ret);
2535 out_free:
2536 free(value);
2538 if (fd >= 0) {
2539 close(fd);
2542 lo_inode_put(lo, &inode);
2543 return;
2545 out_err:
2546 saverr = errno;
2547 out:
2548 fuse_reply_err(req, saverr);
2549 g_free(mapped_name);
2550 goto out_free;
2553 static void lo_listxattr(fuse_req_t req, fuse_ino_t ino, size_t size)
2555 struct lo_data *lo = lo_data(req);
2556 char *value = NULL;
2557 char procname[64];
2558 struct lo_inode *inode;
2559 ssize_t ret;
2560 int saverr;
2561 int fd = -1;
2563 inode = lo_inode(req, ino);
2564 if (!inode) {
2565 fuse_reply_err(req, EBADF);
2566 return;
2569 saverr = ENOSYS;
2570 if (!lo_data(req)->xattr) {
2571 goto out;
2574 fuse_log(FUSE_LOG_DEBUG, "lo_listxattr(ino=%" PRIu64 ", size=%zd)\n", ino,
2575 size);
2577 if (size) {
2578 value = malloc(size);
2579 if (!value) {
2580 goto out_err;
2584 sprintf(procname, "%i", inode->fd);
2585 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2586 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2587 if (fd < 0) {
2588 goto out_err;
2590 ret = flistxattr(fd, value, size);
2591 } else {
2592 /* fchdir should not fail here */
2593 assert(fchdir(lo->proc_self_fd) == 0);
2594 ret = listxattr(procname, value, size);
2595 assert(fchdir(lo->root.fd) == 0);
2598 if (ret == -1) {
2599 goto out_err;
2601 if (size) {
2602 saverr = 0;
2603 if (ret == 0) {
2604 goto out;
2607 if (lo->xattr_map_list) {
2609 * Map the names back, some attributes might be dropped,
2610 * some shortened, but not increased, so we shouldn't
2611 * run out of room.
2613 size_t out_index, in_index;
2614 out_index = 0;
2615 in_index = 0;
2616 while (in_index < ret) {
2617 const char *map_out;
2618 char *in_ptr = value + in_index;
2619 /* Length of current attribute name */
2620 size_t in_len = strlen(value + in_index) + 1;
2622 int mapret = xattr_map_server(lo, in_ptr, &map_out);
2623 if (mapret != -ENODATA && mapret != 0) {
2624 /* Shouldn't happen */
2625 saverr = -mapret;
2626 goto out;
2628 if (mapret == 0) {
2629 /* Either unchanged, or truncated */
2630 size_t out_len;
2631 if (map_out != in_ptr) {
2632 /* +1 copies the NIL */
2633 out_len = strlen(map_out) + 1;
2634 } else {
2635 /* No change */
2636 out_len = in_len;
2639 * Move result along, may still be needed for an unchanged
2640 * entry if a previous entry was changed.
2642 memmove(value + out_index, map_out, out_len);
2644 out_index += out_len;
2646 in_index += in_len;
2648 ret = out_index;
2649 if (ret == 0) {
2650 goto out;
2653 fuse_reply_buf(req, value, ret);
2654 } else {
2656 * xattrmap only ever shortens the result,
2657 * so we don't need to do anything clever with the
2658 * allocation length here.
2660 fuse_reply_xattr(req, ret);
2662 out_free:
2663 free(value);
2665 if (fd >= 0) {
2666 close(fd);
2669 lo_inode_put(lo, &inode);
2670 return;
2672 out_err:
2673 saverr = errno;
2674 out:
2675 fuse_reply_err(req, saverr);
2676 goto out_free;
2679 static void lo_setxattr(fuse_req_t req, fuse_ino_t ino, const char *in_name,
2680 const char *value, size_t size, int flags)
2682 char procname[64];
2683 const char *name;
2684 char *mapped_name;
2685 struct lo_data *lo = lo_data(req);
2686 struct lo_inode *inode;
2687 ssize_t ret;
2688 int saverr;
2689 int fd = -1;
2691 mapped_name = NULL;
2692 name = in_name;
2693 if (lo->xattrmap) {
2694 ret = xattr_map_client(lo, in_name, &mapped_name);
2695 if (ret < 0) {
2696 fuse_reply_err(req, -ret);
2697 return;
2699 if (mapped_name) {
2700 name = mapped_name;
2704 inode = lo_inode(req, ino);
2705 if (!inode) {
2706 fuse_reply_err(req, EBADF);
2707 g_free(mapped_name);
2708 return;
2711 saverr = ENOSYS;
2712 if (!lo_data(req)->xattr) {
2713 goto out;
2716 fuse_log(FUSE_LOG_DEBUG, "lo_setxattr(ino=%" PRIu64
2717 ", name=%s value=%s size=%zd)\n", ino, name, value, size);
2719 sprintf(procname, "%i", inode->fd);
2720 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2721 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2722 if (fd < 0) {
2723 saverr = errno;
2724 goto out;
2726 ret = fsetxattr(fd, name, value, size, flags);
2727 } else {
2728 /* fchdir should not fail here */
2729 assert(fchdir(lo->proc_self_fd) == 0);
2730 ret = setxattr(procname, name, value, size, flags);
2731 assert(fchdir(lo->root.fd) == 0);
2734 saverr = ret == -1 ? errno : 0;
2736 out:
2737 if (fd >= 0) {
2738 close(fd);
2741 lo_inode_put(lo, &inode);
2742 g_free(mapped_name);
2743 fuse_reply_err(req, saverr);
2746 static void lo_removexattr(fuse_req_t req, fuse_ino_t ino, const char *in_name)
2748 char procname[64];
2749 const char *name;
2750 char *mapped_name;
2751 struct lo_data *lo = lo_data(req);
2752 struct lo_inode *inode;
2753 ssize_t ret;
2754 int saverr;
2755 int fd = -1;
2757 mapped_name = NULL;
2758 name = in_name;
2759 if (lo->xattrmap) {
2760 ret = xattr_map_client(lo, in_name, &mapped_name);
2761 if (ret < 0) {
2762 fuse_reply_err(req, -ret);
2763 return;
2765 if (mapped_name) {
2766 name = mapped_name;
2770 inode = lo_inode(req, ino);
2771 if (!inode) {
2772 fuse_reply_err(req, EBADF);
2773 g_free(mapped_name);
2774 return;
2777 saverr = ENOSYS;
2778 if (!lo_data(req)->xattr) {
2779 goto out;
2782 fuse_log(FUSE_LOG_DEBUG, "lo_removexattr(ino=%" PRIu64 ", name=%s)\n", ino,
2783 name);
2785 sprintf(procname, "%i", inode->fd);
2786 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2787 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2788 if (fd < 0) {
2789 saverr = errno;
2790 goto out;
2792 ret = fremovexattr(fd, name);
2793 } else {
2794 /* fchdir should not fail here */
2795 assert(fchdir(lo->proc_self_fd) == 0);
2796 ret = removexattr(procname, name);
2797 assert(fchdir(lo->root.fd) == 0);
2800 saverr = ret == -1 ? errno : 0;
2802 out:
2803 if (fd >= 0) {
2804 close(fd);
2807 lo_inode_put(lo, &inode);
2808 g_free(mapped_name);
2809 fuse_reply_err(req, saverr);
2812 #ifdef HAVE_COPY_FILE_RANGE
2813 static void lo_copy_file_range(fuse_req_t req, fuse_ino_t ino_in, off_t off_in,
2814 struct fuse_file_info *fi_in, fuse_ino_t ino_out,
2815 off_t off_out, struct fuse_file_info *fi_out,
2816 size_t len, int flags)
2818 int in_fd, out_fd;
2819 ssize_t res;
2821 in_fd = lo_fi_fd(req, fi_in);
2822 out_fd = lo_fi_fd(req, fi_out);
2824 fuse_log(FUSE_LOG_DEBUG,
2825 "lo_copy_file_range(ino=%" PRIu64 "/fd=%d, "
2826 "off=%lu, ino=%" PRIu64 "/fd=%d, "
2827 "off=%lu, size=%zd, flags=0x%x)\n",
2828 ino_in, in_fd, off_in, ino_out, out_fd, off_out, len, flags);
2830 res = copy_file_range(in_fd, &off_in, out_fd, &off_out, len, flags);
2831 if (res < 0) {
2832 fuse_reply_err(req, errno);
2833 } else {
2834 fuse_reply_write(req, res);
2837 #endif
2839 static void lo_lseek(fuse_req_t req, fuse_ino_t ino, off_t off, int whence,
2840 struct fuse_file_info *fi)
2842 off_t res;
2844 (void)ino;
2845 res = lseek(lo_fi_fd(req, fi), off, whence);
2846 if (res != -1) {
2847 fuse_reply_lseek(req, res);
2848 } else {
2849 fuse_reply_err(req, errno);
2853 static void lo_destroy(void *userdata)
2855 struct lo_data *lo = (struct lo_data *)userdata;
2857 pthread_mutex_lock(&lo->mutex);
2858 while (true) {
2859 GHashTableIter iter;
2860 gpointer key, value;
2862 g_hash_table_iter_init(&iter, lo->inodes);
2863 if (!g_hash_table_iter_next(&iter, &key, &value)) {
2864 break;
2867 struct lo_inode *inode = value;
2868 unref_inode(lo, inode, inode->nlookup);
2870 pthread_mutex_unlock(&lo->mutex);
2873 static struct fuse_lowlevel_ops lo_oper = {
2874 .init = lo_init,
2875 .lookup = lo_lookup,
2876 .mkdir = lo_mkdir,
2877 .mknod = lo_mknod,
2878 .symlink = lo_symlink,
2879 .link = lo_link,
2880 .unlink = lo_unlink,
2881 .rmdir = lo_rmdir,
2882 .rename = lo_rename,
2883 .forget = lo_forget,
2884 .forget_multi = lo_forget_multi,
2885 .getattr = lo_getattr,
2886 .setattr = lo_setattr,
2887 .readlink = lo_readlink,
2888 .opendir = lo_opendir,
2889 .readdir = lo_readdir,
2890 .readdirplus = lo_readdirplus,
2891 .releasedir = lo_releasedir,
2892 .fsyncdir = lo_fsyncdir,
2893 .create = lo_create,
2894 .getlk = lo_getlk,
2895 .setlk = lo_setlk,
2896 .open = lo_open,
2897 .release = lo_release,
2898 .flush = lo_flush,
2899 .fsync = lo_fsync,
2900 .read = lo_read,
2901 .write_buf = lo_write_buf,
2902 .statfs = lo_statfs,
2903 .fallocate = lo_fallocate,
2904 .flock = lo_flock,
2905 .getxattr = lo_getxattr,
2906 .listxattr = lo_listxattr,
2907 .setxattr = lo_setxattr,
2908 .removexattr = lo_removexattr,
2909 #ifdef HAVE_COPY_FILE_RANGE
2910 .copy_file_range = lo_copy_file_range,
2911 #endif
2912 .lseek = lo_lseek,
2913 .destroy = lo_destroy,
2916 /* Print vhost-user.json backend program capabilities */
2917 static void print_capabilities(void)
2919 printf("{\n");
2920 printf(" \"type\": \"fs\"\n");
2921 printf("}\n");
2925 * Drop all Linux capabilities because the wait parent process only needs to
2926 * sit in waitpid(2) and terminate.
2928 static void setup_wait_parent_capabilities(void)
2930 capng_setpid(syscall(SYS_gettid));
2931 capng_clear(CAPNG_SELECT_BOTH);
2932 capng_apply(CAPNG_SELECT_BOTH);
2936 * Move to a new mount, net, and pid namespaces to isolate this process.
2938 static void setup_namespaces(struct lo_data *lo, struct fuse_session *se)
2940 pid_t child;
2943 * Create a new pid namespace for *child* processes. We'll have to
2944 * fork in order to enter the new pid namespace. A new mount namespace
2945 * is also needed so that we can remount /proc for the new pid
2946 * namespace.
2948 * Our UNIX domain sockets have been created. Now we can move to
2949 * an empty network namespace to prevent TCP/IP and other network
2950 * activity in case this process is compromised.
2952 if (unshare(CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWNET) != 0) {
2953 fuse_log(FUSE_LOG_ERR, "unshare(CLONE_NEWPID | CLONE_NEWNS): %m\n");
2954 exit(1);
2957 child = fork();
2958 if (child < 0) {
2959 fuse_log(FUSE_LOG_ERR, "fork() failed: %m\n");
2960 exit(1);
2962 if (child > 0) {
2963 pid_t waited;
2964 int wstatus;
2966 setup_wait_parent_capabilities();
2968 /* The parent waits for the child */
2969 do {
2970 waited = waitpid(child, &wstatus, 0);
2971 } while (waited < 0 && errno == EINTR && !se->exited);
2973 /* We were terminated by a signal, see fuse_signals.c */
2974 if (se->exited) {
2975 exit(0);
2978 if (WIFEXITED(wstatus)) {
2979 exit(WEXITSTATUS(wstatus));
2982 exit(1);
2985 /* Send us SIGTERM when the parent thread terminates, see prctl(2) */
2986 prctl(PR_SET_PDEATHSIG, SIGTERM);
2989 * If the mounts have shared propagation then we want to opt out so our
2990 * mount changes don't affect the parent mount namespace.
2992 if (mount(NULL, "/", NULL, MS_REC | MS_SLAVE, NULL) < 0) {
2993 fuse_log(FUSE_LOG_ERR, "mount(/, MS_REC|MS_SLAVE): %m\n");
2994 exit(1);
2997 /* The child must remount /proc to use the new pid namespace */
2998 if (mount("proc", "/proc", "proc",
2999 MS_NODEV | MS_NOEXEC | MS_NOSUID | MS_RELATIME, NULL) < 0) {
3000 fuse_log(FUSE_LOG_ERR, "mount(/proc): %m\n");
3001 exit(1);
3005 * We only need /proc/self/fd. Prevent ".." from accessing parent
3006 * directories of /proc/self/fd by bind-mounting it over /proc. Since / was
3007 * previously remounted with MS_REC | MS_SLAVE this mount change only
3008 * affects our process.
3010 if (mount("/proc/self/fd", "/proc", NULL, MS_BIND, NULL) < 0) {
3011 fuse_log(FUSE_LOG_ERR, "mount(/proc/self/fd, MS_BIND): %m\n");
3012 exit(1);
3015 /* Get the /proc (actually /proc/self/fd, see above) file descriptor */
3016 lo->proc_self_fd = open("/proc", O_PATH);
3017 if (lo->proc_self_fd == -1) {
3018 fuse_log(FUSE_LOG_ERR, "open(/proc, O_PATH): %m\n");
3019 exit(1);
3024 * Capture the capability state, we'll need to restore this for individual
3025 * threads later; see load_capng.
3027 static void setup_capng(void)
3029 /* Note this accesses /proc so has to happen before the sandbox */
3030 if (capng_get_caps_process()) {
3031 fuse_log(FUSE_LOG_ERR, "capng_get_caps_process\n");
3032 exit(1);
3034 pthread_mutex_init(&cap.mutex, NULL);
3035 pthread_mutex_lock(&cap.mutex);
3036 cap.saved = capng_save_state();
3037 if (!cap.saved) {
3038 fuse_log(FUSE_LOG_ERR, "capng_save_state\n");
3039 exit(1);
3041 pthread_mutex_unlock(&cap.mutex);
3044 static void cleanup_capng(void)
3046 free(cap.saved);
3047 cap.saved = NULL;
3048 pthread_mutex_destroy(&cap.mutex);
3053 * Make the source directory our root so symlinks cannot escape and no other
3054 * files are accessible. Assumes unshare(CLONE_NEWNS) was already called.
3056 static void setup_mounts(const char *source)
3058 int oldroot;
3059 int newroot;
3061 if (mount(source, source, NULL, MS_BIND | MS_REC, NULL) < 0) {
3062 fuse_log(FUSE_LOG_ERR, "mount(%s, %s, MS_BIND): %m\n", source, source);
3063 exit(1);
3066 /* This magic is based on lxc's lxc_pivot_root() */
3067 oldroot = open("/", O_DIRECTORY | O_RDONLY | O_CLOEXEC);
3068 if (oldroot < 0) {
3069 fuse_log(FUSE_LOG_ERR, "open(/): %m\n");
3070 exit(1);
3073 newroot = open(source, O_DIRECTORY | O_RDONLY | O_CLOEXEC);
3074 if (newroot < 0) {
3075 fuse_log(FUSE_LOG_ERR, "open(%s): %m\n", source);
3076 exit(1);
3079 if (fchdir(newroot) < 0) {
3080 fuse_log(FUSE_LOG_ERR, "fchdir(newroot): %m\n");
3081 exit(1);
3084 if (syscall(__NR_pivot_root, ".", ".") < 0) {
3085 fuse_log(FUSE_LOG_ERR, "pivot_root(., .): %m\n");
3086 exit(1);
3089 if (fchdir(oldroot) < 0) {
3090 fuse_log(FUSE_LOG_ERR, "fchdir(oldroot): %m\n");
3091 exit(1);
3094 if (mount("", ".", "", MS_SLAVE | MS_REC, NULL) < 0) {
3095 fuse_log(FUSE_LOG_ERR, "mount(., MS_SLAVE | MS_REC): %m\n");
3096 exit(1);
3099 if (umount2(".", MNT_DETACH) < 0) {
3100 fuse_log(FUSE_LOG_ERR, "umount2(., MNT_DETACH): %m\n");
3101 exit(1);
3104 if (fchdir(newroot) < 0) {
3105 fuse_log(FUSE_LOG_ERR, "fchdir(newroot): %m\n");
3106 exit(1);
3109 close(newroot);
3110 close(oldroot);
3114 * Only keep whitelisted capabilities that are needed for file system operation
3115 * The (possibly NULL) modcaps_in string passed in is free'd before exit.
3117 static void setup_capabilities(char *modcaps_in)
3119 char *modcaps = modcaps_in;
3120 pthread_mutex_lock(&cap.mutex);
3121 capng_restore_state(&cap.saved);
3124 * Whitelist file system-related capabilities that are needed for a file
3125 * server to act like root. Drop everything else like networking and
3126 * sysadmin capabilities.
3128 * Exclusions:
3129 * 1. CAP_LINUX_IMMUTABLE is not included because it's only used via ioctl
3130 * and we don't support that.
3131 * 2. CAP_MAC_OVERRIDE is not included because it only seems to be
3132 * used by the Smack LSM. Omit it until there is demand for it.
3134 capng_setpid(syscall(SYS_gettid));
3135 capng_clear(CAPNG_SELECT_BOTH);
3136 if (capng_updatev(CAPNG_ADD, CAPNG_PERMITTED | CAPNG_EFFECTIVE,
3137 CAP_CHOWN,
3138 CAP_DAC_OVERRIDE,
3139 CAP_FOWNER,
3140 CAP_FSETID,
3141 CAP_SETGID,
3142 CAP_SETUID,
3143 CAP_MKNOD,
3144 CAP_SETFCAP,
3145 -1)) {
3146 fuse_log(FUSE_LOG_ERR, "%s: capng_updatev failed\n", __func__);
3147 exit(1);
3151 * The modcaps option is a colon separated list of caps,
3152 * each preceded by either + or -.
3154 while (modcaps) {
3155 capng_act_t action;
3156 int cap;
3158 char *next = strchr(modcaps, ':');
3159 if (next) {
3160 *next = '\0';
3161 next++;
3164 switch (modcaps[0]) {
3165 case '+':
3166 action = CAPNG_ADD;
3167 break;
3169 case '-':
3170 action = CAPNG_DROP;
3171 break;
3173 default:
3174 fuse_log(FUSE_LOG_ERR,
3175 "%s: Expecting '+'/'-' in modcaps but found '%c'\n",
3176 __func__, modcaps[0]);
3177 exit(1);
3179 cap = capng_name_to_capability(modcaps + 1);
3180 if (cap < 0) {
3181 fuse_log(FUSE_LOG_ERR, "%s: Unknown capability '%s'\n", __func__,
3182 modcaps);
3183 exit(1);
3185 if (capng_update(action, CAPNG_PERMITTED | CAPNG_EFFECTIVE, cap)) {
3186 fuse_log(FUSE_LOG_ERR, "%s: capng_update failed for '%s'\n",
3187 __func__, modcaps);
3188 exit(1);
3191 modcaps = next;
3193 g_free(modcaps_in);
3195 if (capng_apply(CAPNG_SELECT_BOTH)) {
3196 fuse_log(FUSE_LOG_ERR, "%s: capng_apply failed\n", __func__);
3197 exit(1);
3200 cap.saved = capng_save_state();
3201 if (!cap.saved) {
3202 fuse_log(FUSE_LOG_ERR, "%s: capng_save_state failed\n", __func__);
3203 exit(1);
3205 pthread_mutex_unlock(&cap.mutex);
3209 * Use chroot as a weaker sandbox for environments where the process is
3210 * launched without CAP_SYS_ADMIN.
3212 static void setup_chroot(struct lo_data *lo)
3214 lo->proc_self_fd = open("/proc/self/fd", O_PATH);
3215 if (lo->proc_self_fd == -1) {
3216 fuse_log(FUSE_LOG_ERR, "open(\"/proc/self/fd\", O_PATH): %m\n");
3217 exit(1);
3221 * Make the shared directory the file system root so that FUSE_OPEN
3222 * (lo_open()) cannot escape the shared directory by opening a symlink.
3224 * The chroot(2) syscall is later disabled by seccomp and the
3225 * CAP_SYS_CHROOT capability is dropped so that tampering with the chroot
3226 * is not possible.
3228 * However, it's still possible to escape the chroot via lo->proc_self_fd
3229 * but that requires first gaining control of the process.
3231 if (chroot(lo->source) != 0) {
3232 fuse_log(FUSE_LOG_ERR, "chroot(\"%s\"): %m\n", lo->source);
3233 exit(1);
3236 /* Move into the chroot */
3237 if (chdir("/") != 0) {
3238 fuse_log(FUSE_LOG_ERR, "chdir(\"/\"): %m\n");
3239 exit(1);
3244 * Lock down this process to prevent access to other processes or files outside
3245 * source directory. This reduces the impact of arbitrary code execution bugs.
3247 static void setup_sandbox(struct lo_data *lo, struct fuse_session *se,
3248 bool enable_syslog)
3250 if (lo->sandbox == SANDBOX_NAMESPACE) {
3251 setup_namespaces(lo, se);
3252 setup_mounts(lo->source);
3253 } else {
3254 setup_chroot(lo);
3257 setup_seccomp(enable_syslog);
3258 setup_capabilities(g_strdup(lo->modcaps));
3261 /* Set the maximum number of open file descriptors */
3262 static void setup_nofile_rlimit(unsigned long rlimit_nofile)
3264 struct rlimit rlim = {
3265 .rlim_cur = rlimit_nofile,
3266 .rlim_max = rlimit_nofile,
3269 if (rlimit_nofile == 0) {
3270 return; /* nothing to do */
3273 if (setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
3274 /* Ignore SELinux denials */
3275 if (errno == EPERM) {
3276 return;
3279 fuse_log(FUSE_LOG_ERR, "setrlimit(RLIMIT_NOFILE): %m\n");
3280 exit(1);
3284 static void log_func(enum fuse_log_level level, const char *fmt, va_list ap)
3286 g_autofree char *localfmt = NULL;
3288 if (current_log_level < level) {
3289 return;
3292 if (current_log_level == FUSE_LOG_DEBUG) {
3293 if (!use_syslog) {
3294 localfmt = g_strdup_printf("[%" PRId64 "] [ID: %08ld] %s",
3295 get_clock(), syscall(__NR_gettid), fmt);
3296 } else {
3297 localfmt = g_strdup_printf("[ID: %08ld] %s", syscall(__NR_gettid),
3298 fmt);
3300 fmt = localfmt;
3303 if (use_syslog) {
3304 int priority = LOG_ERR;
3305 switch (level) {
3306 case FUSE_LOG_EMERG:
3307 priority = LOG_EMERG;
3308 break;
3309 case FUSE_LOG_ALERT:
3310 priority = LOG_ALERT;
3311 break;
3312 case FUSE_LOG_CRIT:
3313 priority = LOG_CRIT;
3314 break;
3315 case FUSE_LOG_ERR:
3316 priority = LOG_ERR;
3317 break;
3318 case FUSE_LOG_WARNING:
3319 priority = LOG_WARNING;
3320 break;
3321 case FUSE_LOG_NOTICE:
3322 priority = LOG_NOTICE;
3323 break;
3324 case FUSE_LOG_INFO:
3325 priority = LOG_INFO;
3326 break;
3327 case FUSE_LOG_DEBUG:
3328 priority = LOG_DEBUG;
3329 break;
3331 vsyslog(priority, fmt, ap);
3332 } else {
3333 vfprintf(stderr, fmt, ap);
3337 static void setup_root(struct lo_data *lo, struct lo_inode *root)
3339 int fd, res;
3340 struct stat stat;
3341 uint64_t mnt_id;
3343 fd = open("/", O_PATH);
3344 if (fd == -1) {
3345 fuse_log(FUSE_LOG_ERR, "open(%s, O_PATH): %m\n", lo->source);
3346 exit(1);
3349 res = do_statx(lo, fd, "", &stat, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW,
3350 &mnt_id);
3351 if (res == -1) {
3352 fuse_log(FUSE_LOG_ERR, "fstatat(%s): %m\n", lo->source);
3353 exit(1);
3356 root->filetype = S_IFDIR;
3357 root->fd = fd;
3358 root->key.ino = stat.st_ino;
3359 root->key.dev = stat.st_dev;
3360 root->key.mnt_id = mnt_id;
3361 root->nlookup = 2;
3362 g_atomic_int_set(&root->refcount, 2);
3365 static guint lo_key_hash(gconstpointer key)
3367 const struct lo_key *lkey = key;
3369 return (guint)lkey->ino + (guint)lkey->dev + (guint)lkey->mnt_id;
3372 static gboolean lo_key_equal(gconstpointer a, gconstpointer b)
3374 const struct lo_key *la = a;
3375 const struct lo_key *lb = b;
3377 return la->ino == lb->ino && la->dev == lb->dev && la->mnt_id == lb->mnt_id;
3380 static void fuse_lo_data_cleanup(struct lo_data *lo)
3382 if (lo->inodes) {
3383 g_hash_table_destroy(lo->inodes);
3385 lo_map_destroy(&lo->fd_map);
3386 lo_map_destroy(&lo->dirp_map);
3387 lo_map_destroy(&lo->ino_map);
3389 if (lo->proc_self_fd >= 0) {
3390 close(lo->proc_self_fd);
3393 if (lo->root.fd >= 0) {
3394 close(lo->root.fd);
3397 free(lo->xattrmap);
3398 free_xattrmap(lo);
3399 free(lo->source);
3402 int main(int argc, char *argv[])
3404 struct fuse_args args = FUSE_ARGS_INIT(argc, argv);
3405 struct fuse_session *se;
3406 struct fuse_cmdline_opts opts;
3407 struct lo_data lo = {
3408 .sandbox = SANDBOX_NAMESPACE,
3409 .debug = 0,
3410 .writeback = 0,
3411 .posix_lock = 0,
3412 .allow_direct_io = 0,
3413 .proc_self_fd = -1,
3415 struct lo_map_elem *root_elem;
3416 struct lo_map_elem *reserve_elem;
3417 int ret = -1;
3419 /* Don't mask creation mode, kernel already did that */
3420 umask(0);
3422 qemu_init_exec_dir(argv[0]);
3424 pthread_mutex_init(&lo.mutex, NULL);
3425 lo.inodes = g_hash_table_new(lo_key_hash, lo_key_equal);
3426 lo.root.fd = -1;
3427 lo.root.fuse_ino = FUSE_ROOT_ID;
3428 lo.cache = CACHE_AUTO;
3431 * Set up the ino map like this:
3432 * [0] Reserved (will not be used)
3433 * [1] Root inode
3435 lo_map_init(&lo.ino_map);
3436 reserve_elem = lo_map_reserve(&lo.ino_map, 0);
3437 if (!reserve_elem) {
3438 fuse_log(FUSE_LOG_ERR, "failed to alloc reserve_elem.\n");
3439 goto err_out1;
3441 reserve_elem->in_use = false;
3442 root_elem = lo_map_reserve(&lo.ino_map, lo.root.fuse_ino);
3443 if (!root_elem) {
3444 fuse_log(FUSE_LOG_ERR, "failed to alloc root_elem.\n");
3445 goto err_out1;
3447 root_elem->inode = &lo.root;
3449 lo_map_init(&lo.dirp_map);
3450 lo_map_init(&lo.fd_map);
3452 if (fuse_parse_cmdline(&args, &opts) != 0) {
3453 goto err_out1;
3455 fuse_set_log_func(log_func);
3456 use_syslog = opts.syslog;
3457 if (use_syslog) {
3458 openlog("virtiofsd", LOG_PID, LOG_DAEMON);
3461 if (opts.show_help) {
3462 printf("usage: %s [options]\n\n", argv[0]);
3463 fuse_cmdline_help();
3464 printf(" -o source=PATH shared directory tree\n");
3465 fuse_lowlevel_help();
3466 ret = 0;
3467 goto err_out1;
3468 } else if (opts.show_version) {
3469 fuse_lowlevel_version();
3470 ret = 0;
3471 goto err_out1;
3472 } else if (opts.print_capabilities) {
3473 print_capabilities();
3474 ret = 0;
3475 goto err_out1;
3478 if (fuse_opt_parse(&args, &lo, lo_opts, NULL) == -1) {
3479 goto err_out1;
3482 if (opts.log_level != 0) {
3483 current_log_level = opts.log_level;
3484 } else {
3485 /* default log level is INFO */
3486 current_log_level = FUSE_LOG_INFO;
3488 lo.debug = opts.debug;
3489 if (lo.debug) {
3490 current_log_level = FUSE_LOG_DEBUG;
3492 if (lo.source) {
3493 struct stat stat;
3494 int res;
3496 res = lstat(lo.source, &stat);
3497 if (res == -1) {
3498 fuse_log(FUSE_LOG_ERR, "failed to stat source (\"%s\"): %m\n",
3499 lo.source);
3500 exit(1);
3502 if (!S_ISDIR(stat.st_mode)) {
3503 fuse_log(FUSE_LOG_ERR, "source is not a directory\n");
3504 exit(1);
3506 } else {
3507 lo.source = strdup("/");
3508 if (!lo.source) {
3509 fuse_log(FUSE_LOG_ERR, "failed to strdup source\n");
3510 goto err_out1;
3514 if (lo.xattrmap) {
3515 parse_xattrmap(&lo);
3518 if (!lo.timeout_set) {
3519 switch (lo.cache) {
3520 case CACHE_NONE:
3521 lo.timeout = 0.0;
3522 break;
3524 case CACHE_AUTO:
3525 lo.timeout = 1.0;
3526 break;
3528 case CACHE_ALWAYS:
3529 lo.timeout = 86400.0;
3530 break;
3532 } else if (lo.timeout < 0) {
3533 fuse_log(FUSE_LOG_ERR, "timeout is negative (%lf)\n", lo.timeout);
3534 exit(1);
3537 lo.use_statx = true;
3539 se = fuse_session_new(&args, &lo_oper, sizeof(lo_oper), &lo);
3540 if (se == NULL) {
3541 goto err_out1;
3544 if (fuse_set_signal_handlers(se) != 0) {
3545 goto err_out2;
3548 if (fuse_session_mount(se) != 0) {
3549 goto err_out3;
3552 fuse_daemonize(opts.foreground);
3554 setup_nofile_rlimit(opts.rlimit_nofile);
3556 /* Must be before sandbox since it wants /proc */
3557 setup_capng();
3559 setup_sandbox(&lo, se, opts.syslog);
3561 setup_root(&lo, &lo.root);
3562 /* Block until ctrl+c or fusermount -u */
3563 ret = virtio_loop(se);
3565 fuse_session_unmount(se);
3566 cleanup_capng();
3567 err_out3:
3568 fuse_remove_signal_handlers(se);
3569 err_out2:
3570 fuse_session_destroy(se);
3571 err_out1:
3572 fuse_opt_free_args(&args);
3574 fuse_lo_data_cleanup(&lo);
3576 return ret ? 1 : 0;