Home | History | Annotate | Line # | Download | only in kern
vfs_lookup.c revision 1.93.6.4
      1 /*	$NetBSD: vfs_lookup.c,v 1.93.6.4 2007/11/27 19:38:17 joerg 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.93.6.4 2007/11/27 19:38:17 joerg Exp $");
     41 
     42 #include "opt_systrace.h"
     43 #include "opt_magiclinks.h"
     44 
     45 #include <sys/param.h>
     46 #include <sys/systm.h>
     47 #include <sys/kernel.h>
     48 #include <sys/syslimits.h>
     49 #include <sys/time.h>
     50 #include <sys/namei.h>
     51 #include <sys/vnode.h>
     52 #include <sys/mount.h>
     53 #include <sys/errno.h>
     54 #include <sys/filedesc.h>
     55 #include <sys/hash.h>
     56 #include <sys/malloc.h>
     57 #include <sys/proc.h>
     58 #include <sys/syslog.h>
     59 #include <sys/kauth.h>
     60 #include <sys/ktrace.h>
     61 
     62 #ifdef SYSTRACE
     63 #include <sys/systrace.h>
     64 #endif
     65 
     66 #ifndef MAGICLINKS
     67 #define MAGICLINKS 0
     68 #endif
     69 
     70 struct pathname_internal {
     71 	char *pathbuf;
     72 	bool needfree;
     73 };
     74 
     75 int vfs_magiclinks = MAGICLINKS;
     76 
     77 pool_cache_t pnbuf_cache;	/* pathname buffer cache */
     78 
     79 /*
     80  * Substitute replacement text for 'magic' strings in symlinks.
     81  * Returns 0 if successful, and returns non-zero if an error
     82  * occurs.  (Currently, the only possible error is running out
     83  * of temporary pathname space.)
     84  *
     85  * Looks for "@<string>" and "@<string>/", where <string> is a
     86  * recognized 'magic' string.  Replaces the "@<string>" with the
     87  * appropriate replacement text.  (Note that in some cases the
     88  * replacement text may have zero length.)
     89  *
     90  * This would have been table driven, but the variance in
     91  * replacement strings (and replacement string lengths) made
     92  * that impractical.
     93  */
     94 #define	VNL(x)							\
     95 	(sizeof(x) - 1)
     96 
     97 #define	VO	'{'
     98 #define	VC	'}'
     99 
    100 #define	MATCH(str)						\
    101 	((termchar == '/' && i + VNL(str) == *len) ||		\
    102 	 (i + VNL(str) < *len &&				\
    103 	  cp[i + VNL(str)] == termchar)) &&			\
    104 	!strncmp((str), &cp[i], VNL(str))
    105 
    106 #define	SUBSTITUTE(m, s, sl)					\
    107 	if ((newlen + (sl)) > MAXPATHLEN)			\
    108 		return (1);					\
    109 	i += VNL(m);						\
    110 	if (termchar != '/')					\
    111 		i++;						\
    112 	memcpy(&tmp[newlen], (s), (sl));			\
    113 	newlen += (sl);						\
    114 	change = 1;						\
    115 	termchar = '/';
    116 
    117 static int
    118 symlink_magic(struct proc *p, char *cp, int *len)
    119 {
    120 	char *tmp;
    121 	int change, i, newlen;
    122 	int termchar = '/';
    123 
    124 	tmp = PNBUF_GET();
    125 	for (change = i = newlen = 0; i < *len; ) {
    126 		if (cp[i] != '@') {
    127 			tmp[newlen++] = cp[i++];
    128 			continue;
    129 		}
    130 
    131 		i++;
    132 
    133 		/* Check for @{var} syntax. */
    134 		if (cp[i] == VO) {
    135 			termchar = VC;
    136 			i++;
    137 		}
    138 
    139 		/*
    140 		 * The following checks should be ordered according
    141 		 * to frequency of use.
    142 		 */
    143 		if (MATCH("machine_arch")) {
    144 			SUBSTITUTE("machine_arch", MACHINE_ARCH,
    145 			    sizeof(MACHINE_ARCH) - 1);
    146 		} else if (MATCH("machine")) {
    147 			SUBSTITUTE("machine", MACHINE,
    148 			    sizeof(MACHINE) - 1);
    149 		} else if (MATCH("hostname")) {
    150 			SUBSTITUTE("hostname", hostname,
    151 			    hostnamelen);
    152 		} else if (MATCH("osrelease")) {
    153 			SUBSTITUTE("osrelease", osrelease,
    154 			    strlen(osrelease));
    155 		} else if (MATCH("emul")) {
    156 			SUBSTITUTE("emul", p->p_emul->e_name,
    157 			    strlen(p->p_emul->e_name));
    158 		} else if (MATCH("kernel_ident")) {
    159 			SUBSTITUTE("kernel_ident", kernel_ident,
    160 			    strlen(kernel_ident));
    161 		} else if (MATCH("domainname")) {
    162 			SUBSTITUTE("domainname", domainname,
    163 			    domainnamelen);
    164 		} else if (MATCH("ostype")) {
    165 			SUBSTITUTE("ostype", ostype,
    166 			    strlen(ostype));
    167 		} else if (MATCH("uid")) {
    168 			char uidtmp[11]; /* XXX elad */
    169 
    170 			(void)snprintf(uidtmp, sizeof(uidtmp), "%u",
    171 			    kauth_cred_geteuid(kauth_cred_get()));
    172 			SUBSTITUTE("uid", uidtmp, strlen(uidtmp));
    173 		} else {
    174 			tmp[newlen++] = '@';
    175 			if (termchar == VC)
    176 				tmp[newlen++] = VO;
    177 		}
    178 	}
    179 
    180 	if (change) {
    181 		memcpy(cp, tmp, newlen);
    182 		*len = newlen;
    183 	}
    184 	PNBUF_PUT(tmp);
    185 
    186 	return (0);
    187 }
    188 
    189 #undef VNL
    190 #undef VO
    191 #undef VC
    192 #undef MATCH
    193 #undef SUBSTITUTE
    194 
    195 /*
    196  * Convert a pathname into a pointer to a locked vnode.
    197  *
    198  * The FOLLOW flag is set when symbolic links are to be followed
    199  * when they occur at the end of the name translation process.
    200  * Symbolic links are always followed for all other pathname
    201  * components other than the last.
    202  *
    203  * The segflg defines whether the name is to be copied from user
    204  * space or kernel space.
    205  *
    206  * Overall outline of namei:
    207  *
    208  *	copy in name
    209  *	get starting directory
    210  *	while (!done && !error) {
    211  *		call lookup to search path.
    212  *		if symbolic link, massage name in buffer and continue
    213  *	}
    214  */
    215 int
    216 namei(struct nameidata *ndp)
    217 {
    218 	struct cwdinfo *cwdi;		/* pointer to cwd state */
    219 	char *cp;			/* pointer into pathname argument */
    220 	struct vnode *dp;		/* the directory we are searching */
    221 	struct iovec aiov;		/* uio for reading symbolic links */
    222 	struct uio auio;
    223 	int error, linklen;
    224 	struct componentname *cnp = &ndp->ni_cnd;
    225 
    226 #ifdef DIAGNOSTIC
    227 	if (!cnp->cn_cred || !cnp->cn_lwp)
    228 		panic("namei: bad cred/proc");
    229 	if (cnp->cn_nameiop & (~OPMASK))
    230 		panic("namei: nameiop contaminated with flags");
    231 	if (cnp->cn_flags & OPMASK)
    232 		panic("namei: flags contaminated with nameiops");
    233 #endif
    234 
    235 	/*
    236 	 * Get a buffer for the name to be translated, and copy the
    237 	 * name into the buffer.
    238 	 */
    239 	if ((cnp->cn_flags & HASBUF) == 0)
    240 		cnp->cn_pnbuf = PNBUF_GET();
    241     emul_retry:
    242 	if (ndp->ni_segflg == UIO_SYSSPACE)
    243 		error = copystr(ndp->ni_dirp, cnp->cn_pnbuf,
    244 			    MAXPATHLEN, &ndp->ni_pathlen);
    245 	else
    246 		error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf,
    247 			    MAXPATHLEN, &ndp->ni_pathlen);
    248 
    249 	/*
    250 	 * POSIX.1 requirement: "" is not a valid file name.
    251 	 */
    252 	if (!error && ndp->ni_pathlen == 1)
    253 		error = ENOENT;
    254 
    255 	if (error) {
    256 		PNBUF_PUT(cnp->cn_pnbuf);
    257 		ndp->ni_vp = NULL;
    258 		return (error);
    259 	}
    260 	ndp->ni_loopcnt = 0;
    261 
    262 	/*
    263 	 * Get root directory for the translation.
    264 	 */
    265 	cwdi = cnp->cn_lwp->l_proc->p_cwdi;
    266 	rw_enter(&cwdi->cwdi_lock, RW_READER);
    267 	dp = cwdi->cwdi_rdir;
    268 	if (dp == NULL)
    269 		dp = rootvnode;
    270 	ndp->ni_rootdir = dp;
    271 
    272 	/*
    273 	 * Check if starting from root directory or current directory.
    274 	 */
    275 	if (cnp->cn_pnbuf[0] == '/') {
    276 		if (cnp->cn_flags & TRYEMULROOT) {
    277 			if (cnp->cn_flags & EMULROOTSET) {
    278 				/* Called from (eg) emul_find_interp() */
    279 				dp = ndp->ni_erootdir;
    280 			} else {
    281 				if (cwdi->cwdi_edir == NULL
    282 				    || (cnp->cn_pnbuf[1] == '.'
    283 					   && cnp->cn_pnbuf[2] == '.'
    284 					   && cnp->cn_pnbuf[3] == '/')) {
    285 					ndp->ni_erootdir = NULL;
    286 				} else {
    287 					dp = cwdi->cwdi_edir;
    288 					ndp->ni_erootdir = dp;
    289 				}
    290 			}
    291 		} else
    292 			ndp->ni_erootdir = NULL;
    293 	} else {
    294 		dp = cwdi->cwdi_cdir;
    295 		ndp->ni_erootdir = NULL;
    296 	}
    297 	VREF(dp);
    298 	rw_exit(&cwdi->cwdi_lock);
    299 
    300 	if (ktrpoint(KTR_NAMEI)) {
    301 		if (ndp->ni_erootdir != NULL) {
    302 			/*
    303 			 * To make any sense, the trace entry need to have the
    304 			 * text of the emulation path prepended.
    305 			 * Usually we can get this from the current process,
    306 			 * but when called from emul_find_interp() it is only
    307 			 * in the exec_package - so we get it passed in ni_next
    308 			 * (this is a hack).
    309 			 */
    310 			const char *emul_path;
    311 			if (cnp->cn_flags & EMULROOTSET)
    312 				emul_path = ndp->ni_next;
    313 			else
    314 				emul_path = cnp->cn_lwp->l_proc->p_emul->e_path;
    315 			ktrnamei2(emul_path, strlen(emul_path),
    316 			    cnp->cn_pnbuf, ndp->ni_pathlen);
    317 		} else
    318 			ktrnamei(cnp->cn_pnbuf, ndp->ni_pathlen);
    319 	}
    320 
    321 #ifdef SYSTRACE
    322 	if (ISSET(cnp->cn_lwp->l_proc->p_flag, PK_SYSTRACE))
    323 		systrace_namei(ndp);
    324 #endif
    325 
    326 	vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    327 	/* Loop through symbolic links */
    328 	for (;;) {
    329 		if (!dp->v_mount) {
    330 			/* Give up if the directory is no longer mounted */
    331 			vput(dp);
    332 			PNBUF_PUT(cnp->cn_pnbuf);
    333 			return (ENOENT);
    334 		}
    335 		cnp->cn_nameptr = cnp->cn_pnbuf;
    336 		ndp->ni_startdir = dp;
    337 		error = lookup(ndp);
    338 		if (error != 0) {
    339 			if (ndp->ni_dvp) {
    340 				vput(ndp->ni_dvp);
    341 			}
    342 			if (ndp->ni_erootdir != NULL) {
    343 				/* Retry the whole thing from the normal root */
    344 				cnp->cn_flags &= ~TRYEMULROOT;
    345 				goto emul_retry;
    346 			}
    347 			PNBUF_PUT(cnp->cn_pnbuf);
    348 			return (error);
    349 		}
    350 
    351 		/*
    352 		 * Check for symbolic link
    353 		 */
    354 		if ((cnp->cn_flags & ISSYMLINK) == 0) {
    355 			if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp) {
    356 				if (ndp->ni_dvp == ndp->ni_vp) {
    357 					vrele(ndp->ni_dvp);
    358 				} else {
    359 					vput(ndp->ni_dvp);
    360 				}
    361 			}
    362 			if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0)
    363 				PNBUF_PUT(cnp->cn_pnbuf);
    364 			else
    365 				cnp->cn_flags |= HASBUF;
    366 			return (0);
    367 		}
    368 
    369 		if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
    370 			error = ELOOP;
    371 			break;
    372 		}
    373 		if (ndp->ni_vp->v_mount->mnt_flag & MNT_SYMPERM) {
    374 			error = VOP_ACCESS(ndp->ni_vp, VEXEC, cnp->cn_cred);
    375 			if (error != 0)
    376 				break;
    377 		}
    378 		if (ndp->ni_pathlen > 1)
    379 			cp = PNBUF_GET();
    380 		else
    381 			cp = cnp->cn_pnbuf;
    382 		aiov.iov_base = cp;
    383 		aiov.iov_len = MAXPATHLEN;
    384 		auio.uio_iov = &aiov;
    385 		auio.uio_iovcnt = 1;
    386 		auio.uio_offset = 0;
    387 		auio.uio_rw = UIO_READ;
    388 		auio.uio_resid = MAXPATHLEN;
    389 		UIO_SETUP_SYSSPACE(&auio);
    390 		error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
    391 		if (error) {
    392 badlink:
    393 			if (ndp->ni_pathlen > 1)
    394 				PNBUF_PUT(cp);
    395 			break;
    396 		}
    397 		linklen = MAXPATHLEN - auio.uio_resid;
    398 		if (linklen == 0) {
    399 			error = ENOENT;
    400 			goto badlink;
    401 		}
    402 
    403 		/*
    404 		 * Do symlink substitution, if appropriate, and
    405 		 * check length for potential overflow.
    406 		 */
    407 		if ((vfs_magiclinks &&
    408 		     symlink_magic(cnp->cn_lwp->l_proc, cp, &linklen)) ||
    409 		    (linklen + ndp->ni_pathlen >= MAXPATHLEN)) {
    410 			error = ENAMETOOLONG;
    411 			goto badlink;
    412 		}
    413 		if (ndp->ni_pathlen > 1) {
    414 			memcpy(cp + linklen, ndp->ni_next, ndp->ni_pathlen);
    415 			PNBUF_PUT(cnp->cn_pnbuf);
    416 			cnp->cn_pnbuf = cp;
    417 		} else
    418 			cnp->cn_pnbuf[linklen] = '\0';
    419 		ndp->ni_pathlen += linklen;
    420 		vput(ndp->ni_vp);
    421 		dp = ndp->ni_dvp;
    422 
    423 		/*
    424 		 * Check if root directory should replace current directory.
    425 		 */
    426 		if (cnp->cn_pnbuf[0] == '/') {
    427 			vput(dp);
    428 			/* Keep absolute symbolic links inside emulation root */
    429 			dp = ndp->ni_erootdir;
    430 			if (dp == NULL || (cnp->cn_pnbuf[1] == '.'
    431 			    && cnp->cn_pnbuf[2] == '.'
    432 			    && cnp->cn_pnbuf[3] == '/')) {
    433 				ndp->ni_erootdir = NULL;
    434 				dp = ndp->ni_rootdir;
    435 			}
    436 			VREF(dp);
    437 			vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    438 		}
    439 	}
    440 	/* Failed to process a symbolic link */
    441 	KASSERT(ndp->ni_dvp != ndp->ni_vp);
    442 	vput(ndp->ni_dvp);
    443 	vput(ndp->ni_vp);
    444 	ndp->ni_vp = NULL;
    445 	PNBUF_PUT(cnp->cn_pnbuf);
    446 	return (error);
    447 }
    448 
    449 /*
    450  * Determine the namei hash (for cn_hash) for name.
    451  * If *ep != NULL, hash from name to ep-1.
    452  * If *ep == NULL, hash from name until the first NUL or '/', and
    453  * return the location of this termination character in *ep.
    454  *
    455  * This function returns an equivalent hash to the MI hash32_strn().
    456  * The latter isn't used because in the *ep == NULL case, determining
    457  * the length of the string to the first NUL or `/' and then calling
    458  * hash32_strn() involves unnecessary double-handling of the data.
    459  */
    460 uint32_t
    461 namei_hash(const char *name, const char **ep)
    462 {
    463 	uint32_t	hash;
    464 
    465 	hash = HASH32_STR_INIT;
    466 	if (*ep != NULL) {
    467 		for (; name < *ep; name++)
    468 			hash = hash * 33 + *(const uint8_t *)name;
    469 	} else {
    470 		for (; *name != '\0' && *name != '/'; name++)
    471 			hash = hash * 33 + *(const uint8_t *)name;
    472 		*ep = name;
    473 	}
    474 	return (hash + (hash >> 5));
    475 }
    476 
    477 /*
    478  * Search a pathname.
    479  * This is a very central and rather complicated routine.
    480  *
    481  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
    482  * The starting directory is taken from ni_startdir. The pathname is
    483  * descended until done, or a symbolic link is encountered. The variable
    484  * ni_more is clear if the path is completed; it is set to one if a
    485  * symbolic link needing interpretation is encountered.
    486  *
    487  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
    488  * whether the name is to be looked up, created, renamed, or deleted.
    489  * When CREATE, RENAME, or DELETE is specified, information usable in
    490  * creating, renaming, or deleting a directory entry may be calculated.
    491  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
    492  * locked.  Otherwise the parent directory is not returned. If the target
    493  * of the pathname exists and LOCKLEAF is or'ed into the flag the target
    494  * is returned locked, otherwise it is returned unlocked.  When creating
    495  * or renaming and LOCKPARENT is specified, the target may not be ".".
    496  * When deleting and LOCKPARENT is specified, the target may be ".".
    497  *
    498  * Overall outline of lookup:
    499  *
    500  * dirloop:
    501  *	identify next component of name at ndp->ni_ptr
    502  *	handle degenerate case where name is null string
    503  *	if .. and crossing mount points and on mounted filesys, find parent
    504  *	call VOP_LOOKUP routine for next component name
    505  *	    directory vnode returned in ni_dvp, locked.
    506  *	    component vnode returned in ni_vp (if it exists), locked.
    507  *	if result vnode is mounted on and crossing mount points,
    508  *	    find mounted on vnode
    509  *	if more components of name, do next level at dirloop
    510  *	return the answer in ni_vp, locked if LOCKLEAF set
    511  *	    if LOCKPARENT set, return locked parent in ni_dvp
    512  */
    513 int
    514 lookup(struct nameidata *ndp)
    515 {
    516 	const char *cp;			/* pointer into pathname argument */
    517 	struct vnode *dp = 0;		/* the directory we are searching */
    518 	struct vnode *tdp;		/* saved dp */
    519 	struct mount *mp;		/* mount table entry */
    520 	int docache;			/* == 0 do not cache last component */
    521 	int rdonly;			/* lookup read-only flag bit */
    522 	int error = 0;
    523 	int slashes;
    524 	struct componentname *cnp = &ndp->ni_cnd;
    525 	struct lwp *l = cnp->cn_lwp;
    526 
    527 	/*
    528 	 * Setup: break out flag bits into variables.
    529 	 */
    530 	docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
    531 	if (cnp->cn_nameiop == DELETE)
    532 		docache = 0;
    533 	rdonly = cnp->cn_flags & RDONLY;
    534 	ndp->ni_dvp = NULL;
    535 	cnp->cn_flags &= ~ISSYMLINK;
    536 	dp = ndp->ni_startdir;
    537 	ndp->ni_startdir = NULLVP;
    538 
    539 	/*
    540 	 * If we have a leading string of slashes, remove them, and just make
    541 	 * sure the current node is a directory.
    542 	 */
    543 	cp = cnp->cn_nameptr;
    544 	if (*cp == '/') {
    545 		do {
    546 			cp++;
    547 		} while (*cp == '/');
    548 		ndp->ni_pathlen -= cp - cnp->cn_nameptr;
    549 		cnp->cn_nameptr = cp;
    550 
    551 		if (dp->v_type != VDIR) {
    552 			error = ENOTDIR;
    553 			vput(dp);
    554 			goto bad;
    555 		}
    556 
    557 		/*
    558 		 * If we've exhausted the path name, then just return the
    559 		 * current node.
    560 		 */
    561 		if (cnp->cn_nameptr[0] == '\0') {
    562 			ndp->ni_vp = dp;
    563 			cnp->cn_flags |= ISLASTCN;
    564 			goto terminal;
    565 		}
    566 	}
    567 
    568 dirloop:
    569 	/*
    570 	 * Search a new directory.
    571 	 *
    572 	 * The cn_hash value is for use by vfs_cache.
    573 	 * The last component of the filename is left accessible via
    574 	 * cnp->cn_nameptr for callers that need the name. Callers needing
    575 	 * the name set the SAVENAME flag. When done, they assume
    576 	 * responsibility for freeing the pathname buffer.
    577 	 *
    578 	 * At this point, our only vnode state is that "dp" is held and locked.
    579 	 */
    580 	cnp->cn_consume = 0;
    581 	cp = NULL;
    582 	cnp->cn_hash = namei_hash(cnp->cn_nameptr, &cp);
    583 	cnp->cn_namelen = cp - cnp->cn_nameptr;
    584 	if (cnp->cn_namelen > NAME_MAX) {
    585 		vput(dp);
    586 		error = ENAMETOOLONG;
    587 		ndp->ni_dvp = NULL;
    588 		goto bad;
    589 	}
    590 #ifdef NAMEI_DIAGNOSTIC
    591 	{ char c = *cp;
    592 	*(char *)cp = '\0';
    593 	printf("{%s}: ", cnp->cn_nameptr);
    594 	*(char *)cp = c; }
    595 #endif /* NAMEI_DIAGNOSTIC */
    596 	ndp->ni_pathlen -= cnp->cn_namelen;
    597 	ndp->ni_next = cp;
    598 	/*
    599 	 * If this component is followed by a slash, then move the pointer to
    600 	 * the next component forward, and remember that this component must be
    601 	 * a directory.
    602 	 */
    603 	if (*cp == '/') {
    604 		do {
    605 			cp++;
    606 		} while (*cp == '/');
    607 		slashes = cp - ndp->ni_next;
    608 		ndp->ni_pathlen -= slashes;
    609 		ndp->ni_next = cp;
    610 		cnp->cn_flags |= REQUIREDIR;
    611 	} else {
    612 		slashes = 0;
    613 		cnp->cn_flags &= ~REQUIREDIR;
    614 	}
    615 	/*
    616 	 * We do special processing on the last component, whether or not it's
    617 	 * a directory.  Cache all intervening lookups, but not the final one.
    618 	 */
    619 	if (*cp == '\0') {
    620 		if (docache)
    621 			cnp->cn_flags |= MAKEENTRY;
    622 		else
    623 			cnp->cn_flags &= ~MAKEENTRY;
    624 		cnp->cn_flags |= ISLASTCN;
    625 	} else {
    626 		cnp->cn_flags |= MAKEENTRY;
    627 		cnp->cn_flags &= ~ISLASTCN;
    628 	}
    629 	if (cnp->cn_namelen == 2 &&
    630 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
    631 		cnp->cn_flags |= ISDOTDOT;
    632 	else
    633 		cnp->cn_flags &= ~ISDOTDOT;
    634 
    635 	/*
    636 	 * Handle "..": two special cases.
    637 	 * 1. If at root directory (e.g. after chroot)
    638 	 *    or at absolute root directory
    639 	 *    then ignore it so can't get out.
    640 	 * 1a. If at the root of the emulation filesystem go to the real
    641 	 *    root. So "/../<path>" is always absolute.
    642 	 * 1b. If we have somehow gotten out of a jail, warn
    643 	 *    and also ignore it so we can't get farther out.
    644 	 * 2. If this vnode is the root of a mounted
    645 	 *    filesystem, then replace it with the
    646 	 *    vnode which was mounted on so we take the
    647 	 *    .. in the other file system.
    648 	 */
    649 	if (cnp->cn_flags & ISDOTDOT) {
    650 		struct proc *p = l->l_proc;
    651 
    652 		for (;;) {
    653 			if (dp == ndp->ni_rootdir || dp == rootvnode) {
    654 				ndp->ni_dvp = dp;
    655 				ndp->ni_vp = dp;
    656 				VREF(dp);
    657 				goto nextname;
    658 			}
    659 			if (ndp->ni_rootdir != rootvnode) {
    660 				int retval;
    661 
    662 				VOP_UNLOCK(dp, 0);
    663 				retval = vn_isunder(dp, ndp->ni_rootdir, l);
    664 				vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    665 				if (!retval) {
    666 				    /* Oops! We got out of jail! */
    667 				    log(LOG_WARNING,
    668 					"chrooted pid %d uid %d (%s) "
    669 					"detected outside of its chroot\n",
    670 					p->p_pid, kauth_cred_geteuid(l->l_cred),
    671 					p->p_comm);
    672 				    /* Put us at the jail root. */
    673 				    vput(dp);
    674 				    dp = ndp->ni_rootdir;
    675 				    ndp->ni_dvp = dp;
    676 				    ndp->ni_vp = dp;
    677 				    VREF(dp);
    678 				    VREF(dp);
    679 				    vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    680 				    goto nextname;
    681 				}
    682 			}
    683 			if ((dp->v_vflag & VV_ROOT) == 0 ||
    684 			    (cnp->cn_flags & NOCROSSMOUNT))
    685 				break;
    686 			tdp = dp;
    687 			dp = dp->v_mount->mnt_vnodecovered;
    688 			vput(tdp);
    689 			VREF(dp);
    690 			vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    691 		}
    692 	}
    693 
    694 	/*
    695 	 * We now have a segment name to search for, and a directory to search.
    696 	 * Again, our only vnode state is that "dp" is held and locked.
    697 	 */
    698 unionlookup:
    699 	ndp->ni_dvp = dp;
    700 	ndp->ni_vp = NULL;
    701 	error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp);
    702 	if (error != 0) {
    703 #ifdef DIAGNOSTIC
    704 		if (ndp->ni_vp != NULL)
    705 			panic("leaf `%s' should be empty", cnp->cn_nameptr);
    706 #endif /* DIAGNOSTIC */
    707 #ifdef NAMEI_DIAGNOSTIC
    708 		printf("not found\n");
    709 #endif /* NAMEI_DIAGNOSTIC */
    710 		if ((error == ENOENT) &&
    711 		    (dp->v_vflag & VV_ROOT) &&
    712 		    (dp->v_mount->mnt_flag & MNT_UNION)) {
    713 			tdp = dp;
    714 			dp = dp->v_mount->mnt_vnodecovered;
    715 			vput(tdp);
    716 			VREF(dp);
    717 			vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    718 			goto unionlookup;
    719 		}
    720 
    721 		if (error != EJUSTRETURN)
    722 			goto bad;
    723 
    724 		/*
    725 		 * If this was not the last component, or there were trailing
    726 		 * slashes, and we are not going to create a directory,
    727 		 * then the name must exist.
    728 		 */
    729 		if ((cnp->cn_flags & (REQUIREDIR | CREATEDIR)) == REQUIREDIR) {
    730 			error = ENOENT;
    731 			goto bad;
    732 		}
    733 
    734 		/*
    735 		 * If creating and at end of pathname, then can consider
    736 		 * allowing file to be created.
    737 		 */
    738 		if (rdonly) {
    739 			error = EROFS;
    740 			goto bad;
    741 		}
    742 
    743 		/*
    744 		 * We return with ni_vp NULL to indicate that the entry
    745 		 * doesn't currently exist, leaving a pointer to the
    746 		 * (possibly locked) directory vnode in ndp->ni_dvp.
    747 		 */
    748 		if (cnp->cn_flags & SAVESTART) {
    749 			ndp->ni_startdir = ndp->ni_dvp;
    750 			VREF(ndp->ni_startdir);
    751 		}
    752 		return (0);
    753 	}
    754 #ifdef NAMEI_DIAGNOSTIC
    755 	printf("found\n");
    756 #endif /* NAMEI_DIAGNOSTIC */
    757 
    758 	/*
    759 	 * Take into account any additional components consumed by the
    760 	 * underlying filesystem.  This will include any trailing slashes after
    761 	 * the last component consumed.
    762 	 */
    763 	if (cnp->cn_consume > 0) {
    764 		ndp->ni_pathlen -= cnp->cn_consume - slashes;
    765 		ndp->ni_next += cnp->cn_consume - slashes;
    766 		cnp->cn_consume = 0;
    767 		if (ndp->ni_next[0] == '\0')
    768 			cnp->cn_flags |= ISLASTCN;
    769 	}
    770 
    771 	dp = ndp->ni_vp;
    772 
    773 	/*
    774 	 * "dp" and "ndp->ni_dvp" are both locked and held,
    775 	 * and may be the same vnode.
    776 	 */
    777 
    778 	/*
    779 	 * Check to see if the vnode has been mounted on;
    780 	 * if so find the root of the mounted file system.
    781 	 */
    782 	while (dp->v_type == VDIR && (mp = dp->v_mountedhere) &&
    783 	       (cnp->cn_flags & NOCROSSMOUNT) == 0) {
    784 		if (vfs_busy(mp, 0, 0))
    785 			continue;
    786 
    787 		KASSERT(ndp->ni_dvp != dp);
    788 		VOP_UNLOCK(ndp->ni_dvp, 0);
    789 		vput(dp);
    790 		error = VFS_ROOT(mp, &tdp);
    791 		vfs_unbusy(mp);
    792 		if (error) {
    793 			vn_lock(ndp->ni_dvp, LK_EXCLUSIVE | LK_RETRY);
    794 			goto bad;
    795 		}
    796 		VOP_UNLOCK(tdp, 0);
    797 		ndp->ni_vp = dp = tdp;
    798 		vn_lock(ndp->ni_dvp, LK_EXCLUSIVE | LK_RETRY);
    799 		vn_lock(ndp->ni_vp, LK_EXCLUSIVE | LK_RETRY);
    800 	}
    801 
    802 	/*
    803 	 * Check for symbolic link.  Back up over any slashes that we skipped,
    804 	 * as we will need them again.
    805 	 */
    806 	if ((dp->v_type == VLNK) && (cnp->cn_flags & (FOLLOW|REQUIREDIR))) {
    807 		ndp->ni_pathlen += slashes;
    808 		ndp->ni_next -= slashes;
    809 		cnp->cn_flags |= ISSYMLINK;
    810 		return (0);
    811 	}
    812 
    813 	/*
    814 	 * Check for directory, if the component was followed by a series of
    815 	 * slashes.
    816 	 */
    817 	if ((dp->v_type != VDIR) && (cnp->cn_flags & REQUIREDIR)) {
    818 		error = ENOTDIR;
    819 		KASSERT(dp != ndp->ni_dvp);
    820 		vput(dp);
    821 		goto bad;
    822 	}
    823 
    824 nextname:
    825 
    826 	/*
    827 	 * Not a symbolic link.  If this was not the last component, then
    828 	 * continue at the next component, else return.
    829 	 */
    830 	if (!(cnp->cn_flags & ISLASTCN)) {
    831 		cnp->cn_nameptr = ndp->ni_next;
    832 		if (ndp->ni_dvp == dp) {
    833 			vrele(ndp->ni_dvp);
    834 		} else {
    835 			vput(ndp->ni_dvp);
    836 		}
    837 		goto dirloop;
    838 	}
    839 
    840 terminal:
    841 	if (dp == ndp->ni_erootdir) {
    842 		/*
    843 		 * We are about to return the emulation root.
    844 		 * This isn't a good idea because code might repeatedly
    845 		 * lookup ".." until the file matches that returned
    846 		 * for "/" and loop forever.
    847 		 * So convert it to the real root.
    848 		 */
    849 		if (ndp->ni_dvp == dp)
    850 			vrele(dp);
    851 		else
    852 			if (ndp->ni_dvp != NULL)
    853 				vput(ndp->ni_dvp);
    854 		ndp->ni_dvp = NULL;
    855 		vput(dp);
    856 		dp = ndp->ni_rootdir;
    857 		VREF(dp);
    858 		vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    859 		ndp->ni_vp = dp;
    860 	}
    861 
    862 	/*
    863 	 * If the caller requested the parent node (i.e.
    864 	 * it's a CREATE, DELETE, or RENAME), and we don't have one
    865 	 * (because this is the root directory), then we must fail.
    866 	 */
    867 	if (ndp->ni_dvp == NULL && cnp->cn_nameiop != LOOKUP) {
    868 		switch (cnp->cn_nameiop) {
    869 		case CREATE:
    870 			error = EEXIST;
    871 			break;
    872 		case DELETE:
    873 		case RENAME:
    874 			error = EBUSY;
    875 			break;
    876 		default:
    877 			KASSERT(0);
    878 		}
    879 		vput(dp);
    880 		goto bad;
    881 	}
    882 
    883 	/*
    884 	 * Disallow directory write attempts on read-only lookups.
    885 	 * Prefers EEXIST over EROFS for the CREATE case.
    886 	 */
    887 	if (rdonly &&
    888 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
    889 		error = EROFS;
    890 		if (dp != ndp->ni_dvp) {
    891 			vput(dp);
    892 		}
    893 		goto bad;
    894 	}
    895 	if (ndp->ni_dvp != NULL) {
    896 		if (cnp->cn_flags & SAVESTART) {
    897 			ndp->ni_startdir = ndp->ni_dvp;
    898 			VREF(ndp->ni_startdir);
    899 		}
    900 	}
    901 	if ((cnp->cn_flags & LOCKLEAF) == 0) {
    902 		VOP_UNLOCK(dp, 0);
    903 	}
    904 	return (0);
    905 
    906 bad:
    907 	ndp->ni_vp = NULL;
    908 	return (error);
    909 }
    910 
    911 /*
    912  * Reacquire a path name component.
    913  * dvp is locked on entry and exit.
    914  * *vpp is locked on exit unless it's NULL.
    915  */
    916 int
    917 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
    918 {
    919 	int rdonly;			/* lookup read-only flag bit */
    920 	int error = 0;
    921 #ifdef DEBUG
    922 	uint32_t newhash;		/* DEBUG: check name hash */
    923 	const char *cp;			/* DEBUG: check name ptr/len */
    924 #endif /* DEBUG */
    925 
    926 	/*
    927 	 * Setup: break out flag bits into variables.
    928 	 */
    929 	rdonly = cnp->cn_flags & RDONLY;
    930 	cnp->cn_flags &= ~ISSYMLINK;
    931 
    932 	/*
    933 	 * Search a new directory.
    934 	 *
    935 	 * The cn_hash value is for use by vfs_cache.
    936 	 * The last component of the filename is left accessible via
    937 	 * cnp->cn_nameptr for callers that need the name. Callers needing
    938 	 * the name set the SAVENAME flag. When done, they assume
    939 	 * responsibility for freeing the pathname buffer.
    940 	 */
    941 #ifdef DEBUG
    942 	cp = NULL;
    943 	newhash = namei_hash(cnp->cn_nameptr, &cp);
    944 	if ((uint32_t)newhash != (uint32_t)cnp->cn_hash)
    945 		panic("relookup: bad hash");
    946 	if (cnp->cn_namelen != cp - cnp->cn_nameptr)
    947 		panic("relookup: bad len");
    948 	while (*cp == '/')
    949 		cp++;
    950 	if (*cp != 0)
    951 		panic("relookup: not last component");
    952 #endif /* DEBUG */
    953 
    954 	/*
    955 	 * Check for degenerate name (e.g. / or "")
    956 	 * which is a way of talking about a directory,
    957 	 * e.g. like "/." or ".".
    958 	 */
    959 	if (cnp->cn_nameptr[0] == '\0')
    960 		panic("relookup: null name");
    961 
    962 	if (cnp->cn_flags & ISDOTDOT)
    963 		panic("relookup: lookup on dot-dot");
    964 
    965 	/*
    966 	 * We now have a segment name to search for, and a directory to search.
    967 	 */
    968 	if ((error = VOP_LOOKUP(dvp, vpp, cnp)) != 0) {
    969 #ifdef DIAGNOSTIC
    970 		if (*vpp != NULL)
    971 			panic("leaf `%s' should be empty", cnp->cn_nameptr);
    972 #endif
    973 		if (error != EJUSTRETURN)
    974 			goto bad;
    975 	}
    976 
    977 #ifdef DIAGNOSTIC
    978 	/*
    979 	 * Check for symbolic link
    980 	 */
    981 	if (*vpp && (*vpp)->v_type == VLNK && (cnp->cn_flags & FOLLOW))
    982 		panic("relookup: symlink found");
    983 #endif
    984 
    985 	/*
    986 	 * Check for read-only lookups.
    987 	 */
    988 	if (rdonly && cnp->cn_nameiop != LOOKUP) {
    989 		error = EROFS;
    990 		if (*vpp) {
    991 			vput(*vpp);
    992 		}
    993 		goto bad;
    994 	}
    995 	if (cnp->cn_flags & SAVESTART)
    996 		VREF(dvp);
    997 	return (0);
    998 
    999 bad:
   1000 	*vpp = NULL;
   1001 	return (error);
   1002 }
   1003