Expand PMF_FN_* macros.
[netbsd-mini2440.git] / sys / kern / vfs_lookup.c
blob96cc5488dac614ea74e1a89f8afb5ce1544aa2df
1 /* $NetBSD: vfs_lookup.c,v 1.120 2009/09/27 17:23:54 dholland Exp $ */
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.
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.
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.
36 * @(#)vfs_lookup.c 8.10 (Berkeley) 5/27/95
39 #include <sys/cdefs.h>
40 __KERNEL_RCSID(0, "$NetBSD: vfs_lookup.c,v 1.120 2009/09/27 17:23:54 dholland Exp $");
42 #include "opt_magiclinks.h"
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/syslimits.h>
48 #include <sys/time.h>
49 #include <sys/namei.h>
50 #include <sys/vnode.h>
51 #include <sys/mount.h>
52 #include <sys/errno.h>
53 #include <sys/filedesc.h>
54 #include <sys/hash.h>
55 #include <sys/proc.h>
56 #include <sys/syslog.h>
57 #include <sys/kauth.h>
58 #include <sys/ktrace.h>
60 #ifndef MAGICLINKS
61 #define MAGICLINKS 0
62 #endif
64 struct pathname_internal {
65 char *pathbuf;
66 bool needfree;
69 int vfs_magiclinks = MAGICLINKS;
71 pool_cache_t pnbuf_cache; /* pathname buffer cache */
74 * Substitute replacement text for 'magic' strings in symlinks.
75 * Returns 0 if successful, and returns non-zero if an error
76 * occurs. (Currently, the only possible error is running out
77 * of temporary pathname space.)
79 * Looks for "@<string>" and "@<string>/", where <string> is a
80 * recognized 'magic' string. Replaces the "@<string>" with the
81 * appropriate replacement text. (Note that in some cases the
82 * replacement text may have zero length.)
84 * This would have been table driven, but the variance in
85 * replacement strings (and replacement string lengths) made
86 * that impractical.
88 #define VNL(x) \
89 (sizeof(x) - 1)
91 #define VO '{'
92 #define VC '}'
94 #define MATCH(str) \
95 ((termchar == '/' && i + VNL(str) == *len) || \
96 (i + VNL(str) < *len && \
97 cp[i + VNL(str)] == termchar)) && \
98 !strncmp((str), &cp[i], VNL(str))
100 #define SUBSTITUTE(m, s, sl) \
101 if ((newlen + (sl)) >= MAXPATHLEN) \
102 return 1; \
103 i += VNL(m); \
104 if (termchar != '/') \
105 i++; \
106 (void)memcpy(&tmp[newlen], (s), (sl)); \
107 newlen += (sl); \
108 change = 1; \
109 termchar = '/';
111 static int
112 symlink_magic(struct proc *p, char *cp, size_t *len)
114 char *tmp;
115 size_t change, i, newlen, slen;
116 char termchar = '/';
117 char idtmp[11]; /* enough for 32 bit *unsigned* integer */
120 tmp = PNBUF_GET();
121 for (change = i = newlen = 0; i < *len; ) {
122 if (cp[i] != '@') {
123 tmp[newlen++] = cp[i++];
124 continue;
127 i++;
129 /* Check for @{var} syntax. */
130 if (cp[i] == VO) {
131 termchar = VC;
132 i++;
136 * The following checks should be ordered according
137 * to frequency of use.
139 if (MATCH("machine_arch")) {
140 slen = VNL(MACHINE_ARCH);
141 SUBSTITUTE("machine_arch", MACHINE_ARCH, slen);
142 } else if (MATCH("machine")) {
143 slen = VNL(MACHINE);
144 SUBSTITUTE("machine", MACHINE, slen);
145 } else if (MATCH("hostname")) {
146 SUBSTITUTE("hostname", hostname, hostnamelen);
147 } else if (MATCH("osrelease")) {
148 slen = strlen(osrelease);
149 SUBSTITUTE("osrelease", osrelease, slen);
150 } else if (MATCH("emul")) {
151 slen = strlen(p->p_emul->e_name);
152 SUBSTITUTE("emul", p->p_emul->e_name, slen);
153 } else if (MATCH("kernel_ident")) {
154 slen = strlen(kernel_ident);
155 SUBSTITUTE("kernel_ident", kernel_ident, slen);
156 } else if (MATCH("domainname")) {
157 SUBSTITUTE("domainname", domainname, domainnamelen);
158 } else if (MATCH("ostype")) {
159 slen = strlen(ostype);
160 SUBSTITUTE("ostype", ostype, slen);
161 } else if (MATCH("uid")) {
162 slen = snprintf(idtmp, sizeof(idtmp), "%u",
163 kauth_cred_geteuid(kauth_cred_get()));
164 SUBSTITUTE("uid", idtmp, slen);
165 } else if (MATCH("ruid")) {
166 slen = snprintf(idtmp, sizeof(idtmp), "%u",
167 kauth_cred_getuid(kauth_cred_get()));
168 SUBSTITUTE("ruid", idtmp, slen);
169 } else if (MATCH("gid")) {
170 slen = snprintf(idtmp, sizeof(idtmp), "%u",
171 kauth_cred_getegid(kauth_cred_get()));
172 SUBSTITUTE("gid", idtmp, slen);
173 } else if (MATCH("rgid")) {
174 slen = snprintf(idtmp, sizeof(idtmp), "%u",
175 kauth_cred_getgid(kauth_cred_get()));
176 SUBSTITUTE("rgid", idtmp, slen);
177 } else {
178 tmp[newlen++] = '@';
179 if (termchar == VC)
180 tmp[newlen++] = VO;
184 if (change) {
185 (void)memcpy(cp, tmp, newlen);
186 *len = newlen;
188 PNBUF_PUT(tmp);
190 return 0;
193 #undef VNL
194 #undef VO
195 #undef VC
196 #undef MATCH
197 #undef SUBSTITUTE
200 * Convert a pathname into a pointer to a locked vnode.
202 * The FOLLOW flag is set when symbolic links are to be followed
203 * when they occur at the end of the name translation process.
204 * Symbolic links are always followed for all other pathname
205 * components other than the last.
207 * The segflg defines whether the name is to be copied from user
208 * space or kernel space.
210 * Overall outline of namei:
212 * copy in name
213 * get starting directory
214 * while (!done && !error) {
215 * call lookup to search path.
216 * if symbolic link, massage name in buffer and continue
221 * Internal state for a namei operation.
223 struct namei_state {
224 struct nameidata *ndp;
225 struct componentname *cnp;
227 /* used by the pieces of namei */
228 struct vnode *namei_startdir; /* The directory namei() starts from. */
230 /* used by the pieces of lookup */
231 int lookup_alldone;
233 int docache; /* == 0 do not cache last component */
234 int rdonly; /* lookup read-only flag bit */
235 struct vnode *dp; /* the directory we are searching */
236 int slashes;
239 /* XXX reorder things to make this decl unnecessary */
240 static int do_lookup(struct namei_state *state);
244 * Initialize the namei working state.
246 static void
247 namei_init(struct namei_state *state, struct nameidata *ndp)
249 state->ndp = ndp;
250 state->cnp = &ndp->ni_cnd;
252 state->namei_startdir = NULL;
254 state->lookup_alldone = 0;
256 state->docache = 0;
257 state->rdonly = 0;
258 state->dp = NULL;
259 state->slashes = 0;
263 * Clean up the working namei state, leaving things ready for return
264 * from namei.
266 static void
267 namei_cleanup(struct namei_state *state)
269 KASSERT(state->cnp == &state->ndp->ni_cnd);
271 //KASSERT(state->namei_startdir == NULL); // not yet
273 /* nothing for now */
274 (void)state;
277 //////////////////////////////
280 * Start up namei. Early portion.
282 * This is divided from namei_start2 by the emul_retry: point.
284 static void
285 namei_start1(struct namei_state *state)
288 #ifdef DIAGNOSTIC
289 if (!state->cnp->cn_cred)
290 panic("namei: bad cred/proc");
291 if (state->cnp->cn_nameiop & (~OPMASK))
292 panic("namei: nameiop contaminated with flags");
293 if (state->cnp->cn_flags & OPMASK)
294 panic("namei: flags contaminated with nameiops");
295 #endif
298 * Get a buffer for the name to be translated, and copy the
299 * name into the buffer.
301 if ((state->cnp->cn_flags & HASBUF) == 0)
302 state->cnp->cn_pnbuf = PNBUF_GET();
306 * Start up namei. Copy the path, find the root dir and cwd, establish
307 * the starting directory for lookup, and lock it.
309 static int
310 namei_start2(struct namei_state *state)
312 struct nameidata *ndp = state->ndp;
313 struct componentname *cnp = state->cnp;
315 struct cwdinfo *cwdi; /* pointer to cwd state */
316 struct lwp *self = curlwp; /* thread doing namei() */
317 int error;
319 if (ndp->ni_segflg == UIO_SYSSPACE)
320 error = copystr(ndp->ni_dirp, cnp->cn_pnbuf,
321 MAXPATHLEN, &ndp->ni_pathlen);
322 else
323 error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf,
324 MAXPATHLEN, &ndp->ni_pathlen);
327 * POSIX.1 requirement: "" is not a valid file name.
329 if (!error && ndp->ni_pathlen == 1)
330 error = ENOENT;
332 if (error) {
333 PNBUF_PUT(cnp->cn_pnbuf);
334 ndp->ni_vp = NULL;
335 return (error);
337 ndp->ni_loopcnt = 0;
340 * Get root directory for the translation.
342 cwdi = self->l_proc->p_cwdi;
343 rw_enter(&cwdi->cwdi_lock, RW_READER);
344 state->namei_startdir = cwdi->cwdi_rdir;
345 if (state->namei_startdir == NULL)
346 state->namei_startdir = rootvnode;
347 ndp->ni_rootdir = state->namei_startdir;
350 * Check if starting from root directory or current directory.
352 if (cnp->cn_pnbuf[0] == '/') {
353 if (cnp->cn_flags & TRYEMULROOT) {
354 if (cnp->cn_flags & EMULROOTSET) {
355 /* Called from (eg) emul_find_interp() */
356 state->namei_startdir = ndp->ni_erootdir;
357 } else {
358 if (cwdi->cwdi_edir == NULL
359 || (cnp->cn_pnbuf[1] == '.'
360 && cnp->cn_pnbuf[2] == '.'
361 && cnp->cn_pnbuf[3] == '/')) {
362 ndp->ni_erootdir = NULL;
363 } else {
364 state->namei_startdir = cwdi->cwdi_edir;
365 ndp->ni_erootdir = state->namei_startdir;
368 } else {
369 ndp->ni_erootdir = NULL;
370 if (cnp->cn_flags & NOCHROOT)
371 state->namei_startdir = ndp->ni_rootdir = rootvnode;
373 } else {
374 state->namei_startdir = cwdi->cwdi_cdir;
375 ndp->ni_erootdir = NULL;
377 vref(state->namei_startdir);
378 rw_exit(&cwdi->cwdi_lock);
381 * Ktrace it.
383 if (ktrpoint(KTR_NAMEI)) {
384 if (ndp->ni_erootdir != NULL) {
386 * To make any sense, the trace entry need to have the
387 * text of the emulation path prepended.
388 * Usually we can get this from the current process,
389 * but when called from emul_find_interp() it is only
390 * in the exec_package - so we get it passed in ni_next
391 * (this is a hack).
393 const char *emul_path;
394 if (cnp->cn_flags & EMULROOTSET)
395 emul_path = ndp->ni_next;
396 else
397 emul_path = self->l_proc->p_emul->e_path;
398 ktrnamei2(emul_path, strlen(emul_path),
399 cnp->cn_pnbuf, ndp->ni_pathlen);
400 } else
401 ktrnamei(cnp->cn_pnbuf, ndp->ni_pathlen);
404 vn_lock(state->namei_startdir, LK_EXCLUSIVE | LK_RETRY);
406 return 0;
410 * Undo namei_start: unlock and release the current lookup directory,
411 * and discard the path buffer.
413 static void
414 namei_end(struct namei_state *state)
416 vput(state->namei_startdir);
417 PNBUF_PUT(state->cnp->cn_pnbuf);
418 //state->cnp->cn_pnbuf = NULL; // not yet (just in case) (XXX)
422 * Check for being at a symlink.
424 static inline int
425 namei_atsymlink(struct namei_state *state)
427 return (state->cnp->cn_flags & ISSYMLINK) != 0;
431 * Follow a symlink.
433 static inline int
434 namei_follow(struct namei_state *state)
436 struct nameidata *ndp = state->ndp;
437 struct componentname *cnp = state->cnp;
439 struct lwp *self = curlwp; /* thread doing namei() */
440 struct iovec aiov; /* uio for reading symbolic links */
441 struct uio auio;
442 char *cp; /* pointer into pathname argument */
443 size_t linklen;
444 int error;
446 if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
447 return ELOOP;
449 if (ndp->ni_vp->v_mount->mnt_flag & MNT_SYMPERM) {
450 error = VOP_ACCESS(ndp->ni_vp, VEXEC, cnp->cn_cred);
451 if (error != 0)
452 return error;
454 if (ndp->ni_pathlen > 1)
455 cp = PNBUF_GET();
456 else
457 cp = cnp->cn_pnbuf;
458 aiov.iov_base = cp;
459 aiov.iov_len = MAXPATHLEN;
460 auio.uio_iov = &aiov;
461 auio.uio_iovcnt = 1;
462 auio.uio_offset = 0;
463 auio.uio_rw = UIO_READ;
464 auio.uio_resid = MAXPATHLEN;
465 UIO_SETUP_SYSSPACE(&auio);
466 error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
467 if (error) {
468 badlink:
469 if (ndp->ni_pathlen > 1)
470 PNBUF_PUT(cp);
471 return error;
473 linklen = MAXPATHLEN - auio.uio_resid;
474 if (linklen == 0) {
475 error = ENOENT;
476 goto badlink;
480 * Do symlink substitution, if appropriate, and
481 * check length for potential overflow.
483 if ((vfs_magiclinks &&
484 symlink_magic(self->l_proc, cp, &linklen)) ||
485 (linklen + ndp->ni_pathlen >= MAXPATHLEN)) {
486 error = ENAMETOOLONG;
487 goto badlink;
489 if (ndp->ni_pathlen > 1) {
490 memcpy(cp + linklen, ndp->ni_next, ndp->ni_pathlen);
491 PNBUF_PUT(cnp->cn_pnbuf);
492 cnp->cn_pnbuf = cp;
493 } else
494 cnp->cn_pnbuf[linklen] = '\0';
495 ndp->ni_pathlen += linklen;
496 vput(ndp->ni_vp);
497 state->namei_startdir = ndp->ni_dvp;
500 * Check if root directory should replace current directory.
502 if (cnp->cn_pnbuf[0] == '/') {
503 vput(state->namei_startdir);
504 /* Keep absolute symbolic links inside emulation root */
505 state->namei_startdir = ndp->ni_erootdir;
506 if (state->namei_startdir == NULL || (cnp->cn_pnbuf[1] == '.'
507 && cnp->cn_pnbuf[2] == '.'
508 && cnp->cn_pnbuf[3] == '/')) {
509 ndp->ni_erootdir = NULL;
510 state->namei_startdir = ndp->ni_rootdir;
512 vref(state->namei_startdir);
513 vn_lock(state->namei_startdir, LK_EXCLUSIVE | LK_RETRY);
516 return 0;
519 //////////////////////////////
521 static int
522 do_namei(struct namei_state *state)
524 int error;
526 struct nameidata *ndp = state->ndp;
527 struct componentname *cnp = state->cnp;
529 KASSERT(cnp == &ndp->ni_cnd);
531 namei_start1(state);
533 emul_retry:
535 error = namei_start2(state);
536 if (error) {
537 return error;
540 /* Loop through symbolic links */
541 for (;;) {
542 if (state->namei_startdir->v_mount == NULL) {
543 /* Give up if the directory is no longer mounted */
544 namei_end(state);
545 return (ENOENT);
547 cnp->cn_nameptr = cnp->cn_pnbuf;
548 ndp->ni_startdir = state->namei_startdir;
549 error = do_lookup(state);
550 if (error != 0) {
551 /* XXX this should use namei_end() */
552 if (ndp->ni_dvp) {
553 vput(ndp->ni_dvp);
555 if (ndp->ni_erootdir != NULL) {
556 /* Retry the whole thing from the normal root */
557 cnp->cn_flags &= ~TRYEMULROOT;
558 goto emul_retry;
560 PNBUF_PUT(cnp->cn_pnbuf);
561 return (error);
565 * Check for symbolic link
567 if (namei_atsymlink(state)) {
568 error = namei_follow(state);
569 if (error) {
570 KASSERT(ndp->ni_dvp != ndp->ni_vp);
571 vput(ndp->ni_dvp);
572 vput(ndp->ni_vp);
573 ndp->ni_vp = NULL;
574 PNBUF_PUT(cnp->cn_pnbuf);
575 return error;
578 else {
579 break;
584 * Done
587 if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp) {
588 if (ndp->ni_dvp == ndp->ni_vp) {
589 vrele(ndp->ni_dvp);
590 } else {
591 vput(ndp->ni_dvp);
594 if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0) {
595 PNBUF_PUT(cnp->cn_pnbuf);
596 #if defined(DIAGNOSTIC)
597 cnp->cn_pnbuf = NULL;
598 #endif /* defined(DIAGNOSTIC) */
599 } else {
600 cnp->cn_flags |= HASBUF;
603 return 0;
607 namei(struct nameidata *ndp)
609 struct namei_state state;
610 int error;
612 namei_init(&state, ndp);
613 error = do_namei(&state);
614 namei_cleanup(&state);
616 return error;
620 * Determine the namei hash (for cn_hash) for name.
621 * If *ep != NULL, hash from name to ep-1.
622 * If *ep == NULL, hash from name until the first NUL or '/', and
623 * return the location of this termination character in *ep.
625 * This function returns an equivalent hash to the MI hash32_strn().
626 * The latter isn't used because in the *ep == NULL case, determining
627 * the length of the string to the first NUL or `/' and then calling
628 * hash32_strn() involves unnecessary double-handling of the data.
630 uint32_t
631 namei_hash(const char *name, const char **ep)
633 uint32_t hash;
635 hash = HASH32_STR_INIT;
636 if (*ep != NULL) {
637 for (; name < *ep; name++)
638 hash = hash * 33 + *(const uint8_t *)name;
639 } else {
640 for (; *name != '\0' && *name != '/'; name++)
641 hash = hash * 33 + *(const uint8_t *)name;
642 *ep = name;
644 return (hash + (hash >> 5));
648 * Search a pathname.
649 * This is a very central and rather complicated routine.
651 * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
652 * The starting directory is taken from ni_startdir. The pathname is
653 * descended until done, or a symbolic link is encountered. The variable
654 * ni_more is clear if the path is completed; it is set to one if a
655 * symbolic link needing interpretation is encountered.
657 * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
658 * whether the name is to be looked up, created, renamed, or deleted.
659 * When CREATE, RENAME, or DELETE is specified, information usable in
660 * creating, renaming, or deleting a directory entry may be calculated.
661 * If flag has LOCKPARENT or'ed into it, the parent directory is returned
662 * locked. Otherwise the parent directory is not returned. If the target
663 * of the pathname exists and LOCKLEAF is or'ed into the flag the target
664 * is returned locked, otherwise it is returned unlocked. When creating
665 * or renaming and LOCKPARENT is specified, the target may not be ".".
666 * When deleting and LOCKPARENT is specified, the target may be ".".
668 * Overall outline of lookup:
670 * dirloop:
671 * identify next component of name at ndp->ni_ptr
672 * handle degenerate case where name is null string
673 * if .. and crossing mount points and on mounted filesys, find parent
674 * call VOP_LOOKUP routine for next component name
675 * directory vnode returned in ni_dvp, locked.
676 * component vnode returned in ni_vp (if it exists), locked.
677 * if result vnode is mounted on and crossing mount points,
678 * find mounted on vnode
679 * if more components of name, do next level at dirloop
680 * return the answer in ni_vp, locked if LOCKLEAF set
681 * if LOCKPARENT set, return locked parent in ni_dvp
685 * Begin lookup().
687 static int
688 lookup_start(struct namei_state *state)
690 const char *cp; /* pointer into pathname argument */
692 struct componentname *cnp = state->cnp;
693 struct nameidata *ndp = state->ndp;
695 KASSERT(cnp == &ndp->ni_cnd);
697 state->lookup_alldone = 0;
698 state->dp = NULL;
701 * Setup: break out flag bits into variables.
703 state->docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
704 if (cnp->cn_nameiop == DELETE)
705 state->docache = 0;
706 state->rdonly = cnp->cn_flags & RDONLY;
707 ndp->ni_dvp = NULL;
708 cnp->cn_flags &= ~ISSYMLINK;
709 state->dp = ndp->ni_startdir;
710 ndp->ni_startdir = NULLVP;
713 * If we have a leading string of slashes, remove them, and just make
714 * sure the current node is a directory.
716 cp = cnp->cn_nameptr;
717 if (*cp == '/') {
718 do {
719 cp++;
720 } while (*cp == '/');
721 ndp->ni_pathlen -= cp - cnp->cn_nameptr;
722 cnp->cn_nameptr = cp;
724 if (state->dp->v_type != VDIR) {
725 vput(state->dp);
726 return ENOTDIR;
730 * If we've exhausted the path name, then just return the
731 * current node.
733 if (cnp->cn_nameptr[0] == '\0') {
734 ndp->ni_vp = state->dp;
735 cnp->cn_flags |= ISLASTCN;
737 /* bleh */
738 state->lookup_alldone = 1;
739 return 0;
743 return 0;
746 static int
747 lookup_parsepath(struct namei_state *state)
749 const char *cp; /* pointer into pathname argument */
751 struct componentname *cnp = state->cnp;
752 struct nameidata *ndp = state->ndp;
754 KASSERT(cnp == &ndp->ni_cnd);
757 * Search a new directory.
759 * The cn_hash value is for use by vfs_cache.
760 * The last component of the filename is left accessible via
761 * cnp->cn_nameptr for callers that need the name. Callers needing
762 * the name set the SAVENAME flag. When done, they assume
763 * responsibility for freeing the pathname buffer.
765 * At this point, our only vnode state is that "dp" is held and locked.
767 cnp->cn_consume = 0;
768 cp = NULL;
769 cnp->cn_hash = namei_hash(cnp->cn_nameptr, &cp);
770 cnp->cn_namelen = cp - cnp->cn_nameptr;
771 if (cnp->cn_namelen > NAME_MAX) {
772 vput(state->dp);
773 ndp->ni_dvp = NULL;
774 return ENAMETOOLONG;
776 #ifdef NAMEI_DIAGNOSTIC
777 { char c = *cp;
778 *(char *)cp = '\0';
779 printf("{%s}: ", cnp->cn_nameptr);
780 *(char *)cp = c; }
781 #endif /* NAMEI_DIAGNOSTIC */
782 ndp->ni_pathlen -= cnp->cn_namelen;
783 ndp->ni_next = cp;
785 * If this component is followed by a slash, then move the pointer to
786 * the next component forward, and remember that this component must be
787 * a directory.
789 if (*cp == '/') {
790 do {
791 cp++;
792 } while (*cp == '/');
793 state->slashes = cp - ndp->ni_next;
794 ndp->ni_pathlen -= state->slashes;
795 ndp->ni_next = cp;
796 cnp->cn_flags |= REQUIREDIR;
797 } else {
798 state->slashes = 0;
799 cnp->cn_flags &= ~REQUIREDIR;
802 * We do special processing on the last component, whether or not it's
803 * a directory. Cache all intervening lookups, but not the final one.
805 if (*cp == '\0') {
806 if (state->docache)
807 cnp->cn_flags |= MAKEENTRY;
808 else
809 cnp->cn_flags &= ~MAKEENTRY;
810 cnp->cn_flags |= ISLASTCN;
811 } else {
812 cnp->cn_flags |= MAKEENTRY;
813 cnp->cn_flags &= ~ISLASTCN;
815 if (cnp->cn_namelen == 2 &&
816 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
817 cnp->cn_flags |= ISDOTDOT;
818 else
819 cnp->cn_flags &= ~ISDOTDOT;
821 return 0;
824 static int
825 lookup_once(struct namei_state *state)
827 struct vnode *tdp; /* saved dp */
828 struct mount *mp; /* mount table entry */
829 struct lwp *l = curlwp;
830 int error;
832 struct componentname *cnp = state->cnp;
833 struct nameidata *ndp = state->ndp;
835 KASSERT(cnp == &ndp->ni_cnd);
838 * Handle "..": two special cases.
839 * 1. If at root directory (e.g. after chroot)
840 * or at absolute root directory
841 * then ignore it so can't get out.
842 * 1a. If at the root of the emulation filesystem go to the real
843 * root. So "/../<path>" is always absolute.
844 * 1b. If we have somehow gotten out of a jail, warn
845 * and also ignore it so we can't get farther out.
846 * 2. If this vnode is the root of a mounted
847 * filesystem, then replace it with the
848 * vnode which was mounted on so we take the
849 * .. in the other file system.
851 if (cnp->cn_flags & ISDOTDOT) {
852 struct proc *p = l->l_proc;
854 for (;;) {
855 if (state->dp == ndp->ni_rootdir || state->dp == rootvnode) {
856 ndp->ni_dvp = state->dp;
857 ndp->ni_vp = state->dp;
858 vref(state->dp);
859 return 0;
861 if (ndp->ni_rootdir != rootvnode) {
862 int retval;
864 VOP_UNLOCK(state->dp, 0);
865 retval = vn_isunder(state->dp, ndp->ni_rootdir, l);
866 vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
867 if (!retval) {
868 /* Oops! We got out of jail! */
869 log(LOG_WARNING,
870 "chrooted pid %d uid %d (%s) "
871 "detected outside of its chroot\n",
872 p->p_pid, kauth_cred_geteuid(l->l_cred),
873 p->p_comm);
874 /* Put us at the jail root. */
875 vput(state->dp);
876 state->dp = ndp->ni_rootdir;
877 ndp->ni_dvp = state->dp;
878 ndp->ni_vp = state->dp;
879 vref(state->dp);
880 vref(state->dp);
881 vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
882 return 0;
885 if ((state->dp->v_vflag & VV_ROOT) == 0 ||
886 (cnp->cn_flags & NOCROSSMOUNT))
887 break;
888 tdp = state->dp;
889 state->dp = state->dp->v_mount->mnt_vnodecovered;
890 vput(tdp);
891 vref(state->dp);
892 vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
897 * We now have a segment name to search for, and a directory to search.
898 * Again, our only vnode state is that "dp" is held and locked.
900 unionlookup:
901 ndp->ni_dvp = state->dp;
902 ndp->ni_vp = NULL;
903 error = VOP_LOOKUP(state->dp, &ndp->ni_vp, cnp);
904 if (error != 0) {
905 #ifdef DIAGNOSTIC
906 if (ndp->ni_vp != NULL)
907 panic("leaf `%s' should be empty", cnp->cn_nameptr);
908 #endif /* DIAGNOSTIC */
909 #ifdef NAMEI_DIAGNOSTIC
910 printf("not found\n");
911 #endif /* NAMEI_DIAGNOSTIC */
912 if ((error == ENOENT) &&
913 (state->dp->v_vflag & VV_ROOT) &&
914 (state->dp->v_mount->mnt_flag & MNT_UNION)) {
915 tdp = state->dp;
916 state->dp = state->dp->v_mount->mnt_vnodecovered;
917 vput(tdp);
918 vref(state->dp);
919 vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
920 goto unionlookup;
923 if (error != EJUSTRETURN)
924 return error;
927 * If this was not the last component, or there were trailing
928 * slashes, and we are not going to create a directory,
929 * then the name must exist.
931 if ((cnp->cn_flags & (REQUIREDIR | CREATEDIR)) == REQUIREDIR) {
932 return ENOENT;
936 * If creating and at end of pathname, then can consider
937 * allowing file to be created.
939 if (state->rdonly) {
940 return EROFS;
944 * We return with ni_vp NULL to indicate that the entry
945 * doesn't currently exist, leaving a pointer to the
946 * (possibly locked) directory vnode in ndp->ni_dvp.
948 if (cnp->cn_flags & SAVESTART) {
949 ndp->ni_startdir = ndp->ni_dvp;
950 vref(ndp->ni_startdir);
952 state->lookup_alldone = 1;
953 return (0);
955 #ifdef NAMEI_DIAGNOSTIC
956 printf("found\n");
957 #endif /* NAMEI_DIAGNOSTIC */
960 * Take into account any additional components consumed by the
961 * underlying filesystem. This will include any trailing slashes after
962 * the last component consumed.
964 if (cnp->cn_consume > 0) {
965 ndp->ni_pathlen -= cnp->cn_consume - state->slashes;
966 ndp->ni_next += cnp->cn_consume - state->slashes;
967 cnp->cn_consume = 0;
968 if (ndp->ni_next[0] == '\0')
969 cnp->cn_flags |= ISLASTCN;
972 state->dp = ndp->ni_vp;
975 * "state->dp" and "ndp->ni_dvp" are both locked and held,
976 * and may be the same vnode.
980 * Check to see if the vnode has been mounted on;
981 * if so find the root of the mounted file system.
983 while (state->dp->v_type == VDIR && (mp = state->dp->v_mountedhere) &&
984 (cnp->cn_flags & NOCROSSMOUNT) == 0) {
985 error = vfs_busy(mp, NULL);
986 if (error != 0) {
987 vput(state->dp);
988 return error;
990 KASSERT(ndp->ni_dvp != state->dp);
991 VOP_UNLOCK(ndp->ni_dvp, 0);
992 vput(state->dp);
993 error = VFS_ROOT(mp, &tdp);
994 vfs_unbusy(mp, false, NULL);
995 if (error) {
996 vn_lock(ndp->ni_dvp, LK_EXCLUSIVE | LK_RETRY);
997 return error;
999 VOP_UNLOCK(tdp, 0);
1000 ndp->ni_vp = state->dp = tdp;
1001 vn_lock(ndp->ni_dvp, LK_EXCLUSIVE | LK_RETRY);
1002 vn_lock(ndp->ni_vp, LK_EXCLUSIVE | LK_RETRY);
1005 return 0;
1008 static int
1009 do_lookup(struct namei_state *state)
1011 int error = 0;
1013 struct componentname *cnp = state->cnp;
1014 struct nameidata *ndp = state->ndp;
1016 KASSERT(cnp == &ndp->ni_cnd);
1018 error = lookup_start(state);
1019 if (error) {
1020 goto bad;
1022 // XXX: this case should not be necessary given proper handling
1023 // of slashes elsewhere.
1024 if (state->lookup_alldone) {
1025 goto terminal;
1028 dirloop:
1029 error = lookup_parsepath(state);
1030 if (error) {
1031 goto bad;
1034 error = lookup_once(state);
1035 if (error) {
1036 goto bad;
1038 // XXX ought to be able to avoid this case too
1039 if (state->lookup_alldone) {
1040 /* this should NOT be "goto terminal;" */
1041 return 0;
1045 * Check for symbolic link. Back up over any slashes that we skipped,
1046 * as we will need them again.
1048 if ((state->dp->v_type == VLNK) && (cnp->cn_flags & (FOLLOW|REQUIREDIR))) {
1049 ndp->ni_pathlen += state->slashes;
1050 ndp->ni_next -= state->slashes;
1051 cnp->cn_flags |= ISSYMLINK;
1052 return (0);
1056 * Check for directory, if the component was followed by a series of
1057 * slashes.
1059 if ((state->dp->v_type != VDIR) && (cnp->cn_flags & REQUIREDIR)) {
1060 error = ENOTDIR;
1061 KASSERT(state->dp != ndp->ni_dvp);
1062 vput(state->dp);
1063 goto bad;
1067 * Not a symbolic link. If this was not the last component, then
1068 * continue at the next component, else return.
1070 if (!(cnp->cn_flags & ISLASTCN)) {
1071 cnp->cn_nameptr = ndp->ni_next;
1072 if (ndp->ni_dvp == state->dp) {
1073 vrele(ndp->ni_dvp);
1074 } else {
1075 vput(ndp->ni_dvp);
1077 goto dirloop;
1080 terminal:
1081 if (state->dp == ndp->ni_erootdir) {
1083 * We are about to return the emulation root.
1084 * This isn't a good idea because code might repeatedly
1085 * lookup ".." until the file matches that returned
1086 * for "/" and loop forever.
1087 * So convert it to the real root.
1089 if (ndp->ni_dvp == state->dp)
1090 vrele(state->dp);
1091 else
1092 if (ndp->ni_dvp != NULL)
1093 vput(ndp->ni_dvp);
1094 ndp->ni_dvp = NULL;
1095 vput(state->dp);
1096 state->dp = ndp->ni_rootdir;
1097 vref(state->dp);
1098 vn_lock(state->dp, LK_EXCLUSIVE | LK_RETRY);
1099 ndp->ni_vp = state->dp;
1103 * If the caller requested the parent node (i.e.
1104 * it's a CREATE, DELETE, or RENAME), and we don't have one
1105 * (because this is the root directory), then we must fail.
1107 if (ndp->ni_dvp == NULL && cnp->cn_nameiop != LOOKUP) {
1108 switch (cnp->cn_nameiop) {
1109 case CREATE:
1110 error = EEXIST;
1111 break;
1112 case DELETE:
1113 case RENAME:
1114 error = EBUSY;
1115 break;
1116 default:
1117 KASSERT(0);
1119 vput(state->dp);
1120 goto bad;
1124 * Disallow directory write attempts on read-only lookups.
1125 * Prefers EEXIST over EROFS for the CREATE case.
1127 if (state->rdonly &&
1128 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1129 error = EROFS;
1130 if (state->dp != ndp->ni_dvp) {
1131 vput(state->dp);
1133 goto bad;
1135 if (ndp->ni_dvp != NULL) {
1136 if (cnp->cn_flags & SAVESTART) {
1137 ndp->ni_startdir = ndp->ni_dvp;
1138 vref(ndp->ni_startdir);
1141 if ((cnp->cn_flags & LOCKLEAF) == 0) {
1142 VOP_UNLOCK(state->dp, 0);
1144 return (0);
1146 bad:
1147 ndp->ni_vp = NULL;
1148 return (error);
1152 * Externally visible interfaces used by nfsd (bletch, yuk, XXX)
1154 * The "index" version differs from the "main" version in that it's
1155 * called from a different place in a different context. For now I
1156 * want to be able to shuffle code in from one call site without
1157 * affecting the other.
1161 lookup_for_nfsd(struct nameidata *ndp, struct vnode *dp, int neverfollow)
1163 struct namei_state state;
1164 int error;
1166 struct iovec aiov;
1167 struct uio auio;
1168 int linklen;
1169 char *cp;
1171 /* For now at least we don't have to frob the state */
1172 namei_init(&state, ndp);
1175 * BEGIN wodge of code from nfsd
1178 vref(dp);
1179 vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
1181 for (;;) {
1183 state.cnp->cn_nameptr = state.cnp->cn_pnbuf;
1184 state.ndp->ni_startdir = dp;
1187 * END wodge of code from nfsd
1190 error = do_lookup(&state);
1191 if (error) {
1192 /* BEGIN from nfsd */
1193 if (ndp->ni_dvp) {
1194 vput(ndp->ni_dvp);
1196 PNBUF_PUT(state.cnp->cn_pnbuf);
1197 /* END from nfsd */
1198 namei_cleanup(&state);
1199 return error;
1203 * BEGIN wodge of code from nfsd
1207 * Check for encountering a symbolic link
1209 if ((state.cnp->cn_flags & ISSYMLINK) == 0) {
1210 if ((state.cnp->cn_flags & LOCKPARENT) == 0 && state.ndp->ni_dvp) {
1211 if (state.ndp->ni_dvp == state.ndp->ni_vp) {
1212 vrele(state.ndp->ni_dvp);
1213 } else {
1214 vput(state.ndp->ni_dvp);
1217 if (state.cnp->cn_flags & (SAVENAME | SAVESTART)) {
1218 state.cnp->cn_flags |= HASBUF;
1219 } else {
1220 PNBUF_PUT(state.cnp->cn_pnbuf);
1221 #if defined(DIAGNOSTIC)
1222 state.cnp->cn_pnbuf = NULL;
1223 #endif /* defined(DIAGNOSTIC) */
1225 return (0);
1226 } else {
1227 if (neverfollow) {
1228 error = EINVAL;
1229 goto out;
1231 if (state.ndp->ni_loopcnt++ >= MAXSYMLINKS) {
1232 error = ELOOP;
1233 goto out;
1235 if (state.ndp->ni_vp->v_mount->mnt_flag & MNT_SYMPERM) {
1236 error = VOP_ACCESS(ndp->ni_vp, VEXEC, state.cnp->cn_cred);
1237 if (error != 0)
1238 goto out;
1240 if (state.ndp->ni_pathlen > 1)
1241 cp = PNBUF_GET();
1242 else
1243 cp = state.cnp->cn_pnbuf;
1244 aiov.iov_base = cp;
1245 aiov.iov_len = MAXPATHLEN;
1246 auio.uio_iov = &aiov;
1247 auio.uio_iovcnt = 1;
1248 auio.uio_offset = 0;
1249 auio.uio_rw = UIO_READ;
1250 auio.uio_resid = MAXPATHLEN;
1251 UIO_SETUP_SYSSPACE(&auio);
1252 error = VOP_READLINK(ndp->ni_vp, &auio, state.cnp->cn_cred);
1253 if (error) {
1254 badlink:
1255 if (ndp->ni_pathlen > 1)
1256 PNBUF_PUT(cp);
1257 goto out;
1259 linklen = MAXPATHLEN - auio.uio_resid;
1260 if (linklen == 0) {
1261 error = ENOENT;
1262 goto badlink;
1264 if (linklen + ndp->ni_pathlen >= MAXPATHLEN) {
1265 error = ENAMETOOLONG;
1266 goto badlink;
1268 if (ndp->ni_pathlen > 1) {
1269 memcpy(cp + linklen, ndp->ni_next, ndp->ni_pathlen);
1270 PNBUF_PUT(state.cnp->cn_pnbuf);
1271 state.cnp->cn_pnbuf = cp;
1272 } else
1273 state.cnp->cn_pnbuf[linklen] = '\0';
1274 state.ndp->ni_pathlen += linklen;
1275 vput(state.ndp->ni_vp);
1276 dp = state.ndp->ni_dvp;
1279 * Check if root directory should replace current directory.
1281 if (state.cnp->cn_pnbuf[0] == '/') {
1282 vput(dp);
1283 dp = ndp->ni_rootdir;
1284 vref(dp);
1285 vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
1290 out:
1291 vput(state.ndp->ni_vp);
1292 vput(state.ndp->ni_dvp);
1293 state.ndp->ni_vp = NULL;
1294 PNBUF_PUT(state.cnp->cn_pnbuf);
1297 * END wodge of code from nfsd
1299 namei_cleanup(&state);
1301 return error;
1305 lookup_for_nfsd_index(struct nameidata *ndp)
1307 struct namei_state state;
1308 int error;
1310 /* For now at least we don't have to frob the state */
1311 namei_init(&state, ndp);
1312 error = do_lookup(&state);
1313 namei_cleanup(&state);
1315 return error;
1319 * Reacquire a path name component.
1320 * dvp is locked on entry and exit.
1321 * *vpp is locked on exit unless it's NULL.
1324 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
1326 int rdonly; /* lookup read-only flag bit */
1327 int error = 0;
1328 #ifdef DEBUG
1329 uint32_t newhash; /* DEBUG: check name hash */
1330 const char *cp; /* DEBUG: check name ptr/len */
1331 #endif /* DEBUG */
1334 * Setup: break out flag bits into variables.
1336 rdonly = cnp->cn_flags & RDONLY;
1337 cnp->cn_flags &= ~ISSYMLINK;
1340 * Search a new directory.
1342 * The cn_hash value is for use by vfs_cache.
1343 * The last component of the filename is left accessible via
1344 * cnp->cn_nameptr for callers that need the name. Callers needing
1345 * the name set the SAVENAME flag. When done, they assume
1346 * responsibility for freeing the pathname buffer.
1348 #ifdef DEBUG
1349 cp = NULL;
1350 newhash = namei_hash(cnp->cn_nameptr, &cp);
1351 if ((uint32_t)newhash != (uint32_t)cnp->cn_hash)
1352 panic("relookup: bad hash");
1353 if (cnp->cn_namelen != cp - cnp->cn_nameptr)
1354 panic("relookup: bad len");
1355 while (*cp == '/')
1356 cp++;
1357 if (*cp != 0)
1358 panic("relookup: not last component");
1359 #endif /* DEBUG */
1362 * Check for degenerate name (e.g. / or "")
1363 * which is a way of talking about a directory,
1364 * e.g. like "/." or ".".
1366 if (cnp->cn_nameptr[0] == '\0')
1367 panic("relookup: null name");
1369 if (cnp->cn_flags & ISDOTDOT)
1370 panic("relookup: lookup on dot-dot");
1373 * We now have a segment name to search for, and a directory to search.
1375 if ((error = VOP_LOOKUP(dvp, vpp, cnp)) != 0) {
1376 #ifdef DIAGNOSTIC
1377 if (*vpp != NULL)
1378 panic("leaf `%s' should be empty", cnp->cn_nameptr);
1379 #endif
1380 if (error != EJUSTRETURN)
1381 goto bad;
1384 #ifdef DIAGNOSTIC
1386 * Check for symbolic link
1388 if (*vpp && (*vpp)->v_type == VLNK && (cnp->cn_flags & FOLLOW))
1389 panic("relookup: symlink found");
1390 #endif
1393 * Check for read-only lookups.
1395 if (rdonly && cnp->cn_nameiop != LOOKUP) {
1396 error = EROFS;
1397 if (*vpp) {
1398 vput(*vpp);
1400 goto bad;
1402 if (cnp->cn_flags & SAVESTART)
1403 vref(dvp);
1404 return (0);
1406 bad:
1407 *vpp = NULL;
1408 return (error);
1412 * namei_simple - simple forms of namei.
1414 * These are wrappers to allow the simple case callers of namei to be
1415 * left alone while everything else changes under them.
1418 /* Flags */
1419 struct namei_simple_flags_type {
1420 int dummy;
1422 static const struct namei_simple_flags_type ns_nn, ns_nt, ns_fn, ns_ft;
1423 const namei_simple_flags_t NSM_NOFOLLOW_NOEMULROOT = &ns_nn;
1424 const namei_simple_flags_t NSM_NOFOLLOW_TRYEMULROOT = &ns_nt;
1425 const namei_simple_flags_t NSM_FOLLOW_NOEMULROOT = &ns_fn;
1426 const namei_simple_flags_t NSM_FOLLOW_TRYEMULROOT = &ns_ft;
1428 static
1430 namei_simple_convert_flags(namei_simple_flags_t sflags)
1432 if (sflags == NSM_NOFOLLOW_NOEMULROOT)
1433 return NOFOLLOW | 0;
1434 if (sflags == NSM_NOFOLLOW_TRYEMULROOT)
1435 return NOFOLLOW | TRYEMULROOT;
1436 if (sflags == NSM_FOLLOW_NOEMULROOT)
1437 return FOLLOW | 0;
1438 if (sflags == NSM_FOLLOW_TRYEMULROOT)
1439 return FOLLOW | TRYEMULROOT;
1440 panic("namei_simple_convert_flags: bogus sflags\n");
1441 return 0;
1445 namei_simple_kernel(const char *path, namei_simple_flags_t sflags,
1446 struct vnode **vp_ret)
1448 struct nameidata nd;
1449 int err;
1451 NDINIT(&nd,
1452 LOOKUP,
1453 namei_simple_convert_flags(sflags),
1454 UIO_SYSSPACE,
1455 path);
1456 err = namei(&nd);
1457 if (err != 0) {
1458 return err;
1460 *vp_ret = nd.ni_vp;
1461 return 0;
1465 namei_simple_user(const char *path, namei_simple_flags_t sflags,
1466 struct vnode **vp_ret)
1468 struct nameidata nd;
1469 int err;
1471 NDINIT(&nd,
1472 LOOKUP,
1473 namei_simple_convert_flags(sflags),
1474 UIO_USERSPACE,
1475 path);
1476 err = namei(&nd);
1477 if (err != 0) {
1478 return err;
1480 *vp_ret = nd.ni_vp;
1481 return 0;