+out:
+ SPECHASH_UNLOCK();
+ return (error);
+}
+
+/*
+ * Unmount all filesystems. The list is traversed in reverse order
+ * of mounting to avoid dependencies.
+ */
+__private_extern__ void
+vfs_unmountall(void)
+{
+ struct mount *mp;
+ int error;
+
+ /*
+ * Since this only runs when rebooting, it is not interlocked.
+ */
+ mount_list_lock();
+ while(!TAILQ_EMPTY(&mountlist)) {
+ mp = TAILQ_LAST(&mountlist, mntlist);
+ mount_list_unlock();
+ error = dounmount(mp, MNT_FORCE, 0, vfs_context_current());
+ if ((error != 0) && (error != EBUSY)) {
+ printf("unmount of %s failed (", mp->mnt_vfsstat.f_mntonname);
+ printf("%d)\n", error);
+ mount_list_lock();
+ TAILQ_REMOVE(&mountlist, mp, mnt_list);
+ continue;
+ } else if (error == EBUSY) {
+ /* If EBUSY is returned, the unmount was already in progress */
+ printf("unmount of %p failed (", mp);
+ printf("BUSY)\n");
+ }
+ mount_list_lock();
+ }
+ mount_list_unlock();
+}
+
+
+/*
+ * This routine is called from vnode_pager_deallocate out of the VM
+ * The path to vnode_pager_deallocate can only be initiated by ubc_destroy_named
+ * on a vnode that has a UBCINFO
+ */
+__private_extern__ void
+vnode_pager_vrele(vnode_t vp)
+{
+ struct ubc_info *uip;
+
+ vnode_lock_spin(vp);
+
+ vp->v_lflag &= ~VNAMED_UBC;
+
+ uip = vp->v_ubcinfo;
+ vp->v_ubcinfo = UBC_INFO_NULL;
+
+ vnode_unlock(vp);
+
+ ubc_info_deallocate(uip);
+}
+
+
+#include <sys/disk.h>
+
+errno_t
+vfs_init_io_attributes(vnode_t devvp, mount_t mp)
+{
+ int error;
+ off_t readblockcnt = 0;
+ off_t writeblockcnt = 0;
+ off_t readmaxcnt = 0;
+ off_t writemaxcnt = 0;
+ off_t readsegcnt = 0;
+ off_t writesegcnt = 0;
+ off_t readsegsize = 0;
+ off_t writesegsize = 0;
+ off_t alignment = 0;
+ off_t ioqueue_depth = 0;
+ u_int32_t blksize;
+ u_int64_t temp;
+ u_int32_t features;
+ vfs_context_t ctx = vfs_context_current();
+
+ int isvirtual = 0;
+ /*
+ * determine if this mount point exists on the same device as the root
+ * partition... if so, then it comes under the hard throttle control
+ */
+ int thisunit = -1;
+ static int rootunit = -1;
+
+ if (rootunit == -1) {
+ if (VNOP_IOCTL(rootvp, DKIOCGETBSDUNIT, (caddr_t)&rootunit, 0, ctx))
+ rootunit = -1;
+ else if (rootvp == devvp)
+ mp->mnt_kern_flag |= MNTK_ROOTDEV;
+ }
+ if (devvp != rootvp && rootunit != -1) {
+ if (VNOP_IOCTL(devvp, DKIOCGETBSDUNIT, (caddr_t)&thisunit, 0, ctx) == 0) {
+ if (thisunit == rootunit)
+ mp->mnt_kern_flag |= MNTK_ROOTDEV;
+ }
+ }
+ /*
+ * force the spec device to re-cache
+ * the underlying block size in case
+ * the filesystem overrode the initial value
+ */
+ set_fsblocksize(devvp);
+
+
+ if ((error = VNOP_IOCTL(devvp, DKIOCGETBLOCKSIZE,
+ (caddr_t)&blksize, 0, ctx)))
+ return (error);
+
+ mp->mnt_devblocksize = blksize;
+
+ /*
+ * set the maximum possible I/O size
+ * this may get clipped to a smaller value
+ * based on which constraints are being advertised
+ * and if those advertised constraints result in a smaller
+ * limit for a given I/O
+ */
+ mp->mnt_maxreadcnt = MAX_UPL_SIZE * PAGE_SIZE;
+ mp->mnt_maxwritecnt = MAX_UPL_SIZE * PAGE_SIZE;
+
+ if (VNOP_IOCTL(devvp, DKIOCISVIRTUAL, (caddr_t)&isvirtual, 0, ctx) == 0) {
+ if (isvirtual)
+ mp->mnt_kern_flag |= MNTK_VIRTUALDEV;
+ }
+
+ if ((error = VNOP_IOCTL(devvp, DKIOCGETFEATURES,
+ (caddr_t)&features, 0, ctx)))
+ return (error);
+
+ if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXBLOCKCOUNTREAD,
+ (caddr_t)&readblockcnt, 0, ctx)))
+ return (error);
+
+ if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXBLOCKCOUNTWRITE,
+ (caddr_t)&writeblockcnt, 0, ctx)))
+ return (error);
+
+ if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXBYTECOUNTREAD,
+ (caddr_t)&readmaxcnt, 0, ctx)))
+ return (error);
+
+ if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXBYTECOUNTWRITE,
+ (caddr_t)&writemaxcnt, 0, ctx)))
+ return (error);
+
+ if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXSEGMENTCOUNTREAD,
+ (caddr_t)&readsegcnt, 0, ctx)))
+ return (error);
+
+ if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXSEGMENTCOUNTWRITE,
+ (caddr_t)&writesegcnt, 0, ctx)))
+ return (error);
+
+ if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXSEGMENTBYTECOUNTREAD,
+ (caddr_t)&readsegsize, 0, ctx)))
+ return (error);
+
+ if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXSEGMENTBYTECOUNTWRITE,
+ (caddr_t)&writesegsize, 0, ctx)))
+ return (error);
+
+ if ((error = VNOP_IOCTL(devvp, DKIOCGETMINSEGMENTALIGNMENTBYTECOUNT,
+ (caddr_t)&alignment, 0, ctx)))
+ return (error);
+
+ if ((error = VNOP_IOCTL(devvp, DKIOCGETCOMMANDPOOLSIZE,
+ (caddr_t)&ioqueue_depth, 0, ctx)))
+ return (error);
+
+ if (readmaxcnt)
+ mp->mnt_maxreadcnt = (readmaxcnt > UINT32_MAX) ? UINT32_MAX : readmaxcnt;
+
+ if (readblockcnt) {
+ temp = readblockcnt * blksize;
+ temp = (temp > UINT32_MAX) ? UINT32_MAX : temp;
+
+ if (temp < mp->mnt_maxreadcnt)
+ mp->mnt_maxreadcnt = (u_int32_t)temp;
+ }
+
+ if (writemaxcnt)
+ mp->mnt_maxwritecnt = (writemaxcnt > UINT32_MAX) ? UINT32_MAX : writemaxcnt;
+
+ if (writeblockcnt) {
+ temp = writeblockcnt * blksize;
+ temp = (temp > UINT32_MAX) ? UINT32_MAX : temp;
+
+ if (temp < mp->mnt_maxwritecnt)
+ mp->mnt_maxwritecnt = (u_int32_t)temp;
+ }
+
+ if (readsegcnt) {
+ temp = (readsegcnt > UINT16_MAX) ? UINT16_MAX : readsegcnt;
+ } else {
+ temp = mp->mnt_maxreadcnt / PAGE_SIZE;
+
+ if (temp > UINT16_MAX)
+ temp = UINT16_MAX;
+ }
+ mp->mnt_segreadcnt = (u_int16_t)temp;
+
+ if (writesegcnt) {
+ temp = (writesegcnt > UINT16_MAX) ? UINT16_MAX : writesegcnt;
+ } else {
+ temp = mp->mnt_maxwritecnt / PAGE_SIZE;
+
+ if (temp > UINT16_MAX)
+ temp = UINT16_MAX;
+ }
+ mp->mnt_segwritecnt = (u_int16_t)temp;
+
+ if (readsegsize)
+ temp = (readsegsize > UINT32_MAX) ? UINT32_MAX : readsegsize;
+ else
+ temp = mp->mnt_maxreadcnt;
+ mp->mnt_maxsegreadsize = (u_int32_t)temp;
+
+ if (writesegsize)
+ temp = (writesegsize > UINT32_MAX) ? UINT32_MAX : writesegsize;
+ else
+ temp = mp->mnt_maxwritecnt;
+ mp->mnt_maxsegwritesize = (u_int32_t)temp;
+
+ if (alignment)
+ temp = (alignment > PAGE_SIZE) ? PAGE_MASK : alignment - 1;
+ else
+ temp = 0;
+ mp->mnt_alignmentmask = temp;
+
+
+ if (ioqueue_depth > MNT_DEFAULT_IOQUEUE_DEPTH)
+ temp = ioqueue_depth;
+ else
+ temp = MNT_DEFAULT_IOQUEUE_DEPTH;
+
+ mp->mnt_ioqueue_depth = temp;
+ mp->mnt_ioscale = (mp->mnt_ioqueue_depth + (MNT_DEFAULT_IOQUEUE_DEPTH - 1)) / MNT_DEFAULT_IOQUEUE_DEPTH;
+
+ if (mp->mnt_ioscale > 1)
+ printf("ioqueue_depth = %d, ioscale = %d\n", (int)mp->mnt_ioqueue_depth, (int)mp->mnt_ioscale);
+
+ if (features & DK_FEATURE_FORCE_UNIT_ACCESS)
+ mp->mnt_ioflags |= MNT_IOFLAGS_FUA_SUPPORTED;
+
+ return (error);
+}
+
+static struct klist fs_klist;
+lck_grp_t *fs_klist_lck_grp;
+lck_mtx_t *fs_klist_lock;
+
+void
+vfs_event_init(void)
+{
+
+ klist_init(&fs_klist);
+ fs_klist_lck_grp = lck_grp_alloc_init("fs_klist", NULL);
+ fs_klist_lock = lck_mtx_alloc_init(fs_klist_lck_grp, NULL);
+}
+
+void
+vfs_event_signal(__unused fsid_t *fsid, u_int32_t event, __unused intptr_t data)
+{
+ lck_mtx_lock(fs_klist_lock);
+ KNOTE(&fs_klist, event);
+ lck_mtx_unlock(fs_klist_lock);
+}
+
+/*
+ * return the number of mounted filesystems.
+ */
+static int
+sysctl_vfs_getvfscnt(void)
+{
+ return(mount_getvfscnt());
+}
+
+
+static int
+mount_getvfscnt(void)
+{
+ int ret;
+
+ mount_list_lock();
+ ret = nummounts;
+ mount_list_unlock();
+ return (ret);
+
+}
+
+
+
+static int
+mount_fillfsids(fsid_t *fsidlst, int count)
+{
+ struct mount *mp;
+ int actual=0;
+
+ actual = 0;
+ mount_list_lock();
+ TAILQ_FOREACH(mp, &mountlist, mnt_list) {
+ if (actual <= count) {
+ fsidlst[actual] = mp->mnt_vfsstat.f_fsid;
+ actual++;
+ }
+ }
+ mount_list_unlock();
+ return (actual);
+
+}
+
+/*
+ * fill in the array of fsid_t's up to a max of 'count', the actual
+ * number filled in will be set in '*actual'. If there are more fsid_t's
+ * than room in fsidlst then ENOMEM will be returned and '*actual' will
+ * have the actual count.
+ * having *actual filled out even in the error case is depended upon.
+ */
+static int
+sysctl_vfs_getvfslist(fsid_t *fsidlst, int count, int *actual)
+{
+ struct mount *mp;
+
+ *actual = 0;
+ mount_list_lock();
+ TAILQ_FOREACH(mp, &mountlist, mnt_list) {
+ (*actual)++;
+ if (*actual <= count)
+ fsidlst[(*actual) - 1] = mp->mnt_vfsstat.f_fsid;
+ }
+ mount_list_unlock();
+ return (*actual <= count ? 0 : ENOMEM);
+}
+
+static int
+sysctl_vfs_vfslist(__unused struct sysctl_oid *oidp, __unused void *arg1,
+ __unused int arg2, struct sysctl_req *req)
+{
+ int actual, error;
+ size_t space;
+ fsid_t *fsidlst;
+
+ /* This is a readonly node. */
+ if (req->newptr != USER_ADDR_NULL)
+ return (EPERM);
+
+ /* they are querying us so just return the space required. */
+ if (req->oldptr == USER_ADDR_NULL) {
+ req->oldidx = sysctl_vfs_getvfscnt() * sizeof(fsid_t);
+ return 0;
+ }
+again:
+ /*
+ * Retrieve an accurate count of the amount of space required to copy
+ * out all the fsids in the system.
+ */
+ space = req->oldlen;
+ req->oldlen = sysctl_vfs_getvfscnt() * sizeof(fsid_t);
+
+ /* they didn't give us enough space. */
+ if (space < req->oldlen)
+ return (ENOMEM);
+
+ MALLOC(fsidlst, fsid_t *, req->oldlen, M_TEMP, M_WAITOK);
+ if (fsidlst == NULL) {
+ return (ENOMEM);
+ }
+
+ error = sysctl_vfs_getvfslist(fsidlst, req->oldlen / sizeof(fsid_t),
+ &actual);
+ /*
+ * If we get back ENOMEM, then another mount has been added while we
+ * slept in malloc above. If this is the case then try again.
+ */
+ if (error == ENOMEM) {
+ FREE(fsidlst, M_TEMP);
+ req->oldlen = space;
+ goto again;
+ }
+ if (error == 0) {
+ error = SYSCTL_OUT(req, fsidlst, actual * sizeof(fsid_t));
+ }
+ FREE(fsidlst, M_TEMP);
+ return (error);
+}
+
+/*
+ * Do a sysctl by fsid.
+ */
+static int
+sysctl_vfs_ctlbyfsid(__unused struct sysctl_oid *oidp, void *arg1, int arg2,
+ struct sysctl_req *req)
+{
+ union union_vfsidctl vc;
+ struct mount *mp;
+ struct vfsstatfs *sp;
+ int *name, flags, namelen;
+ int error=0, gotref=0;
+ vfs_context_t ctx = vfs_context_current();
+ proc_t p = req->p; /* XXX req->p != current_proc()? */
+ boolean_t is_64_bit;
+
+ name = arg1;
+ namelen = arg2;
+ is_64_bit = proc_is64bit(p);
+
+ error = SYSCTL_IN(req, &vc, is_64_bit? sizeof(vc.vc64):sizeof(vc.vc32));
+ if (error)
+ goto out;
+ if (vc.vc32.vc_vers != VFS_CTL_VERS1) { /* works for 32 and 64 */
+ error = EINVAL;
+ goto out;
+ }
+ mp = mount_list_lookupby_fsid(&vc.vc32.vc_fsid, 0, 1); /* works for 32 and 64 */
+ if (mp == NULL) {
+ error = ENOENT;
+ goto out;
+ }
+ gotref = 1;
+ /* reset so that the fs specific code can fetch it. */
+ req->newidx = 0;
+ /*
+ * Note if this is a VFS_CTL then we pass the actual sysctl req
+ * in for "oldp" so that the lower layer can DTRT and use the
+ * SYSCTL_IN/OUT routines.
+ */
+ if (mp->mnt_op->vfs_sysctl != NULL) {
+ if (is_64_bit) {
+ if (vfs_64bitready(mp)) {
+ error = mp->mnt_op->vfs_sysctl(name, namelen,
+ CAST_USER_ADDR_T(req),
+ NULL, USER_ADDR_NULL, 0,
+ ctx);
+ }
+ else {
+ error = ENOTSUP;
+ }
+ }
+ else {
+ error = mp->mnt_op->vfs_sysctl(name, namelen,
+ CAST_USER_ADDR_T(req),
+ NULL, USER_ADDR_NULL, 0,
+ ctx);
+ }
+ if (error != ENOTSUP) {
+ goto out;
+ }
+ }
+ switch (name[0]) {
+ case VFS_CTL_UMOUNT:
+ req->newidx = 0;
+ if (is_64_bit) {
+ req->newptr = vc.vc64.vc_ptr;
+ req->newlen = (size_t)vc.vc64.vc_len;
+ }
+ else {
+ req->newptr = CAST_USER_ADDR_T(vc.vc32.vc_ptr);
+ req->newlen = vc.vc32.vc_len;
+ }
+ error = SYSCTL_IN(req, &flags, sizeof(flags));
+ if (error)
+ break;
+
+ mount_ref(mp, 0);
+ mount_iterdrop(mp);
+ gotref = 0;
+ /* safedounmount consumes a ref */
+ error = safedounmount(mp, flags, ctx);
+ break;
+ case VFS_CTL_STATFS:
+ req->newidx = 0;
+ if (is_64_bit) {
+ req->newptr = vc.vc64.vc_ptr;
+ req->newlen = (size_t)vc.vc64.vc_len;
+ }
+ else {
+ req->newptr = CAST_USER_ADDR_T(vc.vc32.vc_ptr);
+ req->newlen = vc.vc32.vc_len;
+ }
+ error = SYSCTL_IN(req, &flags, sizeof(flags));
+ if (error)
+ break;
+ sp = &mp->mnt_vfsstat;
+ if (((flags & MNT_NOWAIT) == 0 || (flags & (MNT_WAIT | MNT_DWAIT))) &&
+ (error = vfs_update_vfsstat(mp, ctx, VFS_USER_EVENT)))
+ goto out;
+ if (is_64_bit) {
+ struct user64_statfs sfs;
+ bzero(&sfs, sizeof(sfs));
+ sfs.f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
+ sfs.f_type = mp->mnt_vtable->vfc_typenum;
+ sfs.f_bsize = (user64_long_t)sp->f_bsize;
+ sfs.f_iosize = (user64_long_t)sp->f_iosize;
+ sfs.f_blocks = (user64_long_t)sp->f_blocks;
+ sfs.f_bfree = (user64_long_t)sp->f_bfree;
+ sfs.f_bavail = (user64_long_t)sp->f_bavail;
+ sfs.f_files = (user64_long_t)sp->f_files;
+ sfs.f_ffree = (user64_long_t)sp->f_ffree;
+ sfs.f_fsid = sp->f_fsid;
+ sfs.f_owner = sp->f_owner;
+
+ strlcpy(sfs.f_fstypename, sp->f_fstypename, MFSNAMELEN);
+ strlcpy(sfs.f_mntonname, sp->f_mntonname, MNAMELEN);
+ strlcpy(sfs.f_mntfromname, sp->f_mntfromname, MNAMELEN);
+
+ error = SYSCTL_OUT(req, &sfs, sizeof(sfs));
+ }
+ else {
+ struct user32_statfs sfs;
+ bzero(&sfs, sizeof(sfs));
+ sfs.f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
+ sfs.f_type = mp->mnt_vtable->vfc_typenum;
+
+ /*
+ * It's possible for there to be more than 2^^31 blocks in the filesystem, so we
+ * have to fudge the numbers here in that case. We inflate the blocksize in order
+ * to reflect the filesystem size as best we can.
+ */
+ if (sp->f_blocks > INT_MAX) {
+ int shift;
+
+ /*
+ * Work out how far we have to shift the block count down to make it fit.
+ * Note that it's possible to have to shift so far that the resulting
+ * blocksize would be unreportably large. At that point, we will clip
+ * any values that don't fit.
+ *
+ * For safety's sake, we also ensure that f_iosize is never reported as
+ * being smaller than f_bsize.
+ */
+ for (shift = 0; shift < 32; shift++) {
+ if ((sp->f_blocks >> shift) <= INT_MAX)
+ break;
+ if ((((long long)sp->f_bsize) << (shift + 1)) > INT_MAX)
+ break;
+ }
+#define __SHIFT_OR_CLIP(x, s) ((((x) >> (s)) > INT_MAX) ? INT_MAX : ((x) >> (s)))
+ sfs.f_blocks = (user32_long_t)__SHIFT_OR_CLIP(sp->f_blocks, shift);
+ sfs.f_bfree = (user32_long_t)__SHIFT_OR_CLIP(sp->f_bfree, shift);
+ sfs.f_bavail = (user32_long_t)__SHIFT_OR_CLIP(sp->f_bavail, shift);
+#undef __SHIFT_OR_CLIP
+ sfs.f_bsize = (user32_long_t)(sp->f_bsize << shift);
+ sfs.f_iosize = lmax(sp->f_iosize, sp->f_bsize);
+ } else {
+ sfs.f_bsize = (user32_long_t)sp->f_bsize;
+ sfs.f_iosize = (user32_long_t)sp->f_iosize;
+ sfs.f_blocks = (user32_long_t)sp->f_blocks;
+ sfs.f_bfree = (user32_long_t)sp->f_bfree;
+ sfs.f_bavail = (user32_long_t)sp->f_bavail;
+ }
+ sfs.f_files = (user32_long_t)sp->f_files;
+ sfs.f_ffree = (user32_long_t)sp->f_ffree;
+ sfs.f_fsid = sp->f_fsid;
+ sfs.f_owner = sp->f_owner;
+
+ strlcpy(sfs.f_fstypename, sp->f_fstypename, MFSNAMELEN);
+ strlcpy(sfs.f_mntonname, sp->f_mntonname, MNAMELEN);
+ strlcpy(sfs.f_mntfromname, sp->f_mntfromname, MNAMELEN);
+
+ error = SYSCTL_OUT(req, &sfs, sizeof(sfs));
+ }
+ break;
+ default:
+ error = ENOTSUP;
+ goto out;
+ }
+out:
+ if(gotref != 0)
+ mount_iterdrop(mp);
+ return (error);
+}
+
+static int filt_fsattach(struct knote *kn);
+static void filt_fsdetach(struct knote *kn);
+static int filt_fsevent(struct knote *kn, long hint);
+struct filterops fs_filtops = {
+ .f_attach = filt_fsattach,
+ .f_detach = filt_fsdetach,
+ .f_event = filt_fsevent,
+};
+
+static int
+filt_fsattach(struct knote *kn)
+{
+
+ lck_mtx_lock(fs_klist_lock);
+ kn->kn_flags |= EV_CLEAR;
+ KNOTE_ATTACH(&fs_klist, kn);
+ lck_mtx_unlock(fs_klist_lock);
+ return (0);
+}
+
+static void
+filt_fsdetach(struct knote *kn)
+{
+ lck_mtx_lock(fs_klist_lock);
+ KNOTE_DETACH(&fs_klist, kn);
+ lck_mtx_unlock(fs_klist_lock);
+}
+
+static int
+filt_fsevent(struct knote *kn, long hint)
+{
+ /*
+ * Backwards compatibility:
+ * Other filters would do nothing if kn->kn_sfflags == 0
+ */
+
+ if ((kn->kn_sfflags == 0) || (kn->kn_sfflags & hint)) {
+ kn->kn_fflags |= hint;
+ }
+
+ return (kn->kn_fflags != 0);
+}
+
+static int
+sysctl_vfs_noremotehang(__unused struct sysctl_oid *oidp,
+ __unused void *arg1, __unused int arg2, struct sysctl_req *req)
+{
+ int out, error;
+ pid_t pid;
+ proc_t p;
+
+ /* We need a pid. */
+ if (req->newptr == USER_ADDR_NULL)
+ return (EINVAL);
+
+ error = SYSCTL_IN(req, &pid, sizeof(pid));
+ if (error)
+ return (error);
+
+ p = proc_find(pid < 0 ? -pid : pid);
+ if (p == NULL)
+ return (ESRCH);
+
+ /*
+ * Fetching the value is ok, but we only fetch if the old
+ * pointer is given.
+ */
+ if (req->oldptr != USER_ADDR_NULL) {
+ out = !((p->p_flag & P_NOREMOTEHANG) == 0);
+ proc_rele(p);
+ error = SYSCTL_OUT(req, &out, sizeof(out));
+ return (error);
+ }
+
+ /* cansignal offers us enough security. */
+ if (p != req->p && proc_suser(req->p) != 0) {
+ proc_rele(p);
+ return (EPERM);
+ }
+
+ if (pid < 0)
+ OSBitAndAtomic(~((uint32_t)P_NOREMOTEHANG), &p->p_flag);
+ else
+ OSBitOrAtomic(P_NOREMOTEHANG, &p->p_flag);
+ proc_rele(p);
+
+ return (0);
+}
+
+/* the vfs.generic. branch. */
+SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RW|CTLFLAG_LOCKED, NULL, "vfs generic hinge");
+/* retreive a list of mounted filesystem fsid_t */
+SYSCTL_PROC(_vfs_generic, OID_AUTO, vfsidlist, CTLFLAG_RD,
+ NULL, 0, sysctl_vfs_vfslist, "S,fsid", "List of mounted filesystem ids");
+/* perform operations on filesystem via fsid_t */
+SYSCTL_NODE(_vfs_generic, OID_AUTO, ctlbyfsid, CTLFLAG_RW|CTLFLAG_LOCKED,
+ sysctl_vfs_ctlbyfsid, "ctlbyfsid");
+SYSCTL_PROC(_vfs_generic, OID_AUTO, noremotehang, CTLFLAG_RW|CTLFLAG_ANYBODY,
+ NULL, 0, sysctl_vfs_noremotehang, "I", "noremotehang");
+
+
+long num_reusedvnodes = 0;
+
+static int
+new_vnode(vnode_t *vpp)
+{
+ vnode_t vp;
+ int retries = 0; /* retry incase of tablefull */
+ int force_alloc = 0, walk_count = 0;
+ unsigned int vpid;
+ struct timespec ts;
+ struct timeval current_tv;
+#ifndef __LP64__
+ struct unsafe_fsnode *l_unsafefs = 0;
+#endif /* __LP64__ */
+ proc_t curproc = current_proc();
+
+retry:
+ microuptime(¤t_tv);
+
+ vp = NULLVP;
+
+ vnode_list_lock();
+
+ if ( !TAILQ_EMPTY(&vnode_dead_list)) {
+ /*
+ * Can always reuse a dead one
+ */
+ vp = TAILQ_FIRST(&vnode_dead_list);
+ goto steal_this_vp;
+ }
+ /*
+ * no dead vnodes available... if we're under
+ * the limit, we'll create a new vnode
+ */
+ if (numvnodes < desiredvnodes || force_alloc) {
+ numvnodes++;
+ vnode_list_unlock();
+
+ MALLOC_ZONE(vp, struct vnode *, sizeof(*vp), M_VNODE, M_WAITOK);
+ bzero((char *)vp, sizeof(*vp));
+ VLISTNONE(vp); /* avoid double queue removal */
+ lck_mtx_init(&vp->v_lock, vnode_lck_grp, vnode_lck_attr);
+
+ klist_init(&vp->v_knotes);
+ nanouptime(&ts);
+ vp->v_id = ts.tv_nsec;
+ vp->v_flag = VSTANDARD;
+
+#if CONFIG_MACF
+ if (mac_vnode_label_init_needed(vp))
+ mac_vnode_label_init(vp);
+#endif /* MAC */
+
+ vp->v_iocount = 1;
+ goto done;
+ }
+
+#define MAX_WALK_COUNT 1000
+
+ if ( !TAILQ_EMPTY(&vnode_rage_list) &&
+ (ragevnodes >= rage_limit ||
+ (current_tv.tv_sec - rage_tv.tv_sec) >= RAGE_TIME_LIMIT)) {
+
+ TAILQ_FOREACH(vp, &vnode_rage_list, v_freelist) {
+ if ( !(vp->v_listflag & VLIST_RAGE))
+ panic("new_vnode: vp (%p) on RAGE list not marked VLIST_RAGE", vp);
+
+ // if we're a dependency-capable process, skip vnodes that can
+ // cause recycling deadlocks. (i.e. this process is diskimages
+ // helper and the vnode is in a disk image).
+ //
+ if ((curproc->p_flag & P_DEPENDENCY_CAPABLE) == 0 || vp->v_mount == NULL || vp->v_mount->mnt_dependent_process == NULL) {
+ break;
+ }
+
+ // don't iterate more than MAX_WALK_COUNT vnodes to
+ // avoid keeping the vnode list lock held for too long.
+ if (walk_count++ > MAX_WALK_COUNT) {
+ vp = NULL;
+ break;
+ }
+ }
+
+ }
+
+ if (vp == NULL && !TAILQ_EMPTY(&vnode_free_list)) {
+ /*
+ * Pick the first vp for possible reuse
+ */
+ walk_count = 0;
+ TAILQ_FOREACH(vp, &vnode_free_list, v_freelist) {
+ // if we're a dependency-capable process, skip vnodes that can
+ // cause recycling deadlocks. (i.e. this process is diskimages
+ // helper and the vnode is in a disk image)
+ //
+ if ((curproc->p_flag & P_DEPENDENCY_CAPABLE) == 0 || vp->v_mount == NULL || vp->v_mount->mnt_dependent_process == NULL) {
+ break;
+ }
+
+ // don't iterate more than MAX_WALK_COUNT vnodes to
+ // avoid keeping the vnode list lock held for too long.
+ if (walk_count++ > MAX_WALK_COUNT) {
+ vp = NULL;
+ break;
+ }
+ }
+
+ }
+
+ //
+ // if we don't have a vnode and the walk_count is >= MAX_WALK_COUNT
+ // then we're trying to create a vnode on behalf of a
+ // process like diskimages-helper that has file systems
+ // mounted on top of itself (and thus we can't reclaim
+ // vnodes in the file systems on top of us). if we can't
+ // find a vnode to reclaim then we'll just have to force
+ // the allocation.
+ //
+ if (vp == NULL && walk_count >= MAX_WALK_COUNT) {
+ force_alloc = 1;
+ vnode_list_unlock();
+ goto retry;
+ }
+
+ if (vp == NULL) {
+ /*
+ * we've reached the system imposed maximum number of vnodes
+ * but there isn't a single one available
+ * wait a bit and then retry... if we can't get a vnode
+ * after 100 retries, than log a complaint
+ */
+ if (++retries <= 100) {
+ vnode_list_unlock();
+ delay_for_interval(1, 1000 * 1000);
+ goto retry;
+ }
+
+ vnode_list_unlock();
+ tablefull("vnode");
+ log(LOG_EMERG, "%d desired, %d numvnodes, "
+ "%d free, %d dead, %d rage\n",
+ desiredvnodes, numvnodes, freevnodes, deadvnodes, ragevnodes);
+#if CONFIG_EMBEDDED
+ /*
+ * Running out of vnodes tends to make a system unusable. On an
+ * embedded system, it's unlikely that the user can do anything
+ * about it (or would know what to do, if they could). So panic
+ * the system so it will automatically restart (and hopefully we
+ * can get a panic log that tells us why we ran out).
+ */
+ panic("vnode table is full\n");
+#endif
+ *vpp = NULL;
+ return (ENFILE);
+ }
+steal_this_vp:
+ vpid = vp->v_id;
+
+ vnode_list_remove_locked(vp);
+
+ vnode_list_unlock();
+
+ vnode_lock_spin(vp);
+
+ /*
+ * We could wait for the vnode_lock after removing the vp from the freelist
+ * and the vid is bumped only at the very end of reclaim. So it is possible
+ * that we are looking at a vnode that is being terminated. If so skip it.
+ */
+ if ((vpid != vp->v_id) || (vp->v_usecount != 0) || (vp->v_iocount != 0) ||
+ VONLIST(vp) || (vp->v_lflag & VL_TERMINATE)) {
+ /*
+ * we lost the race between dropping the list lock
+ * and picking up the vnode_lock... someone else
+ * used this vnode and it is now in a new state
+ * so we need to go back and try again
+ */
+ vnode_unlock(vp);
+ goto retry;
+ }
+ if ( (vp->v_lflag & (VL_NEEDINACTIVE | VL_MARKTERM)) == VL_NEEDINACTIVE ) {
+ /*
+ * we did a vnode_rele_ext that asked for
+ * us not to reenter the filesystem during
+ * the release even though VL_NEEDINACTIVE was
+ * set... we'll do it here by doing a
+ * vnode_get/vnode_put
+ *
+ * pick up an iocount so that we can call
+ * vnode_put and drive the VNOP_INACTIVE...
+ * vnode_put will either leave us off
+ * the freelist if a new ref comes in,
+ * or put us back on the end of the freelist
+ * or recycle us if we were marked for termination...
+ * so we'll just go grab a new candidate
+ */
+ vp->v_iocount++;
+#ifdef JOE_DEBUG
+ record_vp(vp, 1);
+#endif
+ vnode_put_locked(vp);
+ vnode_unlock(vp);
+ goto retry;
+ }
+ OSAddAtomicLong(1, &num_reusedvnodes);
+
+ /* Checks for anyone racing us for recycle */
+ if (vp->v_type != VBAD) {
+ if (vp->v_lflag & VL_DEAD)
+ panic("new_vnode(%p): the vnode is VL_DEAD but not VBAD", vp);
+ vnode_lock_convert(vp);
+ (void)vnode_reclaim_internal(vp, 1, 1, 0);
+
+ if ((VONLIST(vp)))
+ panic("new_vnode(%p): vp on list", vp);
+ if (vp->v_usecount || vp->v_iocount || vp->v_kusecount ||
+ (vp->v_lflag & (VNAMED_UBC | VNAMED_MOUNT | VNAMED_FSHASH)))
+ panic("new_vnode(%p): free vnode still referenced", vp);
+ if ((vp->v_mntvnodes.tqe_prev != 0) && (vp->v_mntvnodes.tqe_next != 0))
+ panic("new_vnode(%p): vnode seems to be on mount list", vp);
+ if ( !LIST_EMPTY(&vp->v_nclinks) || !LIST_EMPTY(&vp->v_ncchildren))
+ panic("new_vnode(%p): vnode still hooked into the name cache", vp);
+ }
+
+#ifndef __LP64__
+ if (vp->v_unsafefs) {
+ l_unsafefs = vp->v_unsafefs;
+ vp->v_unsafefs = (struct unsafe_fsnode *)NULL;
+ }
+#endif /* __LP64__ */
+
+#if CONFIG_MACF
+ /*
+ * We should never see VL_LABELWAIT or VL_LABEL here.
+ * as those operations hold a reference.
+ */
+ assert ((vp->v_lflag & VL_LABELWAIT) != VL_LABELWAIT);
+ assert ((vp->v_lflag & VL_LABEL) != VL_LABEL);
+ if (vp->v_lflag & VL_LABELED) {
+ vnode_lock_convert(vp);
+ mac_vnode_label_recycle(vp);
+ } else if (mac_vnode_label_init_needed(vp)) {
+ vnode_lock_convert(vp);
+ mac_vnode_label_init(vp);
+ }
+
+#endif /* MAC */
+
+ vp->v_iocount = 1;
+ vp->v_lflag = 0;
+ vp->v_writecount = 0;
+ vp->v_references = 0;
+ vp->v_iterblkflags = 0;
+ vp->v_flag = VSTANDARD;
+ /* vbad vnodes can point to dead_mountp */
+ vp->v_mount = NULL;
+ vp->v_defer_reclaimlist = (vnode_t)0;
+
+ vnode_unlock(vp);
+
+#ifndef __LP64__
+ if (l_unsafefs) {
+ lck_mtx_destroy(&l_unsafefs->fsnodelock, vnode_lck_grp);
+ FREE_ZONE((void *)l_unsafefs, sizeof(struct unsafe_fsnode), M_UNSAFEFS);
+ }
+#endif /* __LP64__ */
+
+done:
+ *vpp = vp;
+
+ return (0);
+}
+
+void
+vnode_lock(vnode_t vp)
+{
+ lck_mtx_lock(&vp->v_lock);
+}
+
+void
+vnode_lock_spin(vnode_t vp)
+{
+ lck_mtx_lock_spin(&vp->v_lock);
+}
+
+void
+vnode_unlock(vnode_t vp)
+{
+ lck_mtx_unlock(&vp->v_lock);
+}
+
+
+
+int
+vnode_get(struct vnode *vp)
+{
+ int retval;
+
+ vnode_lock_spin(vp);
+ retval = vnode_get_locked(vp);
+ vnode_unlock(vp);
+
+ return(retval);
+}
+
+int
+vnode_get_locked(struct vnode *vp)
+{
+#if DIAGNOSTIC
+ lck_mtx_assert(&vp->v_lock, LCK_MTX_ASSERT_OWNED);
+#endif
+ if ((vp->v_iocount == 0) && (vp->v_lflag & (VL_TERMINATE | VL_DEAD))) {
+ return(ENOENT);
+ }
+ vp->v_iocount++;
+#ifdef JOE_DEBUG
+ record_vp(vp, 1);
+#endif
+ return (0);
+}
+
+int
+vnode_getwithvid(vnode_t vp, uint32_t vid)
+{
+ return(vget_internal(vp, vid, ( VNODE_NODEAD| VNODE_WITHID)));
+}
+
+int
+vnode_getwithref(vnode_t vp)
+{
+ return(vget_internal(vp, 0, 0));
+}
+
+
+__private_extern__ int
+vnode_getalways(vnode_t vp)
+{
+ return(vget_internal(vp, 0, VNODE_ALWAYS));
+}
+
+int
+vnode_put(vnode_t vp)
+{
+ int retval;
+
+ vnode_lock_spin(vp);
+ retval = vnode_put_locked(vp);
+ vnode_unlock(vp);
+
+ return(retval);
+}
+
+int
+vnode_put_locked(vnode_t vp)
+{
+ vfs_context_t ctx = vfs_context_current(); /* hoist outside loop */
+
+#if DIAGNOSTIC
+ lck_mtx_assert(&vp->v_lock, LCK_MTX_ASSERT_OWNED);
+#endif
+retry:
+ if (vp->v_iocount < 1)
+ panic("vnode_put(%p): iocount < 1", vp);
+
+ if ((vp->v_usecount > 0) || (vp->v_iocount > 1)) {
+ vnode_dropiocount(vp);
+ return(0);
+ }
+ if ((vp->v_lflag & (VL_MARKTERM | VL_TERMINATE | VL_DEAD | VL_NEEDINACTIVE)) == VL_NEEDINACTIVE) {
+
+ vp->v_lflag &= ~VL_NEEDINACTIVE;
+ vnode_unlock(vp);
+
+ VNOP_INACTIVE(vp, ctx);
+
+ vnode_lock_spin(vp);
+ /*
+ * because we had to drop the vnode lock before calling
+ * VNOP_INACTIVE, the state of this vnode may have changed...
+ * we may pick up both VL_MARTERM and either
+ * an iocount or a usecount while in the VNOP_INACTIVE call
+ * we don't want to call vnode_reclaim_internal on a vnode
+ * that has active references on it... so loop back around
+ * and reevaluate the state
+ */
+ goto retry;
+ }
+ vp->v_lflag &= ~VL_NEEDINACTIVE;
+
+ if ((vp->v_lflag & (VL_MARKTERM | VL_TERMINATE | VL_DEAD)) == VL_MARKTERM) {
+ vnode_lock_convert(vp);
+ vnode_reclaim_internal(vp, 1, 1, 0);
+ }
+ vnode_dropiocount(vp);
+ vnode_list_add(vp);
+
+ return(0);
+}
+
+/* is vnode_t in use by others? */
+int
+vnode_isinuse(vnode_t vp, int refcnt)
+{
+ return(vnode_isinuse_locked(vp, refcnt, 0));
+}
+
+
+static int
+vnode_isinuse_locked(vnode_t vp, int refcnt, int locked)
+{
+ int retval = 0;
+
+ if (!locked)
+ vnode_lock_spin(vp);
+ if ((vp->v_type != VREG) && ((vp->v_usecount - vp->v_kusecount) > refcnt)) {
+ retval = 1;
+ goto out;
+ }
+ if (vp->v_type == VREG) {
+ retval = ubc_isinuse_locked(vp, refcnt, 1);
+ }
+
+out:
+ if (!locked)
+ vnode_unlock(vp);
+ return(retval);
+}
+
+
+/* resume vnode_t */
+errno_t
+vnode_resume(vnode_t vp)
+{
+ if ((vp->v_lflag & VL_SUSPENDED) && vp->v_owner == current_thread()) {
+
+ vnode_lock_spin(vp);
+ vp->v_lflag &= ~VL_SUSPENDED;
+ vp->v_owner = NULL;
+ vnode_unlock(vp);
+
+ wakeup(&vp->v_iocount);
+ }
+ return(0);
+}
+
+/* suspend vnode_t
+ * Please do not use on more than one vnode at a time as it may
+ * cause deadlocks.
+ * xxx should we explicity prevent this from happening?
+ */
+
+errno_t
+vnode_suspend(vnode_t vp)
+{
+ if (vp->v_lflag & VL_SUSPENDED) {
+ return(EBUSY);
+ }
+
+ vnode_lock_spin(vp);
+
+ /*
+ * xxx is this sufficient to check if a vnode_drain is
+ * progress?
+ */
+
+ if (vp->v_owner == NULL) {
+ vp->v_lflag |= VL_SUSPENDED;
+ vp->v_owner = current_thread();
+ }
+ vnode_unlock(vp);
+
+ return(0);
+}
+
+
+
+static errno_t
+vnode_drain(vnode_t vp)
+{
+
+ if (vp->v_lflag & VL_DRAIN) {
+ panic("vnode_drain: recursuve drain");
+ return(ENOENT);
+ }
+ vp->v_lflag |= VL_DRAIN;
+ vp->v_owner = current_thread();
+
+ while (vp->v_iocount > 1)
+ msleep(&vp->v_iocount, &vp->v_lock, PVFS, "vnode_drain", NULL);
+ return(0);
+}
+
+
+/*
+ * if the number of recent references via vnode_getwithvid or vnode_getwithref
+ * exceeds this threshhold, than 'UN-AGE' the vnode by removing it from
+ * the LRU list if it's currently on it... once the iocount and usecount both drop
+ * to 0, it will get put back on the end of the list, effectively making it younger
+ * this allows us to keep actively referenced vnodes in the list without having
+ * to constantly remove and add to the list each time a vnode w/o a usecount is
+ * referenced which costs us taking and dropping a global lock twice.
+ */
+#define UNAGE_THRESHHOLD 25
+
+static errno_t
+vnode_getiocount(vnode_t vp, unsigned int vid, int vflags)
+{
+ int nodead = vflags & VNODE_NODEAD;
+ int nosusp = vflags & VNODE_NOSUSPEND;
+ int always = vflags & VNODE_ALWAYS;
+
+ for (;;) {
+ /*
+ * if it is a dead vnode with deadfs
+ */
+ if (nodead && (vp->v_lflag & VL_DEAD) && ((vp->v_type == VBAD) || (vp->v_data == 0))) {
+ return(ENOENT);
+ }
+ /*
+ * will return VL_DEAD ones
+ */
+ if ((vp->v_lflag & (VL_SUSPENDED | VL_DRAIN | VL_TERMINATE)) == 0 ) {
+ break;
+ }
+ /*
+ * if suspended vnodes are to be failed
+ */
+ if (nosusp && (vp->v_lflag & VL_SUSPENDED)) {
+ return(ENOENT);
+ }
+ /*
+ * if you are the owner of drain/suspend/termination , can acquire iocount
+ * check for VL_TERMINATE; it does not set owner
+ */
+ if ((vp->v_lflag & (VL_DRAIN | VL_SUSPENDED | VL_TERMINATE)) &&
+ (vp->v_owner == current_thread())) {
+ break;
+ }
+
+ if (always != 0)
+ break;
+ vnode_lock_convert(vp);
+
+ if (vp->v_lflag & VL_TERMINATE) {
+ vp->v_lflag |= VL_TERMWANT;
+
+ msleep(&vp->v_lflag, &vp->v_lock, PVFS, "vnode getiocount", NULL);
+ } else
+ msleep(&vp->v_iocount, &vp->v_lock, PVFS, "vnode_getiocount", NULL);
+ }
+ if (vid != vp->v_id) {
+ return(ENOENT);
+ }
+ if (++vp->v_references >= UNAGE_THRESHHOLD) {
+ vp->v_references = 0;
+ vnode_list_remove(vp);
+ }
+ vp->v_iocount++;
+#ifdef JOE_DEBUG
+ record_vp(vp, 1);
+#endif
+ return(0);
+}
+
+static void
+vnode_dropiocount (vnode_t vp)
+{
+ if (vp->v_iocount < 1)
+ panic("vnode_dropiocount(%p): v_iocount < 1", vp);
+
+ vp->v_iocount--;
+#ifdef JOE_DEBUG
+ record_vp(vp, -1);
+#endif
+ if ((vp->v_lflag & (VL_DRAIN | VL_SUSPENDED)) && (vp->v_iocount <= 1))
+ wakeup(&vp->v_iocount);
+}
+
+
+void
+vnode_reclaim(struct vnode * vp)
+{
+ vnode_reclaim_internal(vp, 0, 0, 0);
+}
+
+__private_extern__
+void
+vnode_reclaim_internal(struct vnode * vp, int locked, int reuse, int flags)
+{
+ int isfifo = 0;
+
+ if (!locked)
+ vnode_lock(vp);
+
+ if (vp->v_lflag & VL_TERMINATE) {
+ panic("vnode reclaim in progress");
+ }
+ vp->v_lflag |= VL_TERMINATE;
+
+ vn_clearunionwait(vp, 1);
+
+ vnode_drain(vp);
+
+ isfifo = (vp->v_type == VFIFO);
+
+ if (vp->v_type != VBAD)
+ vgone(vp, flags); /* clean and reclaim the vnode */
+
+ /*
+ * give the vnode a new identity so that vnode_getwithvid will fail
+ * on any stale cache accesses...
+ * grab the list_lock so that if we're in "new_vnode"
+ * behind the list_lock trying to steal this vnode, the v_id is stable...
+ * once new_vnode drops the list_lock, it will block trying to take
+ * the vnode lock until we release it... at that point it will evaluate
+ * whether the v_vid has changed
+ * also need to make sure that the vnode isn't on a list where "new_vnode"
+ * can find it after the v_id has been bumped until we are completely done
+ * with the vnode (i.e. putting it back on a list has to be the very last
+ * thing we do to this vnode... many of the callers of vnode_reclaim_internal
+ * are holding an io_count on the vnode... they need to drop the io_count
+ * BEFORE doing a vnode_list_add or make sure to hold the vnode lock until
+ * they are completely done with the vnode
+ */
+ vnode_list_lock();
+
+ vnode_list_remove_locked(vp);
+ vp->v_id++;
+
+ vnode_list_unlock();
+
+ if (isfifo) {
+ struct fifoinfo * fip;
+
+ fip = vp->v_fifoinfo;
+ vp->v_fifoinfo = NULL;
+ FREE(fip, M_TEMP);
+ }
+ vp->v_type = VBAD;
+
+ if (vp->v_data)
+ panic("vnode_reclaim_internal: cleaned vnode isn't");
+ if (vp->v_numoutput)
+ panic("vnode_reclaim_internal: clean vnode has pending I/O's");
+ if (UBCINFOEXISTS(vp))
+ panic("vnode_reclaim_internal: ubcinfo not cleaned");
+ if (vp->v_parent)
+ panic("vnode_reclaim_internal: vparent not removed");
+ if (vp->v_name)
+ panic("vnode_reclaim_internal: vname not removed");
+
+ vp->v_socket = NULL;
+
+ vp->v_lflag &= ~VL_TERMINATE;
+ vp->v_lflag &= ~VL_DRAIN;
+ vp->v_owner = NULL;
+
+ KNOTE(&vp->v_knotes, NOTE_REVOKE);
+
+ /* Make sure that when we reuse the vnode, no knotes left over */
+ klist_init(&vp->v_knotes);
+
+ if (vp->v_lflag & VL_TERMWANT) {
+ vp->v_lflag &= ~VL_TERMWANT;
+ wakeup(&vp->v_lflag);
+ }
+ if (!reuse) {
+ /*
+ * make sure we get on the
+ * dead list if appropriate
+ */
+ vnode_list_add(vp);
+ }
+ if (!locked)
+ vnode_unlock(vp);
+}
+
+/* USAGE:
+ * The following api creates a vnode and associates all the parameter specified in vnode_fsparam
+ * structure and returns a vnode handle with a reference. device aliasing is handled here so checkalias
+ * is obsoleted by this.
+ * vnode_create(int flavor, size_t size, void * param, vnode_t *vp)
+ */
+int
+vnode_create(uint32_t flavor, uint32_t size, void *data, vnode_t *vpp)
+{
+ int error;
+ int insert = 1;
+ vnode_t vp;
+ vnode_t nvp;
+ vnode_t dvp;
+ struct uthread *ut;
+ struct componentname *cnp;
+ struct vnode_fsparam *param = (struct vnode_fsparam *)data;
+
+ if (flavor == VNCREATE_FLAVOR && (size == VCREATESIZE) && param) {
+ if ( (error = new_vnode(&vp)) ) {
+ return(error);
+ } else {
+ dvp = param->vnfs_dvp;
+ cnp = param->vnfs_cnp;
+
+ vp->v_op = param->vnfs_vops;
+ vp->v_type = param->vnfs_vtype;
+ vp->v_data = param->vnfs_fsnode;
+
+ if (param->vnfs_markroot)
+ vp->v_flag |= VROOT;
+ if (param->vnfs_marksystem)
+ vp->v_flag |= VSYSTEM;
+ if (vp->v_type == VREG) {
+ error = ubc_info_init_withsize(vp, param->vnfs_filesize);
+ if (error) {
+#ifdef JOE_DEBUG
+ record_vp(vp, 1);
+#endif
+ vp->v_mount = NULL;
+ vp->v_op = dead_vnodeop_p;
+ vp->v_tag = VT_NON;
+ vp->v_data = NULL;
+ vp->v_type = VBAD;
+ vp->v_lflag |= VL_DEAD;
+
+ vnode_put(vp);
+ return(error);
+ }
+ }
+#ifdef JOE_DEBUG
+ record_vp(vp, 1);
+#endif
+ if (vp->v_type == VCHR || vp->v_type == VBLK) {
+
+ vp->v_tag = VT_DEVFS; /* callers will reset if needed (bdevvp) */
+
+ if ( (nvp = checkalias(vp, param->vnfs_rdev)) ) {
+ /*
+ * if checkalias returns a vnode, it will be locked
+ *
+ * first get rid of the unneeded vnode we acquired
+ */
+ vp->v_data = NULL;
+ vp->v_op = spec_vnodeop_p;
+ vp->v_type = VBAD;
+ vp->v_lflag = VL_DEAD;
+ vp->v_data = NULL;
+ vp->v_tag = VT_NON;
+ vnode_put(vp);
+
+ /*
+ * switch to aliased vnode and finish
+ * preparing it
+ */
+ vp = nvp;
+
+ vclean(vp, 0);
+ vp->v_op = param->vnfs_vops;
+ vp->v_type = param->vnfs_vtype;
+ vp->v_data = param->vnfs_fsnode;
+ vp->v_lflag = 0;
+ vp->v_mount = NULL;
+ insmntque(vp, param->vnfs_mp);
+ insert = 0;
+ vnode_unlock(vp);
+ }
+ }
+
+ if (vp->v_type == VFIFO) {
+ struct fifoinfo *fip;
+
+ MALLOC(fip, struct fifoinfo *,
+ sizeof(*fip), M_TEMP, M_WAITOK);
+ bzero(fip, sizeof(struct fifoinfo ));
+ vp->v_fifoinfo = fip;
+ }
+ /* The file systems must pass the address of the location where
+ * they store the vnode pointer. When we add the vnode into the mount
+ * list and name cache they become discoverable. So the file system node
+ * must have the connection to vnode setup by then
+ */
+ *vpp = vp;
+
+ /* Add fs named reference. */
+ if (param->vnfs_flags & VNFS_ADDFSREF) {
+ vp->v_lflag |= VNAMED_FSHASH;
+ }
+ if (param->vnfs_mp) {
+ if (param->vnfs_mp->mnt_kern_flag & MNTK_LOCK_LOCAL)
+ vp->v_flag |= VLOCKLOCAL;
+ if (insert) {
+ if ((vp->v_freelist.tqe_prev != (struct vnode **)0xdeadb))
+ panic("insmntque: vp on the free list\n");
+ /*
+ * enter in mount vnode list
+ */
+ insmntque(vp, param->vnfs_mp);
+ }
+#ifndef __LP64__
+ if ((param->vnfs_mp->mnt_vtable->vfc_vfsflags & VFC_VFSTHREADSAFE) == 0) {
+ MALLOC_ZONE(vp->v_unsafefs, struct unsafe_fsnode *,
+ sizeof(struct unsafe_fsnode), M_UNSAFEFS, M_WAITOK);
+ vp->v_unsafefs->fsnode_count = 0;
+ vp->v_unsafefs->fsnodeowner = (void *)NULL;
+ lck_mtx_init(&vp->v_unsafefs->fsnodelock, vnode_lck_grp, vnode_lck_attr);
+ }
+#endif /* __LP64__ */
+ }
+ if (dvp && vnode_ref(dvp) == 0) {
+ vp->v_parent = dvp;
+ }
+ if (cnp) {
+ if (dvp && ((param->vnfs_flags & (VNFS_NOCACHE | VNFS_CANTCACHE)) == 0)) {
+ /*
+ * enter into name cache
+ * we've got the info to enter it into the name cache now
+ * cache_enter_create will pick up an extra reference on
+ * the name entered into the string cache
+ */
+ vp->v_name = cache_enter_create(dvp, vp, cnp);
+ } else
+ vp->v_name = vfs_addname(cnp->cn_nameptr, cnp->cn_namelen, cnp->cn_hash, 0);
+
+ if ((cnp->cn_flags & UNIONCREATED) == UNIONCREATED)
+ vp->v_flag |= VISUNION;
+ }
+ if ((param->vnfs_flags & VNFS_CANTCACHE) == 0) {
+ /*
+ * this vnode is being created as cacheable in the name cache
+ * this allows us to re-enter it in the cache
+ */
+ vp->v_flag |= VNCACHEABLE;
+ }
+ ut = get_bsdthread_info(current_thread());
+
+ if ((current_proc()->p_lflag & P_LRAGE_VNODES) ||
+ (ut->uu_flag & UT_RAGE_VNODES)) {
+ /*
+ * process has indicated that it wants any
+ * vnodes created on its behalf to be rapidly
+ * aged to reduce the impact on the cached set
+ * of vnodes
+ */
+ vp->v_flag |= VRAGE;
+ }
+ return(0);
+ }
+ }
+ return (EINVAL);
+}
+
+int
+vnode_addfsref(vnode_t vp)
+{
+ vnode_lock_spin(vp);
+ if (vp->v_lflag & VNAMED_FSHASH)
+ panic("add_fsref: vp already has named reference");
+ if ((vp->v_freelist.tqe_prev != (struct vnode **)0xdeadb))
+ panic("addfsref: vp on the free list\n");
+ vp->v_lflag |= VNAMED_FSHASH;
+ vnode_unlock(vp);
+ return(0);
+
+}
+int
+vnode_removefsref(vnode_t vp)
+{
+ vnode_lock_spin(vp);
+ if ((vp->v_lflag & VNAMED_FSHASH) == 0)
+ panic("remove_fsref: no named reference");
+ vp->v_lflag &= ~VNAMED_FSHASH;
+ vnode_unlock(vp);
+ return(0);
+
+}
+
+
+int
+vfs_iterate(__unused int flags, int (*callout)(mount_t, void *), void *arg)
+{
+ mount_t mp;
+ int ret = 0;
+ fsid_t * fsid_list;
+ int count, actualcount, i;
+ void * allocmem;
+
+ count = mount_getvfscnt();
+ count += 10;
+
+ fsid_list = (fsid_t *)kalloc(count * sizeof(fsid_t));
+ allocmem = (void *)fsid_list;
+
+ actualcount = mount_fillfsids(fsid_list, count);
+
+ for (i=0; i< actualcount; i++) {
+
+ /* obtain the mount point with iteration reference */
+ mp = mount_list_lookupby_fsid(&fsid_list[i], 0, 1);
+
+ if(mp == (struct mount *)0)
+ continue;
+ mount_lock(mp);
+ if (mp->mnt_lflag & (MNT_LDEAD | MNT_LUNMOUNT)) {
+ mount_unlock(mp);
+ mount_iterdrop(mp);
+ continue;
+
+ }
+ mount_unlock(mp);
+
+ /* iterate over all the vnodes */
+ ret = callout(mp, arg);
+
+ mount_iterdrop(mp);
+
+ switch (ret) {
+ case VFS_RETURNED:
+ case VFS_RETURNED_DONE:
+ if (ret == VFS_RETURNED_DONE) {
+ ret = 0;
+ goto out;
+ }
+ break;
+
+ case VFS_CLAIMED_DONE:
+ ret = 0;
+ goto out;
+ case VFS_CLAIMED:
+ default:
+ break;
+ }
+ ret = 0;
+ }
+
+out:
+ kfree(allocmem, (count * sizeof(fsid_t)));
+ return (ret);
+}
+
+/*
+ * Update the vfsstatfs structure in the mountpoint.
+ * MAC: Parameter eventtype added, indicating whether the event that
+ * triggered this update came from user space, via a system call
+ * (VFS_USER_EVENT) or an internal kernel call (VFS_KERNEL_EVENT).
+ */
+int
+vfs_update_vfsstat(mount_t mp, vfs_context_t ctx, __unused int eventtype)
+{
+ struct vfs_attr va;
+ int error;
+
+ /*
+ * Request the attributes we want to propagate into
+ * the per-mount vfsstat structure.
+ */
+ VFSATTR_INIT(&va);
+ VFSATTR_WANTED(&va, f_iosize);
+ VFSATTR_WANTED(&va, f_blocks);
+ VFSATTR_WANTED(&va, f_bfree);
+ VFSATTR_WANTED(&va, f_bavail);
+ VFSATTR_WANTED(&va, f_bused);
+ VFSATTR_WANTED(&va, f_files);
+ VFSATTR_WANTED(&va, f_ffree);
+ VFSATTR_WANTED(&va, f_bsize);
+ VFSATTR_WANTED(&va, f_fssubtype);
+#if CONFIG_MACF
+ if (eventtype == VFS_USER_EVENT) {
+ error = mac_mount_check_getattr(ctx, mp, &va);
+ if (error != 0)
+ return (error);
+ }
+#endif
+
+ if ((error = vfs_getattr(mp, &va, ctx)) != 0) {
+ KAUTH_DEBUG("STAT - filesystem returned error %d", error);
+ return(error);
+ }
+
+ /*
+ * Unpack into the per-mount structure.
+ *
+ * We only overwrite these fields, which are likely to change:
+ * f_blocks
+ * f_bfree
+ * f_bavail
+ * f_bused
+ * f_files
+ * f_ffree
+ *
+ * And these which are not, but which the FS has no other way
+ * of providing to us:
+ * f_bsize
+ * f_iosize
+ * f_fssubtype
+ *
+ */
+ if (VFSATTR_IS_SUPPORTED(&va, f_bsize)) {
+ /* 4822056 - protect against malformed server mount */
+ mp->mnt_vfsstat.f_bsize = (va.f_bsize > 0 ? va.f_bsize : 512);
+ } else {
+ mp->mnt_vfsstat.f_bsize = mp->mnt_devblocksize; /* default from the device block size */
+ }
+ if (VFSATTR_IS_SUPPORTED(&va, f_iosize)) {
+ mp->mnt_vfsstat.f_iosize = va.f_iosize;
+ } else {
+ mp->mnt_vfsstat.f_iosize = 1024 * 1024; /* 1MB sensible I/O size */
+ }
+ if (VFSATTR_IS_SUPPORTED(&va, f_blocks))
+ mp->mnt_vfsstat.f_blocks = va.f_blocks;
+ if (VFSATTR_IS_SUPPORTED(&va, f_bfree))
+ mp->mnt_vfsstat.f_bfree = va.f_bfree;
+ if (VFSATTR_IS_SUPPORTED(&va, f_bavail))
+ mp->mnt_vfsstat.f_bavail = va.f_bavail;
+ if (VFSATTR_IS_SUPPORTED(&va, f_bused))
+ mp->mnt_vfsstat.f_bused = va.f_bused;
+ if (VFSATTR_IS_SUPPORTED(&va, f_files))
+ mp->mnt_vfsstat.f_files = va.f_files;
+ if (VFSATTR_IS_SUPPORTED(&va, f_ffree))
+ mp->mnt_vfsstat.f_ffree = va.f_ffree;
+
+ /* this is unlikely to change, but has to be queried for */
+ if (VFSATTR_IS_SUPPORTED(&va, f_fssubtype))
+ mp->mnt_vfsstat.f_fssubtype = va.f_fssubtype;
+
+ return(0);
+}
+
+int
+mount_list_add(mount_t mp)
+{
+ int res;
+
+ mount_list_lock();
+ if (system_inshutdown != 0) {
+ res = -1;
+ } else {
+ TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
+ nummounts++;
+ res = 0;
+ }
+ mount_list_unlock();
+
+ return res;
+}
+
+void
+mount_list_remove(mount_t mp)
+{
+ mount_list_lock();
+ TAILQ_REMOVE(&mountlist, mp, mnt_list);
+ nummounts--;
+ mp->mnt_list.tqe_next = NULL;
+ mp->mnt_list.tqe_prev = NULL;
+ mount_list_unlock();
+}
+
+mount_t
+mount_lookupby_volfsid(int volfs_id, int withref)
+{
+ mount_t cur_mount = (mount_t)0;
+ mount_t mp;
+
+ mount_list_lock();
+ TAILQ_FOREACH(mp, &mountlist, mnt_list) {
+ if (!(mp->mnt_kern_flag & MNTK_UNMOUNT) &&
+ (mp->mnt_kern_flag & MNTK_PATH_FROM_ID) &&
+ (mp->mnt_vfsstat.f_fsid.val[0] == volfs_id)) {
+ cur_mount = mp;
+ if (withref) {
+ if (mount_iterref(cur_mount, 1)) {
+ cur_mount = (mount_t)0;
+ mount_list_unlock();
+ goto out;
+ }
+ }
+ break;
+ }
+ }
+ mount_list_unlock();
+ if (withref && (cur_mount != (mount_t)0)) {
+ mp = cur_mount;
+ if (vfs_busy(mp, LK_NOWAIT) != 0) {
+ cur_mount = (mount_t)0;
+ }
+ mount_iterdrop(mp);
+ }
+out:
+ return(cur_mount);
+}
+
+mount_t
+mount_list_lookupby_fsid(fsid_t *fsid, int locked, int withref)
+{
+ mount_t retmp = (mount_t)0;
+ mount_t mp;
+
+ if (!locked)
+ mount_list_lock();
+ TAILQ_FOREACH(mp, &mountlist, mnt_list)
+ if (mp->mnt_vfsstat.f_fsid.val[0] == fsid->val[0] &&
+ mp->mnt_vfsstat.f_fsid.val[1] == fsid->val[1]) {
+ retmp = mp;
+ if (withref) {
+ if (mount_iterref(retmp, 1))
+ retmp = (mount_t)0;
+ }
+ goto out;
+ }
+out:
+ if (!locked)
+ mount_list_unlock();
+ return (retmp);
+}
+
+errno_t
+vnode_lookup(const char *path, int flags, vnode_t *vpp, vfs_context_t ctx)
+{
+ struct nameidata nd;
+ int error;
+ u_int32_t ndflags = 0;
+
+ if (ctx == NULL) { /* XXX technically an error */
+ ctx = vfs_context_current();
+ }
+
+ if (flags & VNODE_LOOKUP_NOFOLLOW)
+ ndflags = NOFOLLOW;
+ else
+ ndflags = FOLLOW;
+
+ if (flags & VNODE_LOOKUP_NOCROSSMOUNT)
+ ndflags |= NOCROSSMOUNT;
+ if (flags & VNODE_LOOKUP_DOWHITEOUT)
+ ndflags |= DOWHITEOUT;
+
+ /* XXX AUDITVNPATH1 needed ? */
+ NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, CAST_USER_ADDR_T(path), ctx);
+
+ if ((error = namei(&nd)))
+ return (error);
+ *vpp = nd.ni_vp;
+ nameidone(&nd);
+
+ return (0);
+}
+
+errno_t
+vnode_open(const char *path, int fmode, int cmode, int flags, vnode_t *vpp, vfs_context_t ctx)
+{
+ struct nameidata nd;
+ int error;
+ u_int32_t ndflags = 0;
+ int lflags = flags;
+
+ if (ctx == NULL) { /* XXX technically an error */
+ ctx = vfs_context_current();
+ }
+
+ if (fmode & O_NOFOLLOW)
+ lflags |= VNODE_LOOKUP_NOFOLLOW;
+
+ if (lflags & VNODE_LOOKUP_NOFOLLOW)
+ ndflags = NOFOLLOW;
+ else
+ ndflags = FOLLOW;
+
+ if (lflags & VNODE_LOOKUP_NOCROSSMOUNT)
+ ndflags |= NOCROSSMOUNT;
+ if (lflags & VNODE_LOOKUP_DOWHITEOUT)
+ ndflags |= DOWHITEOUT;
+
+ /* XXX AUDITVNPATH1 needed ? */
+ NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, CAST_USER_ADDR_T(path), ctx);
+
+ if ((error = vn_open(&nd, fmode, cmode)))
+ *vpp = NULL;
+ else
+ *vpp = nd.ni_vp;
+
+ return (error);
+}
+
+errno_t
+vnode_close(vnode_t vp, int flags, vfs_context_t ctx)
+{
+ int error;
+
+ if (ctx == NULL) {
+ ctx = vfs_context_current();
+ }
+
+ error = vn_close(vp, flags, ctx);
+ vnode_put(vp);
+ return (error);
+}
+
+/*
+ * Returns: 0 Success
+ * vnode_getattr:???
+ */
+errno_t
+vnode_size(vnode_t vp, off_t *sizep, vfs_context_t ctx)
+{
+ struct vnode_attr va;
+ int error;
+
+ VATTR_INIT(&va);
+ VATTR_WANTED(&va, va_data_size);
+ error = vnode_getattr(vp, &va, ctx);
+ if (!error)
+ *sizep = va.va_data_size;
+ return(error);
+}
+
+errno_t
+vnode_setsize(vnode_t vp, off_t size, int ioflag, vfs_context_t ctx)
+{
+ struct vnode_attr va;
+
+ VATTR_INIT(&va);
+ VATTR_SET(&va, va_data_size, size);
+ va.va_vaflags = ioflag & 0xffff;
+ return(vnode_setattr(vp, &va, ctx));
+}
+
+/*
+ * Create a filesystem object of arbitrary type with arbitrary attributes in
+ * the spevied directory with the specified name.
+ *
+ * Parameters: dvp Pointer to the vnode of the directory
+ * in which to create the object.
+ * vpp Pointer to the area into which to
+ * return the vnode of the created object.
+ * cnp Component name pointer from the namei
+ * data structure, containing the name to
+ * use for the create object.
+ * vap Pointer to the vnode_attr structure
+ * describing the object to be created,
+ * including the type of object.
+ * flags VN_* flags controlling ACL inheritance
+ * and whether or not authorization is to
+ * be required for the operation.
+ *
+ * Returns: 0 Success
+ * !0 errno value
+ *
+ * Implicit: *vpp Contains the vnode of the object that
+ * was created, if successful.
+ * *cnp May be modified by the underlying VFS.
+ * *vap May be modified by the underlying VFS.
+ * modified by either ACL inheritance or
+ *
+ *
+ * be modified, even if the operation is
+ *
+ *
+ * Notes: The kauth_filesec_t in 'vap', if any, is in host byte order.
+ *
+ * Modification of '*cnp' and '*vap' by the underlying VFS is
+ * strongly discouraged.
+ *
+ * XXX: This function is a 'vn_*' function; it belongs in vfs_vnops.c
+ *
+ * XXX: We should enummerate the possible errno values here, and where
+ * in the code they originated.
+ */
+errno_t
+vn_create(vnode_t dvp, vnode_t *vpp, struct componentname *cnp, struct vnode_attr *vap, int flags, vfs_context_t ctx)
+{
+ kauth_acl_t oacl, nacl;
+ int initial_acl;
+ errno_t error;
+ vnode_t vp = (vnode_t)0;
+
+ error = 0;
+ oacl = nacl = NULL;
+ initial_acl = 0;
+
+ KAUTH_DEBUG("%p CREATE - '%s'", dvp, cnp->cn_nameptr);
+
+ /*
+ * Handle ACL inheritance.
+ */
+ if (!(flags & VN_CREATE_NOINHERIT) && vfs_extendedsecurity(dvp->v_mount)) {
+ /* save the original filesec */
+ if (VATTR_IS_ACTIVE(vap, va_acl)) {
+ initial_acl = 1;
+ oacl = vap->va_acl;
+ }
+
+ vap->va_acl = NULL;
+ if ((error = kauth_acl_inherit(dvp,
+ oacl,
+ &nacl,
+ vap->va_type == VDIR,
+ ctx)) != 0) {
+ KAUTH_DEBUG("%p CREATE - error %d processing inheritance", dvp, error);
+ return(error);
+ }
+
+ /*
+ * If the generated ACL is NULL, then we can save ourselves some effort
+ * by clearing the active bit.
+ */
+ if (nacl == NULL) {
+ VATTR_CLEAR_ACTIVE(vap, va_acl);
+ } else {
+ VATTR_SET(vap, va_acl, nacl);
+ }
+ }
+
+ /*
+ * Check and default new attributes.
+ * This will set va_uid, va_gid, va_mode and va_create_time at least, if the caller
+ * hasn't supplied them.
+ */
+ if ((error = vnode_authattr_new(dvp, vap, flags & VN_CREATE_NOAUTH, ctx)) != 0) {
+ KAUTH_DEBUG("%p CREATE - error %d handing/defaulting attributes", dvp, error);
+ goto out;
+ }
+
+
+ /*
+ * Create the requested node.
+ */
+ switch(vap->va_type) {
+ case VREG:
+ error = VNOP_CREATE(dvp, vpp, cnp, vap, ctx);
+ break;
+ case VDIR:
+ error = VNOP_MKDIR(dvp, vpp, cnp, vap, ctx);
+ break;
+ case VSOCK:
+ case VFIFO:
+ case VBLK:
+ case VCHR:
+ error = VNOP_MKNOD(dvp, vpp, cnp, vap, ctx);
+ break;
+ default:
+ panic("vnode_create: unknown vtype %d", vap->va_type);
+ }
+ if (error != 0) {
+ KAUTH_DEBUG("%p CREATE - error %d returned by filesystem", dvp, error);
+ goto out;
+ }
+
+ vp = *vpp;
+#if CONFIG_MACF
+ if (!(flags & VN_CREATE_NOLABEL)) {
+ error = vnode_label(vnode_mount(vp), dvp, vp, cnp, VNODE_LABEL_CREATE, ctx);
+ if (error)
+ goto error;
+ }
+#endif
+
+ /*
+ * If some of the requested attributes weren't handled by the VNOP,
+ * use our fallback code.
+ */
+ if (!VATTR_ALL_SUPPORTED(vap) && *vpp) {
+ KAUTH_DEBUG(" CREATE - doing fallback with ACL %p", vap->va_acl);
+ error = vnode_setattr_fallback(*vpp, vap, ctx);
+ }
+#if CONFIG_MACF
+error:
+#endif
+ if ((error != 0 ) && (vp != (vnode_t)0)) {
+ *vpp = (vnode_t) 0;
+ vnode_put(vp);
+ }
+
+out:
+ /*
+ * If the caller supplied a filesec in vap, it has been replaced
+ * now by the post-inheritance copy. We need to put the original back
+ * and free the inherited product.
+ */
+ if (initial_acl) {
+ VATTR_SET(vap, va_acl, oacl);
+ } else {
+ VATTR_CLEAR_ACTIVE(vap, va_acl);
+ }
+ if (nacl != NULL)
+ kauth_acl_free(nacl);
+
+ return(error);
+}
+
+static kauth_scope_t vnode_scope;
+static int vnode_authorize_callback(kauth_cred_t credential, void *idata, kauth_action_t action,
+ uintptr_t arg0, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3);
+static int vnode_authorize_callback_int(__unused kauth_cred_t credential, __unused void *idata, kauth_action_t action,
+ uintptr_t arg0, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3);
+
+typedef struct _vnode_authorize_context {
+ vnode_t vp;
+ struct vnode_attr *vap;
+ vnode_t dvp;
+ struct vnode_attr *dvap;
+ vfs_context_t ctx;
+ int flags;
+ int flags_valid;
+#define _VAC_IS_OWNER (1<<0)
+#define _VAC_IN_GROUP (1<<1)
+#define _VAC_IS_DIR_OWNER (1<<2)
+#define _VAC_IN_DIR_GROUP (1<<3)
+} *vauth_ctx;
+
+void
+vnode_authorize_init(void)
+{
+ vnode_scope = kauth_register_scope(KAUTH_SCOPE_VNODE, vnode_authorize_callback, NULL);
+}
+
+/*
+ * Authorize an operation on a vnode.
+ *
+ * This is KPI, but here because it needs vnode_scope.
+ *
+ * Returns: 0 Success
+ * kauth_authorize_action:EPERM ...
+ * xlate => EACCES Permission denied
+ * kauth_authorize_action:0 Success
+ * kauth_authorize_action: Depends on callback return; this is
+ * usually only vnode_authorize_callback(),
+ * but may include other listerners, if any
+ * exist.
+ * EROFS
+ * EACCES
+ * EPERM
+ * ???
+ */
+int
+vnode_authorize(vnode_t vp, vnode_t dvp, kauth_action_t action, vfs_context_t ctx)
+{
+ int error, result;
+
+ /*
+ * We can't authorize against a dead vnode; allow all operations through so that
+ * the correct error can be returned.
+ */
+ if (vp->v_type == VBAD)
+ return(0);
+
+ error = 0;
+ result = kauth_authorize_action(vnode_scope, vfs_context_ucred(ctx), action,
+ (uintptr_t)ctx, (uintptr_t)vp, (uintptr_t)dvp, (uintptr_t)&error);
+ if (result == EPERM) /* traditional behaviour */
+ result = EACCES;
+ /* did the lower layers give a better error return? */
+ if ((result != 0) && (error != 0))
+ return(error);
+ return(result);
+}
+
+/*
+ * Test for vnode immutability.
+ *
+ * The 'append' flag is set when the authorization request is constrained
+ * to operations which only request the right to append to a file.
+ *
+ * The 'ignore' flag is set when an operation modifying the immutability flags
+ * is being authorized. We check the system securelevel to determine which
+ * immutability flags we can ignore.
+ */
+static int
+vnode_immutable(struct vnode_attr *vap, int append, int ignore)
+{
+ int mask;
+
+ /* start with all bits precluding the operation */
+ mask = IMMUTABLE | APPEND;
+
+ /* if appending only, remove the append-only bits */
+ if (append)
+ mask &= ~APPEND;
+
+ /* ignore only set when authorizing flags changes */
+ if (ignore) {
+ if (securelevel <= 0) {
+ /* in insecure state, flags do not inhibit changes */
+ mask = 0;
+ } else {
+ /* in secure state, user flags don't inhibit */
+ mask &= ~(UF_IMMUTABLE | UF_APPEND);
+ }
+ }
+ KAUTH_DEBUG("IMMUTABLE - file flags 0x%x mask 0x%x append = %d ignore = %d", vap->va_flags, mask, append, ignore);
+ if ((vap->va_flags & mask) != 0)
+ return(EPERM);
+ return(0);
+}
+
+static int
+vauth_node_owner(struct vnode_attr *vap, kauth_cred_t cred)
+{
+ int result;
+
+ /* default assumption is not-owner */
+ result = 0;
+
+ /*
+ * If the filesystem has given us a UID, we treat this as authoritative.
+ */
+ if (vap && VATTR_IS_SUPPORTED(vap, va_uid)) {
+ result = (vap->va_uid == kauth_cred_getuid(cred)) ? 1 : 0;
+ }
+ /* we could test the owner UUID here if we had a policy for it */
+
+ return(result);
+}
+
+static int
+vauth_node_group(struct vnode_attr *vap, kauth_cred_t cred, int *ismember)
+{
+ int error;
+ int result;
+
+ error = 0;
+ result = 0;
+
+ /* the caller is expected to have asked the filesystem for a group at some point */
+ if (vap && VATTR_IS_SUPPORTED(vap, va_gid)) {
+ error = kauth_cred_ismember_gid(cred, vap->va_gid, &result);
+ }
+ /* we could test the group UUID here if we had a policy for it */
+
+ if (!error)
+ *ismember = result;
+ return(error);
+}
+
+static int
+vauth_file_owner(vauth_ctx vcp)
+{
+ int result;
+
+ if (vcp->flags_valid & _VAC_IS_OWNER) {
+ result = (vcp->flags & _VAC_IS_OWNER) ? 1 : 0;
+ } else {
+ result = vauth_node_owner(vcp->vap, vcp->ctx->vc_ucred);
+
+ /* cache our result */
+ vcp->flags_valid |= _VAC_IS_OWNER;
+ if (result) {
+ vcp->flags |= _VAC_IS_OWNER;
+ } else {
+ vcp->flags &= ~_VAC_IS_OWNER;
+ }
+ }
+ return(result);
+}
+
+static int
+vauth_file_ingroup(vauth_ctx vcp, int *ismember)
+{
+ int error;
+
+ if (vcp->flags_valid & _VAC_IN_GROUP) {
+ *ismember = (vcp->flags & _VAC_IN_GROUP) ? 1 : 0;
+ error = 0;
+ } else {
+ error = vauth_node_group(vcp->vap, vcp->ctx->vc_ucred, ismember);
+
+ if (!error) {
+ /* cache our result */
+ vcp->flags_valid |= _VAC_IN_GROUP;
+ if (*ismember) {
+ vcp->flags |= _VAC_IN_GROUP;
+ } else {
+ vcp->flags &= ~_VAC_IN_GROUP;
+ }
+ }
+
+ }
+ return(error);
+}
+
+static int
+vauth_dir_owner(vauth_ctx vcp)
+{
+ int result;
+
+ if (vcp->flags_valid & _VAC_IS_DIR_OWNER) {
+ result = (vcp->flags & _VAC_IS_DIR_OWNER) ? 1 : 0;
+ } else {
+ result = vauth_node_owner(vcp->dvap, vcp->ctx->vc_ucred);
+
+ /* cache our result */
+ vcp->flags_valid |= _VAC_IS_DIR_OWNER;
+ if (result) {
+ vcp->flags |= _VAC_IS_DIR_OWNER;
+ } else {
+ vcp->flags &= ~_VAC_IS_DIR_OWNER;
+ }
+ }
+ return(result);
+}
+
+static int
+vauth_dir_ingroup(vauth_ctx vcp, int *ismember)
+{
+ int error;
+
+ if (vcp->flags_valid & _VAC_IN_DIR_GROUP) {
+ *ismember = (vcp->flags & _VAC_IN_DIR_GROUP) ? 1 : 0;
+ error = 0;
+ } else {
+ error = vauth_node_group(vcp->dvap, vcp->ctx->vc_ucred, ismember);
+
+ if (!error) {
+ /* cache our result */
+ vcp->flags_valid |= _VAC_IN_DIR_GROUP;
+ if (*ismember) {
+ vcp->flags |= _VAC_IN_DIR_GROUP;
+ } else {
+ vcp->flags &= ~_VAC_IN_DIR_GROUP;
+ }
+ }
+ }
+ return(error);
+}
+
+/*
+ * Test the posix permissions in (vap) to determine whether (credential)
+ * may perform (action)
+ */
+static int
+vnode_authorize_posix(vauth_ctx vcp, int action, int on_dir)
+{
+ struct vnode_attr *vap;
+ int needed, error, owner_ok, group_ok, world_ok, ismember;
+#ifdef KAUTH_DEBUG_ENABLE
+ const char *where = "uninitialized";
+# define _SETWHERE(c) where = c;
+#else
+# define _SETWHERE(c)
+#endif
+
+ /* checking file or directory? */
+ if (on_dir) {
+ vap = vcp->dvap;
+ } else {
+ vap = vcp->vap;
+ }
+
+ error = 0;
+
+ /*
+ * We want to do as little work here as possible. So first we check
+ * which sets of permissions grant us the access we need, and avoid checking
+ * whether specific permissions grant access when more generic ones would.
+ */
+
+ /* owner permissions */
+ needed = 0;
+ if (action & VREAD)
+ needed |= S_IRUSR;
+ if (action & VWRITE)
+ needed |= S_IWUSR;
+ if (action & VEXEC)
+ needed |= S_IXUSR;
+ owner_ok = (needed & vap->va_mode) == needed;
+
+ /* group permissions */
+ needed = 0;
+ if (action & VREAD)
+ needed |= S_IRGRP;
+ if (action & VWRITE)
+ needed |= S_IWGRP;
+ if (action & VEXEC)
+ needed |= S_IXGRP;
+ group_ok = (needed & vap->va_mode) == needed;
+
+ /* world permissions */
+ needed = 0;
+ if (action & VREAD)
+ needed |= S_IROTH;
+ if (action & VWRITE)
+ needed |= S_IWOTH;
+ if (action & VEXEC)
+ needed |= S_IXOTH;
+ world_ok = (needed & vap->va_mode) == needed;
+
+ /* If granted/denied by all three, we're done */
+ if (owner_ok && group_ok && world_ok) {
+ _SETWHERE("all");
+ goto out;
+ }
+ if (!owner_ok && !group_ok && !world_ok) {
+ _SETWHERE("all");
+ error = EACCES;
+ goto out;
+ }
+
+ /* Check ownership (relatively cheap) */
+ if ((on_dir && vauth_dir_owner(vcp)) ||
+ (!on_dir && vauth_file_owner(vcp))) {
+ _SETWHERE("user");
+ if (!owner_ok)
+ error = EACCES;
+ goto out;
+ }
+
+ /* Not owner; if group and world both grant it we're done */
+ if (group_ok && world_ok) {
+ _SETWHERE("group/world");
+ goto out;
+ }
+ if (!group_ok && !world_ok) {
+ _SETWHERE("group/world");
+ error = EACCES;
+ goto out;
+ }
+
+ /* Check group membership (most expensive) */
+ ismember = 0;
+ if (on_dir) {
+ error = vauth_dir_ingroup(vcp, &ismember);
+ } else {
+ error = vauth_file_ingroup(vcp, &ismember);
+ }
+ if (error)
+ goto out;
+ if (ismember) {
+ _SETWHERE("group");
+ if (!group_ok)
+ error = EACCES;
+ goto out;
+ }
+
+ /* Not owner, not in group, use world result */
+ _SETWHERE("world");
+ if (!world_ok)
+ error = EACCES;
+
+ /* FALLTHROUGH */
+
+out:
+ KAUTH_DEBUG("%p %s - posix %s permissions : need %s%s%s %x have %s%s%s%s%s%s%s%s%s UID = %d file = %d,%d",
+ vcp->vp, (error == 0) ? "ALLOWED" : "DENIED", where,
+ (action & VREAD) ? "r" : "-",
+ (action & VWRITE) ? "w" : "-",
+ (action & VEXEC) ? "x" : "-",
+ needed,
+ (vap->va_mode & S_IRUSR) ? "r" : "-",
+ (vap->va_mode & S_IWUSR) ? "w" : "-",
+ (vap->va_mode & S_IXUSR) ? "x" : "-",
+ (vap->va_mode & S_IRGRP) ? "r" : "-",
+ (vap->va_mode & S_IWGRP) ? "w" : "-",
+ (vap->va_mode & S_IXGRP) ? "x" : "-",
+ (vap->va_mode & S_IROTH) ? "r" : "-",
+ (vap->va_mode & S_IWOTH) ? "w" : "-",
+ (vap->va_mode & S_IXOTH) ? "x" : "-",
+ kauth_cred_getuid(vcp->ctx->vc_ucred),
+ on_dir ? vcp->dvap->va_uid : vcp->vap->va_uid,
+ on_dir ? vcp->dvap->va_gid : vcp->vap->va_gid);
+ return(error);
+}
+
+/*
+ * Authorize the deletion of the node vp from the directory dvp.
+ *
+ * We assume that:
+ * - Neither the node nor the directory are immutable.
+ * - The user is not the superuser.
+ *
+ * Deletion is not permitted if the directory is sticky and the caller is
+ * not owner of the node or directory.
+ *
+ * If either the node grants DELETE, or the directory grants DELETE_CHILD,
+ * the node may be deleted. If neither denies the permission, and the
+ * caller has Posix write access to the directory, then the node may be
+ * deleted.
+ *
+ * As an optimization, we cache whether or not delete child is permitted
+ * on directories without the sticky bit set.
+ */
+int
+vnode_authorize_delete(vauth_ctx vcp, boolean_t cached_delete_child);
+/*static*/ int
+vnode_authorize_delete(vauth_ctx vcp, boolean_t cached_delete_child)
+{
+ struct vnode_attr *vap = vcp->vap;
+ struct vnode_attr *dvap = vcp->dvap;
+ kauth_cred_t cred = vcp->ctx->vc_ucred;
+ struct kauth_acl_eval eval;
+ int error, delete_denied, delete_child_denied, ismember;
+
+ /* check the ACL on the directory */
+ delete_child_denied = 0;
+ if (!cached_delete_child && VATTR_IS_NOT(dvap, va_acl, NULL)) {
+ eval.ae_requested = KAUTH_VNODE_DELETE_CHILD;
+ eval.ae_acl = &dvap->va_acl->acl_ace[0];
+ eval.ae_count = dvap->va_acl->acl_entrycount;
+ eval.ae_options = 0;
+ if (vauth_dir_owner(vcp))
+ eval.ae_options |= KAUTH_AEVAL_IS_OWNER;
+ if ((error = vauth_dir_ingroup(vcp, &ismember)) != 0)
+ return(error);
+ if (ismember)
+ eval.ae_options |= KAUTH_AEVAL_IN_GROUP;
+ eval.ae_exp_gall = KAUTH_VNODE_GENERIC_ALL_BITS;
+ eval.ae_exp_gread = KAUTH_VNODE_GENERIC_READ_BITS;
+ eval.ae_exp_gwrite = KAUTH_VNODE_GENERIC_WRITE_BITS;
+ eval.ae_exp_gexec = KAUTH_VNODE_GENERIC_EXECUTE_BITS;
+
+ error = kauth_acl_evaluate(cred, &eval);
+
+ if (error != 0) {
+ KAUTH_DEBUG("%p ERROR during ACL processing - %d", vcp->vp, error);
+ return(error);
+ }
+ if (eval.ae_result == KAUTH_RESULT_DENY)
+ delete_child_denied = 1;
+ if (eval.ae_result == KAUTH_RESULT_ALLOW) {
+ KAUTH_DEBUG("%p ALLOWED - granted by directory ACL", vcp->vp);
+ return(0);
+ }
+ }
+
+ /* check the ACL on the node */
+ delete_denied = 0;
+ if (VATTR_IS_NOT(vap, va_acl, NULL)) {
+ eval.ae_requested = KAUTH_VNODE_DELETE;
+ eval.ae_acl = &vap->va_acl->acl_ace[0];
+ eval.ae_count = vap->va_acl->acl_entrycount;
+ eval.ae_options = 0;
+ if (vauth_file_owner(vcp))
+ eval.ae_options |= KAUTH_AEVAL_IS_OWNER;
+ if ((error = vauth_file_ingroup(vcp, &ismember)) != 0)
+ return(error);
+ if (ismember)
+ eval.ae_options |= KAUTH_AEVAL_IN_GROUP;
+ eval.ae_exp_gall = KAUTH_VNODE_GENERIC_ALL_BITS;
+ eval.ae_exp_gread = KAUTH_VNODE_GENERIC_READ_BITS;
+ eval.ae_exp_gwrite = KAUTH_VNODE_GENERIC_WRITE_BITS;
+ eval.ae_exp_gexec = KAUTH_VNODE_GENERIC_EXECUTE_BITS;
+
+ if ((error = kauth_acl_evaluate(cred, &eval)) != 0) {
+ KAUTH_DEBUG("%p ERROR during ACL processing - %d", vcp->vp, error);
+ return(error);
+ }
+ if (eval.ae_result == KAUTH_RESULT_DENY)
+ delete_denied = 1;
+ if (eval.ae_result == KAUTH_RESULT_ALLOW) {
+ KAUTH_DEBUG("%p ALLOWED - granted by file ACL", vcp->vp);
+ return(0);
+ }
+ }
+
+ /* if denied by ACL on directory or node, return denial */
+ if (delete_denied || delete_child_denied) {
+ KAUTH_DEBUG("%p ALLOWED - denied by ACL", vcp->vp);
+ return(EACCES);
+ }
+
+ /*
+ * enforce sticky bit behaviour; the cached_delete_child property will
+ * be false and the dvap contents valis for sticky bit directories;
+ * this makes us check the directory each time, but it's unavoidable,
+ * as sticky bit is an exception to caching.
+ */
+ if (!cached_delete_child && (dvap->va_mode & S_ISTXT) && !vauth_file_owner(vcp) && !vauth_dir_owner(vcp)) {
+ KAUTH_DEBUG("%p DENIED - sticky bit rules (user %d file %d dir %d)",
+ vcp->vp, cred->cr_uid, vap->va_uid, dvap->va_uid);
+ return(EACCES);
+ }
+
+ /* check the directory */
+ if (!cached_delete_child && (error = vnode_authorize_posix(vcp, VWRITE, 1 /* on_dir */)) != 0) {
+ KAUTH_DEBUG("%p ALLOWED - granted by posix permisssions", vcp->vp);
+ return(error);
+ }
+
+ /* not denied, must be OK */
+ return(0);
+}
+
+
+/*
+ * Authorize an operation based on the node's attributes.
+ */
+static int
+vnode_authorize_simple(vauth_ctx vcp, kauth_ace_rights_t acl_rights, kauth_ace_rights_t preauth_rights, boolean_t *found_deny)
+{
+ struct vnode_attr *vap = vcp->vap;
+ kauth_cred_t cred = vcp->ctx->vc_ucred;
+ struct kauth_acl_eval eval;
+ int error, ismember;
+ mode_t posix_action;
+
+ /*
+ * If we are the file owner, we automatically have some rights.
+ *
+ * Do we need to expand this to support group ownership?
+ */
+ if (vauth_file_owner(vcp))
+ acl_rights &= ~(KAUTH_VNODE_WRITE_SECURITY);
+
+ /*
+ * If we are checking both TAKE_OWNERSHIP and WRITE_SECURITY, we can
+ * mask the latter. If TAKE_OWNERSHIP is requested the caller is about to
+ * change ownership to themselves, and WRITE_SECURITY is implicitly
+ * granted to the owner. We need to do this because at this point
+ * WRITE_SECURITY may not be granted as the caller is not currently
+ * the owner.
+ */
+ if ((acl_rights & KAUTH_VNODE_TAKE_OWNERSHIP) &&
+ (acl_rights & KAUTH_VNODE_WRITE_SECURITY))
+ acl_rights &= ~KAUTH_VNODE_WRITE_SECURITY;
+
+ if (acl_rights == 0) {
+ KAUTH_DEBUG("%p ALLOWED - implicit or no rights required", vcp->vp);
+ return(0);
+ }
+
+ /* if we have an ACL, evaluate it */
+ if (VATTR_IS_NOT(vap, va_acl, NULL)) {
+ eval.ae_requested = acl_rights;
+ eval.ae_acl = &vap->va_acl->acl_ace[0];
+ eval.ae_count = vap->va_acl->acl_entrycount;
+ eval.ae_options = 0;
+ if (vauth_file_owner(vcp))
+ eval.ae_options |= KAUTH_AEVAL_IS_OWNER;
+ if ((error = vauth_file_ingroup(vcp, &ismember)) != 0)
+ return(error);
+ if (ismember)
+ eval.ae_options |= KAUTH_AEVAL_IN_GROUP;
+ eval.ae_exp_gall = KAUTH_VNODE_GENERIC_ALL_BITS;
+ eval.ae_exp_gread = KAUTH_VNODE_GENERIC_READ_BITS;
+ eval.ae_exp_gwrite = KAUTH_VNODE_GENERIC_WRITE_BITS;
+ eval.ae_exp_gexec = KAUTH_VNODE_GENERIC_EXECUTE_BITS;
+
+ if ((error = kauth_acl_evaluate(cred, &eval)) != 0) {
+ KAUTH_DEBUG("%p ERROR during ACL processing - %d", vcp->vp, error);
+ return(error);
+ }
+
+ if (eval.ae_result == KAUTH_RESULT_DENY) {
+ KAUTH_DEBUG("%p DENIED - by ACL", vcp->vp);
+ return(EACCES); /* deny, deny, counter-allege */
+ }
+ if (eval.ae_result == KAUTH_RESULT_ALLOW) {
+ KAUTH_DEBUG("%p ALLOWED - all rights granted by ACL", vcp->vp);
+ return(0);
+ }
+ *found_deny = eval.ae_found_deny;
+
+ /* fall through and evaluate residual rights */
+ } else {
+ /* no ACL, everything is residual */
+ eval.ae_residual = acl_rights;
+ }
+
+ /*
+ * Grant residual rights that have been pre-authorized.
+ */
+ eval.ae_residual &= ~preauth_rights;
+
+ /*
+ * We grant WRITE_ATTRIBUTES to the owner if it hasn't been denied.
+ */
+ if (vauth_file_owner(vcp))
+ eval.ae_residual &= ~KAUTH_VNODE_WRITE_ATTRIBUTES;
+
+ if (eval.ae_residual == 0) {
+ KAUTH_DEBUG("%p ALLOWED - rights already authorized", vcp->vp);
+ return(0);
+ }
+
+ /*
+ * Bail if we have residual rights that can't be granted by posix permissions,
+ * or aren't presumed granted at this point.
+ *
+ * XXX these can be collapsed for performance
+ */
+ if (eval.ae_residual & KAUTH_VNODE_CHANGE_OWNER) {
+ KAUTH_DEBUG("%p DENIED - CHANGE_OWNER not permitted", vcp->vp);
+ return(EACCES);
+ }
+ if (eval.ae_residual & KAUTH_VNODE_WRITE_SECURITY) {
+ KAUTH_DEBUG("%p DENIED - WRITE_SECURITY not permitted", vcp->vp);
+ return(EACCES);
+ }
+
+#if DIAGNOSTIC
+ if (eval.ae_residual & KAUTH_VNODE_DELETE)
+ panic("vnode_authorize: can't be checking delete permission here");
+#endif
+
+ /*
+ * Compute the fallback posix permissions that will satisfy the remaining
+ * rights.
+ */
+ posix_action = 0;
+ if (eval.ae_residual & (KAUTH_VNODE_READ_DATA |
+ KAUTH_VNODE_LIST_DIRECTORY |
+ KAUTH_VNODE_READ_EXTATTRIBUTES))
+ posix_action |= VREAD;
+ if (eval.ae_residual & (KAUTH_VNODE_WRITE_DATA |
+ KAUTH_VNODE_ADD_FILE |
+ KAUTH_VNODE_ADD_SUBDIRECTORY |
+ KAUTH_VNODE_DELETE_CHILD |
+ KAUTH_VNODE_WRITE_ATTRIBUTES |
+ KAUTH_VNODE_WRITE_EXTATTRIBUTES))
+ posix_action |= VWRITE;
+ if (eval.ae_residual & (KAUTH_VNODE_EXECUTE |
+ KAUTH_VNODE_SEARCH))
+ posix_action |= VEXEC;
+
+ if (posix_action != 0) {
+ return(vnode_authorize_posix(vcp, posix_action, 0 /* !on_dir */));
+ } else {
+ KAUTH_DEBUG("%p ALLOWED - residual rights %s%s%s%s%s%s%s%s%s%s%s%s%s%s granted due to no posix mapping",
+ vcp->vp,
+ (eval.ae_residual & KAUTH_VNODE_READ_DATA)
+ ? vnode_isdir(vcp->vp) ? " LIST_DIRECTORY" : " READ_DATA" : "",
+ (eval.ae_residual & KAUTH_VNODE_WRITE_DATA)
+ ? vnode_isdir(vcp->vp) ? " ADD_FILE" : " WRITE_DATA" : "",
+ (eval.ae_residual & KAUTH_VNODE_EXECUTE)
+ ? vnode_isdir(vcp->vp) ? " SEARCH" : " EXECUTE" : "",
+ (eval.ae_residual & KAUTH_VNODE_DELETE)
+ ? " DELETE" : "",
+ (eval.ae_residual & KAUTH_VNODE_APPEND_DATA)
+ ? vnode_isdir(vcp->vp) ? " ADD_SUBDIRECTORY" : " APPEND_DATA" : "",
+ (eval.ae_residual & KAUTH_VNODE_DELETE_CHILD)
+ ? " DELETE_CHILD" : "",
+ (eval.ae_residual & KAUTH_VNODE_READ_ATTRIBUTES)
+ ? " READ_ATTRIBUTES" : "",
+ (eval.ae_residual & KAUTH_VNODE_WRITE_ATTRIBUTES)
+ ? " WRITE_ATTRIBUTES" : "",
+ (eval.ae_residual & KAUTH_VNODE_READ_EXTATTRIBUTES)
+ ? " READ_EXTATTRIBUTES" : "",
+ (eval.ae_residual & KAUTH_VNODE_WRITE_EXTATTRIBUTES)
+ ? " WRITE_EXTATTRIBUTES" : "",
+ (eval.ae_residual & KAUTH_VNODE_READ_SECURITY)
+ ? " READ_SECURITY" : "",
+ (eval.ae_residual & KAUTH_VNODE_WRITE_SECURITY)
+ ? " WRITE_SECURITY" : "",
+ (eval.ae_residual & KAUTH_VNODE_CHECKIMMUTABLE)
+ ? " CHECKIMMUTABLE" : "",
+ (eval.ae_residual & KAUTH_VNODE_CHANGE_OWNER)
+ ? " CHANGE_OWNER" : "");
+ }
+
+ /*
+ * Lack of required Posix permissions implies no reason to deny access.
+ */
+ return(0);
+}
+
+/*
+ * Check for file immutability.
+ */
+static int
+vnode_authorize_checkimmutable(vnode_t vp, struct vnode_attr *vap, int rights, int ignore)
+{
+ mount_t mp;
+ int error;
+ int append;
+
+ /*
+ * Perform immutability checks for operations that change data.
+ *
+ * Sockets, fifos and devices require special handling.
+ */
+ switch(vp->v_type) {
+ case VSOCK:
+ case VFIFO:
+ case VBLK:
+ case VCHR:
+ /*
+ * Writing to these nodes does not change the filesystem data,
+ * so forget that it's being tried.
+ */
+ rights &= ~KAUTH_VNODE_WRITE_DATA;
+ break;
+ default:
+ break;
+ }
+
+ error = 0;
+ if (rights & KAUTH_VNODE_WRITE_RIGHTS) {
+
+ /* check per-filesystem options if possible */
+ mp = vp->v_mount;
+ if (mp != NULL) {
+
+ /* check for no-EA filesystems */
+ if ((rights & KAUTH_VNODE_WRITE_EXTATTRIBUTES) &&
+ (vfs_flags(mp) & MNT_NOUSERXATTR)) {
+ KAUTH_DEBUG("%p DENIED - filesystem disallowed extended attributes", vp);
+ error = EACCES; /* User attributes disabled */
+ goto out;
+ }
+ }
+
+ /*
+ * check for file immutability. first, check if the requested rights are
+ * allowable for a UF_APPEND file.
+ */
+ append = 0;
+ if (vp->v_type == VDIR) {
+ if ((rights & (KAUTH_VNODE_ADD_FILE | KAUTH_VNODE_ADD_SUBDIRECTORY | KAUTH_VNODE_WRITE_EXTATTRIBUTES)) == rights)
+ append = 1;
+ } else {
+ if ((rights & (KAUTH_VNODE_APPEND_DATA | KAUTH_VNODE_WRITE_EXTATTRIBUTES)) == rights)
+ append = 1;
+ }
+ if ((error = vnode_immutable(vap, append, ignore)) != 0) {
+ KAUTH_DEBUG("%p DENIED - file is immutable", vp);
+ goto out;
+ }
+ }
+out:
+ return(error);
+}
+
+/*
+ * Handle authorization actions for filesystems that advertise that the
+ * server will be enforcing.
+ *
+ * Returns: 0 Authorization should be handled locally
+ * 1 Authorization was handled by the FS
+ *
+ * Note: Imputed returns will only occur if the authorization request
+ * was handled by the FS.
+ *
+ * Imputed: *resultp, modified Return code from FS when the request is
+ * handled by the FS.
+ * VNOP_ACCESS:???
+ * VNOP_OPEN:???
+ */
+static int
+vnode_authorize_opaque(vnode_t vp, int *resultp, kauth_action_t action, vfs_context_t ctx)
+{
+ int error;
+
+ /*
+ * If the vp is a device node, socket or FIFO it actually represents a local
+ * endpoint, so we need to handle it locally.
+ */
+ switch(vp->v_type) {
+ case VBLK:
+ case VCHR:
+ case VSOCK:
+ case VFIFO:
+ return(0);
+ default:
+ break;
+ }
+
+ /*
+ * In the advisory request case, if the filesystem doesn't think it's reliable
+ * we will attempt to formulate a result ourselves based on VNOP_GETATTR data.
+ */
+ if ((action & KAUTH_VNODE_ACCESS) && !vfs_authopaqueaccess(vp->v_mount))
+ return(0);
+
+ /*
+ * Let the filesystem have a say in the matter. It's OK for it to not implemnent
+ * VNOP_ACCESS, as most will authorise inline with the actual request.
+ */
+ if ((error = VNOP_ACCESS(vp, action, ctx)) != ENOTSUP) {
+ *resultp = error;
+ KAUTH_DEBUG("%p DENIED - opaque filesystem VNOP_ACCESS denied access", vp);
+ return(1);
+ }
+
+ /*
+ * Typically opaque filesystems do authorisation in-line, but exec is a special case. In
+ * order to be reasonably sure that exec will be permitted, we try a bit harder here.
+ */
+ if ((action & KAUTH_VNODE_EXECUTE) && (vp->v_type == VREG)) {
+ /* try a VNOP_OPEN for readonly access */
+ if ((error = VNOP_OPEN(vp, FREAD, ctx)) != 0) {
+ *resultp = error;
+ KAUTH_DEBUG("%p DENIED - EXECUTE denied because file could not be opened readonly", vp);
+ return(1);
+ }
+ VNOP_CLOSE(vp, FREAD, ctx);
+ }
+
+ /*
+ * We don't have any reason to believe that the request has to be denied at this point,
+ * so go ahead and allow it.
+ */
+ *resultp = 0;
+ KAUTH_DEBUG("%p ALLOWED - bypassing access check for non-local filesystem", vp);
+ return(1);
+}
+
+
+
+
+/*
+ * Returns: KAUTH_RESULT_ALLOW
+ * KAUTH_RESULT_DENY
+ *
+ * Imputed: *arg3, modified Error code in the deny case
+ * EROFS Read-only file system
+ * EACCES Permission denied
+ * EPERM Operation not permitted [no execute]
+ * vnode_getattr:ENOMEM Not enough space [only if has filesec]
+ * vnode_getattr:???
+ * vnode_authorize_opaque:*arg2 ???
+ * vnode_authorize_checkimmutable:???
+ * vnode_authorize_delete:???
+ * vnode_authorize_simple:???
+ */
+
+
+static int
+vnode_authorize_callback(kauth_cred_t cred, void *idata, kauth_action_t action,
+ uintptr_t arg0, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3)
+{
+ vfs_context_t ctx;
+ vnode_t cvp = NULLVP;
+ vnode_t vp, dvp;
+ int result = KAUTH_RESULT_DENY;
+ int parent_iocount = 0;
+ int parent_action; /* In case we need to use namedstream's data fork for cached rights*/
+
+ ctx = (vfs_context_t)arg0;
+ vp = (vnode_t)arg1;
+ dvp = (vnode_t)arg2;
+
+ /*
+ * if there are 2 vnodes passed in, we don't know at
+ * this point which rights to look at based on the
+ * combined action being passed in... defer until later...
+ * otherwise check the kauth 'rights' cache hung
+ * off of the vnode we're interested in... if we've already
+ * been granted the right we're currently interested in,
+ * we can just return success... otherwise we'll go through
+ * the process of authorizing the requested right(s)... if that
+ * succeeds, we'll add the right(s) to the cache.
+ * VNOP_SETATTR and VNOP_SETXATTR will invalidate this cache
+ */
+ if (dvp && vp)
+ goto defer;
+ if (dvp) {
+ cvp = dvp;
+ } else {
+ /*
+ * For named streams on local-authorization volumes, rights are cached on the parent;
+ * authorization is determined by looking at the parent's properties anyway, so storing
+ * on the parent means that we don't recompute for the named stream and that if
+ * we need to flush rights (e.g. on VNOP_SETATTR()) we don't need to track down the
+ * stream to flush its cache separately. If we miss in the cache, then we authorize
+ * as if there were no cached rights (passing the named stream vnode and desired rights to
+ * vnode_authorize_callback_int()).
+ *
+ * On an opaquely authorized volume, we don't know the relationship between the
+ * data fork's properties and the rights granted on a stream. Thus, named stream vnodes
+ * on such a volume are authorized directly (rather than using the parent) and have their
+ * own caches. When a named stream vnode is created, we mark the parent as having a named
+ * stream. On a VNOP_SETATTR() for the parent that may invalidate cached authorization, we
+ * find the stream and flush its cache.
+ */
+ if (vnode_isnamedstream(vp) && (!vfs_authopaque(vp->v_mount))) {
+ cvp = vp->v_parent;
+ if ((cvp != NULLVP) && (vnode_getwithref(cvp) == 0)) {
+ parent_iocount = 1;
+ } else {
+ cvp = NULL;
+ goto defer; /* If we can't use the parent, take the slow path */
+ }
+
+ /* Have to translate some actions */
+ parent_action = action;
+ if (parent_action & KAUTH_VNODE_READ_DATA) {
+ parent_action &= ~KAUTH_VNODE_READ_DATA;
+ parent_action |= KAUTH_VNODE_READ_EXTATTRIBUTES;
+ }
+ if (parent_action & KAUTH_VNODE_WRITE_DATA) {
+ parent_action &= ~KAUTH_VNODE_WRITE_DATA;
+ parent_action |= KAUTH_VNODE_WRITE_EXTATTRIBUTES;
+ }
+
+ } else {
+ cvp = vp;
+ }
+ }
+
+ if (vnode_cache_is_authorized(cvp, ctx, parent_iocount ? parent_action : action) == TRUE) {
+ result = KAUTH_RESULT_ALLOW;
+ goto out;
+ }
+defer:
+ result = vnode_authorize_callback_int(cred, idata, action, arg0, arg1, arg2, arg3);
+
+ if (result == KAUTH_RESULT_ALLOW && cvp != NULLVP)
+ vnode_cache_authorized_action(cvp, ctx, action);
+
+out:
+ if (parent_iocount) {
+ vnode_put(cvp);
+ }
+
+ return result;
+}
+
+
+static int
+vnode_authorize_callback_int(__unused kauth_cred_t unused_cred, __unused void *idata, kauth_action_t action,
+ uintptr_t arg0, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3)
+{
+ struct _vnode_authorize_context auth_context;
+ vauth_ctx vcp;
+ vfs_context_t ctx;
+ vnode_t vp, dvp;
+ kauth_cred_t cred;
+ kauth_ace_rights_t rights;
+ struct vnode_attr va, dva;
+ int result;
+ int *errorp;
+ int noimmutable;
+ boolean_t parent_authorized_for_delete_child = FALSE;
+ boolean_t found_deny = FALSE;
+ boolean_t parent_ref= FALSE;
+
+ vcp = &auth_context;
+ ctx = vcp->ctx = (vfs_context_t)arg0;
+ vp = vcp->vp = (vnode_t)arg1;
+ dvp = vcp->dvp = (vnode_t)arg2;
+ errorp = (int *)arg3;
+ /*
+ * Note that we authorize against the context, not the passed cred
+ * (the same thing anyway)
+ */
+ cred = ctx->vc_ucred;
+
+ VATTR_INIT(&va);
+ vcp->vap = &va;
+ VATTR_INIT(&dva);
+ vcp->dvap = &dva;
+
+ vcp->flags = vcp->flags_valid = 0;
+
+#if DIAGNOSTIC
+ if ((ctx == NULL) || (vp == NULL) || (cred == NULL))
+ panic("vnode_authorize: bad arguments (context %p vp %p cred %p)", ctx, vp, cred);
+#endif
+
+ KAUTH_DEBUG("%p AUTH - %s %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s on %s '%s' (0x%x:%p/%p)",
+ vp, vfs_context_proc(ctx)->p_comm,
+ (action & KAUTH_VNODE_ACCESS) ? "access" : "auth",
+ (action & KAUTH_VNODE_READ_DATA) ? vnode_isdir(vp) ? " LIST_DIRECTORY" : " READ_DATA" : "",
+ (action & KAUTH_VNODE_WRITE_DATA) ? vnode_isdir(vp) ? " ADD_FILE" : " WRITE_DATA" : "",
+ (action & KAUTH_VNODE_EXECUTE) ? vnode_isdir(vp) ? " SEARCH" : " EXECUTE" : "",
+ (action & KAUTH_VNODE_DELETE) ? " DELETE" : "",
+ (action & KAUTH_VNODE_APPEND_DATA) ? vnode_isdir(vp) ? " ADD_SUBDIRECTORY" : " APPEND_DATA" : "",
+ (action & KAUTH_VNODE_DELETE_CHILD) ? " DELETE_CHILD" : "",
+ (action & KAUTH_VNODE_READ_ATTRIBUTES) ? " READ_ATTRIBUTES" : "",
+ (action & KAUTH_VNODE_WRITE_ATTRIBUTES) ? " WRITE_ATTRIBUTES" : "",
+ (action & KAUTH_VNODE_READ_EXTATTRIBUTES) ? " READ_EXTATTRIBUTES" : "",
+ (action & KAUTH_VNODE_WRITE_EXTATTRIBUTES) ? " WRITE_EXTATTRIBUTES" : "",
+ (action & KAUTH_VNODE_READ_SECURITY) ? " READ_SECURITY" : "",
+ (action & KAUTH_VNODE_WRITE_SECURITY) ? " WRITE_SECURITY" : "",
+ (action & KAUTH_VNODE_CHANGE_OWNER) ? " CHANGE_OWNER" : "",
+ (action & KAUTH_VNODE_NOIMMUTABLE) ? " (noimmutable)" : "",
+ vnode_isdir(vp) ? "directory" : "file",
+ vp->v_name ? vp->v_name : "<NULL>", action, vp, dvp);
+
+ /*
+ * Extract the control bits from the action, everything else is
+ * requested rights.
+ */
+ noimmutable = (action & KAUTH_VNODE_NOIMMUTABLE) ? 1 : 0;
+ rights = action & ~(KAUTH_VNODE_ACCESS | KAUTH_VNODE_NOIMMUTABLE);
+
+ if (rights & KAUTH_VNODE_DELETE) {
+#if DIAGNOSTIC
+ if (dvp == NULL)
+ panic("vnode_authorize: KAUTH_VNODE_DELETE test requires a directory");
+#endif
+ /*
+ * check to see if we've already authorized the parent
+ * directory for deletion of its children... if so, we
+ * can skip a whole bunch of work... we will still have to
+ * authorize that this specific child can be removed
+ */
+ if (vnode_cache_is_authorized(dvp, ctx, KAUTH_VNODE_DELETE_CHILD) == TRUE)
+ parent_authorized_for_delete_child = TRUE;
+ } else {
+ dvp = NULL;
+ }
+
+ /*
+ * Check for read-only filesystems.
+ */
+ if ((rights & KAUTH_VNODE_WRITE_RIGHTS) &&
+ (vp->v_mount->mnt_flag & MNT_RDONLY) &&
+ ((vp->v_type == VREG) || (vp->v_type == VDIR) ||
+ (vp->v_type == VLNK) || (vp->v_type == VCPLX) ||
+ (rights & KAUTH_VNODE_DELETE) || (rights & KAUTH_VNODE_DELETE_CHILD))) {
+ result = EROFS;
+ goto out;
+ }
+
+ /*
+ * Check for noexec filesystems.
+ */
+ if ((rights & KAUTH_VNODE_EXECUTE) && (vp->v_type == VREG) && (vp->v_mount->mnt_flag & MNT_NOEXEC)) {
+ result = EACCES;
+ goto out;
+ }
+
+ /*
+ * Handle cases related to filesystems with non-local enforcement.
+ * This call can return 0, in which case we will fall through to perform a
+ * check based on VNOP_GETATTR data. Otherwise it returns 1 and sets
+ * an appropriate result, at which point we can return immediately.
+ */
+ if ((vp->v_mount->mnt_kern_flag & MNTK_AUTH_OPAQUE) && vnode_authorize_opaque(vp, &result, action, ctx))
+ goto out;
+
+ /*
+ * Get vnode attributes and extended security information for the vnode
+ * and directory if required.
+ */
+ VATTR_WANTED(&va, va_mode);
+ VATTR_WANTED(&va, va_uid);
+ VATTR_WANTED(&va, va_gid);
+ VATTR_WANTED(&va, va_flags);
+ VATTR_WANTED(&va, va_acl);
+ if ((result = vnode_getattr(vp, &va, ctx)) != 0) {
+ KAUTH_DEBUG("%p ERROR - failed to get vnode attributes - %d", vp, result);
+ goto out;
+ }
+ if (dvp && parent_authorized_for_delete_child == FALSE) {
+ VATTR_WANTED(&dva, va_mode);
+ VATTR_WANTED(&dva, va_uid);
+ VATTR_WANTED(&dva, va_gid);
+ VATTR_WANTED(&dva, va_flags);
+ VATTR_WANTED(&dva, va_acl);
+ if ((result = vnode_getattr(dvp, &dva, ctx)) != 0) {
+ KAUTH_DEBUG("%p ERROR - failed to get directory vnode attributes - %d", vp, result);
+ goto out;
+ }
+ }
+
+ /*
+ * If the vnode is an extended attribute data vnode (eg. a resource fork), *_DATA becomes
+ * *_EXTATTRIBUTES.
+ */
+ if (vnode_isnamedstream(vp)) {
+ if (rights & KAUTH_VNODE_READ_DATA) {
+ rights &= ~KAUTH_VNODE_READ_DATA;
+ rights |= KAUTH_VNODE_READ_EXTATTRIBUTES;
+ }
+ if (rights & KAUTH_VNODE_WRITE_DATA) {
+ rights &= ~KAUTH_VNODE_WRITE_DATA;
+ rights |= KAUTH_VNODE_WRITE_EXTATTRIBUTES;
+ }
+ }
+
+ /*
+ * Point 'vp' to the resource fork's parent for ACL checking
+ */
+ if (vnode_isnamedstream(vp) &&
+ (vp->v_parent != NULL) &&
+ (vget_internal(vp->v_parent, 0, VNODE_NODEAD) == 0)) {
+ parent_ref = TRUE;
+ vcp->vp = vp = vp->v_parent;
+ if (VATTR_IS_SUPPORTED(&va, va_acl) && (va.va_acl != NULL))
+ kauth_acl_free(va.va_acl);
+ VATTR_INIT(&va);
+ VATTR_WANTED(&va, va_mode);
+ VATTR_WANTED(&va, va_uid);
+ VATTR_WANTED(&va, va_gid);
+ VATTR_WANTED(&va, va_flags);
+ VATTR_WANTED(&va, va_acl);
+ if ((result = vnode_getattr(vp, &va, ctx)) != 0)
+ goto out;
+ }
+
+ /*
+ * Check for immutability.
+ *
+ * In the deletion case, parent directory immutability vetoes specific
+ * file rights.
+ */
+ if ((result = vnode_authorize_checkimmutable(vp, &va, rights, noimmutable)) != 0)
+ goto out;
+ if ((rights & KAUTH_VNODE_DELETE) &&
+ parent_authorized_for_delete_child == FALSE &&
+ ((result = vnode_authorize_checkimmutable(dvp, &dva, KAUTH_VNODE_DELETE_CHILD, 0)) != 0))
+ goto out;
+
+ /*
+ * Clear rights that have been authorized by reaching this point, bail if nothing left to
+ * check.
+ */
+ rights &= ~(KAUTH_VNODE_LINKTARGET | KAUTH_VNODE_CHECKIMMUTABLE);
+ if (rights == 0)
+ goto out;
+
+ /*
+ * If we're not the superuser, authorize based on file properties;
+ * note that even if parent_authorized_for_delete_child is TRUE, we
+ * need to check on the node itself.
+ */
+ if (!vfs_context_issuser(ctx)) {
+ /* process delete rights */
+ if ((rights & KAUTH_VNODE_DELETE) &&
+ ((result = vnode_authorize_delete(vcp, parent_authorized_for_delete_child)) != 0))
+ goto out;
+
+ /* process remaining rights */
+ if ((rights & ~KAUTH_VNODE_DELETE) &&
+ (result = vnode_authorize_simple(vcp, rights, rights & KAUTH_VNODE_DELETE, &found_deny)) != 0)
+ goto out;
+ } else {
+
+ /*
+ * Execute is only granted to root if one of the x bits is set. This check only
+ * makes sense if the posix mode bits are actually supported.
+ */
+ if ((rights & KAUTH_VNODE_EXECUTE) &&
+ (vp->v_type == VREG) &&
+ VATTR_IS_SUPPORTED(&va, va_mode) &&
+ !(va.va_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) {
+ result = EPERM;
+ KAUTH_DEBUG("%p DENIED - root execute requires at least one x bit in 0x%x", vp, va.va_mode);
+ goto out;
+ }
+
+ KAUTH_DEBUG("%p ALLOWED - caller is superuser", vp);
+ }
+out:
+ if (VATTR_IS_SUPPORTED(&va, va_acl) && (va.va_acl != NULL))
+ kauth_acl_free(va.va_acl);
+ if (VATTR_IS_SUPPORTED(&dva, va_acl) && (dva.va_acl != NULL))
+ kauth_acl_free(dva.va_acl);
+
+ if (result) {
+ if (parent_ref)
+ vnode_put(vp);
+ *errorp = result;
+ KAUTH_DEBUG("%p DENIED - auth denied", vp);
+ return(KAUTH_RESULT_DENY);
+ }
+ if ((rights & KAUTH_VNODE_SEARCH) && found_deny == FALSE && vp->v_type == VDIR) {
+ /*
+ * if we were successfully granted the right to search this directory
+ * and there were NO ACL DENYs for search and the posix permissions also don't
+ * deny execute, we can synthesize a global right that allows anyone to
+ * traverse this directory during a pathname lookup without having to
+ * match the credential associated with this cache of rights.
+ */
+ if (!VATTR_IS_SUPPORTED(&va, va_mode) ||
+ ((va.va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) ==
+ (S_IXUSR | S_IXGRP | S_IXOTH))) {
+ vnode_cache_authorized_action(vp, ctx, KAUTH_VNODE_SEARCHBYANYONE);
+ }
+ }
+ if ((rights & KAUTH_VNODE_DELETE) && parent_authorized_for_delete_child == FALSE) {
+ /*
+ * parent was successfully and newly authorized for content deletions
+ * add it to the cache, but only if it doesn't have the sticky
+ * bit set on it. This same check is done earlier guarding
+ * fetching of dva, and if we jumped to out without having done
+ * this, we will have returned already because of a non-zero
+ * 'result' value.
+ */
+ if (VATTR_IS_SUPPORTED(&dva, va_mode) &&
+ !(dva.va_mode & (S_ISVTX))) {
+ /* OK to cache delete rights */
+ vnode_cache_authorized_action(dvp, ctx, KAUTH_VNODE_DELETE_CHILD);
+ }
+ }
+ if (parent_ref)
+ vnode_put(vp);
+ /*
+ * Note that this implies that we will allow requests for no rights, as well as
+ * for rights that we do not recognise. There should be none of these.
+ */
+ KAUTH_DEBUG("%p ALLOWED - auth granted", vp);
+ return(KAUTH_RESULT_ALLOW);
+}
+
+/*
+ * Check that the attribute information in vattr can be legally applied to
+ * a new file by the context.
+ */
+int
+vnode_authattr_new(vnode_t dvp, struct vnode_attr *vap, int noauth, vfs_context_t ctx)
+{
+ int error;
+ int has_priv_suser, ismember, defaulted_owner, defaulted_group, defaulted_mode;
+ kauth_cred_t cred;
+ guid_t changer;
+ mount_t dmp;
+
+ error = 0;
+ defaulted_owner = defaulted_group = defaulted_mode = 0;
+
+ /*
+ * Require that the filesystem support extended security to apply any.
+ */
+ if (!vfs_extendedsecurity(dvp->v_mount) &&
+ (VATTR_IS_ACTIVE(vap, va_acl) || VATTR_IS_ACTIVE(vap, va_uuuid) || VATTR_IS_ACTIVE(vap, va_guuid))) {
+ error = EINVAL;
+ goto out;
+ }
+
+ /*
+ * Default some fields.
+ */
+ dmp = dvp->v_mount;
+
+ /*
+ * If the filesystem is mounted IGNORE_OWNERSHIP and an explicit owner is set, that
+ * owner takes ownership of all new files.
+ */
+ if ((dmp->mnt_flag & MNT_IGNORE_OWNERSHIP) && (dmp->mnt_fsowner != KAUTH_UID_NONE)) {
+ VATTR_SET(vap, va_uid, dmp->mnt_fsowner);
+ defaulted_owner = 1;
+ } else {
+ if (!VATTR_IS_ACTIVE(vap, va_uid)) {
+ /* default owner is current user */
+ VATTR_SET(vap, va_uid, kauth_cred_getuid(vfs_context_ucred(ctx)));
+ defaulted_owner = 1;
+ }
+ }
+
+ /*
+ * If the filesystem is mounted IGNORE_OWNERSHIP and an explicit grouo is set, that
+ * group takes ownership of all new files.
+ */
+ if ((dmp->mnt_flag & MNT_IGNORE_OWNERSHIP) && (dmp->mnt_fsgroup != KAUTH_GID_NONE)) {
+ VATTR_SET(vap, va_gid, dmp->mnt_fsgroup);
+ defaulted_group = 1;
+ } else {
+ if (!VATTR_IS_ACTIVE(vap, va_gid)) {
+ /* default group comes from parent object, fallback to current user */
+ struct vnode_attr dva;
+ VATTR_INIT(&dva);
+ VATTR_WANTED(&dva, va_gid);
+ if ((error = vnode_getattr(dvp, &dva, ctx)) != 0)
+ goto out;
+ if (VATTR_IS_SUPPORTED(&dva, va_gid)) {
+ VATTR_SET(vap, va_gid, dva.va_gid);
+ } else {
+ VATTR_SET(vap, va_gid, kauth_cred_getgid(vfs_context_ucred(ctx)));
+ }
+ defaulted_group = 1;
+ }
+ }
+
+ if (!VATTR_IS_ACTIVE(vap, va_flags))
+ VATTR_SET(vap, va_flags, 0);
+
+ /* default mode is everything, masked with current umask */
+ if (!VATTR_IS_ACTIVE(vap, va_mode)) {
+ VATTR_SET(vap, va_mode, ACCESSPERMS & ~vfs_context_proc(ctx)->p_fd->fd_cmask);
+ KAUTH_DEBUG("ATTR - defaulting new file mode to %o from umask %o", vap->va_mode, vfs_context_proc(ctx)->p_fd->fd_cmask);
+ defaulted_mode = 1;
+ }
+ /* set timestamps to now */
+ if (!VATTR_IS_ACTIVE(vap, va_create_time)) {
+ nanotime(&vap->va_create_time);
+ VATTR_SET_ACTIVE(vap, va_create_time);
+ }
+
+ /*
+ * Check for attempts to set nonsensical fields.
+ */
+ if (vap->va_active & ~VNODE_ATTR_NEWOBJ) {
+ error = EINVAL;
+ KAUTH_DEBUG("ATTR - ERROR - attempt to set unsupported new-file attributes %llx",
+ vap->va_active & ~VNODE_ATTR_NEWOBJ);
+ goto out;
+ }
+
+ /*
+ * Quickly check for the applicability of any enforcement here.
+ * Tests below maintain the integrity of the local security model.
+ */
+ if (vfs_authopaque(dvp->v_mount))
+ goto out;
+
+ /*
+ * We need to know if the caller is the superuser, or if the work is
+ * otherwise already authorised.
+ */
+ cred = vfs_context_ucred(ctx);
+ if (noauth) {
+ /* doing work for the kernel */
+ has_priv_suser = 1;
+ } else {
+ has_priv_suser = vfs_context_issuser(ctx);
+ }
+
+
+ if (VATTR_IS_ACTIVE(vap, va_flags)) {
+ if (has_priv_suser) {
+ if ((vap->va_flags & (UF_SETTABLE | SF_SETTABLE)) != vap->va_flags) {
+ error = EPERM;
+ KAUTH_DEBUG(" DENIED - superuser attempt to set illegal flag(s)");
+ goto out;
+ }
+ } else {
+ if ((vap->va_flags & UF_SETTABLE) != vap->va_flags) {
+ error = EPERM;
+ KAUTH_DEBUG(" DENIED - user attempt to set illegal flag(s)");
+ goto out;
+ }
+ }
+ }
+
+ /* if not superuser, validate legality of new-item attributes */
+ if (!has_priv_suser) {
+ if (!defaulted_mode && VATTR_IS_ACTIVE(vap, va_mode)) {
+ /* setgid? */
+ if (vap->va_mode & S_ISGID) {
+ if ((error = kauth_cred_ismember_gid(cred, vap->va_gid, &ismember)) != 0) {
+ KAUTH_DEBUG("ATTR - ERROR: got %d checking for membership in %d", error, vap->va_gid);
+ goto out;
+ }
+ if (!ismember) {
+ KAUTH_DEBUG(" DENIED - can't set SGID bit, not a member of %d", vap->va_gid);
+ error = EPERM;
+ goto out;
+ }
+ }
+
+ /* setuid? */
+ if ((vap->va_mode & S_ISUID) && (vap->va_uid != kauth_cred_getuid(cred))) {
+ KAUTH_DEBUG("ATTR - ERROR: illegal attempt to set the setuid bit");
+ error = EPERM;
+ goto out;
+ }
+ }
+ if (!defaulted_owner && (vap->va_uid != kauth_cred_getuid(cred))) {
+ KAUTH_DEBUG(" DENIED - cannot create new item owned by %d", vap->va_uid);
+ error = EPERM;
+ goto out;
+ }
+ if (!defaulted_group) {
+ if ((error = kauth_cred_ismember_gid(cred, vap->va_gid, &ismember)) != 0) {
+ KAUTH_DEBUG(" ERROR - got %d checking for membership in %d", error, vap->va_gid);
+ goto out;
+ }
+ if (!ismember) {
+ KAUTH_DEBUG(" DENIED - cannot create new item with group %d - not a member", vap->va_gid);
+ error = EPERM;
+ goto out;
+ }
+ }
+
+ /* initialising owner/group UUID */
+ if (VATTR_IS_ACTIVE(vap, va_uuuid)) {
+ if ((error = kauth_cred_getguid(cred, &changer)) != 0) {
+ KAUTH_DEBUG(" ERROR - got %d trying to get caller UUID", error);
+ /* XXX ENOENT here - no GUID - should perhaps become EPERM */
+ goto out;
+ }
+ if (!kauth_guid_equal(&vap->va_uuuid, &changer)) {
+ KAUTH_DEBUG(" ERROR - cannot create item with supplied owner UUID - not us");
+ error = EPERM;
+ goto out;
+ }
+ }
+ if (VATTR_IS_ACTIVE(vap, va_guuid)) {
+ if ((error = kauth_cred_ismember_guid(cred, &vap->va_guuid, &ismember)) != 0) {
+ KAUTH_DEBUG(" ERROR - got %d trying to check group membership", error);
+ goto out;
+ }
+ if (!ismember) {
+ KAUTH_DEBUG(" ERROR - cannot create item with supplied group UUID - not a member");
+ error = EPERM;
+ goto out;
+ }
+ }
+ }
+out:
+ return(error);
+}
+
+/*
+ * Check that the attribute information in vap can be legally written by the
+ * context.
+ *
+ * Call this when you're not sure about the vnode_attr; either its contents
+ * have come from an unknown source, or when they are variable.
+ *
+ * Returns errno, or zero and sets *actionp to the KAUTH_VNODE_* actions that
+ * must be authorized to be permitted to write the vattr.
+ */
+int
+vnode_authattr(vnode_t vp, struct vnode_attr *vap, kauth_action_t *actionp, vfs_context_t ctx)
+{
+ struct vnode_attr ova;
+ kauth_action_t required_action;
+ int error, has_priv_suser, ismember, chowner, chgroup, clear_suid, clear_sgid;
+ guid_t changer;
+ gid_t group;
+ uid_t owner;
+ mode_t newmode;
+ kauth_cred_t cred;
+ uint32_t fdelta;
+
+ VATTR_INIT(&ova);
+ required_action = 0;
+ error = 0;
+
+ /*
+ * Quickly check for enforcement applicability.
+ */
+ if (vfs_authopaque(vp->v_mount))
+ goto out;
+
+ /*
+ * Check for attempts to set nonsensical fields.
+ */
+ if (vap->va_active & VNODE_ATTR_RDONLY) {
+ KAUTH_DEBUG("ATTR - ERROR: attempt to set readonly attribute(s)");
+ error = EINVAL;
+ goto out;
+ }
+
+ /*
+ * We need to know if the caller is the superuser.
+ */
+ cred = vfs_context_ucred(ctx);
+ has_priv_suser = kauth_cred_issuser(cred);
+
+ /*
+ * If any of the following are changing, we need information from the old file:
+ * va_uid
+ * va_gid
+ * va_mode
+ * va_uuuid
+ * va_guuid
+ */
+ if (VATTR_IS_ACTIVE(vap, va_uid) ||
+ VATTR_IS_ACTIVE(vap, va_gid) ||
+ VATTR_IS_ACTIVE(vap, va_mode) ||
+ VATTR_IS_ACTIVE(vap, va_uuuid) ||
+ VATTR_IS_ACTIVE(vap, va_guuid)) {
+ VATTR_WANTED(&ova, va_mode);
+ VATTR_WANTED(&ova, va_uid);
+ VATTR_WANTED(&ova, va_gid);
+ VATTR_WANTED(&ova, va_uuuid);
+ VATTR_WANTED(&ova, va_guuid);
+ KAUTH_DEBUG("ATTR - security information changing, fetching existing attributes");
+ }
+
+ /*
+ * If timestamps are being changed, we need to know who the file is owned
+ * by.
+ */
+ if (VATTR_IS_ACTIVE(vap, va_create_time) ||
+ VATTR_IS_ACTIVE(vap, va_change_time) ||
+ VATTR_IS_ACTIVE(vap, va_modify_time) ||
+ VATTR_IS_ACTIVE(vap, va_access_time) ||
+ VATTR_IS_ACTIVE(vap, va_backup_time)) {
+
+ VATTR_WANTED(&ova, va_uid);
+#if 0 /* enable this when we support UUIDs as official owners */
+ VATTR_WANTED(&ova, va_uuuid);
+#endif
+ KAUTH_DEBUG("ATTR - timestamps changing, fetching uid and GUID");
+ }
+
+ /*
+ * If flags are being changed, we need the old flags.
+ */
+ if (VATTR_IS_ACTIVE(vap, va_flags)) {
+ KAUTH_DEBUG("ATTR - flags changing, fetching old flags");
+ VATTR_WANTED(&ova, va_flags);
+ }
+
+ /*
+ * If the size is being set, make sure it's not a directory.
+ */
+ if (VATTR_IS_ACTIVE(vap, va_data_size)) {
+ /* size is meaningless on a directory, don't permit this */
+ if (vnode_isdir(vp)) {
+ KAUTH_DEBUG("ATTR - ERROR: size change requested on a directory");
+ error = EISDIR;
+ goto out;
+ }
+ }
+
+ /*
+ * Get old data.
+ */
+ KAUTH_DEBUG("ATTR - fetching old attributes %016llx", ova.va_active);
+ if ((error = vnode_getattr(vp, &ova, ctx)) != 0) {
+ KAUTH_DEBUG(" ERROR - got %d trying to get attributes", error);
+ goto out;
+ }
+
+ /*
+ * Size changes require write access to the file data.
+ */
+ if (VATTR_IS_ACTIVE(vap, va_data_size)) {
+ /* if we can't get the size, or it's different, we need write access */
+ KAUTH_DEBUG("ATTR - size change, requiring WRITE_DATA");
+ required_action |= KAUTH_VNODE_WRITE_DATA;
+ }
+
+ /*
+ * Changing timestamps?
+ *
+ * Note that we are only called to authorize user-requested time changes;
+ * side-effect time changes are not authorized. Authorisation is only
+ * required for existing files.
+ *
+ * Non-owners are not permitted to change the time on an existing
+ * file to anything other than the current time.
+ */
+ if (VATTR_IS_ACTIVE(vap, va_create_time) ||
+ VATTR_IS_ACTIVE(vap, va_change_time) ||
+ VATTR_IS_ACTIVE(vap, va_modify_time) ||
+ VATTR_IS_ACTIVE(vap, va_access_time) ||
+ VATTR_IS_ACTIVE(vap, va_backup_time)) {
+ /*
+ * The owner and root may set any timestamps they like,
+ * provided that the file is not immutable. The owner still needs
+ * WRITE_ATTRIBUTES (implied by ownership but still deniable).
+ */
+ if (has_priv_suser || vauth_node_owner(&ova, cred)) {
+ KAUTH_DEBUG("ATTR - root or owner changing timestamps");
+ required_action |= KAUTH_VNODE_CHECKIMMUTABLE | KAUTH_VNODE_WRITE_ATTRIBUTES;
+ } else {
+ /* just setting the current time? */
+ if (vap->va_vaflags & VA_UTIMES_NULL) {
+ KAUTH_DEBUG("ATTR - non-root/owner changing timestamps, requiring WRITE_ATTRIBUTES");
+ required_action |= KAUTH_VNODE_WRITE_ATTRIBUTES;
+ } else {
+ KAUTH_DEBUG("ATTR - ERROR: illegal timestamp modification attempted");
+ error = EACCES;
+ goto out;
+ }
+ }
+ }
+
+ /*
+ * Changing file mode?
+ */
+ if (VATTR_IS_ACTIVE(vap, va_mode) && VATTR_IS_SUPPORTED(&ova, va_mode) && (ova.va_mode != vap->va_mode)) {
+ KAUTH_DEBUG("ATTR - mode change from %06o to %06o", ova.va_mode, vap->va_mode);
+
+ /*
+ * Mode changes always have the same basic auth requirements.
+ */
+ if (has_priv_suser) {
+ KAUTH_DEBUG("ATTR - superuser mode change, requiring immutability check");
+ required_action |= KAUTH_VNODE_CHECKIMMUTABLE;
+ } else {
+ /* need WRITE_SECURITY */
+ KAUTH_DEBUG("ATTR - non-superuser mode change, requiring WRITE_SECURITY");
+ required_action |= KAUTH_VNODE_WRITE_SECURITY;
+ }
+
+ /*
+ * Can't set the setgid bit if you're not in the group and not root. Have to have
+ * existing group information in the case we're not setting it right now.
+ */
+ if (vap->va_mode & S_ISGID) {
+ required_action |= KAUTH_VNODE_CHECKIMMUTABLE; /* always required */
+ if (!has_priv_suser) {
+ if (VATTR_IS_ACTIVE(vap, va_gid)) {
+ group = vap->va_gid;
+ } else if (VATTR_IS_SUPPORTED(&ova, va_gid)) {
+ group = ova.va_gid;
+ } else {
+ KAUTH_DEBUG("ATTR - ERROR: setgid but no gid available");
+ error = EINVAL;
+ goto out;
+ }
+ /*
+ * This might be too restrictive; WRITE_SECURITY might be implied by
+ * membership in this case, rather than being an additional requirement.
+ */
+ if ((error = kauth_cred_ismember_gid(cred, group, &ismember)) != 0) {
+ KAUTH_DEBUG("ATTR - ERROR: got %d checking for membership in %d", error, vap->va_gid);
+ goto out;
+ }
+ if (!ismember) {
+ KAUTH_DEBUG(" DENIED - can't set SGID bit, not a member of %d", group);
+ error = EPERM;
+ goto out;
+ }
+ }
+ }
+
+ /*
+ * Can't set the setuid bit unless you're root or the file's owner.
+ */
+ if (vap->va_mode & S_ISUID) {
+ required_action |= KAUTH_VNODE_CHECKIMMUTABLE; /* always required */
+ if (!has_priv_suser) {
+ if (VATTR_IS_ACTIVE(vap, va_uid)) {
+ owner = vap->va_uid;
+ } else if (VATTR_IS_SUPPORTED(&ova, va_uid)) {
+ owner = ova.va_uid;
+ } else {
+ KAUTH_DEBUG("ATTR - ERROR: setuid but no uid available");
+ error = EINVAL;
+ goto out;
+ }
+ if (owner != kauth_cred_getuid(cred)) {
+ /*
+ * We could allow this if WRITE_SECURITY is permitted, perhaps.
+ */
+ KAUTH_DEBUG("ATTR - ERROR: illegal attempt to set the setuid bit");
+ error = EPERM;
+ goto out;
+ }
+ }
+ }
+ }
+
+ /*
+ * Validate/mask flags changes. This checks that only the flags in
+ * the UF_SETTABLE mask are being set, and preserves the flags in
+ * the SF_SETTABLE case.
+ *
+ * Since flags changes may be made in conjunction with other changes,
+ * we will ask the auth code to ignore immutability in the case that
+ * the SF_* flags are not set and we are only manipulating the file flags.
+ *
+ */
+ if (VATTR_IS_ACTIVE(vap, va_flags)) {
+ /* compute changing flags bits */
+ if (VATTR_IS_SUPPORTED(&ova, va_flags)) {
+ fdelta = vap->va_flags ^ ova.va_flags;
+ } else {
+ fdelta = vap->va_flags;
+ }
+
+ if (fdelta != 0) {
+ KAUTH_DEBUG("ATTR - flags changing, requiring WRITE_SECURITY");
+ required_action |= KAUTH_VNODE_WRITE_SECURITY;
+
+ /* check that changing bits are legal */
+ if (has_priv_suser) {
+ /*
+ * The immutability check will prevent us from clearing the SF_*
+ * flags unless the system securelevel permits it, so just check
+ * for legal flags here.
+ */
+ if (fdelta & ~(UF_SETTABLE | SF_SETTABLE)) {
+ error = EPERM;
+ KAUTH_DEBUG(" DENIED - superuser attempt to set illegal flag(s)");
+ goto out;
+ }
+ } else {
+ if (fdelta & ~UF_SETTABLE) {
+ error = EPERM;
+ KAUTH_DEBUG(" DENIED - user attempt to set illegal flag(s)");
+ goto out;
+ }
+ }
+ /*
+ * If the caller has the ability to manipulate file flags,
+ * security is not reduced by ignoring them for this operation.
+ *
+ * A more complete test here would consider the 'after' states of the flags
+ * to determine whether it would permit the operation, but this becomes
+ * very complex.
+ *
+ * Ignoring immutability is conditional on securelevel; this does not bypass
+ * the SF_* flags if securelevel > 0.
+ */
+ required_action |= KAUTH_VNODE_NOIMMUTABLE;
+ }
+ }
+
+ /*
+ * Validate ownership information.
+ */
+ chowner = 0;
+ chgroup = 0;
+ clear_suid = 0;
+ clear_sgid = 0;
+
+ /*
+ * uid changing
+ * Note that if the filesystem didn't give us a UID, we expect that it doesn't
+ * support them in general, and will ignore it if/when we try to set it.
+ * We might want to clear the uid out of vap completely here.
+ */
+ if (VATTR_IS_ACTIVE(vap, va_uid)) {
+ if (VATTR_IS_SUPPORTED(&ova, va_uid) && (vap->va_uid != ova.va_uid)) {
+ if (!has_priv_suser && (kauth_cred_getuid(cred) != vap->va_uid)) {
+ KAUTH_DEBUG(" DENIED - non-superuser cannot change ownershipt to a third party");
+ error = EPERM;
+ goto out;
+ }
+ chowner = 1;
+ }
+ clear_suid = 1;
+ }
+
+ /*
+ * gid changing
+ * Note that if the filesystem didn't give us a GID, we expect that it doesn't
+ * support them in general, and will ignore it if/when we try to set it.
+ * We might want to clear the gid out of vap completely here.
+ */
+ if (VATTR_IS_ACTIVE(vap, va_gid)) {
+ if (VATTR_IS_SUPPORTED(&ova, va_gid) && (vap->va_gid != ova.va_gid)) {
+ if (!has_priv_suser) {
+ if ((error = kauth_cred_ismember_gid(cred, vap->va_gid, &ismember)) != 0) {
+ KAUTH_DEBUG(" ERROR - got %d checking for membership in %d", error, vap->va_gid);
+ goto out;
+ }
+ if (!ismember) {
+ KAUTH_DEBUG(" DENIED - group change from %d to %d but not a member of target group",
+ ova.va_gid, vap->va_gid);
+ error = EPERM;
+ goto out;
+ }
+ }
+ chgroup = 1;
+ }
+ clear_sgid = 1;
+ }