xref: /freebsd-12.1/sys/kern/vfs_lookup.c (revision 82d6e5a5)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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.4 (Berkeley) 2/16/94
37  */
38 
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41 
42 #include "opt_capsicum.h"
43 #include "opt_ktrace.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/capsicum.h>
49 #include <sys/fcntl.h>
50 #include <sys/jail.h>
51 #include <sys/lock.h>
52 #include <sys/mutex.h>
53 #include <sys/namei.h>
54 #include <sys/vnode.h>
55 #include <sys/mount.h>
56 #include <sys/filedesc.h>
57 #include <sys/proc.h>
58 #include <sys/sdt.h>
59 #include <sys/syscallsubr.h>
60 #include <sys/sysctl.h>
61 #ifdef KTRACE
62 #include <sys/ktrace.h>
63 #endif
64 
65 #include <security/audit/audit.h>
66 #include <security/mac/mac_framework.h>
67 
68 #include <vm/uma.h>
69 
70 #define	NAMEI_DIAGNOSTIC 1
71 #undef NAMEI_DIAGNOSTIC
72 
73 SDT_PROVIDER_DECLARE(vfs);
74 SDT_PROBE_DEFINE3(vfs, namei, lookup, entry, "struct vnode *", "char *",
75     "unsigned long");
76 SDT_PROBE_DEFINE2(vfs, namei, lookup, return, "int", "struct vnode *");
77 
78 /* Allocation zone for namei. */
79 uma_zone_t namei_zone;
80 
81 /* Placeholder vnode for mp traversal. */
82 static struct vnode *vp_crossmp;
83 
84 static int
crossmp_vop_islocked(struct vop_islocked_args * ap)85 crossmp_vop_islocked(struct vop_islocked_args *ap)
86 {
87 
88 	return (LK_SHARED);
89 }
90 
91 static int
crossmp_vop_lock1(struct vop_lock1_args * ap)92 crossmp_vop_lock1(struct vop_lock1_args *ap)
93 {
94 	struct vnode *vp;
95 	struct lock *lk __unused;
96 	const char *file __unused;
97 	int flags, line __unused;
98 
99 	vp = ap->a_vp;
100 	lk = vp->v_vnlock;
101 	flags = ap->a_flags;
102 	file = ap->a_file;
103 	line = ap->a_line;
104 
105 	if ((flags & LK_SHARED) == 0)
106 		panic("invalid lock request for crossmp");
107 
108 	WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER, file, line,
109 	    flags & LK_INTERLOCK ? &VI_MTX(vp)->lock_object : NULL);
110 	WITNESS_LOCK(&lk->lock_object, 0, file, line);
111 	if ((flags & LK_INTERLOCK) != 0)
112 		VI_UNLOCK(vp);
113 	LOCK_LOG_LOCK("SLOCK", &lk->lock_object, 0, 0, ap->a_file, line);
114 	return (0);
115 }
116 
117 static int
crossmp_vop_unlock(struct vop_unlock_args * ap)118 crossmp_vop_unlock(struct vop_unlock_args *ap)
119 {
120 	struct vnode *vp;
121 	struct lock *lk __unused;
122 	int flags;
123 
124 	vp = ap->a_vp;
125 	lk = vp->v_vnlock;
126 	flags = ap->a_flags;
127 
128 	if ((flags & LK_INTERLOCK) != 0)
129 		VI_UNLOCK(vp);
130 	WITNESS_UNLOCK(&lk->lock_object, 0, LOCK_FILE, LOCK_LINE);
131 	LOCK_LOG_LOCK("SUNLOCK", &lk->lock_object, 0, 0, LOCK_FILE,
132 	    LOCK_LINE);
133 	return (0);
134 }
135 
136 static struct vop_vector crossmp_vnodeops = {
137 	.vop_default =		&default_vnodeops,
138 	.vop_islocked =		crossmp_vop_islocked,
139 	.vop_lock1 =		crossmp_vop_lock1,
140 	.vop_unlock =		crossmp_vop_unlock,
141 };
142 
143 struct nameicap_tracker {
144 	struct vnode *dp;
145 	TAILQ_ENTRY(nameicap_tracker) nm_link;
146 };
147 
148 /* Zone for cap mode tracker elements used for dotdot capability checks. */
149 static uma_zone_t nt_zone;
150 
151 static void
nameiinit(void * dummy __unused)152 nameiinit(void *dummy __unused)
153 {
154 
155 	namei_zone = uma_zcreate("NAMEI", MAXPATHLEN, NULL, NULL, NULL, NULL,
156 	    UMA_ALIGN_PTR, 0);
157 	nt_zone = uma_zcreate("rentr", sizeof(struct nameicap_tracker),
158 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
159 	getnewvnode("crossmp", NULL, &crossmp_vnodeops, &vp_crossmp);
160 }
161 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nameiinit, NULL);
162 
163 static int lookup_cap_dotdot = 1;
164 SYSCTL_INT(_vfs, OID_AUTO, lookup_cap_dotdot, CTLFLAG_RWTUN,
165     &lookup_cap_dotdot, 0,
166     "enables \"..\" components in path lookup in capability mode");
167 static int lookup_cap_dotdot_nonlocal = 1;
168 SYSCTL_INT(_vfs, OID_AUTO, lookup_cap_dotdot_nonlocal, CTLFLAG_RWTUN,
169     &lookup_cap_dotdot_nonlocal, 0,
170     "enables \"..\" components in path lookup in capability mode "
171     "on non-local mount");
172 
173 static void
nameicap_tracker_add(struct nameidata * ndp,struct vnode * dp)174 nameicap_tracker_add(struct nameidata *ndp, struct vnode *dp)
175 {
176 	struct nameicap_tracker *nt;
177 
178 	if ((ndp->ni_lcf & NI_LCF_CAP_DOTDOT) == 0 || dp->v_type != VDIR)
179 		return;
180 	nt = uma_zalloc(nt_zone, M_WAITOK);
181 	vhold(dp);
182 	nt->dp = dp;
183 	TAILQ_INSERT_TAIL(&ndp->ni_cap_tracker, nt, nm_link);
184 }
185 
186 static void
nameicap_cleanup(struct nameidata * ndp)187 nameicap_cleanup(struct nameidata *ndp)
188 {
189 	struct nameicap_tracker *nt, *nt1;
190 
191 	KASSERT(TAILQ_EMPTY(&ndp->ni_cap_tracker) ||
192 	    (ndp->ni_lcf & NI_LCF_CAP_DOTDOT) != 0, ("not strictrelative"));
193 	TAILQ_FOREACH_SAFE(nt, &ndp->ni_cap_tracker, nm_link, nt1) {
194 		TAILQ_REMOVE(&ndp->ni_cap_tracker, nt, nm_link);
195 		vdrop(nt->dp);
196 		uma_zfree(nt_zone, nt);
197 	}
198 }
199 
200 /*
201  * For dotdot lookups in capability mode, only allow the component
202  * lookup to succeed if the resulting directory was already traversed
203  * during the operation.  Also fail dotdot lookups for non-local
204  * filesystems, where external agents might assist local lookups to
205  * escape the compartment.
206  */
207 static int
nameicap_check_dotdot(struct nameidata * ndp,struct vnode * dp)208 nameicap_check_dotdot(struct nameidata *ndp, struct vnode *dp)
209 {
210 	struct nameicap_tracker *nt;
211 	struct mount *mp;
212 
213 	if ((ndp->ni_lcf & NI_LCF_CAP_DOTDOT) == 0 || dp == NULL ||
214 	    dp->v_type != VDIR)
215 		return (0);
216 	mp = dp->v_mount;
217 	if (lookup_cap_dotdot_nonlocal == 0 && mp != NULL &&
218 	    (mp->mnt_flag & MNT_LOCAL) == 0)
219 		return (ENOTCAPABLE);
220 	TAILQ_FOREACH_REVERSE(nt, &ndp->ni_cap_tracker, nameicap_tracker_head,
221 	    nm_link) {
222 		if (dp == nt->dp)
223 			return (0);
224 	}
225 	return (ENOTCAPABLE);
226 }
227 
228 static void
namei_cleanup_cnp(struct componentname * cnp)229 namei_cleanup_cnp(struct componentname *cnp)
230 {
231 
232 	uma_zfree(namei_zone, cnp->cn_pnbuf);
233 #ifdef DIAGNOSTIC
234 	cnp->cn_pnbuf = NULL;
235 	cnp->cn_nameptr = NULL;
236 #endif
237 }
238 
239 static int
namei_handle_root(struct nameidata * ndp,struct vnode ** dpp)240 namei_handle_root(struct nameidata *ndp, struct vnode **dpp)
241 {
242 	struct componentname *cnp;
243 
244 	cnp = &ndp->ni_cnd;
245 	if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) != 0) {
246 #ifdef KTRACE
247 		if (KTRPOINT(curthread, KTR_CAPFAIL))
248 			ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
249 #endif
250 		return (ENOTCAPABLE);
251 	}
252 	while (*(cnp->cn_nameptr) == '/') {
253 		cnp->cn_nameptr++;
254 		ndp->ni_pathlen--;
255 	}
256 	*dpp = ndp->ni_rootdir;
257 	vrefact(*dpp);
258 	return (0);
259 }
260 
261 /*
262  * Convert a pathname into a pointer to a locked vnode.
263  *
264  * The FOLLOW flag is set when symbolic links are to be followed
265  * when they occur at the end of the name translation process.
266  * Symbolic links are always followed for all other pathname
267  * components other than the last.
268  *
269  * The segflg defines whether the name is to be copied from user
270  * space or kernel space.
271  *
272  * Overall outline of namei:
273  *
274  *	copy in name
275  *	get starting directory
276  *	while (!done && !error) {
277  *		call lookup to search path.
278  *		if symbolic link, massage name in buffer and continue
279  *	}
280  */
281 int
namei(struct nameidata * ndp)282 namei(struct nameidata *ndp)
283 {
284 	struct filedesc *fdp;	/* pointer to file descriptor state */
285 	char *cp;		/* pointer into pathname argument */
286 	struct vnode *dp;	/* the directory we are searching */
287 	struct iovec aiov;		/* uio for reading symbolic links */
288 	struct componentname *cnp;
289 	struct thread *td;
290 	struct proc *p;
291 	cap_rights_t rights;
292 	struct uio auio;
293 	int error, linklen, startdir_used;
294 
295 	cnp = &ndp->ni_cnd;
296 	td = cnp->cn_thread;
297 	p = td->td_proc;
298 	ndp->ni_cnd.cn_cred = ndp->ni_cnd.cn_thread->td_ucred;
299 	KASSERT(cnp->cn_cred && p, ("namei: bad cred/proc"));
300 	KASSERT((cnp->cn_nameiop & (~OPMASK)) == 0,
301 	    ("namei: nameiop contaminated with flags"));
302 	KASSERT((cnp->cn_flags & OPMASK) == 0,
303 	    ("namei: flags contaminated with nameiops"));
304 	MPASS(ndp->ni_startdir == NULL || ndp->ni_startdir->v_type == VDIR ||
305 	    ndp->ni_startdir->v_type == VBAD);
306 	fdp = p->p_fd;
307 	TAILQ_INIT(&ndp->ni_cap_tracker);
308 	ndp->ni_lcf = 0;
309 
310 	/* We will set this ourselves if we need it. */
311 	cnp->cn_flags &= ~TRAILINGSLASH;
312 
313 	/*
314 	 * Get a buffer for the name to be translated, and copy the
315 	 * name into the buffer.
316 	 */
317 	if ((cnp->cn_flags & HASBUF) == 0)
318 		cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
319 	if (ndp->ni_segflg == UIO_SYSSPACE)
320 		error = copystr(ndp->ni_dirp, cnp->cn_pnbuf, MAXPATHLEN,
321 		    &ndp->ni_pathlen);
322 	else
323 		error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf, MAXPATHLEN,
324 		    &ndp->ni_pathlen);
325 
326 	/*
327 	 * Don't allow empty pathnames.
328 	 */
329 	if (error == 0 && *cnp->cn_pnbuf == '\0')
330 		error = ENOENT;
331 
332 #ifdef CAPABILITY_MODE
333 	/*
334 	 * In capability mode, lookups must be restricted to happen in
335 	 * the subtree with the root specified by the file descriptor:
336 	 * - The root must be real file descriptor, not the pseudo-descriptor
337 	 *   AT_FDCWD.
338 	 * - The passed path must be relative and not absolute.
339 	 * - If lookup_cap_dotdot is disabled, path must not contain the
340 	 *   '..' components.
341 	 * - If lookup_cap_dotdot is enabled, we verify that all '..'
342 	 *   components lookups result in the directories which were
343 	 *   previously walked by us, which prevents an escape from
344 	 *   the relative root.
345 	 */
346 	if (error == 0 && IN_CAPABILITY_MODE(td) &&
347 	    (cnp->cn_flags & NOCAPCHECK) == 0) {
348 		ndp->ni_lcf |= NI_LCF_STRICTRELATIVE;
349 		if (ndp->ni_dirfd == AT_FDCWD) {
350 #ifdef KTRACE
351 			if (KTRPOINT(td, KTR_CAPFAIL))
352 				ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
353 #endif
354 			error = ECAPMODE;
355 		}
356 	}
357 #endif
358 	if (error != 0) {
359 		namei_cleanup_cnp(cnp);
360 		ndp->ni_vp = NULL;
361 		return (error);
362 	}
363 	ndp->ni_loopcnt = 0;
364 #ifdef KTRACE
365 	if (KTRPOINT(td, KTR_NAMEI)) {
366 		KASSERT(cnp->cn_thread == curthread,
367 		    ("namei not using curthread"));
368 		ktrnamei(cnp->cn_pnbuf);
369 	}
370 #endif
371 	/*
372 	 * Get starting point for the translation.
373 	 */
374 	FILEDESC_SLOCK(fdp);
375 	ndp->ni_rootdir = fdp->fd_rdir;
376 	vrefact(ndp->ni_rootdir);
377 	ndp->ni_topdir = fdp->fd_jdir;
378 
379 	/*
380 	 * If we are auditing the kernel pathname, save the user pathname.
381 	 */
382 	if (cnp->cn_flags & AUDITVNODE1)
383 		AUDIT_ARG_UPATH1(td, ndp->ni_dirfd, cnp->cn_pnbuf);
384 	if (cnp->cn_flags & AUDITVNODE2)
385 		AUDIT_ARG_UPATH2(td, ndp->ni_dirfd, cnp->cn_pnbuf);
386 
387 	startdir_used = 0;
388 	dp = NULL;
389 	cnp->cn_nameptr = cnp->cn_pnbuf;
390 	if (cnp->cn_pnbuf[0] == '/') {
391 		ndp->ni_resflags |= NIRES_ABS;
392 		error = namei_handle_root(ndp, &dp);
393 	} else {
394 		if (ndp->ni_startdir != NULL) {
395 			dp = ndp->ni_startdir;
396 			startdir_used = 1;
397 		} else if (ndp->ni_dirfd == AT_FDCWD) {
398 			dp = fdp->fd_cdir;
399 			vrefact(dp);
400 		} else {
401 			rights = ndp->ni_rightsneeded;
402 			cap_rights_set(&rights, CAP_LOOKUP);
403 
404 			if (cnp->cn_flags & AUDITVNODE1)
405 				AUDIT_ARG_ATFD1(ndp->ni_dirfd);
406 			if (cnp->cn_flags & AUDITVNODE2)
407 				AUDIT_ARG_ATFD2(ndp->ni_dirfd);
408 			error = fgetvp_rights(td, ndp->ni_dirfd,
409 			    &rights, &ndp->ni_filecaps, &dp);
410 			if (error == EINVAL)
411 				error = ENOTDIR;
412 #ifdef CAPABILITIES
413 			/*
414 			 * If file descriptor doesn't have all rights,
415 			 * all lookups relative to it must also be
416 			 * strictly relative.
417 			 */
418 			CAP_ALL(&rights);
419 			if (!cap_rights_contains(&ndp->ni_filecaps.fc_rights,
420 			    &rights) ||
421 			    ndp->ni_filecaps.fc_fcntls != CAP_FCNTL_ALL ||
422 			    ndp->ni_filecaps.fc_nioctls != -1) {
423 				ndp->ni_lcf |= NI_LCF_STRICTRELATIVE;
424 			}
425 #endif
426 		}
427 		if (error == 0 && dp->v_type != VDIR)
428 			error = ENOTDIR;
429 	}
430 	FILEDESC_SUNLOCK(fdp);
431 	if (ndp->ni_startdir != NULL && !startdir_used)
432 		vrele(ndp->ni_startdir);
433 	if (error != 0) {
434 		if (dp != NULL)
435 			vrele(dp);
436 		goto out;
437 	}
438 	if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) != 0 &&
439 	    lookup_cap_dotdot != 0)
440 		ndp->ni_lcf |= NI_LCF_CAP_DOTDOT;
441 	SDT_PROBE3(vfs, namei, lookup, entry, dp, cnp->cn_pnbuf,
442 	    cnp->cn_flags);
443 	for (;;) {
444 		ndp->ni_startdir = dp;
445 		error = lookup(ndp);
446 		if (error != 0)
447 			goto out;
448 		/*
449 		 * If not a symbolic link, we're done.
450 		 */
451 		if ((cnp->cn_flags & ISSYMLINK) == 0) {
452 			vrele(ndp->ni_rootdir);
453 			if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0) {
454 				namei_cleanup_cnp(cnp);
455 			} else
456 				cnp->cn_flags |= HASBUF;
457 			nameicap_cleanup(ndp);
458 			SDT_PROBE2(vfs, namei, lookup, return, 0, ndp->ni_vp);
459 			return (0);
460 		}
461 		if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
462 			error = ELOOP;
463 			break;
464 		}
465 #ifdef MAC
466 		if ((cnp->cn_flags & NOMACCHECK) == 0) {
467 			error = mac_vnode_check_readlink(td->td_ucred,
468 			    ndp->ni_vp);
469 			if (error != 0)
470 				break;
471 		}
472 #endif
473 		if (ndp->ni_pathlen > 1)
474 			cp = uma_zalloc(namei_zone, M_WAITOK);
475 		else
476 			cp = cnp->cn_pnbuf;
477 		aiov.iov_base = cp;
478 		aiov.iov_len = MAXPATHLEN;
479 		auio.uio_iov = &aiov;
480 		auio.uio_iovcnt = 1;
481 		auio.uio_offset = 0;
482 		auio.uio_rw = UIO_READ;
483 		auio.uio_segflg = UIO_SYSSPACE;
484 		auio.uio_td = td;
485 		auio.uio_resid = MAXPATHLEN;
486 		error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
487 		if (error != 0) {
488 			if (ndp->ni_pathlen > 1)
489 				uma_zfree(namei_zone, cp);
490 			break;
491 		}
492 		linklen = MAXPATHLEN - auio.uio_resid;
493 		if (linklen == 0) {
494 			if (ndp->ni_pathlen > 1)
495 				uma_zfree(namei_zone, cp);
496 			error = ENOENT;
497 			break;
498 		}
499 		if (linklen + ndp->ni_pathlen > MAXPATHLEN) {
500 			if (ndp->ni_pathlen > 1)
501 				uma_zfree(namei_zone, cp);
502 			error = ENAMETOOLONG;
503 			break;
504 		}
505 		if (ndp->ni_pathlen > 1) {
506 			bcopy(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
507 			uma_zfree(namei_zone, cnp->cn_pnbuf);
508 			cnp->cn_pnbuf = cp;
509 		} else
510 			cnp->cn_pnbuf[linklen] = '\0';
511 		ndp->ni_pathlen += linklen;
512 		vput(ndp->ni_vp);
513 		dp = ndp->ni_dvp;
514 		/*
515 		 * Check if root directory should replace current directory.
516 		 */
517 		cnp->cn_nameptr = cnp->cn_pnbuf;
518 		if (*(cnp->cn_nameptr) == '/') {
519 			vrele(dp);
520 			error = namei_handle_root(ndp, &dp);
521 			if (error != 0)
522 				goto out;
523 		}
524 	}
525 	vput(ndp->ni_vp);
526 	ndp->ni_vp = NULL;
527 	vrele(ndp->ni_dvp);
528 out:
529 	vrele(ndp->ni_rootdir);
530 	namei_cleanup_cnp(cnp);
531 	nameicap_cleanup(ndp);
532 	SDT_PROBE2(vfs, namei, lookup, return, error, NULL);
533 	return (error);
534 }
535 
536 static int
compute_cn_lkflags(struct mount * mp,int lkflags,int cnflags)537 compute_cn_lkflags(struct mount *mp, int lkflags, int cnflags)
538 {
539 
540 	if (mp == NULL || ((lkflags & LK_SHARED) &&
541 	    (!(mp->mnt_kern_flag & MNTK_LOOKUP_SHARED) ||
542 	    ((cnflags & ISDOTDOT) &&
543 	    (mp->mnt_kern_flag & MNTK_LOOKUP_EXCL_DOTDOT))))) {
544 		lkflags &= ~LK_SHARED;
545 		lkflags |= LK_EXCLUSIVE;
546 	}
547 	lkflags |= LK_NODDLKTREAT;
548 	return (lkflags);
549 }
550 
551 static __inline int
needs_exclusive_leaf(struct mount * mp,int flags)552 needs_exclusive_leaf(struct mount *mp, int flags)
553 {
554 
555 	/*
556 	 * Intermediate nodes can use shared locks, we only need to
557 	 * force an exclusive lock for leaf nodes.
558 	 */
559 	if ((flags & (ISLASTCN | LOCKLEAF)) != (ISLASTCN | LOCKLEAF))
560 		return (0);
561 
562 	/* Always use exclusive locks if LOCKSHARED isn't set. */
563 	if (!(flags & LOCKSHARED))
564 		return (1);
565 
566 	/*
567 	 * For lookups during open(), if the mount point supports
568 	 * extended shared operations, then use a shared lock for the
569 	 * leaf node, otherwise use an exclusive lock.
570 	 */
571 	if ((flags & ISOPEN) != 0)
572 		return (!MNT_EXTENDED_SHARED(mp));
573 
574 	/*
575 	 * Lookup requests outside of open() that specify LOCKSHARED
576 	 * only need a shared lock on the leaf vnode.
577 	 */
578 	return (0);
579 }
580 
581 /*
582  * Search a pathname.
583  * This is a very central and rather complicated routine.
584  *
585  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
586  * The starting directory is taken from ni_startdir. The pathname is
587  * descended until done, or a symbolic link is encountered. The variable
588  * ni_more is clear if the path is completed; it is set to one if a
589  * symbolic link needing interpretation is encountered.
590  *
591  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
592  * whether the name is to be looked up, created, renamed, or deleted.
593  * When CREATE, RENAME, or DELETE is specified, information usable in
594  * creating, renaming, or deleting a directory entry may be calculated.
595  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
596  * locked. If flag has WANTPARENT or'ed into it, the parent directory is
597  * returned unlocked. Otherwise the parent directory is not returned. If
598  * the target of the pathname exists and LOCKLEAF is or'ed into the flag
599  * the target is returned locked, otherwise it is returned unlocked.
600  * When creating or renaming and LOCKPARENT is specified, the target may not
601  * be ".".  When deleting and LOCKPARENT is specified, the target may be ".".
602  *
603  * Overall outline of lookup:
604  *
605  * dirloop:
606  *	identify next component of name at ndp->ni_ptr
607  *	handle degenerate case where name is null string
608  *	if .. and crossing mount points and on mounted filesys, find parent
609  *	call VOP_LOOKUP routine for next component name
610  *	    directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
611  *	    component vnode returned in ni_vp (if it exists), locked.
612  *	if result vnode is mounted on and crossing mount points,
613  *	    find mounted on vnode
614  *	if more components of name, do next level at dirloop
615  *	return the answer in ni_vp, locked if LOCKLEAF set
616  *	    if LOCKPARENT set, return locked parent in ni_dvp
617  *	    if WANTPARENT set, return unlocked parent in ni_dvp
618  */
619 int
lookup(struct nameidata * ndp)620 lookup(struct nameidata *ndp)
621 {
622 	char *cp;			/* pointer into pathname argument */
623 	char *prev_ni_next;		/* saved ndp->ni_next */
624 	struct vnode *dp = NULL;	/* the directory we are searching */
625 	struct vnode *tdp;		/* saved dp */
626 	struct mount *mp;		/* mount table entry */
627 	struct prison *pr;
628 	size_t prev_ni_pathlen;		/* saved ndp->ni_pathlen */
629 	int docache;			/* == 0 do not cache last component */
630 	int wantparent;			/* 1 => wantparent or lockparent flag */
631 	int rdonly;			/* lookup read-only flag bit */
632 	int error = 0;
633 	int dpunlocked = 0;		/* dp has already been unlocked */
634 	int relookup = 0;		/* do not consume the path component */
635 	struct componentname *cnp = &ndp->ni_cnd;
636 	int lkflags_save;
637 	int ni_dvp_unlocked;
638 
639 	/*
640 	 * Setup: break out flag bits into variables.
641 	 */
642 	ni_dvp_unlocked = 0;
643 	wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
644 	KASSERT(cnp->cn_nameiop == LOOKUP || wantparent,
645 	    ("CREATE, DELETE, RENAME require LOCKPARENT or WANTPARENT."));
646 	docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
647 	if (cnp->cn_nameiop == DELETE ||
648 	    (wantparent && cnp->cn_nameiop != CREATE &&
649 	     cnp->cn_nameiop != LOOKUP))
650 		docache = 0;
651 	rdonly = cnp->cn_flags & RDONLY;
652 	cnp->cn_flags &= ~ISSYMLINK;
653 	ndp->ni_dvp = NULL;
654 	/*
655 	 * We use shared locks until we hit the parent of the last cn then
656 	 * we adjust based on the requesting flags.
657 	 */
658 	cnp->cn_lkflags = LK_SHARED;
659 	dp = ndp->ni_startdir;
660 	ndp->ni_startdir = NULLVP;
661 	vn_lock(dp,
662 	    compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags | LK_RETRY,
663 	    cnp->cn_flags));
664 
665 dirloop:
666 	/*
667 	 * Search a new directory.
668 	 *
669 	 * The last component of the filename is left accessible via
670 	 * cnp->cn_nameptr for callers that need the name. Callers needing
671 	 * the name set the SAVENAME flag. When done, they assume
672 	 * responsibility for freeing the pathname buffer.
673 	 */
674 	for (cp = cnp->cn_nameptr; *cp != 0 && *cp != '/'; cp++)
675 		continue;
676 	cnp->cn_namelen = cp - cnp->cn_nameptr;
677 	if (cnp->cn_namelen > NAME_MAX) {
678 		error = ENAMETOOLONG;
679 		goto bad;
680 	}
681 #ifdef NAMEI_DIAGNOSTIC
682 	{ char c = *cp;
683 	*cp = '\0';
684 	printf("{%s}: ", cnp->cn_nameptr);
685 	*cp = c; }
686 #endif
687 	prev_ni_pathlen = ndp->ni_pathlen;
688 	ndp->ni_pathlen -= cnp->cn_namelen;
689 	KASSERT(ndp->ni_pathlen <= PATH_MAX,
690 	    ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
691 	prev_ni_next = ndp->ni_next;
692 	ndp->ni_next = cp;
693 
694 	/*
695 	 * Replace multiple slashes by a single slash and trailing slashes
696 	 * by a null.  This must be done before VOP_LOOKUP() because some
697 	 * fs's don't know about trailing slashes.  Remember if there were
698 	 * trailing slashes to handle symlinks, existing non-directories
699 	 * and non-existing files that won't be directories specially later.
700 	 */
701 	while (*cp == '/' && (cp[1] == '/' || cp[1] == '\0')) {
702 		cp++;
703 		ndp->ni_pathlen--;
704 		if (*cp == '\0') {
705 			*ndp->ni_next = '\0';
706 			cnp->cn_flags |= TRAILINGSLASH;
707 		}
708 	}
709 	ndp->ni_next = cp;
710 
711 	cnp->cn_flags |= MAKEENTRY;
712 	if (*cp == '\0' && docache == 0)
713 		cnp->cn_flags &= ~MAKEENTRY;
714 	if (cnp->cn_namelen == 2 &&
715 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
716 		cnp->cn_flags |= ISDOTDOT;
717 	else
718 		cnp->cn_flags &= ~ISDOTDOT;
719 	if (*ndp->ni_next == 0)
720 		cnp->cn_flags |= ISLASTCN;
721 	else
722 		cnp->cn_flags &= ~ISLASTCN;
723 
724 	if ((cnp->cn_flags & ISLASTCN) != 0 &&
725 	    cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.' &&
726 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
727 		error = EINVAL;
728 		goto bad;
729 	}
730 
731 	nameicap_tracker_add(ndp, dp);
732 
733 	/*
734 	 * Check for degenerate name (e.g. / or "")
735 	 * which is a way of talking about a directory,
736 	 * e.g. like "/." or ".".
737 	 */
738 	if (cnp->cn_nameptr[0] == '\0') {
739 		if (dp->v_type != VDIR) {
740 			error = ENOTDIR;
741 			goto bad;
742 		}
743 		if (cnp->cn_nameiop != LOOKUP) {
744 			error = EISDIR;
745 			goto bad;
746 		}
747 		if (wantparent) {
748 			ndp->ni_dvp = dp;
749 			VREF(dp);
750 		}
751 		ndp->ni_vp = dp;
752 
753 		if (cnp->cn_flags & AUDITVNODE1)
754 			AUDIT_ARG_VNODE1(dp);
755 		else if (cnp->cn_flags & AUDITVNODE2)
756 			AUDIT_ARG_VNODE2(dp);
757 
758 		if (!(cnp->cn_flags & (LOCKPARENT | LOCKLEAF)))
759 			VOP_UNLOCK(dp, 0);
760 		/* XXX This should probably move to the top of function. */
761 		if (cnp->cn_flags & SAVESTART)
762 			panic("lookup: SAVESTART");
763 		goto success;
764 	}
765 
766 	/*
767 	 * Handle "..": five special cases.
768 	 * 0. If doing a capability lookup and lookup_cap_dotdot is
769 	 *    disabled, return ENOTCAPABLE.
770 	 * 1. Return an error if this is the last component of
771 	 *    the name and the operation is DELETE or RENAME.
772 	 * 2. If at root directory (e.g. after chroot)
773 	 *    or at absolute root directory
774 	 *    then ignore it so can't get out.
775 	 * 3. If this vnode is the root of a mounted
776 	 *    filesystem, then replace it with the
777 	 *    vnode which was mounted on so we take the
778 	 *    .. in the other filesystem.
779 	 * 4. If the vnode is the top directory of
780 	 *    the jail or chroot, don't let them out.
781 	 * 5. If doing a capability lookup and lookup_cap_dotdot is
782 	 *    enabled, return ENOTCAPABLE if the lookup would escape
783 	 *    from the initial file descriptor directory.  Checks are
784 	 *    done by ensuring that namei() already traversed the
785 	 *    result of dotdot lookup.
786 	 */
787 	if (cnp->cn_flags & ISDOTDOT) {
788 		if ((ndp->ni_lcf & (NI_LCF_STRICTRELATIVE | NI_LCF_CAP_DOTDOT))
789 		    == NI_LCF_STRICTRELATIVE) {
790 #ifdef KTRACE
791 			if (KTRPOINT(curthread, KTR_CAPFAIL))
792 				ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
793 #endif
794 			error = ENOTCAPABLE;
795 			goto bad;
796 		}
797 		if ((cnp->cn_flags & ISLASTCN) != 0 &&
798 		    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
799 			error = EINVAL;
800 			goto bad;
801 		}
802 		for (;;) {
803 			for (pr = cnp->cn_cred->cr_prison; pr != NULL;
804 			     pr = pr->pr_parent)
805 				if (dp == pr->pr_root)
806 					break;
807 			if (dp == ndp->ni_rootdir ||
808 			    dp == ndp->ni_topdir ||
809 			    dp == rootvnode ||
810 			    pr != NULL ||
811 			    ((dp->v_vflag & VV_ROOT) != 0 &&
812 			     (cnp->cn_flags & NOCROSSMOUNT) != 0)) {
813 				ndp->ni_dvp = dp;
814 				ndp->ni_vp = dp;
815 				VREF(dp);
816 				goto nextname;
817 			}
818 			if ((dp->v_vflag & VV_ROOT) == 0)
819 				break;
820 			if (dp->v_iflag & VI_DOOMED) {	/* forced unmount */
821 				error = ENOENT;
822 				goto bad;
823 			}
824 			tdp = dp;
825 			dp = dp->v_mount->mnt_vnodecovered;
826 			VREF(dp);
827 			vput(tdp);
828 			vn_lock(dp,
829 			    compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags |
830 			    LK_RETRY, ISDOTDOT));
831 			error = nameicap_check_dotdot(ndp, dp);
832 			if (error != 0) {
833 #ifdef KTRACE
834 				if (KTRPOINT(curthread, KTR_CAPFAIL))
835 					ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
836 #endif
837 				goto bad;
838 			}
839 		}
840 	}
841 
842 	/*
843 	 * We now have a segment name to search for, and a directory to search.
844 	 */
845 unionlookup:
846 #ifdef MAC
847 	if ((cnp->cn_flags & NOMACCHECK) == 0) {
848 		error = mac_vnode_check_lookup(cnp->cn_thread->td_ucred, dp,
849 		    cnp);
850 		if (error)
851 			goto bad;
852 	}
853 #endif
854 	ndp->ni_dvp = dp;
855 	ndp->ni_vp = NULL;
856 	ASSERT_VOP_LOCKED(dp, "lookup");
857 	/*
858 	 * If we have a shared lock we may need to upgrade the lock for the
859 	 * last operation.
860 	 */
861 	if ((cnp->cn_flags & LOCKPARENT) && (cnp->cn_flags & ISLASTCN) &&
862 	    dp != vp_crossmp && VOP_ISLOCKED(dp) == LK_SHARED)
863 		vn_lock(dp, LK_UPGRADE|LK_RETRY);
864 	if ((dp->v_iflag & VI_DOOMED) != 0) {
865 		error = ENOENT;
866 		goto bad;
867 	}
868 	/*
869 	 * If we're looking up the last component and we need an exclusive
870 	 * lock, adjust our lkflags.
871 	 */
872 	if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags))
873 		cnp->cn_lkflags = LK_EXCLUSIVE;
874 #ifdef NAMEI_DIAGNOSTIC
875 	vn_printf(dp, "lookup in ");
876 #endif
877 	lkflags_save = cnp->cn_lkflags;
878 	cnp->cn_lkflags = compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags,
879 	    cnp->cn_flags);
880 	error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp);
881 	cnp->cn_lkflags = lkflags_save;
882 	if (error != 0) {
883 		KASSERT(ndp->ni_vp == NULL, ("leaf should be empty"));
884 #ifdef NAMEI_DIAGNOSTIC
885 		printf("not found\n");
886 #endif
887 		if ((error == ENOENT) &&
888 		    (dp->v_vflag & VV_ROOT) && (dp->v_mount != NULL) &&
889 		    (dp->v_mount->mnt_flag & MNT_UNION)) {
890 			tdp = dp;
891 			dp = dp->v_mount->mnt_vnodecovered;
892 			VREF(dp);
893 			vput(tdp);
894 			vn_lock(dp,
895 			    compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags |
896 			    LK_RETRY, cnp->cn_flags));
897 			nameicap_tracker_add(ndp, dp);
898 			goto unionlookup;
899 		}
900 
901 		if (error == ERELOOKUP) {
902 			vref(dp);
903 			ndp->ni_vp = dp;
904 			error = 0;
905 			relookup = 1;
906 			goto good;
907 		}
908 
909 		if (error != EJUSTRETURN)
910 			goto bad;
911 		/*
912 		 * At this point, we know we're at the end of the
913 		 * pathname.  If creating / renaming, we can consider
914 		 * allowing the file or directory to be created / renamed,
915 		 * provided we're not on a read-only filesystem.
916 		 */
917 		if (rdonly) {
918 			error = EROFS;
919 			goto bad;
920 		}
921 		/* trailing slash only allowed for directories */
922 		if ((cnp->cn_flags & TRAILINGSLASH) &&
923 		    !(cnp->cn_flags & WILLBEDIR)) {
924 			error = ENOENT;
925 			goto bad;
926 		}
927 		if ((cnp->cn_flags & LOCKPARENT) == 0)
928 			VOP_UNLOCK(dp, 0);
929 		/*
930 		 * We return with ni_vp NULL to indicate that the entry
931 		 * doesn't currently exist, leaving a pointer to the
932 		 * (possibly locked) directory vnode in ndp->ni_dvp.
933 		 */
934 		if (cnp->cn_flags & SAVESTART) {
935 			ndp->ni_startdir = ndp->ni_dvp;
936 			VREF(ndp->ni_startdir);
937 		}
938 		goto success;
939 	}
940 
941 good:
942 #ifdef NAMEI_DIAGNOSTIC
943 	printf("found\n");
944 #endif
945 	dp = ndp->ni_vp;
946 
947 	/*
948 	 * Check to see if the vnode has been mounted on;
949 	 * if so find the root of the mounted filesystem.
950 	 */
951 	while (dp->v_type == VDIR && (mp = dp->v_mountedhere) &&
952 	       (cnp->cn_flags & NOCROSSMOUNT) == 0) {
953 		if (vfs_busy(mp, 0))
954 			continue;
955 		vput(dp);
956 		if (dp != ndp->ni_dvp)
957 			vput(ndp->ni_dvp);
958 		else
959 			vrele(ndp->ni_dvp);
960 		vrefact(vp_crossmp);
961 		ndp->ni_dvp = vp_crossmp;
962 		error = VFS_ROOT(mp, compute_cn_lkflags(mp, cnp->cn_lkflags,
963 		    cnp->cn_flags), &tdp);
964 		vfs_unbusy(mp);
965 		if (vn_lock(vp_crossmp, LK_SHARED | LK_NOWAIT))
966 			panic("vp_crossmp exclusively locked or reclaimed");
967 		if (error) {
968 			dpunlocked = 1;
969 			goto bad2;
970 		}
971 		ndp->ni_vp = dp = tdp;
972 	}
973 
974 	/*
975 	 * Check for symbolic link
976 	 */
977 	if ((dp->v_type == VLNK) &&
978 	    ((cnp->cn_flags & FOLLOW) || (cnp->cn_flags & TRAILINGSLASH) ||
979 	     *ndp->ni_next == '/')) {
980 		cnp->cn_flags |= ISSYMLINK;
981 		if (dp->v_iflag & VI_DOOMED) {
982 			/*
983 			 * We can't know whether the directory was mounted with
984 			 * NOSYMFOLLOW, so we can't follow safely.
985 			 */
986 			error = ENOENT;
987 			goto bad2;
988 		}
989 		if (dp->v_mount->mnt_flag & MNT_NOSYMFOLLOW) {
990 			error = EACCES;
991 			goto bad2;
992 		}
993 		/*
994 		 * Symlink code always expects an unlocked dvp.
995 		 */
996 		if (ndp->ni_dvp != ndp->ni_vp) {
997 			VOP_UNLOCK(ndp->ni_dvp, 0);
998 			ni_dvp_unlocked = 1;
999 		}
1000 		goto success;
1001 	}
1002 
1003 nextname:
1004 	/*
1005 	 * Not a symbolic link that we will follow.  Continue with the
1006 	 * next component if there is any; otherwise, we're done.
1007 	 */
1008 	KASSERT((cnp->cn_flags & ISLASTCN) || *ndp->ni_next == '/',
1009 	    ("lookup: invalid path state."));
1010 	if (relookup) {
1011 		relookup = 0;
1012 		ndp->ni_pathlen = prev_ni_pathlen;
1013 		ndp->ni_next = prev_ni_next;
1014 		if (ndp->ni_dvp != dp)
1015 			vput(ndp->ni_dvp);
1016 		else
1017 			vrele(ndp->ni_dvp);
1018 		goto dirloop;
1019 	}
1020 	if (cnp->cn_flags & ISDOTDOT) {
1021 		error = nameicap_check_dotdot(ndp, ndp->ni_vp);
1022 		if (error != 0) {
1023 #ifdef KTRACE
1024 			if (KTRPOINT(curthread, KTR_CAPFAIL))
1025 				ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1026 #endif
1027 			goto bad2;
1028 		}
1029 	}
1030 	if (*ndp->ni_next == '/') {
1031 		cnp->cn_nameptr = ndp->ni_next;
1032 		while (*cnp->cn_nameptr == '/') {
1033 			cnp->cn_nameptr++;
1034 			ndp->ni_pathlen--;
1035 		}
1036 		if (ndp->ni_dvp != dp)
1037 			vput(ndp->ni_dvp);
1038 		else
1039 			vrele(ndp->ni_dvp);
1040 		goto dirloop;
1041 	}
1042 	/*
1043 	 * If we're processing a path with a trailing slash,
1044 	 * check that the end result is a directory.
1045 	 */
1046 	if ((cnp->cn_flags & TRAILINGSLASH) && dp->v_type != VDIR) {
1047 		error = ENOTDIR;
1048 		goto bad2;
1049 	}
1050 	/*
1051 	 * Disallow directory write attempts on read-only filesystems.
1052 	 */
1053 	if (rdonly &&
1054 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1055 		error = EROFS;
1056 		goto bad2;
1057 	}
1058 	if (cnp->cn_flags & SAVESTART) {
1059 		ndp->ni_startdir = ndp->ni_dvp;
1060 		VREF(ndp->ni_startdir);
1061 	}
1062 	if (!wantparent) {
1063 		ni_dvp_unlocked = 2;
1064 		if (ndp->ni_dvp != dp)
1065 			vput(ndp->ni_dvp);
1066 		else
1067 			vrele(ndp->ni_dvp);
1068 	} else if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp != dp) {
1069 		VOP_UNLOCK(ndp->ni_dvp, 0);
1070 		ni_dvp_unlocked = 1;
1071 	}
1072 
1073 	if (cnp->cn_flags & AUDITVNODE1)
1074 		AUDIT_ARG_VNODE1(dp);
1075 	else if (cnp->cn_flags & AUDITVNODE2)
1076 		AUDIT_ARG_VNODE2(dp);
1077 
1078 	if ((cnp->cn_flags & LOCKLEAF) == 0)
1079 		VOP_UNLOCK(dp, 0);
1080 success:
1081 	/*
1082 	 * Because of shared lookup we may have the vnode shared locked, but
1083 	 * the caller may want it to be exclusively locked.
1084 	 */
1085 	if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags) &&
1086 	    VOP_ISLOCKED(dp) != LK_EXCLUSIVE) {
1087 		vn_lock(dp, LK_UPGRADE | LK_RETRY);
1088 		if (dp->v_iflag & VI_DOOMED) {
1089 			error = ENOENT;
1090 			goto bad2;
1091 		}
1092 	}
1093 	return (0);
1094 
1095 bad2:
1096 	if (ni_dvp_unlocked != 2) {
1097 		if (dp != ndp->ni_dvp && !ni_dvp_unlocked)
1098 			vput(ndp->ni_dvp);
1099 		else
1100 			vrele(ndp->ni_dvp);
1101 	}
1102 bad:
1103 	if (!dpunlocked)
1104 		vput(dp);
1105 	ndp->ni_vp = NULL;
1106 	return (error);
1107 }
1108 
1109 /*
1110  * relookup - lookup a path name component
1111  *    Used by lookup to re-acquire things.
1112  */
1113 int
relookup(struct vnode * dvp,struct vnode ** vpp,struct componentname * cnp)1114 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
1115 {
1116 	struct vnode *dp = NULL;		/* the directory we are searching */
1117 	int wantparent;			/* 1 => wantparent or lockparent flag */
1118 	int rdonly;			/* lookup read-only flag bit */
1119 	int error = 0;
1120 
1121 	KASSERT(cnp->cn_flags & ISLASTCN,
1122 	    ("relookup: Not given last component."));
1123 	/*
1124 	 * Setup: break out flag bits into variables.
1125 	 */
1126 	wantparent = cnp->cn_flags & (LOCKPARENT|WANTPARENT);
1127 	KASSERT(wantparent, ("relookup: parent not wanted."));
1128 	rdonly = cnp->cn_flags & RDONLY;
1129 	cnp->cn_flags &= ~ISSYMLINK;
1130 	dp = dvp;
1131 	cnp->cn_lkflags = LK_EXCLUSIVE;
1132 	vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
1133 
1134 	/*
1135 	 * Search a new directory.
1136 	 *
1137 	 * The last component of the filename is left accessible via
1138 	 * cnp->cn_nameptr for callers that need the name. Callers needing
1139 	 * the name set the SAVENAME flag. When done, they assume
1140 	 * responsibility for freeing the pathname buffer.
1141 	 */
1142 #ifdef NAMEI_DIAGNOSTIC
1143 	printf("{%s}: ", cnp->cn_nameptr);
1144 #endif
1145 
1146 	/*
1147 	 * Check for "" which represents the root directory after slash
1148 	 * removal.
1149 	 */
1150 	if (cnp->cn_nameptr[0] == '\0') {
1151 		/*
1152 		 * Support only LOOKUP for "/" because lookup()
1153 		 * can't succeed for CREATE, DELETE and RENAME.
1154 		 */
1155 		KASSERT(cnp->cn_nameiop == LOOKUP, ("nameiop must be LOOKUP"));
1156 		KASSERT(dp->v_type == VDIR, ("dp is not a directory"));
1157 
1158 		if (!(cnp->cn_flags & LOCKLEAF))
1159 			VOP_UNLOCK(dp, 0);
1160 		*vpp = dp;
1161 		/* XXX This should probably move to the top of function. */
1162 		if (cnp->cn_flags & SAVESTART)
1163 			panic("lookup: SAVESTART");
1164 		return (0);
1165 	}
1166 
1167 	if (cnp->cn_flags & ISDOTDOT)
1168 		panic ("relookup: lookup on dot-dot");
1169 
1170 	/*
1171 	 * We now have a segment name to search for, and a directory to search.
1172 	 */
1173 #ifdef NAMEI_DIAGNOSTIC
1174 	vn_printf(dp, "search in ");
1175 #endif
1176 	if ((error = VOP_LOOKUP(dp, vpp, cnp)) != 0) {
1177 		KASSERT(*vpp == NULL, ("leaf should be empty"));
1178 		if (error != EJUSTRETURN)
1179 			goto bad;
1180 		/*
1181 		 * If creating and at end of pathname, then can consider
1182 		 * allowing file to be created.
1183 		 */
1184 		if (rdonly) {
1185 			error = EROFS;
1186 			goto bad;
1187 		}
1188 		/* ASSERT(dvp == ndp->ni_startdir) */
1189 		if (cnp->cn_flags & SAVESTART)
1190 			VREF(dvp);
1191 		if ((cnp->cn_flags & LOCKPARENT) == 0)
1192 			VOP_UNLOCK(dp, 0);
1193 		/*
1194 		 * We return with ni_vp NULL to indicate that the entry
1195 		 * doesn't currently exist, leaving a pointer to the
1196 		 * (possibly locked) directory vnode in ndp->ni_dvp.
1197 		 */
1198 		return (0);
1199 	}
1200 
1201 	dp = *vpp;
1202 
1203 	/*
1204 	 * Disallow directory write attempts on read-only filesystems.
1205 	 */
1206 	if (rdonly &&
1207 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1208 		if (dvp == dp)
1209 			vrele(dvp);
1210 		else
1211 			vput(dvp);
1212 		error = EROFS;
1213 		goto bad;
1214 	}
1215 	/*
1216 	 * Set the parent lock/ref state to the requested state.
1217 	 */
1218 	if ((cnp->cn_flags & LOCKPARENT) == 0 && dvp != dp) {
1219 		if (wantparent)
1220 			VOP_UNLOCK(dvp, 0);
1221 		else
1222 			vput(dvp);
1223 	} else if (!wantparent)
1224 		vrele(dvp);
1225 	/*
1226 	 * Check for symbolic link
1227 	 */
1228 	KASSERT(dp->v_type != VLNK || !(cnp->cn_flags & FOLLOW),
1229 	    ("relookup: symlink found.\n"));
1230 
1231 	/* ASSERT(dvp == ndp->ni_startdir) */
1232 	if (cnp->cn_flags & SAVESTART)
1233 		VREF(dvp);
1234 
1235 	if ((cnp->cn_flags & LOCKLEAF) == 0)
1236 		VOP_UNLOCK(dp, 0);
1237 	return (0);
1238 bad:
1239 	vput(dp);
1240 	*vpp = NULL;
1241 	return (error);
1242 }
1243 
1244 void
NDINIT_ALL(struct nameidata * ndp,u_long op,u_long flags,enum uio_seg segflg,const char * namep,int dirfd,struct vnode * startdir,cap_rights_t * rightsp,struct thread * td)1245 NDINIT_ALL(struct nameidata *ndp, u_long op, u_long flags, enum uio_seg segflg,
1246     const char *namep, int dirfd, struct vnode *startdir, cap_rights_t *rightsp,
1247     struct thread *td)
1248 {
1249 
1250 	ndp->ni_cnd.cn_nameiop = op;
1251 	ndp->ni_cnd.cn_flags = flags;
1252 	ndp->ni_segflg = segflg;
1253 	ndp->ni_dirp = namep;
1254 	ndp->ni_dirfd = dirfd;
1255 	ndp->ni_startdir = startdir;
1256 	ndp->ni_resflags = 0;
1257 	if (rightsp != NULL)
1258 		ndp->ni_rightsneeded = *rightsp;
1259 	else
1260 		cap_rights_init(&ndp->ni_rightsneeded);
1261 	filecaps_init(&ndp->ni_filecaps);
1262 	ndp->ni_cnd.cn_thread = td;
1263 }
1264 
1265 /*
1266  * Free data allocated by namei(); see namei(9) for details.
1267  */
1268 void
NDFREE(struct nameidata * ndp,const u_int flags)1269 NDFREE(struct nameidata *ndp, const u_int flags)
1270 {
1271 	int unlock_dvp;
1272 	int unlock_vp;
1273 
1274 	unlock_dvp = 0;
1275 	unlock_vp = 0;
1276 
1277 	if (!(flags & NDF_NO_FREE_PNBUF) &&
1278 	    (ndp->ni_cnd.cn_flags & HASBUF)) {
1279 		uma_zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
1280 		ndp->ni_cnd.cn_flags &= ~HASBUF;
1281 	}
1282 	if (!(flags & NDF_NO_VP_UNLOCK) &&
1283 	    (ndp->ni_cnd.cn_flags & LOCKLEAF) && ndp->ni_vp)
1284 		unlock_vp = 1;
1285 	if (!(flags & NDF_NO_DVP_UNLOCK) &&
1286 	    (ndp->ni_cnd.cn_flags & LOCKPARENT) &&
1287 	    ndp->ni_dvp != ndp->ni_vp)
1288 		unlock_dvp = 1;
1289 	if (!(flags & NDF_NO_VP_RELE) && ndp->ni_vp) {
1290 		if (unlock_vp) {
1291 			vput(ndp->ni_vp);
1292 			unlock_vp = 0;
1293 		} else
1294 			vrele(ndp->ni_vp);
1295 		ndp->ni_vp = NULL;
1296 	}
1297 	if (unlock_vp)
1298 		VOP_UNLOCK(ndp->ni_vp, 0);
1299 	if (!(flags & NDF_NO_DVP_RELE) &&
1300 	    (ndp->ni_cnd.cn_flags & (LOCKPARENT|WANTPARENT))) {
1301 		if (unlock_dvp) {
1302 			vput(ndp->ni_dvp);
1303 			unlock_dvp = 0;
1304 		} else
1305 			vrele(ndp->ni_dvp);
1306 		ndp->ni_dvp = NULL;
1307 	}
1308 	if (unlock_dvp)
1309 		VOP_UNLOCK(ndp->ni_dvp, 0);
1310 	if (!(flags & NDF_NO_STARTDIR_RELE) &&
1311 	    (ndp->ni_cnd.cn_flags & SAVESTART)) {
1312 		vrele(ndp->ni_startdir);
1313 		ndp->ni_startdir = NULL;
1314 	}
1315 }
1316 
1317 /*
1318  * Determine if there is a suitable alternate filename under the specified
1319  * prefix for the specified path.  If the create flag is set, then the
1320  * alternate prefix will be used so long as the parent directory exists.
1321  * This is used by the various compatibility ABIs so that Linux binaries prefer
1322  * files under /compat/linux for example.  The chosen path (whether under
1323  * the prefix or under /) is returned in a kernel malloc'd buffer pointed
1324  * to by pathbuf.  The caller is responsible for free'ing the buffer from
1325  * the M_TEMP bucket if one is returned.
1326  */
1327 int
kern_alternate_path(struct thread * td,const char * prefix,const char * path,enum uio_seg pathseg,char ** pathbuf,int create,int dirfd)1328 kern_alternate_path(struct thread *td, const char *prefix, const char *path,
1329     enum uio_seg pathseg, char **pathbuf, int create, int dirfd)
1330 {
1331 	struct nameidata nd, ndroot;
1332 	char *ptr, *buf, *cp;
1333 	size_t len, sz;
1334 	int error;
1335 
1336 	buf = (char *) malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1337 	*pathbuf = buf;
1338 
1339 	/* Copy the prefix into the new pathname as a starting point. */
1340 	len = strlcpy(buf, prefix, MAXPATHLEN);
1341 	if (len >= MAXPATHLEN) {
1342 		*pathbuf = NULL;
1343 		free(buf, M_TEMP);
1344 		return (EINVAL);
1345 	}
1346 	sz = MAXPATHLEN - len;
1347 	ptr = buf + len;
1348 
1349 	/* Append the filename to the prefix. */
1350 	if (pathseg == UIO_SYSSPACE)
1351 		error = copystr(path, ptr, sz, &len);
1352 	else
1353 		error = copyinstr(path, ptr, sz, &len);
1354 
1355 	if (error) {
1356 		*pathbuf = NULL;
1357 		free(buf, M_TEMP);
1358 		return (error);
1359 	}
1360 
1361 	/* Only use a prefix with absolute pathnames. */
1362 	if (*ptr != '/') {
1363 		error = EINVAL;
1364 		goto keeporig;
1365 	}
1366 
1367 	if (dirfd != AT_FDCWD) {
1368 		/*
1369 		 * We want the original because the "prefix" is
1370 		 * included in the already opened dirfd.
1371 		 */
1372 		bcopy(ptr, buf, len);
1373 		return (0);
1374 	}
1375 
1376 	/*
1377 	 * We know that there is a / somewhere in this pathname.
1378 	 * Search backwards for it, to find the file's parent dir
1379 	 * to see if it exists in the alternate tree. If it does,
1380 	 * and we want to create a file (cflag is set). We don't
1381 	 * need to worry about the root comparison in this case.
1382 	 */
1383 
1384 	if (create) {
1385 		for (cp = &ptr[len] - 1; *cp != '/'; cp--);
1386 		*cp = '\0';
1387 
1388 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, buf, td);
1389 		error = namei(&nd);
1390 		*cp = '/';
1391 		if (error != 0)
1392 			goto keeporig;
1393 	} else {
1394 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, buf, td);
1395 
1396 		error = namei(&nd);
1397 		if (error != 0)
1398 			goto keeporig;
1399 
1400 		/*
1401 		 * We now compare the vnode of the prefix to the one
1402 		 * vnode asked. If they resolve to be the same, then we
1403 		 * ignore the match so that the real root gets used.
1404 		 * This avoids the problem of traversing "../.." to find the
1405 		 * root directory and never finding it, because "/" resolves
1406 		 * to the emulation root directory. This is expensive :-(
1407 		 */
1408 		NDINIT(&ndroot, LOOKUP, FOLLOW, UIO_SYSSPACE, prefix,
1409 		    td);
1410 
1411 		/* We shouldn't ever get an error from this namei(). */
1412 		error = namei(&ndroot);
1413 		if (error == 0) {
1414 			if (nd.ni_vp == ndroot.ni_vp)
1415 				error = ENOENT;
1416 
1417 			NDFREE(&ndroot, NDF_ONLY_PNBUF);
1418 			vrele(ndroot.ni_vp);
1419 		}
1420 	}
1421 
1422 	NDFREE(&nd, NDF_ONLY_PNBUF);
1423 	vrele(nd.ni_vp);
1424 
1425 keeporig:
1426 	/* If there was an error, use the original path name. */
1427 	if (error)
1428 		bcopy(ptr, buf, len);
1429 	return (error);
1430 }
1431