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