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