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