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