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