Home | History | Annotate | Line # | Download | only in kern
vfs_lookup.c revision 1.195
      1 /*	$NetBSD: vfs_lookup.c,v 1.195 2012/10/10 06:55:25 dholland 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.195 2012/10/10 06:55:25 dholland Exp $");
     41 
     42 #include "opt_magiclinks.h"
     43 
     44 #include <sys/param.h>
     45 #include <sys/systm.h>
     46 #include <sys/kernel.h>
     47 #include <sys/syslimits.h>
     48 #include <sys/time.h>
     49 #include <sys/namei.h>
     50 #include <sys/vnode.h>
     51 #include <sys/mount.h>
     52 #include <sys/errno.h>
     53 #include <sys/filedesc.h>
     54 #include <sys/hash.h>
     55 #include <sys/proc.h>
     56 #include <sys/syslog.h>
     57 #include <sys/kauth.h>
     58 #include <sys/ktrace.h>
     59 #include <sys/dirent.h>
     60 
     61 #ifndef MAGICLINKS
     62 #define MAGICLINKS 0
     63 #endif
     64 
     65 int vfs_magiclinks = MAGICLINKS;
     66 
     67 __CTASSERT(MAXNAMLEN == NAME_MAX);
     68 
     69 /*
     70  * Substitute replacement text for 'magic' strings in symlinks.
     71  * Returns 0 if successful, and returns non-zero if an error
     72  * occurs.  (Currently, the only possible error is running out
     73  * of temporary pathname space.)
     74  *
     75  * Looks for "@<string>" and "@<string>/", where <string> is a
     76  * recognized 'magic' string.  Replaces the "@<string>" with the
     77  * appropriate replacement text.  (Note that in some cases the
     78  * replacement text may have zero length.)
     79  *
     80  * This would have been table driven, but the variance in
     81  * replacement strings (and replacement string lengths) made
     82  * that impractical.
     83  */
     84 #define	VNL(x)							\
     85 	(sizeof(x) - 1)
     86 
     87 #define	VO	'{'
     88 #define	VC	'}'
     89 
     90 #define	MATCH(str)						\
     91 	((termchar == '/' && i + VNL(str) == *len) ||		\
     92 	 (i + VNL(str) < *len &&				\
     93 	  cp[i + VNL(str)] == termchar)) &&			\
     94 	!strncmp((str), &cp[i], VNL(str))
     95 
     96 #define	SUBSTITUTE(m, s, sl)					\
     97 	if ((newlen + (sl)) >= MAXPATHLEN)			\
     98 		return 1;					\
     99 	i += VNL(m);						\
    100 	if (termchar != '/')					\
    101 		i++;						\
    102 	(void)memcpy(&tmp[newlen], (s), (sl));			\
    103 	newlen += (sl);						\
    104 	change = 1;						\
    105 	termchar = '/';
    106 
    107 static int
    108 symlink_magic(struct proc *p, char *cp, size_t *len)
    109 {
    110 	char *tmp;
    111 	size_t change, i, newlen, slen;
    112 	char termchar = '/';
    113 	char idtmp[11]; /* enough for 32 bit *unsigned* integer */
    114 
    115 
    116 	tmp = PNBUF_GET();
    117 	for (change = i = newlen = 0; i < *len; ) {
    118 		if (cp[i] != '@') {
    119 			tmp[newlen++] = cp[i++];
    120 			continue;
    121 		}
    122 
    123 		i++;
    124 
    125 		/* Check for @{var} syntax. */
    126 		if (cp[i] == VO) {
    127 			termchar = VC;
    128 			i++;
    129 		}
    130 
    131 		/*
    132 		 * The following checks should be ordered according
    133 		 * to frequency of use.
    134 		 */
    135 		if (MATCH("machine_arch")) {
    136 			slen = VNL(MACHINE_ARCH);
    137 			SUBSTITUTE("machine_arch", MACHINE_ARCH, slen);
    138 		} else if (MATCH("machine")) {
    139 			slen = VNL(MACHINE);
    140 			SUBSTITUTE("machine", MACHINE, slen);
    141 		} else if (MATCH("hostname")) {
    142 			SUBSTITUTE("hostname", hostname, hostnamelen);
    143 		} else if (MATCH("osrelease")) {
    144 			slen = strlen(osrelease);
    145 			SUBSTITUTE("osrelease", osrelease, slen);
    146 		} else if (MATCH("emul")) {
    147 			slen = strlen(p->p_emul->e_name);
    148 			SUBSTITUTE("emul", p->p_emul->e_name, slen);
    149 		} else if (MATCH("kernel_ident")) {
    150 			slen = strlen(kernel_ident);
    151 			SUBSTITUTE("kernel_ident", kernel_ident, slen);
    152 		} else if (MATCH("domainname")) {
    153 			SUBSTITUTE("domainname", domainname, domainnamelen);
    154 		} else if (MATCH("ostype")) {
    155 			slen = strlen(ostype);
    156 			SUBSTITUTE("ostype", ostype, slen);
    157 		} else if (MATCH("uid")) {
    158 			slen = snprintf(idtmp, sizeof(idtmp), "%u",
    159 			    kauth_cred_geteuid(kauth_cred_get()));
    160 			SUBSTITUTE("uid", idtmp, slen);
    161 		} else if (MATCH("ruid")) {
    162 			slen = snprintf(idtmp, sizeof(idtmp), "%u",
    163 			    kauth_cred_getuid(kauth_cred_get()));
    164 			SUBSTITUTE("ruid", idtmp, slen);
    165 		} else if (MATCH("gid")) {
    166 			slen = snprintf(idtmp, sizeof(idtmp), "%u",
    167 			    kauth_cred_getegid(kauth_cred_get()));
    168 			SUBSTITUTE("gid", idtmp, slen);
    169 		} else if (MATCH("rgid")) {
    170 			slen = snprintf(idtmp, sizeof(idtmp), "%u",
    171 			    kauth_cred_getgid(kauth_cred_get()));
    172 			SUBSTITUTE("rgid", idtmp, slen);
    173 		} else {
    174 			tmp[newlen++] = '@';
    175 			if (termchar == VC)
    176 				tmp[newlen++] = VO;
    177 		}
    178 	}
    179 
    180 	if (change) {
    181 		(void)memcpy(cp, tmp, newlen);
    182 		*len = newlen;
    183 	}
    184 	PNBUF_PUT(tmp);
    185 
    186 	return 0;
    187 }
    188 
    189 #undef VNL
    190 #undef VO
    191 #undef VC
    192 #undef MATCH
    193 #undef SUBSTITUTE
    194 
    195 ////////////////////////////////////////////////////////////
    196 
    197 /*
    198  * Determine the namei hash (for cn_hash) for name.
    199  * If *ep != NULL, hash from name to ep-1.
    200  * If *ep == NULL, hash from name until the first NUL or '/', and
    201  * return the location of this termination character in *ep.
    202  *
    203  * This function returns an equivalent hash to the MI hash32_strn().
    204  * The latter isn't used because in the *ep == NULL case, determining
    205  * the length of the string to the first NUL or `/' and then calling
    206  * hash32_strn() involves unnecessary double-handling of the data.
    207  */
    208 uint32_t
    209 namei_hash(const char *name, const char **ep)
    210 {
    211 	uint32_t	hash;
    212 
    213 	hash = HASH32_STR_INIT;
    214 	if (*ep != NULL) {
    215 		for (; name < *ep; name++)
    216 			hash = hash * 33 + *(const uint8_t *)name;
    217 	} else {
    218 		for (; *name != '\0' && *name != '/'; name++)
    219 			hash = hash * 33 + *(const uint8_t *)name;
    220 		*ep = name;
    221 	}
    222 	return (hash + (hash >> 5));
    223 }
    224 
    225 ////////////////////////////////////////////////////////////
    226 
    227 /*
    228  * Sealed abstraction for pathnames.
    229  *
    230  * System-call-layer level code that is going to call namei should
    231  * first create a pathbuf and adjust all the bells and whistles on it
    232  * as needed by context.
    233  */
    234 
    235 struct pathbuf {
    236 	char *pb_path;
    237 	char *pb_pathcopy;
    238 	unsigned pb_pathcopyuses;
    239 };
    240 
    241 static struct pathbuf *
    242 pathbuf_create_raw(void)
    243 {
    244 	struct pathbuf *pb;
    245 
    246 	pb = kmem_alloc(sizeof(*pb), KM_SLEEP);
    247 	if (pb == NULL) {
    248 		return NULL;
    249 	}
    250 	pb->pb_path = PNBUF_GET();
    251 	if (pb->pb_path == NULL) {
    252 		kmem_free(pb, sizeof(*pb));
    253 		return NULL;
    254 	}
    255 	pb->pb_pathcopy = NULL;
    256 	pb->pb_pathcopyuses = 0;
    257 	return pb;
    258 }
    259 
    260 void
    261 pathbuf_destroy(struct pathbuf *pb)
    262 {
    263 	KASSERT(pb->pb_pathcopyuses == 0);
    264 	KASSERT(pb->pb_pathcopy == NULL);
    265 	PNBUF_PUT(pb->pb_path);
    266 	kmem_free(pb, sizeof(*pb));
    267 }
    268 
    269 struct pathbuf *
    270 pathbuf_assimilate(char *pnbuf)
    271 {
    272 	struct pathbuf *pb;
    273 
    274 	pb = kmem_alloc(sizeof(*pb), KM_SLEEP);
    275 	if (pb == NULL) {
    276 		return NULL;
    277 	}
    278 	pb->pb_path = pnbuf;
    279 	pb->pb_pathcopy = NULL;
    280 	pb->pb_pathcopyuses = 0;
    281 	return pb;
    282 }
    283 
    284 struct pathbuf *
    285 pathbuf_create(const char *path)
    286 {
    287 	struct pathbuf *pb;
    288 	int error;
    289 
    290 	pb = pathbuf_create_raw();
    291 	if (pb == NULL) {
    292 		return NULL;
    293 	}
    294 	error = copystr(path, pb->pb_path, PATH_MAX, NULL);
    295 	if (error != 0) {
    296 		KASSERT(!"kernel path too long in pathbuf_create");
    297 		/* make sure it's null-terminated, just in case */
    298 		pb->pb_path[PATH_MAX-1] = '\0';
    299 	}
    300 	return pb;
    301 }
    302 
    303 int
    304 pathbuf_copyin(const char *userpath, struct pathbuf **ret)
    305 {
    306 	struct pathbuf *pb;
    307 	int error;
    308 
    309 	pb = pathbuf_create_raw();
    310 	if (pb == NULL) {
    311 		return ENOMEM;
    312 	}
    313 	error = copyinstr(userpath, pb->pb_path, PATH_MAX, NULL);
    314 	if (error) {
    315 		pathbuf_destroy(pb);
    316 		return error;
    317 	}
    318 	*ret = pb;
    319 	return 0;
    320 }
    321 
    322 /*
    323  * XXX should not exist:
    324  *   1. whether a pointer is kernel or user should be statically checkable.
    325  *   2. copyin should be handled by the upper part of the syscall layer,
    326  *      not in here.
    327  */
    328 int
    329 pathbuf_maybe_copyin(const char *path, enum uio_seg seg, struct pathbuf **ret)
    330 {
    331 	if (seg == UIO_USERSPACE) {
    332 		return pathbuf_copyin(path, ret);
    333 	} else {
    334 		*ret = pathbuf_create(path);
    335 		if (*ret == NULL) {
    336 			return ENOMEM;
    337 		}
    338 		return 0;
    339 	}
    340 }
    341 
    342 /*
    343  * Get a copy of the path buffer as it currently exists. If this is
    344  * called after namei starts the results may be arbitrary.
    345  */
    346 void
    347 pathbuf_copystring(const struct pathbuf *pb, char *buf, size_t maxlen)
    348 {
    349 	strlcpy(buf, pb->pb_path, maxlen);
    350 }
    351 
    352 /*
    353  * These two functions allow access to a saved copy of the original
    354  * path string. The first copy should be gotten before namei is
    355  * called. Each copy that is gotten should be put back.
    356  */
    357 
    358 const char *
    359 pathbuf_stringcopy_get(struct pathbuf *pb)
    360 {
    361 	if (pb->pb_pathcopyuses == 0) {
    362 		pb->pb_pathcopy = PNBUF_GET();
    363 		strcpy(pb->pb_pathcopy, pb->pb_path);
    364 	}
    365 	pb->pb_pathcopyuses++;
    366 	return pb->pb_pathcopy;
    367 }
    368 
    369 void
    370 pathbuf_stringcopy_put(struct pathbuf *pb, const char *str)
    371 {
    372 	KASSERT(str == pb->pb_pathcopy);
    373 	KASSERT(pb->pb_pathcopyuses > 0);
    374 	pb->pb_pathcopyuses--;
    375 	if (pb->pb_pathcopyuses == 0) {
    376 		PNBUF_PUT(pb->pb_pathcopy);
    377 		pb->pb_pathcopy = NULL;
    378 	}
    379 }
    380 
    381 
    382 ////////////////////////////////////////////////////////////
    383 
    384 /*
    385  * namei: convert a pathname into a pointer to a (maybe-locked) vnode,
    386  * and maybe also its parent directory vnode, and assorted other guff.
    387  * See namei(9) for the interface documentation.
    388  *
    389  *
    390  * The FOLLOW flag is set when symbolic links are to be followed
    391  * when they occur at the end of the name translation process.
    392  * Symbolic links are always followed for all other pathname
    393  * components other than the last.
    394  *
    395  * The segflg defines whether the name is to be copied from user
    396  * space or kernel space.
    397  *
    398  * Overall outline of namei:
    399  *
    400  *	copy in name
    401  *	get starting directory
    402  *	while (!done && !error) {
    403  *		call lookup to search path.
    404  *		if symbolic link, massage name in buffer and continue
    405  *	}
    406  */
    407 
    408 /*
    409  * Search a pathname.
    410  * This is a very central and rather complicated routine.
    411  *
    412  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
    413  * The starting directory is passed in. The pathname is descended
    414  * until done, or a symbolic link is encountered. The variable ni_more
    415  * is clear if the path is completed; it is set to one if a symbolic
    416  * link needing interpretation is encountered.
    417  *
    418  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
    419  * whether the name is to be looked up, created, renamed, or deleted.
    420  * When CREATE, RENAME, or DELETE is specified, information usable in
    421  * creating, renaming, or deleting a directory entry may be calculated.
    422  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
    423  * locked.  Otherwise the parent directory is not returned. If the target
    424  * of the pathname exists and LOCKLEAF is or'ed into the flag the target
    425  * is returned locked, otherwise it is returned unlocked.  When creating
    426  * or renaming and LOCKPARENT is specified, the target may not be ".".
    427  * When deleting and LOCKPARENT is specified, the target may be ".".
    428  *
    429  * Overall outline of lookup:
    430  *
    431  * dirloop:
    432  *	identify next component of name at ndp->ni_ptr
    433  *	handle degenerate case where name is null string
    434  *	if .. and crossing mount points and on mounted filesys, find parent
    435  *	call VOP_LOOKUP routine for next component name
    436  *	    directory vnode returned in ni_dvp, locked.
    437  *	    component vnode returned in ni_vp (if it exists), locked.
    438  *	if result vnode is mounted on and crossing mount points,
    439  *	    find mounted on vnode
    440  *	if more components of name, do next level at dirloop
    441  *	return the answer in ni_vp, locked if LOCKLEAF set
    442  *	    if LOCKPARENT set, return locked parent in ni_dvp
    443  */
    444 
    445 
    446 /*
    447  * Internal state for a namei operation.
    448  *
    449  * cnp is always equal to &ndp->ni_cnp.
    450  */
    451 struct namei_state {
    452 	struct nameidata *ndp;
    453 	struct componentname *cnp;
    454 
    455 	int docache;			/* == 0 do not cache last component */
    456 	int rdonly;			/* lookup read-only flag bit */
    457 	int slashes;
    458 
    459 	unsigned attempt_retry:1;	/* true if error allows emul retry */
    460 };
    461 
    462 
    463 /*
    464  * Initialize the namei working state.
    465  */
    466 static void
    467 namei_init(struct namei_state *state, struct nameidata *ndp)
    468 {
    469 	state->ndp = ndp;
    470 	state->cnp = &ndp->ni_cnd;
    471 	KASSERT((state->cnp->cn_flags & INRELOOKUP) == 0);
    472 
    473 	state->docache = 0;
    474 	state->rdonly = 0;
    475 	state->slashes = 0;
    476 
    477 #ifdef DIAGNOSTIC
    478 	if (!state->cnp->cn_cred)
    479 		panic("namei: bad cred/proc");
    480 	if (state->cnp->cn_nameiop & (~OPMASK))
    481 		panic("namei: nameiop contaminated with flags");
    482 	if (state->cnp->cn_flags & OPMASK)
    483 		panic("namei: flags contaminated with nameiops");
    484 #endif
    485 
    486 	/*
    487 	 * The buffer for name translation shall be the one inside the
    488 	 * pathbuf.
    489 	 */
    490 	state->ndp->ni_pnbuf = state->ndp->ni_pathbuf->pb_path;
    491 }
    492 
    493 /*
    494  * Clean up the working namei state, leaving things ready for return
    495  * from namei.
    496  */
    497 static void
    498 namei_cleanup(struct namei_state *state)
    499 {
    500 	KASSERT(state->cnp == &state->ndp->ni_cnd);
    501 
    502 	/* nothing for now */
    503 	(void)state;
    504 }
    505 
    506 //////////////////////////////
    507 
    508 /*
    509  * Get the directory context.
    510  * Initializes the rootdir and erootdir state and returns a reference
    511  * to the starting dir.
    512  */
    513 static struct vnode *
    514 namei_getstartdir(struct namei_state *state, struct vnode *forcecwd)
    515 {
    516 	struct nameidata *ndp = state->ndp;
    517 	struct componentname *cnp = state->cnp;
    518 	struct cwdinfo *cwdi;		/* pointer to cwd state */
    519 	struct lwp *self = curlwp;	/* thread doing namei() */
    520 	struct vnode *rootdir, *erootdir, *curdir, *startdir;
    521 
    522 	cwdi = self->l_proc->p_cwdi;
    523 	rw_enter(&cwdi->cwdi_lock, RW_READER);
    524 
    525 	/* root dir */
    526 	if (cwdi->cwdi_rdir == NULL || (cnp->cn_flags & NOCHROOT)) {
    527 		rootdir = rootvnode;
    528 	} else {
    529 		rootdir = cwdi->cwdi_rdir;
    530 	}
    531 
    532 	/* emulation root dir, if any */
    533 	if ((cnp->cn_flags & TRYEMULROOT) == 0) {
    534 		/* if we don't want it, don't fetch it */
    535 		erootdir = NULL;
    536 	} else if (cnp->cn_flags & EMULROOTSET) {
    537 		/* explicitly set emulroot; "/../" doesn't override this */
    538 		erootdir = ndp->ni_erootdir;
    539 	} else if (!strncmp(ndp->ni_pnbuf, "/../", 4)) {
    540 		/* explicit reference to real rootdir */
    541 		erootdir = NULL;
    542 	} else {
    543 		/* may be null */
    544 		erootdir = cwdi->cwdi_edir;
    545 	}
    546 
    547 	/* current dir */
    548 	if (forcecwd != NULL) {
    549 		curdir = forcecwd;
    550 	} else {
    551 		curdir = cwdi->cwdi_cdir;
    552 	}
    553 
    554 	if (ndp->ni_pnbuf[0] != '/') {
    555 		startdir = curdir;
    556 		erootdir = NULL;
    557 	} else if (cnp->cn_flags & TRYEMULROOT && erootdir != NULL) {
    558 		startdir = erootdir;
    559 	} else {
    560 		startdir = rootdir;
    561 		erootdir = NULL;
    562 	}
    563 
    564 	state->ndp->ni_rootdir = rootdir;
    565 	state->ndp->ni_erootdir = erootdir;
    566 
    567 	/*
    568 	 * Get a reference to the start dir so we can safely unlock cwdi.
    569 	 *
    570 	 * XXX: should we hold references to rootdir and erootdir while
    571 	 * we're running? What happens if a multithreaded process chroots
    572 	 * during namei?
    573 	 */
    574 	vref(startdir);
    575 
    576 	rw_exit(&cwdi->cwdi_lock);
    577 	return startdir;
    578 }
    579 
    580 /*
    581  * Get the directory context for the nfsd case, in parallel to
    582  * getstartdir. Initializes the rootdir and erootdir state and
    583  * returns a reference to the passed-in starting dir.
    584  */
    585 static struct vnode *
    586 namei_getstartdir_for_nfsd(struct namei_state *state, struct vnode *startdir)
    587 {
    588 	KASSERT(startdir != NULL);
    589 
    590 	/* always use the real root, and never set an emulation root */
    591 	state->ndp->ni_rootdir = rootvnode;
    592 	state->ndp->ni_erootdir = NULL;
    593 
    594 	vref(startdir);
    595 	return startdir;
    596 }
    597 
    598 
    599 /*
    600  * Ktrace the namei operation.
    601  */
    602 static void
    603 namei_ktrace(struct namei_state *state)
    604 {
    605 	struct nameidata *ndp = state->ndp;
    606 	struct componentname *cnp = state->cnp;
    607 	struct lwp *self = curlwp;	/* thread doing namei() */
    608 	const char *emul_path;
    609 
    610 	if (ktrpoint(KTR_NAMEI)) {
    611 		if (ndp->ni_erootdir != NULL) {
    612 			/*
    613 			 * To make any sense, the trace entry need to have the
    614 			 * text of the emulation path prepended.
    615 			 * Usually we can get this from the current process,
    616 			 * but when called from emul_find_interp() it is only
    617 			 * in the exec_package - so we get it passed in ni_next
    618 			 * (this is a hack).
    619 			 */
    620 			if (cnp->cn_flags & EMULROOTSET)
    621 				emul_path = ndp->ni_next;
    622 			else
    623 				emul_path = self->l_proc->p_emul->e_path;
    624 			ktrnamei2(emul_path, strlen(emul_path),
    625 			    ndp->ni_pnbuf, ndp->ni_pathlen);
    626 		} else
    627 			ktrnamei(ndp->ni_pnbuf, ndp->ni_pathlen);
    628 	}
    629 }
    630 
    631 /*
    632  * Start up namei. Find the root dir and cwd, establish the starting
    633  * directory for lookup, and lock it. Also calls ktrace when
    634  * appropriate.
    635  */
    636 static int
    637 namei_start(struct namei_state *state, struct vnode *forcecwd, int isnfsd,
    638 	    struct vnode **startdir_ret)
    639 {
    640 	struct nameidata *ndp = state->ndp;
    641 	struct vnode *startdir;
    642 
    643 	/* length includes null terminator (was originally from copyinstr) */
    644 	ndp->ni_pathlen = strlen(ndp->ni_pnbuf) + 1;
    645 
    646 	/*
    647 	 * POSIX.1 requirement: "" is not a valid file name.
    648 	 */
    649 	if (ndp->ni_pathlen == 1) {
    650 		return ENOENT;
    651 	}
    652 
    653 	ndp->ni_loopcnt = 0;
    654 
    655 	/* Get starting directory, set up root, and ktrace. */
    656 	if (isnfsd) {
    657 		startdir = namei_getstartdir_for_nfsd(state, forcecwd);
    658 		/* no ktrace */
    659 	} else {
    660 		startdir = namei_getstartdir(state, forcecwd);
    661 		namei_ktrace(state);
    662 	}
    663 
    664 	vn_lock(startdir, LK_EXCLUSIVE | LK_RETRY);
    665 
    666 	*startdir_ret = startdir;
    667 	return 0;
    668 }
    669 
    670 /*
    671  * Check for being at a symlink that we're going to follow.
    672  */
    673 static inline int
    674 namei_atsymlink(struct namei_state *state, struct vnode *foundobj)
    675 {
    676 	return (foundobj->v_type == VLNK) &&
    677 		(state->cnp->cn_flags & (FOLLOW|REQUIREDIR));
    678 }
    679 
    680 /*
    681  * Follow a symlink.
    682  *
    683  * Updates searchdir. inhibitmagic causes magic symlinks to not be
    684  * interpreted; this is used by nfsd.
    685  *
    686  * Unlocks foundobj on success (ugh)
    687  */
    688 static inline int
    689 namei_follow(struct namei_state *state, int inhibitmagic,
    690 	     struct vnode *searchdir, struct vnode *foundobj,
    691 	     struct vnode **newsearchdir_ret)
    692 {
    693 	struct nameidata *ndp = state->ndp;
    694 	struct componentname *cnp = state->cnp;
    695 
    696 	struct lwp *self = curlwp;	/* thread doing namei() */
    697 	struct iovec aiov;		/* uio for reading symbolic links */
    698 	struct uio auio;
    699 	char *cp;			/* pointer into pathname argument */
    700 	size_t linklen;
    701 	int error;
    702 
    703 	KASSERT(VOP_ISLOCKED(searchdir) == LK_EXCLUSIVE);
    704 	KASSERT(VOP_ISLOCKED(foundobj) == LK_EXCLUSIVE);
    705 	if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
    706 		return ELOOP;
    707 	}
    708 	if (foundobj->v_mount->mnt_flag & MNT_SYMPERM) {
    709 		error = VOP_ACCESS(foundobj, VEXEC, cnp->cn_cred);
    710 		if (error != 0)
    711 			return error;
    712 	}
    713 
    714 	/* FUTURE: fix this to not use a second buffer */
    715 	cp = PNBUF_GET();
    716 	aiov.iov_base = cp;
    717 	aiov.iov_len = MAXPATHLEN;
    718 	auio.uio_iov = &aiov;
    719 	auio.uio_iovcnt = 1;
    720 	auio.uio_offset = 0;
    721 	auio.uio_rw = UIO_READ;
    722 	auio.uio_resid = MAXPATHLEN;
    723 	UIO_SETUP_SYSSPACE(&auio);
    724 	error = VOP_READLINK(foundobj, &auio, cnp->cn_cred);
    725 	if (error) {
    726 		PNBUF_PUT(cp);
    727 		return error;
    728 	}
    729 	linklen = MAXPATHLEN - auio.uio_resid;
    730 	if (linklen == 0) {
    731 		PNBUF_PUT(cp);
    732 		return ENOENT;
    733 	}
    734 
    735 	/*
    736 	 * Do symlink substitution, if appropriate, and
    737 	 * check length for potential overflow.
    738 	 *
    739 	 * Inhibit symlink substitution for nfsd.
    740 	 * XXX: This is how it was before; is that a bug or a feature?
    741 	 */
    742 	if ((!inhibitmagic && vfs_magiclinks &&
    743 	     symlink_magic(self->l_proc, cp, &linklen)) ||
    744 	    (linklen + ndp->ni_pathlen >= MAXPATHLEN)) {
    745 		PNBUF_PUT(cp);
    746 		return ENAMETOOLONG;
    747 	}
    748 	if (ndp->ni_pathlen > 1) {
    749 		/* includes a null-terminator */
    750 		memcpy(cp + linklen, ndp->ni_next, ndp->ni_pathlen);
    751 	} else {
    752 		cp[linklen] = '\0';
    753 	}
    754 	ndp->ni_pathlen += linklen;
    755 	memcpy(ndp->ni_pnbuf, cp, ndp->ni_pathlen);
    756 	PNBUF_PUT(cp);
    757 
    758 	/* we're now starting from the beginning of the buffer again */
    759 	cnp->cn_nameptr = ndp->ni_pnbuf;
    760 
    761 	/* must unlock this before relocking searchdir */
    762 	VOP_UNLOCK(foundobj);
    763 
    764 	/*
    765 	 * Check if root directory should replace current directory.
    766 	 */
    767 	if (ndp->ni_pnbuf[0] == '/') {
    768 		vput(searchdir);
    769 		/* Keep absolute symbolic links inside emulation root */
    770 		searchdir = ndp->ni_erootdir;
    771 		if (searchdir == NULL ||
    772 		    (ndp->ni_pnbuf[1] == '.'
    773 		     && ndp->ni_pnbuf[2] == '.'
    774 		     && ndp->ni_pnbuf[3] == '/')) {
    775 			ndp->ni_erootdir = NULL;
    776 			searchdir = ndp->ni_rootdir;
    777 		}
    778 		vref(searchdir);
    779 		vn_lock(searchdir, LK_EXCLUSIVE | LK_RETRY);
    780 		while (cnp->cn_nameptr[0] == '/') {
    781 			cnp->cn_nameptr++;
    782 			ndp->ni_pathlen--;
    783 		}
    784 	}
    785 
    786 	*newsearchdir_ret = searchdir;
    787 	KASSERT(VOP_ISLOCKED(searchdir) == LK_EXCLUSIVE);
    788 	return 0;
    789 }
    790 
    791 //////////////////////////////
    792 
    793 /*
    794  * Inspect the leading path component and update the state accordingly.
    795  */
    796 static int
    797 lookup_parsepath(struct namei_state *state)
    798 {
    799 	const char *cp;			/* pointer into pathname argument */
    800 
    801 	struct componentname *cnp = state->cnp;
    802 	struct nameidata *ndp = state->ndp;
    803 
    804 	KASSERT(cnp == &ndp->ni_cnd);
    805 
    806 	/*
    807 	 * Search a new directory.
    808 	 *
    809 	 * The cn_hash value is for use by vfs_cache.
    810 	 * The last component of the filename is left accessible via
    811 	 * cnp->cn_nameptr for callers that need the name. Callers needing
    812 	 * the name set the SAVENAME flag. When done, they assume
    813 	 * responsibility for freeing the pathname buffer.
    814 	 *
    815 	 * At this point, our only vnode state is that the search dir
    816 	 * is held and locked.
    817 	 */
    818 	cnp->cn_consume = 0;
    819 	cp = NULL;
    820 	cnp->cn_hash = namei_hash(cnp->cn_nameptr, &cp);
    821 	cnp->cn_namelen = cp - cnp->cn_nameptr;
    822 	if (cnp->cn_namelen > KERNEL_NAME_MAX) {
    823 		return ENAMETOOLONG;
    824 	}
    825 #ifdef NAMEI_DIAGNOSTIC
    826 	{ char c = *cp;
    827 	*(char *)cp = '\0';
    828 	printf("{%s}: ", cnp->cn_nameptr);
    829 	*(char *)cp = c; }
    830 #endif /* NAMEI_DIAGNOSTIC */
    831 	ndp->ni_pathlen -= cnp->cn_namelen;
    832 	ndp->ni_next = cp;
    833 	/*
    834 	 * If this component is followed by a slash, then move the pointer to
    835 	 * the next component forward, and remember that this component must be
    836 	 * a directory.
    837 	 */
    838 	if (*cp == '/') {
    839 		do {
    840 			cp++;
    841 		} while (*cp == '/');
    842 		state->slashes = cp - ndp->ni_next;
    843 		ndp->ni_pathlen -= state->slashes;
    844 		ndp->ni_next = cp;
    845 		cnp->cn_flags |= REQUIREDIR;
    846 	} else {
    847 		state->slashes = 0;
    848 		cnp->cn_flags &= ~REQUIREDIR;
    849 	}
    850 	/*
    851 	 * We do special processing on the last component, whether or not it's
    852 	 * a directory.  Cache all intervening lookups, but not the final one.
    853 	 */
    854 	if (*cp == '\0') {
    855 		if (state->docache)
    856 			cnp->cn_flags |= MAKEENTRY;
    857 		else
    858 			cnp->cn_flags &= ~MAKEENTRY;
    859 		cnp->cn_flags |= ISLASTCN;
    860 	} else {
    861 		cnp->cn_flags |= MAKEENTRY;
    862 		cnp->cn_flags &= ~ISLASTCN;
    863 	}
    864 	if (cnp->cn_namelen == 2 &&
    865 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
    866 		cnp->cn_flags |= ISDOTDOT;
    867 	else
    868 		cnp->cn_flags &= ~ISDOTDOT;
    869 
    870 	return 0;
    871 }
    872 
    873 /*
    874  * Call VOP_LOOKUP for a single lookup; return a new search directory
    875  * (used when crossing mountpoints up or searching union mounts down) and
    876  * the found object, which for create operations may be NULL on success.
    877  */
    878 static int
    879 lookup_once(struct namei_state *state,
    880 	    struct vnode *searchdir,
    881 	    struct vnode **newsearchdir_ret,
    882 	    struct vnode **foundobj_ret)
    883 {
    884 	struct vnode *tmpvn;		/* scratch vnode */
    885 	struct vnode *foundobj;		/* result */
    886 	struct mount *mp;		/* mount table entry */
    887 	struct lwp *l = curlwp;
    888 	int error;
    889 
    890 	struct componentname *cnp = state->cnp;
    891 	struct nameidata *ndp = state->ndp;
    892 
    893 	KASSERT(cnp == &ndp->ni_cnd);
    894 	KASSERT(VOP_ISLOCKED(searchdir) == LK_EXCLUSIVE);
    895 	*newsearchdir_ret = searchdir;
    896 
    897 	/*
    898 	 * Handle "..": two special cases.
    899 	 * 1. If at root directory (e.g. after chroot)
    900 	 *    or at absolute root directory
    901 	 *    then ignore it so can't get out.
    902 	 * 1a. If at the root of the emulation filesystem go to the real
    903 	 *    root. So "/../<path>" is always absolute.
    904 	 * 1b. If we have somehow gotten out of a jail, warn
    905 	 *    and also ignore it so we can't get farther out.
    906 	 * 2. If this vnode is the root of a mounted
    907 	 *    filesystem, then replace it with the
    908 	 *    vnode which was mounted on so we take the
    909 	 *    .. in the other file system.
    910 	 */
    911 	if (cnp->cn_flags & ISDOTDOT) {
    912 		struct proc *p = l->l_proc;
    913 
    914 		for (;;) {
    915 			if (searchdir == ndp->ni_rootdir ||
    916 			    searchdir == rootvnode) {
    917 				foundobj = searchdir;
    918 				vref(foundobj);
    919 				*foundobj_ret = foundobj;
    920 				error = 0;
    921 				goto done;
    922 			}
    923 			if (ndp->ni_rootdir != rootvnode) {
    924 				int retval;
    925 
    926 				VOP_UNLOCK(searchdir);
    927 				retval = vn_isunder(searchdir, ndp->ni_rootdir, l);
    928 				vn_lock(searchdir, LK_EXCLUSIVE | LK_RETRY);
    929 				if (!retval) {
    930 				    /* Oops! We got out of jail! */
    931 				    log(LOG_WARNING,
    932 					"chrooted pid %d uid %d (%s) "
    933 					"detected outside of its chroot\n",
    934 					p->p_pid, kauth_cred_geteuid(l->l_cred),
    935 					p->p_comm);
    936 				    /* Put us at the jail root. */
    937 				    vput(searchdir);
    938 				    searchdir = NULL;
    939 				    foundobj = ndp->ni_rootdir;
    940 				    vref(foundobj);
    941 				    vref(foundobj);
    942 				    vn_lock(foundobj, LK_EXCLUSIVE | LK_RETRY);
    943 				    *newsearchdir_ret = foundobj;
    944 				    *foundobj_ret = foundobj;
    945 				    error = 0;
    946 				    goto done;
    947 				}
    948 			}
    949 			if ((searchdir->v_vflag & VV_ROOT) == 0 ||
    950 			    (cnp->cn_flags & NOCROSSMOUNT))
    951 				break;
    952 			tmpvn = searchdir;
    953 			searchdir = searchdir->v_mount->mnt_vnodecovered;
    954 			vref(searchdir);
    955 			vput(tmpvn);
    956 			vn_lock(searchdir, LK_EXCLUSIVE | LK_RETRY);
    957 			*newsearchdir_ret = searchdir;
    958 		}
    959 	}
    960 
    961 	/*
    962 	 * We now have a segment name to search for, and a directory to search.
    963 	 * Our vnode state here is that "searchdir" is held and locked.
    964 	 */
    965 unionlookup:
    966 	foundobj = NULL;
    967 	error = VOP_LOOKUP(searchdir, &foundobj, cnp);
    968 
    969 	if (error != 0) {
    970 #ifdef DIAGNOSTIC
    971 		if (foundobj != NULL)
    972 			panic("leaf `%s' should be empty", cnp->cn_nameptr);
    973 #endif /* DIAGNOSTIC */
    974 #ifdef NAMEI_DIAGNOSTIC
    975 		printf("not found\n");
    976 #endif /* NAMEI_DIAGNOSTIC */
    977 		if ((error == ENOENT) &&
    978 		    (searchdir->v_vflag & VV_ROOT) &&
    979 		    (searchdir->v_mount->mnt_flag & MNT_UNION)) {
    980 			tmpvn = searchdir;
    981 			searchdir = searchdir->v_mount->mnt_vnodecovered;
    982 			vref(searchdir);
    983 			vput(tmpvn);
    984 			vn_lock(searchdir, LK_EXCLUSIVE | LK_RETRY);
    985 			*newsearchdir_ret = searchdir;
    986 			goto unionlookup;
    987 		}
    988 
    989 		if (error != EJUSTRETURN)
    990 			goto done;
    991 
    992 		/*
    993 		 * If this was not the last component, or there were trailing
    994 		 * slashes, and we are not going to create a directory,
    995 		 * then the name must exist.
    996 		 */
    997 		if ((cnp->cn_flags & (REQUIREDIR | CREATEDIR)) == REQUIREDIR) {
    998 			error = ENOENT;
    999 			goto done;
   1000 		}
   1001 
   1002 		/*
   1003 		 * If creating and at end of pathname, then can consider
   1004 		 * allowing file to be created.
   1005 		 */
   1006 		if (state->rdonly) {
   1007 			error = EROFS;
   1008 			goto done;
   1009 		}
   1010 
   1011 		/*
   1012 		 * We return success and a NULL foundobj to indicate
   1013 		 * that the entry doesn't currently exist, leaving a
   1014 		 * pointer to the (normally, locked) directory vnode
   1015 		 * as searchdir.
   1016 		 */
   1017 		*foundobj_ret = NULL;
   1018 		error = 0;
   1019 		goto done;
   1020 	}
   1021 #ifdef NAMEI_DIAGNOSTIC
   1022 	printf("found\n");
   1023 #endif /* NAMEI_DIAGNOSTIC */
   1024 
   1025 	/*
   1026 	 * Take into account any additional components consumed by the
   1027 	 * underlying filesystem.  This will include any trailing slashes after
   1028 	 * the last component consumed.
   1029 	 */
   1030 	if (cnp->cn_consume > 0) {
   1031 		ndp->ni_pathlen -= cnp->cn_consume - state->slashes;
   1032 		ndp->ni_next += cnp->cn_consume - state->slashes;
   1033 		cnp->cn_consume = 0;
   1034 		if (ndp->ni_next[0] == '\0')
   1035 			cnp->cn_flags |= ISLASTCN;
   1036 	}
   1037 
   1038 	/*
   1039 	 * "foundobj" and "searchdir" are both locked and held,
   1040 	 * and may be the same vnode.
   1041 	 */
   1042 
   1043 	/*
   1044 	 * Check to see if the vnode has been mounted on;
   1045 	 * if so find the root of the mounted file system.
   1046 	 */
   1047 	while (foundobj->v_type == VDIR &&
   1048 	       (mp = foundobj->v_mountedhere) != NULL &&
   1049 	       (cnp->cn_flags & NOCROSSMOUNT) == 0) {
   1050 		error = vfs_busy(mp, NULL);
   1051 		if (error != 0) {
   1052 			if (searchdir != foundobj) {
   1053 				vput(foundobj);
   1054 			} else {
   1055 				vrele(foundobj);
   1056 			}
   1057 			goto done;
   1058 		}
   1059 		if (searchdir != foundobj) {
   1060 			VOP_UNLOCK(searchdir);
   1061 		}
   1062 		vput(foundobj);
   1063 		error = VFS_ROOT(mp, &foundobj);
   1064 		vfs_unbusy(mp, false, NULL);
   1065 		if (error) {
   1066 			vn_lock(searchdir, LK_EXCLUSIVE | LK_RETRY);
   1067 			goto done;
   1068 		}
   1069 		/*
   1070 		 * avoid locking vnodes from two filesystems because it's
   1071 		 * prune to deadlock.  eg. when using puffs.
   1072 		 * also, it isn't a good idea to propagate slowness of a
   1073 		 * filesystem up to the root directory.
   1074 		 * for now, only handle the common case.  (ie. foundobj is VDIR)
   1075 		 */
   1076 		if (foundobj->v_type == VDIR) {
   1077 			vrele(searchdir);
   1078 			*newsearchdir_ret = searchdir = foundobj;
   1079 			vref(searchdir);
   1080 		} else {
   1081 			VOP_UNLOCK(foundobj);
   1082 			vn_lock(searchdir, LK_EXCLUSIVE | LK_RETRY);
   1083 			vn_lock(foundobj, LK_EXCLUSIVE | LK_RETRY);
   1084 		}
   1085 	}
   1086 
   1087 	*foundobj_ret = foundobj;
   1088 	error = 0;
   1089 done:
   1090 	KASSERT(VOP_ISLOCKED(*newsearchdir_ret) == LK_EXCLUSIVE);
   1091 	/*
   1092 	 * *foundobj_ret is valid only if error == 0.
   1093 	 */
   1094 	KASSERT(error != 0 || *foundobj_ret == NULL ||
   1095 	    VOP_ISLOCKED(*foundobj_ret) == LK_EXCLUSIVE);
   1096 	return error;
   1097 }
   1098 
   1099 //////////////////////////////
   1100 
   1101 /*
   1102  * Do a complete path search from a single root directory.
   1103  * (This is called up to twice if TRYEMULROOT is in effect.)
   1104  */
   1105 static int
   1106 namei_oneroot(struct namei_state *state, struct vnode *forcecwd,
   1107 	 int neverfollow, int inhibitmagic, int isnfsd)
   1108 {
   1109 	struct nameidata *ndp = state->ndp;
   1110 	struct componentname *cnp = state->cnp;
   1111 	struct vnode *searchdir, *foundobj;
   1112 	int error;
   1113 
   1114 	error = namei_start(state, forcecwd, isnfsd, &searchdir);
   1115 	if (error) {
   1116 		ndp->ni_dvp = NULL;
   1117 		ndp->ni_vp = NULL;
   1118 		return error;
   1119 	}
   1120 	KASSERT(searchdir->v_type == VDIR);
   1121 
   1122 	/*
   1123 	 * Setup: break out flag bits into variables.
   1124 	 */
   1125 	state->docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
   1126 	if (cnp->cn_nameiop == DELETE)
   1127 		state->docache = 0;
   1128 	state->rdonly = cnp->cn_flags & RDONLY;
   1129 
   1130 	/*
   1131 	 * Keep going until we run out of path components.
   1132 	 */
   1133 	cnp->cn_nameptr = ndp->ni_pnbuf;
   1134 
   1135 	/* drop leading slashes (already used them to choose startdir) */
   1136 	while (cnp->cn_nameptr[0] == '/') {
   1137 		cnp->cn_nameptr++;
   1138 		ndp->ni_pathlen--;
   1139 	}
   1140 	/* was it just "/"? */
   1141 	if (cnp->cn_nameptr[0] == '\0') {
   1142 		foundobj = searchdir;
   1143 		searchdir = NULL;
   1144 		cnp->cn_flags |= ISLASTCN;
   1145 
   1146 		/* bleh */
   1147 		goto skiploop;
   1148 	}
   1149 
   1150 	for (;;) {
   1151 
   1152 		/*
   1153 		 * If the directory we're on is unmounted, bail out.
   1154 		 * XXX: should this also check if it's unlinked?
   1155 		 * XXX: yes it should... but how?
   1156 		 */
   1157 		if (searchdir->v_mount == NULL) {
   1158 			vput(searchdir);
   1159 			ndp->ni_dvp = NULL;
   1160 			ndp->ni_vp = NULL;
   1161 			return (ENOENT);
   1162 		}
   1163 
   1164 		/*
   1165 		 * Look up the next path component.
   1166 		 * (currently, this may consume more than one)
   1167 		 */
   1168 
   1169 		/* There should be no slashes here. */
   1170 		KASSERT(cnp->cn_nameptr[0] != '/');
   1171 
   1172 		/* and we shouldn't have looped around if we were done */
   1173 		KASSERT(cnp->cn_nameptr[0] != '\0');
   1174 
   1175 		error = lookup_parsepath(state);
   1176 		if (error) {
   1177 			vput(searchdir);
   1178 			ndp->ni_dvp = NULL;
   1179 			ndp->ni_vp = NULL;
   1180 			state->attempt_retry = 1;
   1181 			return (error);
   1182 		}
   1183 
   1184 		error = lookup_once(state, searchdir, &searchdir, &foundobj);
   1185 		if (error) {
   1186 			vput(searchdir);
   1187 			ndp->ni_dvp = NULL;
   1188 			ndp->ni_vp = NULL;
   1189 			/*
   1190 			 * Note that if we're doing TRYEMULROOT we can
   1191 			 * retry with the normal root. Where this is
   1192 			 * currently set matches previous practice,
   1193 			 * but the previous practice didn't make much
   1194 			 * sense and somebody should sit down and
   1195 			 * figure out which cases should cause retry
   1196 			 * and which shouldn't. XXX.
   1197 			 */
   1198 			state->attempt_retry = 1;
   1199 			return (error);
   1200 		}
   1201 
   1202 		if (foundobj == NULL) {
   1203 			/*
   1204 			 * Success with no object returned means we're
   1205 			 * creating something and it isn't already
   1206 			 * there. Break out of the main loop now so
   1207 			 * the code below doesn't have to test for
   1208 			 * foundobj == NULL.
   1209 			 */
   1210 			break;
   1211 		}
   1212 
   1213 		/*
   1214 		 * Check for symbolic link. If we've reached one,
   1215 		 * follow it, unless we aren't supposed to. Back up
   1216 		 * over any slashes that we skipped, as we will need
   1217 		 * them again.
   1218 		 */
   1219 		if (namei_atsymlink(state, foundobj)) {
   1220 			ndp->ni_pathlen += state->slashes;
   1221 			ndp->ni_next -= state->slashes;
   1222 			if (neverfollow) {
   1223 				error = EINVAL;
   1224 			} else {
   1225 				/*
   1226 				 * dholland 20110410: if we're at a
   1227 				 * union mount it might make sense to
   1228 				 * use the top of the union stack here
   1229 				 * rather than the layer we found the
   1230 				 * symlink in. (FUTURE)
   1231 				 */
   1232 				error = namei_follow(state, inhibitmagic,
   1233 						     searchdir, foundobj,
   1234 						     &searchdir);
   1235 			}
   1236 			if (error) {
   1237 				KASSERT(searchdir != foundobj);
   1238 				vput(searchdir);
   1239 				vput(foundobj);
   1240 				ndp->ni_dvp = NULL;
   1241 				ndp->ni_vp = NULL;
   1242 				return error;
   1243 			}
   1244 			/* namei_follow unlocks it (ugh) so rele, not put */
   1245 			vrele(foundobj);
   1246 			foundobj = NULL;
   1247 
   1248 			/*
   1249 			 * If we followed a symlink to `/' and there
   1250 			 * are no more components after the symlink,
   1251 			 * we're done with the loop and what we found
   1252 			 * is the searchdir.
   1253 			 */
   1254 			if (cnp->cn_nameptr[0] == '\0') {
   1255 				foundobj = searchdir;
   1256 				searchdir = NULL;
   1257 				cnp->cn_flags |= ISLASTCN;
   1258 				break;
   1259 			}
   1260 
   1261 			continue;
   1262 		}
   1263 
   1264 		/*
   1265 		 * Not a symbolic link.
   1266 		 *
   1267 		 * Check for directory, if the component was
   1268 		 * followed by a series of slashes.
   1269 		 */
   1270 		if ((foundobj->v_type != VDIR) &&
   1271 		    (cnp->cn_flags & REQUIREDIR)) {
   1272 			if (searchdir == foundobj) {
   1273 				vrele(searchdir);
   1274 			} else {
   1275 				vput(searchdir);
   1276 			}
   1277 			vput(foundobj);
   1278 			ndp->ni_dvp = NULL;
   1279 			ndp->ni_vp = NULL;
   1280 			state->attempt_retry = 1;
   1281 			return ENOTDIR;
   1282 		}
   1283 
   1284 		/*
   1285 		 * Stop if we've reached the last component.
   1286 		 */
   1287 		if (cnp->cn_flags & ISLASTCN) {
   1288 			break;
   1289 		}
   1290 
   1291 		/*
   1292 		 * Continue with the next component.
   1293 		 */
   1294 		cnp->cn_nameptr = ndp->ni_next;
   1295 		if (searchdir == foundobj) {
   1296 			vrele(searchdir);
   1297 		} else {
   1298 			vput(searchdir);
   1299 		}
   1300 		searchdir = foundobj;
   1301 		foundobj = NULL;
   1302 	}
   1303 
   1304  skiploop:
   1305 
   1306 	if (foundobj != NULL) {
   1307 		if (foundobj == ndp->ni_erootdir) {
   1308 			/*
   1309 			 * We are about to return the emulation root.
   1310 			 * This isn't a good idea because code might
   1311 			 * repeatedly lookup ".." until the file
   1312 			 * matches that returned for "/" and loop
   1313 			 * forever.  So convert it to the real root.
   1314 			 */
   1315 			if (searchdir != NULL) {
   1316 				if (searchdir == foundobj)
   1317 					vrele(searchdir);
   1318 				else
   1319 					vput(searchdir);
   1320 				searchdir = NULL;
   1321 			}
   1322 			vput(foundobj);
   1323 			foundobj = ndp->ni_rootdir;
   1324 			vref(foundobj);
   1325 			vn_lock(foundobj, LK_EXCLUSIVE | LK_RETRY);
   1326 		}
   1327 
   1328 		/*
   1329 		 * If the caller requested the parent node (i.e. it's
   1330 		 * a CREATE, DELETE, or RENAME), and we don't have one
   1331 		 * (because this is the root directory, or we crossed
   1332 		 * a mount point), then we must fail.
   1333 		 */
   1334 		if (cnp->cn_nameiop != LOOKUP &&
   1335 		    (searchdir == NULL ||
   1336 		     searchdir->v_mount != foundobj->v_mount)) {
   1337 			if (searchdir) {
   1338 				vput(searchdir);
   1339 			}
   1340 			vput(foundobj);
   1341 			foundobj = NULL;
   1342 			ndp->ni_dvp = NULL;
   1343 			ndp->ni_vp = NULL;
   1344 			state->attempt_retry = 1;
   1345 
   1346 			switch (cnp->cn_nameiop) {
   1347 			    case CREATE:
   1348 				return EEXIST;
   1349 			    case DELETE:
   1350 			    case RENAME:
   1351 				return EBUSY;
   1352 			    default:
   1353 				break;
   1354 			}
   1355 			panic("Invalid nameiop\n");
   1356 		}
   1357 
   1358 		/*
   1359 		 * Disallow directory write attempts on read-only lookups.
   1360 		 * Prefers EEXIST over EROFS for the CREATE case.
   1361 		 */
   1362 		if (state->rdonly &&
   1363 		    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
   1364 			if (searchdir) {
   1365 				if (foundobj != searchdir) {
   1366 					vput(searchdir);
   1367 				} else {
   1368 					vrele(searchdir);
   1369 				}
   1370 				searchdir = NULL;
   1371 			}
   1372 			vput(foundobj);
   1373 			foundobj = NULL;
   1374 			ndp->ni_dvp = NULL;
   1375 			ndp->ni_vp = NULL;
   1376 			state->attempt_retry = 1;
   1377 			return EROFS;
   1378 		}
   1379 		if ((cnp->cn_flags & LOCKLEAF) == 0) {
   1380 			/*
   1381 			 * Note: if LOCKPARENT but not LOCKLEAF is
   1382 			 * set, and searchdir == foundobj, this code
   1383 			 * necessarily unlocks the parent as well as
   1384 			 * the leaf. That is, just because you specify
   1385 			 * LOCKPARENT doesn't mean you necessarily get
   1386 			 * a locked parent vnode. The code in
   1387 			 * vfs_syscalls.c, and possibly elsewhere,
   1388 			 * that uses this combination "knows" this, so
   1389 			 * it can't be safely changed. Feh. XXX
   1390 			 */
   1391 			VOP_UNLOCK(foundobj);
   1392 		}
   1393 	}
   1394 
   1395 	/*
   1396 	 * Done.
   1397 	 */
   1398 
   1399 	/*
   1400 	 * If LOCKPARENT is not set, the parent directory isn't returned.
   1401 	 */
   1402 	if ((cnp->cn_flags & LOCKPARENT) == 0 && searchdir != NULL) {
   1403 		if (searchdir == foundobj) {
   1404 			vrele(searchdir);
   1405 		} else {
   1406 			vput(searchdir);
   1407 		}
   1408 		searchdir = NULL;
   1409 	}
   1410 
   1411 	ndp->ni_dvp = searchdir;
   1412 	ndp->ni_vp = foundobj;
   1413 	return 0;
   1414 }
   1415 
   1416 /*
   1417  * Do namei; wrapper layer that handles TRYEMULROOT.
   1418  */
   1419 static int
   1420 namei_tryemulroot(struct namei_state *state, struct vnode *forcecwd,
   1421 	 int neverfollow, int inhibitmagic, int isnfsd)
   1422 {
   1423 	int error;
   1424 
   1425 	struct nameidata *ndp = state->ndp;
   1426 	struct componentname *cnp = state->cnp;
   1427 	const char *savepath = NULL;
   1428 
   1429 	KASSERT(cnp == &ndp->ni_cnd);
   1430 
   1431 	if (cnp->cn_flags & TRYEMULROOT) {
   1432 		savepath = pathbuf_stringcopy_get(ndp->ni_pathbuf);
   1433 	}
   1434 
   1435     emul_retry:
   1436 	state->attempt_retry = 0;
   1437 
   1438 	error = namei_oneroot(state, forcecwd, neverfollow, inhibitmagic, isnfsd);
   1439 	if (error) {
   1440 		/*
   1441 		 * Once namei has started up, the existence of ni_erootdir
   1442 		 * tells us whether we're working from an emulation root.
   1443 		 * The TRYEMULROOT flag isn't necessarily authoritative.
   1444 		 */
   1445 		if (ndp->ni_erootdir != NULL && state->attempt_retry) {
   1446 			/* Retry the whole thing using the normal root */
   1447 			cnp->cn_flags &= ~TRYEMULROOT;
   1448 			state->attempt_retry = 0;
   1449 
   1450 			/* kinda gross */
   1451 			strcpy(ndp->ni_pathbuf->pb_path, savepath);
   1452 			pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
   1453 			savepath = NULL;
   1454 
   1455 			goto emul_retry;
   1456 		}
   1457 	}
   1458 	if (savepath != NULL) {
   1459 		pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
   1460 	}
   1461 	return error;
   1462 }
   1463 
   1464 /*
   1465  * External interface.
   1466  */
   1467 int
   1468 namei(struct nameidata *ndp)
   1469 {
   1470 	struct namei_state state;
   1471 	struct vnode *forcecwd;
   1472 	int error;
   1473 
   1474 	if (ndp->ni_cnd.cn_flags & DIDNDAT) {
   1475 		/* Gross. This is done this way so it can go into 6.1. */
   1476 		forcecwd = ndp->ni_dvp;
   1477 		ndp->ni_dvp = NULL;
   1478 		KASSERT(forcecwd != NULL);
   1479 	} else {
   1480 		forcecwd = NULL;
   1481 	}
   1482 
   1483 	namei_init(&state, ndp);
   1484 	error = namei_tryemulroot(&state, forcecwd,
   1485 				  0/*!neverfollow*/, 0/*!inhibitmagic*/,
   1486 				  0/*isnfsd*/);
   1487 	namei_cleanup(&state);
   1488 
   1489 	if (error) {
   1490 		/* make sure no stray refs leak out */
   1491 		KASSERT(ndp->ni_dvp == NULL);
   1492 		KASSERT(ndp->ni_vp == NULL);
   1493 	}
   1494 
   1495 	return error;
   1496 }
   1497 
   1498 ////////////////////////////////////////////////////////////
   1499 
   1500 /*
   1501  * External interface used by nfsd. This is basically different from
   1502  * namei only in that it has the ability to pass in the "current
   1503  * directory", and uses an extra flag "neverfollow" for which there's
   1504  * no physical flag defined in namei.h. (There used to be a cut&paste
   1505  * copy of about half of namei in nfsd to allow these minor
   1506  * adjustments to exist.)
   1507  *
   1508  * XXX: the namei interface should be adjusted so nfsd can just use
   1509  * ordinary namei().
   1510  */
   1511 int
   1512 lookup_for_nfsd(struct nameidata *ndp, struct vnode *forcecwd, int neverfollow)
   1513 {
   1514 	struct namei_state state;
   1515 	int error;
   1516 
   1517 	KASSERT((ndp->ni_cnd.cn_flags & DIDNDAT) == 0); /* not allowed */
   1518 
   1519 	namei_init(&state, ndp);
   1520 	error = namei_tryemulroot(&state, forcecwd,
   1521 				  neverfollow, 1/*inhibitmagic*/, 1/*isnfsd*/);
   1522 	namei_cleanup(&state);
   1523 
   1524 	if (error) {
   1525 		/* make sure no stray refs leak out */
   1526 		KASSERT(ndp->ni_dvp == NULL);
   1527 		KASSERT(ndp->ni_vp == NULL);
   1528 	}
   1529 
   1530 	return error;
   1531 }
   1532 
   1533 /*
   1534  * A second external interface used by nfsd. This turns out to be a
   1535  * single lookup used by the WebNFS code (ha!) to get "index.html" or
   1536  * equivalent when asked for a directory. It should eventually evolve
   1537  * into some kind of namei_once() call; for the time being it's kind
   1538  * of a mess. XXX.
   1539  *
   1540  * dholland 20110109: I don't think it works, and I don't think it
   1541  * worked before I started hacking and slashing either, and I doubt
   1542  * anyone will ever notice.
   1543  */
   1544 
   1545 /*
   1546  * Internals. This calls lookup_once() after setting up the assorted
   1547  * pieces of state the way they ought to be.
   1548  */
   1549 static int
   1550 do_lookup_for_nfsd_index(struct namei_state *state, struct vnode *startdir)
   1551 {
   1552 	int error = 0;
   1553 
   1554 	struct componentname *cnp = state->cnp;
   1555 	struct nameidata *ndp = state->ndp;
   1556 	struct vnode *foundobj;
   1557 	const char *cp;			/* pointer into pathname argument */
   1558 
   1559 	KASSERT(cnp == &ndp->ni_cnd);
   1560 
   1561 	cnp->cn_nameptr = ndp->ni_pnbuf;
   1562 	state->docache = 1;
   1563 	state->rdonly = cnp->cn_flags & RDONLY;
   1564 	ndp->ni_dvp = NULL;
   1565 
   1566 	cnp->cn_consume = 0;
   1567 	cp = NULL;
   1568 	cnp->cn_hash = namei_hash(cnp->cn_nameptr, &cp);
   1569 	cnp->cn_namelen = cp - cnp->cn_nameptr;
   1570 	KASSERT(cnp->cn_namelen <= KERNEL_NAME_MAX);
   1571 	ndp->ni_pathlen -= cnp->cn_namelen;
   1572 	ndp->ni_next = cp;
   1573 	state->slashes = 0;
   1574 	cnp->cn_flags &= ~REQUIREDIR;
   1575 	cnp->cn_flags |= MAKEENTRY|ISLASTCN;
   1576 
   1577 	if (cnp->cn_namelen == 2 &&
   1578 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
   1579 		cnp->cn_flags |= ISDOTDOT;
   1580 	else
   1581 		cnp->cn_flags &= ~ISDOTDOT;
   1582 
   1583 	/*
   1584 	 * Because lookup_once can change the startdir, we need our
   1585 	 * own reference to it to avoid consuming the caller's.
   1586 	 */
   1587 	vref(startdir);
   1588 	vn_lock(startdir, LK_EXCLUSIVE | LK_RETRY);
   1589 	error = lookup_once(state, startdir, &startdir, &foundobj);
   1590 	if (error == 0 && startdir == foundobj) {
   1591 		vrele(startdir);
   1592 	} else {
   1593 		vput(startdir);
   1594 	}
   1595 	if (error) {
   1596 		goto bad;
   1597 	}
   1598 	ndp->ni_vp = foundobj;
   1599 
   1600 	if (foundobj == NULL) {
   1601 		return 0;
   1602 	}
   1603 
   1604 	KASSERT((cnp->cn_flags & LOCKPARENT) == 0);
   1605 	if ((cnp->cn_flags & LOCKLEAF) == 0) {
   1606 		VOP_UNLOCK(foundobj);
   1607 	}
   1608 	return (0);
   1609 
   1610 bad:
   1611 	ndp->ni_vp = NULL;
   1612 	return (error);
   1613 }
   1614 
   1615 /*
   1616  * External interface. The partitioning between this function and the
   1617  * above isn't very clear - the above function exists mostly so code
   1618  * that uses "state->" can be shuffled around without having to change
   1619  * it to "state.".
   1620  */
   1621 int
   1622 lookup_for_nfsd_index(struct nameidata *ndp, struct vnode *startdir)
   1623 {
   1624 	struct namei_state state;
   1625 	int error;
   1626 
   1627 	KASSERT((ndp->ni_cnd.cn_flags & DIDNDAT) == 0); /* not allowed */
   1628 
   1629 	/*
   1630 	 * Note: the name sent in here (is not|should not be) allowed
   1631 	 * to contain a slash.
   1632 	 */
   1633 	if (strlen(ndp->ni_pathbuf->pb_path) > KERNEL_NAME_MAX) {
   1634 		return ENAMETOOLONG;
   1635 	}
   1636 	if (strchr(ndp->ni_pathbuf->pb_path, '/')) {
   1637 		return EINVAL;
   1638 	}
   1639 
   1640 	ndp->ni_pathlen = strlen(ndp->ni_pathbuf->pb_path) + 1;
   1641 	ndp->ni_pnbuf = NULL;
   1642 	ndp->ni_cnd.cn_nameptr = NULL;
   1643 
   1644 	namei_init(&state, ndp);
   1645 	error = do_lookup_for_nfsd_index(&state, startdir);
   1646 	namei_cleanup(&state);
   1647 
   1648 	return error;
   1649 }
   1650 
   1651 ////////////////////////////////////////////////////////////
   1652 
   1653 /*
   1654  * Reacquire a path name component.
   1655  * dvp is locked on entry and exit.
   1656  * *vpp is locked on exit unless it's NULL.
   1657  */
   1658 int
   1659 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp, int dummy)
   1660 {
   1661 	int rdonly;			/* lookup read-only flag bit */
   1662 	int error = 0;
   1663 #ifdef DEBUG
   1664 	uint32_t newhash;		/* DEBUG: check name hash */
   1665 	const char *cp;			/* DEBUG: check name ptr/len */
   1666 #endif /* DEBUG */
   1667 
   1668 	(void)dummy;
   1669 
   1670 	/*
   1671 	 * Setup: break out flag bits into variables.
   1672 	 */
   1673 	rdonly = cnp->cn_flags & RDONLY;
   1674 
   1675 	/*
   1676 	 * Search a new directory.
   1677 	 *
   1678 	 * The cn_hash value is for use by vfs_cache.
   1679 	 * The last component of the filename is left accessible via
   1680 	 * cnp->cn_nameptr for callers that need the name. Callers needing
   1681 	 * the name set the SAVENAME flag. When done, they assume
   1682 	 * responsibility for freeing the pathname buffer.
   1683 	 */
   1684 #ifdef DEBUG
   1685 	cp = NULL;
   1686 	newhash = namei_hash(cnp->cn_nameptr, &cp);
   1687 	if ((uint32_t)newhash != (uint32_t)cnp->cn_hash)
   1688 		panic("relookup: bad hash");
   1689 	if (cnp->cn_namelen != cp - cnp->cn_nameptr)
   1690 		panic("relookup: bad len");
   1691 	while (*cp == '/')
   1692 		cp++;
   1693 	if (*cp != 0)
   1694 		panic("relookup: not last component");
   1695 #endif /* DEBUG */
   1696 
   1697 	/*
   1698 	 * Check for degenerate name (e.g. / or "")
   1699 	 * which is a way of talking about a directory,
   1700 	 * e.g. like "/." or ".".
   1701 	 */
   1702 	if (cnp->cn_nameptr[0] == '\0')
   1703 		panic("relookup: null name");
   1704 
   1705 	if (cnp->cn_flags & ISDOTDOT)
   1706 		panic("relookup: lookup on dot-dot");
   1707 
   1708 	/*
   1709 	 * We now have a segment name to search for, and a directory to search.
   1710 	 */
   1711 	*vpp = NULL;
   1712 	cnp->cn_flags |= INRELOOKUP;
   1713 	error = VOP_LOOKUP(dvp, vpp, cnp);
   1714 	cnp->cn_flags &= ~INRELOOKUP;
   1715 	if ((error) != 0) {
   1716 #ifdef DIAGNOSTIC
   1717 		if (*vpp != NULL)
   1718 			panic("leaf `%s' should be empty", cnp->cn_nameptr);
   1719 #endif
   1720 		if (error != EJUSTRETURN)
   1721 			goto bad;
   1722 	}
   1723 
   1724 #ifdef DIAGNOSTIC
   1725 	/*
   1726 	 * Check for symbolic link
   1727 	 */
   1728 	if (*vpp && (*vpp)->v_type == VLNK && (cnp->cn_flags & FOLLOW))
   1729 		panic("relookup: symlink found");
   1730 #endif
   1731 
   1732 	/*
   1733 	 * Check for read-only lookups.
   1734 	 */
   1735 	if (rdonly && cnp->cn_nameiop != LOOKUP) {
   1736 		error = EROFS;
   1737 		if (*vpp) {
   1738 			vput(*vpp);
   1739 		}
   1740 		goto bad;
   1741 	}
   1742 	return (0);
   1743 
   1744 bad:
   1745 	*vpp = NULL;
   1746 	return (error);
   1747 }
   1748 
   1749 /*
   1750  * namei_simple - simple forms of namei.
   1751  *
   1752  * These are wrappers to allow the simple case callers of namei to be
   1753  * left alone while everything else changes under them.
   1754  */
   1755 
   1756 /* Flags */
   1757 struct namei_simple_flags_type {
   1758 	int dummy;
   1759 };
   1760 static const struct namei_simple_flags_type ns_nn, ns_nt, ns_fn, ns_ft;
   1761 const namei_simple_flags_t NSM_NOFOLLOW_NOEMULROOT = &ns_nn;
   1762 const namei_simple_flags_t NSM_NOFOLLOW_TRYEMULROOT = &ns_nt;
   1763 const namei_simple_flags_t NSM_FOLLOW_NOEMULROOT = &ns_fn;
   1764 const namei_simple_flags_t NSM_FOLLOW_TRYEMULROOT = &ns_ft;
   1765 
   1766 static
   1767 int
   1768 namei_simple_convert_flags(namei_simple_flags_t sflags)
   1769 {
   1770 	if (sflags == NSM_NOFOLLOW_NOEMULROOT)
   1771 		return NOFOLLOW | 0;
   1772 	if (sflags == NSM_NOFOLLOW_TRYEMULROOT)
   1773 		return NOFOLLOW | TRYEMULROOT;
   1774 	if (sflags == NSM_FOLLOW_NOEMULROOT)
   1775 		return FOLLOW | 0;
   1776 	if (sflags == NSM_FOLLOW_TRYEMULROOT)
   1777 		return FOLLOW | TRYEMULROOT;
   1778 	panic("namei_simple_convert_flags: bogus sflags\n");
   1779 	return 0;
   1780 }
   1781 
   1782 int
   1783 namei_simple_kernel(const char *path, namei_simple_flags_t sflags,
   1784 			struct vnode **vp_ret)
   1785 {
   1786 	struct nameidata nd;
   1787 	struct pathbuf *pb;
   1788 	int err;
   1789 
   1790 	pb = pathbuf_create(path);
   1791 	if (pb == NULL) {
   1792 		return ENOMEM;
   1793 	}
   1794 
   1795 	NDINIT(&nd,
   1796 		LOOKUP,
   1797 		namei_simple_convert_flags(sflags),
   1798 		pb);
   1799 	err = namei(&nd);
   1800 	if (err != 0) {
   1801 		pathbuf_destroy(pb);
   1802 		return err;
   1803 	}
   1804 	*vp_ret = nd.ni_vp;
   1805 	pathbuf_destroy(pb);
   1806 	return 0;
   1807 }
   1808 
   1809 int
   1810 namei_simple_user(const char *path, namei_simple_flags_t sflags,
   1811 			struct vnode **vp_ret)
   1812 {
   1813 	struct pathbuf *pb;
   1814 	struct nameidata nd;
   1815 	int err;
   1816 
   1817 	err = pathbuf_copyin(path, &pb);
   1818 	if (err) {
   1819 		return err;
   1820 	}
   1821 
   1822 	NDINIT(&nd,
   1823 		LOOKUP,
   1824 		namei_simple_convert_flags(sflags),
   1825 		pb);
   1826 	err = namei(&nd);
   1827 	if (err != 0) {
   1828 		pathbuf_destroy(pb);
   1829 		return err;
   1830 	}
   1831 	*vp_ret = nd.ni_vp;
   1832 	pathbuf_destroy(pb);
   1833 	return 0;
   1834 }
   1835