Home | History | Annotate | Line # | Download | only in kern
vfs_lookup.c revision 1.72.2.1
      1 /*	$NetBSD: vfs_lookup.c,v 1.72.2.1 2007/01/03 13:59:32 tron 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.72.2.1 2007/01/03 13:59:32 tron 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 	boolean_t 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 			return (error);
    218 		}
    219 		(*path)->needfree = TRUE;
    220 	} else {
    221 		(*path)->pathbuf = __UNCONST(dirp);
    222 		(*path)->needfree = FALSE;
    223 	}
    224 
    225 	return (0);
    226 }
    227 
    228 const char *
    229 pathname_path(pathname_t path)
    230 {
    231 	KASSERT(path != NULL);
    232 	return (path->pathbuf);
    233 }
    234 
    235 void
    236 pathname_put(pathname_t path)
    237 {
    238 	if (path != NULL) {
    239 		if (path->pathbuf != NULL && path->needfree)
    240 			PNBUF_PUT(path->pathbuf);
    241 		free(path, M_TEMP);
    242 	}
    243 }
    244 
    245 /*
    246  * Convert a pathname into a pointer to a locked vnode.
    247  *
    248  * The FOLLOW flag is set when symbolic links are to be followed
    249  * when they occur at the end of the name translation process.
    250  * Symbolic links are always followed for all other pathname
    251  * components other than the last.
    252  *
    253  * The segflg defines whether the name is to be copied from user
    254  * space or kernel space.
    255  *
    256  * Overall outline of namei:
    257  *
    258  *	copy in name
    259  *	get starting directory
    260  *	while (!done && !error) {
    261  *		call lookup to search path.
    262  *		if symbolic link, massage name in buffer and continue
    263  *	}
    264  */
    265 int
    266 namei(struct nameidata *ndp)
    267 {
    268 	struct cwdinfo *cwdi;		/* pointer to cwd state */
    269 	char *cp;			/* pointer into pathname argument */
    270 	struct vnode *dp;		/* the directory we are searching */
    271 	struct iovec aiov;		/* uio for reading symbolic links */
    272 	struct uio auio;
    273 	int error, linklen;
    274 	struct componentname *cnp = &ndp->ni_cnd;
    275 
    276 #ifdef DIAGNOSTIC
    277 	if (!cnp->cn_cred || !cnp->cn_lwp)
    278 		panic("namei: bad cred/proc");
    279 	if (cnp->cn_nameiop & (~OPMASK))
    280 		panic("namei: nameiop contaminated with flags");
    281 	if (cnp->cn_flags & OPMASK)
    282 		panic("namei: flags contaminated with nameiops");
    283 #endif
    284 	cwdi = cnp->cn_lwp->l_proc->p_cwdi;
    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 	if (ndp->ni_segflg == UIO_SYSSPACE)
    293 		error = copystr(ndp->ni_dirp, cnp->cn_pnbuf,
    294 			    MAXPATHLEN, &ndp->ni_pathlen);
    295 	else
    296 		error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf,
    297 			    MAXPATHLEN, &ndp->ni_pathlen);
    298 
    299 	/*
    300 	 * POSIX.1 requirement: "" is not a valid file name.
    301 	 */
    302 	if (!error && ndp->ni_pathlen == 1)
    303 		error = ENOENT;
    304 
    305 	if (error) {
    306 		PNBUF_PUT(cnp->cn_pnbuf);
    307 		ndp->ni_vp = NULL;
    308 		return (error);
    309 	}
    310 	ndp->ni_loopcnt = 0;
    311 
    312 #ifdef KTRACE
    313 	if (KTRPOINT(cnp->cn_lwp->l_proc, KTR_NAMEI))
    314 		ktrnamei(cnp->cn_lwp, cnp->cn_pnbuf);
    315 #endif
    316 #ifdef SYSTRACE
    317 	if (ISSET(cnp->cn_lwp->l_proc->p_flag, P_SYSTRACE))
    318 		systrace_namei(ndp);
    319 #endif
    320 
    321 	/*
    322 	 * Get starting point for the translation.
    323 	 */
    324 	if ((ndp->ni_rootdir = cwdi->cwdi_rdir) == NULL)
    325 		ndp->ni_rootdir = rootvnode;
    326 	/*
    327 	 * Check if starting from root directory or current directory.
    328 	 */
    329 	if (cnp->cn_pnbuf[0] == '/') {
    330 		dp = ndp->ni_rootdir;
    331 		VREF(dp);
    332 	} else {
    333 		dp = cwdi->cwdi_cdir;
    334 		VREF(dp);
    335 	}
    336 	for (;;) {
    337 		if (!dp->v_mount)
    338 		{
    339 			/* Give up if the directory is no longer mounted */
    340 			PNBUF_PUT(cnp->cn_pnbuf);
    341 			return (ENOENT);
    342 		}
    343 		cnp->cn_nameptr = cnp->cn_pnbuf;
    344 		ndp->ni_startdir = dp;
    345 		if ((error = lookup(ndp)) != 0) {
    346 			PNBUF_PUT(cnp->cn_pnbuf);
    347 			return (error);
    348 		}
    349 		/*
    350 		 * Check for symbolic link
    351 		 */
    352 		if ((cnp->cn_flags & ISSYMLINK) == 0) {
    353 			if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0)
    354 				PNBUF_PUT(cnp->cn_pnbuf);
    355 			else
    356 				cnp->cn_flags |= HASBUF;
    357 			return (0);
    358 		}
    359 		if ((cnp->cn_flags & LOCKPARENT) && (cnp->cn_flags & ISLASTCN))
    360 			VOP_UNLOCK(ndp->ni_dvp, 0);
    361 		if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
    362 			error = ELOOP;
    363 			break;
    364 		}
    365 		if (ndp->ni_vp->v_mount->mnt_flag & MNT_SYMPERM) {
    366 			error = VOP_ACCESS(ndp->ni_vp, VEXEC, cnp->cn_cred,
    367 			    cnp->cn_lwp);
    368 			if (error != 0)
    369 				break;
    370 		}
    371 		if (ndp->ni_pathlen > 1)
    372 			cp = PNBUF_GET();
    373 		else
    374 			cp = cnp->cn_pnbuf;
    375 		aiov.iov_base = cp;
    376 		aiov.iov_len = MAXPATHLEN;
    377 		auio.uio_iov = &aiov;
    378 		auio.uio_iovcnt = 1;
    379 		auio.uio_offset = 0;
    380 		auio.uio_rw = UIO_READ;
    381 		auio.uio_resid = MAXPATHLEN;
    382 		UIO_SETUP_SYSSPACE(&auio);
    383 		error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
    384 		if (error) {
    385 		badlink:
    386 			if (ndp->ni_pathlen > 1)
    387 				PNBUF_PUT(cp);
    388 			break;
    389 		}
    390 		linklen = MAXPATHLEN - auio.uio_resid;
    391 		if (linklen == 0) {
    392 			error = ENOENT;
    393 			goto badlink;
    394 		}
    395 		/*
    396 		 * Do symlink substitution, if appropriate, and
    397 		 * check length for potential overflow.
    398 		 */
    399 		if ((vfs_magiclinks &&
    400 		     symlink_magic(cnp->cn_lwp->l_proc, cp, &linklen)) ||
    401 		    (linklen + ndp->ni_pathlen >= MAXPATHLEN)) {
    402 			error = ENAMETOOLONG;
    403 			goto badlink;
    404 		}
    405 		if (ndp->ni_pathlen > 1) {
    406 			memcpy(cp + linklen, ndp->ni_next, ndp->ni_pathlen);
    407 			PNBUF_PUT(cnp->cn_pnbuf);
    408 			cnp->cn_pnbuf = cp;
    409 		} else
    410 			cnp->cn_pnbuf[linklen] = '\0';
    411 		ndp->ni_pathlen += linklen;
    412 		vput(ndp->ni_vp);
    413 		dp = ndp->ni_dvp;
    414 		/*
    415 		 * Check if root directory should replace current directory.
    416 		 */
    417 		if (cnp->cn_pnbuf[0] == '/') {
    418 			vrele(dp);
    419 			dp = ndp->ni_rootdir;
    420 			VREF(dp);
    421 		}
    422 	}
    423 	PNBUF_PUT(cnp->cn_pnbuf);
    424 	vrele(ndp->ni_dvp);
    425 	vput(ndp->ni_vp);
    426 	ndp->ni_vp = NULL;
    427 	return (error);
    428 }
    429 
    430 /*
    431  * Determine the namei hash (for cn_hash) for name.
    432  * If *ep != NULL, hash from name to ep-1.
    433  * If *ep == NULL, hash from name until the first NUL or '/', and
    434  * return the location of this termination character in *ep.
    435  *
    436  * This function returns an equivalent hash to the MI hash32_strn().
    437  * The latter isn't used because in the *ep == NULL case, determining
    438  * the length of the string to the first NUL or `/' and then calling
    439  * hash32_strn() involves unnecessary double-handling of the data.
    440  */
    441 uint32_t
    442 namei_hash(const char *name, const char **ep)
    443 {
    444 	uint32_t	hash;
    445 
    446 	hash = HASH32_STR_INIT;
    447 	if (*ep != NULL) {
    448 		for (; name < *ep; name++)
    449 			hash = hash * 33 + *(const uint8_t *)name;
    450 	} else {
    451 		for (; *name != '\0' && *name != '/'; name++)
    452 			hash = hash * 33 + *(const uint8_t *)name;
    453 		*ep = name;
    454 	}
    455 	return (hash + (hash >> 5));
    456 }
    457 
    458 /*
    459  * Search a pathname.
    460  * This is a very central and rather complicated routine.
    461  *
    462  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
    463  * The starting directory is taken from ni_startdir. The pathname is
    464  * descended until done, or a symbolic link is encountered. The variable
    465  * ni_more is clear if the path is completed; it is set to one if a
    466  * symbolic link needing interpretation is encountered.
    467  *
    468  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
    469  * whether the name is to be looked up, created, renamed, or deleted.
    470  * When CREATE, RENAME, or DELETE is specified, information usable in
    471  * creating, renaming, or deleting a directory entry may be calculated.
    472  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
    473  * locked. If flag has WANTPARENT or'ed into it, the parent directory is
    474  * returned unlocked. Otherwise the parent directory is not returned. If
    475  * the target of the pathname exists and LOCKLEAF is or'ed into the flag
    476  * the target is returned locked, otherwise it is returned unlocked.
    477  * When creating or renaming and LOCKPARENT is specified, the target may not
    478  * be ".".  When deleting and LOCKPARENT is specified, the target may be ".".
    479  *
    480  * Overall outline of lookup:
    481  *
    482  * dirloop:
    483  *	identify next component of name at ndp->ni_ptr
    484  *	handle degenerate case where name is null string
    485  *	if .. and crossing mount points and on mounted filesys, find parent
    486  *	call VOP_LOOKUP routine for next component name
    487  *	    directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
    488  *	    component vnode returned in ni_vp (if it exists), locked.
    489  *	if result vnode is mounted on and crossing mount points,
    490  *	    find mounted on vnode
    491  *	if more components of name, do next level at dirloop
    492  *	return the answer in ni_vp, locked if LOCKLEAF set
    493  *	    if LOCKPARENT set, return locked parent in ni_dvp
    494  *	    if WANTPARENT set, return unlocked parent in ni_dvp
    495  */
    496 int
    497 lookup(struct nameidata *ndp)
    498 {
    499 	const char *cp;			/* pointer into pathname argument */
    500 	struct vnode *dp = 0;		/* the directory we are searching */
    501 	struct vnode *tdp;		/* saved dp */
    502 	struct mount *mp;		/* mount table entry */
    503 	int docache;			/* == 0 do not cache last component */
    504 	int wantparent;			/* 1 => wantparent or lockparent flag */
    505 	int rdonly;			/* lookup read-only flag bit */
    506 	int error = 0;
    507 	int slashes;
    508 	int dpunlocked = 0;		/* dp has already been unlocked */
    509 	struct componentname *cnp = &ndp->ni_cnd;
    510 	struct lwp *l = cnp->cn_lwp;
    511 
    512 	/*
    513 	 * Setup: break out flag bits into variables.
    514 	 */
    515 	wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
    516 	docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
    517 	if (cnp->cn_nameiop == DELETE ||
    518 	    (wantparent && cnp->cn_nameiop != CREATE))
    519 		docache = 0;
    520 	rdonly = cnp->cn_flags & RDONLY;
    521 	ndp->ni_dvp = NULL;
    522 	cnp->cn_flags &= ~ISSYMLINK;
    523 	dp = ndp->ni_startdir;
    524 	ndp->ni_startdir = NULLVP;
    525 	vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    526 
    527 	/*
    528 	 * If we have a leading string of slashes, remove them, and just make
    529 	 * sure the current node is a directory.
    530 	 */
    531 	cp = cnp->cn_nameptr;
    532 	if (*cp == '/') {
    533 		do {
    534 			cp++;
    535 		} while (*cp == '/');
    536 		ndp->ni_pathlen -= cp - cnp->cn_nameptr;
    537 		cnp->cn_nameptr = cp;
    538 
    539 		if (dp->v_type != VDIR) {
    540 			error = ENOTDIR;
    541 			goto bad;
    542 		}
    543 
    544 		/*
    545 		 * If we've exhausted the path name, then just return the
    546 		 * current node.  If the caller requested the parent node (i.e.
    547 		 * it's a CREATE, DELETE, or RENAME), and we don't have one
    548 		 * (because this is the root directory), then we must fail.
    549 		 */
    550 		if (cnp->cn_nameptr[0] == '\0') {
    551 			if (ndp->ni_dvp == NULL && wantparent) {
    552 				switch (cnp->cn_nameiop) {
    553 				case CREATE:
    554 					error = EEXIST;
    555 					break;
    556 				case DELETE:
    557 				case RENAME:
    558 					error = EBUSY;
    559 					break;
    560 				default:
    561 					KASSERT(0);
    562 				}
    563 				goto bad;
    564 			}
    565 			ndp->ni_vp = dp;
    566 			cnp->cn_flags |= ISLASTCN;
    567 			goto terminal;
    568 		}
    569 	}
    570 
    571 dirloop:
    572 	/*
    573 	 * Search a new directory.
    574 	 *
    575 	 * The cn_hash value is for use by vfs_cache.
    576 	 * The last component of the filename is left accessible via
    577 	 * cnp->cn_nameptr for callers that need the name. Callers needing
    578 	 * the name set the SAVENAME flag. When done, they assume
    579 	 * responsibility for freeing the pathname buffer.
    580 	 */
    581 	cnp->cn_consume = 0;
    582 	cp = NULL;
    583 	cnp->cn_hash = namei_hash(cnp->cn_nameptr, &cp);
    584 	cnp->cn_namelen = cp - cnp->cn_nameptr;
    585 	if (cnp->cn_namelen > NAME_MAX) {
    586 		error = ENAMETOOLONG;
    587 		goto bad;
    588 	}
    589 #ifdef NAMEI_DIAGNOSTIC
    590 	{ char c = *cp;
    591 	*(char *)cp = '\0';
    592 	printf("{%s}: ", cnp->cn_nameptr);
    593 	*(char *)cp = c; }
    594 #endif /* NAMEI_DIAGNOSTIC */
    595 	ndp->ni_pathlen -= cnp->cn_namelen;
    596 	ndp->ni_next = cp;
    597 	/*
    598 	 * If this component is followed by a slash, then move the pointer to
    599 	 * the next component forward, and remember that this component must be
    600 	 * a directory.
    601 	 */
    602 	if (*cp == '/') {
    603 		do {
    604 			cp++;
    605 		} while (*cp == '/');
    606 		slashes = cp - ndp->ni_next;
    607 		ndp->ni_pathlen -= slashes;
    608 		ndp->ni_next = cp;
    609 		cnp->cn_flags |= REQUIREDIR;
    610 	} else {
    611 		slashes = 0;
    612 		cnp->cn_flags &= ~REQUIREDIR;
    613 	}
    614 	/*
    615 	 * We do special processing on the last component, whether or not it's
    616 	 * a directory.  Cache all intervening lookups, but not the final one.
    617 	 */
    618 	if (*cp == '\0') {
    619 		if (docache)
    620 			cnp->cn_flags |= MAKEENTRY;
    621 		else
    622 			cnp->cn_flags &= ~MAKEENTRY;
    623 		cnp->cn_flags |= ISLASTCN;
    624 	} else {
    625 		cnp->cn_flags |= MAKEENTRY;
    626 		cnp->cn_flags &= ~ISLASTCN;
    627 	}
    628 	if (cnp->cn_namelen == 2 &&
    629 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
    630 		cnp->cn_flags |= ISDOTDOT;
    631 	else
    632 		cnp->cn_flags &= ~ISDOTDOT;
    633 
    634 	/*
    635 	 * Handle "..": two special cases.
    636 	 * 1. If at root directory (e.g. after chroot)
    637 	 *    or at absolute root directory
    638 	 *    then ignore it so can't get out.
    639 	 * 1a. If we have somehow gotten out of a jail, warn
    640 	 *    and also ignore it so we can't get farther out.
    641 	 * 2. If this vnode is the root of a mounted
    642 	 *    filesystem, then replace it with the
    643 	 *    vnode which was mounted on so we take the
    644 	 *    .. in the other file system.
    645 	 */
    646 	if (cnp->cn_flags & ISDOTDOT) {
    647 		struct proc *p = l->l_proc;
    648 
    649 		for (;;) {
    650 			if (dp == ndp->ni_rootdir || dp == rootvnode) {
    651 				ndp->ni_dvp = dp;
    652 				ndp->ni_vp = dp;
    653 				VREF(dp);
    654 				goto nextname;
    655 			}
    656 			if (ndp->ni_rootdir != rootvnode) {
    657 				int retval;
    658 				VOP_UNLOCK(dp, 0);
    659 				retval = vn_isunder(dp, ndp->ni_rootdir, l);
    660 				vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    661 				if (!retval) {
    662 				    /* Oops! We got out of jail! */
    663 				    log(LOG_WARNING,
    664 					"chrooted pid %d uid %d (%s) "
    665 					"detected outside of its chroot\n",
    666 					p->p_pid, kauth_cred_geteuid(l->l_cred),
    667 					p->p_comm);
    668 				    /* Put us at the jail root. */
    669 				    vput(dp);
    670 				    dp = ndp->ni_rootdir;
    671 				    ndp->ni_dvp = dp;
    672 				    ndp->ni_vp = dp;
    673 				    VREF(dp);
    674 				    VREF(dp);
    675 				    vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    676 				    goto nextname;
    677 				}
    678 			}
    679 			if ((dp->v_flag & VROOT) == 0 ||
    680 			    (cnp->cn_flags & NOCROSSMOUNT))
    681 				break;
    682 			tdp = dp;
    683 			dp = dp->v_mount->mnt_vnodecovered;
    684 			vput(tdp);
    685 			VREF(dp);
    686 			vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    687 		}
    688 	}
    689 
    690 	/*
    691 	 * We now have a segment name to search for, and a directory to search.
    692 	 */
    693 unionlookup:
    694 	ndp->ni_dvp = dp;
    695 	ndp->ni_vp = NULL;
    696 	cnp->cn_flags &= ~PDIRUNLOCK;
    697 	if ((error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp)) != 0) {
    698 #ifdef DIAGNOSTIC
    699 		if (ndp->ni_vp != NULL)
    700 			panic("leaf `%s' should be empty", cnp->cn_nameptr);
    701 #endif /* DIAGNOSTIC */
    702 #ifdef NAMEI_DIAGNOSTIC
    703 		printf("not found\n");
    704 #endif /* NAMEI_DIAGNOSTIC */
    705 		if ((error == ENOENT) &&
    706 		    (dp->v_flag & VROOT) &&
    707 		    (dp->v_mount->mnt_flag & MNT_UNION)) {
    708 			tdp = dp;
    709 			dp = dp->v_mount->mnt_vnodecovered;
    710 			if (cnp->cn_flags & PDIRUNLOCK)
    711 				vrele(tdp);
    712 			else
    713 				vput(tdp);
    714 			VREF(dp);
    715 			vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    716 			goto unionlookup;
    717 		}
    718 
    719 		if (cnp->cn_flags & PDIRUNLOCK)
    720 			dpunlocked = 1;
    721 
    722 		if (error != EJUSTRETURN)
    723 			goto bad;
    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 		 * If creating and at end of pathname, then can consider
    735 		 * allowing file to be created.
    736 		 */
    737 		if (rdonly) {
    738 			error = EROFS;
    739 			goto bad;
    740 		}
    741 		/*
    742 		 * We return with ni_vp NULL to indicate that the entry
    743 		 * doesn't currently exist, leaving a pointer to the
    744 		 * (possibly locked) directory vnode in ndp->ni_dvp.
    745 		 */
    746 		if (cnp->cn_flags & SAVESTART) {
    747 			ndp->ni_startdir = ndp->ni_dvp;
    748 			VREF(ndp->ni_startdir);
    749 		}
    750 		return (0);
    751 	}
    752 #ifdef NAMEI_DIAGNOSTIC
    753 	printf("found\n");
    754 #endif /* NAMEI_DIAGNOSTIC */
    755 
    756 	/*
    757 	 * Take into account any additional components consumed by the
    758 	 * underlying filesystem.  This will include any trailing slashes after
    759 	 * the last component consumed.
    760 	 */
    761 	if (cnp->cn_consume > 0) {
    762 		ndp->ni_pathlen -= cnp->cn_consume - slashes;
    763 		ndp->ni_next += cnp->cn_consume - slashes;
    764 		cnp->cn_consume = 0;
    765 		if (ndp->ni_next[0] == '\0')
    766 			cnp->cn_flags |= ISLASTCN;
    767 	}
    768 
    769 	dp = ndp->ni_vp;
    770 	/*
    771 	 * Check to see if the vnode has been mounted on;
    772 	 * if so find the root of the mounted file system.
    773 	 */
    774 	while (dp->v_type == VDIR && (mp = dp->v_mountedhere) &&
    775 	       (cnp->cn_flags & NOCROSSMOUNT) == 0) {
    776 		if (vfs_busy(mp, 0, 0))
    777 			continue;
    778 		VOP_UNLOCK(dp, 0);
    779 		error = VFS_ROOT(mp, &tdp);
    780 		vfs_unbusy(mp);
    781 		if (error) {
    782 			dpunlocked = 1;
    783 			goto bad2;
    784 		}
    785 		vrele(dp);
    786 		ndp->ni_vp = dp = tdp;
    787 	}
    788 
    789 	/*
    790 	 * Check for symbolic link.  Back up over any slashes that we skipped,
    791 	 * as we will need them again.
    792 	 */
    793 	if ((dp->v_type == VLNK) && (cnp->cn_flags & (FOLLOW|REQUIREDIR))) {
    794 		ndp->ni_pathlen += slashes;
    795 		ndp->ni_next -= slashes;
    796 		cnp->cn_flags |= ISSYMLINK;
    797 		return (0);
    798 	}
    799 
    800 	/*
    801 	 * Check for directory, if the component was followed by a series of
    802 	 * slashes.
    803 	 */
    804 	if ((dp->v_type != VDIR) && (cnp->cn_flags & REQUIREDIR)) {
    805 		error = ENOTDIR;
    806 		goto bad2;
    807 	}
    808 
    809 nextname:
    810 	/*
    811 	 * Not a symbolic link.  If this was not the last component, then
    812 	 * continue at the next component, else return.
    813 	 */
    814 	if (!(cnp->cn_flags & ISLASTCN)) {
    815 		cnp->cn_nameptr = ndp->ni_next;
    816 		vrele(ndp->ni_dvp);
    817 		goto dirloop;
    818 	}
    819 
    820 terminal:
    821 	/*
    822 	 * Disallow directory write attempts on read-only file systems.
    823 	 */
    824 	if (rdonly &&
    825 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
    826 		/*
    827 		 * Disallow directory write attempts on read-only
    828 		 * file systems.
    829 		 */
    830 		error = EROFS;
    831 		goto bad2;
    832 	}
    833 	if (ndp->ni_dvp != NULL) {
    834 		if (cnp->cn_flags & SAVESTART) {
    835 			ndp->ni_startdir = ndp->ni_dvp;
    836 			VREF(ndp->ni_startdir);
    837 		}
    838 		if (!wantparent)
    839 			vrele(ndp->ni_dvp);
    840 	}
    841 	if ((cnp->cn_flags & LOCKLEAF) == 0)
    842 		VOP_UNLOCK(dp, 0);
    843 	return (0);
    844 
    845 bad2:
    846 	if ((cnp->cn_flags & LOCKPARENT) && (cnp->cn_flags & ISLASTCN) &&
    847 			((cnp->cn_flags & PDIRUNLOCK) == 0))
    848 		VOP_UNLOCK(ndp->ni_dvp, 0);
    849 	vrele(ndp->ni_dvp);
    850 bad:
    851 	if (dpunlocked)
    852 		vrele(dp);
    853 	else
    854 		vput(dp);
    855 	ndp->ni_vp = NULL;
    856 	return (error);
    857 }
    858 
    859 /*
    860  * Reacquire a path name component.
    861  */
    862 int
    863 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
    864 {
    865 	struct vnode *dp = 0;		/* the directory we are searching */
    866 	int wantparent;			/* 1 => wantparent or lockparent flag */
    867 	int rdonly;			/* lookup read-only flag bit */
    868 	int error = 0;
    869 #ifdef DEBUG
    870 	u_long newhash;			/* DEBUG: check name hash */
    871 	const char *cp;			/* DEBUG: check name ptr/len */
    872 #endif /* DEBUG */
    873 
    874 	/*
    875 	 * Setup: break out flag bits into variables.
    876 	 */
    877 	wantparent = cnp->cn_flags & (LOCKPARENT|WANTPARENT);
    878 	rdonly = cnp->cn_flags & RDONLY;
    879 	cnp->cn_flags &= ~ISSYMLINK;
    880 	dp = dvp;
    881 	vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
    882 
    883 /* dirloop: */
    884 	/*
    885 	 * Search a new directory.
    886 	 *
    887 	 * The cn_hash value is for use by vfs_cache.
    888 	 * The last component of the filename is left accessible via
    889 	 * cnp->cn_nameptr for callers that need the name. Callers needing
    890 	 * the name set the SAVENAME flag. When done, they assume
    891 	 * responsibility for freeing the pathname buffer.
    892 	 */
    893 #ifdef DEBUG
    894 	cp = NULL;
    895 	newhash = namei_hash(cnp->cn_nameptr, &cp);
    896 	if (newhash != cnp->cn_hash)
    897 		panic("relookup: bad hash");
    898 	if (cnp->cn_namelen != cp - cnp->cn_nameptr)
    899 		panic("relookup: bad len");
    900 	while (*cp == '/')
    901 		cp++;
    902 	if (*cp != 0)
    903 		panic("relookup: not last component");
    904 #endif /* DEBUG */
    905 #ifdef NAMEI_DIAGNOSTIC
    906 	printf("{%s}: ", cnp->cn_nameptr);
    907 #endif /* NAMEI_DIAGNOSTIC */
    908 
    909 	/*
    910 	 * Check for degenerate name (e.g. / or "")
    911 	 * which is a way of talking about a directory,
    912 	 * e.g. like "/." or ".".
    913 	 */
    914 	if (cnp->cn_nameptr[0] == '\0')
    915 		panic("relookup: null name");
    916 
    917 	if (cnp->cn_flags & ISDOTDOT)
    918 		panic("relookup: lookup on dot-dot");
    919 
    920 	/*
    921 	 * We now have a segment name to search for, and a directory to search.
    922 	 */
    923 	if ((error = VOP_LOOKUP(dp, vpp, cnp)) != 0) {
    924 #ifdef DIAGNOSTIC
    925 		if (*vpp != NULL)
    926 			panic("leaf `%s' should be empty", cnp->cn_nameptr);
    927 #endif
    928 		if (error != EJUSTRETURN)
    929 			goto bad;
    930 		/*
    931 		 * If creating and at end of pathname, then can consider
    932 		 * allowing file to be created.
    933 		 */
    934 		if (rdonly) {
    935 			error = EROFS;
    936 			goto bad;
    937 		}
    938 		/* ASSERT(dvp == ndp->ni_startdir) */
    939 		if (cnp->cn_flags & SAVESTART)
    940 			VREF(dvp);
    941 		/*
    942 		 * We return with ni_vp NULL to indicate that the entry
    943 		 * doesn't currently exist, leaving a pointer to the
    944 		 * (possibly locked) directory vnode in ndp->ni_dvp.
    945 		 */
    946 		return (0);
    947 	}
    948 	dp = *vpp;
    949 
    950 #ifdef DIAGNOSTIC
    951 	/*
    952 	 * Check for symbolic link
    953 	 */
    954 	if (dp->v_type == VLNK && (cnp->cn_flags & FOLLOW))
    955 		panic("relookup: symlink found");
    956 #endif
    957 
    958 	/*
    959 	 * Check for read-only file systems.
    960 	 */
    961 	if (rdonly &&
    962 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
    963 		error = EROFS;
    964 		goto bad2;
    965 	}
    966 	/* ASSERT(dvp == ndp->ni_startdir) */
    967 	if (cnp->cn_flags & SAVESTART)
    968 		VREF(dvp);
    969 	if (!wantparent)
    970 		vrele(dvp);
    971 	if ((cnp->cn_flags & LOCKLEAF) == 0)
    972 		VOP_UNLOCK(dp, 0);
    973 	return (0);
    974 
    975 bad2:
    976 	if ((cnp->cn_flags & LOCKPARENT) && (cnp->cn_flags & ISLASTCN))
    977 		VOP_UNLOCK(dvp, 0);
    978 	vrele(dvp);
    979 bad:
    980 	vput(dp);
    981 	*vpp = NULL;
    982 	return (error);
    983 }
    984