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