virtiofsd: optionally return inode pointer from lo_do_lookup()
[qemu/kevin.git] / tools / virtiofsd / passthrough_ll.c
blobaa35fc6ba5a5aab0b83087f4ff27b72f511c91e2
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(struct lo_data *lo, int fd)
464 struct lo_map_elem *elem;
466 elem = lo_map_alloc_elem(&lo->fd_map);
467 if (!elem) {
468 return -1;
471 elem->fd = fd;
472 return elem - lo->fd_map.elems;
475 /* Assumes lo->mutex is held */
476 static ssize_t lo_add_dirp_mapping(fuse_req_t req, struct lo_dirp *dirp)
478 struct lo_map_elem *elem;
480 elem = lo_map_alloc_elem(&lo_data(req)->dirp_map);
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 on the inode on success. unref_inode_lolocked() must be
835 * called eventually to decrement nlookup again. If inodep is non-NULL, the
836 * inode pointer is stored and the caller must call lo_inode_put().
838 static int lo_do_lookup(fuse_req_t req, fuse_ino_t parent, const char *name,
839 struct fuse_entry_param *e,
840 struct lo_inode **inodep)
842 int newfd;
843 int res;
844 int saverr;
845 uint64_t mnt_id;
846 struct lo_data *lo = lo_data(req);
847 struct lo_inode *inode = NULL;
848 struct lo_inode *dir = lo_inode(req, parent);
850 if (inodep) {
851 *inodep = NULL;
855 * name_to_handle_at() and open_by_handle_at() can reach here with fuse
856 * mount point in guest, but we don't have its inode info in the
857 * ino_map.
859 if (!dir) {
860 return ENOENT;
863 memset(e, 0, sizeof(*e));
864 e->attr_timeout = lo->timeout;
865 e->entry_timeout = lo->timeout;
867 /* Do not allow escaping root directory */
868 if (dir == &lo->root && strcmp(name, "..") == 0) {
869 name = ".";
872 newfd = openat(dir->fd, name, O_PATH | O_NOFOLLOW);
873 if (newfd == -1) {
874 goto out_err;
877 res = do_statx(lo, newfd, "", &e->attr, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW,
878 &mnt_id);
879 if (res == -1) {
880 goto out_err;
883 if (S_ISDIR(e->attr.st_mode) && lo->announce_submounts &&
884 (e->attr.st_dev != dir->key.dev || mnt_id != dir->key.mnt_id)) {
885 e->attr_flags |= FUSE_ATTR_SUBMOUNT;
888 inode = lo_find(lo, &e->attr, mnt_id);
889 if (inode) {
890 close(newfd);
891 } else {
892 inode = calloc(1, sizeof(struct lo_inode));
893 if (!inode) {
894 goto out_err;
897 /* cache only filetype */
898 inode->filetype = (e->attr.st_mode & S_IFMT);
901 * One for the caller and one for nlookup (released in
902 * unref_inode_lolocked())
904 g_atomic_int_set(&inode->refcount, 2);
906 inode->nlookup = 1;
907 inode->fd = newfd;
908 inode->key.ino = e->attr.st_ino;
909 inode->key.dev = e->attr.st_dev;
910 inode->key.mnt_id = mnt_id;
911 if (lo->posix_lock) {
912 pthread_mutex_init(&inode->plock_mutex, NULL);
913 inode->posix_locks = g_hash_table_new_full(
914 g_direct_hash, g_direct_equal, NULL, posix_locks_value_destroy);
916 pthread_mutex_lock(&lo->mutex);
917 inode->fuse_ino = lo_add_inode_mapping(req, inode);
918 g_hash_table_insert(lo->inodes, &inode->key, inode);
919 pthread_mutex_unlock(&lo->mutex);
921 e->ino = inode->fuse_ino;
923 /* Transfer ownership of inode pointer to caller or drop it */
924 if (inodep) {
925 *inodep = inode;
926 } else {
927 lo_inode_put(lo, &inode);
930 lo_inode_put(lo, &dir);
932 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
933 name, (unsigned long long)e->ino);
935 return 0;
937 out_err:
938 saverr = errno;
939 if (newfd != -1) {
940 close(newfd);
942 lo_inode_put(lo, &inode);
943 lo_inode_put(lo, &dir);
944 return saverr;
947 static void lo_lookup(fuse_req_t req, fuse_ino_t parent, const char *name)
949 struct fuse_entry_param e;
950 int err;
952 fuse_log(FUSE_LOG_DEBUG, "lo_lookup(parent=%" PRIu64 ", name=%s)\n", parent,
953 name);
956 * Don't use is_safe_path_component(), allow "." and ".." for NFS export
957 * support.
959 if (strchr(name, '/')) {
960 fuse_reply_err(req, EINVAL);
961 return;
964 err = lo_do_lookup(req, parent, name, &e, NULL);
965 if (err) {
966 fuse_reply_err(req, err);
967 } else {
968 fuse_reply_entry(req, &e);
973 * On some archs, setres*id is limited to 2^16 but they
974 * provide setres*id32 variants that allow 2^32.
975 * Others just let setres*id do 2^32 anyway.
977 #ifdef SYS_setresgid32
978 #define OURSYS_setresgid SYS_setresgid32
979 #else
980 #define OURSYS_setresgid SYS_setresgid
981 #endif
983 #ifdef SYS_setresuid32
984 #define OURSYS_setresuid SYS_setresuid32
985 #else
986 #define OURSYS_setresuid SYS_setresuid
987 #endif
990 * Change to uid/gid of caller so that file is created with
991 * ownership of caller.
992 * TODO: What about selinux context?
994 static int lo_change_cred(fuse_req_t req, struct lo_cred *old)
996 int res;
998 old->euid = geteuid();
999 old->egid = getegid();
1001 res = syscall(OURSYS_setresgid, -1, fuse_req_ctx(req)->gid, -1);
1002 if (res == -1) {
1003 return errno;
1006 res = syscall(OURSYS_setresuid, -1, fuse_req_ctx(req)->uid, -1);
1007 if (res == -1) {
1008 int errno_save = errno;
1010 syscall(OURSYS_setresgid, -1, old->egid, -1);
1011 return errno_save;
1014 return 0;
1017 /* Regain Privileges */
1018 static void lo_restore_cred(struct lo_cred *old)
1020 int res;
1022 res = syscall(OURSYS_setresuid, -1, old->euid, -1);
1023 if (res == -1) {
1024 fuse_log(FUSE_LOG_ERR, "seteuid(%u): %m\n", old->euid);
1025 exit(1);
1028 res = syscall(OURSYS_setresgid, -1, old->egid, -1);
1029 if (res == -1) {
1030 fuse_log(FUSE_LOG_ERR, "setegid(%u): %m\n", old->egid);
1031 exit(1);
1035 static void lo_mknod_symlink(fuse_req_t req, fuse_ino_t parent,
1036 const char *name, mode_t mode, dev_t rdev,
1037 const char *link)
1039 int res;
1040 int saverr;
1041 struct lo_data *lo = lo_data(req);
1042 struct lo_inode *dir;
1043 struct fuse_entry_param e;
1044 struct lo_cred old = {};
1046 if (!is_safe_path_component(name)) {
1047 fuse_reply_err(req, EINVAL);
1048 return;
1051 dir = lo_inode(req, parent);
1052 if (!dir) {
1053 fuse_reply_err(req, EBADF);
1054 return;
1057 saverr = lo_change_cred(req, &old);
1058 if (saverr) {
1059 goto out;
1062 res = mknod_wrapper(dir->fd, name, link, mode, rdev);
1064 saverr = errno;
1066 lo_restore_cred(&old);
1068 if (res == -1) {
1069 goto out;
1072 saverr = lo_do_lookup(req, parent, name, &e, NULL);
1073 if (saverr) {
1074 goto out;
1077 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
1078 name, (unsigned long long)e.ino);
1080 fuse_reply_entry(req, &e);
1081 lo_inode_put(lo, &dir);
1082 return;
1084 out:
1085 lo_inode_put(lo, &dir);
1086 fuse_reply_err(req, saverr);
1089 static void lo_mknod(fuse_req_t req, fuse_ino_t parent, const char *name,
1090 mode_t mode, dev_t rdev)
1092 lo_mknod_symlink(req, parent, name, mode, rdev, NULL);
1095 static void lo_mkdir(fuse_req_t req, fuse_ino_t parent, const char *name,
1096 mode_t mode)
1098 lo_mknod_symlink(req, parent, name, S_IFDIR | mode, 0, NULL);
1101 static void lo_symlink(fuse_req_t req, const char *link, fuse_ino_t parent,
1102 const char *name)
1104 lo_mknod_symlink(req, parent, name, S_IFLNK, 0, link);
1107 static void lo_link(fuse_req_t req, fuse_ino_t ino, fuse_ino_t parent,
1108 const char *name)
1110 int res;
1111 struct lo_data *lo = lo_data(req);
1112 struct lo_inode *parent_inode;
1113 struct lo_inode *inode;
1114 struct fuse_entry_param e;
1115 char procname[64];
1116 int saverr;
1118 if (!is_safe_path_component(name)) {
1119 fuse_reply_err(req, EINVAL);
1120 return;
1123 parent_inode = lo_inode(req, parent);
1124 inode = lo_inode(req, ino);
1125 if (!parent_inode || !inode) {
1126 errno = EBADF;
1127 goto out_err;
1130 memset(&e, 0, sizeof(struct fuse_entry_param));
1131 e.attr_timeout = lo->timeout;
1132 e.entry_timeout = lo->timeout;
1134 sprintf(procname, "%i", inode->fd);
1135 res = linkat(lo->proc_self_fd, procname, parent_inode->fd, name,
1136 AT_SYMLINK_FOLLOW);
1137 if (res == -1) {
1138 goto out_err;
1141 res = fstatat(inode->fd, "", &e.attr, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW);
1142 if (res == -1) {
1143 goto out_err;
1146 pthread_mutex_lock(&lo->mutex);
1147 inode->nlookup++;
1148 pthread_mutex_unlock(&lo->mutex);
1149 e.ino = inode->fuse_ino;
1151 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
1152 name, (unsigned long long)e.ino);
1154 fuse_reply_entry(req, &e);
1155 lo_inode_put(lo, &parent_inode);
1156 lo_inode_put(lo, &inode);
1157 return;
1159 out_err:
1160 saverr = errno;
1161 lo_inode_put(lo, &parent_inode);
1162 lo_inode_put(lo, &inode);
1163 fuse_reply_err(req, saverr);
1166 /* Increments nlookup and caller must release refcount using lo_inode_put() */
1167 static struct lo_inode *lookup_name(fuse_req_t req, fuse_ino_t parent,
1168 const char *name)
1170 int res;
1171 uint64_t mnt_id;
1172 struct stat attr;
1173 struct lo_data *lo = lo_data(req);
1174 struct lo_inode *dir = lo_inode(req, parent);
1176 if (!dir) {
1177 return NULL;
1180 res = do_statx(lo, dir->fd, name, &attr,
1181 AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW, &mnt_id);
1182 lo_inode_put(lo, &dir);
1183 if (res == -1) {
1184 return NULL;
1187 return lo_find(lo, &attr, mnt_id);
1190 static void lo_rmdir(fuse_req_t req, fuse_ino_t parent, const char *name)
1192 int res;
1193 struct lo_inode *inode;
1194 struct lo_data *lo = lo_data(req);
1196 if (!is_safe_path_component(name)) {
1197 fuse_reply_err(req, EINVAL);
1198 return;
1201 inode = lookup_name(req, parent, name);
1202 if (!inode) {
1203 fuse_reply_err(req, EIO);
1204 return;
1207 res = unlinkat(lo_fd(req, parent), name, AT_REMOVEDIR);
1209 fuse_reply_err(req, res == -1 ? errno : 0);
1210 unref_inode_lolocked(lo, inode, 1);
1211 lo_inode_put(lo, &inode);
1214 static void lo_rename(fuse_req_t req, fuse_ino_t parent, const char *name,
1215 fuse_ino_t newparent, const char *newname,
1216 unsigned int flags)
1218 int res;
1219 struct lo_inode *parent_inode;
1220 struct lo_inode *newparent_inode;
1221 struct lo_inode *oldinode = NULL;
1222 struct lo_inode *newinode = NULL;
1223 struct lo_data *lo = lo_data(req);
1225 if (!is_safe_path_component(name) || !is_safe_path_component(newname)) {
1226 fuse_reply_err(req, EINVAL);
1227 return;
1230 parent_inode = lo_inode(req, parent);
1231 newparent_inode = lo_inode(req, newparent);
1232 if (!parent_inode || !newparent_inode) {
1233 fuse_reply_err(req, EBADF);
1234 goto out;
1237 oldinode = lookup_name(req, parent, name);
1238 newinode = lookup_name(req, newparent, newname);
1240 if (!oldinode) {
1241 fuse_reply_err(req, EIO);
1242 goto out;
1245 if (flags) {
1246 #ifndef SYS_renameat2
1247 fuse_reply_err(req, EINVAL);
1248 #else
1249 res = syscall(SYS_renameat2, parent_inode->fd, name,
1250 newparent_inode->fd, newname, flags);
1251 if (res == -1 && errno == ENOSYS) {
1252 fuse_reply_err(req, EINVAL);
1253 } else {
1254 fuse_reply_err(req, res == -1 ? errno : 0);
1256 #endif
1257 goto out;
1260 res = renameat(parent_inode->fd, name, newparent_inode->fd, newname);
1262 fuse_reply_err(req, res == -1 ? errno : 0);
1263 out:
1264 unref_inode_lolocked(lo, oldinode, 1);
1265 unref_inode_lolocked(lo, newinode, 1);
1266 lo_inode_put(lo, &oldinode);
1267 lo_inode_put(lo, &newinode);
1268 lo_inode_put(lo, &parent_inode);
1269 lo_inode_put(lo, &newparent_inode);
1272 static void lo_unlink(fuse_req_t req, fuse_ino_t parent, const char *name)
1274 int res;
1275 struct lo_inode *inode;
1276 struct lo_data *lo = lo_data(req);
1278 if (!is_safe_path_component(name)) {
1279 fuse_reply_err(req, EINVAL);
1280 return;
1283 inode = lookup_name(req, parent, name);
1284 if (!inode) {
1285 fuse_reply_err(req, EIO);
1286 return;
1289 res = unlinkat(lo_fd(req, parent), name, 0);
1291 fuse_reply_err(req, res == -1 ? errno : 0);
1292 unref_inode_lolocked(lo, inode, 1);
1293 lo_inode_put(lo, &inode);
1296 /* To be called with lo->mutex held */
1297 static void unref_inode(struct lo_data *lo, struct lo_inode *inode, uint64_t n)
1299 if (!inode) {
1300 return;
1303 assert(inode->nlookup >= n);
1304 inode->nlookup -= n;
1305 if (!inode->nlookup) {
1306 lo_map_remove(&lo->ino_map, inode->fuse_ino);
1307 g_hash_table_remove(lo->inodes, &inode->key);
1308 if (lo->posix_lock) {
1309 if (g_hash_table_size(inode->posix_locks)) {
1310 fuse_log(FUSE_LOG_WARNING, "Hash table is not empty\n");
1312 g_hash_table_destroy(inode->posix_locks);
1313 pthread_mutex_destroy(&inode->plock_mutex);
1315 /* Drop our refcount from lo_do_lookup() */
1316 lo_inode_put(lo, &inode);
1320 static void unref_inode_lolocked(struct lo_data *lo, struct lo_inode *inode,
1321 uint64_t n)
1323 if (!inode) {
1324 return;
1327 pthread_mutex_lock(&lo->mutex);
1328 unref_inode(lo, inode, n);
1329 pthread_mutex_unlock(&lo->mutex);
1332 static void lo_forget_one(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup)
1334 struct lo_data *lo = lo_data(req);
1335 struct lo_inode *inode;
1337 inode = lo_inode(req, ino);
1338 if (!inode) {
1339 return;
1342 fuse_log(FUSE_LOG_DEBUG, " forget %lli %lli -%lli\n",
1343 (unsigned long long)ino, (unsigned long long)inode->nlookup,
1344 (unsigned long long)nlookup);
1346 unref_inode_lolocked(lo, inode, nlookup);
1347 lo_inode_put(lo, &inode);
1350 static void lo_forget(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup)
1352 lo_forget_one(req, ino, nlookup);
1353 fuse_reply_none(req);
1356 static void lo_forget_multi(fuse_req_t req, size_t count,
1357 struct fuse_forget_data *forgets)
1359 int i;
1361 for (i = 0; i < count; i++) {
1362 lo_forget_one(req, forgets[i].ino, forgets[i].nlookup);
1364 fuse_reply_none(req);
1367 static void lo_readlink(fuse_req_t req, fuse_ino_t ino)
1369 char buf[PATH_MAX + 1];
1370 int res;
1372 res = readlinkat(lo_fd(req, ino), "", buf, sizeof(buf));
1373 if (res == -1) {
1374 return (void)fuse_reply_err(req, errno);
1377 if (res == sizeof(buf)) {
1378 return (void)fuse_reply_err(req, ENAMETOOLONG);
1381 buf[res] = '\0';
1383 fuse_reply_readlink(req, buf);
1386 struct lo_dirp {
1387 gint refcount;
1388 DIR *dp;
1389 struct dirent *entry;
1390 off_t offset;
1393 static void lo_dirp_put(struct lo_dirp **dp)
1395 struct lo_dirp *d = *dp;
1397 if (!d) {
1398 return;
1400 *dp = NULL;
1402 if (g_atomic_int_dec_and_test(&d->refcount)) {
1403 closedir(d->dp);
1404 free(d);
1408 /* Call lo_dirp_put() on the return value when no longer needed */
1409 static struct lo_dirp *lo_dirp(fuse_req_t req, struct fuse_file_info *fi)
1411 struct lo_data *lo = lo_data(req);
1412 struct lo_map_elem *elem;
1414 pthread_mutex_lock(&lo->mutex);
1415 elem = lo_map_get(&lo->dirp_map, fi->fh);
1416 if (elem) {
1417 g_atomic_int_inc(&elem->dirp->refcount);
1419 pthread_mutex_unlock(&lo->mutex);
1420 if (!elem) {
1421 return NULL;
1424 return elem->dirp;
1427 static void lo_opendir(fuse_req_t req, fuse_ino_t ino,
1428 struct fuse_file_info *fi)
1430 int error = ENOMEM;
1431 struct lo_data *lo = lo_data(req);
1432 struct lo_dirp *d;
1433 int fd;
1434 ssize_t fh;
1436 d = calloc(1, sizeof(struct lo_dirp));
1437 if (d == NULL) {
1438 goto out_err;
1441 fd = openat(lo_fd(req, ino), ".", O_RDONLY);
1442 if (fd == -1) {
1443 goto out_errno;
1446 d->dp = fdopendir(fd);
1447 if (d->dp == NULL) {
1448 goto out_errno;
1451 d->offset = 0;
1452 d->entry = NULL;
1454 g_atomic_int_set(&d->refcount, 1); /* paired with lo_releasedir() */
1455 pthread_mutex_lock(&lo->mutex);
1456 fh = lo_add_dirp_mapping(req, d);
1457 pthread_mutex_unlock(&lo->mutex);
1458 if (fh == -1) {
1459 goto out_err;
1462 fi->fh = fh;
1463 if (lo->cache == CACHE_ALWAYS) {
1464 fi->cache_readdir = 1;
1466 fuse_reply_open(req, fi);
1467 return;
1469 out_errno:
1470 error = errno;
1471 out_err:
1472 if (d) {
1473 if (d->dp) {
1474 closedir(d->dp);
1475 } else if (fd != -1) {
1476 close(fd);
1478 free(d);
1480 fuse_reply_err(req, error);
1483 static void lo_do_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
1484 off_t offset, struct fuse_file_info *fi, int plus)
1486 struct lo_data *lo = lo_data(req);
1487 struct lo_dirp *d = NULL;
1488 struct lo_inode *dinode;
1489 char *buf = NULL;
1490 char *p;
1491 size_t rem = size;
1492 int err = EBADF;
1494 dinode = lo_inode(req, ino);
1495 if (!dinode) {
1496 goto error;
1499 d = lo_dirp(req, fi);
1500 if (!d) {
1501 goto error;
1504 err = ENOMEM;
1505 buf = calloc(1, size);
1506 if (!buf) {
1507 goto error;
1509 p = buf;
1511 if (offset != d->offset) {
1512 seekdir(d->dp, offset);
1513 d->entry = NULL;
1514 d->offset = offset;
1516 while (1) {
1517 size_t entsize;
1518 off_t nextoff;
1519 const char *name;
1521 if (!d->entry) {
1522 errno = 0;
1523 d->entry = readdir(d->dp);
1524 if (!d->entry) {
1525 if (errno) { /* Error */
1526 err = errno;
1527 goto error;
1528 } else { /* End of stream */
1529 break;
1533 nextoff = d->entry->d_off;
1534 name = d->entry->d_name;
1536 fuse_ino_t entry_ino = 0;
1537 struct fuse_entry_param e = (struct fuse_entry_param){
1538 .attr.st_ino = d->entry->d_ino,
1539 .attr.st_mode = d->entry->d_type << 12,
1542 /* Hide root's parent directory */
1543 if (dinode == &lo->root && strcmp(name, "..") == 0) {
1544 e.attr.st_ino = lo->root.key.ino;
1545 e.attr.st_mode = DT_DIR << 12;
1548 if (plus) {
1549 if (!is_dot_or_dotdot(name)) {
1550 err = lo_do_lookup(req, ino, name, &e, NULL);
1551 if (err) {
1552 goto error;
1554 entry_ino = e.ino;
1557 entsize = fuse_add_direntry_plus(req, p, rem, name, &e, nextoff);
1558 } else {
1559 entsize = fuse_add_direntry(req, p, rem, name, &e.attr, nextoff);
1561 if (entsize > rem) {
1562 if (entry_ino != 0) {
1563 lo_forget_one(req, entry_ino, 1);
1565 break;
1568 p += entsize;
1569 rem -= entsize;
1571 d->entry = NULL;
1572 d->offset = nextoff;
1575 err = 0;
1576 error:
1577 lo_dirp_put(&d);
1578 lo_inode_put(lo, &dinode);
1581 * If there's an error, we can only signal it if we haven't stored
1582 * any entries yet - otherwise we'd end up with wrong lookup
1583 * counts for the entries that are already in the buffer. So we
1584 * return what we've collected until that point.
1586 if (err && rem == size) {
1587 fuse_reply_err(req, err);
1588 } else {
1589 fuse_reply_buf(req, buf, size - rem);
1591 free(buf);
1594 static void lo_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
1595 off_t offset, struct fuse_file_info *fi)
1597 lo_do_readdir(req, ino, size, offset, fi, 0);
1600 static void lo_readdirplus(fuse_req_t req, fuse_ino_t ino, size_t size,
1601 off_t offset, struct fuse_file_info *fi)
1603 lo_do_readdir(req, ino, size, offset, fi, 1);
1606 static void lo_releasedir(fuse_req_t req, fuse_ino_t ino,
1607 struct fuse_file_info *fi)
1609 struct lo_data *lo = lo_data(req);
1610 struct lo_map_elem *elem;
1611 struct lo_dirp *d;
1613 (void)ino;
1615 pthread_mutex_lock(&lo->mutex);
1616 elem = lo_map_get(&lo->dirp_map, fi->fh);
1617 if (!elem) {
1618 pthread_mutex_unlock(&lo->mutex);
1619 fuse_reply_err(req, EBADF);
1620 return;
1623 d = elem->dirp;
1624 lo_map_remove(&lo->dirp_map, fi->fh);
1625 pthread_mutex_unlock(&lo->mutex);
1627 lo_dirp_put(&d); /* paired with lo_opendir() */
1629 fuse_reply_err(req, 0);
1632 static void update_open_flags(int writeback, int allow_direct_io,
1633 struct fuse_file_info *fi)
1636 * With writeback cache, kernel may send read requests even
1637 * when userspace opened write-only
1639 if (writeback && (fi->flags & O_ACCMODE) == O_WRONLY) {
1640 fi->flags &= ~O_ACCMODE;
1641 fi->flags |= O_RDWR;
1645 * With writeback cache, O_APPEND is handled by the kernel.
1646 * This breaks atomicity (since the file may change in the
1647 * underlying filesystem, so that the kernel's idea of the
1648 * end of the file isn't accurate anymore). In this example,
1649 * we just accept that. A more rigorous filesystem may want
1650 * to return an error here
1652 if (writeback && (fi->flags & O_APPEND)) {
1653 fi->flags &= ~O_APPEND;
1657 * O_DIRECT in guest should not necessarily mean bypassing page
1658 * cache on host as well. Therefore, we discard it by default
1659 * ('-o no_allow_direct_io'). If somebody needs that behavior,
1660 * the '-o allow_direct_io' option should be set.
1662 if (!allow_direct_io) {
1663 fi->flags &= ~O_DIRECT;
1667 static int lo_do_open(struct lo_data *lo, struct lo_inode *inode,
1668 struct fuse_file_info *fi)
1670 char buf[64];
1671 ssize_t fh;
1672 int fd;
1674 update_open_flags(lo->writeback, lo->allow_direct_io, fi);
1676 sprintf(buf, "%i", inode->fd);
1677 fd = openat(lo->proc_self_fd, buf, fi->flags & ~O_NOFOLLOW);
1678 if (fd == -1) {
1679 return errno;
1682 pthread_mutex_lock(&lo->mutex);
1683 fh = lo_add_fd_mapping(lo, fd);
1684 pthread_mutex_unlock(&lo->mutex);
1685 if (fh == -1) {
1686 close(fd);
1687 return ENOMEM;
1690 fi->fh = fh;
1691 if (lo->cache == CACHE_NONE) {
1692 fi->direct_io = 1;
1693 } else if (lo->cache == CACHE_ALWAYS) {
1694 fi->keep_cache = 1;
1696 return 0;
1699 static void lo_create(fuse_req_t req, fuse_ino_t parent, const char *name,
1700 mode_t mode, struct fuse_file_info *fi)
1702 int fd;
1703 struct lo_data *lo = lo_data(req);
1704 struct lo_inode *parent_inode;
1705 struct fuse_entry_param e;
1706 int err;
1707 struct lo_cred old = {};
1709 fuse_log(FUSE_LOG_DEBUG, "lo_create(parent=%" PRIu64 ", name=%s)\n", parent,
1710 name);
1712 if (!is_safe_path_component(name)) {
1713 fuse_reply_err(req, EINVAL);
1714 return;
1717 parent_inode = lo_inode(req, parent);
1718 if (!parent_inode) {
1719 fuse_reply_err(req, EBADF);
1720 return;
1723 err = lo_change_cred(req, &old);
1724 if (err) {
1725 goto out;
1728 update_open_flags(lo->writeback, lo->allow_direct_io, fi);
1730 fd = openat(parent_inode->fd, name, (fi->flags | O_CREAT) & ~O_NOFOLLOW,
1731 mode);
1732 err = fd == -1 ? errno : 0;
1733 lo_restore_cred(&old);
1735 if (!err) {
1736 ssize_t fh;
1738 pthread_mutex_lock(&lo->mutex);
1739 fh = lo_add_fd_mapping(lo, fd);
1740 pthread_mutex_unlock(&lo->mutex);
1741 if (fh == -1) {
1742 close(fd);
1743 err = ENOMEM;
1744 goto out;
1747 fi->fh = fh;
1748 err = lo_do_lookup(req, parent, name, &e, NULL);
1750 if (lo->cache == CACHE_NONE) {
1751 fi->direct_io = 1;
1752 } else if (lo->cache == CACHE_ALWAYS) {
1753 fi->keep_cache = 1;
1756 out:
1757 lo_inode_put(lo, &parent_inode);
1759 if (err) {
1760 fuse_reply_err(req, err);
1761 } else {
1762 fuse_reply_create(req, &e, fi);
1766 /* Should be called with inode->plock_mutex held */
1767 static struct lo_inode_plock *lookup_create_plock_ctx(struct lo_data *lo,
1768 struct lo_inode *inode,
1769 uint64_t lock_owner,
1770 pid_t pid, int *err)
1772 struct lo_inode_plock *plock;
1773 char procname[64];
1774 int fd;
1776 plock =
1777 g_hash_table_lookup(inode->posix_locks, GUINT_TO_POINTER(lock_owner));
1779 if (plock) {
1780 return plock;
1783 plock = malloc(sizeof(struct lo_inode_plock));
1784 if (!plock) {
1785 *err = ENOMEM;
1786 return NULL;
1789 /* Open another instance of file which can be used for ofd locks. */
1790 sprintf(procname, "%i", inode->fd);
1792 /* TODO: What if file is not writable? */
1793 fd = openat(lo->proc_self_fd, procname, O_RDWR);
1794 if (fd == -1) {
1795 *err = errno;
1796 free(plock);
1797 return NULL;
1800 plock->lock_owner = lock_owner;
1801 plock->fd = fd;
1802 g_hash_table_insert(inode->posix_locks, GUINT_TO_POINTER(plock->lock_owner),
1803 plock);
1804 return plock;
1807 static void lo_getlk(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
1808 struct flock *lock)
1810 struct lo_data *lo = lo_data(req);
1811 struct lo_inode *inode;
1812 struct lo_inode_plock *plock;
1813 int ret, saverr = 0;
1815 fuse_log(FUSE_LOG_DEBUG,
1816 "lo_getlk(ino=%" PRIu64 ", flags=%d)"
1817 " owner=0x%lx, l_type=%d l_start=0x%lx"
1818 " l_len=0x%lx\n",
1819 ino, fi->flags, fi->lock_owner, lock->l_type, lock->l_start,
1820 lock->l_len);
1822 if (!lo->posix_lock) {
1823 fuse_reply_err(req, ENOSYS);
1824 return;
1827 inode = lo_inode(req, ino);
1828 if (!inode) {
1829 fuse_reply_err(req, EBADF);
1830 return;
1833 pthread_mutex_lock(&inode->plock_mutex);
1834 plock =
1835 lookup_create_plock_ctx(lo, inode, fi->lock_owner, lock->l_pid, &ret);
1836 if (!plock) {
1837 saverr = ret;
1838 goto out;
1841 ret = fcntl(plock->fd, F_OFD_GETLK, lock);
1842 if (ret == -1) {
1843 saverr = errno;
1846 out:
1847 pthread_mutex_unlock(&inode->plock_mutex);
1848 lo_inode_put(lo, &inode);
1850 if (saverr) {
1851 fuse_reply_err(req, saverr);
1852 } else {
1853 fuse_reply_lock(req, lock);
1857 static void lo_setlk(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
1858 struct flock *lock, int sleep)
1860 struct lo_data *lo = lo_data(req);
1861 struct lo_inode *inode;
1862 struct lo_inode_plock *plock;
1863 int ret, saverr = 0;
1865 fuse_log(FUSE_LOG_DEBUG,
1866 "lo_setlk(ino=%" PRIu64 ", flags=%d)"
1867 " cmd=%d pid=%d owner=0x%lx sleep=%d l_whence=%d"
1868 " l_start=0x%lx l_len=0x%lx\n",
1869 ino, fi->flags, lock->l_type, lock->l_pid, fi->lock_owner, sleep,
1870 lock->l_whence, lock->l_start, lock->l_len);
1872 if (!lo->posix_lock) {
1873 fuse_reply_err(req, ENOSYS);
1874 return;
1877 if (sleep) {
1878 fuse_reply_err(req, EOPNOTSUPP);
1879 return;
1882 inode = lo_inode(req, ino);
1883 if (!inode) {
1884 fuse_reply_err(req, EBADF);
1885 return;
1888 pthread_mutex_lock(&inode->plock_mutex);
1889 plock =
1890 lookup_create_plock_ctx(lo, inode, fi->lock_owner, lock->l_pid, &ret);
1892 if (!plock) {
1893 saverr = ret;
1894 goto out;
1897 /* TODO: Is it alright to modify flock? */
1898 lock->l_pid = 0;
1899 ret = fcntl(plock->fd, F_OFD_SETLK, lock);
1900 if (ret == -1) {
1901 saverr = errno;
1904 out:
1905 pthread_mutex_unlock(&inode->plock_mutex);
1906 lo_inode_put(lo, &inode);
1908 fuse_reply_err(req, saverr);
1911 static void lo_fsyncdir(fuse_req_t req, fuse_ino_t ino, int datasync,
1912 struct fuse_file_info *fi)
1914 int res;
1915 struct lo_dirp *d;
1916 int fd;
1918 (void)ino;
1920 d = lo_dirp(req, fi);
1921 if (!d) {
1922 fuse_reply_err(req, EBADF);
1923 return;
1926 fd = dirfd(d->dp);
1927 if (datasync) {
1928 res = fdatasync(fd);
1929 } else {
1930 res = fsync(fd);
1933 lo_dirp_put(&d);
1935 fuse_reply_err(req, res == -1 ? errno : 0);
1938 static void lo_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi)
1940 struct lo_data *lo = lo_data(req);
1941 struct lo_inode *inode = lo_inode(req, ino);
1942 int err;
1944 fuse_log(FUSE_LOG_DEBUG, "lo_open(ino=%" PRIu64 ", flags=%d)\n", ino,
1945 fi->flags);
1947 if (!inode) {
1948 fuse_reply_err(req, EBADF);
1949 return;
1952 err = lo_do_open(lo, inode, fi);
1953 lo_inode_put(lo, &inode);
1954 if (err) {
1955 fuse_reply_err(req, err);
1956 } else {
1957 fuse_reply_open(req, fi);
1961 static void lo_release(fuse_req_t req, fuse_ino_t ino,
1962 struct fuse_file_info *fi)
1964 struct lo_data *lo = lo_data(req);
1965 struct lo_map_elem *elem;
1966 int fd = -1;
1968 (void)ino;
1970 pthread_mutex_lock(&lo->mutex);
1971 elem = lo_map_get(&lo->fd_map, fi->fh);
1972 if (elem) {
1973 fd = elem->fd;
1974 elem = NULL;
1975 lo_map_remove(&lo->fd_map, fi->fh);
1977 pthread_mutex_unlock(&lo->mutex);
1979 close(fd);
1980 fuse_reply_err(req, 0);
1983 static void lo_flush(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi)
1985 int res;
1986 (void)ino;
1987 struct lo_inode *inode;
1988 struct lo_data *lo = lo_data(req);
1990 inode = lo_inode(req, ino);
1991 if (!inode) {
1992 fuse_reply_err(req, EBADF);
1993 return;
1996 if (!S_ISREG(inode->filetype)) {
1997 lo_inode_put(lo, &inode);
1998 fuse_reply_err(req, EBADF);
1999 return;
2002 /* An fd is going away. Cleanup associated posix locks */
2003 if (lo->posix_lock) {
2004 pthread_mutex_lock(&inode->plock_mutex);
2005 g_hash_table_remove(inode->posix_locks,
2006 GUINT_TO_POINTER(fi->lock_owner));
2007 pthread_mutex_unlock(&inode->plock_mutex);
2009 res = close(dup(lo_fi_fd(req, fi)));
2010 lo_inode_put(lo, &inode);
2011 fuse_reply_err(req, res == -1 ? errno : 0);
2014 static void lo_fsync(fuse_req_t req, fuse_ino_t ino, int datasync,
2015 struct fuse_file_info *fi)
2017 int res;
2018 int fd;
2019 char *buf;
2021 fuse_log(FUSE_LOG_DEBUG, "lo_fsync(ino=%" PRIu64 ", fi=0x%p)\n", ino,
2022 (void *)fi);
2024 if (!fi) {
2025 struct lo_data *lo = lo_data(req);
2027 res = asprintf(&buf, "%i", lo_fd(req, ino));
2028 if (res == -1) {
2029 return (void)fuse_reply_err(req, errno);
2032 fd = openat(lo->proc_self_fd, buf, O_RDWR);
2033 free(buf);
2034 if (fd == -1) {
2035 return (void)fuse_reply_err(req, errno);
2037 } else {
2038 fd = lo_fi_fd(req, fi);
2041 if (datasync) {
2042 res = fdatasync(fd);
2043 } else {
2044 res = fsync(fd);
2046 if (!fi) {
2047 close(fd);
2049 fuse_reply_err(req, res == -1 ? errno : 0);
2052 static void lo_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t offset,
2053 struct fuse_file_info *fi)
2055 struct fuse_bufvec buf = FUSE_BUFVEC_INIT(size);
2057 fuse_log(FUSE_LOG_DEBUG,
2058 "lo_read(ino=%" PRIu64 ", size=%zd, "
2059 "off=%lu)\n",
2060 ino, size, (unsigned long)offset);
2062 buf.buf[0].flags = FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK;
2063 buf.buf[0].fd = lo_fi_fd(req, fi);
2064 buf.buf[0].pos = offset;
2066 fuse_reply_data(req, &buf);
2069 static void lo_write_buf(fuse_req_t req, fuse_ino_t ino,
2070 struct fuse_bufvec *in_buf, off_t off,
2071 struct fuse_file_info *fi)
2073 (void)ino;
2074 ssize_t res;
2075 struct fuse_bufvec out_buf = FUSE_BUFVEC_INIT(fuse_buf_size(in_buf));
2076 bool cap_fsetid_dropped = false;
2078 out_buf.buf[0].flags = FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK;
2079 out_buf.buf[0].fd = lo_fi_fd(req, fi);
2080 out_buf.buf[0].pos = off;
2082 fuse_log(FUSE_LOG_DEBUG,
2083 "lo_write_buf(ino=%" PRIu64 ", size=%zd, off=%lu)\n", ino,
2084 out_buf.buf[0].size, (unsigned long)off);
2087 * If kill_priv is set, drop CAP_FSETID which should lead to kernel
2088 * clearing setuid/setgid on file.
2090 if (fi->kill_priv) {
2091 res = drop_effective_cap("FSETID", &cap_fsetid_dropped);
2092 if (res != 0) {
2093 fuse_reply_err(req, res);
2094 return;
2098 res = fuse_buf_copy(&out_buf, in_buf);
2099 if (res < 0) {
2100 fuse_reply_err(req, -res);
2101 } else {
2102 fuse_reply_write(req, (size_t)res);
2105 if (cap_fsetid_dropped) {
2106 res = gain_effective_cap("FSETID");
2107 if (res) {
2108 fuse_log(FUSE_LOG_ERR, "Failed to gain CAP_FSETID\n");
2113 static void lo_statfs(fuse_req_t req, fuse_ino_t ino)
2115 int res;
2116 struct statvfs stbuf;
2118 res = fstatvfs(lo_fd(req, ino), &stbuf);
2119 if (res == -1) {
2120 fuse_reply_err(req, errno);
2121 } else {
2122 fuse_reply_statfs(req, &stbuf);
2126 static void lo_fallocate(fuse_req_t req, fuse_ino_t ino, int mode, off_t offset,
2127 off_t length, struct fuse_file_info *fi)
2129 int err = EOPNOTSUPP;
2130 (void)ino;
2132 #ifdef CONFIG_FALLOCATE
2133 err = fallocate(lo_fi_fd(req, fi), mode, offset, length);
2134 if (err < 0) {
2135 err = errno;
2138 #elif defined(CONFIG_POSIX_FALLOCATE)
2139 if (mode) {
2140 fuse_reply_err(req, EOPNOTSUPP);
2141 return;
2144 err = posix_fallocate(lo_fi_fd(req, fi), offset, length);
2145 #endif
2147 fuse_reply_err(req, err);
2150 static void lo_flock(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
2151 int op)
2153 int res;
2154 (void)ino;
2156 res = flock(lo_fi_fd(req, fi), op);
2158 fuse_reply_err(req, res == -1 ? errno : 0);
2161 /* types */
2163 * Exit; process attribute unmodified if matched.
2164 * An empty key applies to all.
2166 #define XATTR_MAP_FLAG_OK (1 << 0)
2168 * The attribute is unwanted;
2169 * EPERM on write, hidden on read.
2171 #define XATTR_MAP_FLAG_BAD (1 << 1)
2173 * For attr that start with 'key' prepend 'prepend'
2174 * 'key' may be empty to prepend for all attrs
2175 * key is defined from set/remove point of view.
2176 * Automatically reversed on read
2178 #define XATTR_MAP_FLAG_PREFIX (1 << 2)
2180 /* scopes */
2181 /* Apply rule to get/set/remove */
2182 #define XATTR_MAP_FLAG_CLIENT (1 << 16)
2183 /* Apply rule to list */
2184 #define XATTR_MAP_FLAG_SERVER (1 << 17)
2185 /* Apply rule to all */
2186 #define XATTR_MAP_FLAG_ALL (XATTR_MAP_FLAG_SERVER | XATTR_MAP_FLAG_CLIENT)
2188 static void add_xattrmap_entry(struct lo_data *lo,
2189 const XattrMapEntry *new_entry)
2191 XattrMapEntry *res = g_realloc_n(lo->xattr_map_list,
2192 lo->xattr_map_nentries + 1,
2193 sizeof(XattrMapEntry));
2194 res[lo->xattr_map_nentries++] = *new_entry;
2196 lo->xattr_map_list = res;
2199 static void free_xattrmap(struct lo_data *lo)
2201 XattrMapEntry *map = lo->xattr_map_list;
2202 size_t i;
2204 if (!map) {
2205 return;
2208 for (i = 0; i < lo->xattr_map_nentries; i++) {
2209 g_free(map[i].key);
2210 g_free(map[i].prepend);
2213 g_free(map);
2214 lo->xattr_map_list = NULL;
2215 lo->xattr_map_nentries = -1;
2219 * Handle the 'map' type, which is sugar for a set of commands
2220 * for the common case of prefixing a subset or everything,
2221 * and allowing anything not prefixed through.
2222 * It must be the last entry in the stream, although there
2223 * can be other entries before it.
2224 * The form is:
2225 * :map:key:prefix:
2227 * key maybe empty in which case all entries are prefixed.
2229 static void parse_xattrmap_map(struct lo_data *lo,
2230 const char *rule, char sep)
2232 const char *tmp;
2233 char *key;
2234 char *prefix;
2235 XattrMapEntry tmp_entry;
2237 if (*rule != sep) {
2238 fuse_log(FUSE_LOG_ERR,
2239 "%s: Expecting '%c' after 'map' keyword, found '%c'\n",
2240 __func__, sep, *rule);
2241 exit(1);
2244 rule++;
2246 /* At start of 'key' field */
2247 tmp = strchr(rule, sep);
2248 if (!tmp) {
2249 fuse_log(FUSE_LOG_ERR,
2250 "%s: Missing '%c' at end of key field in map rule\n",
2251 __func__, sep);
2252 exit(1);
2255 key = g_strndup(rule, tmp - rule);
2256 rule = tmp + 1;
2258 /* At start of prefix field */
2259 tmp = strchr(rule, sep);
2260 if (!tmp) {
2261 fuse_log(FUSE_LOG_ERR,
2262 "%s: Missing '%c' at end of prefix field in map rule\n",
2263 __func__, sep);
2264 exit(1);
2267 prefix = g_strndup(rule, tmp - rule);
2268 rule = tmp + 1;
2271 * This should be the end of the string, we don't allow
2272 * any more commands after 'map'.
2274 if (*rule) {
2275 fuse_log(FUSE_LOG_ERR,
2276 "%s: Expecting end of command after map, found '%c'\n",
2277 __func__, *rule);
2278 exit(1);
2281 /* 1st: Prefix matches/everything */
2282 tmp_entry.flags = XATTR_MAP_FLAG_PREFIX | XATTR_MAP_FLAG_ALL;
2283 tmp_entry.key = g_strdup(key);
2284 tmp_entry.prepend = g_strdup(prefix);
2285 add_xattrmap_entry(lo, &tmp_entry);
2287 if (!*key) {
2288 /* Prefix all case */
2290 /* 2nd: Hide any non-prefixed entries on the host */
2291 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_ALL;
2292 tmp_entry.key = g_strdup("");
2293 tmp_entry.prepend = g_strdup("");
2294 add_xattrmap_entry(lo, &tmp_entry);
2295 } else {
2296 /* Prefix matching case */
2298 /* 2nd: Hide non-prefixed but matching entries on the host */
2299 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_SERVER;
2300 tmp_entry.key = g_strdup(""); /* Not used */
2301 tmp_entry.prepend = g_strdup(key);
2302 add_xattrmap_entry(lo, &tmp_entry);
2304 /* 3rd: Stop the client accessing prefixed attributes directly */
2305 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_CLIENT;
2306 tmp_entry.key = g_strdup(prefix);
2307 tmp_entry.prepend = g_strdup(""); /* Not used */
2308 add_xattrmap_entry(lo, &tmp_entry);
2310 /* 4th: Everything else is OK */
2311 tmp_entry.flags = XATTR_MAP_FLAG_OK | XATTR_MAP_FLAG_ALL;
2312 tmp_entry.key = g_strdup("");
2313 tmp_entry.prepend = g_strdup("");
2314 add_xattrmap_entry(lo, &tmp_entry);
2317 g_free(key);
2318 g_free(prefix);
2321 static void parse_xattrmap(struct lo_data *lo)
2323 const char *map = lo->xattrmap;
2324 const char *tmp;
2326 lo->xattr_map_nentries = 0;
2327 while (*map) {
2328 XattrMapEntry tmp_entry;
2329 char sep;
2331 if (isspace(*map)) {
2332 map++;
2333 continue;
2335 /* The separator is the first non-space of the rule */
2336 sep = *map++;
2337 if (!sep) {
2338 break;
2341 tmp_entry.flags = 0;
2342 /* Start of 'type' */
2343 if (strstart(map, "prefix", &map)) {
2344 tmp_entry.flags |= XATTR_MAP_FLAG_PREFIX;
2345 } else if (strstart(map, "ok", &map)) {
2346 tmp_entry.flags |= XATTR_MAP_FLAG_OK;
2347 } else if (strstart(map, "bad", &map)) {
2348 tmp_entry.flags |= XATTR_MAP_FLAG_BAD;
2349 } else if (strstart(map, "map", &map)) {
2351 * map is sugar that adds a number of rules, and must be
2352 * the last entry.
2354 parse_xattrmap_map(lo, map, sep);
2355 return;
2356 } else {
2357 fuse_log(FUSE_LOG_ERR,
2358 "%s: Unexpected type;"
2359 "Expecting 'prefix', 'ok', 'bad' or 'map' in rule %zu\n",
2360 __func__, lo->xattr_map_nentries);
2361 exit(1);
2364 if (*map++ != sep) {
2365 fuse_log(FUSE_LOG_ERR,
2366 "%s: Missing '%c' at end of type field of rule %zu\n",
2367 __func__, sep, lo->xattr_map_nentries);
2368 exit(1);
2371 /* Start of 'scope' */
2372 if (strstart(map, "client", &map)) {
2373 tmp_entry.flags |= XATTR_MAP_FLAG_CLIENT;
2374 } else if (strstart(map, "server", &map)) {
2375 tmp_entry.flags |= XATTR_MAP_FLAG_SERVER;
2376 } else if (strstart(map, "all", &map)) {
2377 tmp_entry.flags |= XATTR_MAP_FLAG_ALL;
2378 } else {
2379 fuse_log(FUSE_LOG_ERR,
2380 "%s: Unexpected scope;"
2381 " Expecting 'client', 'server', or 'all', in rule %zu\n",
2382 __func__, lo->xattr_map_nentries);
2383 exit(1);
2386 if (*map++ != sep) {
2387 fuse_log(FUSE_LOG_ERR,
2388 "%s: Expecting '%c' found '%c'"
2389 " after scope in rule %zu\n",
2390 __func__, sep, *map, lo->xattr_map_nentries);
2391 exit(1);
2394 /* At start of 'key' field */
2395 tmp = strchr(map, sep);
2396 if (!tmp) {
2397 fuse_log(FUSE_LOG_ERR,
2398 "%s: Missing '%c' at end of key field of rule %zu",
2399 __func__, sep, lo->xattr_map_nentries);
2400 exit(1);
2402 tmp_entry.key = g_strndup(map, tmp - map);
2403 map = tmp + 1;
2405 /* At start of 'prepend' field */
2406 tmp = strchr(map, sep);
2407 if (!tmp) {
2408 fuse_log(FUSE_LOG_ERR,
2409 "%s: Missing '%c' at end of prepend field of rule %zu",
2410 __func__, sep, lo->xattr_map_nentries);
2411 exit(1);
2413 tmp_entry.prepend = g_strndup(map, tmp - map);
2414 map = tmp + 1;
2416 add_xattrmap_entry(lo, &tmp_entry);
2417 /* End of rule - go around again for another rule */
2420 if (!lo->xattr_map_nentries) {
2421 fuse_log(FUSE_LOG_ERR, "Empty xattr map\n");
2422 exit(1);
2427 * For use with getxattr/setxattr/removexattr, where the client
2428 * gives us a name and we may need to choose a different one.
2429 * Allocates a buffer for the result placing it in *out_name.
2430 * If there's no change then *out_name is not set.
2431 * Returns 0 on success
2432 * Can return -EPERM to indicate we block a given attribute
2433 * (in which case out_name is not allocated)
2434 * Can return -ENOMEM to indicate out_name couldn't be allocated.
2436 static int xattr_map_client(const struct lo_data *lo, const char *client_name,
2437 char **out_name)
2439 size_t i;
2440 for (i = 0; i < lo->xattr_map_nentries; i++) {
2441 const XattrMapEntry *cur_entry = lo->xattr_map_list + i;
2443 if ((cur_entry->flags & XATTR_MAP_FLAG_CLIENT) &&
2444 (strstart(client_name, cur_entry->key, NULL))) {
2445 if (cur_entry->flags & XATTR_MAP_FLAG_BAD) {
2446 return -EPERM;
2448 if (cur_entry->flags & XATTR_MAP_FLAG_OK) {
2449 /* Unmodified name */
2450 return 0;
2452 if (cur_entry->flags & XATTR_MAP_FLAG_PREFIX) {
2453 *out_name = g_try_malloc(strlen(client_name) +
2454 strlen(cur_entry->prepend) + 1);
2455 if (!*out_name) {
2456 return -ENOMEM;
2458 sprintf(*out_name, "%s%s", cur_entry->prepend, client_name);
2459 return 0;
2464 return -EPERM;
2468 * For use with listxattr where the server fs gives us a name and we may need
2469 * to sanitize this for the client.
2470 * Returns a pointer to the result in *out_name
2471 * This is always the original string or the current string with some prefix
2472 * removed; no reallocation is done.
2473 * Returns 0 on success
2474 * Can return -ENODATA to indicate the name should be dropped from the list.
2476 static int xattr_map_server(const struct lo_data *lo, const char *server_name,
2477 const char **out_name)
2479 size_t i;
2480 const char *end;
2482 for (i = 0; i < lo->xattr_map_nentries; i++) {
2483 const XattrMapEntry *cur_entry = lo->xattr_map_list + i;
2485 if ((cur_entry->flags & XATTR_MAP_FLAG_SERVER) &&
2486 (strstart(server_name, cur_entry->prepend, &end))) {
2487 if (cur_entry->flags & XATTR_MAP_FLAG_BAD) {
2488 return -ENODATA;
2490 if (cur_entry->flags & XATTR_MAP_FLAG_OK) {
2491 *out_name = server_name;
2492 return 0;
2494 if (cur_entry->flags & XATTR_MAP_FLAG_PREFIX) {
2495 /* Remove prefix */
2496 *out_name = end;
2497 return 0;
2502 return -ENODATA;
2505 static void lo_getxattr(fuse_req_t req, fuse_ino_t ino, const char *in_name,
2506 size_t size)
2508 struct lo_data *lo = lo_data(req);
2509 char *value = NULL;
2510 char procname[64];
2511 const char *name;
2512 char *mapped_name;
2513 struct lo_inode *inode;
2514 ssize_t ret;
2515 int saverr;
2516 int fd = -1;
2518 mapped_name = NULL;
2519 name = in_name;
2520 if (lo->xattrmap) {
2521 ret = xattr_map_client(lo, in_name, &mapped_name);
2522 if (ret < 0) {
2523 if (ret == -EPERM) {
2524 ret = -ENODATA;
2526 fuse_reply_err(req, -ret);
2527 return;
2529 if (mapped_name) {
2530 name = mapped_name;
2534 inode = lo_inode(req, ino);
2535 if (!inode) {
2536 fuse_reply_err(req, EBADF);
2537 g_free(mapped_name);
2538 return;
2541 saverr = ENOSYS;
2542 if (!lo_data(req)->xattr) {
2543 goto out;
2546 fuse_log(FUSE_LOG_DEBUG, "lo_getxattr(ino=%" PRIu64 ", name=%s size=%zd)\n",
2547 ino, name, size);
2549 if (size) {
2550 value = malloc(size);
2551 if (!value) {
2552 goto out_err;
2556 sprintf(procname, "%i", inode->fd);
2558 * It is not safe to open() non-regular/non-dir files in file server
2559 * unless O_PATH is used, so use that method for regular files/dir
2560 * only (as it seems giving less performance overhead).
2561 * Otherwise, call fchdir() to avoid open().
2563 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2564 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2565 if (fd < 0) {
2566 goto out_err;
2568 ret = fgetxattr(fd, name, value, size);
2569 } else {
2570 /* fchdir should not fail here */
2571 assert(fchdir(lo->proc_self_fd) == 0);
2572 ret = getxattr(procname, name, value, size);
2573 assert(fchdir(lo->root.fd) == 0);
2576 if (ret == -1) {
2577 goto out_err;
2579 if (size) {
2580 saverr = 0;
2581 if (ret == 0) {
2582 goto out;
2584 fuse_reply_buf(req, value, ret);
2585 } else {
2586 fuse_reply_xattr(req, ret);
2588 out_free:
2589 free(value);
2591 if (fd >= 0) {
2592 close(fd);
2595 lo_inode_put(lo, &inode);
2596 return;
2598 out_err:
2599 saverr = errno;
2600 out:
2601 fuse_reply_err(req, saverr);
2602 g_free(mapped_name);
2603 goto out_free;
2606 static void lo_listxattr(fuse_req_t req, fuse_ino_t ino, size_t size)
2608 struct lo_data *lo = lo_data(req);
2609 char *value = NULL;
2610 char procname[64];
2611 struct lo_inode *inode;
2612 ssize_t ret;
2613 int saverr;
2614 int fd = -1;
2616 inode = lo_inode(req, ino);
2617 if (!inode) {
2618 fuse_reply_err(req, EBADF);
2619 return;
2622 saverr = ENOSYS;
2623 if (!lo_data(req)->xattr) {
2624 goto out;
2627 fuse_log(FUSE_LOG_DEBUG, "lo_listxattr(ino=%" PRIu64 ", size=%zd)\n", ino,
2628 size);
2630 if (size) {
2631 value = malloc(size);
2632 if (!value) {
2633 goto out_err;
2637 sprintf(procname, "%i", inode->fd);
2638 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2639 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2640 if (fd < 0) {
2641 goto out_err;
2643 ret = flistxattr(fd, value, size);
2644 } else {
2645 /* fchdir should not fail here */
2646 assert(fchdir(lo->proc_self_fd) == 0);
2647 ret = listxattr(procname, value, size);
2648 assert(fchdir(lo->root.fd) == 0);
2651 if (ret == -1) {
2652 goto out_err;
2654 if (size) {
2655 saverr = 0;
2656 if (ret == 0) {
2657 goto out;
2660 if (lo->xattr_map_list) {
2662 * Map the names back, some attributes might be dropped,
2663 * some shortened, but not increased, so we shouldn't
2664 * run out of room.
2666 size_t out_index, in_index;
2667 out_index = 0;
2668 in_index = 0;
2669 while (in_index < ret) {
2670 const char *map_out;
2671 char *in_ptr = value + in_index;
2672 /* Length of current attribute name */
2673 size_t in_len = strlen(value + in_index) + 1;
2675 int mapret = xattr_map_server(lo, in_ptr, &map_out);
2676 if (mapret != -ENODATA && mapret != 0) {
2677 /* Shouldn't happen */
2678 saverr = -mapret;
2679 goto out;
2681 if (mapret == 0) {
2682 /* Either unchanged, or truncated */
2683 size_t out_len;
2684 if (map_out != in_ptr) {
2685 /* +1 copies the NIL */
2686 out_len = strlen(map_out) + 1;
2687 } else {
2688 /* No change */
2689 out_len = in_len;
2692 * Move result along, may still be needed for an unchanged
2693 * entry if a previous entry was changed.
2695 memmove(value + out_index, map_out, out_len);
2697 out_index += out_len;
2699 in_index += in_len;
2701 ret = out_index;
2702 if (ret == 0) {
2703 goto out;
2706 fuse_reply_buf(req, value, ret);
2707 } else {
2709 * xattrmap only ever shortens the result,
2710 * so we don't need to do anything clever with the
2711 * allocation length here.
2713 fuse_reply_xattr(req, ret);
2715 out_free:
2716 free(value);
2718 if (fd >= 0) {
2719 close(fd);
2722 lo_inode_put(lo, &inode);
2723 return;
2725 out_err:
2726 saverr = errno;
2727 out:
2728 fuse_reply_err(req, saverr);
2729 goto out_free;
2732 static void lo_setxattr(fuse_req_t req, fuse_ino_t ino, const char *in_name,
2733 const char *value, size_t size, int flags)
2735 char procname[64];
2736 const char *name;
2737 char *mapped_name;
2738 struct lo_data *lo = lo_data(req);
2739 struct lo_inode *inode;
2740 ssize_t ret;
2741 int saverr;
2742 int fd = -1;
2744 mapped_name = NULL;
2745 name = in_name;
2746 if (lo->xattrmap) {
2747 ret = xattr_map_client(lo, in_name, &mapped_name);
2748 if (ret < 0) {
2749 fuse_reply_err(req, -ret);
2750 return;
2752 if (mapped_name) {
2753 name = mapped_name;
2757 inode = lo_inode(req, ino);
2758 if (!inode) {
2759 fuse_reply_err(req, EBADF);
2760 g_free(mapped_name);
2761 return;
2764 saverr = ENOSYS;
2765 if (!lo_data(req)->xattr) {
2766 goto out;
2769 fuse_log(FUSE_LOG_DEBUG, "lo_setxattr(ino=%" PRIu64
2770 ", name=%s value=%s size=%zd)\n", ino, name, value, size);
2772 sprintf(procname, "%i", inode->fd);
2773 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2774 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2775 if (fd < 0) {
2776 saverr = errno;
2777 goto out;
2779 ret = fsetxattr(fd, name, value, size, flags);
2780 } else {
2781 /* fchdir should not fail here */
2782 assert(fchdir(lo->proc_self_fd) == 0);
2783 ret = setxattr(procname, name, value, size, flags);
2784 assert(fchdir(lo->root.fd) == 0);
2787 saverr = ret == -1 ? errno : 0;
2789 out:
2790 if (fd >= 0) {
2791 close(fd);
2794 lo_inode_put(lo, &inode);
2795 g_free(mapped_name);
2796 fuse_reply_err(req, saverr);
2799 static void lo_removexattr(fuse_req_t req, fuse_ino_t ino, const char *in_name)
2801 char procname[64];
2802 const char *name;
2803 char *mapped_name;
2804 struct lo_data *lo = lo_data(req);
2805 struct lo_inode *inode;
2806 ssize_t ret;
2807 int saverr;
2808 int fd = -1;
2810 mapped_name = NULL;
2811 name = in_name;
2812 if (lo->xattrmap) {
2813 ret = xattr_map_client(lo, in_name, &mapped_name);
2814 if (ret < 0) {
2815 fuse_reply_err(req, -ret);
2816 return;
2818 if (mapped_name) {
2819 name = mapped_name;
2823 inode = lo_inode(req, ino);
2824 if (!inode) {
2825 fuse_reply_err(req, EBADF);
2826 g_free(mapped_name);
2827 return;
2830 saverr = ENOSYS;
2831 if (!lo_data(req)->xattr) {
2832 goto out;
2835 fuse_log(FUSE_LOG_DEBUG, "lo_removexattr(ino=%" PRIu64 ", name=%s)\n", ino,
2836 name);
2838 sprintf(procname, "%i", inode->fd);
2839 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2840 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2841 if (fd < 0) {
2842 saverr = errno;
2843 goto out;
2845 ret = fremovexattr(fd, name);
2846 } else {
2847 /* fchdir should not fail here */
2848 assert(fchdir(lo->proc_self_fd) == 0);
2849 ret = removexattr(procname, name);
2850 assert(fchdir(lo->root.fd) == 0);
2853 saverr = ret == -1 ? errno : 0;
2855 out:
2856 if (fd >= 0) {
2857 close(fd);
2860 lo_inode_put(lo, &inode);
2861 g_free(mapped_name);
2862 fuse_reply_err(req, saverr);
2865 #ifdef HAVE_COPY_FILE_RANGE
2866 static void lo_copy_file_range(fuse_req_t req, fuse_ino_t ino_in, off_t off_in,
2867 struct fuse_file_info *fi_in, fuse_ino_t ino_out,
2868 off_t off_out, struct fuse_file_info *fi_out,
2869 size_t len, int flags)
2871 int in_fd, out_fd;
2872 ssize_t res;
2874 in_fd = lo_fi_fd(req, fi_in);
2875 out_fd = lo_fi_fd(req, fi_out);
2877 fuse_log(FUSE_LOG_DEBUG,
2878 "lo_copy_file_range(ino=%" PRIu64 "/fd=%d, "
2879 "off=%lu, ino=%" PRIu64 "/fd=%d, "
2880 "off=%lu, size=%zd, flags=0x%x)\n",
2881 ino_in, in_fd, off_in, ino_out, out_fd, off_out, len, flags);
2883 res = copy_file_range(in_fd, &off_in, out_fd, &off_out, len, flags);
2884 if (res < 0) {
2885 fuse_reply_err(req, errno);
2886 } else {
2887 fuse_reply_write(req, res);
2890 #endif
2892 static void lo_lseek(fuse_req_t req, fuse_ino_t ino, off_t off, int whence,
2893 struct fuse_file_info *fi)
2895 off_t res;
2897 (void)ino;
2898 res = lseek(lo_fi_fd(req, fi), off, whence);
2899 if (res != -1) {
2900 fuse_reply_lseek(req, res);
2901 } else {
2902 fuse_reply_err(req, errno);
2906 static void lo_destroy(void *userdata)
2908 struct lo_data *lo = (struct lo_data *)userdata;
2910 pthread_mutex_lock(&lo->mutex);
2911 while (true) {
2912 GHashTableIter iter;
2913 gpointer key, value;
2915 g_hash_table_iter_init(&iter, lo->inodes);
2916 if (!g_hash_table_iter_next(&iter, &key, &value)) {
2917 break;
2920 struct lo_inode *inode = value;
2921 unref_inode(lo, inode, inode->nlookup);
2923 pthread_mutex_unlock(&lo->mutex);
2926 static struct fuse_lowlevel_ops lo_oper = {
2927 .init = lo_init,
2928 .lookup = lo_lookup,
2929 .mkdir = lo_mkdir,
2930 .mknod = lo_mknod,
2931 .symlink = lo_symlink,
2932 .link = lo_link,
2933 .unlink = lo_unlink,
2934 .rmdir = lo_rmdir,
2935 .rename = lo_rename,
2936 .forget = lo_forget,
2937 .forget_multi = lo_forget_multi,
2938 .getattr = lo_getattr,
2939 .setattr = lo_setattr,
2940 .readlink = lo_readlink,
2941 .opendir = lo_opendir,
2942 .readdir = lo_readdir,
2943 .readdirplus = lo_readdirplus,
2944 .releasedir = lo_releasedir,
2945 .fsyncdir = lo_fsyncdir,
2946 .create = lo_create,
2947 .getlk = lo_getlk,
2948 .setlk = lo_setlk,
2949 .open = lo_open,
2950 .release = lo_release,
2951 .flush = lo_flush,
2952 .fsync = lo_fsync,
2953 .read = lo_read,
2954 .write_buf = lo_write_buf,
2955 .statfs = lo_statfs,
2956 .fallocate = lo_fallocate,
2957 .flock = lo_flock,
2958 .getxattr = lo_getxattr,
2959 .listxattr = lo_listxattr,
2960 .setxattr = lo_setxattr,
2961 .removexattr = lo_removexattr,
2962 #ifdef HAVE_COPY_FILE_RANGE
2963 .copy_file_range = lo_copy_file_range,
2964 #endif
2965 .lseek = lo_lseek,
2966 .destroy = lo_destroy,
2969 /* Print vhost-user.json backend program capabilities */
2970 static void print_capabilities(void)
2972 printf("{\n");
2973 printf(" \"type\": \"fs\"\n");
2974 printf("}\n");
2978 * Drop all Linux capabilities because the wait parent process only needs to
2979 * sit in waitpid(2) and terminate.
2981 static void setup_wait_parent_capabilities(void)
2983 capng_setpid(syscall(SYS_gettid));
2984 capng_clear(CAPNG_SELECT_BOTH);
2985 capng_apply(CAPNG_SELECT_BOTH);
2989 * Move to a new mount, net, and pid namespaces to isolate this process.
2991 static void setup_namespaces(struct lo_data *lo, struct fuse_session *se)
2993 pid_t child;
2996 * Create a new pid namespace for *child* processes. We'll have to
2997 * fork in order to enter the new pid namespace. A new mount namespace
2998 * is also needed so that we can remount /proc for the new pid
2999 * namespace.
3001 * Our UNIX domain sockets have been created. Now we can move to
3002 * an empty network namespace to prevent TCP/IP and other network
3003 * activity in case this process is compromised.
3005 if (unshare(CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWNET) != 0) {
3006 fuse_log(FUSE_LOG_ERR, "unshare(CLONE_NEWPID | CLONE_NEWNS): %m\n");
3007 exit(1);
3010 child = fork();
3011 if (child < 0) {
3012 fuse_log(FUSE_LOG_ERR, "fork() failed: %m\n");
3013 exit(1);
3015 if (child > 0) {
3016 pid_t waited;
3017 int wstatus;
3019 setup_wait_parent_capabilities();
3021 /* The parent waits for the child */
3022 do {
3023 waited = waitpid(child, &wstatus, 0);
3024 } while (waited < 0 && errno == EINTR && !se->exited);
3026 /* We were terminated by a signal, see fuse_signals.c */
3027 if (se->exited) {
3028 exit(0);
3031 if (WIFEXITED(wstatus)) {
3032 exit(WEXITSTATUS(wstatus));
3035 exit(1);
3038 /* Send us SIGTERM when the parent thread terminates, see prctl(2) */
3039 prctl(PR_SET_PDEATHSIG, SIGTERM);
3042 * If the mounts have shared propagation then we want to opt out so our
3043 * mount changes don't affect the parent mount namespace.
3045 if (mount(NULL, "/", NULL, MS_REC | MS_SLAVE, NULL) < 0) {
3046 fuse_log(FUSE_LOG_ERR, "mount(/, MS_REC|MS_SLAVE): %m\n");
3047 exit(1);
3050 /* The child must remount /proc to use the new pid namespace */
3051 if (mount("proc", "/proc", "proc",
3052 MS_NODEV | MS_NOEXEC | MS_NOSUID | MS_RELATIME, NULL) < 0) {
3053 fuse_log(FUSE_LOG_ERR, "mount(/proc): %m\n");
3054 exit(1);
3058 * We only need /proc/self/fd. Prevent ".." from accessing parent
3059 * directories of /proc/self/fd by bind-mounting it over /proc. Since / was
3060 * previously remounted with MS_REC | MS_SLAVE this mount change only
3061 * affects our process.
3063 if (mount("/proc/self/fd", "/proc", NULL, MS_BIND, NULL) < 0) {
3064 fuse_log(FUSE_LOG_ERR, "mount(/proc/self/fd, MS_BIND): %m\n");
3065 exit(1);
3068 /* Get the /proc (actually /proc/self/fd, see above) file descriptor */
3069 lo->proc_self_fd = open("/proc", O_PATH);
3070 if (lo->proc_self_fd == -1) {
3071 fuse_log(FUSE_LOG_ERR, "open(/proc, O_PATH): %m\n");
3072 exit(1);
3077 * Capture the capability state, we'll need to restore this for individual
3078 * threads later; see load_capng.
3080 static void setup_capng(void)
3082 /* Note this accesses /proc so has to happen before the sandbox */
3083 if (capng_get_caps_process()) {
3084 fuse_log(FUSE_LOG_ERR, "capng_get_caps_process\n");
3085 exit(1);
3087 pthread_mutex_init(&cap.mutex, NULL);
3088 pthread_mutex_lock(&cap.mutex);
3089 cap.saved = capng_save_state();
3090 if (!cap.saved) {
3091 fuse_log(FUSE_LOG_ERR, "capng_save_state\n");
3092 exit(1);
3094 pthread_mutex_unlock(&cap.mutex);
3097 static void cleanup_capng(void)
3099 free(cap.saved);
3100 cap.saved = NULL;
3101 pthread_mutex_destroy(&cap.mutex);
3106 * Make the source directory our root so symlinks cannot escape and no other
3107 * files are accessible. Assumes unshare(CLONE_NEWNS) was already called.
3109 static void setup_mounts(const char *source)
3111 int oldroot;
3112 int newroot;
3114 if (mount(source, source, NULL, MS_BIND | MS_REC, NULL) < 0) {
3115 fuse_log(FUSE_LOG_ERR, "mount(%s, %s, MS_BIND): %m\n", source, source);
3116 exit(1);
3119 /* This magic is based on lxc's lxc_pivot_root() */
3120 oldroot = open("/", O_DIRECTORY | O_RDONLY | O_CLOEXEC);
3121 if (oldroot < 0) {
3122 fuse_log(FUSE_LOG_ERR, "open(/): %m\n");
3123 exit(1);
3126 newroot = open(source, O_DIRECTORY | O_RDONLY | O_CLOEXEC);
3127 if (newroot < 0) {
3128 fuse_log(FUSE_LOG_ERR, "open(%s): %m\n", source);
3129 exit(1);
3132 if (fchdir(newroot) < 0) {
3133 fuse_log(FUSE_LOG_ERR, "fchdir(newroot): %m\n");
3134 exit(1);
3137 if (syscall(__NR_pivot_root, ".", ".") < 0) {
3138 fuse_log(FUSE_LOG_ERR, "pivot_root(., .): %m\n");
3139 exit(1);
3142 if (fchdir(oldroot) < 0) {
3143 fuse_log(FUSE_LOG_ERR, "fchdir(oldroot): %m\n");
3144 exit(1);
3147 if (mount("", ".", "", MS_SLAVE | MS_REC, NULL) < 0) {
3148 fuse_log(FUSE_LOG_ERR, "mount(., MS_SLAVE | MS_REC): %m\n");
3149 exit(1);
3152 if (umount2(".", MNT_DETACH) < 0) {
3153 fuse_log(FUSE_LOG_ERR, "umount2(., MNT_DETACH): %m\n");
3154 exit(1);
3157 if (fchdir(newroot) < 0) {
3158 fuse_log(FUSE_LOG_ERR, "fchdir(newroot): %m\n");
3159 exit(1);
3162 close(newroot);
3163 close(oldroot);
3167 * Only keep whitelisted capabilities that are needed for file system operation
3168 * The (possibly NULL) modcaps_in string passed in is free'd before exit.
3170 static void setup_capabilities(char *modcaps_in)
3172 char *modcaps = modcaps_in;
3173 pthread_mutex_lock(&cap.mutex);
3174 capng_restore_state(&cap.saved);
3177 * Whitelist file system-related capabilities that are needed for a file
3178 * server to act like root. Drop everything else like networking and
3179 * sysadmin capabilities.
3181 * Exclusions:
3182 * 1. CAP_LINUX_IMMUTABLE is not included because it's only used via ioctl
3183 * and we don't support that.
3184 * 2. CAP_MAC_OVERRIDE is not included because it only seems to be
3185 * used by the Smack LSM. Omit it until there is demand for it.
3187 capng_setpid(syscall(SYS_gettid));
3188 capng_clear(CAPNG_SELECT_BOTH);
3189 if (capng_updatev(CAPNG_ADD, CAPNG_PERMITTED | CAPNG_EFFECTIVE,
3190 CAP_CHOWN,
3191 CAP_DAC_OVERRIDE,
3192 CAP_FOWNER,
3193 CAP_FSETID,
3194 CAP_SETGID,
3195 CAP_SETUID,
3196 CAP_MKNOD,
3197 CAP_SETFCAP,
3198 -1)) {
3199 fuse_log(FUSE_LOG_ERR, "%s: capng_updatev failed\n", __func__);
3200 exit(1);
3204 * The modcaps option is a colon separated list of caps,
3205 * each preceded by either + or -.
3207 while (modcaps) {
3208 capng_act_t action;
3209 int cap;
3211 char *next = strchr(modcaps, ':');
3212 if (next) {
3213 *next = '\0';
3214 next++;
3217 switch (modcaps[0]) {
3218 case '+':
3219 action = CAPNG_ADD;
3220 break;
3222 case '-':
3223 action = CAPNG_DROP;
3224 break;
3226 default:
3227 fuse_log(FUSE_LOG_ERR,
3228 "%s: Expecting '+'/'-' in modcaps but found '%c'\n",
3229 __func__, modcaps[0]);
3230 exit(1);
3232 cap = capng_name_to_capability(modcaps + 1);
3233 if (cap < 0) {
3234 fuse_log(FUSE_LOG_ERR, "%s: Unknown capability '%s'\n", __func__,
3235 modcaps);
3236 exit(1);
3238 if (capng_update(action, CAPNG_PERMITTED | CAPNG_EFFECTIVE, cap)) {
3239 fuse_log(FUSE_LOG_ERR, "%s: capng_update failed for '%s'\n",
3240 __func__, modcaps);
3241 exit(1);
3244 modcaps = next;
3246 g_free(modcaps_in);
3248 if (capng_apply(CAPNG_SELECT_BOTH)) {
3249 fuse_log(FUSE_LOG_ERR, "%s: capng_apply failed\n", __func__);
3250 exit(1);
3253 cap.saved = capng_save_state();
3254 if (!cap.saved) {
3255 fuse_log(FUSE_LOG_ERR, "%s: capng_save_state failed\n", __func__);
3256 exit(1);
3258 pthread_mutex_unlock(&cap.mutex);
3262 * Use chroot as a weaker sandbox for environments where the process is
3263 * launched without CAP_SYS_ADMIN.
3265 static void setup_chroot(struct lo_data *lo)
3267 lo->proc_self_fd = open("/proc/self/fd", O_PATH);
3268 if (lo->proc_self_fd == -1) {
3269 fuse_log(FUSE_LOG_ERR, "open(\"/proc/self/fd\", O_PATH): %m\n");
3270 exit(1);
3274 * Make the shared directory the file system root so that FUSE_OPEN
3275 * (lo_open()) cannot escape the shared directory by opening a symlink.
3277 * The chroot(2) syscall is later disabled by seccomp and the
3278 * CAP_SYS_CHROOT capability is dropped so that tampering with the chroot
3279 * is not possible.
3281 * However, it's still possible to escape the chroot via lo->proc_self_fd
3282 * but that requires first gaining control of the process.
3284 if (chroot(lo->source) != 0) {
3285 fuse_log(FUSE_LOG_ERR, "chroot(\"%s\"): %m\n", lo->source);
3286 exit(1);
3289 /* Move into the chroot */
3290 if (chdir("/") != 0) {
3291 fuse_log(FUSE_LOG_ERR, "chdir(\"/\"): %m\n");
3292 exit(1);
3297 * Lock down this process to prevent access to other processes or files outside
3298 * source directory. This reduces the impact of arbitrary code execution bugs.
3300 static void setup_sandbox(struct lo_data *lo, struct fuse_session *se,
3301 bool enable_syslog)
3303 if (lo->sandbox == SANDBOX_NAMESPACE) {
3304 setup_namespaces(lo, se);
3305 setup_mounts(lo->source);
3306 } else {
3307 setup_chroot(lo);
3310 setup_seccomp(enable_syslog);
3311 setup_capabilities(g_strdup(lo->modcaps));
3314 /* Set the maximum number of open file descriptors */
3315 static void setup_nofile_rlimit(unsigned long rlimit_nofile)
3317 struct rlimit rlim = {
3318 .rlim_cur = rlimit_nofile,
3319 .rlim_max = rlimit_nofile,
3322 if (rlimit_nofile == 0) {
3323 return; /* nothing to do */
3326 if (setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
3327 /* Ignore SELinux denials */
3328 if (errno == EPERM) {
3329 return;
3332 fuse_log(FUSE_LOG_ERR, "setrlimit(RLIMIT_NOFILE): %m\n");
3333 exit(1);
3337 static void log_func(enum fuse_log_level level, const char *fmt, va_list ap)
3339 g_autofree char *localfmt = NULL;
3340 struct timespec ts;
3341 struct tm tm;
3342 char sec_fmt[sizeof "2020-12-07 18:17:54"];
3343 char zone_fmt[sizeof "+0100"];
3345 if (current_log_level < level) {
3346 return;
3349 if (current_log_level == FUSE_LOG_DEBUG) {
3350 if (use_syslog) {
3351 /* no timestamp needed */
3352 localfmt = g_strdup_printf("[ID: %08ld] %s", syscall(__NR_gettid),
3353 fmt);
3354 } else {
3355 /* try formatting a broken-down timestamp */
3356 if (clock_gettime(CLOCK_REALTIME, &ts) != -1 &&
3357 localtime_r(&ts.tv_sec, &tm) != NULL &&
3358 strftime(sec_fmt, sizeof sec_fmt, "%Y-%m-%d %H:%M:%S",
3359 &tm) != 0 &&
3360 strftime(zone_fmt, sizeof zone_fmt, "%z", &tm) != 0) {
3361 localfmt = g_strdup_printf("[%s.%02ld%s] [ID: %08ld] %s",
3362 sec_fmt,
3363 ts.tv_nsec / (10L * 1000 * 1000),
3364 zone_fmt, syscall(__NR_gettid),
3365 fmt);
3366 } else {
3367 /* fall back to a flat timestamp */
3368 localfmt = g_strdup_printf("[%" PRId64 "] [ID: %08ld] %s",
3369 get_clock(), syscall(__NR_gettid),
3370 fmt);
3373 fmt = localfmt;
3376 if (use_syslog) {
3377 int priority = LOG_ERR;
3378 switch (level) {
3379 case FUSE_LOG_EMERG:
3380 priority = LOG_EMERG;
3381 break;
3382 case FUSE_LOG_ALERT:
3383 priority = LOG_ALERT;
3384 break;
3385 case FUSE_LOG_CRIT:
3386 priority = LOG_CRIT;
3387 break;
3388 case FUSE_LOG_ERR:
3389 priority = LOG_ERR;
3390 break;
3391 case FUSE_LOG_WARNING:
3392 priority = LOG_WARNING;
3393 break;
3394 case FUSE_LOG_NOTICE:
3395 priority = LOG_NOTICE;
3396 break;
3397 case FUSE_LOG_INFO:
3398 priority = LOG_INFO;
3399 break;
3400 case FUSE_LOG_DEBUG:
3401 priority = LOG_DEBUG;
3402 break;
3404 vsyslog(priority, fmt, ap);
3405 } else {
3406 vfprintf(stderr, fmt, ap);
3410 static void setup_root(struct lo_data *lo, struct lo_inode *root)
3412 int fd, res;
3413 struct stat stat;
3414 uint64_t mnt_id;
3416 fd = open("/", O_PATH);
3417 if (fd == -1) {
3418 fuse_log(FUSE_LOG_ERR, "open(%s, O_PATH): %m\n", lo->source);
3419 exit(1);
3422 res = do_statx(lo, fd, "", &stat, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW,
3423 &mnt_id);
3424 if (res == -1) {
3425 fuse_log(FUSE_LOG_ERR, "fstatat(%s): %m\n", lo->source);
3426 exit(1);
3429 root->filetype = S_IFDIR;
3430 root->fd = fd;
3431 root->key.ino = stat.st_ino;
3432 root->key.dev = stat.st_dev;
3433 root->key.mnt_id = mnt_id;
3434 root->nlookup = 2;
3435 g_atomic_int_set(&root->refcount, 2);
3436 if (lo->posix_lock) {
3437 pthread_mutex_init(&root->plock_mutex, NULL);
3438 root->posix_locks = g_hash_table_new_full(
3439 g_direct_hash, g_direct_equal, NULL, posix_locks_value_destroy);
3443 static guint lo_key_hash(gconstpointer key)
3445 const struct lo_key *lkey = key;
3447 return (guint)lkey->ino + (guint)lkey->dev + (guint)lkey->mnt_id;
3450 static gboolean lo_key_equal(gconstpointer a, gconstpointer b)
3452 const struct lo_key *la = a;
3453 const struct lo_key *lb = b;
3455 return la->ino == lb->ino && la->dev == lb->dev && la->mnt_id == lb->mnt_id;
3458 static void fuse_lo_data_cleanup(struct lo_data *lo)
3460 if (lo->inodes) {
3461 g_hash_table_destroy(lo->inodes);
3464 if (lo->root.posix_locks) {
3465 g_hash_table_destroy(lo->root.posix_locks);
3467 lo_map_destroy(&lo->fd_map);
3468 lo_map_destroy(&lo->dirp_map);
3469 lo_map_destroy(&lo->ino_map);
3471 if (lo->proc_self_fd >= 0) {
3472 close(lo->proc_self_fd);
3475 if (lo->root.fd >= 0) {
3476 close(lo->root.fd);
3479 free(lo->xattrmap);
3480 free_xattrmap(lo);
3481 free(lo->source);
3484 int main(int argc, char *argv[])
3486 struct fuse_args args = FUSE_ARGS_INIT(argc, argv);
3487 struct fuse_session *se;
3488 struct fuse_cmdline_opts opts;
3489 struct lo_data lo = {
3490 .sandbox = SANDBOX_NAMESPACE,
3491 .debug = 0,
3492 .writeback = 0,
3493 .posix_lock = 0,
3494 .allow_direct_io = 0,
3495 .proc_self_fd = -1,
3497 struct lo_map_elem *root_elem;
3498 struct lo_map_elem *reserve_elem;
3499 int ret = -1;
3501 /* Initialize time conversion information for localtime_r(). */
3502 tzset();
3504 /* Don't mask creation mode, kernel already did that */
3505 umask(0);
3507 qemu_init_exec_dir(argv[0]);
3509 pthread_mutex_init(&lo.mutex, NULL);
3510 lo.inodes = g_hash_table_new(lo_key_hash, lo_key_equal);
3511 lo.root.fd = -1;
3512 lo.root.fuse_ino = FUSE_ROOT_ID;
3513 lo.cache = CACHE_AUTO;
3516 * Set up the ino map like this:
3517 * [0] Reserved (will not be used)
3518 * [1] Root inode
3520 lo_map_init(&lo.ino_map);
3521 reserve_elem = lo_map_reserve(&lo.ino_map, 0);
3522 if (!reserve_elem) {
3523 fuse_log(FUSE_LOG_ERR, "failed to alloc reserve_elem.\n");
3524 goto err_out1;
3526 reserve_elem->in_use = false;
3527 root_elem = lo_map_reserve(&lo.ino_map, lo.root.fuse_ino);
3528 if (!root_elem) {
3529 fuse_log(FUSE_LOG_ERR, "failed to alloc root_elem.\n");
3530 goto err_out1;
3532 root_elem->inode = &lo.root;
3534 lo_map_init(&lo.dirp_map);
3535 lo_map_init(&lo.fd_map);
3537 if (fuse_parse_cmdline(&args, &opts) != 0) {
3538 goto err_out1;
3540 fuse_set_log_func(log_func);
3541 use_syslog = opts.syslog;
3542 if (use_syslog) {
3543 openlog("virtiofsd", LOG_PID, LOG_DAEMON);
3546 if (opts.show_help) {
3547 printf("usage: %s [options]\n\n", argv[0]);
3548 fuse_cmdline_help();
3549 printf(" -o source=PATH shared directory tree\n");
3550 fuse_lowlevel_help();
3551 ret = 0;
3552 goto err_out1;
3553 } else if (opts.show_version) {
3554 fuse_lowlevel_version();
3555 ret = 0;
3556 goto err_out1;
3557 } else if (opts.print_capabilities) {
3558 print_capabilities();
3559 ret = 0;
3560 goto err_out1;
3563 if (fuse_opt_parse(&args, &lo, lo_opts, NULL) == -1) {
3564 goto err_out1;
3567 if (opts.log_level != 0) {
3568 current_log_level = opts.log_level;
3569 } else {
3570 /* default log level is INFO */
3571 current_log_level = FUSE_LOG_INFO;
3573 lo.debug = opts.debug;
3574 if (lo.debug) {
3575 current_log_level = FUSE_LOG_DEBUG;
3577 if (lo.source) {
3578 struct stat stat;
3579 int res;
3581 res = lstat(lo.source, &stat);
3582 if (res == -1) {
3583 fuse_log(FUSE_LOG_ERR, "failed to stat source (\"%s\"): %m\n",
3584 lo.source);
3585 exit(1);
3587 if (!S_ISDIR(stat.st_mode)) {
3588 fuse_log(FUSE_LOG_ERR, "source is not a directory\n");
3589 exit(1);
3591 } else {
3592 lo.source = strdup("/");
3593 if (!lo.source) {
3594 fuse_log(FUSE_LOG_ERR, "failed to strdup source\n");
3595 goto err_out1;
3599 if (lo.xattrmap) {
3600 parse_xattrmap(&lo);
3603 if (!lo.timeout_set) {
3604 switch (lo.cache) {
3605 case CACHE_NONE:
3606 lo.timeout = 0.0;
3607 break;
3609 case CACHE_AUTO:
3610 lo.timeout = 1.0;
3611 break;
3613 case CACHE_ALWAYS:
3614 lo.timeout = 86400.0;
3615 break;
3617 } else if (lo.timeout < 0) {
3618 fuse_log(FUSE_LOG_ERR, "timeout is negative (%lf)\n", lo.timeout);
3619 exit(1);
3622 lo.use_statx = true;
3624 se = fuse_session_new(&args, &lo_oper, sizeof(lo_oper), &lo);
3625 if (se == NULL) {
3626 goto err_out1;
3629 if (fuse_set_signal_handlers(se) != 0) {
3630 goto err_out2;
3633 if (fuse_session_mount(se) != 0) {
3634 goto err_out3;
3637 fuse_daemonize(opts.foreground);
3639 setup_nofile_rlimit(opts.rlimit_nofile);
3641 /* Must be before sandbox since it wants /proc */
3642 setup_capng();
3644 setup_sandbox(&lo, se, opts.syslog);
3646 setup_root(&lo, &lo.root);
3647 /* Block until ctrl+c or fusermount -u */
3648 ret = virtio_loop(se);
3650 fuse_session_unmount(se);
3651 cleanup_capng();
3652 err_out3:
3653 fuse_remove_signal_handlers(se);
3654 err_out2:
3655 fuse_session_destroy(se);
3656 err_out1:
3657 fuse_opt_free_args(&args);
3659 fuse_lo_data_cleanup(&lo);
3661 return ret ? 1 : 0;