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