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