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