2 * SPDX-License-Identifier: BSD-3-Clause
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.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
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.
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
36 * @(#)vfs_lookup.c 8.4 (Berkeley) 2/16/94
39 #include <sys/cdefs.h>
40 #include "opt_capsicum.h"
41 #include "opt_ktrace.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/dirent.h>
46 #include <sys/kernel.h>
47 #include <sys/capsicum.h>
48 #include <sys/fcntl.h>
51 #include <sys/mutex.h>
52 #include <sys/namei.h>
53 #include <sys/vnode.h>
54 #include <sys/mount.h>
55 #include <sys/filedesc.h>
58 #include <sys/syscallsubr.h>
59 #include <sys/sysctl.h>
61 #include <sys/ktrace.h>
64 #include <machine/_inttypes.h>
67 #include <security/audit/audit.h>
68 #include <security/mac/mac_framework.h>
73 static void NDVALIDATE_impl(struct nameidata *, int);
74 #define NDVALIDATE(ndp) NDVALIDATE_impl(ndp, __LINE__)
76 #define NDVALIDATE(ndp)
80 * Prepare namei() to restart. Reset components to its original state and set
81 * ISRESTARTED flag which signals the underlying lookup code to change the root
82 * from ABI root to actual root and prevents a further restarts.
84 #define NDRESTART(ndp) do { \
86 ndp->ni_resflags = 0; \
87 ndp->ni_cnd.cn_flags &= ~NAMEI_INTERNAL_FLAGS; \
88 ndp->ni_cnd.cn_flags |= ISRESTARTED; \
91 SDT_PROVIDER_DEFINE(vfs);
92 SDT_PROBE_DEFINE4(vfs, namei, lookup, entry, "struct vnode *", "char *",
93 "unsigned long", "bool");
94 SDT_PROBE_DEFINE4(vfs, namei, lookup, return, "int", "struct vnode *", "bool",
97 /* Allocation zone for namei. */
98 uma_zone_t namei_zone;
100 /* Placeholder vnode for mp traversal. */
101 static struct vnode *vp_crossmp;
104 crossmp_vop_islocked(struct vop_islocked_args *ap)
111 crossmp_vop_lock1(struct vop_lock1_args *ap)
114 struct lock *lk __diagused;
121 KASSERT((flags & (LK_SHARED | LK_NOWAIT)) == (LK_SHARED | LK_NOWAIT),
122 ("%s: invalid lock request 0x%x for crossmp", __func__, flags));
124 if ((flags & LK_INTERLOCK) != 0)
126 LOCK_LOG_LOCK("SLOCK", &lk->lock_object, 0, 0, ap->a_file, ap->a_line);
131 crossmp_vop_unlock(struct vop_unlock_args *ap)
134 struct lock *lk __diagused;
139 LOCK_LOG_LOCK("SUNLOCK", &lk->lock_object, 0, 0, LOCK_FILE,
144 static struct vop_vector crossmp_vnodeops = {
145 .vop_default = &default_vnodeops,
146 .vop_islocked = crossmp_vop_islocked,
147 .vop_lock1 = crossmp_vop_lock1,
148 .vop_unlock = crossmp_vop_unlock,
151 * VFS_VOP_VECTOR_REGISTER(crossmp_vnodeops) is not used here since the vnode
152 * gets allocated early. See nameiinit for the direct call below.
155 struct nameicap_tracker {
157 TAILQ_ENTRY(nameicap_tracker) nm_link;
160 /* Zone for cap mode tracker elements used for dotdot capability checks. */
161 MALLOC_DEFINE(M_NAMEITRACKER, "namei_tracker", "namei tracking for dotdot");
164 nameiinit(void *dummy __unused)
167 namei_zone = uma_zcreate("NAMEI", MAXPATHLEN, NULL, NULL, NULL, NULL,
169 vfs_vector_op_register(&crossmp_vnodeops);
170 getnewvnode("crossmp", NULL, &crossmp_vnodeops, &vp_crossmp);
171 vp_crossmp->v_state = VSTATE_CONSTRUCTED;
172 vp_crossmp->v_irflag |= VIRF_CROSSMP;
174 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nameiinit, NULL);
176 static int lookup_cap_dotdot = 1;
177 SYSCTL_INT(_vfs, OID_AUTO, lookup_cap_dotdot, CTLFLAG_RWTUN,
178 &lookup_cap_dotdot, 0,
179 "enables \"..\" components in path lookup in capability mode");
180 static int lookup_cap_dotdot_nonlocal = 1;
181 SYSCTL_INT(_vfs, OID_AUTO, lookup_cap_dotdot_nonlocal, CTLFLAG_RWTUN,
182 &lookup_cap_dotdot_nonlocal, 0,
183 "enables \"..\" components in path lookup in capability mode "
184 "on non-local mount");
187 nameicap_tracker_add(struct nameidata *ndp, struct vnode *dp)
189 struct nameicap_tracker *nt;
191 if ((ndp->ni_lcf & NI_LCF_CAP_DOTDOT) == 0 || dp->v_type != VDIR)
193 nt = TAILQ_LAST(&ndp->ni_cap_tracker, nameicap_tracker_head);
194 if (nt != NULL && nt->dp == dp)
196 nt = malloc(sizeof(*nt), M_NAMEITRACKER, M_WAITOK);
199 TAILQ_INSERT_TAIL(&ndp->ni_cap_tracker, nt, nm_link);
203 nameicap_cleanup_from(struct nameidata *ndp, struct nameicap_tracker *first)
205 struct nameicap_tracker *nt, *nt1;
208 TAILQ_FOREACH_FROM_SAFE(nt, &ndp->ni_cap_tracker, nm_link, nt1) {
209 TAILQ_REMOVE(&ndp->ni_cap_tracker, nt, nm_link);
211 free(nt, M_NAMEITRACKER);
216 nameicap_cleanup(struct nameidata *ndp)
218 KASSERT(TAILQ_EMPTY(&ndp->ni_cap_tracker) ||
219 (ndp->ni_lcf & NI_LCF_CAP_DOTDOT) != 0, ("not strictrelative"));
220 nameicap_cleanup_from(ndp, NULL);
224 * For dotdot lookups in capability mode, only allow the component
225 * lookup to succeed if the resulting directory was already traversed
226 * during the operation. This catches situations where already
227 * traversed directory is moved to different parent, and then we walk
228 * over it with dotdots.
230 * Also allow to force failure of dotdot lookups for non-local
231 * filesystems, where external agents might assist local lookups to
232 * escape the compartment.
235 nameicap_check_dotdot(struct nameidata *ndp, struct vnode *dp)
237 struct nameicap_tracker *nt;
240 if (dp == NULL || dp->v_type != VDIR || (ndp->ni_lcf &
241 NI_LCF_STRICTRELATIVE) == 0)
243 if ((ndp->ni_lcf & NI_LCF_CAP_DOTDOT) == 0)
244 return (ENOTCAPABLE);
246 if (lookup_cap_dotdot_nonlocal == 0 && mp != NULL &&
247 (mp->mnt_flag & MNT_LOCAL) == 0)
248 return (ENOTCAPABLE);
249 TAILQ_FOREACH_REVERSE(nt, &ndp->ni_cap_tracker, nameicap_tracker_head,
252 nt = TAILQ_NEXT(nt, nm_link);
254 nameicap_cleanup_from(ndp, nt);
258 return (ENOTCAPABLE);
262 namei_cleanup_cnp(struct componentname *cnp)
265 uma_zfree(namei_zone, cnp->cn_pnbuf);
266 cnp->cn_pnbuf = NULL;
267 cnp->cn_nameptr = NULL;
271 namei_handle_root(struct nameidata *ndp, struct vnode **dpp)
273 struct componentname *cnp;
276 if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) != 0) {
278 if (KTRPOINT(curthread, KTR_CAPFAIL))
279 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
281 return (ENOTCAPABLE);
283 while (*(cnp->cn_nameptr) == '/') {
287 *dpp = ndp->ni_rootdir;
293 namei_setup(struct nameidata *ndp, struct vnode **dpp, struct pwd **pwdp)
295 struct componentname *cnp;
304 startdir_used = false;
308 #ifdef CAPABILITY_MODE
310 * In capability mode, lookups must be restricted to happen in
311 * the subtree with the root specified by the file descriptor:
312 * - The root must be real file descriptor, not the pseudo-descriptor
314 * - The passed path must be relative and not absolute.
315 * - If lookup_cap_dotdot is disabled, path must not contain the
317 * - If lookup_cap_dotdot is enabled, we verify that all '..'
318 * components lookups result in the directories which were
319 * previously walked by us, which prevents an escape from
322 if (IN_CAPABILITY_MODE(td) && (cnp->cn_flags & NOCAPCHECK) == 0) {
323 ndp->ni_lcf |= NI_LCF_STRICTRELATIVE;
324 ndp->ni_resflags |= NIRES_STRICTREL;
325 if (ndp->ni_dirfd == AT_FDCWD) {
327 if (KTRPOINT(td, KTR_CAPFAIL))
328 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
337 * Get starting point for the translation.
341 * The reference on ni_rootdir is acquired in the block below to avoid
342 * back-to-back atomics for absolute lookups.
344 namei_setup_rootdir(ndp, cnp, pwd);
345 ndp->ni_topdir = pwd->pwd_jdir;
347 if (cnp->cn_pnbuf[0] == '/') {
348 ndp->ni_resflags |= NIRES_ABS;
349 error = namei_handle_root(ndp, dpp);
351 if (ndp->ni_startdir != NULL) {
352 *dpp = ndp->ni_startdir;
353 startdir_used = true;
354 } else if (ndp->ni_dirfd == AT_FDCWD) {
355 *dpp = pwd->pwd_cdir;
358 if (cnp->cn_flags & AUDITVNODE1)
359 AUDIT_ARG_ATFD1(ndp->ni_dirfd);
360 if (cnp->cn_flags & AUDITVNODE2)
361 AUDIT_ARG_ATFD2(ndp->ni_dirfd);
363 error = fgetvp_lookup(ndp->ni_dirfd, ndp, dpp);
365 if (error == 0 && (*dpp)->v_type != VDIR &&
366 (cnp->cn_pnbuf[0] != '\0' ||
367 (cnp->cn_flags & EMPTYPATH) == 0))
370 if (error == 0 && (cnp->cn_flags & RBENEATH) != 0) {
371 if (cnp->cn_pnbuf[0] == '/') {
373 } else if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) == 0) {
374 ndp->ni_lcf |= NI_LCF_STRICTRELATIVE |
380 * If we are auditing the kernel pathname, save the user pathname.
382 if (AUDITING_TD(td)) {
383 if (cnp->cn_flags & AUDITVNODE1)
384 AUDIT_ARG_UPATH1_VP(td, ndp->ni_rootdir, *dpp, cnp->cn_pnbuf);
385 if (cnp->cn_flags & AUDITVNODE2)
386 AUDIT_ARG_UPATH2_VP(td, ndp->ni_rootdir, *dpp, cnp->cn_pnbuf);
388 if (ndp->ni_startdir != NULL && !startdir_used)
389 vrele(ndp->ni_startdir);
396 if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) != 0 &&
397 lookup_cap_dotdot != 0)
398 ndp->ni_lcf |= NI_LCF_CAP_DOTDOT;
399 SDT_PROBE4(vfs, namei, lookup, entry, *dpp, cnp->cn_pnbuf,
400 cnp->cn_flags, false);
406 namei_getpath(struct nameidata *ndp)
408 struct componentname *cnp;
414 * Get a buffer for the name to be translated, and copy the
415 * name into the buffer.
417 cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
418 if (ndp->ni_segflg == UIO_SYSSPACE) {
419 error = copystr(ndp->ni_dirp, cnp->cn_pnbuf, MAXPATHLEN,
422 error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf, MAXPATHLEN,
430 namei_emptypath(struct nameidata *ndp)
432 struct componentname *cnp;
438 MPASS(*cnp->cn_pnbuf == '\0');
439 MPASS((cnp->cn_flags & EMPTYPATH) != 0);
440 MPASS((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) == 0);
442 ndp->ni_resflags |= NIRES_EMPTYPATH;
443 error = namei_setup(ndp, &dp, &pwd);
449 * Usecount on dp already provided by namei_setup.
454 if ((cnp->cn_flags & LOCKLEAF) != 0) {
455 VOP_LOCK(dp, (cnp->cn_flags & LOCKSHARED) != 0 ?
456 LK_SHARED : LK_EXCLUSIVE);
457 if (VN_IS_DOOMED(dp)) {
463 SDT_PROBE4(vfs, namei, lookup, return, 0, ndp->ni_vp, false, ndp);
467 SDT_PROBE4(vfs, namei, lookup, return, error, NULL, false, ndp);
468 namei_cleanup_cnp(cnp);
472 static int __noinline
473 namei_follow_link(struct nameidata *ndp)
478 struct componentname *cnp;
486 if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
491 if ((cnp->cn_flags & NOMACCHECK) == 0) {
492 error = mac_vnode_check_readlink(td->td_ucred, ndp->ni_vp);
497 if (ndp->ni_pathlen > 1)
498 cp = uma_zalloc(namei_zone, M_WAITOK);
502 aiov.iov_len = MAXPATHLEN;
503 auio.uio_iov = &aiov;
506 auio.uio_rw = UIO_READ;
507 auio.uio_segflg = UIO_SYSSPACE;
509 auio.uio_resid = MAXPATHLEN;
510 error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
512 if (ndp->ni_pathlen > 1)
513 uma_zfree(namei_zone, cp);
516 linklen = MAXPATHLEN - auio.uio_resid;
518 if (ndp->ni_pathlen > 1)
519 uma_zfree(namei_zone, cp);
523 if (linklen + ndp->ni_pathlen > MAXPATHLEN) {
524 if (ndp->ni_pathlen > 1)
525 uma_zfree(namei_zone, cp);
526 error = ENAMETOOLONG;
529 if (ndp->ni_pathlen > 1) {
530 bcopy(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
531 uma_zfree(namei_zone, cnp->cn_pnbuf);
534 cnp->cn_pnbuf[linklen] = '\0';
535 ndp->ni_pathlen += linklen;
541 * Convert a pathname into a pointer to a locked vnode.
543 * The FOLLOW flag is set when symbolic links are to be followed
544 * when they occur at the end of the name translation process.
545 * Symbolic links are always followed for all other pathname
546 * components other than the last.
548 * The segflg defines whether the name is to be copied from user
549 * space or kernel space.
551 * Overall outline of namei:
554 * get starting directory
555 * while (!done && !error) {
556 * call lookup to search path.
557 * if symbolic link, massage name in buffer and continue
561 namei(struct nameidata *ndp)
563 struct vnode *dp; /* the directory we are searching */
564 struct componentname *cnp;
568 enum cache_fpl_status status;
573 KASSERT((ndp->ni_debugflags & NAMEI_DBG_CALLED) == 0,
574 ("%s: repeated call to namei without NDREINIT", __func__));
575 KASSERT(ndp->ni_debugflags == NAMEI_DBG_INITED,
576 ("%s: bad debugflags %d", __func__, ndp->ni_debugflags));
577 ndp->ni_debugflags |= NAMEI_DBG_CALLED;
578 if (ndp->ni_startdir != NULL)
579 ndp->ni_debugflags |= NAMEI_DBG_HADSTARTDIR;
580 if (cnp->cn_flags & FAILIFEXISTS) {
581 KASSERT(cnp->cn_nameiop == CREATE,
582 ("%s: FAILIFEXISTS passed for op %d", __func__, cnp->cn_nameiop));
584 * The limitation below is to restrict hairy corner cases.
586 KASSERT((cnp->cn_flags & (LOCKPARENT | LOCKLEAF)) == LOCKPARENT,
587 ("%s: FAILIFEXISTS must be passed with LOCKPARENT and without LOCKLEAF",
591 ndp->ni_cnd.cn_cred = td->td_ucred;
592 KASSERT(ndp->ni_resflags == 0, ("%s: garbage in ni_resflags: %x\n",
593 __func__, ndp->ni_resflags));
594 KASSERT(cnp->cn_cred && td->td_proc, ("namei: bad cred/proc"));
595 KASSERT((cnp->cn_flags & NAMEI_INTERNAL_FLAGS) == 0,
596 ("namei: unexpected flags: %" PRIx64 "\n",
597 cnp->cn_flags & NAMEI_INTERNAL_FLAGS));
598 if (cnp->cn_flags & NOCACHE)
599 KASSERT(cnp->cn_nameiop != LOOKUP,
600 ("%s: NOCACHE passed with LOOKUP", __func__));
601 MPASS(ndp->ni_startdir == NULL || ndp->ni_startdir->v_type == VDIR ||
602 ndp->ni_startdir->v_type == VBAD);
609 error = namei_getpath(ndp);
610 if (__predict_false(error != 0)) {
611 namei_cleanup_cnp(cnp);
612 SDT_PROBE4(vfs, namei, lookup, return, error, NULL,
617 cnp->cn_nameptr = cnp->cn_pnbuf;
620 if (KTRPOINT(td, KTR_NAMEI)) {
621 ktrnamei(cnp->cn_pnbuf);
624 TSNAMEI(curthread->td_proc->p_pid, cnp->cn_pnbuf);
627 * First try looking up the target without locking any vnodes.
629 * We may need to start from scratch or pick up where it left off.
631 error = cache_fplookup(ndp, &status, &pwd);
633 case CACHE_FPL_STATUS_UNSET:
634 __assert_unreachable();
636 case CACHE_FPL_STATUS_HANDLED:
639 else if (__predict_false(pwd->pwd_adir != pwd->pwd_rdir &&
640 (cnp->cn_flags & ISRESTARTED) == 0)) {
641 namei_cleanup_cnp(cnp);
646 case CACHE_FPL_STATUS_PARTIAL:
647 TAILQ_INIT(&ndp->ni_cap_tracker);
648 dp = ndp->ni_startdir;
650 case CACHE_FPL_STATUS_DESTROYED:
652 error = namei_getpath(ndp);
653 if (__predict_false(error != 0)) {
654 namei_cleanup_cnp(cnp);
657 cnp->cn_nameptr = cnp->cn_pnbuf;
659 case CACHE_FPL_STATUS_ABORTED:
660 TAILQ_INIT(&ndp->ni_cap_tracker);
661 MPASS(ndp->ni_lcf == 0);
662 if (*cnp->cn_pnbuf == '\0') {
663 if ((cnp->cn_flags & EMPTYPATH) != 0) {
664 return (namei_emptypath(ndp));
666 namei_cleanup_cnp(cnp);
667 SDT_PROBE4(vfs, namei, lookup, return, ENOENT, NULL,
671 error = namei_setup(ndp, &dp, &pwd);
673 namei_cleanup_cnp(cnp);
683 ndp->ni_startdir = dp;
684 error = vfs_lookup(ndp);
686 if (__predict_false(pwd->pwd_adir != pwd->pwd_rdir &&
688 (cnp->cn_flags & ISRESTARTED) == 0)) {
689 nameicap_cleanup(ndp);
691 namei_cleanup_cnp(cnp);
699 * If not a symbolic link, we're done.
701 if ((cnp->cn_flags & ISSYMLINK) == 0) {
702 SDT_PROBE4(vfs, namei, lookup, return, error,
703 ndp->ni_vp, false, ndp);
704 nameicap_cleanup(ndp);
709 error = namei_follow_link(ndp);
715 * Check if root directory should replace current directory.
717 cnp->cn_nameptr = cnp->cn_pnbuf;
718 if (*(cnp->cn_nameptr) == '/') {
720 * Reset the lookup to start from the real root without
721 * origin path name reloading.
723 if (__predict_false(ndp->ni_rootdir != pwd->pwd_rdir)) {
724 cnp->cn_flags |= ISRESTARTED;
725 ndp->ni_rootdir = pwd->pwd_rdir;
728 error = namei_handle_root(ndp, &dp);
738 SDT_PROBE4(vfs, namei, lookup, return, error, NULL, false, ndp);
739 namei_cleanup_cnp(cnp);
740 nameicap_cleanup(ndp);
746 enforce_lkflags(struct mount *mp, int lkflags)
749 if (mp == NULL || ((lkflags & LK_SHARED) &&
750 !(mp->mnt_kern_flag & MNTK_LOOKUP_SHARED))) {
751 lkflags &= ~LK_SHARED;
752 lkflags |= LK_EXCLUSIVE;
754 lkflags |= LK_NODDLKTREAT;
759 needs_exclusive_leaf(struct mount *mp, int flags)
763 * Intermediate nodes can use shared locks, we only need to
764 * force an exclusive lock for leaf nodes.
766 if ((flags & (ISLASTCN | LOCKLEAF)) != (ISLASTCN | LOCKLEAF))
769 /* Always use exclusive locks if LOCKSHARED isn't set. */
770 if (!(flags & LOCKSHARED))
774 * For lookups during open(), if the mount point supports
775 * extended shared operations, then use a shared lock for the
776 * leaf node, otherwise use an exclusive lock.
778 if ((flags & ISOPEN) != 0)
779 return (!MNT_EXTENDED_SHARED(mp));
782 * Lookup requests outside of open() that specify LOCKSHARED
783 * only need a shared lock on the leaf vnode.
789 * Various filesystems expect to be able to copy a name component with length
790 * bounded by NAME_MAX into a directory entry buffer of size MAXNAMLEN. Make
791 * sure that these are the same size.
793 _Static_assert(MAXNAMLEN == NAME_MAX,
794 "MAXNAMLEN and NAME_MAX have different values");
796 static int __noinline
797 vfs_lookup_degenerate(struct nameidata *ndp, struct vnode *dp, int wantparent)
799 struct componentname *cnp;
805 cnp->cn_flags |= ISLASTCN;
807 mp = atomic_load_ptr(&dp->v_mount);
808 if (needs_exclusive_leaf(mp, cnp->cn_flags)) {
809 cnp->cn_lkflags &= ~LK_SHARED;
810 cnp->cn_lkflags |= LK_EXCLUSIVE;
813 vn_lock(dp, enforce_lkflags(mp, cnp->cn_lkflags | LK_RETRY));
815 if (dp->v_type != VDIR) {
819 if (cnp->cn_nameiop != LOOKUP) {
830 if (cnp->cn_flags & AUDITVNODE1)
831 AUDIT_ARG_VNODE1(dp);
832 else if (cnp->cn_flags & AUDITVNODE2)
833 AUDIT_ARG_VNODE2(dp);
835 if (!(cnp->cn_flags & (LOCKPARENT | LOCKLEAF)))
844 * FAILIFEXISTS handling.
846 * XXX namei called with LOCKPARENT but not LOCKLEAF has the strange
847 * behaviour of leaving the vnode unlocked if the target is the same
848 * vnode as the parent.
850 static int __noinline
851 vfs_lookup_failifexists(struct nameidata *ndp)
853 struct componentname *cnp __diagused;
857 MPASS((cnp->cn_flags & ISSYMLINK) == 0);
858 if (ndp->ni_vp == ndp->ni_dvp)
869 static int __noinline
870 vfs_lookup_cross_mount(struct nameidata *ndp)
872 struct componentname *cnp;
874 struct vnode *dp, *tdp;
875 int error, crosslkflags;
882 * The vnode has been mounted on, find the root of the mounted
886 mp = dp->v_mountedhere;
887 ASSERT_VOP_LOCKED(dp, __func__);
888 VNPASS((vn_irflag_read(dp) & VIRF_MOUNTPOINT) != 0 && mp != NULL, dp);
890 crosslock = (dp->v_vflag & VV_CROSSLOCK) != 0;
891 crosslkflags = enforce_lkflags(mp, cnp->cn_lkflags);
892 if (__predict_false(crosslock)) {
894 * We are going to be holding the vnode lock, which
895 * in this case is shared by the root vnode of the
896 * filesystem mounted at mp, across the call to
897 * VFS_ROOT(). Make the situation clear to the
898 * filesystem by passing LK_CANRECURSE if the
899 * lock is held exclusive, or by clearinng
900 * LK_NODDLKTREAT to allow recursion on the shared
901 * lock in the presence of an exclusive waiter.
903 if (VOP_ISLOCKED(dp) == LK_EXCLUSIVE) {
904 crosslkflags &= ~LK_SHARED;
905 crosslkflags |= LK_EXCLUSIVE | LK_CANRECURSE;
906 } else if ((crosslkflags & LK_EXCLUSIVE) != 0) {
907 error = vn_lock(dp, LK_UPGRADE);
910 if (dp->v_mountedhere != mp) {
914 crosslkflags &= ~LK_NODDLKTREAT;
916 if (vfs_busy(mp, 0) != 0)
918 if (__predict_true(!crosslock))
920 if (dp != ndp->ni_dvp)
925 ndp->ni_dvp = vp_crossmp;
926 error = VFS_ROOT(mp, crosslkflags, &tdp);
928 if (__predict_false(crosslock))
930 if (vn_lock(vp_crossmp, LK_SHARED | LK_NOWAIT))
931 panic("vp_crossmp exclusively locked or reclaimed");
934 ndp->ni_vp = dp = tdp;
935 if ((vn_irflag_read(dp) & VIRF_MOUNTPOINT) == 0)
944 * This is a very central and rather complicated routine.
946 * The pathname is pointed to by cn_nameptr and is of length ni_pathlen.
947 * The starting directory is taken from ni_startdir. The pathname is
948 * descended until done, or a symbolic link is encountered. The cn_flags
949 * has ISLASTCN or'ed if the path is completed or ISSYMLINK or'ed if a
950 * symbolic link needing interpretation is encountered.
952 * The cn_nameiop is LOOKUP, CREATE, RENAME, or DELETE depending on
953 * whether the name is to be looked up, created, renamed, or deleted.
954 * When CREATE, RENAME, or DELETE is specified, information usable in
955 * creating, renaming, or deleting a directory entry may be calculated.
956 * If cn_flags has LOCKPARENT or'ed into it, the parent directory is returned
957 * locked. If it has WANTPARENT or'ed into it, the parent directory is
958 * returned unlocked. Otherwise the parent directory is not returned. If
959 * the target of the pathname exists and LOCKLEAF is or'ed into the cn_flags
960 * the target is returned locked, otherwise it is returned unlocked.
962 * Overall outline of lookup:
964 * handle degenerate case where name is null string
967 * identify next component of name at ndp->ni_cnd.cn_nameptr
968 * handle .. special cases related to capabilities, chroot, jail
969 * if .. and crossing mount points and on mounted filesys, find parent
970 * call VOP_LOOKUP routine for next component name
971 * directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
972 * component vnode returned in ni_vp (if it exists), locked.
973 * if result vnode is mounted on and crossing mount points,
974 * find mounted on vnode
975 * if more components of name, do next level at dirloop
976 * if VOP_LOOKUP returns ERELOOKUP, repeat the same level at dirloop
977 * return the answer in ni_vp, locked if LOCKLEAF set
978 * if LOCKPARENT set, return locked parent in ni_dvp
979 * if WANTPARENT set, return unlocked parent in ni_dvp
982 vfs_lookup(struct nameidata *ndp)
984 char *cp; /* pointer into pathname argument */
985 char *prev_ni_next; /* saved ndp->ni_next */
986 char *nulchar; /* location of '\0' in cn_pnbuf */
987 char *lastchar; /* location of the last character */
988 struct vnode *dp = NULL; /* the directory we are searching */
989 struct vnode *tdp; /* saved dp */
991 size_t prev_ni_pathlen; /* saved ndp->ni_pathlen */
992 int docache; /* == 0 do not cache last component */
993 int wantparent; /* 1 => wantparent or lockparent flag */
994 int rdonly; /* lookup read-only flag bit */
996 int relookup = 0; /* do not consume the path component */
997 struct componentname *cnp = &ndp->ni_cnd;
1002 * Setup: break out flag bits into variables.
1004 ni_dvp_unlocked = 0;
1005 wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
1006 KASSERT(cnp->cn_nameiop == LOOKUP || wantparent,
1007 ("CREATE, DELETE, RENAME require LOCKPARENT or WANTPARENT."));
1009 * When set to zero, docache causes the last component of the
1010 * pathname to be deleted from the cache and the full lookup
1011 * of the name to be done (via VOP_CACHEDLOOKUP()). Often
1012 * filesystems need some pre-computed values that are made
1013 * during the full lookup, for instance UFS sets dp->i_offset.
1015 * The docache variable is set to zero when requested by the
1016 * NOCACHE flag and for all modifying operations except CREATE.
1018 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
1019 if (cnp->cn_nameiop == DELETE ||
1020 (wantparent && cnp->cn_nameiop != CREATE &&
1021 cnp->cn_nameiop != LOOKUP))
1023 rdonly = cnp->cn_flags & RDONLY;
1024 cnp->cn_flags &= ~ISSYMLINK;
1027 cnp->cn_lkflags = LK_SHARED;
1028 dp = ndp->ni_startdir;
1029 ndp->ni_startdir = NULLVP;
1032 * Leading slashes, if any, are supposed to be skipped by the caller.
1034 MPASS(cnp->cn_nameptr[0] != '/');
1037 * Check for degenerate name (e.g. / or "") which is a way of talking
1038 * about a directory, e.g. like "/." or ".".
1040 if (__predict_false(cnp->cn_nameptr[0] == '\0')) {
1041 error = vfs_lookup_degenerate(ndp, dp, wantparent);
1043 goto success_right_lock;
1048 * Nul-out trailing slashes (e.g., "foo///" -> "foo").
1050 * This must be done before VOP_LOOKUP() because some fs's don't know
1051 * about trailing slashes. Remember if there were trailing slashes to
1052 * handle symlinks, existing non-directories and non-existing files
1053 * that won't be directories specially later.
1055 MPASS(ndp->ni_pathlen >= 2);
1056 lastchar = &cnp->cn_nameptr[ndp->ni_pathlen - 2];
1057 if (*lastchar == '/') {
1058 while (lastchar >= cnp->cn_pnbuf) {
1062 if (*lastchar != '/') {
1066 cnp->cn_flags |= TRAILINGSLASH;
1070 * We use shared locks until we hit the parent of the last cn then
1071 * we adjust based on the requesting flags.
1074 enforce_lkflags(dp->v_mount, cnp->cn_lkflags | LK_RETRY));
1078 * Search a new directory.
1080 * The last component of the filename is left accessible via
1081 * cnp->cn_nameptr. It has to be freed with a call to NDFREE*.
1083 * Store / as a temporary sentinel so that we only have one character
1084 * to test for. Pathnames tend to be short so this should not be
1085 * resulting in cache misses.
1087 nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
1088 KASSERT(*nulchar == '\0',
1089 ("%s: expected nul at %p; string [%s]\n", __func__, nulchar,
1092 for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
1093 KASSERT(*cp != '\0',
1094 ("%s: encountered unexpected nul; string [%s]\n", __func__,
1099 cnp->cn_namelen = cp - cnp->cn_nameptr;
1100 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
1101 error = ENAMETOOLONG;
1104 prev_ni_pathlen = ndp->ni_pathlen;
1105 ndp->ni_pathlen -= cnp->cn_namelen;
1106 KASSERT(ndp->ni_pathlen <= PATH_MAX,
1107 ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
1108 prev_ni_next = ndp->ni_next;
1112 * Something else should be clearing this.
1114 cnp->cn_flags &= ~(ISDOTDOT|ISLASTCN);
1116 cnp->cn_flags |= MAKEENTRY;
1117 if (*cp == '\0' && docache == 0)
1118 cnp->cn_flags &= ~MAKEENTRY;
1119 if (cnp->cn_namelen == 2 &&
1120 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
1121 cnp->cn_flags |= ISDOTDOT;
1122 if (*ndp->ni_next == 0) {
1123 cnp->cn_flags |= ISLASTCN;
1125 if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.' &&
1126 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))) {
1132 nameicap_tracker_add(ndp, dp);
1135 * Make sure degenerate names don't get here, their handling was
1136 * previously found in this spot.
1138 MPASS(cnp->cn_nameptr[0] != '\0');
1141 * Handle "..": five special cases.
1142 * 0. If doing a capability lookup and lookup_cap_dotdot is
1143 * disabled, return ENOTCAPABLE.
1144 * 1. Return an error if this is the last component of
1145 * the name and the operation is DELETE or RENAME.
1146 * 2. If at root directory (e.g. after chroot)
1147 * or at absolute root directory
1148 * then ignore it so can't get out.
1149 * 3. If this vnode is the root of a mounted
1150 * filesystem, then replace it with the
1151 * vnode which was mounted on so we take the
1152 * .. in the other filesystem.
1153 * 4. If the vnode is the top directory of
1154 * the jail or chroot, don't let them out.
1155 * 5. If doing a capability lookup and lookup_cap_dotdot is
1156 * enabled, return ENOTCAPABLE if the lookup would escape
1157 * from the initial file descriptor directory. Checks are
1158 * done by ensuring that namei() already traversed the
1159 * result of dotdot lookup.
1161 if (cnp->cn_flags & ISDOTDOT) {
1162 if ((ndp->ni_lcf & (NI_LCF_STRICTRELATIVE | NI_LCF_CAP_DOTDOT))
1163 == NI_LCF_STRICTRELATIVE) {
1165 if (KTRPOINT(curthread, KTR_CAPFAIL))
1166 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1168 error = ENOTCAPABLE;
1171 if ((cnp->cn_flags & ISLASTCN) != 0 &&
1172 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1177 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
1179 if (dp == pr->pr_root)
1181 bool isroot = dp == ndp->ni_rootdir ||
1182 dp == ndp->ni_topdir || dp == rootvnode ||
1184 if (isroot && (ndp->ni_lcf &
1185 NI_LCF_STRICTRELATIVE) != 0) {
1186 error = ENOTCAPABLE;
1189 if (isroot || ((dp->v_vflag & VV_ROOT) != 0 &&
1190 (cnp->cn_flags & NOCROSSMOUNT) != 0)) {
1196 if ((dp->v_vflag & VV_ROOT) == 0)
1198 if (VN_IS_DOOMED(dp)) { /* forced unmount */
1203 dp = dp->v_mount->mnt_vnodecovered;
1207 enforce_lkflags(dp->v_mount, cnp->cn_lkflags |
1209 error = nameicap_check_dotdot(ndp, dp);
1213 if (KTRPOINT(curthread, KTR_CAPFAIL))
1214 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1222 * We now have a segment name to search for, and a directory to search.
1226 error = mac_vnode_check_lookup(cnp->cn_cred, dp, cnp);
1227 if (__predict_false(error))
1232 ASSERT_VOP_LOCKED(dp, "lookup");
1234 * If we have a shared lock we may need to upgrade the lock for the
1237 if ((cnp->cn_flags & LOCKPARENT) && (cnp->cn_flags & ISLASTCN) &&
1238 dp != vp_crossmp && VOP_ISLOCKED(dp) == LK_SHARED)
1239 vn_lock(dp, LK_UPGRADE|LK_RETRY);
1240 if (VN_IS_DOOMED(dp)) {
1245 * If we're looking up the last component and we need an exclusive
1246 * lock, adjust our lkflags.
1248 if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags))
1249 cnp->cn_lkflags = LK_EXCLUSIVE;
1250 lkflags_save = cnp->cn_lkflags;
1251 cnp->cn_lkflags = enforce_lkflags(dp->v_mount, cnp->cn_lkflags);
1252 error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp);
1253 cnp->cn_lkflags = lkflags_save;
1255 KASSERT(ndp->ni_vp == NULL, ("leaf should be empty"));
1256 if ((error == ENOENT) &&
1257 (dp->v_vflag & VV_ROOT) && (dp->v_mount != NULL) &&
1258 (dp->v_mount->mnt_flag & MNT_UNION)) {
1260 dp = dp->v_mount->mnt_vnodecovered;
1264 enforce_lkflags(dp->v_mount, cnp->cn_lkflags |
1266 nameicap_tracker_add(ndp, dp);
1270 if (error == ERELOOKUP) {
1278 if (error != EJUSTRETURN)
1281 * At this point, we know we're at the end of the
1282 * pathname. If creating / renaming, we can consider
1283 * allowing the file or directory to be created / renamed,
1284 * provided we're not on a read-only filesystem.
1290 /* trailing slash only allowed for directories */
1291 if ((cnp->cn_flags & TRAILINGSLASH) &&
1292 !(cnp->cn_flags & WILLBEDIR)) {
1296 if ((cnp->cn_flags & LOCKPARENT) == 0)
1299 * We return with ni_vp NULL to indicate that the entry
1300 * doesn't currently exist, leaving a pointer to the
1301 * (possibly locked) directory vnode in ndp->ni_dvp.
1310 * Check for symbolic link
1312 if ((dp->v_type == VLNK) &&
1313 ((cnp->cn_flags & FOLLOW) || (cnp->cn_flags & TRAILINGSLASH) ||
1314 *ndp->ni_next == '/')) {
1315 cnp->cn_flags |= ISSYMLINK;
1316 if (VN_IS_DOOMED(dp)) {
1318 * We can't know whether the directory was mounted with
1319 * NOSYMFOLLOW, so we can't follow safely.
1324 if (dp->v_mount->mnt_flag & MNT_NOSYMFOLLOW) {
1329 * Symlink code always expects an unlocked dvp.
1331 if (ndp->ni_dvp != ndp->ni_vp) {
1332 VOP_UNLOCK(ndp->ni_dvp);
1333 ni_dvp_unlocked = 1;
1338 if ((vn_irflag_read(dp) & VIRF_MOUNTPOINT) != 0 &&
1339 (cnp->cn_flags & NOCROSSMOUNT) == 0) {
1340 error = vfs_lookup_cross_mount(ndp);
1344 * FALLTHROUGH to nextname
1351 * Not a symbolic link that we will follow. Continue with the
1352 * next component if there is any; otherwise, we're done.
1354 KASSERT((cnp->cn_flags & ISLASTCN) || *ndp->ni_next == '/',
1355 ("lookup: invalid path state."));
1358 ndp->ni_pathlen = prev_ni_pathlen;
1359 ndp->ni_next = prev_ni_next;
1360 if (ndp->ni_dvp != dp)
1366 if (cnp->cn_flags & ISDOTDOT) {
1367 error = nameicap_check_dotdot(ndp, ndp->ni_vp);
1370 if (KTRPOINT(curthread, KTR_CAPFAIL))
1371 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1376 if (*ndp->ni_next == '/') {
1377 cnp->cn_nameptr = ndp->ni_next;
1378 while (*cnp->cn_nameptr == '/') {
1382 if (ndp->ni_dvp != dp)
1389 * If we're processing a path with a trailing slash,
1390 * check that the end result is a directory.
1392 if ((cnp->cn_flags & TRAILINGSLASH) && dp->v_type != VDIR) {
1397 * Disallow directory write attempts on read-only filesystems.
1400 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1405 ni_dvp_unlocked = 2;
1406 if (ndp->ni_dvp != dp)
1410 } else if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp != dp) {
1411 VOP_UNLOCK(ndp->ni_dvp);
1412 ni_dvp_unlocked = 1;
1415 if (cnp->cn_flags & AUDITVNODE1)
1416 AUDIT_ARG_VNODE1(dp);
1417 else if (cnp->cn_flags & AUDITVNODE2)
1418 AUDIT_ARG_VNODE2(dp);
1420 if ((cnp->cn_flags & LOCKLEAF) == 0)
1424 * FIXME: for lookups which only cross a mount point to fetch the
1425 * root vnode, ni_dvp will be set to vp_crossmp. This can be a problem
1426 * if either WANTPARENT or LOCKPARENT is set.
1429 * Because of shared lookup we may have the vnode shared locked, but
1430 * the caller may want it to be exclusively locked.
1432 if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags) &&
1433 VOP_ISLOCKED(dp) != LK_EXCLUSIVE) {
1434 vn_lock(dp, LK_UPGRADE | LK_RETRY);
1435 if (VN_IS_DOOMED(dp)) {
1441 if (ndp->ni_vp != NULL) {
1442 if ((cnp->cn_flags & ISDOTDOT) == 0)
1443 nameicap_tracker_add(ndp, ndp->ni_vp);
1444 if ((cnp->cn_flags & (FAILIFEXISTS | ISSYMLINK)) == FAILIFEXISTS)
1445 return (vfs_lookup_failifexists(ndp));
1450 if (ni_dvp_unlocked != 2) {
1451 if (dp != ndp->ni_dvp && !ni_dvp_unlocked)
1464 * relookup - lookup a path name component
1465 * Used by lookup to re-acquire things.
1468 vfs_relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1471 struct vnode *dp = NULL; /* the directory we are searching */
1472 int rdonly; /* lookup read-only flag bit */
1475 KASSERT(cnp->cn_flags & ISLASTCN,
1476 ("relookup: Not given last component."));
1478 * Setup: break out flag bits into variables.
1480 KASSERT((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) != 0,
1481 ("relookup: parent not wanted"));
1482 rdonly = cnp->cn_flags & RDONLY;
1483 cnp->cn_flags &= ~ISSYMLINK;
1485 cnp->cn_lkflags = LK_EXCLUSIVE;
1486 vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
1489 * Search a new directory.
1491 * See a comment in vfs_lookup for cnp->cn_nameptr.
1493 * Check for "" which represents the root directory after slash
1496 if (cnp->cn_nameptr[0] == '\0') {
1498 * Support only LOOKUP for "/" because lookup()
1499 * can't succeed for CREATE, DELETE and RENAME.
1501 KASSERT(cnp->cn_nameiop == LOOKUP, ("nameiop must be LOOKUP"));
1502 KASSERT(dp->v_type == VDIR, ("dp is not a directory"));
1504 if (!(cnp->cn_flags & LOCKLEAF))
1507 /* XXX This should probably move to the top of function. */
1509 panic("lookup: SAVESTART");
1513 if (cnp->cn_flags & ISDOTDOT)
1514 panic ("relookup: lookup on dot-dot");
1517 * We now have a segment name to search for, and a directory to search.
1519 if ((error = VOP_LOOKUP(dp, vpp, cnp)) != 0) {
1520 KASSERT(*vpp == NULL, ("leaf should be empty"));
1521 if (error != EJUSTRETURN)
1524 * If creating and at end of pathname, then can consider
1525 * allowing file to be created.
1531 /* ASSERT(dvp == ndp->ni_startdir) */
1534 if ((cnp->cn_flags & LOCKPARENT) == 0)
1537 * We return with ni_vp NULL to indicate that the entry
1538 * doesn't currently exist, leaving a pointer to the
1539 * (possibly locked) directory vnode in ndp->ni_dvp.
1547 * Disallow directory write attempts on read-only filesystems.
1550 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1559 * Set the parent lock/ref state to the requested state.
1561 if ((cnp->cn_flags & LOCKPARENT) == 0 && dvp != dp)
1564 * Check for symbolic link
1566 KASSERT(dp->v_type != VLNK || !(cnp->cn_flags & FOLLOW),
1567 ("relookup: symlink found.\n"));
1569 /* ASSERT(dvp == ndp->ni_startdir) */
1573 if ((cnp->cn_flags & LOCKLEAF) == 0)
1584 * Validate the final state of ndp after the lookup.
1587 NDVALIDATE_impl(struct nameidata *ndp, int line)
1589 struct componentname *cnp;
1592 if (cnp->cn_pnbuf == NULL)
1593 panic("%s: got no buf! called from %d", __func__, line);