configure: Improve TCI feature description
[qemu/ar7.git] / tools / virtiofsd / passthrough_ll.c
blob147b59338a185295b40fd09c641545ad72ed8ec6
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;
559 * Open a file descriptor for an inode. Returns -EBADF if the inode is not a
560 * regular file or a directory.
562 * Use this helper function instead of raw openat(2) to prevent security issues
563 * when a malicious client opens special files such as block device nodes.
564 * Symlink inodes are also rejected since symlinks must already have been
565 * traversed on the client side.
567 static int lo_inode_open(struct lo_data *lo, struct lo_inode *inode,
568 int open_flags)
570 g_autofree char *fd_str = g_strdup_printf("%d", inode->fd);
571 int fd;
573 if (!S_ISREG(inode->filetype) && !S_ISDIR(inode->filetype)) {
574 return -EBADF;
578 * The file is a symlink so O_NOFOLLOW must be ignored. We checked earlier
579 * that the inode is not a special file but if an external process races
580 * with us then symlinks are traversed here. It is not possible to escape
581 * the shared directory since it is mounted as "/" though.
583 fd = openat(lo->proc_self_fd, fd_str, open_flags & ~O_NOFOLLOW);
584 if (fd < 0) {
585 return -errno;
587 return fd;
590 static void lo_init(void *userdata, struct fuse_conn_info *conn)
592 struct lo_data *lo = (struct lo_data *)userdata;
594 if (conn->capable & FUSE_CAP_EXPORT_SUPPORT) {
595 conn->want |= FUSE_CAP_EXPORT_SUPPORT;
598 if (lo->writeback && conn->capable & FUSE_CAP_WRITEBACK_CACHE) {
599 fuse_log(FUSE_LOG_DEBUG, "lo_init: activating writeback\n");
600 conn->want |= FUSE_CAP_WRITEBACK_CACHE;
602 if (conn->capable & FUSE_CAP_FLOCK_LOCKS) {
603 if (lo->flock) {
604 fuse_log(FUSE_LOG_DEBUG, "lo_init: activating flock locks\n");
605 conn->want |= FUSE_CAP_FLOCK_LOCKS;
606 } else {
607 fuse_log(FUSE_LOG_DEBUG, "lo_init: disabling flock locks\n");
608 conn->want &= ~FUSE_CAP_FLOCK_LOCKS;
612 if (conn->capable & FUSE_CAP_POSIX_LOCKS) {
613 if (lo->posix_lock) {
614 fuse_log(FUSE_LOG_DEBUG, "lo_init: activating posix locks\n");
615 conn->want |= FUSE_CAP_POSIX_LOCKS;
616 } else {
617 fuse_log(FUSE_LOG_DEBUG, "lo_init: disabling posix locks\n");
618 conn->want &= ~FUSE_CAP_POSIX_LOCKS;
622 if ((lo->cache == CACHE_NONE && !lo->readdirplus_set) ||
623 lo->readdirplus_clear) {
624 fuse_log(FUSE_LOG_DEBUG, "lo_init: disabling readdirplus\n");
625 conn->want &= ~FUSE_CAP_READDIRPLUS;
628 if (!(conn->capable & FUSE_CAP_SUBMOUNTS) && lo->announce_submounts) {
629 fuse_log(FUSE_LOG_WARNING, "lo_init: Cannot announce submounts, client "
630 "does not support it\n");
631 lo->announce_submounts = false;
635 static void lo_getattr(fuse_req_t req, fuse_ino_t ino,
636 struct fuse_file_info *fi)
638 int res;
639 struct stat buf;
640 struct lo_data *lo = lo_data(req);
642 (void)fi;
644 res =
645 fstatat(lo_fd(req, ino), "", &buf, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW);
646 if (res == -1) {
647 return (void)fuse_reply_err(req, errno);
650 fuse_reply_attr(req, &buf, lo->timeout);
653 static int lo_fi_fd(fuse_req_t req, struct fuse_file_info *fi)
655 struct lo_data *lo = lo_data(req);
656 struct lo_map_elem *elem;
658 pthread_mutex_lock(&lo->mutex);
659 elem = lo_map_get(&lo->fd_map, fi->fh);
660 pthread_mutex_unlock(&lo->mutex);
662 if (!elem) {
663 return -1;
666 return elem->fd;
669 static void lo_setattr(fuse_req_t req, fuse_ino_t ino, struct stat *attr,
670 int valid, struct fuse_file_info *fi)
672 int saverr;
673 char procname[64];
674 struct lo_data *lo = lo_data(req);
675 struct lo_inode *inode;
676 int ifd;
677 int res;
678 int fd = -1;
680 inode = lo_inode(req, ino);
681 if (!inode) {
682 fuse_reply_err(req, EBADF);
683 return;
686 ifd = inode->fd;
688 /* If fi->fh is invalid we'll report EBADF later */
689 if (fi) {
690 fd = lo_fi_fd(req, fi);
693 if (valid & FUSE_SET_ATTR_MODE) {
694 if (fi) {
695 res = fchmod(fd, attr->st_mode);
696 } else {
697 sprintf(procname, "%i", ifd);
698 res = fchmodat(lo->proc_self_fd, procname, attr->st_mode, 0);
700 if (res == -1) {
701 goto out_err;
704 if (valid & (FUSE_SET_ATTR_UID | FUSE_SET_ATTR_GID)) {
705 uid_t uid = (valid & FUSE_SET_ATTR_UID) ? attr->st_uid : (uid_t)-1;
706 gid_t gid = (valid & FUSE_SET_ATTR_GID) ? attr->st_gid : (gid_t)-1;
708 res = fchownat(ifd, "", uid, gid, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW);
709 if (res == -1) {
710 goto out_err;
713 if (valid & FUSE_SET_ATTR_SIZE) {
714 int truncfd;
716 if (fi) {
717 truncfd = fd;
718 } else {
719 truncfd = lo_inode_open(lo, inode, O_RDWR);
720 if (truncfd < 0) {
721 errno = -truncfd;
722 goto out_err;
726 res = ftruncate(truncfd, attr->st_size);
727 if (!fi) {
728 saverr = errno;
729 close(truncfd);
730 errno = saverr;
732 if (res == -1) {
733 goto out_err;
736 if (valid & (FUSE_SET_ATTR_ATIME | FUSE_SET_ATTR_MTIME)) {
737 struct timespec tv[2];
739 tv[0].tv_sec = 0;
740 tv[1].tv_sec = 0;
741 tv[0].tv_nsec = UTIME_OMIT;
742 tv[1].tv_nsec = UTIME_OMIT;
744 if (valid & FUSE_SET_ATTR_ATIME_NOW) {
745 tv[0].tv_nsec = UTIME_NOW;
746 } else if (valid & FUSE_SET_ATTR_ATIME) {
747 tv[0] = attr->st_atim;
750 if (valid & FUSE_SET_ATTR_MTIME_NOW) {
751 tv[1].tv_nsec = UTIME_NOW;
752 } else if (valid & FUSE_SET_ATTR_MTIME) {
753 tv[1] = attr->st_mtim;
756 if (fi) {
757 res = futimens(fd, tv);
758 } else {
759 sprintf(procname, "%i", inode->fd);
760 res = utimensat(lo->proc_self_fd, procname, tv, 0);
762 if (res == -1) {
763 goto out_err;
766 lo_inode_put(lo, &inode);
768 return lo_getattr(req, ino, fi);
770 out_err:
771 saverr = errno;
772 lo_inode_put(lo, &inode);
773 fuse_reply_err(req, saverr);
776 static struct lo_inode *lo_find(struct lo_data *lo, struct stat *st,
777 uint64_t mnt_id)
779 struct lo_inode *p;
780 struct lo_key key = {
781 .ino = st->st_ino,
782 .dev = st->st_dev,
783 .mnt_id = mnt_id,
786 pthread_mutex_lock(&lo->mutex);
787 p = g_hash_table_lookup(lo->inodes, &key);
788 if (p) {
789 assert(p->nlookup > 0);
790 p->nlookup++;
791 g_atomic_int_inc(&p->refcount);
793 pthread_mutex_unlock(&lo->mutex);
795 return p;
798 /* value_destroy_func for posix_locks GHashTable */
799 static void posix_locks_value_destroy(gpointer data)
801 struct lo_inode_plock *plock = data;
804 * We had used open() for locks and had only one fd. So
805 * closing this fd should release all OFD locks.
807 close(plock->fd);
808 free(plock);
811 static int do_statx(struct lo_data *lo, int dirfd, const char *pathname,
812 struct stat *statbuf, int flags, uint64_t *mnt_id)
814 int res;
816 #if defined(CONFIG_STATX) && defined(STATX_MNT_ID)
817 if (lo->use_statx) {
818 struct statx statxbuf;
820 res = statx(dirfd, pathname, flags, STATX_BASIC_STATS | STATX_MNT_ID,
821 &statxbuf);
822 if (!res) {
823 memset(statbuf, 0, sizeof(*statbuf));
824 statbuf->st_dev = makedev(statxbuf.stx_dev_major,
825 statxbuf.stx_dev_minor);
826 statbuf->st_ino = statxbuf.stx_ino;
827 statbuf->st_mode = statxbuf.stx_mode;
828 statbuf->st_nlink = statxbuf.stx_nlink;
829 statbuf->st_uid = statxbuf.stx_uid;
830 statbuf->st_gid = statxbuf.stx_gid;
831 statbuf->st_rdev = makedev(statxbuf.stx_rdev_major,
832 statxbuf.stx_rdev_minor);
833 statbuf->st_size = statxbuf.stx_size;
834 statbuf->st_blksize = statxbuf.stx_blksize;
835 statbuf->st_blocks = statxbuf.stx_blocks;
836 statbuf->st_atim.tv_sec = statxbuf.stx_atime.tv_sec;
837 statbuf->st_atim.tv_nsec = statxbuf.stx_atime.tv_nsec;
838 statbuf->st_mtim.tv_sec = statxbuf.stx_mtime.tv_sec;
839 statbuf->st_mtim.tv_nsec = statxbuf.stx_mtime.tv_nsec;
840 statbuf->st_ctim.tv_sec = statxbuf.stx_ctime.tv_sec;
841 statbuf->st_ctim.tv_nsec = statxbuf.stx_ctime.tv_nsec;
843 if (statxbuf.stx_mask & STATX_MNT_ID) {
844 *mnt_id = statxbuf.stx_mnt_id;
845 } else {
846 *mnt_id = 0;
848 return 0;
849 } else if (errno != ENOSYS) {
850 return -1;
852 lo->use_statx = false;
853 /* fallback */
855 #endif
856 res = fstatat(dirfd, pathname, statbuf, flags);
857 if (res == -1) {
858 return -1;
860 *mnt_id = 0;
862 return 0;
866 * Increments nlookup on the inode on success. unref_inode_lolocked() must be
867 * called eventually to decrement nlookup again. If inodep is non-NULL, the
868 * inode pointer is stored and the caller must call lo_inode_put().
870 static int lo_do_lookup(fuse_req_t req, fuse_ino_t parent, const char *name,
871 struct fuse_entry_param *e,
872 struct lo_inode **inodep)
874 int newfd;
875 int res;
876 int saverr;
877 uint64_t mnt_id;
878 struct lo_data *lo = lo_data(req);
879 struct lo_inode *inode = NULL;
880 struct lo_inode *dir = lo_inode(req, parent);
882 if (inodep) {
883 *inodep = NULL; /* in case there is an error */
887 * name_to_handle_at() and open_by_handle_at() can reach here with fuse
888 * mount point in guest, but we don't have its inode info in the
889 * ino_map.
891 if (!dir) {
892 return ENOENT;
895 memset(e, 0, sizeof(*e));
896 e->attr_timeout = lo->timeout;
897 e->entry_timeout = lo->timeout;
899 /* Do not allow escaping root directory */
900 if (dir == &lo->root && strcmp(name, "..") == 0) {
901 name = ".";
904 newfd = openat(dir->fd, name, O_PATH | O_NOFOLLOW);
905 if (newfd == -1) {
906 goto out_err;
909 res = do_statx(lo, newfd, "", &e->attr, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW,
910 &mnt_id);
911 if (res == -1) {
912 goto out_err;
915 if (S_ISDIR(e->attr.st_mode) && lo->announce_submounts &&
916 (e->attr.st_dev != dir->key.dev || mnt_id != dir->key.mnt_id)) {
917 e->attr_flags |= FUSE_ATTR_SUBMOUNT;
920 inode = lo_find(lo, &e->attr, mnt_id);
921 if (inode) {
922 close(newfd);
923 } else {
924 inode = calloc(1, sizeof(struct lo_inode));
925 if (!inode) {
926 goto out_err;
929 /* cache only filetype */
930 inode->filetype = (e->attr.st_mode & S_IFMT);
933 * One for the caller and one for nlookup (released in
934 * unref_inode_lolocked())
936 g_atomic_int_set(&inode->refcount, 2);
938 inode->nlookup = 1;
939 inode->fd = newfd;
940 inode->key.ino = e->attr.st_ino;
941 inode->key.dev = e->attr.st_dev;
942 inode->key.mnt_id = mnt_id;
943 if (lo->posix_lock) {
944 pthread_mutex_init(&inode->plock_mutex, NULL);
945 inode->posix_locks = g_hash_table_new_full(
946 g_direct_hash, g_direct_equal, NULL, posix_locks_value_destroy);
948 pthread_mutex_lock(&lo->mutex);
949 inode->fuse_ino = lo_add_inode_mapping(req, inode);
950 g_hash_table_insert(lo->inodes, &inode->key, inode);
951 pthread_mutex_unlock(&lo->mutex);
953 e->ino = inode->fuse_ino;
955 /* Transfer ownership of inode pointer to caller or drop it */
956 if (inodep) {
957 *inodep = inode;
958 } else {
959 lo_inode_put(lo, &inode);
962 lo_inode_put(lo, &dir);
964 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
965 name, (unsigned long long)e->ino);
967 return 0;
969 out_err:
970 saverr = errno;
971 if (newfd != -1) {
972 close(newfd);
974 lo_inode_put(lo, &inode);
975 lo_inode_put(lo, &dir);
976 return saverr;
979 static void lo_lookup(fuse_req_t req, fuse_ino_t parent, const char *name)
981 struct fuse_entry_param e;
982 int err;
984 fuse_log(FUSE_LOG_DEBUG, "lo_lookup(parent=%" PRIu64 ", name=%s)\n", parent,
985 name);
988 * Don't use is_safe_path_component(), allow "." and ".." for NFS export
989 * support.
991 if (strchr(name, '/')) {
992 fuse_reply_err(req, EINVAL);
993 return;
996 err = lo_do_lookup(req, parent, name, &e, NULL);
997 if (err) {
998 fuse_reply_err(req, err);
999 } else {
1000 fuse_reply_entry(req, &e);
1005 * On some archs, setres*id is limited to 2^16 but they
1006 * provide setres*id32 variants that allow 2^32.
1007 * Others just let setres*id do 2^32 anyway.
1009 #ifdef SYS_setresgid32
1010 #define OURSYS_setresgid SYS_setresgid32
1011 #else
1012 #define OURSYS_setresgid SYS_setresgid
1013 #endif
1015 #ifdef SYS_setresuid32
1016 #define OURSYS_setresuid SYS_setresuid32
1017 #else
1018 #define OURSYS_setresuid SYS_setresuid
1019 #endif
1022 * Change to uid/gid of caller so that file is created with
1023 * ownership of caller.
1024 * TODO: What about selinux context?
1026 static int lo_change_cred(fuse_req_t req, struct lo_cred *old)
1028 int res;
1030 old->euid = geteuid();
1031 old->egid = getegid();
1033 res = syscall(OURSYS_setresgid, -1, fuse_req_ctx(req)->gid, -1);
1034 if (res == -1) {
1035 return errno;
1038 res = syscall(OURSYS_setresuid, -1, fuse_req_ctx(req)->uid, -1);
1039 if (res == -1) {
1040 int errno_save = errno;
1042 syscall(OURSYS_setresgid, -1, old->egid, -1);
1043 return errno_save;
1046 return 0;
1049 /* Regain Privileges */
1050 static void lo_restore_cred(struct lo_cred *old)
1052 int res;
1054 res = syscall(OURSYS_setresuid, -1, old->euid, -1);
1055 if (res == -1) {
1056 fuse_log(FUSE_LOG_ERR, "seteuid(%u): %m\n", old->euid);
1057 exit(1);
1060 res = syscall(OURSYS_setresgid, -1, old->egid, -1);
1061 if (res == -1) {
1062 fuse_log(FUSE_LOG_ERR, "setegid(%u): %m\n", old->egid);
1063 exit(1);
1067 static void lo_mknod_symlink(fuse_req_t req, fuse_ino_t parent,
1068 const char *name, mode_t mode, dev_t rdev,
1069 const char *link)
1071 int res;
1072 int saverr;
1073 struct lo_data *lo = lo_data(req);
1074 struct lo_inode *dir;
1075 struct fuse_entry_param e;
1076 struct lo_cred old = {};
1078 if (!is_safe_path_component(name)) {
1079 fuse_reply_err(req, EINVAL);
1080 return;
1083 dir = lo_inode(req, parent);
1084 if (!dir) {
1085 fuse_reply_err(req, EBADF);
1086 return;
1089 saverr = lo_change_cred(req, &old);
1090 if (saverr) {
1091 goto out;
1094 res = mknod_wrapper(dir->fd, name, link, mode, rdev);
1096 saverr = errno;
1098 lo_restore_cred(&old);
1100 if (res == -1) {
1101 goto out;
1104 saverr = lo_do_lookup(req, parent, name, &e, NULL);
1105 if (saverr) {
1106 goto out;
1109 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
1110 name, (unsigned long long)e.ino);
1112 fuse_reply_entry(req, &e);
1113 lo_inode_put(lo, &dir);
1114 return;
1116 out:
1117 lo_inode_put(lo, &dir);
1118 fuse_reply_err(req, saverr);
1121 static void lo_mknod(fuse_req_t req, fuse_ino_t parent, const char *name,
1122 mode_t mode, dev_t rdev)
1124 lo_mknod_symlink(req, parent, name, mode, rdev, NULL);
1127 static void lo_mkdir(fuse_req_t req, fuse_ino_t parent, const char *name,
1128 mode_t mode)
1130 lo_mknod_symlink(req, parent, name, S_IFDIR | mode, 0, NULL);
1133 static void lo_symlink(fuse_req_t req, const char *link, fuse_ino_t parent,
1134 const char *name)
1136 lo_mknod_symlink(req, parent, name, S_IFLNK, 0, link);
1139 static void lo_link(fuse_req_t req, fuse_ino_t ino, fuse_ino_t parent,
1140 const char *name)
1142 int res;
1143 struct lo_data *lo = lo_data(req);
1144 struct lo_inode *parent_inode;
1145 struct lo_inode *inode;
1146 struct fuse_entry_param e;
1147 char procname[64];
1148 int saverr;
1150 if (!is_safe_path_component(name)) {
1151 fuse_reply_err(req, EINVAL);
1152 return;
1155 parent_inode = lo_inode(req, parent);
1156 inode = lo_inode(req, ino);
1157 if (!parent_inode || !inode) {
1158 errno = EBADF;
1159 goto out_err;
1162 memset(&e, 0, sizeof(struct fuse_entry_param));
1163 e.attr_timeout = lo->timeout;
1164 e.entry_timeout = lo->timeout;
1166 sprintf(procname, "%i", inode->fd);
1167 res = linkat(lo->proc_self_fd, procname, parent_inode->fd, name,
1168 AT_SYMLINK_FOLLOW);
1169 if (res == -1) {
1170 goto out_err;
1173 res = fstatat(inode->fd, "", &e.attr, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW);
1174 if (res == -1) {
1175 goto out_err;
1178 pthread_mutex_lock(&lo->mutex);
1179 inode->nlookup++;
1180 pthread_mutex_unlock(&lo->mutex);
1181 e.ino = inode->fuse_ino;
1183 fuse_log(FUSE_LOG_DEBUG, " %lli/%s -> %lli\n", (unsigned long long)parent,
1184 name, (unsigned long long)e.ino);
1186 fuse_reply_entry(req, &e);
1187 lo_inode_put(lo, &parent_inode);
1188 lo_inode_put(lo, &inode);
1189 return;
1191 out_err:
1192 saverr = errno;
1193 lo_inode_put(lo, &parent_inode);
1194 lo_inode_put(lo, &inode);
1195 fuse_reply_err(req, saverr);
1198 /* Increments nlookup and caller must release refcount using lo_inode_put() */
1199 static struct lo_inode *lookup_name(fuse_req_t req, fuse_ino_t parent,
1200 const char *name)
1202 int res;
1203 uint64_t mnt_id;
1204 struct stat attr;
1205 struct lo_data *lo = lo_data(req);
1206 struct lo_inode *dir = lo_inode(req, parent);
1208 if (!dir) {
1209 return NULL;
1212 res = do_statx(lo, dir->fd, name, &attr,
1213 AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW, &mnt_id);
1214 lo_inode_put(lo, &dir);
1215 if (res == -1) {
1216 return NULL;
1219 return lo_find(lo, &attr, mnt_id);
1222 static void lo_rmdir(fuse_req_t req, fuse_ino_t parent, const char *name)
1224 int res;
1225 struct lo_inode *inode;
1226 struct lo_data *lo = lo_data(req);
1228 if (!is_safe_path_component(name)) {
1229 fuse_reply_err(req, EINVAL);
1230 return;
1233 inode = lookup_name(req, parent, name);
1234 if (!inode) {
1235 fuse_reply_err(req, EIO);
1236 return;
1239 res = unlinkat(lo_fd(req, parent), name, AT_REMOVEDIR);
1241 fuse_reply_err(req, res == -1 ? errno : 0);
1242 unref_inode_lolocked(lo, inode, 1);
1243 lo_inode_put(lo, &inode);
1246 static void lo_rename(fuse_req_t req, fuse_ino_t parent, const char *name,
1247 fuse_ino_t newparent, const char *newname,
1248 unsigned int flags)
1250 int res;
1251 struct lo_inode *parent_inode;
1252 struct lo_inode *newparent_inode;
1253 struct lo_inode *oldinode = NULL;
1254 struct lo_inode *newinode = NULL;
1255 struct lo_data *lo = lo_data(req);
1257 if (!is_safe_path_component(name) || !is_safe_path_component(newname)) {
1258 fuse_reply_err(req, EINVAL);
1259 return;
1262 parent_inode = lo_inode(req, parent);
1263 newparent_inode = lo_inode(req, newparent);
1264 if (!parent_inode || !newparent_inode) {
1265 fuse_reply_err(req, EBADF);
1266 goto out;
1269 oldinode = lookup_name(req, parent, name);
1270 newinode = lookup_name(req, newparent, newname);
1272 if (!oldinode) {
1273 fuse_reply_err(req, EIO);
1274 goto out;
1277 if (flags) {
1278 #ifndef SYS_renameat2
1279 fuse_reply_err(req, EINVAL);
1280 #else
1281 res = syscall(SYS_renameat2, parent_inode->fd, name,
1282 newparent_inode->fd, newname, flags);
1283 if (res == -1 && errno == ENOSYS) {
1284 fuse_reply_err(req, EINVAL);
1285 } else {
1286 fuse_reply_err(req, res == -1 ? errno : 0);
1288 #endif
1289 goto out;
1292 res = renameat(parent_inode->fd, name, newparent_inode->fd, newname);
1294 fuse_reply_err(req, res == -1 ? errno : 0);
1295 out:
1296 unref_inode_lolocked(lo, oldinode, 1);
1297 unref_inode_lolocked(lo, newinode, 1);
1298 lo_inode_put(lo, &oldinode);
1299 lo_inode_put(lo, &newinode);
1300 lo_inode_put(lo, &parent_inode);
1301 lo_inode_put(lo, &newparent_inode);
1304 static void lo_unlink(fuse_req_t req, fuse_ino_t parent, const char *name)
1306 int res;
1307 struct lo_inode *inode;
1308 struct lo_data *lo = lo_data(req);
1310 if (!is_safe_path_component(name)) {
1311 fuse_reply_err(req, EINVAL);
1312 return;
1315 inode = lookup_name(req, parent, name);
1316 if (!inode) {
1317 fuse_reply_err(req, EIO);
1318 return;
1321 res = unlinkat(lo_fd(req, parent), name, 0);
1323 fuse_reply_err(req, res == -1 ? errno : 0);
1324 unref_inode_lolocked(lo, inode, 1);
1325 lo_inode_put(lo, &inode);
1328 /* To be called with lo->mutex held */
1329 static void unref_inode(struct lo_data *lo, struct lo_inode *inode, uint64_t n)
1331 if (!inode) {
1332 return;
1335 assert(inode->nlookup >= n);
1336 inode->nlookup -= n;
1337 if (!inode->nlookup) {
1338 lo_map_remove(&lo->ino_map, inode->fuse_ino);
1339 g_hash_table_remove(lo->inodes, &inode->key);
1340 if (lo->posix_lock) {
1341 if (g_hash_table_size(inode->posix_locks)) {
1342 fuse_log(FUSE_LOG_WARNING, "Hash table is not empty\n");
1344 g_hash_table_destroy(inode->posix_locks);
1345 pthread_mutex_destroy(&inode->plock_mutex);
1347 /* Drop our refcount from lo_do_lookup() */
1348 lo_inode_put(lo, &inode);
1352 static void unref_inode_lolocked(struct lo_data *lo, struct lo_inode *inode,
1353 uint64_t n)
1355 if (!inode) {
1356 return;
1359 pthread_mutex_lock(&lo->mutex);
1360 unref_inode(lo, inode, n);
1361 pthread_mutex_unlock(&lo->mutex);
1364 static void lo_forget_one(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup)
1366 struct lo_data *lo = lo_data(req);
1367 struct lo_inode *inode;
1369 inode = lo_inode(req, ino);
1370 if (!inode) {
1371 return;
1374 fuse_log(FUSE_LOG_DEBUG, " forget %lli %lli -%lli\n",
1375 (unsigned long long)ino, (unsigned long long)inode->nlookup,
1376 (unsigned long long)nlookup);
1378 unref_inode_lolocked(lo, inode, nlookup);
1379 lo_inode_put(lo, &inode);
1382 static void lo_forget(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup)
1384 lo_forget_one(req, ino, nlookup);
1385 fuse_reply_none(req);
1388 static void lo_forget_multi(fuse_req_t req, size_t count,
1389 struct fuse_forget_data *forgets)
1391 int i;
1393 for (i = 0; i < count; i++) {
1394 lo_forget_one(req, forgets[i].ino, forgets[i].nlookup);
1396 fuse_reply_none(req);
1399 static void lo_readlink(fuse_req_t req, fuse_ino_t ino)
1401 char buf[PATH_MAX + 1];
1402 int res;
1404 res = readlinkat(lo_fd(req, ino), "", buf, sizeof(buf));
1405 if (res == -1) {
1406 return (void)fuse_reply_err(req, errno);
1409 if (res == sizeof(buf)) {
1410 return (void)fuse_reply_err(req, ENAMETOOLONG);
1413 buf[res] = '\0';
1415 fuse_reply_readlink(req, buf);
1418 struct lo_dirp {
1419 gint refcount;
1420 DIR *dp;
1421 struct dirent *entry;
1422 off_t offset;
1425 static void lo_dirp_put(struct lo_dirp **dp)
1427 struct lo_dirp *d = *dp;
1429 if (!d) {
1430 return;
1432 *dp = NULL;
1434 if (g_atomic_int_dec_and_test(&d->refcount)) {
1435 closedir(d->dp);
1436 free(d);
1440 /* Call lo_dirp_put() on the return value when no longer needed */
1441 static struct lo_dirp *lo_dirp(fuse_req_t req, struct fuse_file_info *fi)
1443 struct lo_data *lo = lo_data(req);
1444 struct lo_map_elem *elem;
1446 pthread_mutex_lock(&lo->mutex);
1447 elem = lo_map_get(&lo->dirp_map, fi->fh);
1448 if (elem) {
1449 g_atomic_int_inc(&elem->dirp->refcount);
1451 pthread_mutex_unlock(&lo->mutex);
1452 if (!elem) {
1453 return NULL;
1456 return elem->dirp;
1459 static void lo_opendir(fuse_req_t req, fuse_ino_t ino,
1460 struct fuse_file_info *fi)
1462 int error = ENOMEM;
1463 struct lo_data *lo = lo_data(req);
1464 struct lo_dirp *d;
1465 int fd;
1466 ssize_t fh;
1468 d = calloc(1, sizeof(struct lo_dirp));
1469 if (d == NULL) {
1470 goto out_err;
1473 fd = openat(lo_fd(req, ino), ".", O_RDONLY);
1474 if (fd == -1) {
1475 goto out_errno;
1478 d->dp = fdopendir(fd);
1479 if (d->dp == NULL) {
1480 goto out_errno;
1483 d->offset = 0;
1484 d->entry = NULL;
1486 g_atomic_int_set(&d->refcount, 1); /* paired with lo_releasedir() */
1487 pthread_mutex_lock(&lo->mutex);
1488 fh = lo_add_dirp_mapping(req, d);
1489 pthread_mutex_unlock(&lo->mutex);
1490 if (fh == -1) {
1491 goto out_err;
1494 fi->fh = fh;
1495 if (lo->cache == CACHE_ALWAYS) {
1496 fi->cache_readdir = 1;
1498 fuse_reply_open(req, fi);
1499 return;
1501 out_errno:
1502 error = errno;
1503 out_err:
1504 if (d) {
1505 if (d->dp) {
1506 closedir(d->dp);
1507 } else if (fd != -1) {
1508 close(fd);
1510 free(d);
1512 fuse_reply_err(req, error);
1515 static void lo_do_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
1516 off_t offset, struct fuse_file_info *fi, int plus)
1518 struct lo_data *lo = lo_data(req);
1519 struct lo_dirp *d = NULL;
1520 struct lo_inode *dinode;
1521 char *buf = NULL;
1522 char *p;
1523 size_t rem = size;
1524 int err = EBADF;
1526 dinode = lo_inode(req, ino);
1527 if (!dinode) {
1528 goto error;
1531 d = lo_dirp(req, fi);
1532 if (!d) {
1533 goto error;
1536 err = ENOMEM;
1537 buf = calloc(1, size);
1538 if (!buf) {
1539 goto error;
1541 p = buf;
1543 if (offset != d->offset) {
1544 seekdir(d->dp, offset);
1545 d->entry = NULL;
1546 d->offset = offset;
1548 while (1) {
1549 size_t entsize;
1550 off_t nextoff;
1551 const char *name;
1553 if (!d->entry) {
1554 errno = 0;
1555 d->entry = readdir(d->dp);
1556 if (!d->entry) {
1557 if (errno) { /* Error */
1558 err = errno;
1559 goto error;
1560 } else { /* End of stream */
1561 break;
1565 nextoff = d->entry->d_off;
1566 name = d->entry->d_name;
1568 fuse_ino_t entry_ino = 0;
1569 struct fuse_entry_param e = (struct fuse_entry_param){
1570 .attr.st_ino = d->entry->d_ino,
1571 .attr.st_mode = d->entry->d_type << 12,
1574 /* Hide root's parent directory */
1575 if (dinode == &lo->root && strcmp(name, "..") == 0) {
1576 e.attr.st_ino = lo->root.key.ino;
1577 e.attr.st_mode = DT_DIR << 12;
1580 if (plus) {
1581 if (!is_dot_or_dotdot(name)) {
1582 err = lo_do_lookup(req, ino, name, &e, NULL);
1583 if (err) {
1584 goto error;
1586 entry_ino = e.ino;
1589 entsize = fuse_add_direntry_plus(req, p, rem, name, &e, nextoff);
1590 } else {
1591 entsize = fuse_add_direntry(req, p, rem, name, &e.attr, nextoff);
1593 if (entsize > rem) {
1594 if (entry_ino != 0) {
1595 lo_forget_one(req, entry_ino, 1);
1597 break;
1600 p += entsize;
1601 rem -= entsize;
1603 d->entry = NULL;
1604 d->offset = nextoff;
1607 err = 0;
1608 error:
1609 lo_dirp_put(&d);
1610 lo_inode_put(lo, &dinode);
1613 * If there's an error, we can only signal it if we haven't stored
1614 * any entries yet - otherwise we'd end up with wrong lookup
1615 * counts for the entries that are already in the buffer. So we
1616 * return what we've collected until that point.
1618 if (err && rem == size) {
1619 fuse_reply_err(req, err);
1620 } else {
1621 fuse_reply_buf(req, buf, size - rem);
1623 free(buf);
1626 static void lo_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
1627 off_t offset, struct fuse_file_info *fi)
1629 lo_do_readdir(req, ino, size, offset, fi, 0);
1632 static void lo_readdirplus(fuse_req_t req, fuse_ino_t ino, size_t size,
1633 off_t offset, struct fuse_file_info *fi)
1635 lo_do_readdir(req, ino, size, offset, fi, 1);
1638 static void lo_releasedir(fuse_req_t req, fuse_ino_t ino,
1639 struct fuse_file_info *fi)
1641 struct lo_data *lo = lo_data(req);
1642 struct lo_map_elem *elem;
1643 struct lo_dirp *d;
1645 (void)ino;
1647 pthread_mutex_lock(&lo->mutex);
1648 elem = lo_map_get(&lo->dirp_map, fi->fh);
1649 if (!elem) {
1650 pthread_mutex_unlock(&lo->mutex);
1651 fuse_reply_err(req, EBADF);
1652 return;
1655 d = elem->dirp;
1656 lo_map_remove(&lo->dirp_map, fi->fh);
1657 pthread_mutex_unlock(&lo->mutex);
1659 lo_dirp_put(&d); /* paired with lo_opendir() */
1661 fuse_reply_err(req, 0);
1664 static void update_open_flags(int writeback, int allow_direct_io,
1665 struct fuse_file_info *fi)
1668 * With writeback cache, kernel may send read requests even
1669 * when userspace opened write-only
1671 if (writeback && (fi->flags & O_ACCMODE) == O_WRONLY) {
1672 fi->flags &= ~O_ACCMODE;
1673 fi->flags |= O_RDWR;
1677 * With writeback cache, O_APPEND is handled by the kernel.
1678 * This breaks atomicity (since the file may change in the
1679 * underlying filesystem, so that the kernel's idea of the
1680 * end of the file isn't accurate anymore). In this example,
1681 * we just accept that. A more rigorous filesystem may want
1682 * to return an error here
1684 if (writeback && (fi->flags & O_APPEND)) {
1685 fi->flags &= ~O_APPEND;
1689 * O_DIRECT in guest should not necessarily mean bypassing page
1690 * cache on host as well. Therefore, we discard it by default
1691 * ('-o no_allow_direct_io'). If somebody needs that behavior,
1692 * the '-o allow_direct_io' option should be set.
1694 if (!allow_direct_io) {
1695 fi->flags &= ~O_DIRECT;
1700 * Open a regular file, set up an fd mapping, and fill out the struct
1701 * fuse_file_info for it. If existing_fd is not negative, use that fd instead
1702 * opening a new one. Takes ownership of existing_fd.
1704 * Returns 0 on success or a positive errno.
1706 static int lo_do_open(struct lo_data *lo, struct lo_inode *inode,
1707 int existing_fd, struct fuse_file_info *fi)
1709 ssize_t fh;
1710 int fd = existing_fd;
1712 update_open_flags(lo->writeback, lo->allow_direct_io, fi);
1714 if (fd < 0) {
1715 fd = lo_inode_open(lo, inode, fi->flags);
1716 if (fd < 0) {
1717 return -fd;
1721 pthread_mutex_lock(&lo->mutex);
1722 fh = lo_add_fd_mapping(lo, fd);
1723 pthread_mutex_unlock(&lo->mutex);
1724 if (fh == -1) {
1725 close(fd);
1726 return ENOMEM;
1729 fi->fh = fh;
1730 if (lo->cache == CACHE_NONE) {
1731 fi->direct_io = 1;
1732 } else if (lo->cache == CACHE_ALWAYS) {
1733 fi->keep_cache = 1;
1735 return 0;
1738 static void lo_create(fuse_req_t req, fuse_ino_t parent, const char *name,
1739 mode_t mode, struct fuse_file_info *fi)
1741 int fd = -1;
1742 struct lo_data *lo = lo_data(req);
1743 struct lo_inode *parent_inode;
1744 struct lo_inode *inode = NULL;
1745 struct fuse_entry_param e;
1746 int err;
1747 struct lo_cred old = {};
1749 fuse_log(FUSE_LOG_DEBUG, "lo_create(parent=%" PRIu64 ", name=%s)\n", parent,
1750 name);
1752 if (!is_safe_path_component(name)) {
1753 fuse_reply_err(req, EINVAL);
1754 return;
1757 parent_inode = lo_inode(req, parent);
1758 if (!parent_inode) {
1759 fuse_reply_err(req, EBADF);
1760 return;
1763 err = lo_change_cred(req, &old);
1764 if (err) {
1765 goto out;
1768 update_open_flags(lo->writeback, lo->allow_direct_io, fi);
1770 /* Try to create a new file but don't open existing files */
1771 fd = openat(parent_inode->fd, name, fi->flags | O_CREAT | O_EXCL, mode);
1772 err = fd == -1 ? errno : 0;
1774 lo_restore_cred(&old);
1776 /* Ignore the error if file exists and O_EXCL was not given */
1777 if (err && (err != EEXIST || (fi->flags & O_EXCL))) {
1778 goto out;
1781 err = lo_do_lookup(req, parent, name, &e, &inode);
1782 if (err) {
1783 goto out;
1786 err = lo_do_open(lo, inode, fd, fi);
1787 fd = -1; /* lo_do_open() takes ownership of fd */
1788 if (err) {
1789 /* Undo lo_do_lookup() nlookup ref */
1790 unref_inode_lolocked(lo, inode, 1);
1793 out:
1794 lo_inode_put(lo, &inode);
1795 lo_inode_put(lo, &parent_inode);
1797 if (err) {
1798 if (fd >= 0) {
1799 close(fd);
1802 fuse_reply_err(req, err);
1803 } else {
1804 fuse_reply_create(req, &e, fi);
1808 /* Should be called with inode->plock_mutex held */
1809 static struct lo_inode_plock *lookup_create_plock_ctx(struct lo_data *lo,
1810 struct lo_inode *inode,
1811 uint64_t lock_owner,
1812 pid_t pid, int *err)
1814 struct lo_inode_plock *plock;
1815 int fd;
1817 plock =
1818 g_hash_table_lookup(inode->posix_locks, GUINT_TO_POINTER(lock_owner));
1820 if (plock) {
1821 return plock;
1824 plock = malloc(sizeof(struct lo_inode_plock));
1825 if (!plock) {
1826 *err = ENOMEM;
1827 return NULL;
1830 /* Open another instance of file which can be used for ofd locks. */
1831 /* TODO: What if file is not writable? */
1832 fd = lo_inode_open(lo, inode, O_RDWR);
1833 if (fd < 0) {
1834 *err = -fd;
1835 free(plock);
1836 return NULL;
1839 plock->lock_owner = lock_owner;
1840 plock->fd = fd;
1841 g_hash_table_insert(inode->posix_locks, GUINT_TO_POINTER(plock->lock_owner),
1842 plock);
1843 return plock;
1846 static void lo_getlk(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
1847 struct flock *lock)
1849 struct lo_data *lo = lo_data(req);
1850 struct lo_inode *inode;
1851 struct lo_inode_plock *plock;
1852 int ret, saverr = 0;
1854 fuse_log(FUSE_LOG_DEBUG,
1855 "lo_getlk(ino=%" PRIu64 ", flags=%d)"
1856 " owner=0x%lx, l_type=%d l_start=0x%lx"
1857 " l_len=0x%lx\n",
1858 ino, fi->flags, fi->lock_owner, lock->l_type, lock->l_start,
1859 lock->l_len);
1861 if (!lo->posix_lock) {
1862 fuse_reply_err(req, ENOSYS);
1863 return;
1866 inode = lo_inode(req, ino);
1867 if (!inode) {
1868 fuse_reply_err(req, EBADF);
1869 return;
1872 pthread_mutex_lock(&inode->plock_mutex);
1873 plock =
1874 lookup_create_plock_ctx(lo, inode, fi->lock_owner, lock->l_pid, &ret);
1875 if (!plock) {
1876 saverr = ret;
1877 goto out;
1880 ret = fcntl(plock->fd, F_OFD_GETLK, lock);
1881 if (ret == -1) {
1882 saverr = errno;
1885 out:
1886 pthread_mutex_unlock(&inode->plock_mutex);
1887 lo_inode_put(lo, &inode);
1889 if (saverr) {
1890 fuse_reply_err(req, saverr);
1891 } else {
1892 fuse_reply_lock(req, lock);
1896 static void lo_setlk(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
1897 struct flock *lock, int sleep)
1899 struct lo_data *lo = lo_data(req);
1900 struct lo_inode *inode;
1901 struct lo_inode_plock *plock;
1902 int ret, saverr = 0;
1904 fuse_log(FUSE_LOG_DEBUG,
1905 "lo_setlk(ino=%" PRIu64 ", flags=%d)"
1906 " cmd=%d pid=%d owner=0x%lx sleep=%d l_whence=%d"
1907 " l_start=0x%lx l_len=0x%lx\n",
1908 ino, fi->flags, lock->l_type, lock->l_pid, fi->lock_owner, sleep,
1909 lock->l_whence, lock->l_start, lock->l_len);
1911 if (!lo->posix_lock) {
1912 fuse_reply_err(req, ENOSYS);
1913 return;
1916 if (sleep) {
1917 fuse_reply_err(req, EOPNOTSUPP);
1918 return;
1921 inode = lo_inode(req, ino);
1922 if (!inode) {
1923 fuse_reply_err(req, EBADF);
1924 return;
1927 pthread_mutex_lock(&inode->plock_mutex);
1928 plock =
1929 lookup_create_plock_ctx(lo, inode, fi->lock_owner, lock->l_pid, &ret);
1931 if (!plock) {
1932 saverr = ret;
1933 goto out;
1936 /* TODO: Is it alright to modify flock? */
1937 lock->l_pid = 0;
1938 ret = fcntl(plock->fd, F_OFD_SETLK, lock);
1939 if (ret == -1) {
1940 saverr = errno;
1943 out:
1944 pthread_mutex_unlock(&inode->plock_mutex);
1945 lo_inode_put(lo, &inode);
1947 fuse_reply_err(req, saverr);
1950 static void lo_fsyncdir(fuse_req_t req, fuse_ino_t ino, int datasync,
1951 struct fuse_file_info *fi)
1953 int res;
1954 struct lo_dirp *d;
1955 int fd;
1957 (void)ino;
1959 d = lo_dirp(req, fi);
1960 if (!d) {
1961 fuse_reply_err(req, EBADF);
1962 return;
1965 fd = dirfd(d->dp);
1966 if (datasync) {
1967 res = fdatasync(fd);
1968 } else {
1969 res = fsync(fd);
1972 lo_dirp_put(&d);
1974 fuse_reply_err(req, res == -1 ? errno : 0);
1977 static void lo_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi)
1979 struct lo_data *lo = lo_data(req);
1980 struct lo_inode *inode = lo_inode(req, ino);
1981 int err;
1983 fuse_log(FUSE_LOG_DEBUG, "lo_open(ino=%" PRIu64 ", flags=%d)\n", ino,
1984 fi->flags);
1986 if (!inode) {
1987 fuse_reply_err(req, EBADF);
1988 return;
1991 err = lo_do_open(lo, inode, -1, fi);
1992 lo_inode_put(lo, &inode);
1993 if (err) {
1994 fuse_reply_err(req, err);
1995 } else {
1996 fuse_reply_open(req, fi);
2000 static void lo_release(fuse_req_t req, fuse_ino_t ino,
2001 struct fuse_file_info *fi)
2003 struct lo_data *lo = lo_data(req);
2004 struct lo_map_elem *elem;
2005 int fd = -1;
2007 (void)ino;
2009 pthread_mutex_lock(&lo->mutex);
2010 elem = lo_map_get(&lo->fd_map, fi->fh);
2011 if (elem) {
2012 fd = elem->fd;
2013 elem = NULL;
2014 lo_map_remove(&lo->fd_map, fi->fh);
2016 pthread_mutex_unlock(&lo->mutex);
2018 close(fd);
2019 fuse_reply_err(req, 0);
2022 static void lo_flush(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi)
2024 int res;
2025 (void)ino;
2026 struct lo_inode *inode;
2027 struct lo_data *lo = lo_data(req);
2029 inode = lo_inode(req, ino);
2030 if (!inode) {
2031 fuse_reply_err(req, EBADF);
2032 return;
2035 if (!S_ISREG(inode->filetype)) {
2036 lo_inode_put(lo, &inode);
2037 fuse_reply_err(req, EBADF);
2038 return;
2041 /* An fd is going away. Cleanup associated posix locks */
2042 if (lo->posix_lock) {
2043 pthread_mutex_lock(&inode->plock_mutex);
2044 g_hash_table_remove(inode->posix_locks,
2045 GUINT_TO_POINTER(fi->lock_owner));
2046 pthread_mutex_unlock(&inode->plock_mutex);
2048 res = close(dup(lo_fi_fd(req, fi)));
2049 lo_inode_put(lo, &inode);
2050 fuse_reply_err(req, res == -1 ? errno : 0);
2053 static void lo_fsync(fuse_req_t req, fuse_ino_t ino, int datasync,
2054 struct fuse_file_info *fi)
2056 struct lo_inode *inode = lo_inode(req, ino);
2057 struct lo_data *lo = lo_data(req);
2058 int res;
2059 int fd;
2061 fuse_log(FUSE_LOG_DEBUG, "lo_fsync(ino=%" PRIu64 ", fi=0x%p)\n", ino,
2062 (void *)fi);
2064 if (!inode) {
2065 fuse_reply_err(req, EBADF);
2066 return;
2069 if (!fi) {
2070 fd = lo_inode_open(lo, inode, O_RDWR);
2071 if (fd < 0) {
2072 res = -fd;
2073 goto out;
2075 } else {
2076 fd = lo_fi_fd(req, fi);
2079 if (datasync) {
2080 res = fdatasync(fd) == -1 ? errno : 0;
2081 } else {
2082 res = fsync(fd) == -1 ? errno : 0;
2084 if (!fi) {
2085 close(fd);
2087 out:
2088 lo_inode_put(lo, &inode);
2089 fuse_reply_err(req, res);
2092 static void lo_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t offset,
2093 struct fuse_file_info *fi)
2095 struct fuse_bufvec buf = FUSE_BUFVEC_INIT(size);
2097 fuse_log(FUSE_LOG_DEBUG,
2098 "lo_read(ino=%" PRIu64 ", size=%zd, "
2099 "off=%lu)\n",
2100 ino, size, (unsigned long)offset);
2102 buf.buf[0].flags = FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK;
2103 buf.buf[0].fd = lo_fi_fd(req, fi);
2104 buf.buf[0].pos = offset;
2106 fuse_reply_data(req, &buf);
2109 static void lo_write_buf(fuse_req_t req, fuse_ino_t ino,
2110 struct fuse_bufvec *in_buf, off_t off,
2111 struct fuse_file_info *fi)
2113 (void)ino;
2114 ssize_t res;
2115 struct fuse_bufvec out_buf = FUSE_BUFVEC_INIT(fuse_buf_size(in_buf));
2116 bool cap_fsetid_dropped = false;
2118 out_buf.buf[0].flags = FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK;
2119 out_buf.buf[0].fd = lo_fi_fd(req, fi);
2120 out_buf.buf[0].pos = off;
2122 fuse_log(FUSE_LOG_DEBUG,
2123 "lo_write_buf(ino=%" PRIu64 ", size=%zd, off=%lu)\n", ino,
2124 out_buf.buf[0].size, (unsigned long)off);
2127 * If kill_priv is set, drop CAP_FSETID which should lead to kernel
2128 * clearing setuid/setgid on file.
2130 if (fi->kill_priv) {
2131 res = drop_effective_cap("FSETID", &cap_fsetid_dropped);
2132 if (res != 0) {
2133 fuse_reply_err(req, res);
2134 return;
2138 res = fuse_buf_copy(&out_buf, in_buf);
2139 if (res < 0) {
2140 fuse_reply_err(req, -res);
2141 } else {
2142 fuse_reply_write(req, (size_t)res);
2145 if (cap_fsetid_dropped) {
2146 res = gain_effective_cap("FSETID");
2147 if (res) {
2148 fuse_log(FUSE_LOG_ERR, "Failed to gain CAP_FSETID\n");
2153 static void lo_statfs(fuse_req_t req, fuse_ino_t ino)
2155 int res;
2156 struct statvfs stbuf;
2158 res = fstatvfs(lo_fd(req, ino), &stbuf);
2159 if (res == -1) {
2160 fuse_reply_err(req, errno);
2161 } else {
2162 fuse_reply_statfs(req, &stbuf);
2166 static void lo_fallocate(fuse_req_t req, fuse_ino_t ino, int mode, off_t offset,
2167 off_t length, struct fuse_file_info *fi)
2169 int err = EOPNOTSUPP;
2170 (void)ino;
2172 #ifdef CONFIG_FALLOCATE
2173 err = fallocate(lo_fi_fd(req, fi), mode, offset, length);
2174 if (err < 0) {
2175 err = errno;
2178 #elif defined(CONFIG_POSIX_FALLOCATE)
2179 if (mode) {
2180 fuse_reply_err(req, EOPNOTSUPP);
2181 return;
2184 err = posix_fallocate(lo_fi_fd(req, fi), offset, length);
2185 #endif
2187 fuse_reply_err(req, err);
2190 static void lo_flock(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi,
2191 int op)
2193 int res;
2194 (void)ino;
2196 res = flock(lo_fi_fd(req, fi), op);
2198 fuse_reply_err(req, res == -1 ? errno : 0);
2201 /* types */
2203 * Exit; process attribute unmodified if matched.
2204 * An empty key applies to all.
2206 #define XATTR_MAP_FLAG_OK (1 << 0)
2208 * The attribute is unwanted;
2209 * EPERM on write, hidden on read.
2211 #define XATTR_MAP_FLAG_BAD (1 << 1)
2213 * For attr that start with 'key' prepend 'prepend'
2214 * 'key' may be empty to prepend for all attrs
2215 * key is defined from set/remove point of view.
2216 * Automatically reversed on read
2218 #define XATTR_MAP_FLAG_PREFIX (1 << 2)
2220 /* scopes */
2221 /* Apply rule to get/set/remove */
2222 #define XATTR_MAP_FLAG_CLIENT (1 << 16)
2223 /* Apply rule to list */
2224 #define XATTR_MAP_FLAG_SERVER (1 << 17)
2225 /* Apply rule to all */
2226 #define XATTR_MAP_FLAG_ALL (XATTR_MAP_FLAG_SERVER | XATTR_MAP_FLAG_CLIENT)
2228 static void add_xattrmap_entry(struct lo_data *lo,
2229 const XattrMapEntry *new_entry)
2231 XattrMapEntry *res = g_realloc_n(lo->xattr_map_list,
2232 lo->xattr_map_nentries + 1,
2233 sizeof(XattrMapEntry));
2234 res[lo->xattr_map_nentries++] = *new_entry;
2236 lo->xattr_map_list = res;
2239 static void free_xattrmap(struct lo_data *lo)
2241 XattrMapEntry *map = lo->xattr_map_list;
2242 size_t i;
2244 if (!map) {
2245 return;
2248 for (i = 0; i < lo->xattr_map_nentries; i++) {
2249 g_free(map[i].key);
2250 g_free(map[i].prepend);
2253 g_free(map);
2254 lo->xattr_map_list = NULL;
2255 lo->xattr_map_nentries = -1;
2259 * Handle the 'map' type, which is sugar for a set of commands
2260 * for the common case of prefixing a subset or everything,
2261 * and allowing anything not prefixed through.
2262 * It must be the last entry in the stream, although there
2263 * can be other entries before it.
2264 * The form is:
2265 * :map:key:prefix:
2267 * key maybe empty in which case all entries are prefixed.
2269 static void parse_xattrmap_map(struct lo_data *lo,
2270 const char *rule, char sep)
2272 const char *tmp;
2273 char *key;
2274 char *prefix;
2275 XattrMapEntry tmp_entry;
2277 if (*rule != sep) {
2278 fuse_log(FUSE_LOG_ERR,
2279 "%s: Expecting '%c' after 'map' keyword, found '%c'\n",
2280 __func__, sep, *rule);
2281 exit(1);
2284 rule++;
2286 /* At start of 'key' field */
2287 tmp = strchr(rule, sep);
2288 if (!tmp) {
2289 fuse_log(FUSE_LOG_ERR,
2290 "%s: Missing '%c' at end of key field in map rule\n",
2291 __func__, sep);
2292 exit(1);
2295 key = g_strndup(rule, tmp - rule);
2296 rule = tmp + 1;
2298 /* At start of prefix field */
2299 tmp = strchr(rule, sep);
2300 if (!tmp) {
2301 fuse_log(FUSE_LOG_ERR,
2302 "%s: Missing '%c' at end of prefix field in map rule\n",
2303 __func__, sep);
2304 exit(1);
2307 prefix = g_strndup(rule, tmp - rule);
2308 rule = tmp + 1;
2311 * This should be the end of the string, we don't allow
2312 * any more commands after 'map'.
2314 if (*rule) {
2315 fuse_log(FUSE_LOG_ERR,
2316 "%s: Expecting end of command after map, found '%c'\n",
2317 __func__, *rule);
2318 exit(1);
2321 /* 1st: Prefix matches/everything */
2322 tmp_entry.flags = XATTR_MAP_FLAG_PREFIX | XATTR_MAP_FLAG_ALL;
2323 tmp_entry.key = g_strdup(key);
2324 tmp_entry.prepend = g_strdup(prefix);
2325 add_xattrmap_entry(lo, &tmp_entry);
2327 if (!*key) {
2328 /* Prefix all case */
2330 /* 2nd: Hide any non-prefixed entries on the host */
2331 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_ALL;
2332 tmp_entry.key = g_strdup("");
2333 tmp_entry.prepend = g_strdup("");
2334 add_xattrmap_entry(lo, &tmp_entry);
2335 } else {
2336 /* Prefix matching case */
2338 /* 2nd: Hide non-prefixed but matching entries on the host */
2339 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_SERVER;
2340 tmp_entry.key = g_strdup(""); /* Not used */
2341 tmp_entry.prepend = g_strdup(key);
2342 add_xattrmap_entry(lo, &tmp_entry);
2344 /* 3rd: Stop the client accessing prefixed attributes directly */
2345 tmp_entry.flags = XATTR_MAP_FLAG_BAD | XATTR_MAP_FLAG_CLIENT;
2346 tmp_entry.key = g_strdup(prefix);
2347 tmp_entry.prepend = g_strdup(""); /* Not used */
2348 add_xattrmap_entry(lo, &tmp_entry);
2350 /* 4th: Everything else is OK */
2351 tmp_entry.flags = XATTR_MAP_FLAG_OK | XATTR_MAP_FLAG_ALL;
2352 tmp_entry.key = g_strdup("");
2353 tmp_entry.prepend = g_strdup("");
2354 add_xattrmap_entry(lo, &tmp_entry);
2357 g_free(key);
2358 g_free(prefix);
2361 static void parse_xattrmap(struct lo_data *lo)
2363 const char *map = lo->xattrmap;
2364 const char *tmp;
2366 lo->xattr_map_nentries = 0;
2367 while (*map) {
2368 XattrMapEntry tmp_entry;
2369 char sep;
2371 if (isspace(*map)) {
2372 map++;
2373 continue;
2375 /* The separator is the first non-space of the rule */
2376 sep = *map++;
2377 if (!sep) {
2378 break;
2381 tmp_entry.flags = 0;
2382 /* Start of 'type' */
2383 if (strstart(map, "prefix", &map)) {
2384 tmp_entry.flags |= XATTR_MAP_FLAG_PREFIX;
2385 } else if (strstart(map, "ok", &map)) {
2386 tmp_entry.flags |= XATTR_MAP_FLAG_OK;
2387 } else if (strstart(map, "bad", &map)) {
2388 tmp_entry.flags |= XATTR_MAP_FLAG_BAD;
2389 } else if (strstart(map, "map", &map)) {
2391 * map is sugar that adds a number of rules, and must be
2392 * the last entry.
2394 parse_xattrmap_map(lo, map, sep);
2395 return;
2396 } else {
2397 fuse_log(FUSE_LOG_ERR,
2398 "%s: Unexpected type;"
2399 "Expecting 'prefix', 'ok', 'bad' or 'map' in rule %zu\n",
2400 __func__, lo->xattr_map_nentries);
2401 exit(1);
2404 if (*map++ != sep) {
2405 fuse_log(FUSE_LOG_ERR,
2406 "%s: Missing '%c' at end of type field of rule %zu\n",
2407 __func__, sep, lo->xattr_map_nentries);
2408 exit(1);
2411 /* Start of 'scope' */
2412 if (strstart(map, "client", &map)) {
2413 tmp_entry.flags |= XATTR_MAP_FLAG_CLIENT;
2414 } else if (strstart(map, "server", &map)) {
2415 tmp_entry.flags |= XATTR_MAP_FLAG_SERVER;
2416 } else if (strstart(map, "all", &map)) {
2417 tmp_entry.flags |= XATTR_MAP_FLAG_ALL;
2418 } else {
2419 fuse_log(FUSE_LOG_ERR,
2420 "%s: Unexpected scope;"
2421 " Expecting 'client', 'server', or 'all', in rule %zu\n",
2422 __func__, lo->xattr_map_nentries);
2423 exit(1);
2426 if (*map++ != sep) {
2427 fuse_log(FUSE_LOG_ERR,
2428 "%s: Expecting '%c' found '%c'"
2429 " after scope in rule %zu\n",
2430 __func__, sep, *map, lo->xattr_map_nentries);
2431 exit(1);
2434 /* At start of 'key' field */
2435 tmp = strchr(map, sep);
2436 if (!tmp) {
2437 fuse_log(FUSE_LOG_ERR,
2438 "%s: Missing '%c' at end of key field of rule %zu",
2439 __func__, sep, lo->xattr_map_nentries);
2440 exit(1);
2442 tmp_entry.key = g_strndup(map, tmp - map);
2443 map = tmp + 1;
2445 /* At start of 'prepend' field */
2446 tmp = strchr(map, sep);
2447 if (!tmp) {
2448 fuse_log(FUSE_LOG_ERR,
2449 "%s: Missing '%c' at end of prepend field of rule %zu",
2450 __func__, sep, lo->xattr_map_nentries);
2451 exit(1);
2453 tmp_entry.prepend = g_strndup(map, tmp - map);
2454 map = tmp + 1;
2456 add_xattrmap_entry(lo, &tmp_entry);
2457 /* End of rule - go around again for another rule */
2460 if (!lo->xattr_map_nentries) {
2461 fuse_log(FUSE_LOG_ERR, "Empty xattr map\n");
2462 exit(1);
2467 * For use with getxattr/setxattr/removexattr, where the client
2468 * gives us a name and we may need to choose a different one.
2469 * Allocates a buffer for the result placing it in *out_name.
2470 * If there's no change then *out_name is not set.
2471 * Returns 0 on success
2472 * Can return -EPERM to indicate we block a given attribute
2473 * (in which case out_name is not allocated)
2474 * Can return -ENOMEM to indicate out_name couldn't be allocated.
2476 static int xattr_map_client(const struct lo_data *lo, const char *client_name,
2477 char **out_name)
2479 size_t i;
2480 for (i = 0; i < lo->xattr_map_nentries; i++) {
2481 const XattrMapEntry *cur_entry = lo->xattr_map_list + i;
2483 if ((cur_entry->flags & XATTR_MAP_FLAG_CLIENT) &&
2484 (strstart(client_name, cur_entry->key, NULL))) {
2485 if (cur_entry->flags & XATTR_MAP_FLAG_BAD) {
2486 return -EPERM;
2488 if (cur_entry->flags & XATTR_MAP_FLAG_OK) {
2489 /* Unmodified name */
2490 return 0;
2492 if (cur_entry->flags & XATTR_MAP_FLAG_PREFIX) {
2493 *out_name = g_try_malloc(strlen(client_name) +
2494 strlen(cur_entry->prepend) + 1);
2495 if (!*out_name) {
2496 return -ENOMEM;
2498 sprintf(*out_name, "%s%s", cur_entry->prepend, client_name);
2499 return 0;
2504 return -EPERM;
2508 * For use with listxattr where the server fs gives us a name and we may need
2509 * to sanitize this for the client.
2510 * Returns a pointer to the result in *out_name
2511 * This is always the original string or the current string with some prefix
2512 * removed; no reallocation is done.
2513 * Returns 0 on success
2514 * Can return -ENODATA to indicate the name should be dropped from the list.
2516 static int xattr_map_server(const struct lo_data *lo, const char *server_name,
2517 const char **out_name)
2519 size_t i;
2520 const char *end;
2522 for (i = 0; i < lo->xattr_map_nentries; i++) {
2523 const XattrMapEntry *cur_entry = lo->xattr_map_list + i;
2525 if ((cur_entry->flags & XATTR_MAP_FLAG_SERVER) &&
2526 (strstart(server_name, cur_entry->prepend, &end))) {
2527 if (cur_entry->flags & XATTR_MAP_FLAG_BAD) {
2528 return -ENODATA;
2530 if (cur_entry->flags & XATTR_MAP_FLAG_OK) {
2531 *out_name = server_name;
2532 return 0;
2534 if (cur_entry->flags & XATTR_MAP_FLAG_PREFIX) {
2535 /* Remove prefix */
2536 *out_name = end;
2537 return 0;
2542 return -ENODATA;
2545 static void lo_getxattr(fuse_req_t req, fuse_ino_t ino, const char *in_name,
2546 size_t size)
2548 struct lo_data *lo = lo_data(req);
2549 char *value = NULL;
2550 char procname[64];
2551 const char *name;
2552 char *mapped_name;
2553 struct lo_inode *inode;
2554 ssize_t ret;
2555 int saverr;
2556 int fd = -1;
2558 mapped_name = NULL;
2559 name = in_name;
2560 if (lo->xattrmap) {
2561 ret = xattr_map_client(lo, in_name, &mapped_name);
2562 if (ret < 0) {
2563 if (ret == -EPERM) {
2564 ret = -ENODATA;
2566 fuse_reply_err(req, -ret);
2567 return;
2569 if (mapped_name) {
2570 name = mapped_name;
2574 inode = lo_inode(req, ino);
2575 if (!inode) {
2576 fuse_reply_err(req, EBADF);
2577 g_free(mapped_name);
2578 return;
2581 saverr = ENOSYS;
2582 if (!lo_data(req)->xattr) {
2583 goto out;
2586 fuse_log(FUSE_LOG_DEBUG, "lo_getxattr(ino=%" PRIu64 ", name=%s size=%zd)\n",
2587 ino, name, size);
2589 if (size) {
2590 value = malloc(size);
2591 if (!value) {
2592 goto out_err;
2596 sprintf(procname, "%i", inode->fd);
2598 * It is not safe to open() non-regular/non-dir files in file server
2599 * unless O_PATH is used, so use that method for regular files/dir
2600 * only (as it seems giving less performance overhead).
2601 * Otherwise, call fchdir() to avoid open().
2603 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2604 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2605 if (fd < 0) {
2606 goto out_err;
2608 ret = fgetxattr(fd, name, value, size);
2609 } else {
2610 /* fchdir should not fail here */
2611 assert(fchdir(lo->proc_self_fd) == 0);
2612 ret = getxattr(procname, name, value, size);
2613 assert(fchdir(lo->root.fd) == 0);
2616 if (ret == -1) {
2617 goto out_err;
2619 if (size) {
2620 saverr = 0;
2621 if (ret == 0) {
2622 goto out;
2624 fuse_reply_buf(req, value, ret);
2625 } else {
2626 fuse_reply_xattr(req, ret);
2628 out_free:
2629 free(value);
2631 if (fd >= 0) {
2632 close(fd);
2635 lo_inode_put(lo, &inode);
2636 return;
2638 out_err:
2639 saverr = errno;
2640 out:
2641 fuse_reply_err(req, saverr);
2642 g_free(mapped_name);
2643 goto out_free;
2646 static void lo_listxattr(fuse_req_t req, fuse_ino_t ino, size_t size)
2648 struct lo_data *lo = lo_data(req);
2649 char *value = NULL;
2650 char procname[64];
2651 struct lo_inode *inode;
2652 ssize_t ret;
2653 int saverr;
2654 int fd = -1;
2656 inode = lo_inode(req, ino);
2657 if (!inode) {
2658 fuse_reply_err(req, EBADF);
2659 return;
2662 saverr = ENOSYS;
2663 if (!lo_data(req)->xattr) {
2664 goto out;
2667 fuse_log(FUSE_LOG_DEBUG, "lo_listxattr(ino=%" PRIu64 ", size=%zd)\n", ino,
2668 size);
2670 if (size) {
2671 value = malloc(size);
2672 if (!value) {
2673 goto out_err;
2677 sprintf(procname, "%i", inode->fd);
2678 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2679 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2680 if (fd < 0) {
2681 goto out_err;
2683 ret = flistxattr(fd, value, size);
2684 } else {
2685 /* fchdir should not fail here */
2686 assert(fchdir(lo->proc_self_fd) == 0);
2687 ret = listxattr(procname, value, size);
2688 assert(fchdir(lo->root.fd) == 0);
2691 if (ret == -1) {
2692 goto out_err;
2694 if (size) {
2695 saverr = 0;
2696 if (ret == 0) {
2697 goto out;
2700 if (lo->xattr_map_list) {
2702 * Map the names back, some attributes might be dropped,
2703 * some shortened, but not increased, so we shouldn't
2704 * run out of room.
2706 size_t out_index, in_index;
2707 out_index = 0;
2708 in_index = 0;
2709 while (in_index < ret) {
2710 const char *map_out;
2711 char *in_ptr = value + in_index;
2712 /* Length of current attribute name */
2713 size_t in_len = strlen(value + in_index) + 1;
2715 int mapret = xattr_map_server(lo, in_ptr, &map_out);
2716 if (mapret != -ENODATA && mapret != 0) {
2717 /* Shouldn't happen */
2718 saverr = -mapret;
2719 goto out;
2721 if (mapret == 0) {
2722 /* Either unchanged, or truncated */
2723 size_t out_len;
2724 if (map_out != in_ptr) {
2725 /* +1 copies the NIL */
2726 out_len = strlen(map_out) + 1;
2727 } else {
2728 /* No change */
2729 out_len = in_len;
2732 * Move result along, may still be needed for an unchanged
2733 * entry if a previous entry was changed.
2735 memmove(value + out_index, map_out, out_len);
2737 out_index += out_len;
2739 in_index += in_len;
2741 ret = out_index;
2742 if (ret == 0) {
2743 goto out;
2746 fuse_reply_buf(req, value, ret);
2747 } else {
2749 * xattrmap only ever shortens the result,
2750 * so we don't need to do anything clever with the
2751 * allocation length here.
2753 fuse_reply_xattr(req, ret);
2755 out_free:
2756 free(value);
2758 if (fd >= 0) {
2759 close(fd);
2762 lo_inode_put(lo, &inode);
2763 return;
2765 out_err:
2766 saverr = errno;
2767 out:
2768 fuse_reply_err(req, saverr);
2769 goto out_free;
2772 static void lo_setxattr(fuse_req_t req, fuse_ino_t ino, const char *in_name,
2773 const char *value, size_t size, int flags)
2775 char procname[64];
2776 const char *name;
2777 char *mapped_name;
2778 struct lo_data *lo = lo_data(req);
2779 struct lo_inode *inode;
2780 ssize_t ret;
2781 int saverr;
2782 int fd = -1;
2784 mapped_name = NULL;
2785 name = in_name;
2786 if (lo->xattrmap) {
2787 ret = xattr_map_client(lo, in_name, &mapped_name);
2788 if (ret < 0) {
2789 fuse_reply_err(req, -ret);
2790 return;
2792 if (mapped_name) {
2793 name = mapped_name;
2797 inode = lo_inode(req, ino);
2798 if (!inode) {
2799 fuse_reply_err(req, EBADF);
2800 g_free(mapped_name);
2801 return;
2804 saverr = ENOSYS;
2805 if (!lo_data(req)->xattr) {
2806 goto out;
2809 fuse_log(FUSE_LOG_DEBUG, "lo_setxattr(ino=%" PRIu64
2810 ", name=%s value=%s size=%zd)\n", ino, name, value, size);
2812 sprintf(procname, "%i", inode->fd);
2813 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2814 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2815 if (fd < 0) {
2816 saverr = errno;
2817 goto out;
2819 ret = fsetxattr(fd, name, value, size, flags);
2820 } else {
2821 /* fchdir should not fail here */
2822 assert(fchdir(lo->proc_self_fd) == 0);
2823 ret = setxattr(procname, name, value, size, flags);
2824 assert(fchdir(lo->root.fd) == 0);
2827 saverr = ret == -1 ? errno : 0;
2829 out:
2830 if (fd >= 0) {
2831 close(fd);
2834 lo_inode_put(lo, &inode);
2835 g_free(mapped_name);
2836 fuse_reply_err(req, saverr);
2839 static void lo_removexattr(fuse_req_t req, fuse_ino_t ino, const char *in_name)
2841 char procname[64];
2842 const char *name;
2843 char *mapped_name;
2844 struct lo_data *lo = lo_data(req);
2845 struct lo_inode *inode;
2846 ssize_t ret;
2847 int saverr;
2848 int fd = -1;
2850 mapped_name = NULL;
2851 name = in_name;
2852 if (lo->xattrmap) {
2853 ret = xattr_map_client(lo, in_name, &mapped_name);
2854 if (ret < 0) {
2855 fuse_reply_err(req, -ret);
2856 return;
2858 if (mapped_name) {
2859 name = mapped_name;
2863 inode = lo_inode(req, ino);
2864 if (!inode) {
2865 fuse_reply_err(req, EBADF);
2866 g_free(mapped_name);
2867 return;
2870 saverr = ENOSYS;
2871 if (!lo_data(req)->xattr) {
2872 goto out;
2875 fuse_log(FUSE_LOG_DEBUG, "lo_removexattr(ino=%" PRIu64 ", name=%s)\n", ino,
2876 name);
2878 sprintf(procname, "%i", inode->fd);
2879 if (S_ISREG(inode->filetype) || S_ISDIR(inode->filetype)) {
2880 fd = openat(lo->proc_self_fd, procname, O_RDONLY);
2881 if (fd < 0) {
2882 saverr = errno;
2883 goto out;
2885 ret = fremovexattr(fd, name);
2886 } else {
2887 /* fchdir should not fail here */
2888 assert(fchdir(lo->proc_self_fd) == 0);
2889 ret = removexattr(procname, name);
2890 assert(fchdir(lo->root.fd) == 0);
2893 saverr = ret == -1 ? errno : 0;
2895 out:
2896 if (fd >= 0) {
2897 close(fd);
2900 lo_inode_put(lo, &inode);
2901 g_free(mapped_name);
2902 fuse_reply_err(req, saverr);
2905 #ifdef HAVE_COPY_FILE_RANGE
2906 static void lo_copy_file_range(fuse_req_t req, fuse_ino_t ino_in, off_t off_in,
2907 struct fuse_file_info *fi_in, fuse_ino_t ino_out,
2908 off_t off_out, struct fuse_file_info *fi_out,
2909 size_t len, int flags)
2911 int in_fd, out_fd;
2912 ssize_t res;
2914 in_fd = lo_fi_fd(req, fi_in);
2915 out_fd = lo_fi_fd(req, fi_out);
2917 fuse_log(FUSE_LOG_DEBUG,
2918 "lo_copy_file_range(ino=%" PRIu64 "/fd=%d, "
2919 "off=%lu, ino=%" PRIu64 "/fd=%d, "
2920 "off=%lu, size=%zd, flags=0x%x)\n",
2921 ino_in, in_fd, off_in, ino_out, out_fd, off_out, len, flags);
2923 res = copy_file_range(in_fd, &off_in, out_fd, &off_out, len, flags);
2924 if (res < 0) {
2925 fuse_reply_err(req, errno);
2926 } else {
2927 fuse_reply_write(req, res);
2930 #endif
2932 static void lo_lseek(fuse_req_t req, fuse_ino_t ino, off_t off, int whence,
2933 struct fuse_file_info *fi)
2935 off_t res;
2937 (void)ino;
2938 res = lseek(lo_fi_fd(req, fi), off, whence);
2939 if (res != -1) {
2940 fuse_reply_lseek(req, res);
2941 } else {
2942 fuse_reply_err(req, errno);
2946 static void lo_destroy(void *userdata)
2948 struct lo_data *lo = (struct lo_data *)userdata;
2950 pthread_mutex_lock(&lo->mutex);
2951 while (true) {
2952 GHashTableIter iter;
2953 gpointer key, value;
2955 g_hash_table_iter_init(&iter, lo->inodes);
2956 if (!g_hash_table_iter_next(&iter, &key, &value)) {
2957 break;
2960 struct lo_inode *inode = value;
2961 unref_inode(lo, inode, inode->nlookup);
2963 pthread_mutex_unlock(&lo->mutex);
2966 static struct fuse_lowlevel_ops lo_oper = {
2967 .init = lo_init,
2968 .lookup = lo_lookup,
2969 .mkdir = lo_mkdir,
2970 .mknod = lo_mknod,
2971 .symlink = lo_symlink,
2972 .link = lo_link,
2973 .unlink = lo_unlink,
2974 .rmdir = lo_rmdir,
2975 .rename = lo_rename,
2976 .forget = lo_forget,
2977 .forget_multi = lo_forget_multi,
2978 .getattr = lo_getattr,
2979 .setattr = lo_setattr,
2980 .readlink = lo_readlink,
2981 .opendir = lo_opendir,
2982 .readdir = lo_readdir,
2983 .readdirplus = lo_readdirplus,
2984 .releasedir = lo_releasedir,
2985 .fsyncdir = lo_fsyncdir,
2986 .create = lo_create,
2987 .getlk = lo_getlk,
2988 .setlk = lo_setlk,
2989 .open = lo_open,
2990 .release = lo_release,
2991 .flush = lo_flush,
2992 .fsync = lo_fsync,
2993 .read = lo_read,
2994 .write_buf = lo_write_buf,
2995 .statfs = lo_statfs,
2996 .fallocate = lo_fallocate,
2997 .flock = lo_flock,
2998 .getxattr = lo_getxattr,
2999 .listxattr = lo_listxattr,
3000 .setxattr = lo_setxattr,
3001 .removexattr = lo_removexattr,
3002 #ifdef HAVE_COPY_FILE_RANGE
3003 .copy_file_range = lo_copy_file_range,
3004 #endif
3005 .lseek = lo_lseek,
3006 .destroy = lo_destroy,
3009 /* Print vhost-user.json backend program capabilities */
3010 static void print_capabilities(void)
3012 printf("{\n");
3013 printf(" \"type\": \"fs\"\n");
3014 printf("}\n");
3018 * Drop all Linux capabilities because the wait parent process only needs to
3019 * sit in waitpid(2) and terminate.
3021 static void setup_wait_parent_capabilities(void)
3023 capng_setpid(syscall(SYS_gettid));
3024 capng_clear(CAPNG_SELECT_BOTH);
3025 capng_apply(CAPNG_SELECT_BOTH);
3029 * Move to a new mount, net, and pid namespaces to isolate this process.
3031 static void setup_namespaces(struct lo_data *lo, struct fuse_session *se)
3033 pid_t child;
3036 * Create a new pid namespace for *child* processes. We'll have to
3037 * fork in order to enter the new pid namespace. A new mount namespace
3038 * is also needed so that we can remount /proc for the new pid
3039 * namespace.
3041 * Our UNIX domain sockets have been created. Now we can move to
3042 * an empty network namespace to prevent TCP/IP and other network
3043 * activity in case this process is compromised.
3045 if (unshare(CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWNET) != 0) {
3046 fuse_log(FUSE_LOG_ERR, "unshare(CLONE_NEWPID | CLONE_NEWNS): %m\n");
3047 exit(1);
3050 child = fork();
3051 if (child < 0) {
3052 fuse_log(FUSE_LOG_ERR, "fork() failed: %m\n");
3053 exit(1);
3055 if (child > 0) {
3056 pid_t waited;
3057 int wstatus;
3059 setup_wait_parent_capabilities();
3061 /* The parent waits for the child */
3062 do {
3063 waited = waitpid(child, &wstatus, 0);
3064 } while (waited < 0 && errno == EINTR && !se->exited);
3066 /* We were terminated by a signal, see fuse_signals.c */
3067 if (se->exited) {
3068 exit(0);
3071 if (WIFEXITED(wstatus)) {
3072 exit(WEXITSTATUS(wstatus));
3075 exit(1);
3078 /* Send us SIGTERM when the parent thread terminates, see prctl(2) */
3079 prctl(PR_SET_PDEATHSIG, SIGTERM);
3082 * If the mounts have shared propagation then we want to opt out so our
3083 * mount changes don't affect the parent mount namespace.
3085 if (mount(NULL, "/", NULL, MS_REC | MS_SLAVE, NULL) < 0) {
3086 fuse_log(FUSE_LOG_ERR, "mount(/, MS_REC|MS_SLAVE): %m\n");
3087 exit(1);
3090 /* The child must remount /proc to use the new pid namespace */
3091 if (mount("proc", "/proc", "proc",
3092 MS_NODEV | MS_NOEXEC | MS_NOSUID | MS_RELATIME, NULL) < 0) {
3093 fuse_log(FUSE_LOG_ERR, "mount(/proc): %m\n");
3094 exit(1);
3098 * We only need /proc/self/fd. Prevent ".." from accessing parent
3099 * directories of /proc/self/fd by bind-mounting it over /proc. Since / was
3100 * previously remounted with MS_REC | MS_SLAVE this mount change only
3101 * affects our process.
3103 if (mount("/proc/self/fd", "/proc", NULL, MS_BIND, NULL) < 0) {
3104 fuse_log(FUSE_LOG_ERR, "mount(/proc/self/fd, MS_BIND): %m\n");
3105 exit(1);
3108 /* Get the /proc (actually /proc/self/fd, see above) file descriptor */
3109 lo->proc_self_fd = open("/proc", O_PATH);
3110 if (lo->proc_self_fd == -1) {
3111 fuse_log(FUSE_LOG_ERR, "open(/proc, O_PATH): %m\n");
3112 exit(1);
3117 * Capture the capability state, we'll need to restore this for individual
3118 * threads later; see load_capng.
3120 static void setup_capng(void)
3122 /* Note this accesses /proc so has to happen before the sandbox */
3123 if (capng_get_caps_process()) {
3124 fuse_log(FUSE_LOG_ERR, "capng_get_caps_process\n");
3125 exit(1);
3127 pthread_mutex_init(&cap.mutex, NULL);
3128 pthread_mutex_lock(&cap.mutex);
3129 cap.saved = capng_save_state();
3130 if (!cap.saved) {
3131 fuse_log(FUSE_LOG_ERR, "capng_save_state\n");
3132 exit(1);
3134 pthread_mutex_unlock(&cap.mutex);
3137 static void cleanup_capng(void)
3139 free(cap.saved);
3140 cap.saved = NULL;
3141 pthread_mutex_destroy(&cap.mutex);
3146 * Make the source directory our root so symlinks cannot escape and no other
3147 * files are accessible. Assumes unshare(CLONE_NEWNS) was already called.
3149 static void setup_mounts(const char *source)
3151 int oldroot;
3152 int newroot;
3154 if (mount(source, source, NULL, MS_BIND | MS_REC, NULL) < 0) {
3155 fuse_log(FUSE_LOG_ERR, "mount(%s, %s, MS_BIND): %m\n", source, source);
3156 exit(1);
3159 /* This magic is based on lxc's lxc_pivot_root() */
3160 oldroot = open("/", O_DIRECTORY | O_RDONLY | O_CLOEXEC);
3161 if (oldroot < 0) {
3162 fuse_log(FUSE_LOG_ERR, "open(/): %m\n");
3163 exit(1);
3166 newroot = open(source, O_DIRECTORY | O_RDONLY | O_CLOEXEC);
3167 if (newroot < 0) {
3168 fuse_log(FUSE_LOG_ERR, "open(%s): %m\n", source);
3169 exit(1);
3172 if (fchdir(newroot) < 0) {
3173 fuse_log(FUSE_LOG_ERR, "fchdir(newroot): %m\n");
3174 exit(1);
3177 if (syscall(__NR_pivot_root, ".", ".") < 0) {
3178 fuse_log(FUSE_LOG_ERR, "pivot_root(., .): %m\n");
3179 exit(1);
3182 if (fchdir(oldroot) < 0) {
3183 fuse_log(FUSE_LOG_ERR, "fchdir(oldroot): %m\n");
3184 exit(1);
3187 if (mount("", ".", "", MS_SLAVE | MS_REC, NULL) < 0) {
3188 fuse_log(FUSE_LOG_ERR, "mount(., MS_SLAVE | MS_REC): %m\n");
3189 exit(1);
3192 if (umount2(".", MNT_DETACH) < 0) {
3193 fuse_log(FUSE_LOG_ERR, "umount2(., MNT_DETACH): %m\n");
3194 exit(1);
3197 if (fchdir(newroot) < 0) {
3198 fuse_log(FUSE_LOG_ERR, "fchdir(newroot): %m\n");
3199 exit(1);
3202 close(newroot);
3203 close(oldroot);
3207 * Only keep whitelisted capabilities that are needed for file system operation
3208 * The (possibly NULL) modcaps_in string passed in is free'd before exit.
3210 static void setup_capabilities(char *modcaps_in)
3212 char *modcaps = modcaps_in;
3213 pthread_mutex_lock(&cap.mutex);
3214 capng_restore_state(&cap.saved);
3217 * Whitelist file system-related capabilities that are needed for a file
3218 * server to act like root. Drop everything else like networking and
3219 * sysadmin capabilities.
3221 * Exclusions:
3222 * 1. CAP_LINUX_IMMUTABLE is not included because it's only used via ioctl
3223 * and we don't support that.
3224 * 2. CAP_MAC_OVERRIDE is not included because it only seems to be
3225 * used by the Smack LSM. Omit it until there is demand for it.
3227 capng_setpid(syscall(SYS_gettid));
3228 capng_clear(CAPNG_SELECT_BOTH);
3229 if (capng_updatev(CAPNG_ADD, CAPNG_PERMITTED | CAPNG_EFFECTIVE,
3230 CAP_CHOWN,
3231 CAP_DAC_OVERRIDE,
3232 CAP_FOWNER,
3233 CAP_FSETID,
3234 CAP_SETGID,
3235 CAP_SETUID,
3236 CAP_MKNOD,
3237 CAP_SETFCAP,
3238 -1)) {
3239 fuse_log(FUSE_LOG_ERR, "%s: capng_updatev failed\n", __func__);
3240 exit(1);
3244 * The modcaps option is a colon separated list of caps,
3245 * each preceded by either + or -.
3247 while (modcaps) {
3248 capng_act_t action;
3249 int cap;
3251 char *next = strchr(modcaps, ':');
3252 if (next) {
3253 *next = '\0';
3254 next++;
3257 switch (modcaps[0]) {
3258 case '+':
3259 action = CAPNG_ADD;
3260 break;
3262 case '-':
3263 action = CAPNG_DROP;
3264 break;
3266 default:
3267 fuse_log(FUSE_LOG_ERR,
3268 "%s: Expecting '+'/'-' in modcaps but found '%c'\n",
3269 __func__, modcaps[0]);
3270 exit(1);
3272 cap = capng_name_to_capability(modcaps + 1);
3273 if (cap < 0) {
3274 fuse_log(FUSE_LOG_ERR, "%s: Unknown capability '%s'\n", __func__,
3275 modcaps);
3276 exit(1);
3278 if (capng_update(action, CAPNG_PERMITTED | CAPNG_EFFECTIVE, cap)) {
3279 fuse_log(FUSE_LOG_ERR, "%s: capng_update failed for '%s'\n",
3280 __func__, modcaps);
3281 exit(1);
3284 modcaps = next;
3286 g_free(modcaps_in);
3288 if (capng_apply(CAPNG_SELECT_BOTH)) {
3289 fuse_log(FUSE_LOG_ERR, "%s: capng_apply failed\n", __func__);
3290 exit(1);
3293 cap.saved = capng_save_state();
3294 if (!cap.saved) {
3295 fuse_log(FUSE_LOG_ERR, "%s: capng_save_state failed\n", __func__);
3296 exit(1);
3298 pthread_mutex_unlock(&cap.mutex);
3302 * Use chroot as a weaker sandbox for environments where the process is
3303 * launched without CAP_SYS_ADMIN.
3305 static void setup_chroot(struct lo_data *lo)
3307 lo->proc_self_fd = open("/proc/self/fd", O_PATH);
3308 if (lo->proc_self_fd == -1) {
3309 fuse_log(FUSE_LOG_ERR, "open(\"/proc/self/fd\", O_PATH): %m\n");
3310 exit(1);
3314 * Make the shared directory the file system root so that FUSE_OPEN
3315 * (lo_open()) cannot escape the shared directory by opening a symlink.
3317 * The chroot(2) syscall is later disabled by seccomp and the
3318 * CAP_SYS_CHROOT capability is dropped so that tampering with the chroot
3319 * is not possible.
3321 * However, it's still possible to escape the chroot via lo->proc_self_fd
3322 * but that requires first gaining control of the process.
3324 if (chroot(lo->source) != 0) {
3325 fuse_log(FUSE_LOG_ERR, "chroot(\"%s\"): %m\n", lo->source);
3326 exit(1);
3329 /* Move into the chroot */
3330 if (chdir("/") != 0) {
3331 fuse_log(FUSE_LOG_ERR, "chdir(\"/\"): %m\n");
3332 exit(1);
3337 * Lock down this process to prevent access to other processes or files outside
3338 * source directory. This reduces the impact of arbitrary code execution bugs.
3340 static void setup_sandbox(struct lo_data *lo, struct fuse_session *se,
3341 bool enable_syslog)
3343 if (lo->sandbox == SANDBOX_NAMESPACE) {
3344 setup_namespaces(lo, se);
3345 setup_mounts(lo->source);
3346 } else {
3347 setup_chroot(lo);
3350 setup_seccomp(enable_syslog);
3351 setup_capabilities(g_strdup(lo->modcaps));
3354 /* Set the maximum number of open file descriptors */
3355 static void setup_nofile_rlimit(unsigned long rlimit_nofile)
3357 struct rlimit rlim = {
3358 .rlim_cur = rlimit_nofile,
3359 .rlim_max = rlimit_nofile,
3362 if (rlimit_nofile == 0) {
3363 return; /* nothing to do */
3366 if (setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
3367 /* Ignore SELinux denials */
3368 if (errno == EPERM) {
3369 return;
3372 fuse_log(FUSE_LOG_ERR, "setrlimit(RLIMIT_NOFILE): %m\n");
3373 exit(1);
3377 static void log_func(enum fuse_log_level level, const char *fmt, va_list ap)
3379 g_autofree char *localfmt = NULL;
3380 struct timespec ts;
3381 struct tm tm;
3382 char sec_fmt[sizeof "2020-12-07 18:17:54"];
3383 char zone_fmt[sizeof "+0100"];
3385 if (current_log_level < level) {
3386 return;
3389 if (current_log_level == FUSE_LOG_DEBUG) {
3390 if (use_syslog) {
3391 /* no timestamp needed */
3392 localfmt = g_strdup_printf("[ID: %08ld] %s", syscall(__NR_gettid),
3393 fmt);
3394 } else {
3395 /* try formatting a broken-down timestamp */
3396 if (clock_gettime(CLOCK_REALTIME, &ts) != -1 &&
3397 localtime_r(&ts.tv_sec, &tm) != NULL &&
3398 strftime(sec_fmt, sizeof sec_fmt, "%Y-%m-%d %H:%M:%S",
3399 &tm) != 0 &&
3400 strftime(zone_fmt, sizeof zone_fmt, "%z", &tm) != 0) {
3401 localfmt = g_strdup_printf("[%s.%02ld%s] [ID: %08ld] %s",
3402 sec_fmt,
3403 ts.tv_nsec / (10L * 1000 * 1000),
3404 zone_fmt, syscall(__NR_gettid),
3405 fmt);
3406 } else {
3407 /* fall back to a flat timestamp */
3408 localfmt = g_strdup_printf("[%" PRId64 "] [ID: %08ld] %s",
3409 get_clock(), syscall(__NR_gettid),
3410 fmt);
3413 fmt = localfmt;
3416 if (use_syslog) {
3417 int priority = LOG_ERR;
3418 switch (level) {
3419 case FUSE_LOG_EMERG:
3420 priority = LOG_EMERG;
3421 break;
3422 case FUSE_LOG_ALERT:
3423 priority = LOG_ALERT;
3424 break;
3425 case FUSE_LOG_CRIT:
3426 priority = LOG_CRIT;
3427 break;
3428 case FUSE_LOG_ERR:
3429 priority = LOG_ERR;
3430 break;
3431 case FUSE_LOG_WARNING:
3432 priority = LOG_WARNING;
3433 break;
3434 case FUSE_LOG_NOTICE:
3435 priority = LOG_NOTICE;
3436 break;
3437 case FUSE_LOG_INFO:
3438 priority = LOG_INFO;
3439 break;
3440 case FUSE_LOG_DEBUG:
3441 priority = LOG_DEBUG;
3442 break;
3444 vsyslog(priority, fmt, ap);
3445 } else {
3446 vfprintf(stderr, fmt, ap);
3450 static void setup_root(struct lo_data *lo, struct lo_inode *root)
3452 int fd, res;
3453 struct stat stat;
3454 uint64_t mnt_id;
3456 fd = open("/", O_PATH);
3457 if (fd == -1) {
3458 fuse_log(FUSE_LOG_ERR, "open(%s, O_PATH): %m\n", lo->source);
3459 exit(1);
3462 res = do_statx(lo, fd, "", &stat, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW,
3463 &mnt_id);
3464 if (res == -1) {
3465 fuse_log(FUSE_LOG_ERR, "fstatat(%s): %m\n", lo->source);
3466 exit(1);
3469 root->filetype = S_IFDIR;
3470 root->fd = fd;
3471 root->key.ino = stat.st_ino;
3472 root->key.dev = stat.st_dev;
3473 root->key.mnt_id = mnt_id;
3474 root->nlookup = 2;
3475 g_atomic_int_set(&root->refcount, 2);
3476 if (lo->posix_lock) {
3477 pthread_mutex_init(&root->plock_mutex, NULL);
3478 root->posix_locks = g_hash_table_new_full(
3479 g_direct_hash, g_direct_equal, NULL, posix_locks_value_destroy);
3483 static guint lo_key_hash(gconstpointer key)
3485 const struct lo_key *lkey = key;
3487 return (guint)lkey->ino + (guint)lkey->dev + (guint)lkey->mnt_id;
3490 static gboolean lo_key_equal(gconstpointer a, gconstpointer b)
3492 const struct lo_key *la = a;
3493 const struct lo_key *lb = b;
3495 return la->ino == lb->ino && la->dev == lb->dev && la->mnt_id == lb->mnt_id;
3498 static void fuse_lo_data_cleanup(struct lo_data *lo)
3500 if (lo->inodes) {
3501 g_hash_table_destroy(lo->inodes);
3504 if (lo->root.posix_locks) {
3505 g_hash_table_destroy(lo->root.posix_locks);
3507 lo_map_destroy(&lo->fd_map);
3508 lo_map_destroy(&lo->dirp_map);
3509 lo_map_destroy(&lo->ino_map);
3511 if (lo->proc_self_fd >= 0) {
3512 close(lo->proc_self_fd);
3515 if (lo->root.fd >= 0) {
3516 close(lo->root.fd);
3519 free(lo->xattrmap);
3520 free_xattrmap(lo);
3521 free(lo->source);
3524 int main(int argc, char *argv[])
3526 struct fuse_args args = FUSE_ARGS_INIT(argc, argv);
3527 struct fuse_session *se;
3528 struct fuse_cmdline_opts opts;
3529 struct lo_data lo = {
3530 .sandbox = SANDBOX_NAMESPACE,
3531 .debug = 0,
3532 .writeback = 0,
3533 .posix_lock = 0,
3534 .allow_direct_io = 0,
3535 .proc_self_fd = -1,
3537 struct lo_map_elem *root_elem;
3538 struct lo_map_elem *reserve_elem;
3539 int ret = -1;
3541 /* Initialize time conversion information for localtime_r(). */
3542 tzset();
3544 /* Don't mask creation mode, kernel already did that */
3545 umask(0);
3547 qemu_init_exec_dir(argv[0]);
3549 pthread_mutex_init(&lo.mutex, NULL);
3550 lo.inodes = g_hash_table_new(lo_key_hash, lo_key_equal);
3551 lo.root.fd = -1;
3552 lo.root.fuse_ino = FUSE_ROOT_ID;
3553 lo.cache = CACHE_AUTO;
3556 * Set up the ino map like this:
3557 * [0] Reserved (will not be used)
3558 * [1] Root inode
3560 lo_map_init(&lo.ino_map);
3561 reserve_elem = lo_map_reserve(&lo.ino_map, 0);
3562 if (!reserve_elem) {
3563 fuse_log(FUSE_LOG_ERR, "failed to alloc reserve_elem.\n");
3564 goto err_out1;
3566 reserve_elem->in_use = false;
3567 root_elem = lo_map_reserve(&lo.ino_map, lo.root.fuse_ino);
3568 if (!root_elem) {
3569 fuse_log(FUSE_LOG_ERR, "failed to alloc root_elem.\n");
3570 goto err_out1;
3572 root_elem->inode = &lo.root;
3574 lo_map_init(&lo.dirp_map);
3575 lo_map_init(&lo.fd_map);
3577 if (fuse_parse_cmdline(&args, &opts) != 0) {
3578 goto err_out1;
3580 fuse_set_log_func(log_func);
3581 use_syslog = opts.syslog;
3582 if (use_syslog) {
3583 openlog("virtiofsd", LOG_PID, LOG_DAEMON);
3586 if (opts.show_help) {
3587 printf("usage: %s [options]\n\n", argv[0]);
3588 fuse_cmdline_help();
3589 printf(" -o source=PATH shared directory tree\n");
3590 fuse_lowlevel_help();
3591 ret = 0;
3592 goto err_out1;
3593 } else if (opts.show_version) {
3594 fuse_lowlevel_version();
3595 ret = 0;
3596 goto err_out1;
3597 } else if (opts.print_capabilities) {
3598 print_capabilities();
3599 ret = 0;
3600 goto err_out1;
3603 if (fuse_opt_parse(&args, &lo, lo_opts, NULL) == -1) {
3604 goto err_out1;
3607 if (opts.log_level != 0) {
3608 current_log_level = opts.log_level;
3609 } else {
3610 /* default log level is INFO */
3611 current_log_level = FUSE_LOG_INFO;
3613 lo.debug = opts.debug;
3614 if (lo.debug) {
3615 current_log_level = FUSE_LOG_DEBUG;
3617 if (lo.source) {
3618 struct stat stat;
3619 int res;
3621 res = lstat(lo.source, &stat);
3622 if (res == -1) {
3623 fuse_log(FUSE_LOG_ERR, "failed to stat source (\"%s\"): %m\n",
3624 lo.source);
3625 exit(1);
3627 if (!S_ISDIR(stat.st_mode)) {
3628 fuse_log(FUSE_LOG_ERR, "source is not a directory\n");
3629 exit(1);
3631 } else {
3632 lo.source = strdup("/");
3633 if (!lo.source) {
3634 fuse_log(FUSE_LOG_ERR, "failed to strdup source\n");
3635 goto err_out1;
3639 if (lo.xattrmap) {
3640 parse_xattrmap(&lo);
3643 if (!lo.timeout_set) {
3644 switch (lo.cache) {
3645 case CACHE_NONE:
3646 lo.timeout = 0.0;
3647 break;
3649 case CACHE_AUTO:
3650 lo.timeout = 1.0;
3651 break;
3653 case CACHE_ALWAYS:
3654 lo.timeout = 86400.0;
3655 break;
3657 } else if (lo.timeout < 0) {
3658 fuse_log(FUSE_LOG_ERR, "timeout is negative (%lf)\n", lo.timeout);
3659 exit(1);
3662 lo.use_statx = true;
3664 se = fuse_session_new(&args, &lo_oper, sizeof(lo_oper), &lo);
3665 if (se == NULL) {
3666 goto err_out1;
3669 if (fuse_set_signal_handlers(se) != 0) {
3670 goto err_out2;
3673 if (fuse_session_mount(se) != 0) {
3674 goto err_out3;
3677 fuse_daemonize(opts.foreground);
3679 setup_nofile_rlimit(opts.rlimit_nofile);
3681 /* Must be before sandbox since it wants /proc */
3682 setup_capng();
3684 setup_sandbox(&lo, se, opts.syslog);
3686 setup_root(&lo, &lo.root);
3687 /* Block until ctrl+c or fusermount -u */
3688 ret = virtio_loop(se);
3690 fuse_session_unmount(se);
3691 cleanup_capng();
3692 err_out3:
3693 fuse_remove_signal_handlers(se);
3694 err_out2:
3695 fuse_session_destroy(se);
3696 err_out1:
3697 fuse_opt_free_args(&args);
3699 fuse_lo_data_cleanup(&lo);
3701 return ret ? 1 : 0;