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