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