Home | History | Annotate | Line # | Download | only in kern
vfs_lookup.c revision 1.139
      1 /*	$NetBSD: vfs_lookup.c,v 1.139 2011/04/11 01:37:43 dholland Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1982, 1986, 1989, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  * (c) UNIX System Laboratories, Inc.
      7  * All or some portions of this file are derived from material licensed
      8  * to the University of California by American Telephone and Telegraph
      9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     10  * the permission of UNIX System Laboratories, Inc.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  *
     36  *	@(#)vfs_lookup.c	8.10 (Berkeley) 5/27/95
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 __KERNEL_RCSID(0, "$NetBSD: vfs_lookup.c,v 1.139 2011/04/11 01:37:43 dholland Exp $");
     41 
     42 #include "opt_magiclinks.h"
     43 
     44 #include <sys/param.h>
     45 #include <sys/systm.h>
     46 #include <sys/kernel.h>
     47 #include <sys/syslimits.h>
     48 #include <sys/time.h>
     49 #include <sys/namei.h>
     50 #include <sys/vnode.h>
     51 #include <sys/mount.h>
     52 #include <sys/errno.h>
     53 #include <sys/filedesc.h>
     54 #include <sys/hash.h>
     55 #include <sys/proc.h>
     56 #include <sys/syslog.h>
     57 #include <sys/kauth.h>
     58 #include <sys/ktrace.h>
     59 
     60 #ifndef MAGICLINKS
     61 #define MAGICLINKS 0
     62 #endif
     63 
     64 int vfs_magiclinks = MAGICLINKS;
     65 
     66 /*
     67  * Substitute replacement text for 'magic' strings in symlinks.
     68  * Returns 0 if successful, and returns non-zero if an error
     69  * occurs.  (Currently, the only possible error is running out
     70  * of temporary pathname space.)
     71  *
     72  * Looks for "@<string>" and "@<string>/", where <string> is a
     73  * recognized 'magic' string.  Replaces the "@<string>" with the
     74  * appropriate replacement text.  (Note that in some cases the
     75  * replacement text may have zero length.)
     76  *
     77  * This would have been table driven, but the variance in
     78  * replacement strings (and replacement string lengths) made
     79  * that impractical.
     80  */
     81 #define	VNL(x)							\
     82 	(sizeof(x) - 1)
     83 
     84 #define	VO	'{'
     85 #define	VC	'}'
     86 
     87 #define	MATCH(str)						\
     88 	((termchar == '/' && i + VNL(str) == *len) ||		\
     89 	 (i + VNL(str) < *len &&				\
     90 	  cp[i + VNL(str)] == termchar)) &&			\
     91 	!strncmp((str), &cp[i], VNL(str))
     92 
     93 #define	SUBSTITUTE(m, s, sl)					\
     94 	if ((newlen + (sl)) >= MAXPATHLEN)			\
     95 		return 1;					\
     96 	i += VNL(m);						\
     97 	if (termchar != '/')					\
     98 		i++;						\
     99 	(void)memcpy(&tmp[newlen], (s), (sl));			\
    100 	newlen += (sl);						\
    101 	change = 1;						\
    102 	termchar = '/';
    103 
    104 static int
    105 symlink_magic(struct proc *p, char *cp, size_t *len)
    106 {
    107 	char *tmp;
    108 	size_t change, i, newlen, slen;
    109 	char termchar = '/';
    110 	char idtmp[11]; /* enough for 32 bit *unsigned* integer */
    111 
    112 
    113 	tmp = PNBUF_GET();
    114 	for (change = i = newlen = 0; i < *len; ) {
    115 		if (cp[i] != '@') {
    116 			tmp[newlen++] = cp[i++];
    117 			continue;
    118 		}
    119 
    120 		i++;
    121 
    122 		/* Check for @{var} syntax. */
    123 		if (cp[i] == VO) {
    124 			termchar = VC;
    125 			i++;
    126 		}
    127 
    128 		/*
    129 		 * The following checks should be ordered according
    130 		 * to frequency of use.
    131 		 */
    132 		if (MATCH("machine_arch")) {
    133 			slen = VNL(MACHINE_ARCH);
    134 			SUBSTITUTE("machine_arch", MACHINE_ARCH, slen);
    135 		} else if (MATCH("machine")) {
    136 			slen = VNL(MACHINE);
    137 			SUBSTITUTE("machine", MACHINE, slen);
    138 		} else if (MATCH("hostname")) {
    139 			SUBSTITUTE("hostname", hostname, hostnamelen);
    140 		} else if (MATCH("osrelease")) {
    141 			slen = strlen(osrelease);
    142 			SUBSTITUTE("osrelease", osrelease, slen);
    143 		} else if (MATCH("emul")) {
    144 			slen = strlen(p->p_emul->e_name);
    145 			SUBSTITUTE("emul", p->p_emul->e_name, slen);
    146 		} else if (MATCH("kernel_ident")) {
    147 			slen = strlen(kernel_ident);
    148 			SUBSTITUTE("kernel_ident", kernel_ident, slen);
    149 		} else if (MATCH("domainname")) {
    150 			SUBSTITUTE("domainname", domainname, domainnamelen);
    151 		} else if (MATCH("ostype")) {
    152 			slen = strlen(ostype);
    153 			SUBSTITUTE("ostype", ostype, slen);
    154 		} else if (MATCH("uid")) {
    155 			slen = snprintf(idtmp, sizeof(idtmp), "%u",
    156 			    kauth_cred_geteuid(kauth_cred_get()));
    157 			SUBSTITUTE("uid", idtmp, slen);
    158 		} else if (MATCH("ruid")) {
    159 			slen = snprintf(idtmp, sizeof(idtmp), "%u",
    160 			    kauth_cred_getuid(kauth_cred_get()));
    161 			SUBSTITUTE("ruid", idtmp, slen);
    162 		} else if (MATCH("gid")) {
    163 			slen = snprintf(idtmp, sizeof(idtmp), "%u",
    164 			    kauth_cred_getegid(kauth_cred_get()));
    165 			SUBSTITUTE("gid", idtmp, slen);
    166 		} else if (MATCH("rgid")) {
    167 			slen = snprintf(idtmp, sizeof(idtmp), "%u",
    168 			    kauth_cred_getgid(kauth_cred_get()));
    169 			SUBSTITUTE("rgid", idtmp, slen);
    170 		} else {
    171 			tmp[newlen++] = '@';
    172 			if (termchar == VC)
    173 				tmp[newlen++] = VO;
    174 		}
    175 	}
    176 
    177 	if (change) {
    178 		(void)memcpy(cp, tmp, newlen);
    179 		*len = newlen;
    180 	}
    181 	PNBUF_PUT(tmp);
    182 
    183 	return 0;
    184 }
    185 
    186 #undef VNL
    187 #undef VO
    188 #undef VC
    189 #undef MATCH
    190 #undef SUBSTITUTE
    191 
    192 ////////////////////////////////////////////////////////////
    193 
    194 /*
    195  * Determine the namei hash (for cn_hash) for name.
    196  * If *ep != NULL, hash from name to ep-1.
    197  * If *ep == NULL, hash from name until the first NUL or '/', and
    198  * return the location of this termination character in *ep.
    199  *
    200  * This function returns an equivalent hash to the MI hash32_strn().
    201  * The latter isn't used because in the *ep == NULL case, determining
    202  * the length of the string to the first NUL or `/' and then calling
    203  * hash32_strn() involves unnecessary double-handling of the data.
    204  */
    205 uint32_t
    206 namei_hash(const char *name, const char **ep)
    207 {
    208 	uint32_t	hash;
    209 
    210 	hash = HASH32_STR_INIT;
    211 	if (*ep != NULL) {
    212 		for (; name < *ep; name++)
    213 			hash = hash * 33 + *(const uint8_t *)name;
    214 	} else {
    215 		for (; *name != '\0' && *name != '/'; name++)
    216 			hash = hash * 33 + *(const uint8_t *)name;
    217 		*ep = name;
    218 	}
    219 	return (hash + (hash >> 5));
    220 }
    221 
    222 ////////////////////////////////////////////////////////////
    223 
    224 /*
    225  * Sealed abstraction for pathnames.
    226  *
    227  * System-call-layer level code that is going to call namei should
    228  * first create a pathbuf and adjust all the bells and whistles on it
    229  * as needed by context
    230  */
    231 
    232 struct pathbuf {
    233 	char *pb_path;
    234 	char *pb_pathcopy;
    235 	unsigned pb_pathcopyuses;
    236 };
    237 
    238 static struct pathbuf *
    239 pathbuf_create_raw(void)
    240 {
    241 	struct pathbuf *pb;
    242 
    243 	pb = kmem_alloc(sizeof(*pb), KM_SLEEP);
    244 	if (pb == NULL) {
    245 		return NULL;
    246 	}
    247 	pb->pb_path = PNBUF_GET();
    248 	if (pb->pb_path == NULL) {
    249 		kmem_free(pb, sizeof(*pb));
    250 		return NULL;
    251 	}
    252 	pb->pb_pathcopy = NULL;
    253 	pb->pb_pathcopyuses = 0;
    254 	return pb;
    255 }
    256 
    257 void
    258 pathbuf_destroy(struct pathbuf *pb)
    259 {
    260 	KASSERT(pb->pb_pathcopyuses == 0);
    261 	KASSERT(pb->pb_pathcopy == NULL);
    262 	PNBUF_PUT(pb->pb_path);
    263 	kmem_free(pb, sizeof(*pb));
    264 }
    265 
    266 struct pathbuf *
    267 pathbuf_assimilate(char *pnbuf)
    268 {
    269 	struct pathbuf *pb;
    270 
    271 	pb = kmem_alloc(sizeof(*pb), KM_SLEEP);
    272 	if (pb == NULL) {
    273 		return NULL;
    274 	}
    275 	pb->pb_path = pnbuf;
    276 	pb->pb_pathcopy = NULL;
    277 	pb->pb_pathcopyuses = 0;
    278 	return pb;
    279 }
    280 
    281 struct pathbuf *
    282 pathbuf_create(const char *path)
    283 {
    284 	struct pathbuf *pb;
    285 	int error;
    286 
    287 	pb = pathbuf_create_raw();
    288 	if (pb == NULL) {
    289 		return NULL;
    290 	}
    291 	error = copystr(path, pb->pb_path, PATH_MAX, NULL);
    292 	if (error != 0) {
    293 		KASSERT(!"kernel path too long in pathbuf_create");
    294 		/* make sure it's null-terminated, just in case */
    295 		pb->pb_path[PATH_MAX-1] = '\0';
    296 	}
    297 	return pb;
    298 }
    299 
    300 int
    301 pathbuf_copyin(const char *userpath, struct pathbuf **ret)
    302 {
    303 	struct pathbuf *pb;
    304 	int error;
    305 
    306 	pb = pathbuf_create_raw();
    307 	if (pb == NULL) {
    308 		return ENOMEM;
    309 	}
    310 	error = copyinstr(userpath, pb->pb_path, PATH_MAX, NULL);
    311 	if (error) {
    312 		pathbuf_destroy(pb);
    313 		return error;
    314 	}
    315 	*ret = pb;
    316 	return 0;
    317 }
    318 
    319 /*
    320  * XXX should not exist
    321  */
    322 int
    323 pathbuf_maybe_copyin(const char *path, enum uio_seg seg, struct pathbuf **ret)
    324 {
    325 	if (seg == UIO_USERSPACE) {
    326 		return pathbuf_copyin(path, ret);
    327 	} else {
    328 		*ret = pathbuf_create(path);
    329 		if (*ret == NULL) {
    330 			return ENOMEM;
    331 		}
    332 		return 0;
    333 	}
    334 }
    335 
    336 /*
    337  * Get a copy of the path buffer as it currently exists. If this is
    338  * called after namei starts the results may be arbitrary.
    339  */
    340 void
    341 pathbuf_copystring(const struct pathbuf *pb, char *buf, size_t maxlen)
    342 {
    343 	strlcpy(buf, pb->pb_path, maxlen);
    344 }
    345 
    346 /*
    347  * These two functions allow access to a saved copy of the original
    348  * path string. The first copy should be gotten before namei is
    349  * called. Each copy that is gotten should be put back.
    350  */
    351 
    352 const char *
    353 pathbuf_stringcopy_get(struct pathbuf *pb)
    354 {
    355 	if (pb->pb_pathcopyuses == 0) {
    356 		pb->pb_pathcopy = PNBUF_GET();
    357 		strcpy(pb->pb_pathcopy, pb->pb_path);
    358 	}
    359 	pb->pb_pathcopyuses++;
    360 	return pb->pb_pathcopy;
    361 }
    362 
    363 void
    364 pathbuf_stringcopy_put(struct pathbuf *pb, const char *str)
    365 {
    366 	KASSERT(str == pb->pb_pathcopy);
    367 	KASSERT(pb->pb_pathcopyuses > 0);
    368 	pb->pb_pathcopyuses--;
    369 	if (pb->pb_pathcopyuses == 0) {
    370 		PNBUF_PUT(pb->pb_pathcopy);
    371 		pb->pb_pathcopy = NULL;
    372 	}
    373 }
    374 
    375 
    376 ////////////////////////////////////////////////////////////
    377 
    378 /*
    379  * Convert a pathname into a pointer to a locked vnode.
    380  *
    381  * The FOLLOW flag is set when symbolic links are to be followed
    382  * when they occur at the end of the name translation process.
    383  * Symbolic links are always followed for all other pathname
    384  * components other than the last.
    385  *
    386  * The segflg defines whether the name is to be copied from user
    387  * space or kernel space.
    388  *
    389  * Overall outline of namei:
    390  *
    391  *	copy in name
    392  *	get starting directory
    393  *	while (!done && !error) {
    394  *		call lookup to search path.
    395  *		if symbolic link, massage name in buffer and continue
    396  *	}
    397  */
    398 
    399 /*
    400  * Internal state for a namei operation.
    401  */
    402 struct namei_state {
    403 	struct nameidata *ndp;
    404 	struct componentname *cnp;
    405 
    406 	/* used by the pieces of namei */
    407 	struct vnode *namei_startdir; /* The directory namei() starts from. */
    408 
    409 	/* used by the pieces of lookup */
    410 	int lookup_alldone;
    411 
    412 	int docache;			/* == 0 do not cache last component */
    413 	int rdonly;			/* lookup read-only flag bit */
    414 	struct vnode *dp;		/* the directory we are searching */
    415 	int slashes;
    416 
    417 	unsigned attempt_retry:1;	/* true if error allows emul retry */
    418 };
    419 
    420 
    421 /*
    422  * Initialize the namei working state.
    423  */
    424 static void
    425 namei_init(struct namei_state *state, struct nameidata *ndp)
    426 {
    427 	state->ndp = ndp;
    428 	state->cnp = &ndp->ni_cnd;
    429 	KASSERT((state->cnp->cn_flags & INRELOOKUP) == 0);
    430 
    431 	state->namei_startdir = NULL;
    432 
    433 	state->lookup_alldone = 0;
    434 
    435 	state->docache = 0;
    436 	state->rdonly = 0;
    437 	state->dp = NULL;
    438 	state->slashes = 0;
    439 
    440 #ifdef DIAGNOSTIC
    441 	if (!state->cnp->cn_cred)
    442 		panic("namei: bad cred/proc");
    443 	if (state->cnp->cn_nameiop & (~OPMASK))
    444 		panic("namei: nameiop contaminated with flags");
    445 	if (state->cnp->cn_flags & OPMASK)
    446 		panic("namei: flags contaminated with nameiops");
    447 #endif
    448 
    449 	/*
    450 	 * The buffer for name translation shall be the one inside the
    451 	 * pathbuf.
    452 	 */
    453 	state->ndp->ni_pnbuf = state->ndp->ni_pathbuf->pb_path;
    454 }
    455 
    456 /*
    457  * Clean up the working namei state, leaving things ready for return
    458  * from namei.
    459  */
    460 static void
    461 namei_cleanup(struct namei_state *state)
    462 {
    463 	KASSERT(state->cnp == &state->ndp->ni_cnd);
    464 
    465 	//KASSERT(state->namei_startdir == NULL); 	// not yet
    466 
    467 	/* nothing for now */
    468 	(void)state;
    469 }
    470 
    471 //////////////////////////////
    472 
    473 /*
    474  * Get the directory context.
    475  * Initializes the rootdir and erootdir state and returns a reference
    476  * to the starting dir.
    477  */
    478 static struct vnode *
    479 namei_getstartdir(struct namei_state *state)
    480 {
    481 	struct nameidata *ndp = state->ndp;
    482 	struct componentname *cnp = state->cnp;
    483 	struct cwdinfo *cwdi;		/* pointer to cwd state */
    484 	struct lwp *self = curlwp;	/* thread doing namei() */
    485 	struct vnode *rootdir, *erootdir, *curdir, *startdir;
    486 
    487 	cwdi = self->l_proc->p_cwdi;
    488 	rw_enter(&cwdi->cwdi_lock, RW_READER);
    489 
    490 	/* root dir */
    491 	if (cwdi->cwdi_rdir == NULL || (cnp->cn_flags & NOCHROOT)) {
    492 		rootdir = rootvnode;
    493 	} else {
    494 		rootdir = cwdi->cwdi_rdir;
    495 	}
    496 
    497 	/* emulation root dir, if any */
    498 	if ((cnp->cn_flags & TRYEMULROOT) == 0) {
    499 		/* if we don't want it, don't fetch it */
    500 		erootdir = NULL;
    501 	} else if (cnp->cn_flags & EMULROOTSET) {
    502 		/* explicitly set emulroot; "/../" doesn't override this */
    503 		erootdir = ndp->ni_erootdir;
    504 	} else if (!strncmp(ndp->ni_pnbuf, "/../", 4)) {
    505 		/* explicit reference to real rootdir */
    506 		erootdir = NULL;
    507 	} else {
    508 		/* may be null */
    509 		erootdir = cwdi->cwdi_edir;
    510 	}
    511 
    512 	/* current dir */
    513 	curdir = cwdi->cwdi_cdir;
    514 
    515 	if (ndp->ni_pnbuf[0] != '/') {
    516 		startdir = curdir;
    517 		erootdir = NULL;
    518 	} else if (cnp->cn_flags & TRYEMULROOT && erootdir != NULL) {
    519 		startdir = erootdir;
    520 	} else {
    521 		startdir = rootdir;
    522 		erootdir = NULL;
    523 	}
    524 
    525 	state->ndp->ni_rootdir = rootdir;
    526 	state->ndp->ni_erootdir = erootdir;
    527 
    528 	/*
    529 	 * Get a reference to the start dir so we can safely unlock cwdi.
    530 	 *
    531 	 * XXX: should we hold references to rootdir and erootdir while
    532 	 * we're running? What happens if a multithreaded process chroots
    533 	 * during namei?
    534 	 */
    535 	vref(startdir);
    536 
    537 	rw_exit(&cwdi->cwdi_lock);
    538 	return startdir;
    539 }
    540 
    541 /*
    542  * Get the directory context for the nfsd case, in parallel to
    543  * getstartdir. Initializes the rootdir and erootdir state and
    544  * returns a reference to the passed-instarting dir.
    545  */
    546 static struct vnode *
    547 namei_getstartdir_for_nfsd(struct namei_state *state, struct vnode *startdir)
    548 {
    549 	/* always use the real root, and never set an emulation root */
    550 	state->ndp->ni_rootdir = rootvnode;
    551 	state->ndp->ni_erootdir = NULL;
    552 
    553 	vref(startdir);
    554 	return startdir;
    555 }
    556 
    557 
    558 /*
    559  * Ktrace the namei operation.
    560  */
    561 static void
    562 namei_ktrace(struct namei_state *state)
    563 {
    564 	struct nameidata *ndp = state->ndp;
    565 	struct componentname *cnp = state->cnp;
    566 	struct lwp *self = curlwp;	/* thread doing namei() */
    567 	const char *emul_path;
    568 
    569 	if (ktrpoint(KTR_NAMEI)) {
    570 		if (ndp->ni_erootdir != NULL) {
    571 			/*
    572 			 * To make any sense, the trace entry need to have the
    573 			 * text of the emulation path prepended.
    574 			 * Usually we can get this from the current process,
    575 			 * but when called from emul_find_interp() it is only
    576 			 * in the exec_package - so we get it passed in ni_next
    577 			 * (this is a hack).
    578 			 */
    579 			if (cnp->cn_flags & EMULROOTSET)
    580 				emul_path = ndp->ni_next;
    581 			else
    582 				emul_path = self->l_proc->p_emul->e_path;
    583 			ktrnamei2(emul_path, strlen(emul_path),
    584 			    ndp->ni_pnbuf, ndp->ni_pathlen);
    585 		} else
    586 			ktrnamei(ndp->ni_pnbuf, ndp->ni_pathlen);
    587 	}
    588 }
    589 
    590 /*
    591  * Start up namei. Copy the path, find the root dir and cwd, establish
    592  * the starting directory for lookup, and lock it. Also calls ktrace when
    593  * appropriate.
    594  */
    595 static int
    596 namei_start(struct namei_state *state, struct vnode *forcecwd)
    597 {
    598 	struct nameidata *ndp = state->ndp;
    599 
    600 	/* length includes null terminator (was originally from copyinstr) */
    601 	ndp->ni_pathlen = strlen(ndp->ni_pnbuf) + 1;
    602 
    603 	/*
    604 	 * POSIX.1 requirement: "" is not a valid file name.
    605 	 */
    606 	if (ndp->ni_pathlen == 1) {
    607 		ndp->ni_vp = NULL;
    608 		return ENOENT;
    609 	}
    610 
    611 	ndp->ni_loopcnt = 0;
    612 
    613 	/* Get starting directory, set up root, and ktrace. */
    614 	if (forcecwd != NULL) {
    615 		state->namei_startdir = namei_getstartdir_for_nfsd(state,
    616 								   forcecwd);
    617 		/* no ktrace */
    618 	} else {
    619 		state->namei_startdir = namei_getstartdir(state);
    620 		namei_ktrace(state);
    621 	}
    622 
    623 	vn_lock(state->namei_startdir, LK_EXCLUSIVE | LK_RETRY);
    624 
    625 	return 0;
    626 }
    627 
    628 /*
    629  * Undo namei_start: unlock and release the current lookup directory.
    630  */
    631 static void
    632 namei_end(struct namei_state *state)
    633 {
    634 	vput(state->namei_startdir);
    635 }
    636 
    637 /*
    638  * Check for being at a symlink.
    639  */
    640 static inline int
    641 namei_atsymlink(struct namei_state *state)
    642 {
    643 	return (state->dp->v_type == VLNK) &&
    644 		(state->cnp->cn_flags & (FOLLOW|REQUIREDIR));
    645 }
    646 
    647 /*
    648  * Follow a symlink.
    649  */
    650 static inline int
    651 namei_follow(struct namei_state *state, int inhibitmagic)
    652 {
    653 	struct nameidata *ndp = state->ndp;
    654 	struct componentname *cnp = state->cnp;
    655 
    656 	struct lwp *self = curlwp;	/* thread doing namei() */
    657 	struct iovec aiov;		/* uio for reading symbolic links */
    658 	struct uio auio;
    659 	char *cp;			/* pointer into pathname argument */
    660 	size_t linklen;
    661 	int error;
    662 
    663 	if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
    664 		return ELOOP;
    665 	}
    666 	if (ndp->ni_vp->v_mount->mnt_flag & MNT_SYMPERM) {
    667 		error = VOP_ACCESS(ndp->ni_vp, VEXEC, cnp->cn_cred);
    668 		if (error != 0)
    669 			return error;
    670 	}
    671 
    672 	/* FUTURE: fix this to not use a second buffer */
    673 	cp = PNBUF_GET();
    674 	aiov.iov_base = cp;
    675 	aiov.iov_len = MAXPATHLEN;
    676 	auio.uio_iov = &aiov;
    677 	auio.uio_iovcnt = 1;
    678 	auio.uio_offset = 0;
    679 	auio.uio_rw = UIO_READ;
    680 	auio.uio_resid = MAXPATHLEN;
    681 	UIO_SETUP_SYSSPACE(&auio);
    682 	error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
    683 	if (error) {
    684 		PNBUF_PUT(cp);
    685 		return error;
    686 	}
    687 	linklen = MAXPATHLEN - auio.uio_resid;
    688 	if (linklen == 0) {
    689 		PNBUF_PUT(cp);
    690 		return ENOENT;
    691 	}
    692 
    693 	/*
    694 	 * Do symlink substitution, if appropriate, and
    695 	 * check length for potential overflow.
    696 	 *
    697 	 * Inhibit symlink substitution for nfsd.
    698 	 * XXX: This is how it was before; is that a bug or a feature?
    699 	 */
    700 	if ((!inhibitmagic && vfs_magiclinks &&
    701 	     symlink_magic(self->l_proc, cp, &linklen)) ||
    702 	    (linklen + ndp->ni_pathlen >= MAXPATHLEN)) {
    703 		PNBUF_PUT(cp);
    704 		return ENAMETOOLONG;
    705 	}
    706 	if (ndp->ni_pathlen > 1) {
    707 		/* includes a null-terminator */
    708 		memcpy(cp + linklen, ndp->ni_next, ndp->ni_pathlen);
    709 	} else {
    710 		cp[linklen] = '\0';
    711 	}
    712 	ndp->ni_pathlen += linklen;
    713 	memcpy(ndp->ni_pnbuf, cp, ndp->ni_pathlen);
    714 	PNBUF_PUT(cp);
    715 	vput(ndp->ni_vp);
    716 	state->namei_startdir = ndp->ni_dvp;
    717 
    718 	/*
    719 	 * Check if root directory should replace current directory.
    720 	 */
    721 	if (ndp->ni_pnbuf[0] == '/') {
    722 		vput(state->namei_startdir);
    723 		/* Keep absolute symbolic links inside emulation root */
    724 		state->namei_startdir = ndp->ni_erootdir;
    725 		if (state->namei_startdir == NULL ||
    726 		    (ndp->ni_pnbuf[1] == '.'
    727 		     && ndp->ni_pnbuf[2] == '.'
    728 		     && ndp->ni_pnbuf[3] == '/')) {
    729 			ndp->ni_erootdir = NULL;
    730 			state->namei_startdir = ndp->ni_rootdir;
    731 		}
    732 		vref(state->namei_startdir);
    733 		vn_lock(state->namei_startdir, LK_EXCLUSIVE | LK_RETRY);
    734 	}
    735 
    736 	return 0;
    737 }
    738 
    739 //////////////////////////////
    740 
    741 /*
    742  * Search a pathname.
    743  * This is a very central and rather complicated routine.
    744  *
    745  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
    746  * The starting directory is passed in. The pathname is descended
    747  * until done, or a symbolic link is encountered. The variable ni_more
    748  * is clear if the path is completed; it is set to one if a symbolic
    749  * link needing interpretation is encountered.
    750  *
    751  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
    752  * whether the name is to be looked up, created, renamed, or deleted.
    753  * When CREATE, RENAME, or DELETE is specified, information usable in
    754  * creating, renaming, or deleting a directory entry may be calculated.
    755  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
    756  * locked.  Otherwise the parent directory is not returned. If the target
    757  * of the pathname exists and LOCKLEAF is or'ed into the flag the target
    758  * is returned locked, otherwise it is returned unlocked.  When creating
    759  * or renaming and LOCKPARENT is specified, the target may not be ".".
    760  * When deleting and LOCKPARENT is specified, the target may be ".".
    761  *
    762  * Overall outline of lookup:
    763  *
    764  * dirloop:
    765  *	identify next component of name at ndp->ni_ptr
    766  *	handle degenerate case where name is null string
    767  *	if .. and crossing mount points and on mounted filesys, find parent
    768  *	call VOP_LOOKUP routine for next component name
    769  *	    directory vnode returned in ni_dvp, locked.
    770  *	    component vnode returned in ni_vp (if it exists), locked.
    771  *	if result vnode is mounted on and crossing mount points,
    772  *	    find mounted on vnode
    773  *	if more components of name, do next level at dirloop
    774  *	return the answer in ni_vp, locked if LOCKLEAF set
    775  *	    if LOCKPARENT set, return locked parent in ni_dvp
    776  */
    777 
    778 static int
    779 lookup_parsepath(struct namei_state *state)
    780 {
    781 	const char *cp;			/* pointer into pathname argument */
    782 
    783 	struct componentname *cnp = state->cnp;
    784 	struct nameidata *ndp = state->ndp;
    785 
    786 	KASSERT(cnp == &ndp->ni_cnd);
    787 
    788 	/*
    789 	 * Search a new directory.
    790 	 *
    791 	 * The cn_hash value is for use by vfs_cache.
    792 	 * The last component of the filename is left accessible via
    793 	 * cnp->cn_nameptr for callers that need the name. Callers needing
    794 	 * the name set the SAVENAME flag. When done, they assume
    795 	 * responsibility for freeing the pathname buffer.
    796 	 *
    797 	 * At this point, our only vnode state is that "dp" is held and locked.
    798 	 */
    799 	cnp->cn_consume = 0;
    800 	cp = NULL;
    801 	cnp->cn_hash = namei_hash(cnp->cn_nameptr, &cp);
    802 	cnp->cn_namelen = cp - cnp->cn_nameptr;
    803 	if (cnp->cn_namelen > NAME_MAX) {
    804 		vput(state->dp);
    805 		ndp->ni_dvp = NULL;
    806 		return ENAMETOOLONG;
    807 	}
    808 #ifdef NAMEI_DIAGNOSTIC
    809 	{ char c = *cp;
    810 	*(char *)cp = '\0';
    811 	printf("{%s}: ", cnp->cn_nameptr);
    812 	*(char *)cp = c; }
    813 #endif /* NAMEI_DIAGNOSTIC */
    814 	ndp->ni_pathlen -= cnp->cn_namelen;
    815 	ndp->ni_next = cp;
    816 	/*
    817 	 * If this component is followed by a slash, then move the pointer to
    818 	 * the next component forward, and remember that this component must be
    819 	 * a directory.
    820 	 */
    821 	if (*cp == '/') {
    822 		do {
    823 			cp++;
    824 		} while (*cp == '/');
    825 		state->slashes = cp - ndp->ni_next;
    826 		ndp->ni_pathlen -= state->slashes;
    827 		ndp->ni_next = cp;
    828 		cnp->cn_flags |= REQUIREDIR;
    829 	} else {
    830 		state->slashes = 0;
    831 		cnp->cn_flags &= ~REQUIREDIR;
    832 	}
    833 	/*
    834 	 * We do special processing on the last component, whether or not it's
    835 	 * a directory.  Cache all intervening lookups, but not the final one.
    836 	 */
    837 	if (*cp == '\0') {
    838 		if (state->docache)
    839 			cnp->cn_flags |= MAKEENTRY;
    840 		else
    841 			cnp->cn_flags &= ~MAKEENTRY;
    842 		cnp->cn_flags |= ISLASTCN;
    843 	} else {
    844 		cnp->cn_flags |= MAKEENTRY;
    845 		cnp->cn_flags &= ~ISLASTCN;
    846 	}
    847 	if (cnp->cn_namelen == 2 &&
    848 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
    849 		cnp->cn_flags |= ISDOTDOT;
    850 	else
    851 		cnp->cn_flags &= ~ISDOTDOT;
    852 
    853 	return 0;
    854 }
    855 
    856 static int
    857 lookup_once(struct namei_state *state)
    858 {
    859 	struct vnode *tdp;		/* saved dp */
    860 	struct mount *mp;		/* mount table entry */
    861 	struct lwp *l = curlwp;
    862 	int error;
    863 
    864 	struct componentname *cnp = state->cnp;
    865 	struct nameidata *ndp = state->ndp;
    866 
    867 	KASSERT(cnp == &ndp->ni_cnd);
    868 
    869 	/*
    870 	 * Handle "..": two special cases.
    871 	 * 1. If at root directory (e.g. after chroot)
    872 	 *    or at absolute root directory
    873 	 *    then ignore it so can't get out.
    874 	 * 1a. If at the root of the emulation filesystem go to the real
    875 	 *    root. So "/../<path>" is always absolute.
    876 	 * 1b. If we have somehow gotten out of a jail, warn
    877 	 *    and also ignore it so we can't get farther out.
    878 	 * 2. If this vnode is the root of a mounted
    879 	 *    filesystem, then replace it with the
    880 	 *    vnode which was mounted on so we take the
    881 	 *    .. in the other file system.
    882 	 */
    883 	if (cnp->cn_flags & ISDOTDOT) {
    884 		struct proc *p = l->l_proc;
    885 
    886 		for (;;) {
    887 			if (state->dp == ndp->ni_rootdir || state->dp == rootvnode) {
    888 				ndp->ni_dvp = state->dp;
    889 				ndp->ni_vp = state->dp;
    890 				vref(state->dp);
    891 				return 0;
    892 			}
    893 			if (ndp->ni_rootdir != rootvnode) {
    894 				int retval;
    895 
    896 				VOP_UNLOCK(state->dp);
    897 				retval = vn_isunder(state->dp, ndp->ni_rootdir, l);
    898 				vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
    899 				if (!retval) {
    900 				    /* Oops! We got out of jail! */
    901 				    log(LOG_WARNING,
    902 					"chrooted pid %d uid %d (%s) "
    903 					"detected outside of its chroot\n",
    904 					p->p_pid, kauth_cred_geteuid(l->l_cred),
    905 					p->p_comm);
    906 				    /* Put us at the jail root. */
    907 				    vput(state->dp);
    908 				    state->dp = ndp->ni_rootdir;
    909 				    ndp->ni_dvp = state->dp;
    910 				    ndp->ni_vp = state->dp;
    911 				    vref(state->dp);
    912 				    vref(state->dp);
    913 				    vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
    914 				    return 0;
    915 				}
    916 			}
    917 			if ((state->dp->v_vflag & VV_ROOT) == 0 ||
    918 			    (cnp->cn_flags & NOCROSSMOUNT))
    919 				break;
    920 			tdp = state->dp;
    921 			state->dp = state->dp->v_mount->mnt_vnodecovered;
    922 			vput(tdp);
    923 			vref(state->dp);
    924 			vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
    925 		}
    926 	}
    927 
    928 	/*
    929 	 * We now have a segment name to search for, and a directory to search.
    930 	 * Again, our only vnode state is that "dp" is held and locked.
    931 	 */
    932 unionlookup:
    933 	ndp->ni_dvp = state->dp;
    934 	ndp->ni_vp = NULL;
    935 	error = VOP_LOOKUP(state->dp, &ndp->ni_vp, cnp);
    936 	if (error != 0) {
    937 #ifdef DIAGNOSTIC
    938 		if (ndp->ni_vp != NULL)
    939 			panic("leaf `%s' should be empty", cnp->cn_nameptr);
    940 #endif /* DIAGNOSTIC */
    941 #ifdef NAMEI_DIAGNOSTIC
    942 		printf("not found\n");
    943 #endif /* NAMEI_DIAGNOSTIC */
    944 		if ((error == ENOENT) &&
    945 		    (state->dp->v_vflag & VV_ROOT) &&
    946 		    (state->dp->v_mount->mnt_flag & MNT_UNION)) {
    947 			tdp = state->dp;
    948 			state->dp = state->dp->v_mount->mnt_vnodecovered;
    949 			vput(tdp);
    950 			vref(state->dp);
    951 			vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
    952 			goto unionlookup;
    953 		}
    954 
    955 		if (error != EJUSTRETURN)
    956 			return error;
    957 
    958 		/*
    959 		 * If this was not the last component, or there were trailing
    960 		 * slashes, and we are not going to create a directory,
    961 		 * then the name must exist.
    962 		 */
    963 		if ((cnp->cn_flags & (REQUIREDIR | CREATEDIR)) == REQUIREDIR) {
    964 			return ENOENT;
    965 		}
    966 
    967 		/*
    968 		 * If creating and at end of pathname, then can consider
    969 		 * allowing file to be created.
    970 		 */
    971 		if (state->rdonly) {
    972 			return EROFS;
    973 		}
    974 
    975 		/*
    976 		 * We return with ni_vp NULL to indicate that the entry
    977 		 * doesn't currently exist, leaving a pointer to the
    978 		 * (possibly locked) directory vnode in ndp->ni_dvp.
    979 		 */
    980 		state->lookup_alldone = 1;
    981 		return (0);
    982 	}
    983 #ifdef NAMEI_DIAGNOSTIC
    984 	printf("found\n");
    985 #endif /* NAMEI_DIAGNOSTIC */
    986 
    987 	/*
    988 	 * Take into account any additional components consumed by the
    989 	 * underlying filesystem.  This will include any trailing slashes after
    990 	 * the last component consumed.
    991 	 */
    992 	if (cnp->cn_consume > 0) {
    993 		ndp->ni_pathlen -= cnp->cn_consume - state->slashes;
    994 		ndp->ni_next += cnp->cn_consume - state->slashes;
    995 		cnp->cn_consume = 0;
    996 		if (ndp->ni_next[0] == '\0')
    997 			cnp->cn_flags |= ISLASTCN;
    998 	}
    999 
   1000 	state->dp = ndp->ni_vp;
   1001 
   1002 	/*
   1003 	 * "state->dp" and "ndp->ni_dvp" are both locked and held,
   1004 	 * and may be the same vnode.
   1005 	 */
   1006 
   1007 	/*
   1008 	 * Check to see if the vnode has been mounted on;
   1009 	 * if so find the root of the mounted file system.
   1010 	 */
   1011 	while (state->dp->v_type == VDIR && (mp = state->dp->v_mountedhere) &&
   1012 	       (cnp->cn_flags & NOCROSSMOUNT) == 0) {
   1013 		error = vfs_busy(mp, NULL);
   1014 		if (error != 0) {
   1015 			vput(state->dp);
   1016 			return error;
   1017 		}
   1018 		KASSERT(ndp->ni_dvp != state->dp);
   1019 		VOP_UNLOCK(ndp->ni_dvp);
   1020 		vput(state->dp);
   1021 		error = VFS_ROOT(mp, &tdp);
   1022 		vfs_unbusy(mp, false, NULL);
   1023 		if (error) {
   1024 			vn_lock(ndp->ni_dvp, LK_EXCLUSIVE | LK_RETRY);
   1025 			return error;
   1026 		}
   1027 		VOP_UNLOCK(tdp);
   1028 		ndp->ni_vp = state->dp = tdp;
   1029 		vn_lock(ndp->ni_dvp, LK_EXCLUSIVE | LK_RETRY);
   1030 		vn_lock(ndp->ni_vp, LK_EXCLUSIVE | LK_RETRY);
   1031 	}
   1032 
   1033 	return 0;
   1034 }
   1035 
   1036 //////////////////////////////
   1037 
   1038 static int
   1039 namei_oneroot(struct namei_state *state, struct vnode *forcecwd,
   1040 	 int neverfollow, int inhibitmagic)
   1041 {
   1042 	struct nameidata *ndp = state->ndp;
   1043 	struct componentname *cnp = state->cnp;
   1044 	const char *cp;
   1045 	int error;
   1046 
   1047 	error = namei_start(state, forcecwd);
   1048 	if (error) {
   1049 		return error;
   1050 	}
   1051 
   1052 	/*
   1053 	 * Setup: break out flag bits into variables.
   1054 	 */
   1055 	state->docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
   1056 	if (cnp->cn_nameiop == DELETE)
   1057 		state->docache = 0;
   1058 	state->rdonly = cnp->cn_flags & RDONLY;
   1059 
   1060 	/*
   1061 	 * Keep going until we run out of path components.
   1062 	 */
   1063 	cnp->cn_nameptr = ndp->ni_pnbuf;
   1064 	for (;;) {
   1065 
   1066 		/*
   1067 		 * If the directory we're on is unmounted, bail out.
   1068 		 * XXX: should this also check if it's unlinked?
   1069 		 */
   1070 		if (state->namei_startdir->v_mount == NULL) {
   1071 			namei_end(state);
   1072 			return (ENOENT);
   1073 		}
   1074 
   1075 		/*
   1076 		 * Look up the next path component.
   1077 		 * (currently, this may consume more than one)
   1078 		 */
   1079 
   1080 		state->lookup_alldone = 0;
   1081 
   1082 		ndp->ni_dvp = NULL;
   1083 		cnp->cn_flags &= ~ISSYMLINK;
   1084 		state->dp = state->namei_startdir;
   1085 
   1086     dirloop:
   1087 		/*
   1088 		 * If we have a leading string of slashes, remove
   1089 		 * them, and just make sure the current node is a
   1090 		 * directory.
   1091 		 */
   1092 		cp = cnp->cn_nameptr;
   1093 		if (*cp == '/') {
   1094 			do {
   1095 				cp++;
   1096 			} while (*cp == '/');
   1097 			ndp->ni_pathlen -= cp - cnp->cn_nameptr;
   1098 			cnp->cn_nameptr = cp;
   1099 
   1100 			if (state->dp->v_type != VDIR) {
   1101 				vput(state->dp);
   1102 				ndp->ni_vp = NULL;
   1103 				/* XXX this should use namei_end() */
   1104 				if (ndp->ni_dvp) {
   1105 					vput(ndp->ni_dvp);
   1106 				}
   1107 				state->attempt_retry = 1;
   1108 				return ENOTDIR;
   1109 			}
   1110 		}
   1111 
   1112 		/*
   1113 		 * If we've exhausted the path name, then just return the
   1114 		 * current node.
   1115 		 */
   1116 		if (cnp->cn_nameptr[0] == '\0') {
   1117 			ndp->ni_vp = state->dp;
   1118 			cnp->cn_flags |= ISLASTCN;
   1119 
   1120 			/* bleh */
   1121 			goto terminal;
   1122 		}
   1123 
   1124 		error = lookup_parsepath(state);
   1125 		if (error) {
   1126 			ndp->ni_vp = NULL;
   1127 			/* XXX this should use namei_end() */
   1128 			if (ndp->ni_dvp) {
   1129 				vput(ndp->ni_dvp);
   1130 			}
   1131 			state->attempt_retry = 1;
   1132 			return (error);
   1133 		}
   1134 
   1135 		error = lookup_once(state);
   1136 		if (error) {
   1137 			ndp->ni_vp = NULL;
   1138 			/* XXX this should use namei_end() */
   1139 			if (ndp->ni_dvp) {
   1140 				vput(ndp->ni_dvp);
   1141 			}
   1142 			/*
   1143 			 * Note that if we're doing TRYEMULROOT we can
   1144 			 * retry with the normal root. Where this is
   1145 			 * currently set matches previous practice,
   1146 			 * but the previous practice didn't make much
   1147 			 * sense and somebody should sit down and
   1148 			 * figure out which cases should cause retry
   1149 			 * and which shouldn't. XXX.
   1150 			 */
   1151 			state->attempt_retry = 1;
   1152 			return (error);
   1153 		}
   1154 		// XXX ought to be able to avoid this case too
   1155 		if (state->lookup_alldone) {
   1156 			error = 0;
   1157 			/* break out of main loop */
   1158 			break;
   1159 		}
   1160 
   1161 		/*
   1162 		 * Check for symbolic link. If we've reached one,
   1163 		 * follow it, unless we aren't supposed to. Back up
   1164 		 * over any slashes that we skipped, as we will need
   1165 		 * them again.
   1166 		 */
   1167 		if (namei_atsymlink(state)) {
   1168 			ndp->ni_pathlen += state->slashes;
   1169 			ndp->ni_next -= state->slashes;
   1170 			cnp->cn_flags |= ISSYMLINK;
   1171 			if (neverfollow) {
   1172 				error = EINVAL;
   1173 			} else {
   1174 				error = namei_follow(state, inhibitmagic);
   1175 			}
   1176 			if (error) {
   1177 				KASSERT(ndp->ni_dvp != ndp->ni_vp);
   1178 				vput(ndp->ni_dvp);
   1179 				vput(ndp->ni_vp);
   1180 				ndp->ni_vp = NULL;
   1181 				return error;
   1182 			}
   1183 			cnp->cn_nameptr = ndp->ni_pnbuf;
   1184 			continue;
   1185 		}
   1186 
   1187 		/*
   1188 		 * Check for directory, if the component was
   1189 		 * followed by a series of slashes.
   1190 		 */
   1191 		if ((state->dp->v_type != VDIR) && (cnp->cn_flags & REQUIREDIR)) {
   1192 			KASSERT(state->dp != ndp->ni_dvp);
   1193 			vput(state->dp);
   1194 			ndp->ni_vp = NULL;
   1195 			/* XXX this should use namei_end() */
   1196 			if (ndp->ni_dvp) {
   1197 				vput(ndp->ni_dvp);
   1198 			}
   1199 			state->attempt_retry = 1;
   1200 			return ENOTDIR;
   1201 		}
   1202 
   1203 		/*
   1204 		 * Not a symbolic link.  If this was not the
   1205 		 * last component, then continue at the next
   1206 		 * component, else return.
   1207 		 */
   1208 		if (!(cnp->cn_flags & ISLASTCN)) {
   1209 			cnp->cn_nameptr = ndp->ni_next;
   1210 			if (ndp->ni_dvp == state->dp) {
   1211 				vrele(ndp->ni_dvp);
   1212 			} else {
   1213 				vput(ndp->ni_dvp);
   1214 			}
   1215 			ndp->ni_dvp = NULL;
   1216 			goto dirloop;
   1217 		}
   1218 
   1219     terminal:
   1220 		error = 0;
   1221 		if (state->dp == ndp->ni_erootdir) {
   1222 			/*
   1223 			 * We are about to return the emulation root.
   1224 			 * This isn't a good idea because code might
   1225 			 * repeatedly lookup ".." until the file
   1226 			 * matches that returned for "/" and loop
   1227 			 * forever.  So convert it to the real root.
   1228 			 */
   1229 			if (ndp->ni_dvp == state->dp)
   1230 				vrele(state->dp);
   1231 			else
   1232 				if (ndp->ni_dvp != NULL)
   1233 					vput(ndp->ni_dvp);
   1234 			ndp->ni_dvp = NULL;
   1235 			vput(state->dp);
   1236 			state->dp = ndp->ni_rootdir;
   1237 			vref(state->dp);
   1238 			vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
   1239 			ndp->ni_vp = state->dp;
   1240 		}
   1241 
   1242 		/*
   1243 		 * If the caller requested the parent node
   1244 		 * (i.e.  it's a CREATE, DELETE, or RENAME),
   1245 		 * and we don't have one (because this is the
   1246 		 * root directory), then we must fail.
   1247 		 */
   1248 		if (ndp->ni_dvp == NULL && cnp->cn_nameiop != LOOKUP) {
   1249 			switch (cnp->cn_nameiop) {
   1250 			    case CREATE:
   1251 				error = EEXIST;
   1252 				break;
   1253 			    case DELETE:
   1254 			    case RENAME:
   1255 				error = EBUSY;
   1256 				break;
   1257 			    default:
   1258 				KASSERT(0);
   1259 			}
   1260 			vput(state->dp);
   1261 			ndp->ni_vp = NULL;
   1262 			/* XXX this should use namei_end() */
   1263 			if (ndp->ni_dvp) {
   1264 				vput(ndp->ni_dvp);
   1265 			}
   1266 			state->attempt_retry = 1;
   1267 			return (error);
   1268 		}
   1269 
   1270 		/*
   1271 		 * Disallow directory write attempts on read-only lookups.
   1272 		 * Prefers EEXIST over EROFS for the CREATE case.
   1273 		 */
   1274 		if (state->rdonly &&
   1275 		    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
   1276 			error = EROFS;
   1277 			if (state->dp != ndp->ni_dvp) {
   1278 				vput(state->dp);
   1279 			}
   1280 			ndp->ni_vp = NULL;
   1281 			/* XXX this should use namei_end() */
   1282 			if (ndp->ni_dvp) {
   1283 				vput(ndp->ni_dvp);
   1284 			}
   1285 			state->attempt_retry = 1;
   1286 			return (error);
   1287 		}
   1288 		if ((cnp->cn_flags & LOCKLEAF) == 0) {
   1289 			VOP_UNLOCK(state->dp);
   1290 		}
   1291 
   1292 		break;
   1293 	}
   1294 
   1295 	/*
   1296 	 * Done.
   1297 	 */
   1298 
   1299 	/*
   1300 	 * If LOCKPARENT is not set, the parent directory isn't returned.
   1301 	 */
   1302 	if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp != NULL) {
   1303 		if (ndp->ni_dvp == ndp->ni_vp) {
   1304 			vrele(ndp->ni_dvp);
   1305 		} else {
   1306 			vput(ndp->ni_dvp);
   1307 		}
   1308 		ndp->ni_dvp = NULL;
   1309 	}
   1310 
   1311 	return 0;
   1312 }
   1313 
   1314 static int
   1315 namei_tryemulroot(struct namei_state *state, struct vnode *forcecwd,
   1316 	 int neverfollow, int inhibitmagic)
   1317 {
   1318 	int error;
   1319 
   1320 	struct nameidata *ndp = state->ndp;
   1321 	struct componentname *cnp = state->cnp;
   1322 	const char *savepath = NULL;
   1323 
   1324 	KASSERT(cnp == &ndp->ni_cnd);
   1325 
   1326 	if (cnp->cn_flags & TRYEMULROOT) {
   1327 		savepath = pathbuf_stringcopy_get(ndp->ni_pathbuf);
   1328 	}
   1329 
   1330     emul_retry:
   1331 	state->attempt_retry = 0;
   1332 
   1333 	error = namei_oneroot(state, forcecwd, neverfollow, inhibitmagic);
   1334 	if (error) {
   1335 		/*
   1336 		 * Once namei has started up, the existence of ni_erootdir
   1337 		 * tells us whether we're working from an emulation root.
   1338 		 * The TRYEMULROOT flag isn't necessarily authoritative.
   1339 		 */
   1340 		if (ndp->ni_erootdir != NULL && state->attempt_retry) {
   1341 			/* Retry the whole thing using the normal root */
   1342 			cnp->cn_flags &= ~TRYEMULROOT;
   1343 			state->attempt_retry = 0;
   1344 
   1345 			/* kinda gross */
   1346 			strcpy(ndp->ni_pathbuf->pb_path, savepath);
   1347 			pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
   1348 			savepath = NULL;
   1349 
   1350 			goto emul_retry;
   1351 		}
   1352 	}
   1353 	if (savepath != NULL) {
   1354 		pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
   1355 	}
   1356 	return error;
   1357 }
   1358 
   1359 int
   1360 namei(struct nameidata *ndp)
   1361 {
   1362 	struct namei_state state;
   1363 	int error;
   1364 
   1365 	namei_init(&state, ndp);
   1366 	error = namei_tryemulroot(&state, NULL,
   1367 				  0/*!neverfollow*/, 0/*!inhibitmagic*/);
   1368 	namei_cleanup(&state);
   1369 
   1370 	return error;
   1371 }
   1372 
   1373 ////////////////////////////////////////////////////////////
   1374 
   1375 /*
   1376  * Externally visible interfaces used by nfsd (bletch, yuk, XXX)
   1377  *
   1378  * The "index" version differs from the "main" version in that it's
   1379  * called from a different place in a different context. For now I
   1380  * want to be able to shuffle code in from one call site without
   1381  * affecting the other.
   1382  *
   1383  * It turns out that the "main" version was a cut and pasted copy of
   1384  * namei with a few changes; the "index" version on the other hand
   1385  * always takes a single component and is an elaborate form of calling
   1386  * VOP_LOOKUP once.
   1387  */
   1388 
   1389 int
   1390 lookup_for_nfsd(struct nameidata *ndp, struct vnode *forcecwd, int neverfollow)
   1391 {
   1392 	struct namei_state state;
   1393 	int error;
   1394 
   1395 	namei_init(&state, ndp);
   1396 	error = namei_tryemulroot(&state, forcecwd,
   1397 				  neverfollow, 1/*inhibitmagic*/);
   1398 	namei_cleanup(&state);
   1399 
   1400 	return error;
   1401 }
   1402 
   1403 static int
   1404 do_lookup_for_nfsd_index(struct namei_state *state, struct vnode *startdir)
   1405 {
   1406 	int error = 0;
   1407 
   1408 	struct componentname *cnp = state->cnp;
   1409 	struct nameidata *ndp = state->ndp;
   1410 	const char *cp;			/* pointer into pathname argument */
   1411 
   1412 	KASSERT(cnp == &ndp->ni_cnd);
   1413 
   1414 	cnp->cn_nameptr = ndp->ni_pnbuf;
   1415 	state->lookup_alldone = 0;
   1416 	state->docache = 1;
   1417 	state->rdonly = cnp->cn_flags & RDONLY;
   1418 	ndp->ni_dvp = NULL;
   1419 	cnp->cn_flags &= ~ISSYMLINK;
   1420 	state->dp = startdir;
   1421 
   1422 	cnp->cn_consume = 0;
   1423 	cp = NULL;
   1424 	cnp->cn_hash = namei_hash(cnp->cn_nameptr, &cp);
   1425 	cnp->cn_namelen = cp - cnp->cn_nameptr;
   1426 	KASSERT(cnp->cn_namelen <= NAME_MAX);
   1427 	ndp->ni_pathlen -= cnp->cn_namelen;
   1428 	ndp->ni_next = cp;
   1429 	state->slashes = 0;
   1430 	cnp->cn_flags &= ~REQUIREDIR;
   1431 	cnp->cn_flags |= MAKEENTRY|ISLASTCN;
   1432 
   1433 	if (cnp->cn_namelen == 2 &&
   1434 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
   1435 		cnp->cn_flags |= ISDOTDOT;
   1436 	else
   1437 		cnp->cn_flags &= ~ISDOTDOT;
   1438 
   1439 	error = lookup_once(state);
   1440 	if (error) {
   1441 		goto bad;
   1442 	}
   1443 	// XXX ought to be able to avoid this case too
   1444 	if (state->lookup_alldone) {
   1445 		/* this should NOT be "goto terminal;" */
   1446 		return 0;
   1447 	}
   1448 
   1449 	if ((cnp->cn_flags & LOCKLEAF) == 0) {
   1450 		VOP_UNLOCK(state->dp);
   1451 	}
   1452 	return (0);
   1453 
   1454 bad:
   1455 	ndp->ni_vp = NULL;
   1456 	return (error);
   1457 }
   1458 
   1459 int
   1460 lookup_for_nfsd_index(struct nameidata *ndp, struct vnode *startdir)
   1461 {
   1462 	struct namei_state state;
   1463 	int error;
   1464 
   1465 	/*
   1466 	 * Note: the name sent in here (is not|should not be) allowed
   1467 	 * to contain a slash.
   1468 	 */
   1469 	if (strlen(ndp->ni_pathbuf->pb_path) > NAME_MAX) {
   1470 		return ENAMETOOLONG;
   1471 	}
   1472 	if (strchr(ndp->ni_pathbuf->pb_path, '/')) {
   1473 		return EINVAL;
   1474 	}
   1475 
   1476 	ndp->ni_pathlen = strlen(ndp->ni_pathbuf->pb_path) + 1;
   1477 	ndp->ni_pnbuf = NULL;
   1478 	ndp->ni_cnd.cn_nameptr = NULL;
   1479 
   1480 	vref(startdir);
   1481 
   1482 	namei_init(&state, ndp);
   1483 	error = do_lookup_for_nfsd_index(&state, startdir);
   1484 	namei_cleanup(&state);
   1485 
   1486 	return error;
   1487 }
   1488 
   1489 ////////////////////////////////////////////////////////////
   1490 
   1491 /*
   1492  * Reacquire a path name component.
   1493  * dvp is locked on entry and exit.
   1494  * *vpp is locked on exit unless it's NULL.
   1495  */
   1496 int
   1497 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp, int dummy)
   1498 {
   1499 	int rdonly;			/* lookup read-only flag bit */
   1500 	int error = 0;
   1501 #ifdef DEBUG
   1502 	uint32_t newhash;		/* DEBUG: check name hash */
   1503 	const char *cp;			/* DEBUG: check name ptr/len */
   1504 #endif /* DEBUG */
   1505 
   1506 	(void)dummy;
   1507 
   1508 	/*
   1509 	 * Setup: break out flag bits into variables.
   1510 	 */
   1511 	rdonly = cnp->cn_flags & RDONLY;
   1512 	cnp->cn_flags &= ~ISSYMLINK;
   1513 
   1514 	/*
   1515 	 * Search a new directory.
   1516 	 *
   1517 	 * The cn_hash value is for use by vfs_cache.
   1518 	 * The last component of the filename is left accessible via
   1519 	 * cnp->cn_nameptr for callers that need the name. Callers needing
   1520 	 * the name set the SAVENAME flag. When done, they assume
   1521 	 * responsibility for freeing the pathname buffer.
   1522 	 */
   1523 #ifdef DEBUG
   1524 	cp = NULL;
   1525 	newhash = namei_hash(cnp->cn_nameptr, &cp);
   1526 	if ((uint32_t)newhash != (uint32_t)cnp->cn_hash)
   1527 		panic("relookup: bad hash");
   1528 	if (cnp->cn_namelen != cp - cnp->cn_nameptr)
   1529 		panic("relookup: bad len");
   1530 	while (*cp == '/')
   1531 		cp++;
   1532 	if (*cp != 0)
   1533 		panic("relookup: not last component");
   1534 #endif /* DEBUG */
   1535 
   1536 	/*
   1537 	 * Check for degenerate name (e.g. / or "")
   1538 	 * which is a way of talking about a directory,
   1539 	 * e.g. like "/." or ".".
   1540 	 */
   1541 	if (cnp->cn_nameptr[0] == '\0')
   1542 		panic("relookup: null name");
   1543 
   1544 	if (cnp->cn_flags & ISDOTDOT)
   1545 		panic("relookup: lookup on dot-dot");
   1546 
   1547 	/*
   1548 	 * We now have a segment name to search for, and a directory to search.
   1549 	 */
   1550 	cnp->cn_flags |= INRELOOKUP;
   1551 	error = VOP_LOOKUP(dvp, vpp, cnp);
   1552 	cnp->cn_flags &= ~INRELOOKUP;
   1553 	if ((error) != 0) {
   1554 #ifdef DIAGNOSTIC
   1555 		if (*vpp != NULL)
   1556 			panic("leaf `%s' should be empty", cnp->cn_nameptr);
   1557 #endif
   1558 		if (error != EJUSTRETURN)
   1559 			goto bad;
   1560 	}
   1561 
   1562 #ifdef DIAGNOSTIC
   1563 	/*
   1564 	 * Check for symbolic link
   1565 	 */
   1566 	if (*vpp && (*vpp)->v_type == VLNK && (cnp->cn_flags & FOLLOW))
   1567 		panic("relookup: symlink found");
   1568 #endif
   1569 
   1570 	/*
   1571 	 * Check for read-only lookups.
   1572 	 */
   1573 	if (rdonly && cnp->cn_nameiop != LOOKUP) {
   1574 		error = EROFS;
   1575 		if (*vpp) {
   1576 			vput(*vpp);
   1577 		}
   1578 		goto bad;
   1579 	}
   1580 	return (0);
   1581 
   1582 bad:
   1583 	*vpp = NULL;
   1584 	return (error);
   1585 }
   1586 
   1587 /*
   1588  * namei_simple - simple forms of namei.
   1589  *
   1590  * These are wrappers to allow the simple case callers of namei to be
   1591  * left alone while everything else changes under them.
   1592  */
   1593 
   1594 /* Flags */
   1595 struct namei_simple_flags_type {
   1596 	int dummy;
   1597 };
   1598 static const struct namei_simple_flags_type ns_nn, ns_nt, ns_fn, ns_ft;
   1599 const namei_simple_flags_t NSM_NOFOLLOW_NOEMULROOT = &ns_nn;
   1600 const namei_simple_flags_t NSM_NOFOLLOW_TRYEMULROOT = &ns_nt;
   1601 const namei_simple_flags_t NSM_FOLLOW_NOEMULROOT = &ns_fn;
   1602 const namei_simple_flags_t NSM_FOLLOW_TRYEMULROOT = &ns_ft;
   1603 
   1604 static
   1605 int
   1606 namei_simple_convert_flags(namei_simple_flags_t sflags)
   1607 {
   1608 	if (sflags == NSM_NOFOLLOW_NOEMULROOT)
   1609 		return NOFOLLOW | 0;
   1610 	if (sflags == NSM_NOFOLLOW_TRYEMULROOT)
   1611 		return NOFOLLOW | TRYEMULROOT;
   1612 	if (sflags == NSM_FOLLOW_NOEMULROOT)
   1613 		return FOLLOW | 0;
   1614 	if (sflags == NSM_FOLLOW_TRYEMULROOT)
   1615 		return FOLLOW | TRYEMULROOT;
   1616 	panic("namei_simple_convert_flags: bogus sflags\n");
   1617 	return 0;
   1618 }
   1619 
   1620 int
   1621 namei_simple_kernel(const char *path, namei_simple_flags_t sflags,
   1622 			struct vnode **vp_ret)
   1623 {
   1624 	struct nameidata nd;
   1625 	struct pathbuf *pb;
   1626 	int err;
   1627 
   1628 	pb = pathbuf_create(path);
   1629 	if (pb == NULL) {
   1630 		return ENOMEM;
   1631 	}
   1632 
   1633 	NDINIT(&nd,
   1634 		LOOKUP,
   1635 		namei_simple_convert_flags(sflags),
   1636 		pb);
   1637 	err = namei(&nd);
   1638 	if (err != 0) {
   1639 		pathbuf_destroy(pb);
   1640 		return err;
   1641 	}
   1642 	*vp_ret = nd.ni_vp;
   1643 	pathbuf_destroy(pb);
   1644 	return 0;
   1645 }
   1646 
   1647 int
   1648 namei_simple_user(const char *path, namei_simple_flags_t sflags,
   1649 			struct vnode **vp_ret)
   1650 {
   1651 	struct pathbuf *pb;
   1652 	struct nameidata nd;
   1653 	int err;
   1654 
   1655 	err = pathbuf_copyin(path, &pb);
   1656 	if (err) {
   1657 		return err;
   1658 	}
   1659 
   1660 	NDINIT(&nd,
   1661 		LOOKUP,
   1662 		namei_simple_convert_flags(sflags),
   1663 		pb);
   1664 	err = namei(&nd);
   1665 	if (err != 0) {
   1666 		pathbuf_destroy(pb);
   1667 		return err;
   1668 	}
   1669 	*vp_ret = nd.ni_vp;
   1670 	pathbuf_destroy(pb);
   1671 	return 0;
   1672 }
   1673