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