xref: /freebsd/sys/kern/vfs_lookup.c (revision 2f60984053e5a91e2cfb45e424129297859fb11d)
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 
37 #include <sys/cdefs.h>
38 #include "opt_capsicum.h"
39 #include "opt_ktrace.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/dirent.h>
44 #include <sys/kernel.h>
45 #include <sys/capsicum.h>
46 #include <sys/fcntl.h>
47 #include <sys/jail.h>
48 #include <sys/lock.h>
49 #include <sys/mutex.h>
50 #include <sys/namei.h>
51 #include <sys/vnode.h>
52 #include <sys/mount.h>
53 #include <sys/filedesc.h>
54 #include <sys/proc.h>
55 #include <sys/sdt.h>
56 #include <sys/syscallsubr.h>
57 #include <sys/sysctl.h>
58 #ifdef KTRACE
59 #include <sys/ktrace.h>
60 #endif
61 #ifdef INVARIANTS
62 #include <machine/_inttypes.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 #ifdef INVARIANTS
71 static void NDVALIDATE_impl(struct nameidata *, int);
72 #define NDVALIDATE(ndp) NDVALIDATE_impl(ndp, __LINE__)
73 #else
74 #define NDVALIDATE(ndp)
75 #endif
76 
77 /*
78  * Reset ndp to its original state.
79  */
80 #define	NDRESET(ndp) do {						\
81 	NDREINIT_DBG(ndp);						\
82 	ndp->ni_resflags = 0;						\
83 	ndp->ni_cnd.cn_flags &= ~NAMEI_INTERNAL_FLAGS;			\
84 } while (0)
85 /*
86  * Prepare namei() to restart. Reset components to its original state and set
87  * ISRESTARTED flag which signals the underlying lookup code to change the root
88  * from ABI root to actual root and prevents a further restarts.
89  */
90 #define	NDRESTART(ndp) do {						\
91 	NDRESET(ndp);						\
92 	ndp->ni_cnd.cn_flags |= ISRESTARTED;				\
93 } while (0)
94 
95 #ifdef KTRACE
96 #define	NIKTRCAPFAIL(path)	ktrcapfail(CAPFAIL_NAMEI, (path))
97 #else
98 #define	NIKTRCAPFAIL(path)
99 #endif
100 
101 #define	NI_CAP_VIOLATION(ndp, path)	do {			\
102 	NIKTRCAPFAIL(path);					\
103 	(ndp)->ni_lcf &= ~NI_LCF_KTR_FLAGS;			\
104 } while (0)
105 
106 SDT_PROVIDER_DEFINE(vfs);
107 SDT_PROBE_DEFINE4(vfs, namei, lookup, entry, "struct vnode *", "char *",
108     "unsigned long", "bool");
109 SDT_PROBE_DEFINE4(vfs, namei, lookup, return, "int", "struct vnode *", "bool",
110     "struct nameidata");
111 
112 /* Allocation zone for namei. */
113 uma_zone_t namei_zone;
114 
115 /* Placeholder vnode for mp traversal. */
116 static struct vnode *vp_crossmp;
117 
118 static int
crossmp_vop_islocked(struct vop_islocked_args * ap)119 crossmp_vop_islocked(struct vop_islocked_args *ap)
120 {
121 
122 	return (LK_SHARED);
123 }
124 
125 static int
crossmp_vop_lock1(struct vop_lock1_args * ap)126 crossmp_vop_lock1(struct vop_lock1_args *ap)
127 {
128 	struct vnode *vp;
129 	struct lock *lk __diagused;
130 	int flags;
131 
132 	vp = ap->a_vp;
133 	lk = vp->v_vnlock;
134 	flags = ap->a_flags;
135 
136 	KASSERT((flags & (LK_SHARED | LK_NOWAIT)) == (LK_SHARED | LK_NOWAIT),
137 	    ("%s: invalid lock request 0x%x for crossmp", __func__, flags));
138 
139 	if ((flags & LK_INTERLOCK) != 0)
140 		VI_UNLOCK(vp);
141 	LOCK_LOG_LOCK("SLOCK", &lk->lock_object, 0, 0, ap->a_file, ap->a_line);
142 	return (0);
143 }
144 
145 static int
crossmp_vop_unlock(struct vop_unlock_args * ap)146 crossmp_vop_unlock(struct vop_unlock_args *ap)
147 {
148 	struct vnode *vp;
149 	struct lock *lk __diagused;
150 
151 	vp = ap->a_vp;
152 	lk = vp->v_vnlock;
153 
154 	LOCK_LOG_LOCK("SUNLOCK", &lk->lock_object, 0, 0, LOCK_FILE,
155 	    LOCK_LINE);
156 	return (0);
157 }
158 
159 static struct vop_vector crossmp_vnodeops = {
160 	.vop_default =		&default_vnodeops,
161 	.vop_islocked =		crossmp_vop_islocked,
162 	.vop_lock1 =		crossmp_vop_lock1,
163 	.vop_unlock =		crossmp_vop_unlock,
164 };
165 /*
166  * VFS_VOP_VECTOR_REGISTER(crossmp_vnodeops) is not used here since the vnode
167  * gets allocated early. See nameiinit for the direct call below.
168  */
169 
170 struct nameicap_tracker {
171 	TAILQ_ENTRY(nameicap_tracker) nm_link;
172 	struct mount *mp;
173 };
174 
175 /* Zone for cap mode tracker elements used for dotdot capability checks. */
176 MALLOC_DEFINE(M_NAMEITRACKER, "namei_tracker", "namei tracking for dotdot");
177 
178 static void
nameiinit(void * dummy __unused)179 nameiinit(void *dummy __unused)
180 {
181 
182 	namei_zone = uma_zcreate("NAMEI", MAXPATHLEN, NULL, NULL, NULL, NULL,
183 	    UMA_ALIGN_PTR, 0);
184 	vfs_vector_op_register(&crossmp_vnodeops);
185 	getnewvnode("crossmp", NULL, &crossmp_vnodeops, &vp_crossmp);
186 	vp_crossmp->v_state = VSTATE_CONSTRUCTED;
187 	vp_crossmp->v_irflag |= VIRF_CROSSMP;
188 }
189 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nameiinit, NULL);
190 
191 static int lookup_cap_dotdot = 1;
192 SYSCTL_INT(_vfs, OID_AUTO, lookup_cap_dotdot, CTLFLAG_RWTUN,
193     &lookup_cap_dotdot, 0,
194     "enables \"..\" components in path lookup in capability mode");
195 static int lookup_cap_dotdot_nonlocal = 1;
196 SYSCTL_INT(_vfs, OID_AUTO, lookup_cap_dotdot_nonlocal, CTLFLAG_RWTUN,
197     &lookup_cap_dotdot_nonlocal, 0,
198     "enables \"..\" components in path lookup in capability mode "
199     "on non-local mount");
200 
201 static int
nameicap_tracker_add(struct nameidata * ndp,struct vnode * dp)202 nameicap_tracker_add(struct nameidata *ndp, struct vnode *dp)
203 {
204 	struct nameicap_tracker *nt;
205 	struct mount *mp;
206 	int error;
207 
208 	if ((ndp->ni_lcf & NI_LCF_CAP_DOTDOT) == 0 || dp->v_type != VDIR)
209 		return (0);
210 	mp = NULL;
211 	error = VOP_GETWRITEMOUNT(dp, &mp);
212 	if (error != 0)
213 		return (error);
214 	nt = TAILQ_LAST(&ndp->ni_cap_tracker, nameicap_tracker_head);
215 	if (nt != NULL && nt->mp == mp) {
216 		vfs_rel(mp);
217 		return (0);
218 	}
219 	nt = malloc(sizeof(*nt), M_NAMEITRACKER, M_WAITOK);
220 	nt->mp = mp;
221 	error = lockmgr(&mp->mnt_renamelock, LK_SHARED | LK_NOWAIT, 0);
222 	if (error != 0) {
223 		MPASS(ndp->ni_nctrack_mnt == NULL);
224 		ndp->ni_nctrack_mnt = mp;
225 		free(nt, M_NAMEITRACKER);
226 		error = ERESTART;
227 	} else {
228 		TAILQ_INSERT_TAIL(&ndp->ni_cap_tracker, nt, nm_link);
229 	}
230 	return (error);
231 }
232 
233 static void
nameicap_cleanup(struct nameidata * ndp,int error)234 nameicap_cleanup(struct nameidata *ndp, int error)
235 {
236 	struct nameicap_tracker *nt, *nt1;
237 	struct mount *mp;
238 
239 	KASSERT((ndp->ni_nctrack_mnt == NULL &&
240 	    TAILQ_EMPTY(&ndp->ni_cap_tracker)) ||
241 	    (ndp->ni_lcf & NI_LCF_CAP_DOTDOT) != 0,
242 	    ("tracker active and not strictrelative"));
243 
244 	TAILQ_FOREACH_SAFE(nt, &ndp->ni_cap_tracker, nm_link, nt1) {
245 		mp = nt->mp;
246 		lockmgr(&mp->mnt_renamelock, LK_RELEASE, 0);
247 		vfs_rel(mp);
248 		TAILQ_REMOVE(&ndp->ni_cap_tracker, nt, nm_link);
249 		free(nt, M_NAMEITRACKER);
250 	}
251 
252 	mp = ndp->ni_nctrack_mnt;
253 	if (mp != NULL) {
254 		if (error == ERESTART) {
255 			lockmgr(&mp->mnt_renamelock, LK_EXCLUSIVE, 0);
256 			lockmgr(&mp->mnt_renamelock, LK_RELEASE, 0);
257 		}
258 		vfs_rel(mp);
259 		ndp->ni_nctrack_mnt = NULL;
260 	}
261 }
262 
263 /*
264  * For dotdot lookups in capability mode, disallow walking over the
265  * directory no_rbeneath_dpp that was used as the starting point of
266  * the lookup.  Since we take the mnt_renamelocks of all mounts we
267  * ever walked over during lookup, parallel renames are disabled.
268  * This prevents the situation where we circumvent walk over
269  * ni_rbeneath_dpp following dotdots.
270  *
271  * Also allow to force failure of dotdot lookups for non-local
272  * filesystems, where external agents might assist local lookups to
273  * escape the compartment.
274  */
275 static int
nameicap_check_dotdot(struct nameidata * ndp,struct vnode * dp)276 nameicap_check_dotdot(struct nameidata *ndp, struct vnode *dp)
277 {
278 	struct mount *mp;
279 
280 	if (dp == NULL || dp->v_type != VDIR || (ndp->ni_lcf &
281 	    NI_LCF_STRICTREL) == 0)
282 		return (0);
283 	if (__predict_false((ndp->ni_lcf & (NI_LCF_STRICTREL_KTR |
284 	    NI_LCF_CAP_DOTDOT_KTR)) == NI_LCF_STRICTREL_KTR))
285 		NI_CAP_VIOLATION(ndp, ndp->ni_cnd.cn_pnbuf);
286 	if ((ndp->ni_lcf & NI_LCF_CAP_DOTDOT) == 0)
287 		goto violation;
288 	if (dp == ndp->ni_rbeneath_dpp)
289 		goto violation;
290 	mp = dp->v_mount;
291 	if (lookup_cap_dotdot_nonlocal == 0 && mp != NULL &&
292 	    (mp->mnt_flag & MNT_LOCAL) == 0)
293 		goto violation;
294 	return (0);
295 
296 violation:
297 	if (__predict_false((ndp->ni_lcf & NI_LCF_STRICTREL_KTR) != 0))
298 		NI_CAP_VIOLATION(ndp, ndp->ni_cnd.cn_pnbuf);
299 	return (ENOTCAPABLE);
300 }
301 
302 static void
namei_cleanup_cnp(struct componentname * cnp)303 namei_cleanup_cnp(struct componentname *cnp)
304 {
305 
306 	uma_zfree(namei_zone, cnp->cn_pnbuf);
307 	cnp->cn_pnbuf = NULL;
308 	cnp->cn_nameptr = NULL;
309 }
310 
311 static int
namei_handle_root(struct nameidata * ndp,struct vnode ** dpp)312 namei_handle_root(struct nameidata *ndp, struct vnode **dpp)
313 {
314 	struct componentname *cnp;
315 
316 	cnp = &ndp->ni_cnd;
317 	if (__predict_false((ndp->ni_lcf & (NI_LCF_STRICTREL |
318 	    NI_LCF_STRICTREL_KTR)) != 0)) {
319 		if ((ndp->ni_lcf & NI_LCF_STRICTREL_KTR) != 0)
320 			NI_CAP_VIOLATION(ndp, cnp->cn_pnbuf);
321 		if ((ndp->ni_lcf & NI_LCF_STRICTREL) != 0)
322 			return (ENOTCAPABLE);
323 	}
324 	while (*(cnp->cn_nameptr) == '/') {
325 		cnp->cn_nameptr++;
326 		ndp->ni_pathlen--;
327 	}
328 	*dpp = ndp->ni_rootdir;
329 	vrefact(*dpp);
330 	return (0);
331 }
332 
333 static int
namei_setup(struct nameidata * ndp,struct vnode ** dpp,struct pwd ** pwdp)334 namei_setup(struct nameidata *ndp, struct vnode **dpp, struct pwd **pwdp)
335 {
336 	struct componentname *cnp;
337 	struct thread *td;
338 	struct pwd *pwd;
339 	int error;
340 	bool startdir_used;
341 
342 	cnp = &ndp->ni_cnd;
343 	td = curthread;
344 
345 	startdir_used = false;
346 	*pwdp = NULL;
347 	*dpp = NULL;
348 
349 #ifdef CAPABILITY_MODE
350 	/*
351 	 * In capability mode, lookups must be restricted to happen in
352 	 * the subtree with the root specified by the file descriptor:
353 	 * - The root must be real file descriptor, not the pseudo-descriptor
354 	 *   AT_FDCWD.
355 	 * - The passed path must be relative and not absolute.
356 	 * - If lookup_cap_dotdot is disabled, path must not contain the
357 	 *   '..' components.
358 	 * - If lookup_cap_dotdot is enabled, we verify that all '..'
359 	 *   components lookups result in the directories which were
360 	 *   previously walked by us, which prevents an escape from
361 	 *   the relative root.
362 	 */
363 	if ((cnp->cn_flags & NOCAPCHECK) == 0) {
364 		if (CAP_TRACING(td)) {
365 			ndp->ni_lcf |= NI_LCF_STRICTREL_KTR;
366 			if (ndp->ni_dirfd == AT_FDCWD)
367 				NI_CAP_VIOLATION(ndp, "AT_FDCWD");
368 		}
369 		if (IN_CAPABILITY_MODE(td)) {
370 			ndp->ni_lcf |= NI_LCF_STRICTREL;
371 			ndp->ni_resflags |= NIRES_STRICTREL;
372 			if (ndp->ni_dirfd == AT_FDCWD)
373 				return (ECAPMODE);
374 		}
375 	}
376 #endif
377 	error = 0;
378 
379 	/*
380 	 * Get starting point for the translation.
381 	 */
382 	pwd = pwd_hold(td);
383 	/*
384 	 * The reference on ni_rootdir is acquired in the block below to avoid
385 	 * back-to-back atomics for absolute lookups.
386 	 */
387 	namei_setup_rootdir(ndp, cnp, pwd);
388 	ndp->ni_topdir = pwd->pwd_jdir;
389 
390 	if (cnp->cn_pnbuf[0] == '/') {
391 		ndp->ni_resflags |= NIRES_ABS;
392 		error = namei_handle_root(ndp, dpp);
393 	} else {
394 		if (ndp->ni_startdir != NULL) {
395 			*dpp = ndp->ni_startdir;
396 			startdir_used = true;
397 		} else if (ndp->ni_dirfd == AT_FDCWD) {
398 			*dpp = pwd->pwd_cdir;
399 			vrefact(*dpp);
400 		} else {
401 			if (cnp->cn_flags & AUDITVNODE1)
402 				AUDIT_ARG_ATFD1(ndp->ni_dirfd);
403 			if (cnp->cn_flags & AUDITVNODE2)
404 				AUDIT_ARG_ATFD2(ndp->ni_dirfd);
405 
406 			error = fgetvp_lookup(ndp, dpp);
407 		}
408 		if (error == 0 && (*dpp)->v_type != VDIR &&
409 		    (cnp->cn_flags & OPENNAMED) == 0 &&
410 		    (cnp->cn_pnbuf[0] != '\0' ||
411 		    (cnp->cn_flags & EMPTYPATH) == 0))
412 			error = ENOTDIR;
413 	}
414 	if (error == 0 && (cnp->cn_flags & RBENEATH) != 0) {
415 		if (cnp->cn_pnbuf[0] == '/') {
416 			error = ENOTCAPABLE;
417 		} else if ((ndp->ni_lcf & NI_LCF_STRICTREL) == 0) {
418 			ndp->ni_lcf |= NI_LCF_STRICTREL |
419 			    NI_LCF_CAP_DOTDOT;
420 		}
421 	}
422 	if (error == 0 && (ndp->ni_lcf & NI_LCF_STRICTREL) != 0)
423 		ndp->ni_rbeneath_dpp = *dpp;
424 
425 	/*
426 	 * If we are auditing the kernel pathname, save the user pathname.
427 	 */
428 	if (AUDITING_TD(td)) {
429 		if (cnp->cn_flags & AUDITVNODE1)
430 			AUDIT_ARG_UPATH1_VP(td, ndp->ni_rootdir, *dpp, cnp->cn_pnbuf);
431 		if (cnp->cn_flags & AUDITVNODE2)
432 			AUDIT_ARG_UPATH2_VP(td, ndp->ni_rootdir, *dpp, cnp->cn_pnbuf);
433 	}
434 	if (ndp->ni_startdir != NULL && !startdir_used)
435 		vrele(ndp->ni_startdir);
436 	if (error != 0) {
437 		if (*dpp != NULL)
438 			vrele(*dpp);
439 		pwd_drop(pwd);
440 		return (error);
441 	}
442 	if (lookup_cap_dotdot != 0) {
443 		if ((ndp->ni_lcf & NI_LCF_STRICTREL_KTR) != 0)
444 			ndp->ni_lcf |= NI_LCF_CAP_DOTDOT_KTR;
445 		if ((ndp->ni_lcf & NI_LCF_STRICTREL) != 0)
446 			ndp->ni_lcf |= NI_LCF_CAP_DOTDOT;
447 	}
448 	SDT_PROBE4(vfs, namei, lookup, entry, *dpp, cnp->cn_pnbuf,
449 	    cnp->cn_flags, false);
450 	*pwdp = pwd;
451 	return (0);
452 }
453 
454 static int
namei_getpath(struct nameidata * ndp)455 namei_getpath(struct nameidata *ndp)
456 {
457 	struct componentname *cnp;
458 	int error;
459 
460 	cnp = &ndp->ni_cnd;
461 
462 	/*
463 	 * Get a buffer for the name to be translated, and copy the
464 	 * name into the buffer.
465 	 */
466 	cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
467 	if (ndp->ni_segflg == UIO_SYSSPACE) {
468 		error = copystr(ndp->ni_dirp, cnp->cn_pnbuf, MAXPATHLEN,
469 		    &ndp->ni_pathlen);
470 	} else {
471 		error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf, MAXPATHLEN,
472 		    &ndp->ni_pathlen);
473 	}
474 
475 	return (error);
476 }
477 
478 static int
namei_emptypath(struct nameidata * ndp)479 namei_emptypath(struct nameidata *ndp)
480 {
481 	struct componentname *cnp;
482 	struct pwd *pwd;
483 	struct vnode *dp;
484 	int error;
485 
486 	cnp = &ndp->ni_cnd;
487 	MPASS(*cnp->cn_pnbuf == '\0');
488 	MPASS((cnp->cn_flags & EMPTYPATH) != 0);
489 	MPASS((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) == 0);
490 
491 	ndp->ni_resflags |= NIRES_EMPTYPATH;
492 	error = namei_setup(ndp, &dp, &pwd);
493 	if (error != 0) {
494 		goto errout;
495 	}
496 
497 	/*
498 	 * Usecount on dp already provided by namei_setup.
499 	 */
500 	ndp->ni_vp = dp;
501 	pwd_drop(pwd);
502 	NDVALIDATE(ndp);
503 	if ((cnp->cn_flags & LOCKLEAF) != 0) {
504 		VOP_LOCK(dp, (cnp->cn_flags & LOCKSHARED) != 0 ?
505 		    LK_SHARED : LK_EXCLUSIVE);
506 		if (VN_IS_DOOMED(dp)) {
507 			vput(dp);
508 			error = ENOENT;
509 			goto errout;
510 		}
511 	}
512 	SDT_PROBE4(vfs, namei, lookup, return, 0, ndp->ni_vp, false, ndp);
513 	return (0);
514 
515 errout:
516 	SDT_PROBE4(vfs, namei, lookup, return, error, NULL, false, ndp);
517 	namei_cleanup_cnp(cnp);
518 	return (error);
519 }
520 
521 static int __noinline
namei_follow_link(struct nameidata * ndp)522 namei_follow_link(struct nameidata *ndp)
523 {
524 	char *cp;
525 	struct iovec aiov;
526 	struct uio auio;
527 	struct componentname *cnp;
528 	struct thread *td;
529 	int error, linklen;
530 
531 	error = 0;
532 	cnp = &ndp->ni_cnd;
533 	td = curthread;
534 
535 	if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
536 		error = ELOOP;
537 		goto out;
538 	}
539 #ifdef MAC
540 	if ((cnp->cn_flags & NOMACCHECK) == 0) {
541 		error = mac_vnode_check_readlink(td->td_ucred, ndp->ni_vp);
542 		if (error != 0)
543 			goto out;
544 	}
545 #endif
546 	if (ndp->ni_pathlen > 1)
547 		cp = uma_zalloc(namei_zone, M_WAITOK);
548 	else
549 		cp = cnp->cn_pnbuf;
550 	aiov.iov_base = cp;
551 	aiov.iov_len = MAXPATHLEN;
552 	auio.uio_iov = &aiov;
553 	auio.uio_iovcnt = 1;
554 	auio.uio_offset = 0;
555 	auio.uio_rw = UIO_READ;
556 	auio.uio_segflg = UIO_SYSSPACE;
557 	auio.uio_td = td;
558 	auio.uio_resid = MAXPATHLEN;
559 	error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
560 	if (error != 0) {
561 		if (ndp->ni_pathlen > 1)
562 			uma_zfree(namei_zone, cp);
563 		goto out;
564 	}
565 	linklen = MAXPATHLEN - auio.uio_resid;
566 	if (linklen == 0) {
567 		if (ndp->ni_pathlen > 1)
568 			uma_zfree(namei_zone, cp);
569 		error = ENOENT;
570 		goto out;
571 	}
572 	if (linklen + ndp->ni_pathlen > MAXPATHLEN) {
573 		if (ndp->ni_pathlen > 1)
574 			uma_zfree(namei_zone, cp);
575 		error = ENAMETOOLONG;
576 		goto out;
577 	}
578 	if (ndp->ni_pathlen > 1) {
579 		bcopy(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
580 		uma_zfree(namei_zone, cnp->cn_pnbuf);
581 		cnp->cn_pnbuf = cp;
582 	} else
583 		cnp->cn_pnbuf[linklen] = '\0';
584 	ndp->ni_pathlen += linklen;
585 out:
586 	return (error);
587 }
588 
589 /*
590  * Convert a pathname into a pointer to a locked vnode.
591  *
592  * The FOLLOW flag is set when symbolic links are to be followed
593  * when they occur at the end of the name translation process.
594  * Symbolic links are always followed for all other pathname
595  * components other than the last.
596  *
597  * The segflg defines whether the name is to be copied from user
598  * space or kernel space.
599  *
600  * Overall outline of namei:
601  *
602  *	copy in name
603  *	get starting directory
604  *	while (!done && !error) {
605  *		call lookup to search path.
606  *		if symbolic link, massage name in buffer and continue
607  *	}
608  */
609 int
namei(struct nameidata * ndp)610 namei(struct nameidata *ndp)
611 {
612 	struct vnode *dp;	/* the directory we are searching */
613 	struct componentname *cnp;
614 	struct thread *td;
615 	struct pwd *pwd;
616 	int error;
617 	enum cache_fpl_status status;
618 
619 	cnp = &ndp->ni_cnd;
620 	td = curthread;
621 #ifdef INVARIANTS
622 	KASSERT((ndp->ni_debugflags & NAMEI_DBG_CALLED) == 0,
623 	    ("%s: repeated call to namei without NDREINIT", __func__));
624 	KASSERT(ndp->ni_debugflags == NAMEI_DBG_INITED,
625 	    ("%s: bad debugflags %d", __func__, ndp->ni_debugflags));
626 	ndp->ni_debugflags |= NAMEI_DBG_CALLED;
627 	if (ndp->ni_startdir != NULL)
628 		ndp->ni_debugflags |= NAMEI_DBG_HADSTARTDIR;
629 	if (cnp->cn_flags & FAILIFEXISTS) {
630 		KASSERT(cnp->cn_nameiop == CREATE,
631 		    ("%s: FAILIFEXISTS passed for op %d", __func__, cnp->cn_nameiop));
632 		/*
633 		 * The limitation below is to restrict hairy corner cases.
634 		 */
635 		KASSERT((cnp->cn_flags & (LOCKPARENT | LOCKLEAF)) == LOCKPARENT,
636 		    ("%s: FAILIFEXISTS must be passed with LOCKPARENT and without LOCKLEAF",
637 		    __func__));
638 	}
639 #endif
640 	ndp->ni_cnd.cn_cred = td->td_ucred;
641 	KASSERT(ndp->ni_resflags == 0, ("%s: garbage in ni_resflags: %x",
642 	    __func__, ndp->ni_resflags));
643 	KASSERT(cnp->cn_cred && td->td_proc, ("namei: bad cred/proc"));
644 	KASSERT((cnp->cn_flags & NAMEI_INTERNAL_FLAGS) == 0,
645 	    ("namei: unexpected flags: %#jx",
646 	    (uintmax_t)(cnp->cn_flags & NAMEI_INTERNAL_FLAGS)));
647 	if (cnp->cn_flags & NOCACHE)
648 		KASSERT(cnp->cn_nameiop != LOOKUP,
649 		    ("%s: NOCACHE passed with LOOKUP", __func__));
650 	MPASS(ndp->ni_startdir == NULL || ndp->ni_startdir->v_type == VDIR ||
651 	    ndp->ni_startdir->v_type == VBAD);
652 
653 restart:
654 	ndp->ni_lcf = 0;
655 	ndp->ni_loopcnt = 0;
656 	ndp->ni_vp = NULL;
657 
658 	error = namei_getpath(ndp);
659 	if (__predict_false(error != 0)) {
660 		namei_cleanup_cnp(cnp);
661 		nameicap_cleanup(ndp, error);
662 		SDT_PROBE4(vfs, namei, lookup, return, error, NULL,
663 		    false, ndp);
664 		return (error);
665 	}
666 
667 	cnp->cn_nameptr = cnp->cn_pnbuf;
668 
669 #ifdef KTRACE
670 	if (KTRPOINT(td, KTR_NAMEI)) {
671 		ktrnamei(cnp->cn_pnbuf);
672 	}
673 #endif
674 	TSNAMEI(curthread->td_proc->p_pid, cnp->cn_pnbuf);
675 
676 	/*
677 	 * First try looking up the target without locking any vnodes.
678 	 *
679 	 * We may need to start from scratch or pick up where it left off.
680 	 */
681 	error = cache_fplookup(ndp, &status, &pwd);
682 	switch (status) {
683 	case CACHE_FPL_STATUS_UNSET:
684 		__assert_unreachable();
685 		break;
686 	case CACHE_FPL_STATUS_HANDLED:
687 		if (error == 0)
688 			NDVALIDATE(ndp);
689 		else if (__predict_false(pwd->pwd_adir != pwd->pwd_rdir &&
690 		    (cnp->cn_flags & ISRESTARTED) == 0)) {
691 			namei_cleanup_cnp(cnp);
692 			nameicap_cleanup(ndp, ERESTART);
693 			NDRESTART(ndp);
694 			goto restart;
695 		}
696 		return (error);
697 	case CACHE_FPL_STATUS_PARTIAL:
698 		dp = ndp->ni_startdir;
699 		break;
700 	case CACHE_FPL_STATUS_DESTROYED:
701 		ndp->ni_loopcnt = 0;
702 		error = namei_getpath(ndp);
703 		if (__predict_false(error != 0)) {
704 			namei_cleanup_cnp(cnp);
705 			nameicap_cleanup(ndp, error);
706 			return (error);
707 		}
708 		cnp->cn_nameptr = cnp->cn_pnbuf;
709 		/* FALLTHROUGH */
710 	case CACHE_FPL_STATUS_ABORTED:
711 		MPASS(ndp->ni_lcf == 0);
712 		if (*cnp->cn_pnbuf == '\0') {
713 			if ((cnp->cn_flags & EMPTYPATH) != 0) {
714 				error = namei_emptypath(ndp);
715 				nameicap_cleanup(ndp, error);
716 				return (error);
717 			}
718 			namei_cleanup_cnp(cnp);
719 			nameicap_cleanup(ndp, ENOENT);
720 			SDT_PROBE4(vfs, namei, lookup, return, ENOENT, NULL,
721 			    false, ndp);
722 			return (ENOENT);
723 		}
724 		error = namei_setup(ndp, &dp, &pwd);
725 		if (error != 0) {
726 			namei_cleanup_cnp(cnp);
727 			nameicap_cleanup(ndp, error);
728 			return (error);
729 		}
730 		break;
731 	}
732 
733 	/*
734 	 * Locked lookup.
735 	 */
736 	for (;;) {
737 		ndp->ni_startdir = dp;
738 		error = vfs_lookup(ndp);
739 		if (error != 0) {
740 			uint64_t was_restarted;
741 			bool abi_restart;
742 
743 			was_restarted = ndp->ni_cnd.cn_flags &
744 			    ISRESTARTED;
745 			abi_restart = pwd->pwd_adir != pwd->pwd_rdir &&
746 			    error == ENOENT && was_restarted == 0;
747 			if (error != ERESTART && !abi_restart)
748 				goto out;
749 			nameicap_cleanup(ndp, error);
750 			pwd_drop(pwd);
751 			namei_cleanup_cnp(cnp);
752 			NDRESET(ndp);
753 			if (abi_restart)
754 				was_restarted = ISRESTARTED;
755 			ndp->ni_cnd.cn_flags |= was_restarted;
756 			goto restart;
757 		}
758 
759 		/*
760 		 * If not a symbolic link, we're done.
761 		 */
762 		if ((cnp->cn_flags & ISSYMLINK) == 0) {
763 			SDT_PROBE4(vfs, namei, lookup, return, error,
764 			    ndp->ni_vp, false, ndp);
765 			nameicap_cleanup(ndp, 0);
766 			pwd_drop(pwd);
767 			NDVALIDATE(ndp);
768 			return (0);
769 		}
770 		error = namei_follow_link(ndp);
771 		if (error != 0)
772 			break;
773 		vput(ndp->ni_vp);
774 		dp = ndp->ni_dvp;
775 		/*
776 		 * Check if root directory should replace current directory.
777 		 */
778 		cnp->cn_nameptr = cnp->cn_pnbuf;
779 		if (*(cnp->cn_nameptr) == '/') {
780 			/*
781 			 * Reset the lookup to start from the real root without
782 			 * origin path name reloading.
783 			 */
784 			if (__predict_false(ndp->ni_rootdir != pwd->pwd_rdir)) {
785 				cnp->cn_flags |= ISRESTARTED;
786 				ndp->ni_rootdir = pwd->pwd_rdir;
787 			}
788 			vrele(dp);
789 			error = namei_handle_root(ndp, &dp);
790 			if (error != 0)
791 				goto out;
792 		}
793 	}
794 	vput(ndp->ni_vp);
795 	ndp->ni_vp = NULL;
796 	vrele(ndp->ni_dvp);
797 out:
798 	MPASS(error != 0 && error != ERESTART);
799 	SDT_PROBE4(vfs, namei, lookup, return, error, NULL, false, ndp);
800 	namei_cleanup_cnp(cnp);
801 	nameicap_cleanup(ndp, error);
802 	pwd_drop(pwd);
803 	return (error);
804 }
805 
806 static int
enforce_lkflags(struct mount * mp,int lkflags)807 enforce_lkflags(struct mount *mp, int lkflags)
808 {
809 
810 	if (mp == NULL || ((lkflags & LK_SHARED) &&
811 	    !(mp->mnt_kern_flag & MNTK_LOOKUP_SHARED))) {
812 		lkflags &= ~LK_SHARED;
813 		lkflags |= LK_EXCLUSIVE;
814 	}
815 	lkflags |= LK_NODDLKTREAT;
816 	return (lkflags);
817 }
818 
819 static __inline int
needs_exclusive_leaf(struct mount * mp,int flags)820 needs_exclusive_leaf(struct mount *mp, int flags)
821 {
822 
823 	/*
824 	 * Intermediate nodes can use shared locks, we only need to
825 	 * force an exclusive lock for leaf nodes.
826 	 */
827 	if ((flags & (ISLASTCN | LOCKLEAF)) != (ISLASTCN | LOCKLEAF))
828 		return (0);
829 
830 	/* Always use exclusive locks if LOCKSHARED isn't set. */
831 	if (!(flags & LOCKSHARED))
832 		return (1);
833 
834 	/*
835 	 * For lookups during open(), if the mount point supports
836 	 * extended shared operations, then use a shared lock for the
837 	 * leaf node, otherwise use an exclusive lock.
838 	 */
839 	if ((flags & ISOPEN) != 0)
840 		return (!MNT_EXTENDED_SHARED(mp));
841 
842 	/*
843 	 * Lookup requests outside of open() that specify LOCKSHARED
844 	 * only need a shared lock on the leaf vnode.
845 	 */
846 	return (0);
847 }
848 
849 /*
850  * Various filesystems expect to be able to copy a name component with length
851  * bounded by NAME_MAX into a directory entry buffer of size MAXNAMLEN.  Make
852  * sure that these are the same size.
853  */
854 _Static_assert(MAXNAMLEN == NAME_MAX,
855     "MAXNAMLEN and NAME_MAX have different values");
856 
857 static int __noinline
vfs_lookup_degenerate(struct nameidata * ndp,struct vnode * dp,int wantparent)858 vfs_lookup_degenerate(struct nameidata *ndp, struct vnode *dp, int wantparent)
859 {
860 	struct componentname *cnp;
861 	struct mount *mp;
862 	int error;
863 
864 	cnp = &ndp->ni_cnd;
865 
866 	cnp->cn_flags |= ISLASTCN;
867 
868 	mp = atomic_load_ptr(&dp->v_mount);
869 	if (needs_exclusive_leaf(mp, cnp->cn_flags)) {
870 		cnp->cn_lkflags &= ~LK_SHARED;
871 		cnp->cn_lkflags |= LK_EXCLUSIVE;
872 	}
873 
874 	vn_lock(dp, enforce_lkflags(mp, cnp->cn_lkflags | LK_RETRY));
875 
876 	if (dp->v_type != VDIR) {
877 		error = ENOTDIR;
878 		goto bad;
879 	}
880 	if (cnp->cn_nameiop != LOOKUP) {
881 		error = EISDIR;
882 		goto bad;
883 	}
884 	if (wantparent) {
885 		ndp->ni_dvp = dp;
886 		VREF(dp);
887 	}
888 	ndp->ni_vp = dp;
889 	cnp->cn_namelen = 0;
890 
891 	if (cnp->cn_flags & AUDITVNODE1)
892 		AUDIT_ARG_VNODE1(dp);
893 	else if (cnp->cn_flags & AUDITVNODE2)
894 		AUDIT_ARG_VNODE2(dp);
895 
896 	if (!(cnp->cn_flags & (LOCKPARENT | LOCKLEAF)))
897 		VOP_UNLOCK(dp);
898 	return (0);
899 bad:
900 	VOP_UNLOCK(dp);
901 	return (error);
902 }
903 
904 struct nameidata *
vfs_lookup_nameidata(struct componentname * cnp)905 vfs_lookup_nameidata(struct componentname *cnp)
906 {
907 	if ((cnp->cn_flags & NAMEILOOKUP) == 0)
908 		return (NULL);
909 	return (__containerof(cnp, struct nameidata, ni_cnd));
910 }
911 
912 /*
913  * Would a dotdot lookup relative to dvp cause this lookup to cross a jail or
914  * chroot boundary?
915  */
916 bool
vfs_lookup_isroot(struct nameidata * ndp,struct vnode * dvp)917 vfs_lookup_isroot(struct nameidata *ndp, struct vnode *dvp)
918 {
919 	for (struct prison *pr = ndp->ni_cnd.cn_cred->cr_prison; pr != NULL;
920 	    pr = pr->pr_parent) {
921 		if (dvp == pr->pr_root)
922 			return (true);
923 	}
924 	return (dvp == ndp->ni_rootdir || dvp == ndp->ni_topdir ||
925 	    dvp == rootvnode);
926 }
927 
928 /*
929  * FAILIFEXISTS handling.
930  *
931  * XXX namei called with LOCKPARENT but not LOCKLEAF has the strange
932  * behaviour of leaving the vnode unlocked if the target is the same
933  * vnode as the parent.
934  */
935 static int __noinline
vfs_lookup_failifexists(struct nameidata * ndp)936 vfs_lookup_failifexists(struct nameidata *ndp)
937 {
938 	struct componentname *cnp __diagused;
939 
940 	cnp = &ndp->ni_cnd;
941 
942 	MPASS((cnp->cn_flags & ISSYMLINK) == 0);
943 	if (ndp->ni_vp == ndp->ni_dvp)
944 		vrele(ndp->ni_dvp);
945 	else
946 		vput(ndp->ni_dvp);
947 	vrele(ndp->ni_vp);
948 	ndp->ni_dvp = NULL;
949 	ndp->ni_vp = NULL;
950 	NDFREE_PNBUF(ndp);
951 	return (EEXIST);
952 }
953 
954 static int __noinline
vfs_lookup_cross_mount(struct nameidata * ndp)955 vfs_lookup_cross_mount(struct nameidata *ndp)
956 {
957 	struct componentname *cnp;
958 	struct mount *mp;
959 	struct vnode *dp, *tdp;
960 	int error, crosslkflags;
961 	bool crosslock;
962 
963 	cnp = &ndp->ni_cnd;
964 	dp = ndp->ni_vp;
965 
966 	/*
967 	 * The vnode has been mounted on, find the root of the mounted
968 	 * filesystem.
969 	 */
970 	do {
971 		mp = dp->v_mountedhere;
972 		ASSERT_VOP_LOCKED(dp, __func__);
973 		VNPASS((vn_irflag_read(dp) & VIRF_MOUNTPOINT) != 0 && mp != NULL, dp);
974 
975 		crosslock = (dp->v_vflag & VV_CROSSLOCK) != 0;
976 		crosslkflags = enforce_lkflags(mp, cnp->cn_lkflags);
977 		if (__predict_false(crosslock)) {
978 			/*
979 			 * We are going to be holding the vnode lock, which
980 			 * in this case is shared by the root vnode of the
981 			 * filesystem mounted at mp, across the call to
982 			 * VFS_ROOT().  Make the situation clear to the
983 			 * filesystem by passing LK_CANRECURSE if the
984 			 * lock is held exclusive, or by clearinng
985 			 * LK_NODDLKTREAT to allow recursion on the shared
986 			 * lock in the presence of an exclusive waiter.
987 			 */
988 			if (VOP_ISLOCKED(dp) == LK_EXCLUSIVE) {
989 				crosslkflags &= ~LK_SHARED;
990 				crosslkflags |= LK_EXCLUSIVE | LK_CANRECURSE;
991 			} else if ((crosslkflags & LK_EXCLUSIVE) != 0) {
992 				error = vn_lock(dp, LK_UPGRADE);
993 				if (error != 0) {
994 					MPASS(error == ENOENT);
995 					vrele(dp);
996 					if (dp != ndp->ni_dvp)
997 						vput(ndp->ni_dvp);
998 					else
999 						vrele(ndp->ni_dvp);
1000 					break;
1001 				}
1002 				if (dp->v_mountedhere != mp) {
1003 					/*
1004 					 * Note that we rely on the
1005 					 * VIRF_MOUNTPOINT loop condition to
1006 					 * ensure we stop iterating if dp is
1007 					 * no longer a mountpoint at all.
1008 					 */
1009 					continue;
1010 				}
1011 			} else
1012 				crosslkflags &= ~LK_NODDLKTREAT;
1013 		}
1014 		if (vfs_busy(mp, 0) != 0)
1015 			continue;
1016 		if (__predict_true(!crosslock))
1017 			vput(dp);
1018 		if (dp != ndp->ni_dvp)
1019 			vput(ndp->ni_dvp);
1020 		else
1021 			vrele(ndp->ni_dvp);
1022 		vrefact(vp_crossmp);
1023 		ndp->ni_dvp = vp_crossmp;
1024 		error = VFS_ROOT(mp, crosslkflags, &tdp);
1025 		vfs_unbusy(mp);
1026 		if (__predict_false(crosslock))
1027 			vput(dp);
1028 		if (vn_lock(vp_crossmp, LK_SHARED | LK_NOWAIT))
1029 			panic("vp_crossmp exclusively locked or reclaimed");
1030 		if (error != 0)
1031 			break;
1032 		ndp->ni_vp = dp = tdp;
1033 	} while ((vn_irflag_read(dp) & VIRF_MOUNTPOINT) != 0);
1034 
1035 	return (error);
1036 }
1037 
1038 /*
1039  * Search a pathname.
1040  * This is a very central and rather complicated routine.
1041  *
1042  * The pathname is pointed to by cn_nameptr and is of length ni_pathlen.
1043  * The starting directory is taken from ni_startdir. The pathname is
1044  * descended until done, or a symbolic link is encountered. The cn_flags
1045  * has ISLASTCN or'ed if the path is completed or ISSYMLINK or'ed if a
1046  * symbolic link needing interpretation is encountered.
1047  *
1048  * The cn_nameiop is LOOKUP, CREATE, RENAME, or DELETE depending on
1049  * whether the name is to be looked up, created, renamed, or deleted.
1050  * When CREATE, RENAME, or DELETE is specified, information usable in
1051  * creating, renaming, or deleting a directory entry may be calculated.
1052  * If cn_flags has LOCKPARENT or'ed into it, the parent directory is returned
1053  * locked. If it has WANTPARENT or'ed into it, the parent directory is
1054  * returned unlocked. Otherwise the parent directory is not returned. If
1055  * the target of the pathname exists and LOCKLEAF is or'ed into the cn_flags
1056  * the target is returned locked, otherwise it is returned unlocked.
1057  *
1058  * Overall outline of lookup:
1059  *
1060  *	handle degenerate case where name is null string
1061  *
1062  * dirloop:
1063  *	identify next component of name at ndp->ni_cnd.cn_nameptr
1064  *	handle .. special cases related to capabilities, chroot, jail
1065  *	if .. and crossing mount points and on mounted filesys, find parent
1066  *	call VOP_LOOKUP routine for next component name
1067  *	    directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
1068  *	    component vnode returned in ni_vp (if it exists), locked.
1069  *	if result vnode is mounted on and crossing mount points,
1070  *	    find mounted on vnode
1071  *	if more components of name, do next level at dirloop
1072  *	if VOP_LOOKUP returns ERELOOKUP, repeat the same level at dirloop
1073  *	return the answer in ni_vp, locked if LOCKLEAF set
1074  *	    if LOCKPARENT set, return locked parent in ni_dvp
1075  *	    if WANTPARENT set, return unlocked parent in ni_dvp
1076  */
1077 int
vfs_lookup(struct nameidata * ndp)1078 vfs_lookup(struct nameidata *ndp)
1079 {
1080 	char *cp;			/* pointer into pathname argument */
1081 	char *prev_ni_next;		/* saved ndp->ni_next */
1082 	char *nulchar;			/* location of '\0' in cn_pnbuf */
1083 	char *lastchar;			/* location of the last character */
1084 	struct vnode *dp = NULL;	/* the directory we are searching */
1085 	struct vnode *tdp;		/* saved dp */
1086 	size_t prev_ni_pathlen;		/* saved ndp->ni_pathlen */
1087 	int docache;			/* == 0 do not cache last component */
1088 	int wantparent;			/* 1 => wantparent or lockparent flag */
1089 	int rdonly;			/* lookup read-only flag bit */
1090 	int error = 0;
1091 	int relookup = 0;		/* do not consume the path component */
1092 	struct componentname *cnp = &ndp->ni_cnd;
1093 	int lkflags_save;
1094 	int ni_dvp_unlocked;
1095 
1096 	/*
1097 	 * Setup: break out flag bits into variables.
1098 	 */
1099 	ni_dvp_unlocked = 0;
1100 	wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
1101 	KASSERT(cnp->cn_nameiop == LOOKUP || wantparent,
1102 	    ("CREATE, DELETE, RENAME require LOCKPARENT or WANTPARENT."));
1103 	/*
1104 	 * When set to zero, docache causes the last component of the
1105 	 * pathname to be deleted from the cache and the full lookup
1106 	 * of the name to be done (via VOP_CACHEDLOOKUP()). Often
1107 	 * filesystems need some pre-computed values that are made
1108 	 * during the full lookup, for instance UFS sets dp->i_offset.
1109 	 *
1110 	 * The docache variable is set to zero when requested by the
1111 	 * NOCACHE flag and for all modifying operations except CREATE.
1112 	 */
1113 	docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
1114 	if (cnp->cn_nameiop == DELETE ||
1115 	    (wantparent && cnp->cn_nameiop != CREATE &&
1116 	     cnp->cn_nameiop != LOOKUP))
1117 		docache = 0;
1118 	rdonly = cnp->cn_flags & RDONLY;
1119 	cnp->cn_flags &= ~ISSYMLINK;
1120 	ndp->ni_dvp = NULL;
1121 
1122 	cnp->cn_lkflags = LK_SHARED;
1123 	dp = ndp->ni_startdir;
1124 	ndp->ni_startdir = NULLVP;
1125 
1126 	/*
1127 	 * Leading slashes, if any, are supposed to be skipped by the caller.
1128 	 */
1129 	MPASS(cnp->cn_nameptr[0] != '/');
1130 
1131 	/*
1132 	 * Check for degenerate name (e.g. / or "") which is a way of talking
1133 	 * about a directory, e.g. like "/." or ".".
1134 	 */
1135 	if (__predict_false(cnp->cn_nameptr[0] == '\0')) {
1136 		error = vfs_lookup_degenerate(ndp, dp, wantparent);
1137 		if (error == 0)
1138 			goto success_right_lock;
1139 		goto bad_unlocked;
1140 	}
1141 
1142 	/*
1143 	 * Nul-out trailing slashes (e.g., "foo///" -> "foo").
1144 	 *
1145 	 * This must be done before VOP_LOOKUP() because some fs's don't know
1146 	 * about trailing slashes.  Remember if there were trailing slashes to
1147 	 * handle symlinks, existing non-directories and non-existing files
1148 	 * that won't be directories specially later.
1149 	 */
1150 	MPASS(ndp->ni_pathlen >= 2);
1151 	lastchar = &cnp->cn_nameptr[ndp->ni_pathlen - 2];
1152 	if (*lastchar == '/') {
1153 		while (lastchar >= cnp->cn_pnbuf) {
1154 			*lastchar = '\0';
1155 			lastchar--;
1156 			ndp->ni_pathlen--;
1157 			if (*lastchar != '/') {
1158 				break;
1159 			}
1160 		}
1161 		cnp->cn_flags |= TRAILINGSLASH;
1162 	}
1163 
1164 	/*
1165 	 * We use shared locks until we hit the parent of the last cn then
1166 	 * we adjust based on the requesting flags.
1167 	 */
1168 	vn_lock(dp,
1169 	    enforce_lkflags(dp->v_mount, cnp->cn_lkflags | LK_RETRY));
1170 
1171 dirloop:
1172 	/*
1173 	 * Search a new directory.
1174 	 *
1175 	 * The last component of the filename is left accessible via
1176 	 * cnp->cn_nameptr. It has to be freed with a call to NDFREE*.
1177 	 *
1178 	 * Store / as a temporary sentinel so that we only have one character
1179 	 * to test for. Pathnames tend to be short so this should not be
1180 	 * resulting in cache misses.
1181 	 */
1182 	nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
1183 	KASSERT(*nulchar == '\0',
1184 	    ("%s: expected nul at %p; string [%s]\n", __func__, nulchar,
1185 	    cnp->cn_pnbuf));
1186 	*nulchar = '/';
1187 	for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
1188 		KASSERT(*cp != '\0',
1189 		    ("%s: encountered unexpected nul; string [%s]\n", __func__,
1190 		    cnp->cn_nameptr));
1191 		continue;
1192 	}
1193 	*nulchar = '\0';
1194 	cnp->cn_namelen = cp - cnp->cn_nameptr;
1195 	if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
1196 		error = ENAMETOOLONG;
1197 		goto bad;
1198 	}
1199 	prev_ni_pathlen = ndp->ni_pathlen;
1200 	ndp->ni_pathlen -= cnp->cn_namelen;
1201 	KASSERT(ndp->ni_pathlen <= PATH_MAX,
1202 	    ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
1203 	prev_ni_next = ndp->ni_next;
1204 	ndp->ni_next = cp;
1205 
1206 	/*
1207 	 * Something else should be clearing this.
1208 	 */
1209 	cnp->cn_flags &= ~(ISDOTDOT|ISLASTCN);
1210 
1211 	cnp->cn_flags |= MAKEENTRY;
1212 	if (*cp == '\0' && docache == 0)
1213 		cnp->cn_flags &= ~MAKEENTRY;
1214 	if (cnp->cn_namelen == 2 &&
1215 	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
1216 		cnp->cn_flags |= ISDOTDOT;
1217 	if (*ndp->ni_next == 0) {
1218 		cnp->cn_flags |= ISLASTCN;
1219 
1220 		if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.' &&
1221 		    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))) {
1222 			error = EINVAL;
1223 			goto bad;
1224 		}
1225 	}
1226 
1227 	error = nameicap_tracker_add(ndp, dp);
1228 	if (error != 0)
1229 		goto bad;
1230 
1231 	/*
1232 	 * Make sure degenerate names don't get here, their handling was
1233 	 * previously found in this spot.
1234 	 */
1235 	MPASS(cnp->cn_nameptr[0] != '\0');
1236 
1237 	/*
1238 	 * Handle "..": five special cases.
1239 	 * 0. If doing a capability lookup and lookup_cap_dotdot is
1240 	 *    disabled, return ENOTCAPABLE.
1241 	 * 1. Return an error if this is the last component of
1242 	 *    the name and the operation is DELETE or RENAME.
1243 	 * 2. If at root directory (e.g. after chroot)
1244 	 *    or at absolute root directory
1245 	 *    then ignore it so can't get out.
1246 	 * 3. If this vnode is the root of a mounted
1247 	 *    filesystem, then replace it with the
1248 	 *    vnode which was mounted on so we take the
1249 	 *    .. in the other filesystem.
1250 	 * 4. If the vnode is the top directory of
1251 	 *    the jail or chroot, don't let them out.
1252 	 * 5. If doing a capability lookup and lookup_cap_dotdot is
1253 	 *    enabled, return ENOTCAPABLE if the lookup would escape
1254 	 *    from the initial file descriptor directory.
1255 	 */
1256 	if (cnp->cn_flags & ISDOTDOT) {
1257 		if (__predict_false((ndp->ni_lcf & (NI_LCF_STRICTREL_KTR |
1258 		    NI_LCF_CAP_DOTDOT_KTR)) == NI_LCF_STRICTREL_KTR))
1259 			NI_CAP_VIOLATION(ndp, cnp->cn_pnbuf);
1260 		if (__predict_false((ndp->ni_lcf & (NI_LCF_STRICTREL |
1261 		    NI_LCF_CAP_DOTDOT)) == NI_LCF_STRICTREL)) {
1262 			error = ENOTCAPABLE;
1263 			goto bad;
1264 		}
1265 		if ((cnp->cn_flags & ISLASTCN) != 0 &&
1266 		    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1267 			error = EINVAL;
1268 			goto bad;
1269 		}
1270 		for (;;) {
1271 			bool isroot;
1272 
1273 			isroot = vfs_lookup_isroot(ndp, dp);
1274 			if (__predict_false(isroot && (ndp->ni_lcf &
1275 			    (NI_LCF_STRICTREL | NI_LCF_STRICTREL_KTR)) != 0)) {
1276 				if ((ndp->ni_lcf & NI_LCF_STRICTREL_KTR) != 0)
1277 					NI_CAP_VIOLATION(ndp, cnp->cn_pnbuf);
1278 				if ((ndp->ni_lcf & NI_LCF_STRICTREL) != 0) {
1279 					error = ENOTCAPABLE;
1280 					goto bad;
1281 				}
1282 			}
1283 			if (isroot || ((dp->v_vflag & VV_ROOT) != 0 &&
1284 			    (cnp->cn_flags & NOCROSSMOUNT) != 0)) {
1285 				ndp->ni_dvp = dp;
1286 				ndp->ni_vp = dp;
1287 				VREF(dp);
1288 				goto nextname;
1289 			}
1290 			if ((dp->v_vflag & VV_ROOT) == 0)
1291 				break;
1292 			if (VN_IS_DOOMED(dp)) {	/* forced unmount */
1293 				error = ENOENT;
1294 				goto bad;
1295 			}
1296 			tdp = dp;
1297 			dp = dp->v_mount->mnt_vnodecovered;
1298 			VREF(dp);
1299 			vput(tdp);
1300 			vn_lock(dp,
1301 			    enforce_lkflags(dp->v_mount, cnp->cn_lkflags |
1302 			    LK_RETRY));
1303 		}
1304 	}
1305 
1306 	/*
1307 	 * We now have a segment name to search for, and a directory to search.
1308 	 */
1309 unionlookup:
1310 #ifdef MAC
1311 	error = mac_vnode_check_lookup(cnp->cn_cred, dp, cnp);
1312 	if (__predict_false(error))
1313 		goto bad;
1314 #endif
1315 	ndp->ni_dvp = dp;
1316 	ndp->ni_vp = NULL;
1317 	ASSERT_VOP_LOCKED(dp, "lookup");
1318 	/*
1319 	 * If we have a shared lock we may need to upgrade the lock for the
1320 	 * last operation.
1321 	 */
1322 	if ((cnp->cn_flags & LOCKPARENT) && (cnp->cn_flags & ISLASTCN) &&
1323 	    dp != vp_crossmp && VOP_ISLOCKED(dp) == LK_SHARED)
1324 		vn_lock(dp, LK_UPGRADE|LK_RETRY);
1325 	if (VN_IS_DOOMED(dp)) {
1326 		error = ENOENT;
1327 		goto bad;
1328 	}
1329 	/*
1330 	 * If we're looking up the last component and we need an exclusive
1331 	 * lock, adjust our lkflags.
1332 	 */
1333 	if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags))
1334 		cnp->cn_lkflags = LK_EXCLUSIVE;
1335 	lkflags_save = cnp->cn_lkflags;
1336 	cnp->cn_lkflags = enforce_lkflags(dp->v_mount, cnp->cn_lkflags);
1337 	error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp);
1338 	cnp->cn_lkflags = lkflags_save;
1339 	if (error != 0) {
1340 		KASSERT(ndp->ni_vp == NULL, ("leaf should be empty"));
1341 		if ((error == ENOENT) &&
1342 		    (dp->v_vflag & VV_ROOT) && (dp->v_mount != NULL) &&
1343 		    (dp->v_mount->mnt_flag & MNT_UNION)) {
1344 			tdp = dp;
1345 			dp = dp->v_mount->mnt_vnodecovered;
1346 			VREF(dp);
1347 			vput(tdp);
1348 			vn_lock(dp,
1349 			    enforce_lkflags(dp->v_mount, cnp->cn_lkflags |
1350 			    LK_RETRY));
1351 			error = nameicap_tracker_add(ndp, dp);
1352 			if (error != 0)
1353 				goto bad;
1354 			goto unionlookup;
1355 		}
1356 
1357 		if (error == ERELOOKUP) {
1358 			vref(dp);
1359 			ndp->ni_vp = dp;
1360 			error = 0;
1361 			relookup = 1;
1362 			goto good;
1363 		}
1364 
1365 		if (error != EJUSTRETURN)
1366 			goto bad;
1367 		/*
1368 		 * At this point, we know we're at the end of the
1369 		 * pathname.  If creating / renaming, we can consider
1370 		 * allowing the file or directory to be created / renamed,
1371 		 * provided we're not on a read-only filesystem.
1372 		 */
1373 		if (rdonly) {
1374 			error = EROFS;
1375 			goto bad;
1376 		}
1377 		/* trailing slash only allowed for directories */
1378 		if ((cnp->cn_flags & TRAILINGSLASH) &&
1379 		    !(cnp->cn_flags & WILLBEDIR)) {
1380 			error = ENOENT;
1381 			goto bad;
1382 		}
1383 		if ((cnp->cn_flags & LOCKPARENT) == 0)
1384 			VOP_UNLOCK(dp);
1385 		/*
1386 		 * We return with ni_vp NULL to indicate that the entry
1387 		 * doesn't currently exist, leaving a pointer to the
1388 		 * (possibly locked) directory vnode in ndp->ni_dvp.
1389 		 */
1390 		goto success;
1391 	}
1392 
1393 good:
1394 	dp = ndp->ni_vp;
1395 
1396 	/*
1397 	 * Check for symbolic link
1398 	 */
1399 	if ((dp->v_type == VLNK) &&
1400 	    ((cnp->cn_flags & FOLLOW) || (cnp->cn_flags & TRAILINGSLASH) ||
1401 	     *ndp->ni_next == '/')) {
1402 		cnp->cn_flags |= ISSYMLINK;
1403 		if (VN_IS_DOOMED(dp)) {
1404 			/*
1405 			 * We can't know whether the directory was mounted with
1406 			 * NOSYMFOLLOW, so we can't follow safely.
1407 			 */
1408 			error = ENOENT;
1409 			goto bad2;
1410 		}
1411 		if (dp->v_mount->mnt_flag & MNT_NOSYMFOLLOW) {
1412 			error = EACCES;
1413 			goto bad2;
1414 		}
1415 		/*
1416 		 * Symlink code always expects an unlocked dvp.
1417 		 */
1418 		if (ndp->ni_dvp != ndp->ni_vp) {
1419 			VOP_UNLOCK(ndp->ni_dvp);
1420 			ni_dvp_unlocked = 1;
1421 		}
1422 		goto success;
1423 	}
1424 
1425 	if ((vn_irflag_read(dp) & VIRF_MOUNTPOINT) != 0 &&
1426 	    (cnp->cn_flags & NOCROSSMOUNT) == 0) {
1427 		error = vfs_lookup_cross_mount(ndp);
1428 		if (error != 0)
1429 			goto bad_unlocked;
1430 		/*
1431 		 * FALLTHROUGH to nextname
1432 		 */
1433 		dp = ndp->ni_vp;
1434 	}
1435 
1436 nextname:
1437 	/*
1438 	 * Not a symbolic link that we will follow.  Continue with the
1439 	 * next component if there is any; otherwise, we're done.
1440 	 */
1441 	KASSERT((cnp->cn_flags & ISLASTCN) || *ndp->ni_next == '/',
1442 	    ("lookup: invalid path state."));
1443 	if (relookup) {
1444 		relookup = 0;
1445 		ndp->ni_pathlen = prev_ni_pathlen;
1446 		ndp->ni_next = prev_ni_next;
1447 		if (ndp->ni_dvp != dp)
1448 			vput(ndp->ni_dvp);
1449 		else
1450 			vrele(ndp->ni_dvp);
1451 		goto dirloop;
1452 	}
1453 	if (cnp->cn_flags & ISDOTDOT) {
1454 		error = nameicap_check_dotdot(ndp, ndp->ni_dvp);
1455 		if (error != 0)
1456 			goto bad2;
1457 	}
1458 	if (*ndp->ni_next == '/') {
1459 		cnp->cn_nameptr = ndp->ni_next;
1460 		while (*cnp->cn_nameptr == '/') {
1461 			cnp->cn_nameptr++;
1462 			ndp->ni_pathlen--;
1463 		}
1464 		if (ndp->ni_dvp != dp)
1465 			vput(ndp->ni_dvp);
1466 		else
1467 			vrele(ndp->ni_dvp);
1468 		goto dirloop;
1469 	}
1470 	/*
1471 	 * If we're processing a path with a trailing slash,
1472 	 * check that the end result is a directory.
1473 	 */
1474 	if ((cnp->cn_flags & TRAILINGSLASH) && dp->v_type != VDIR) {
1475 		error = ENOTDIR;
1476 		goto bad2;
1477 	}
1478 	/*
1479 	 * Disallow directory write attempts on read-only filesystems.
1480 	 */
1481 	if (rdonly &&
1482 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1483 		error = EROFS;
1484 		goto bad2;
1485 	}
1486 	if (!wantparent) {
1487 		ni_dvp_unlocked = 2;
1488 		if (ndp->ni_dvp != dp)
1489 			vput(ndp->ni_dvp);
1490 		else
1491 			vrele(ndp->ni_dvp);
1492 	} else if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp != dp) {
1493 		VOP_UNLOCK(ndp->ni_dvp);
1494 		ni_dvp_unlocked = 1;
1495 	}
1496 
1497 	if (cnp->cn_flags & AUDITVNODE1)
1498 		AUDIT_ARG_VNODE1(dp);
1499 	else if (cnp->cn_flags & AUDITVNODE2)
1500 		AUDIT_ARG_VNODE2(dp);
1501 
1502 	if ((cnp->cn_flags & LOCKLEAF) == 0)
1503 		VOP_UNLOCK(dp);
1504 success:
1505 	/*
1506 	 * FIXME: for lookups which only cross a mount point to fetch the
1507 	 * root vnode, ni_dvp will be set to vp_crossmp. This can be a problem
1508 	 * if either WANTPARENT or LOCKPARENT is set.
1509 	 */
1510 	/*
1511 	 * Because of shared lookup we may have the vnode shared locked, but
1512 	 * the caller may want it to be exclusively locked.
1513 	 */
1514 	if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags) &&
1515 	    VOP_ISLOCKED(dp) != LK_EXCLUSIVE) {
1516 		vn_lock(dp, LK_UPGRADE | LK_RETRY);
1517 		if (VN_IS_DOOMED(dp)) {
1518 			error = ENOENT;
1519 			goto bad2;
1520 		}
1521 	}
1522 success_right_lock:
1523 	if (ndp->ni_vp != NULL) {
1524 		if ((cnp->cn_flags & ISDOTDOT) == 0) {
1525 			error = nameicap_tracker_add(ndp, ndp->ni_vp);
1526 			if (error != 0)
1527 				goto bad2;
1528 		}
1529 		if ((cnp->cn_flags & (FAILIFEXISTS | ISSYMLINK)) == FAILIFEXISTS)
1530 			return (vfs_lookup_failifexists(ndp));
1531 	}
1532 	return (0);
1533 
1534 bad2:
1535 	if (ni_dvp_unlocked != 2) {
1536 		if (dp != ndp->ni_dvp && !ni_dvp_unlocked)
1537 			vput(ndp->ni_dvp);
1538 		else
1539 			vrele(ndp->ni_dvp);
1540 	}
1541 bad:
1542 	vput(dp);
1543 bad_unlocked:
1544 	ndp->ni_vp = NULL;
1545 	return (error);
1546 }
1547 
1548 /*
1549  * relookup - lookup a path name component
1550  *    Used by lookup to re-acquire things.
1551  */
1552 int
vfs_relookup(struct vnode * dvp,struct vnode ** vpp,struct componentname * cnp,bool refstart)1553 vfs_relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1554     bool refstart)
1555 {
1556 	struct vnode *dp = NULL;		/* the directory we are searching */
1557 	int rdonly;			/* lookup read-only flag bit */
1558 	int error = 0;
1559 
1560 	KASSERT(cnp->cn_flags & ISLASTCN,
1561 	    ("relookup: Not given last component."));
1562 	/*
1563 	 * Setup: break out flag bits into variables.
1564 	 */
1565 	KASSERT((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) != 0,
1566 	    ("relookup: parent not wanted"));
1567 	rdonly = cnp->cn_flags & RDONLY;
1568 	cnp->cn_flags &= ~ISSYMLINK;
1569 	dp = dvp;
1570 	cnp->cn_lkflags = LK_EXCLUSIVE;
1571 	vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
1572 
1573 	/*
1574 	 * Search a new directory.
1575 	 *
1576 	 * See a comment in vfs_lookup for cnp->cn_nameptr.
1577 	 *
1578 	 * Check for "" which represents the root directory after slash
1579 	 * removal.
1580 	 */
1581 	if (cnp->cn_nameptr[0] == '\0') {
1582 		/*
1583 		 * Support only LOOKUP for "/" because lookup()
1584 		 * can't succeed for CREATE, DELETE and RENAME.
1585 		 */
1586 		KASSERT(cnp->cn_nameiop == LOOKUP, ("nameiop must be LOOKUP"));
1587 		KASSERT(dp->v_type == VDIR, ("dp is not a directory"));
1588 
1589 		if (!(cnp->cn_flags & LOCKLEAF))
1590 			VOP_UNLOCK(dp);
1591 		*vpp = dp;
1592 		/* XXX This should probably move to the top of function. */
1593 		if (refstart)
1594 			panic("lookup: SAVESTART");
1595 		return (0);
1596 	}
1597 
1598 	if (cnp->cn_flags & ISDOTDOT)
1599 		panic ("relookup: lookup on dot-dot");
1600 
1601 	/*
1602 	 * We now have a segment name to search for, and a directory to search.
1603 	 */
1604 	if ((error = VOP_LOOKUP(dp, vpp, cnp)) != 0) {
1605 		KASSERT(*vpp == NULL, ("leaf should be empty"));
1606 		if (error != EJUSTRETURN)
1607 			goto bad;
1608 		/*
1609 		 * If creating and at end of pathname, then can consider
1610 		 * allowing file to be created.
1611 		 */
1612 		if (rdonly) {
1613 			error = EROFS;
1614 			goto bad;
1615 		}
1616 		/* ASSERT(dvp == ndp->ni_startdir) */
1617 		if (refstart)
1618 			VREF(dvp);
1619 		if ((cnp->cn_flags & LOCKPARENT) == 0)
1620 			VOP_UNLOCK(dp);
1621 		/*
1622 		 * We return with ni_vp NULL to indicate that the entry
1623 		 * doesn't currently exist, leaving a pointer to the
1624 		 * (possibly locked) directory vnode in ndp->ni_dvp.
1625 		 */
1626 		return (0);
1627 	}
1628 
1629 	dp = *vpp;
1630 
1631 	/*
1632 	 * Disallow directory write attempts on read-only filesystems.
1633 	 */
1634 	if (rdonly &&
1635 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1636 		if (dvp == dp)
1637 			vrele(dvp);
1638 		else
1639 			vput(dvp);
1640 		error = EROFS;
1641 		goto bad;
1642 	}
1643 	/*
1644 	 * Set the parent lock/ref state to the requested state.
1645 	 */
1646 	if ((cnp->cn_flags & LOCKPARENT) == 0 && dvp != dp)
1647 		VOP_UNLOCK(dvp);
1648 	/*
1649 	 * Check for symbolic link
1650 	 */
1651 	KASSERT(dp->v_type != VLNK || !(cnp->cn_flags & FOLLOW),
1652 	    ("relookup: symlink found.\n"));
1653 
1654 	/* ASSERT(dvp == ndp->ni_startdir) */
1655 	if (refstart)
1656 		VREF(dvp);
1657 
1658 	if ((cnp->cn_flags & LOCKLEAF) == 0)
1659 		VOP_UNLOCK(dp);
1660 	return (0);
1661 bad:
1662 	vput(dp);
1663 	*vpp = NULL;
1664 	return (error);
1665 }
1666 
1667 #ifdef INVARIANTS
1668 /*
1669  * Validate the final state of ndp after the lookup.
1670  */
1671 static void
NDVALIDATE_impl(struct nameidata * ndp,int line)1672 NDVALIDATE_impl(struct nameidata *ndp, int line)
1673 {
1674 	struct componentname *cnp;
1675 
1676 	cnp = &ndp->ni_cnd;
1677 	if (cnp->cn_pnbuf == NULL)
1678 		panic("%s: got no buf! called from %d", __func__, line);
1679 }
1680 
1681 #endif
1682