void fs_tmpfs(const char *dir, unsigned check_owner) {
	EUID_ASSERT();
	assert(dir);
	if (arg_debug)
		printf("Mounting tmpfs on %s, check owner: %s\n", dir, (check_owner)? "yes": "no");
	// get a file descriptor for dir, fails if there is any symlink
	int fd = safer_openat(-1, dir, O_PATH|O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC);
	if (fd == -1)
		errExit("while opening directory");
	struct stat s;
	if (fstat(fd, &s) == -1)
		errExit("fstat");
	if (check_owner && s.st_uid != getuid()) {
		fprintf(stderr, "Error: cannot mount tmpfs on %s: not owned by the current user\n", dir);
		exit(1);
	}
	// preserve ownership, mode
	char *options;
	if (asprintf(&options, "mode=%o,uid=%u,gid=%u", s.st_mode & 07777, s.st_uid, s.st_gid) == -1)
		errExit("asprintf");
	// preserve mount flags, but remove read-only flag
	struct statvfs buf;
	if (fstatvfs(fd, &buf) == -1)
		errExit("fstatvfs");
	unsigned long flags = buf.f_flag & ~(MS_RDONLY|MS_BIND|MS_REMOUNT);
	// mount via the symbolic link in /proc/self/fd
	char *proc;
	if (asprintf(&proc, "/proc/self/fd/%d", fd) == -1)
		errExit("asprintf");
	EUID_ROOT();
	if (mount("tmpfs", proc, "tmpfs", flags|MS_NOSUID|MS_NODEV, options) < 0)
		errExit("mounting tmpfs");
	EUID_USER();
	// check the last mount operation
	MountData *mdata = get_last_mount();
	if (strcmp(mdata->fstype, "tmpfs") != 0 || strcmp(mdata->dir, dir) != 0)
		errLogExit("invalid tmpfs mount");
	fs_logger2("tmpfs", dir);
	free(options);
	free(proc);
	close(fd);
}
void fs_tmpfs(const char *dir, unsigned check_owner) {
	EUID_ASSERT();
	assert(dir);
	if (arg_debug)
		printf("Mounting tmpfs on %s, check owner: %s\n", dir, (check_owner)? "yes": "no");
	 
	int fd = safer_openat(-1, dir, O_PATH|O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC);
	if (fd == -1)
		errExit("while opening directory");
	struct stat s;
	if (fstat(fd, &s) == -1)
		errExit("fstat");
	if (check_owner && s.st_uid != getuid()) {
		fprintf(stderr, "Error: cannot mount tmpfs on %s: not owned by the current user\n", dir);
		exit(1);
	}
	 
	char *options;
	if (asprintf(&options, "mode=%o,uid=%u,gid=%u", s.st_mode & 07777, s.st_uid, s.st_gid) == -1)
		errExit("asprintf");
	 
	struct statvfs buf;
	if (fstatvfs(fd, &buf) == -1)
		errExit("fstatvfs");
	unsigned long flags = buf.f_flag & ~(MS_RDONLY|MS_BIND|MS_REMOUNT);
	 
	char *proc;
	if (asprintf(&proc, "/proc/self/fd/%d", fd) == -1)
		errExit("asprintf");
	EUID_ROOT();
	if (mount("tmpfs", proc, "tmpfs", flags|MS_NOSUID|MS_NODEV, options) < 0)
		errExit("mounting tmpfs");
	EUID_USER();
	 
	MountData *mdata = get_last_mount();
	if (strcmp(mdata->fstype, "tmpfs") != 0 || strcmp(mdata->dir, dir) != 0)
		errLogExit("invalid tmpfs mount");
	fs_logger2("tmpfs", dir);
	free(options);
	free(proc);
	close(fd);
}