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