vfs_lookup.c revision 1.191 1 /* $NetBSD: vfs_lookup.c,v 1.191 2011/09/27 01:42:45 christos Exp $ */
2
3 /*
4 * Copyright (c) 1982, 1986, 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 * @(#)vfs_lookup.c 8.10 (Berkeley) 5/27/95
37 */
38
39 #include <sys/cdefs.h>
40 __KERNEL_RCSID(0, "$NetBSD: vfs_lookup.c,v 1.191 2011/09/27 01:42:45 christos Exp $");
41
42 #include "opt_magiclinks.h"
43
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>
59
60 #ifndef MAGICLINKS
61 #define MAGICLINKS 0
62 #endif
63
64 int vfs_magiclinks = MAGICLINKS;
65
66 __CTASSERT(MAXNAMLEN == NAME_MAX);
67
68 /*
69 * Substitute replacement text for 'magic' strings in symlinks.
70 * Returns 0 if successful, and returns non-zero if an error
71 * occurs. (Currently, the only possible error is running out
72 * of temporary pathname space.)
73 *
74 * Looks for "@<string>" and "@<string>/", where <string> is a
75 * recognized 'magic' string. Replaces the "@<string>" with the
76 * appropriate replacement text. (Note that in some cases the
77 * replacement text may have zero length.)
78 *
79 * This would have been table driven, but the variance in
80 * replacement strings (and replacement string lengths) made
81 * that impractical.
82 */
83 #define VNL(x) \
84 (sizeof(x) - 1)
85
86 #define VO '{'
87 #define VC '}'
88
89 #define MATCH(str) \
90 ((termchar == '/' && i + VNL(str) == *len) || \
91 (i + VNL(str) < *len && \
92 cp[i + VNL(str)] == termchar)) && \
93 !strncmp((str), &cp[i], VNL(str))
94
95 #define SUBSTITUTE(m, s, sl) \
96 if ((newlen + (sl)) >= MAXPATHLEN) \
97 return 1; \
98 i += VNL(m); \
99 if (termchar != '/') \
100 i++; \
101 (void)memcpy(&tmp[newlen], (s), (sl)); \
102 newlen += (sl); \
103 change = 1; \
104 termchar = '/';
105
106 static int
107 symlink_magic(struct proc *p, char *cp, size_t *len)
108 {
109 char *tmp;
110 size_t change, i, newlen, slen;
111 char termchar = '/';
112 char idtmp[11]; /* enough for 32 bit *unsigned* integer */
113
114
115 tmp = PNBUF_GET();
116 for (change = i = newlen = 0; i < *len; ) {
117 if (cp[i] != '@') {
118 tmp[newlen++] = cp[i++];
119 continue;
120 }
121
122 i++;
123
124 /* Check for @{var} syntax. */
125 if (cp[i] == VO) {
126 termchar = VC;
127 i++;
128 }
129
130 /*
131 * The following checks should be ordered according
132 * to frequency of use.
133 */
134 if (MATCH("machine_arch")) {
135 slen = VNL(MACHINE_ARCH);
136 SUBSTITUTE("machine_arch", MACHINE_ARCH, slen);
137 } else if (MATCH("machine")) {
138 slen = VNL(MACHINE);
139 SUBSTITUTE("machine", MACHINE, slen);
140 } else if (MATCH("hostname")) {
141 SUBSTITUTE("hostname", hostname, hostnamelen);
142 } else if (MATCH("osrelease")) {
143 slen = strlen(osrelease);
144 SUBSTITUTE("osrelease", osrelease, slen);
145 } else if (MATCH("emul")) {
146 slen = strlen(p->p_emul->e_name);
147 SUBSTITUTE("emul", p->p_emul->e_name, slen);
148 } else if (MATCH("kernel_ident")) {
149 slen = strlen(kernel_ident);
150 SUBSTITUTE("kernel_ident", kernel_ident, slen);
151 } else if (MATCH("domainname")) {
152 SUBSTITUTE("domainname", domainname, domainnamelen);
153 } else if (MATCH("ostype")) {
154 slen = strlen(ostype);
155 SUBSTITUTE("ostype", ostype, slen);
156 } else if (MATCH("uid")) {
157 slen = snprintf(idtmp, sizeof(idtmp), "%u",
158 kauth_cred_geteuid(kauth_cred_get()));
159 SUBSTITUTE("uid", idtmp, slen);
160 } else if (MATCH("ruid")) {
161 slen = snprintf(idtmp, sizeof(idtmp), "%u",
162 kauth_cred_getuid(kauth_cred_get()));
163 SUBSTITUTE("ruid", idtmp, slen);
164 } else if (MATCH("gid")) {
165 slen = snprintf(idtmp, sizeof(idtmp), "%u",
166 kauth_cred_getegid(kauth_cred_get()));
167 SUBSTITUTE("gid", idtmp, slen);
168 } else if (MATCH("rgid")) {
169 slen = snprintf(idtmp, sizeof(idtmp), "%u",
170 kauth_cred_getgid(kauth_cred_get()));
171 SUBSTITUTE("rgid", idtmp, slen);
172 } else {
173 tmp[newlen++] = '@';
174 if (termchar == VC)
175 tmp[newlen++] = VO;
176 }
177 }
178
179 if (change) {
180 (void)memcpy(cp, tmp, newlen);
181 *len = newlen;
182 }
183 PNBUF_PUT(tmp);
184
185 return 0;
186 }
187
188 #undef VNL
189 #undef VO
190 #undef VC
191 #undef MATCH
192 #undef SUBSTITUTE
193
194 ////////////////////////////////////////////////////////////
195
196 /*
197 * Determine the namei hash (for cn_hash) for name.
198 * If *ep != NULL, hash from name to ep-1.
199 * If *ep == NULL, hash from name until the first NUL or '/', and
200 * return the location of this termination character in *ep.
201 *
202 * This function returns an equivalent hash to the MI hash32_strn().
203 * The latter isn't used because in the *ep == NULL case, determining
204 * the length of the string to the first NUL or `/' and then calling
205 * hash32_strn() involves unnecessary double-handling of the data.
206 */
207 uint32_t
208 namei_hash(const char *name, const char **ep)
209 {
210 uint32_t hash;
211
212 hash = HASH32_STR_INIT;
213 if (*ep != NULL) {
214 for (; name < *ep; name++)
215 hash = hash * 33 + *(const uint8_t *)name;
216 } else {
217 for (; *name != '\0' && *name != '/'; name++)
218 hash = hash * 33 + *(const uint8_t *)name;
219 *ep = name;
220 }
221 return (hash + (hash >> 5));
222 }
223
224 ////////////////////////////////////////////////////////////
225
226 /*
227 * Sealed abstraction for pathnames.
228 *
229 * System-call-layer level code that is going to call namei should
230 * first create a pathbuf and adjust all the bells and whistles on it
231 * as needed by context.
232 */
233
234 struct pathbuf {
235 char *pb_path;
236 char *pb_pathcopy;
237 unsigned pb_pathcopyuses;
238 };
239
240 static struct pathbuf *
241 pathbuf_create_raw(void)
242 {
243 struct pathbuf *pb;
244
245 pb = kmem_alloc(sizeof(*pb), KM_SLEEP);
246 if (pb == NULL) {
247 return NULL;
248 }
249 pb->pb_path = PNBUF_GET();
250 if (pb->pb_path == NULL) {
251 kmem_free(pb, sizeof(*pb));
252 return NULL;
253 }
254 pb->pb_pathcopy = NULL;
255 pb->pb_pathcopyuses = 0;
256 return pb;
257 }
258
259 void
260 pathbuf_destroy(struct pathbuf *pb)
261 {
262 KASSERT(pb->pb_pathcopyuses == 0);
263 KASSERT(pb->pb_pathcopy == NULL);
264 PNBUF_PUT(pb->pb_path);
265 kmem_free(pb, sizeof(*pb));
266 }
267
268 struct pathbuf *
269 pathbuf_assimilate(char *pnbuf)
270 {
271 struct pathbuf *pb;
272
273 pb = kmem_alloc(sizeof(*pb), KM_SLEEP);
274 if (pb == NULL) {
275 return NULL;
276 }
277 pb->pb_path = pnbuf;
278 pb->pb_pathcopy = NULL;
279 pb->pb_pathcopyuses = 0;
280 return pb;
281 }
282
283 struct pathbuf *
284 pathbuf_create(const char *path)
285 {
286 struct pathbuf *pb;
287 int error;
288
289 pb = pathbuf_create_raw();
290 if (pb == NULL) {
291 return NULL;
292 }
293 error = copystr(path, pb->pb_path, PATH_MAX, NULL);
294 if (error != 0) {
295 KASSERT(!"kernel path too long in pathbuf_create");
296 /* make sure it's null-terminated, just in case */
297 pb->pb_path[PATH_MAX-1] = '\0';
298 }
299 return pb;
300 }
301
302 int
303 pathbuf_copyin(const char *userpath, struct pathbuf **ret)
304 {
305 struct pathbuf *pb;
306 int error;
307
308 pb = pathbuf_create_raw();
309 if (pb == NULL) {
310 return ENOMEM;
311 }
312 error = copyinstr(userpath, pb->pb_path, PATH_MAX, NULL);
313 if (error) {
314 pathbuf_destroy(pb);
315 return error;
316 }
317 *ret = pb;
318 return 0;
319 }
320
321 /*
322 * XXX should not exist:
323 * 1. whether a pointer is kernel or user should be statically checkable.
324 * 2. copyin should be handled by the upper part of the syscall layer,
325 * not in here.
326 */
327 int
328 pathbuf_maybe_copyin(const char *path, enum uio_seg seg, struct pathbuf **ret)
329 {
330 if (seg == UIO_USERSPACE) {
331 return pathbuf_copyin(path, ret);
332 } else {
333 *ret = pathbuf_create(path);
334 if (*ret == NULL) {
335 return ENOMEM;
336 }
337 return 0;
338 }
339 }
340
341 /*
342 * Get a copy of the path buffer as it currently exists. If this is
343 * called after namei starts the results may be arbitrary.
344 */
345 void
346 pathbuf_copystring(const struct pathbuf *pb, char *buf, size_t maxlen)
347 {
348 strlcpy(buf, pb->pb_path, maxlen);
349 }
350
351 /*
352 * These two functions allow access to a saved copy of the original
353 * path string. The first copy should be gotten before namei is
354 * called. Each copy that is gotten should be put back.
355 */
356
357 const char *
358 pathbuf_stringcopy_get(struct pathbuf *pb)
359 {
360 if (pb->pb_pathcopyuses == 0) {
361 pb->pb_pathcopy = PNBUF_GET();
362 strcpy(pb->pb_pathcopy, pb->pb_path);
363 }
364 pb->pb_pathcopyuses++;
365 return pb->pb_pathcopy;
366 }
367
368 void
369 pathbuf_stringcopy_put(struct pathbuf *pb, const char *str)
370 {
371 KASSERT(str == pb->pb_pathcopy);
372 KASSERT(pb->pb_pathcopyuses > 0);
373 pb->pb_pathcopyuses--;
374 if (pb->pb_pathcopyuses == 0) {
375 PNBUF_PUT(pb->pb_pathcopy);
376 pb->pb_pathcopy = NULL;
377 }
378 }
379
380
381 ////////////////////////////////////////////////////////////
382
383 /*
384 * namei: convert a pathname into a pointer to a (maybe-locked) vnode,
385 * and maybe also its parent directory vnode, and assorted other guff.
386 * See namei(9) for the interface documentation.
387 *
388 *
389 * The FOLLOW flag is set when symbolic links are to be followed
390 * when they occur at the end of the name translation process.
391 * Symbolic links are always followed for all other pathname
392 * components other than the last.
393 *
394 * The segflg defines whether the name is to be copied from user
395 * space or kernel space.
396 *
397 * Overall outline of namei:
398 *
399 * copy in name
400 * get starting directory
401 * while (!done && !error) {
402 * call lookup to search path.
403 * if symbolic link, massage name in buffer and continue
404 * }
405 */
406
407 /*
408 * Search a pathname.
409 * This is a very central and rather complicated routine.
410 *
411 * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
412 * The starting directory is passed in. The pathname is descended
413 * until done, or a symbolic link is encountered. The variable ni_more
414 * is clear if the path is completed; it is set to one if a symbolic
415 * link needing interpretation is encountered.
416 *
417 * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
418 * whether the name is to be looked up, created, renamed, or deleted.
419 * When CREATE, RENAME, or DELETE is specified, information usable in
420 * creating, renaming, or deleting a directory entry may be calculated.
421 * If flag has LOCKPARENT or'ed into it, the parent directory is returned
422 * locked. Otherwise the parent directory is not returned. If the target
423 * of the pathname exists and LOCKLEAF is or'ed into the flag the target
424 * is returned locked, otherwise it is returned unlocked. When creating
425 * or renaming and LOCKPARENT is specified, the target may not be ".".
426 * When deleting and LOCKPARENT is specified, the target may be ".".
427 *
428 * Overall outline of lookup:
429 *
430 * dirloop:
431 * identify next component of name at ndp->ni_ptr
432 * handle degenerate case where name is null string
433 * if .. and crossing mount points and on mounted filesys, find parent
434 * call VOP_LOOKUP routine for next component name
435 * directory vnode returned in ni_dvp, locked.
436 * component vnode returned in ni_vp (if it exists), locked.
437 * if result vnode is mounted on and crossing mount points,
438 * find mounted on vnode
439 * if more components of name, do next level at dirloop
440 * return the answer in ni_vp, locked if LOCKLEAF set
441 * if LOCKPARENT set, return locked parent in ni_dvp
442 */
443
444
445 /*
446 * Internal state for a namei operation.
447 *
448 * cnp is always equal to &ndp->ni_cnp.
449 */
450 struct namei_state {
451 struct nameidata *ndp;
452 struct componentname *cnp;
453
454 int docache; /* == 0 do not cache last component */
455 int rdonly; /* lookup read-only flag bit */
456 int slashes;
457
458 unsigned attempt_retry:1; /* true if error allows emul retry */
459 };
460
461
462 /*
463 * Initialize the namei working state.
464 */
465 static void
466 namei_init(struct namei_state *state, struct nameidata *ndp)
467 {
468 state->ndp = ndp;
469 state->cnp = &ndp->ni_cnd;
470 KASSERT((state->cnp->cn_flags & INRELOOKUP) == 0);
471
472 state->docache = 0;
473 state->rdonly = 0;
474 state->slashes = 0;
475
476 #ifdef DIAGNOSTIC
477 if (!state->cnp->cn_cred)
478 panic("namei: bad cred/proc");
479 if (state->cnp->cn_nameiop & (~OPMASK))
480 panic("namei: nameiop contaminated with flags");
481 if (state->cnp->cn_flags & OPMASK)
482 panic("namei: flags contaminated with nameiops");
483 #endif
484
485 /*
486 * The buffer for name translation shall be the one inside the
487 * pathbuf.
488 */
489 state->ndp->ni_pnbuf = state->ndp->ni_pathbuf->pb_path;
490 }
491
492 /*
493 * Clean up the working namei state, leaving things ready for return
494 * from namei.
495 */
496 static void
497 namei_cleanup(struct namei_state *state)
498 {
499 KASSERT(state->cnp == &state->ndp->ni_cnd);
500
501 /* nothing for now */
502 (void)state;
503 }
504
505 //////////////////////////////
506
507 /*
508 * Get the directory context.
509 * Initializes the rootdir and erootdir state and returns a reference
510 * to the starting dir.
511 */
512 static struct vnode *
513 namei_getstartdir(struct namei_state *state)
514 {
515 struct nameidata *ndp = state->ndp;
516 struct componentname *cnp = state->cnp;
517 struct cwdinfo *cwdi; /* pointer to cwd state */
518 struct lwp *self = curlwp; /* thread doing namei() */
519 struct vnode *rootdir, *erootdir, *curdir, *startdir;
520
521 cwdi = self->l_proc->p_cwdi;
522 rw_enter(&cwdi->cwdi_lock, RW_READER);
523
524 /* root dir */
525 if (cwdi->cwdi_rdir == NULL || (cnp->cn_flags & NOCHROOT)) {
526 rootdir = rootvnode;
527 } else {
528 rootdir = cwdi->cwdi_rdir;
529 }
530
531 /* emulation root dir, if any */
532 if ((cnp->cn_flags & TRYEMULROOT) == 0) {
533 /* if we don't want it, don't fetch it */
534 erootdir = NULL;
535 } else if (cnp->cn_flags & EMULROOTSET) {
536 /* explicitly set emulroot; "/../" doesn't override this */
537 erootdir = ndp->ni_erootdir;
538 } else if (!strncmp(ndp->ni_pnbuf, "/../", 4)) {
539 /* explicit reference to real rootdir */
540 erootdir = NULL;
541 } else {
542 /* may be null */
543 erootdir = cwdi->cwdi_edir;
544 }
545
546 /* current dir */
547 curdir = cwdi->cwdi_cdir;
548
549 if (ndp->ni_pnbuf[0] != '/') {
550 startdir = curdir;
551 erootdir = NULL;
552 } else if (cnp->cn_flags & TRYEMULROOT && erootdir != NULL) {
553 startdir = erootdir;
554 } else {
555 startdir = rootdir;
556 erootdir = NULL;
557 }
558
559 state->ndp->ni_rootdir = rootdir;
560 state->ndp->ni_erootdir = erootdir;
561
562 /*
563 * Get a reference to the start dir so we can safely unlock cwdi.
564 *
565 * XXX: should we hold references to rootdir and erootdir while
566 * we're running? What happens if a multithreaded process chroots
567 * during namei?
568 */
569 vref(startdir);
570
571 rw_exit(&cwdi->cwdi_lock);
572 return startdir;
573 }
574
575 /*
576 * Get the directory context for the nfsd case, in parallel to
577 * getstartdir. Initializes the rootdir and erootdir state and
578 * returns a reference to the passed-in starting dir.
579 */
580 static struct vnode *
581 namei_getstartdir_for_nfsd(struct namei_state *state, struct vnode *startdir)
582 {
583 /* always use the real root, and never set an emulation root */
584 state->ndp->ni_rootdir = rootvnode;
585 state->ndp->ni_erootdir = NULL;
586
587 vref(startdir);
588 return startdir;
589 }
590
591
592 /*
593 * Ktrace the namei operation.
594 */
595 static void
596 namei_ktrace(struct namei_state *state)
597 {
598 struct nameidata *ndp = state->ndp;
599 struct componentname *cnp = state->cnp;
600 struct lwp *self = curlwp; /* thread doing namei() */
601 const char *emul_path;
602
603 if (ktrpoint(KTR_NAMEI)) {
604 if (ndp->ni_erootdir != NULL) {
605 /*
606 * To make any sense, the trace entry need to have the
607 * text of the emulation path prepended.
608 * Usually we can get this from the current process,
609 * but when called from emul_find_interp() it is only
610 * in the exec_package - so we get it passed in ni_next
611 * (this is a hack).
612 */
613 if (cnp->cn_flags & EMULROOTSET)
614 emul_path = ndp->ni_next;
615 else
616 emul_path = self->l_proc->p_emul->e_path;
617 ktrnamei2(emul_path, strlen(emul_path),
618 ndp->ni_pnbuf, ndp->ni_pathlen);
619 } else
620 ktrnamei(ndp->ni_pnbuf, ndp->ni_pathlen);
621 }
622 }
623
624 /*
625 * Start up namei. Find the root dir and cwd, establish the starting
626 * directory for lookup, and lock it. Also calls ktrace when
627 * appropriate.
628 */
629 static int
630 namei_start(struct namei_state *state, struct vnode *forcecwd,
631 struct vnode **startdir_ret)
632 {
633 struct nameidata *ndp = state->ndp;
634 struct vnode *startdir;
635
636 /* length includes null terminator (was originally from copyinstr) */
637 ndp->ni_pathlen = strlen(ndp->ni_pnbuf) + 1;
638
639 /*
640 * POSIX.1 requirement: "" is not a valid file name.
641 */
642 if (ndp->ni_pathlen == 1) {
643 return ENOENT;
644 }
645
646 ndp->ni_loopcnt = 0;
647
648 /* Get starting directory, set up root, and ktrace. */
649 if (forcecwd != NULL) {
650 startdir = namei_getstartdir_for_nfsd(state, forcecwd);
651 /* no ktrace */
652 } else {
653 startdir = namei_getstartdir(state);
654 namei_ktrace(state);
655 }
656
657 vn_lock(startdir, LK_EXCLUSIVE | LK_RETRY);
658
659 *startdir_ret = startdir;
660 return 0;
661 }
662
663 /*
664 * Check for being at a symlink that we're going to follow.
665 */
666 static inline int
667 namei_atsymlink(struct namei_state *state, struct vnode *foundobj)
668 {
669 return (foundobj->v_type == VLNK) &&
670 (state->cnp->cn_flags & (FOLLOW|REQUIREDIR));
671 }
672
673 /*
674 * Follow a symlink.
675 *
676 * Updates searchdir. inhibitmagic causes magic symlinks to not be
677 * interpreted; this is used by nfsd.
678 *
679 * Unlocks foundobj on success (ugh)
680 */
681 static inline int
682 namei_follow(struct namei_state *state, int inhibitmagic,
683 struct vnode *searchdir, struct vnode *foundobj,
684 struct vnode **newsearchdir_ret)
685 {
686 struct nameidata *ndp = state->ndp;
687 struct componentname *cnp = state->cnp;
688
689 struct lwp *self = curlwp; /* thread doing namei() */
690 struct iovec aiov; /* uio for reading symbolic links */
691 struct uio auio;
692 char *cp; /* pointer into pathname argument */
693 size_t linklen;
694 int error;
695
696 KASSERT(VOP_ISLOCKED(searchdir) == LK_EXCLUSIVE);
697 KASSERT(VOP_ISLOCKED(foundobj) == LK_EXCLUSIVE);
698 if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
699 return ELOOP;
700 }
701 if (foundobj->v_mount->mnt_flag & MNT_SYMPERM) {
702 error = VOP_ACCESS(foundobj, VEXEC, cnp->cn_cred);
703 if (error != 0)
704 return error;
705 }
706
707 /* FUTURE: fix this to not use a second buffer */
708 cp = PNBUF_GET();
709 aiov.iov_base = cp;
710 aiov.iov_len = MAXPATHLEN;
711 auio.uio_iov = &aiov;
712 auio.uio_iovcnt = 1;
713 auio.uio_offset = 0;
714 auio.uio_rw = UIO_READ;
715 auio.uio_resid = MAXPATHLEN;
716 UIO_SETUP_SYSSPACE(&auio);
717 error = VOP_READLINK(foundobj, &auio, cnp->cn_cred);
718 if (error) {
719 PNBUF_PUT(cp);
720 return error;
721 }
722 linklen = MAXPATHLEN - auio.uio_resid;
723 if (linklen == 0) {
724 PNBUF_PUT(cp);
725 return ENOENT;
726 }
727
728 /*
729 * Do symlink substitution, if appropriate, and
730 * check length for potential overflow.
731 *
732 * Inhibit symlink substitution for nfsd.
733 * XXX: This is how it was before; is that a bug or a feature?
734 */
735 if ((!inhibitmagic && vfs_magiclinks &&
736 symlink_magic(self->l_proc, cp, &linklen)) ||
737 (linklen + ndp->ni_pathlen >= MAXPATHLEN)) {
738 PNBUF_PUT(cp);
739 return ENAMETOOLONG;
740 }
741 if (ndp->ni_pathlen > 1) {
742 /* includes a null-terminator */
743 memcpy(cp + linklen, ndp->ni_next, ndp->ni_pathlen);
744 } else {
745 cp[linklen] = '\0';
746 }
747 ndp->ni_pathlen += linklen;
748 memcpy(ndp->ni_pnbuf, cp, ndp->ni_pathlen);
749 PNBUF_PUT(cp);
750
751 /* we're now starting from the beginning of the buffer again */
752 cnp->cn_nameptr = ndp->ni_pnbuf;
753
754 /* must unlock this before relocking searchdir */
755 VOP_UNLOCK(foundobj);
756
757 /*
758 * Check if root directory should replace current directory.
759 */
760 if (ndp->ni_pnbuf[0] == '/') {
761 vput(searchdir);
762 /* Keep absolute symbolic links inside emulation root */
763 searchdir = ndp->ni_erootdir;
764 if (searchdir == NULL ||
765 (ndp->ni_pnbuf[1] == '.'
766 && ndp->ni_pnbuf[2] == '.'
767 && ndp->ni_pnbuf[3] == '/')) {
768 ndp->ni_erootdir = NULL;
769 searchdir = ndp->ni_rootdir;
770 }
771 vref(searchdir);
772 vn_lock(searchdir, LK_EXCLUSIVE | LK_RETRY);
773 while (cnp->cn_nameptr[0] == '/') {
774 cnp->cn_nameptr++;
775 ndp->ni_pathlen--;
776 }
777 }
778
779 *newsearchdir_ret = searchdir;
780 KASSERT(VOP_ISLOCKED(searchdir) == LK_EXCLUSIVE);
781 return 0;
782 }
783
784 //////////////////////////////
785
786 /*
787 * Inspect the leading path component and update the state accordingly.
788 */
789 static int
790 lookup_parsepath(struct namei_state *state)
791 {
792 const char *cp; /* pointer into pathname argument */
793
794 struct componentname *cnp = state->cnp;
795 struct nameidata *ndp = state->ndp;
796
797 KASSERT(cnp == &ndp->ni_cnd);
798
799 /*
800 * Search a new directory.
801 *
802 * The cn_hash value is for use by vfs_cache.
803 * The last component of the filename is left accessible via
804 * cnp->cn_nameptr for callers that need the name. Callers needing
805 * the name set the SAVENAME flag. When done, they assume
806 * responsibility for freeing the pathname buffer.
807 *
808 * At this point, our only vnode state is that the search dir
809 * is held and locked.
810 */
811 cnp->cn_consume = 0;
812 cp = NULL;
813 cnp->cn_hash = namei_hash(cnp->cn_nameptr, &cp);
814 cnp->cn_namelen = cp - cnp->cn_nameptr;
815 if (cnp->cn_namelen > KERNEL_NAME_MAX) {
816 return ENAMETOOLONG;
817 }
818 #ifdef NAMEI_DIAGNOSTIC
819 { char c = *cp;
820 *(char *)cp = '\0';
821 printf("{%s}: ", cnp->cn_nameptr);
822 *(char *)cp = c; }
823 #endif /* NAMEI_DIAGNOSTIC */
824 ndp->ni_pathlen -= cnp->cn_namelen;
825 ndp->ni_next = cp;
826 /*
827 * If this component is followed by a slash, then move the pointer to
828 * the next component forward, and remember that this component must be
829 * a directory.
830 */
831 if (*cp == '/') {
832 do {
833 cp++;
834 } while (*cp == '/');
835 state->slashes = cp - ndp->ni_next;
836 ndp->ni_pathlen -= state->slashes;
837 ndp->ni_next = cp;
838 cnp->cn_flags |= REQUIREDIR;
839 } else {
840 state->slashes = 0;
841 cnp->cn_flags &= ~REQUIREDIR;
842 }
843 /*
844 * We do special processing on the last component, whether or not it's
845 * a directory. Cache all intervening lookups, but not the final one.
846 */
847 if (*cp == '\0') {
848 if (state->docache)
849 cnp->cn_flags |= MAKEENTRY;
850 else
851 cnp->cn_flags &= ~MAKEENTRY;
852 cnp->cn_flags |= ISLASTCN;
853 } else {
854 cnp->cn_flags |= MAKEENTRY;
855 cnp->cn_flags &= ~ISLASTCN;
856 }
857 if (cnp->cn_namelen == 2 &&
858 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
859 cnp->cn_flags |= ISDOTDOT;
860 else
861 cnp->cn_flags &= ~ISDOTDOT;
862
863 return 0;
864 }
865
866 /*
867 * Call VOP_LOOKUP for a single lookup; return a new search directory
868 * (used when crossing mountpoints up or searching union mounts down) and
869 * the found object, which for create operations may be NULL on success.
870 */
871 static int
872 lookup_once(struct namei_state *state,
873 struct vnode *searchdir,
874 struct vnode **newsearchdir_ret,
875 struct vnode **foundobj_ret)
876 {
877 struct vnode *tmpvn; /* scratch vnode */
878 struct vnode *foundobj; /* result */
879 struct mount *mp; /* mount table entry */
880 struct lwp *l = curlwp;
881 int error;
882
883 struct componentname *cnp = state->cnp;
884 struct nameidata *ndp = state->ndp;
885
886 KASSERT(cnp == &ndp->ni_cnd);
887 KASSERT(VOP_ISLOCKED(searchdir) == LK_EXCLUSIVE);
888 *newsearchdir_ret = searchdir;
889
890 /*
891 * Handle "..": two special cases.
892 * 1. If at root directory (e.g. after chroot)
893 * or at absolute root directory
894 * then ignore it so can't get out.
895 * 1a. If at the root of the emulation filesystem go to the real
896 * root. So "/../<path>" is always absolute.
897 * 1b. If we have somehow gotten out of a jail, warn
898 * and also ignore it so we can't get farther out.
899 * 2. If this vnode is the root of a mounted
900 * filesystem, then replace it with the
901 * vnode which was mounted on so we take the
902 * .. in the other file system.
903 */
904 if (cnp->cn_flags & ISDOTDOT) {
905 struct proc *p = l->l_proc;
906
907 for (;;) {
908 if (searchdir == ndp->ni_rootdir ||
909 searchdir == rootvnode) {
910 foundobj = searchdir;
911 vref(foundobj);
912 *foundobj_ret = foundobj;
913 error = 0;
914 goto done;
915 }
916 if (ndp->ni_rootdir != rootvnode) {
917 int retval;
918
919 VOP_UNLOCK(searchdir);
920 retval = vn_isunder(searchdir, ndp->ni_rootdir, l);
921 vn_lock(searchdir, LK_EXCLUSIVE | LK_RETRY);
922 if (!retval) {
923 /* Oops! We got out of jail! */
924 log(LOG_WARNING,
925 "chrooted pid %d uid %d (%s) "
926 "detected outside of its chroot\n",
927 p->p_pid, kauth_cred_geteuid(l->l_cred),
928 p->p_comm);
929 /* Put us at the jail root. */
930 vput(searchdir);
931 searchdir = NULL;
932 foundobj = ndp->ni_rootdir;
933 vref(foundobj);
934 vref(foundobj);
935 vn_lock(foundobj, LK_EXCLUSIVE | LK_RETRY);
936 *newsearchdir_ret = foundobj;
937 *foundobj_ret = foundobj;
938 error = 0;
939 goto done;
940 }
941 }
942 if ((searchdir->v_vflag & VV_ROOT) == 0 ||
943 (cnp->cn_flags & NOCROSSMOUNT))
944 break;
945 tmpvn = searchdir;
946 searchdir = searchdir->v_mount->mnt_vnodecovered;
947 vref(searchdir);
948 vput(tmpvn);
949 vn_lock(searchdir, LK_EXCLUSIVE | LK_RETRY);
950 *newsearchdir_ret = searchdir;
951 }
952 }
953
954 /*
955 * We now have a segment name to search for, and a directory to search.
956 * Our vnode state here is that "searchdir" is held and locked.
957 */
958 unionlookup:
959 foundobj = NULL;
960 error = VOP_LOOKUP(searchdir, &foundobj, cnp);
961
962 if (error != 0) {
963 #ifdef DIAGNOSTIC
964 if (foundobj != NULL)
965 panic("leaf `%s' should be empty", cnp->cn_nameptr);
966 #endif /* DIAGNOSTIC */
967 #ifdef NAMEI_DIAGNOSTIC
968 printf("not found\n");
969 #endif /* NAMEI_DIAGNOSTIC */
970 if ((error == ENOENT) &&
971 (searchdir->v_vflag & VV_ROOT) &&
972 (searchdir->v_mount->mnt_flag & MNT_UNION)) {
973 tmpvn = searchdir;
974 searchdir = searchdir->v_mount->mnt_vnodecovered;
975 vref(searchdir);
976 vput(tmpvn);
977 vn_lock(searchdir, LK_EXCLUSIVE | LK_RETRY);
978 *newsearchdir_ret = searchdir;
979 goto unionlookup;
980 }
981
982 if (error != EJUSTRETURN)
983 goto done;
984
985 /*
986 * If this was not the last component, or there were trailing
987 * slashes, and we are not going to create a directory,
988 * then the name must exist.
989 */
990 if ((cnp->cn_flags & (REQUIREDIR | CREATEDIR)) == REQUIREDIR) {
991 error = ENOENT;
992 goto done;
993 }
994
995 /*
996 * If creating and at end of pathname, then can consider
997 * allowing file to be created.
998 */
999 if (state->rdonly) {
1000 error = EROFS;
1001 goto done;
1002 }
1003
1004 /*
1005 * We return success and a NULL foundobj to indicate
1006 * that the entry doesn't currently exist, leaving a
1007 * pointer to the (normally, locked) directory vnode
1008 * as searchdir.
1009 */
1010 *foundobj_ret = NULL;
1011 error = 0;
1012 goto done;
1013 }
1014 #ifdef NAMEI_DIAGNOSTIC
1015 printf("found\n");
1016 #endif /* NAMEI_DIAGNOSTIC */
1017
1018 /*
1019 * Take into account any additional components consumed by the
1020 * underlying filesystem. This will include any trailing slashes after
1021 * the last component consumed.
1022 */
1023 if (cnp->cn_consume > 0) {
1024 ndp->ni_pathlen -= cnp->cn_consume - state->slashes;
1025 ndp->ni_next += cnp->cn_consume - state->slashes;
1026 cnp->cn_consume = 0;
1027 if (ndp->ni_next[0] == '\0')
1028 cnp->cn_flags |= ISLASTCN;
1029 }
1030
1031 /*
1032 * "foundobj" and "searchdir" are both locked and held,
1033 * and may be the same vnode.
1034 */
1035
1036 /*
1037 * Check to see if the vnode has been mounted on;
1038 * if so find the root of the mounted file system.
1039 */
1040 while (foundobj->v_type == VDIR &&
1041 (mp = foundobj->v_mountedhere) != NULL &&
1042 (cnp->cn_flags & NOCROSSMOUNT) == 0) {
1043 error = vfs_busy(mp, NULL);
1044 if (error != 0) {
1045 if (searchdir != foundobj) {
1046 vput(foundobj);
1047 } else {
1048 vrele(foundobj);
1049 }
1050 goto done;
1051 }
1052 if (searchdir != foundobj) {
1053 VOP_UNLOCK(searchdir);
1054 }
1055 vput(foundobj);
1056 error = VFS_ROOT(mp, &foundobj);
1057 vfs_unbusy(mp, false, NULL);
1058 if (error) {
1059 vn_lock(searchdir, LK_EXCLUSIVE | LK_RETRY);
1060 goto done;
1061 }
1062 /*
1063 * avoid locking vnodes from two filesystems because it's
1064 * prune to deadlock. eg. when using puffs.
1065 * also, it isn't a good idea to propagate slowness of a
1066 * filesystem up to the root directory.
1067 * for now, only handle the common case. (ie. foundobj is VDIR)
1068 */
1069 if (foundobj->v_type == VDIR) {
1070 vrele(searchdir);
1071 *newsearchdir_ret = searchdir = foundobj;
1072 vref(searchdir);
1073 } else {
1074 VOP_UNLOCK(foundobj);
1075 vn_lock(searchdir, LK_EXCLUSIVE | LK_RETRY);
1076 vn_lock(foundobj, LK_EXCLUSIVE | LK_RETRY);
1077 }
1078 }
1079
1080 *foundobj_ret = foundobj;
1081 error = 0;
1082 done:
1083 KASSERT(VOP_ISLOCKED(*newsearchdir_ret) == LK_EXCLUSIVE);
1084 /*
1085 * *foundobj_ret is valid only if error == 0.
1086 */
1087 KASSERT(error != 0 || *foundobj_ret == NULL ||
1088 VOP_ISLOCKED(*foundobj_ret) == LK_EXCLUSIVE);
1089 return error;
1090 }
1091
1092 //////////////////////////////
1093
1094 /*
1095 * Do a complete path search from a single root directory.
1096 * (This is called up to twice if TRYEMULROOT is in effect.)
1097 */
1098 static int
1099 namei_oneroot(struct namei_state *state, struct vnode *forcecwd,
1100 int neverfollow, int inhibitmagic)
1101 {
1102 struct nameidata *ndp = state->ndp;
1103 struct componentname *cnp = state->cnp;
1104 struct vnode *searchdir, *foundobj;
1105 int error;
1106
1107 error = namei_start(state, forcecwd, &searchdir);
1108 if (error) {
1109 ndp->ni_dvp = NULL;
1110 ndp->ni_vp = NULL;
1111 return error;
1112 }
1113 KASSERT(searchdir->v_type == VDIR);
1114
1115 /*
1116 * Setup: break out flag bits into variables.
1117 */
1118 state->docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
1119 if (cnp->cn_nameiop == DELETE)
1120 state->docache = 0;
1121 state->rdonly = cnp->cn_flags & RDONLY;
1122
1123 /*
1124 * Keep going until we run out of path components.
1125 */
1126 cnp->cn_nameptr = ndp->ni_pnbuf;
1127
1128 /* drop leading slashes (already used them to choose startdir) */
1129 while (cnp->cn_nameptr[0] == '/') {
1130 cnp->cn_nameptr++;
1131 ndp->ni_pathlen--;
1132 }
1133 /* was it just "/"? */
1134 if (cnp->cn_nameptr[0] == '\0') {
1135 foundobj = searchdir;
1136 searchdir = NULL;
1137 cnp->cn_flags |= ISLASTCN;
1138
1139 /* bleh */
1140 goto skiploop;
1141 }
1142
1143 for (;;) {
1144
1145 /*
1146 * If the directory we're on is unmounted, bail out.
1147 * XXX: should this also check if it's unlinked?
1148 * XXX: yes it should... but how?
1149 */
1150 if (searchdir->v_mount == NULL) {
1151 vput(searchdir);
1152 ndp->ni_dvp = NULL;
1153 ndp->ni_vp = NULL;
1154 return (ENOENT);
1155 }
1156
1157 /*
1158 * Look up the next path component.
1159 * (currently, this may consume more than one)
1160 */
1161
1162 /* There should be no slashes here. */
1163 KASSERT(cnp->cn_nameptr[0] != '/');
1164
1165 /* and we shouldn't have looped around if we were done */
1166 KASSERT(cnp->cn_nameptr[0] != '\0');
1167
1168 error = lookup_parsepath(state);
1169 if (error) {
1170 vput(searchdir);
1171 ndp->ni_dvp = NULL;
1172 ndp->ni_vp = NULL;
1173 state->attempt_retry = 1;
1174 return (error);
1175 }
1176
1177 error = lookup_once(state, searchdir, &searchdir, &foundobj);
1178 if (error) {
1179 vput(searchdir);
1180 ndp->ni_dvp = NULL;
1181 ndp->ni_vp = NULL;
1182 /*
1183 * Note that if we're doing TRYEMULROOT we can
1184 * retry with the normal root. Where this is
1185 * currently set matches previous practice,
1186 * but the previous practice didn't make much
1187 * sense and somebody should sit down and
1188 * figure out which cases should cause retry
1189 * and which shouldn't. XXX.
1190 */
1191 state->attempt_retry = 1;
1192 return (error);
1193 }
1194
1195 if (foundobj == NULL) {
1196 /*
1197 * Success with no object returned means we're
1198 * creating something and it isn't already
1199 * there. Break out of the main loop now so
1200 * the code below doesn't have to test for
1201 * foundobj == NULL.
1202 */
1203 break;
1204 }
1205
1206 /*
1207 * Check for symbolic link. If we've reached one,
1208 * follow it, unless we aren't supposed to. Back up
1209 * over any slashes that we skipped, as we will need
1210 * them again.
1211 */
1212 if (namei_atsymlink(state, foundobj)) {
1213 ndp->ni_pathlen += state->slashes;
1214 ndp->ni_next -= state->slashes;
1215 if (neverfollow) {
1216 error = EINVAL;
1217 } else {
1218 /*
1219 * dholland 20110410: if we're at a
1220 * union mount it might make sense to
1221 * use the top of the union stack here
1222 * rather than the layer we found the
1223 * symlink in. (FUTURE)
1224 */
1225 error = namei_follow(state, inhibitmagic,
1226 searchdir, foundobj,
1227 &searchdir);
1228 }
1229 if (error) {
1230 KASSERT(searchdir != foundobj);
1231 vput(searchdir);
1232 vput(foundobj);
1233 ndp->ni_dvp = NULL;
1234 ndp->ni_vp = NULL;
1235 return error;
1236 }
1237 /* namei_follow unlocks it (ugh) so rele, not put */
1238 vrele(foundobj);
1239 foundobj = NULL;
1240
1241 /*
1242 * If we followed a symlink to `/' and there
1243 * are no more components after the symlink,
1244 * we're done with the loop and what we found
1245 * is the searchdir.
1246 */
1247 if (cnp->cn_nameptr[0] == '\0') {
1248 foundobj = searchdir;
1249 searchdir = NULL;
1250 cnp->cn_flags |= ISLASTCN;
1251 break;
1252 }
1253
1254 continue;
1255 }
1256
1257 /*
1258 * Not a symbolic link.
1259 *
1260 * Check for directory, if the component was
1261 * followed by a series of slashes.
1262 */
1263 if ((foundobj->v_type != VDIR) &&
1264 (cnp->cn_flags & REQUIREDIR)) {
1265 if (searchdir == foundobj) {
1266 vrele(searchdir);
1267 } else {
1268 vput(searchdir);
1269 }
1270 vput(foundobj);
1271 ndp->ni_dvp = NULL;
1272 ndp->ni_vp = NULL;
1273 state->attempt_retry = 1;
1274 return ENOTDIR;
1275 }
1276
1277 /*
1278 * Stop if we've reached the last component.
1279 */
1280 if (cnp->cn_flags & ISLASTCN) {
1281 break;
1282 }
1283
1284 /*
1285 * Continue with the next component.
1286 */
1287 cnp->cn_nameptr = ndp->ni_next;
1288 if (searchdir == foundobj) {
1289 vrele(searchdir);
1290 } else {
1291 vput(searchdir);
1292 }
1293 searchdir = foundobj;
1294 foundobj = NULL;
1295 }
1296
1297 skiploop:
1298
1299 if (foundobj != NULL) {
1300 if (foundobj == ndp->ni_erootdir) {
1301 /*
1302 * We are about to return the emulation root.
1303 * This isn't a good idea because code might
1304 * repeatedly lookup ".." until the file
1305 * matches that returned for "/" and loop
1306 * forever. So convert it to the real root.
1307 */
1308 if (searchdir != NULL) {
1309 if (searchdir == foundobj)
1310 vrele(searchdir);
1311 else
1312 vput(searchdir);
1313 searchdir = NULL;
1314 }
1315 vput(foundobj);
1316 foundobj = ndp->ni_rootdir;
1317 vref(foundobj);
1318 vn_lock(foundobj, LK_EXCLUSIVE | LK_RETRY);
1319 }
1320
1321 /*
1322 * If the caller requested the parent node (i.e. it's
1323 * a CREATE, DELETE, or RENAME), and we don't have one
1324 * (because this is the root directory, or we crossed
1325 * a mount point), then we must fail.
1326 */
1327 if (cnp->cn_nameiop != LOOKUP &&
1328 (searchdir == NULL ||
1329 searchdir->v_mount != foundobj->v_mount)) {
1330 if (searchdir) {
1331 vput(searchdir);
1332 }
1333 vput(foundobj);
1334 foundobj = NULL;
1335 ndp->ni_dvp = NULL;
1336 ndp->ni_vp = NULL;
1337 state->attempt_retry = 1;
1338
1339 switch (cnp->cn_nameiop) {
1340 case CREATE:
1341 return EEXIST;
1342 case DELETE:
1343 case RENAME:
1344 return EBUSY;
1345 default:
1346 break;
1347 }
1348 panic("Invalid nameiop\n");
1349 }
1350
1351 /*
1352 * Disallow directory write attempts on read-only lookups.
1353 * Prefers EEXIST over EROFS for the CREATE case.
1354 */
1355 if (state->rdonly &&
1356 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1357 if (searchdir) {
1358 if (foundobj != searchdir) {
1359 vput(searchdir);
1360 } else {
1361 vrele(searchdir);
1362 }
1363 searchdir = NULL;
1364 }
1365 vput(foundobj);
1366 foundobj = NULL;
1367 ndp->ni_dvp = NULL;
1368 ndp->ni_vp = NULL;
1369 state->attempt_retry = 1;
1370 return EROFS;
1371 }
1372 if ((cnp->cn_flags & LOCKLEAF) == 0) {
1373 /*
1374 * Note: if LOCKPARENT but not LOCKLEAF is
1375 * set, and searchdir == foundobj, this code
1376 * necessarily unlocks the parent as well as
1377 * the leaf. That is, just because you specify
1378 * LOCKPARENT doesn't mean you necessarily get
1379 * a locked parent vnode. The code in
1380 * vfs_syscalls.c, and possibly elsewhere,
1381 * that uses this combination "knows" this, so
1382 * it can't be safely changed. Feh. XXX
1383 */
1384 VOP_UNLOCK(foundobj);
1385 }
1386 }
1387
1388 /*
1389 * Done.
1390 */
1391
1392 /*
1393 * If LOCKPARENT is not set, the parent directory isn't returned.
1394 */
1395 if ((cnp->cn_flags & LOCKPARENT) == 0 && searchdir != NULL) {
1396 if (searchdir == foundobj) {
1397 vrele(searchdir);
1398 } else {
1399 vput(searchdir);
1400 }
1401 searchdir = NULL;
1402 }
1403
1404 ndp->ni_dvp = searchdir;
1405 ndp->ni_vp = foundobj;
1406 return 0;
1407 }
1408
1409 /*
1410 * Do namei; wrapper layer that handles TRYEMULROOT.
1411 */
1412 static int
1413 namei_tryemulroot(struct namei_state *state, struct vnode *forcecwd,
1414 int neverfollow, int inhibitmagic)
1415 {
1416 int error;
1417
1418 struct nameidata *ndp = state->ndp;
1419 struct componentname *cnp = state->cnp;
1420 const char *savepath = NULL;
1421
1422 KASSERT(cnp == &ndp->ni_cnd);
1423
1424 if (cnp->cn_flags & TRYEMULROOT) {
1425 savepath = pathbuf_stringcopy_get(ndp->ni_pathbuf);
1426 }
1427
1428 emul_retry:
1429 state->attempt_retry = 0;
1430
1431 error = namei_oneroot(state, forcecwd, neverfollow, inhibitmagic);
1432 if (error) {
1433 /*
1434 * Once namei has started up, the existence of ni_erootdir
1435 * tells us whether we're working from an emulation root.
1436 * The TRYEMULROOT flag isn't necessarily authoritative.
1437 */
1438 if (ndp->ni_erootdir != NULL && state->attempt_retry) {
1439 /* Retry the whole thing using the normal root */
1440 cnp->cn_flags &= ~TRYEMULROOT;
1441 state->attempt_retry = 0;
1442
1443 /* kinda gross */
1444 strcpy(ndp->ni_pathbuf->pb_path, savepath);
1445 pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
1446 savepath = NULL;
1447
1448 goto emul_retry;
1449 }
1450 }
1451 if (savepath != NULL) {
1452 pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
1453 }
1454 return error;
1455 }
1456
1457 /*
1458 * External interface.
1459 */
1460 int
1461 namei(struct nameidata *ndp)
1462 {
1463 struct namei_state state;
1464 int error;
1465
1466 namei_init(&state, ndp);
1467 error = namei_tryemulroot(&state, NULL,
1468 0/*!neverfollow*/, 0/*!inhibitmagic*/);
1469 namei_cleanup(&state);
1470
1471 if (error) {
1472 /* make sure no stray refs leak out */
1473 KASSERT(ndp->ni_dvp == NULL);
1474 KASSERT(ndp->ni_vp == NULL);
1475 }
1476
1477 return error;
1478 }
1479
1480 ////////////////////////////////////////////////////////////
1481
1482 /*
1483 * External interface used by nfsd. This is basically different from
1484 * namei only in that it has the ability to pass in the "current
1485 * directory", and uses an extra flag "neverfollow" for which there's
1486 * no physical flag defined in namei.h. (There used to be a cut&paste
1487 * copy of about half of namei in nfsd to allow these minor
1488 * adjustments to exist.)
1489 *
1490 * XXX: the namei interface should be adjusted so nfsd can just use
1491 * ordinary namei().
1492 */
1493 int
1494 lookup_for_nfsd(struct nameidata *ndp, struct vnode *forcecwd, int neverfollow)
1495 {
1496 struct namei_state state;
1497 int error;
1498
1499 namei_init(&state, ndp);
1500 error = namei_tryemulroot(&state, forcecwd,
1501 neverfollow, 1/*inhibitmagic*/);
1502 namei_cleanup(&state);
1503
1504 if (error) {
1505 /* make sure no stray refs leak out */
1506 KASSERT(ndp->ni_dvp == NULL);
1507 KASSERT(ndp->ni_vp == NULL);
1508 }
1509
1510 return error;
1511 }
1512
1513 /*
1514 * A second external interface used by nfsd. This turns out to be a
1515 * single lookup used by the WebNFS code (ha!) to get "index.html" or
1516 * equivalent when asked for a directory. It should eventually evolve
1517 * into some kind of namei_once() call; for the time being it's kind
1518 * of a mess. XXX.
1519 *
1520 * dholland 20110109: I don't think it works, and I don't think it
1521 * worked before I started hacking and slashing either, and I doubt
1522 * anyone will ever notice.
1523 */
1524
1525 /*
1526 * Internals. This calls lookup_once() after setting up the assorted
1527 * pieces of state the way they ought to be.
1528 */
1529 static int
1530 do_lookup_for_nfsd_index(struct namei_state *state, struct vnode *startdir)
1531 {
1532 int error = 0;
1533
1534 struct componentname *cnp = state->cnp;
1535 struct nameidata *ndp = state->ndp;
1536 struct vnode *foundobj;
1537 const char *cp; /* pointer into pathname argument */
1538
1539 KASSERT(cnp == &ndp->ni_cnd);
1540
1541 cnp->cn_nameptr = ndp->ni_pnbuf;
1542 state->docache = 1;
1543 state->rdonly = cnp->cn_flags & RDONLY;
1544 ndp->ni_dvp = NULL;
1545
1546 cnp->cn_consume = 0;
1547 cp = NULL;
1548 cnp->cn_hash = namei_hash(cnp->cn_nameptr, &cp);
1549 cnp->cn_namelen = cp - cnp->cn_nameptr;
1550 KASSERT(cnp->cn_namelen <= KERNEL_NAME_MAX);
1551 ndp->ni_pathlen -= cnp->cn_namelen;
1552 ndp->ni_next = cp;
1553 state->slashes = 0;
1554 cnp->cn_flags &= ~REQUIREDIR;
1555 cnp->cn_flags |= MAKEENTRY|ISLASTCN;
1556
1557 if (cnp->cn_namelen == 2 &&
1558 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
1559 cnp->cn_flags |= ISDOTDOT;
1560 else
1561 cnp->cn_flags &= ~ISDOTDOT;
1562
1563 /*
1564 * Because lookup_once can change the startdir, we need our
1565 * own reference to it to avoid consuming the caller's.
1566 */
1567 vref(startdir);
1568 vn_lock(startdir, LK_EXCLUSIVE | LK_RETRY);
1569 error = lookup_once(state, startdir, &startdir, &foundobj);
1570 if (error == 0 && startdir == foundobj) {
1571 vrele(startdir);
1572 } else {
1573 vput(startdir);
1574 }
1575 if (error) {
1576 goto bad;
1577 }
1578 ndp->ni_vp = foundobj;
1579
1580 if (foundobj == NULL) {
1581 return 0;
1582 }
1583
1584 KASSERT((cnp->cn_flags & LOCKPARENT) == 0);
1585 if ((cnp->cn_flags & LOCKLEAF) == 0) {
1586 VOP_UNLOCK(foundobj);
1587 }
1588 return (0);
1589
1590 bad:
1591 ndp->ni_vp = NULL;
1592 return (error);
1593 }
1594
1595 /*
1596 * External interface. The partitioning between this function and the
1597 * above isn't very clear - the above function exists mostly so code
1598 * that uses "state->" can be shuffled around without having to change
1599 * it to "state.".
1600 */
1601 int
1602 lookup_for_nfsd_index(struct nameidata *ndp, struct vnode *startdir)
1603 {
1604 struct namei_state state;
1605 int error;
1606
1607 /*
1608 * Note: the name sent in here (is not|should not be) allowed
1609 * to contain a slash.
1610 */
1611 if (strlen(ndp->ni_pathbuf->pb_path) > KERNEL_NAME_MAX) {
1612 return ENAMETOOLONG;
1613 }
1614 if (strchr(ndp->ni_pathbuf->pb_path, '/')) {
1615 return EINVAL;
1616 }
1617
1618 ndp->ni_pathlen = strlen(ndp->ni_pathbuf->pb_path) + 1;
1619 ndp->ni_pnbuf = NULL;
1620 ndp->ni_cnd.cn_nameptr = NULL;
1621
1622 namei_init(&state, ndp);
1623 error = do_lookup_for_nfsd_index(&state, startdir);
1624 namei_cleanup(&state);
1625
1626 return error;
1627 }
1628
1629 ////////////////////////////////////////////////////////////
1630
1631 /*
1632 * Reacquire a path name component.
1633 * dvp is locked on entry and exit.
1634 * *vpp is locked on exit unless it's NULL.
1635 */
1636 int
1637 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp, int dummy)
1638 {
1639 int rdonly; /* lookup read-only flag bit */
1640 int error = 0;
1641 #ifdef DEBUG
1642 uint32_t newhash; /* DEBUG: check name hash */
1643 const char *cp; /* DEBUG: check name ptr/len */
1644 #endif /* DEBUG */
1645
1646 (void)dummy;
1647
1648 /*
1649 * Setup: break out flag bits into variables.
1650 */
1651 rdonly = cnp->cn_flags & RDONLY;
1652
1653 /*
1654 * Search a new directory.
1655 *
1656 * The cn_hash value is for use by vfs_cache.
1657 * The last component of the filename is left accessible via
1658 * cnp->cn_nameptr for callers that need the name. Callers needing
1659 * the name set the SAVENAME flag. When done, they assume
1660 * responsibility for freeing the pathname buffer.
1661 */
1662 #ifdef DEBUG
1663 cp = NULL;
1664 newhash = namei_hash(cnp->cn_nameptr, &cp);
1665 if ((uint32_t)newhash != (uint32_t)cnp->cn_hash)
1666 panic("relookup: bad hash");
1667 if (cnp->cn_namelen != cp - cnp->cn_nameptr)
1668 panic("relookup: bad len");
1669 while (*cp == '/')
1670 cp++;
1671 if (*cp != 0)
1672 panic("relookup: not last component");
1673 #endif /* DEBUG */
1674
1675 /*
1676 * Check for degenerate name (e.g. / or "")
1677 * which is a way of talking about a directory,
1678 * e.g. like "/." or ".".
1679 */
1680 if (cnp->cn_nameptr[0] == '\0')
1681 panic("relookup: null name");
1682
1683 if (cnp->cn_flags & ISDOTDOT)
1684 panic("relookup: lookup on dot-dot");
1685
1686 /*
1687 * We now have a segment name to search for, and a directory to search.
1688 */
1689 cnp->cn_flags |= INRELOOKUP;
1690 error = VOP_LOOKUP(dvp, vpp, cnp);
1691 cnp->cn_flags &= ~INRELOOKUP;
1692 if ((error) != 0) {
1693 #ifdef DIAGNOSTIC
1694 if (*vpp != NULL)
1695 panic("leaf `%s' should be empty", cnp->cn_nameptr);
1696 #endif
1697 if (error != EJUSTRETURN)
1698 goto bad;
1699 }
1700
1701 #ifdef DIAGNOSTIC
1702 /*
1703 * Check for symbolic link
1704 */
1705 if (*vpp && (*vpp)->v_type == VLNK && (cnp->cn_flags & FOLLOW))
1706 panic("relookup: symlink found");
1707 #endif
1708
1709 /*
1710 * Check for read-only lookups.
1711 */
1712 if (rdonly && cnp->cn_nameiop != LOOKUP) {
1713 error = EROFS;
1714 if (*vpp) {
1715 vput(*vpp);
1716 }
1717 goto bad;
1718 }
1719 return (0);
1720
1721 bad:
1722 *vpp = NULL;
1723 return (error);
1724 }
1725
1726 /*
1727 * namei_simple - simple forms of namei.
1728 *
1729 * These are wrappers to allow the simple case callers of namei to be
1730 * left alone while everything else changes under them.
1731 */
1732
1733 /* Flags */
1734 struct namei_simple_flags_type {
1735 int dummy;
1736 };
1737 static const struct namei_simple_flags_type ns_nn, ns_nt, ns_fn, ns_ft;
1738 const namei_simple_flags_t NSM_NOFOLLOW_NOEMULROOT = &ns_nn;
1739 const namei_simple_flags_t NSM_NOFOLLOW_TRYEMULROOT = &ns_nt;
1740 const namei_simple_flags_t NSM_FOLLOW_NOEMULROOT = &ns_fn;
1741 const namei_simple_flags_t NSM_FOLLOW_TRYEMULROOT = &ns_ft;
1742
1743 static
1744 int
1745 namei_simple_convert_flags(namei_simple_flags_t sflags)
1746 {
1747 if (sflags == NSM_NOFOLLOW_NOEMULROOT)
1748 return NOFOLLOW | 0;
1749 if (sflags == NSM_NOFOLLOW_TRYEMULROOT)
1750 return NOFOLLOW | TRYEMULROOT;
1751 if (sflags == NSM_FOLLOW_NOEMULROOT)
1752 return FOLLOW | 0;
1753 if (sflags == NSM_FOLLOW_TRYEMULROOT)
1754 return FOLLOW | TRYEMULROOT;
1755 panic("namei_simple_convert_flags: bogus sflags\n");
1756 return 0;
1757 }
1758
1759 int
1760 namei_simple_kernel(const char *path, namei_simple_flags_t sflags,
1761 struct vnode **vp_ret)
1762 {
1763 struct nameidata nd;
1764 struct pathbuf *pb;
1765 int err;
1766
1767 pb = pathbuf_create(path);
1768 if (pb == NULL) {
1769 return ENOMEM;
1770 }
1771
1772 NDINIT(&nd,
1773 LOOKUP,
1774 namei_simple_convert_flags(sflags),
1775 pb);
1776 err = namei(&nd);
1777 if (err != 0) {
1778 pathbuf_destroy(pb);
1779 return err;
1780 }
1781 *vp_ret = nd.ni_vp;
1782 pathbuf_destroy(pb);
1783 return 0;
1784 }
1785
1786 int
1787 namei_simple_user(const char *path, namei_simple_flags_t sflags,
1788 struct vnode **vp_ret)
1789 {
1790 struct pathbuf *pb;
1791 struct nameidata nd;
1792 int err;
1793
1794 err = pathbuf_copyin(path, &pb);
1795 if (err) {
1796 return err;
1797 }
1798
1799 NDINIT(&nd,
1800 LOOKUP,
1801 namei_simple_convert_flags(sflags),
1802 pb);
1803 err = namei(&nd);
1804 if (err != 0) {
1805 pathbuf_destroy(pb);
1806 return err;
1807 }
1808 *vp_ret = nd.ni_vp;
1809 pathbuf_destroy(pb);
1810 return 0;
1811 }
1812