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