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