vfs_lookup.c revision 1.228 1 /* $NetBSD: vfs_lookup.c,v 1.228 2021/06/29 22:34:08 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.228 2021/06/29 22:34:08 dholland Exp $");
41
42 #ifdef _KERNEL_OPT
43 #include "opt_magiclinks.h"
44 #endif
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/kernel.h>
49 #include <sys/syslimits.h>
50 #include <sys/time.h>
51 #include <sys/namei.h>
52 #include <sys/vnode.h>
53 #include <sys/vnode_impl.h>
54 #include <sys/mount.h>
55 #include <sys/errno.h>
56 #include <sys/filedesc.h>
57 #include <sys/hash.h>
58 #include <sys/proc.h>
59 #include <sys/syslog.h>
60 #include <sys/kauth.h>
61 #include <sys/ktrace.h>
62 #include <sys/dirent.h>
63
64 #ifndef MAGICLINKS
65 #define MAGICLINKS 0
66 #endif
67
68 int vfs_magiclinks = MAGICLINKS;
69
70 __CTASSERT(MAXNAMLEN == NAME_MAX);
71
72 /*
73 * Substitute replacement text for 'magic' strings in symlinks.
74 * Returns 0 if successful, and returns non-zero if an error
75 * occurs. (Currently, the only possible error is running out
76 * of temporary pathname space.)
77 *
78 * Looks for "@<string>" and "@<string>/", where <string> is a
79 * recognized 'magic' string. Replaces the "@<string>" with the
80 * appropriate replacement text. (Note that in some cases the
81 * replacement text may have zero length.)
82 *
83 * This would have been table driven, but the variance in
84 * replacement strings (and replacement string lengths) made
85 * that impractical.
86 */
87 #define VNL(x) \
88 (sizeof(x) - 1)
89
90 #define VO '{'
91 #define VC '}'
92
93 #define MATCH(str) \
94 ((termchar == '/' && i + VNL(str) == *len) || \
95 (i + VNL(str) < *len && \
96 cp[i + VNL(str)] == termchar)) && \
97 !strncmp((str), &cp[i], VNL(str))
98
99 #define SUBSTITUTE(m, s, sl) \
100 if ((newlen + (sl)) >= MAXPATHLEN) \
101 return 1; \
102 i += VNL(m); \
103 if (termchar != '/') \
104 i++; \
105 (void)memcpy(&tmp[newlen], (s), (sl)); \
106 newlen += (sl); \
107 change = 1; \
108 termchar = '/';
109
110 static int
111 symlink_magic(struct proc *p, char *cp, size_t *len)
112 {
113 char *tmp;
114 size_t change, i, newlen, slen;
115 char termchar = '/';
116 char idtmp[11]; /* enough for 32 bit *unsigned* integer */
117
118
119 tmp = PNBUF_GET();
120 for (change = i = newlen = 0; i < *len; ) {
121 if (cp[i] != '@') {
122 tmp[newlen++] = cp[i++];
123 continue;
124 }
125
126 i++;
127
128 /* Check for @{var} syntax. */
129 if (cp[i] == VO) {
130 termchar = VC;
131 i++;
132 }
133
134 /*
135 * The following checks should be ordered according
136 * to frequency of use.
137 */
138 if (MATCH("machine_arch")) {
139 slen = VNL(MACHINE_ARCH);
140 SUBSTITUTE("machine_arch", MACHINE_ARCH, slen);
141 } else if (MATCH("machine")) {
142 slen = VNL(MACHINE);
143 SUBSTITUTE("machine", MACHINE, slen);
144 } else if (MATCH("hostname")) {
145 SUBSTITUTE("hostname", hostname, hostnamelen);
146 } else if (MATCH("osrelease")) {
147 slen = strlen(osrelease);
148 SUBSTITUTE("osrelease", osrelease, slen);
149 } else if (MATCH("emul")) {
150 slen = strlen(p->p_emul->e_name);
151 SUBSTITUTE("emul", p->p_emul->e_name, slen);
152 } else if (MATCH("kernel_ident")) {
153 slen = strlen(kernel_ident);
154 SUBSTITUTE("kernel_ident", kernel_ident, slen);
155 } else if (MATCH("domainname")) {
156 SUBSTITUTE("domainname", domainname, domainnamelen);
157 } else if (MATCH("ostype")) {
158 slen = strlen(ostype);
159 SUBSTITUTE("ostype", ostype, slen);
160 } else if (MATCH("uid")) {
161 slen = snprintf(idtmp, sizeof(idtmp), "%u",
162 kauth_cred_geteuid(kauth_cred_get()));
163 SUBSTITUTE("uid", idtmp, slen);
164 } else if (MATCH("ruid")) {
165 slen = snprintf(idtmp, sizeof(idtmp), "%u",
166 kauth_cred_getuid(kauth_cred_get()));
167 SUBSTITUTE("ruid", idtmp, slen);
168 } else if (MATCH("gid")) {
169 slen = snprintf(idtmp, sizeof(idtmp), "%u",
170 kauth_cred_getegid(kauth_cred_get()));
171 SUBSTITUTE("gid", idtmp, slen);
172 } else if (MATCH("rgid")) {
173 slen = snprintf(idtmp, sizeof(idtmp), "%u",
174 kauth_cred_getgid(kauth_cred_get()));
175 SUBSTITUTE("rgid", idtmp, slen);
176 } else {
177 tmp[newlen++] = '@';
178 if (termchar == VC)
179 tmp[newlen++] = VO;
180 }
181 }
182
183 if (change) {
184 (void)memcpy(cp, tmp, newlen);
185 *len = newlen;
186 }
187 PNBUF_PUT(tmp);
188
189 return 0;
190 }
191
192 #undef VNL
193 #undef VO
194 #undef VC
195 #undef MATCH
196 #undef SUBSTITUTE
197
198 ////////////////////////////////////////////////////////////
199
200 /*
201 * Determine the namei hash (for the namecache) for name.
202 * If *ep != NULL, hash from name to ep-1.
203 * If *ep == NULL, hash from name until the first NUL or '/', and
204 * return the location of this termination character in *ep.
205 *
206 * This function returns an equivalent hash to the MI hash32_strn().
207 * The latter isn't used because in the *ep == NULL case, determining
208 * the length of the string to the first NUL or `/' and then calling
209 * hash32_strn() involves unnecessary double-handling of the data.
210 */
211 uint32_t
212 namei_hash(const char *name, const char **ep)
213 {
214 uint32_t hash;
215
216 hash = HASH32_STR_INIT;
217 if (*ep != NULL) {
218 for (; name < *ep; name++)
219 hash = hash * 33 + *(const uint8_t *)name;
220 } else {
221 for (; *name != '\0' && *name != '/'; name++)
222 hash = hash * 33 + *(const uint8_t *)name;
223 *ep = name;
224 }
225 return (hash + (hash >> 5));
226 }
227
228 ////////////////////////////////////////////////////////////
229
230 /*
231 * Sealed abstraction for pathnames.
232 *
233 * System-call-layer level code that is going to call namei should
234 * first create a pathbuf and adjust all the bells and whistles on it
235 * as needed by context.
236 */
237
238 struct pathbuf {
239 char *pb_path;
240 char *pb_pathcopy;
241 unsigned pb_pathcopyuses;
242 };
243
244 static struct pathbuf *
245 pathbuf_create_raw(void)
246 {
247 struct pathbuf *pb;
248
249 pb = kmem_alloc(sizeof(*pb), KM_SLEEP);
250 pb->pb_path = PNBUF_GET();
251 if (pb->pb_path == NULL) {
252 kmem_free(pb, sizeof(*pb));
253 return NULL;
254 }
255 pb->pb_pathcopy = NULL;
256 pb->pb_pathcopyuses = 0;
257 return pb;
258 }
259
260 void
261 pathbuf_destroy(struct pathbuf *pb)
262 {
263 KASSERT(pb->pb_pathcopyuses == 0);
264 KASSERT(pb->pb_pathcopy == NULL);
265 PNBUF_PUT(pb->pb_path);
266 kmem_free(pb, sizeof(*pb));
267 }
268
269 struct pathbuf *
270 pathbuf_assimilate(char *pnbuf)
271 {
272 struct pathbuf *pb;
273
274 pb = kmem_alloc(sizeof(*pb), KM_SLEEP);
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 * 1. whether a pointer is kernel or user should be statically checkable.
322 * 2. copyin should be handled by the upper part of the syscall layer,
323 * not in here.
324 */
325 int
326 pathbuf_maybe_copyin(const char *path, enum uio_seg seg, struct pathbuf **ret)
327 {
328 if (seg == UIO_USERSPACE) {
329 return pathbuf_copyin(path, ret);
330 } else {
331 *ret = pathbuf_create(path);
332 if (*ret == NULL) {
333 return ENOMEM;
334 }
335 return 0;
336 }
337 }
338
339 /*
340 * Get a copy of the path buffer as it currently exists. If this is
341 * called after namei starts the results may be arbitrary.
342 */
343 void
344 pathbuf_copystring(const struct pathbuf *pb, char *buf, size_t maxlen)
345 {
346 strlcpy(buf, pb->pb_path, maxlen);
347 }
348
349 /*
350 * These two functions allow access to a saved copy of the original
351 * path string. The first copy should be gotten before namei is
352 * called. Each copy that is gotten should be put back.
353 */
354
355 const char *
356 pathbuf_stringcopy_get(struct pathbuf *pb)
357 {
358 if (pb->pb_pathcopyuses == 0) {
359 pb->pb_pathcopy = PNBUF_GET();
360 strcpy(pb->pb_pathcopy, pb->pb_path);
361 }
362 pb->pb_pathcopyuses++;
363 return pb->pb_pathcopy;
364 }
365
366 void
367 pathbuf_stringcopy_put(struct pathbuf *pb, const char *str)
368 {
369 KASSERT(str == pb->pb_pathcopy);
370 KASSERT(pb->pb_pathcopyuses > 0);
371 pb->pb_pathcopyuses--;
372 if (pb->pb_pathcopyuses == 0) {
373 PNBUF_PUT(pb->pb_pathcopy);
374 pb->pb_pathcopy = NULL;
375 }
376 }
377
378
379 ////////////////////////////////////////////////////////////
380
381 /*
382 * namei: convert a pathname into a pointer to a (maybe-locked) vnode,
383 * and maybe also its parent directory vnode, and assorted other guff.
384 * See namei(9) for the interface documentation.
385 *
386 *
387 * The FOLLOW flag is set when symbolic links are to be followed
388 * when they occur at the end of the name translation process.
389 * Symbolic links are always followed for all other pathname
390 * components other than the last.
391 *
392 * The segflg defines whether the name is to be copied from user
393 * space or kernel space.
394 *
395 * Overall outline of namei:
396 *
397 * copy in name
398 * get starting directory
399 * while (!done && !error) {
400 * call lookup to search path.
401 * if symbolic link, massage name in buffer and continue
402 * }
403 */
404
405 /*
406 * Search a pathname.
407 * This is a very central and rather complicated routine.
408 *
409 * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
410 * The starting directory is passed in. The pathname is descended
411 * until done, or a symbolic link is encountered. The variable ni_more
412 * is clear if the path is completed; it is set to one if a symbolic
413 * link needing interpretation is encountered.
414 *
415 * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
416 * whether the name is to be looked up, created, renamed, or deleted.
417 * When CREATE, RENAME, or DELETE is specified, information usable in
418 * creating, renaming, or deleting a directory entry may be calculated.
419 * If flag has LOCKPARENT or'ed into it, the parent directory is returned
420 * locked. Otherwise the parent directory is not returned. If the target
421 * of the pathname exists and LOCKLEAF is or'ed into the flag the target
422 * is returned locked, otherwise it is returned unlocked. When creating
423 * or renaming and LOCKPARENT is specified, the target may not be ".".
424 * When deleting and LOCKPARENT is specified, the target may be ".".
425 *
426 * Overall outline of lookup:
427 *
428 * dirloop:
429 * identify next component of name at ndp->ni_ptr
430 * handle degenerate case where name is null string
431 * if .. and crossing mount points and on mounted filesys, find parent
432 * call VOP_LOOKUP routine for next component name
433 * directory vnode returned in ni_dvp, locked.
434 * component vnode returned in ni_vp (if it exists), locked.
435 * if result vnode is mounted on and crossing mount points,
436 * find mounted on vnode
437 * if more components of name, do next level at dirloop
438 * return the answer in ni_vp, locked if LOCKLEAF set
439 * if LOCKPARENT set, return locked parent in ni_dvp
440 */
441
442
443 /*
444 * Internal state for a namei operation.
445 *
446 * cnp is always equal to &ndp->ni_cnp.
447 */
448 struct namei_state {
449 struct nameidata *ndp;
450 struct componentname *cnp;
451
452 int docache; /* == 0 do not cache last component */
453 int rdonly; /* lookup read-only flag bit */
454 int slashes;
455
456 unsigned attempt_retry:1; /* true if error allows emul retry */
457 unsigned root_referenced:1; /* true if ndp->ni_rootdir and
458 ndp->ni_erootdir were referenced */
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
469 state->ndp = ndp;
470 state->cnp = &ndp->ni_cnd;
471
472 state->docache = 0;
473 state->rdonly = 0;
474 state->slashes = 0;
475
476 state->root_referenced = 0;
477
478 KASSERTMSG((state->cnp->cn_cred != NULL), "namei: bad cred/proc");
479 KASSERTMSG(((state->cnp->cn_nameiop & (~OPMASK)) == 0),
480 "namei: nameiop contaminated with flags: %08"PRIx32,
481 state->cnp->cn_nameiop);
482 KASSERTMSG(((state->cnp->cn_flags & OPMASK) == 0),
483 "name: flags contaminated with nameiops: %08"PRIx32,
484 state->cnp->cn_flags);
485
486 /*
487 * The buffer for name translation shall be the one inside the
488 * pathbuf.
489 */
490 state->ndp->ni_pnbuf = state->ndp->ni_pathbuf->pb_path;
491 }
492
493 /*
494 * Clean up the working namei state, leaving things ready for return
495 * from namei.
496 */
497 static void
498 namei_cleanup(struct namei_state *state)
499 {
500 KASSERT(state->cnp == &state->ndp->ni_cnd);
501
502 if (state->root_referenced) {
503 if (state->ndp->ni_rootdir != NULL)
504 vrele(state->ndp->ni_rootdir);
505 if (state->ndp->ni_erootdir != NULL)
506 vrele(state->ndp->ni_erootdir);
507 }
508 }
509
510 //////////////////////////////
511
512 /*
513 * Get the directory context.
514 * Initializes the rootdir and erootdir state and returns a reference
515 * to the starting dir.
516 */
517 static struct vnode *
518 namei_getstartdir(struct namei_state *state)
519 {
520 struct nameidata *ndp = state->ndp;
521 struct componentname *cnp = state->cnp;
522 struct cwdinfo *cwdi; /* pointer to cwd state */
523 struct lwp *self = curlwp; /* thread doing namei() */
524 struct vnode *rootdir, *erootdir, *curdir, *startdir;
525
526 if (state->root_referenced) {
527 if (state->ndp->ni_rootdir != NULL)
528 vrele(state->ndp->ni_rootdir);
529 if (state->ndp->ni_erootdir != NULL)
530 vrele(state->ndp->ni_erootdir);
531 state->root_referenced = 0;
532 }
533
534 cwdi = self->l_proc->p_cwdi;
535 rw_enter(&cwdi->cwdi_lock, RW_READER);
536
537 /* root dir */
538 if (cwdi->cwdi_rdir == NULL || (cnp->cn_flags & NOCHROOT)) {
539 rootdir = rootvnode;
540 } else {
541 rootdir = cwdi->cwdi_rdir;
542 }
543
544 /* emulation root dir, if any */
545 if ((cnp->cn_flags & TRYEMULROOT) == 0) {
546 /* if we don't want it, don't fetch it */
547 erootdir = NULL;
548 } else if (cnp->cn_flags & EMULROOTSET) {
549 /* explicitly set emulroot; "/../" doesn't override this */
550 erootdir = ndp->ni_erootdir;
551 } else if (!strncmp(ndp->ni_pnbuf, "/../", 4)) {
552 /* explicit reference to real rootdir */
553 erootdir = NULL;
554 } else {
555 /* may be null */
556 erootdir = cwdi->cwdi_edir;
557 }
558
559 /* current dir */
560 curdir = cwdi->cwdi_cdir;
561
562 if (ndp->ni_pnbuf[0] != '/') {
563 if (ndp->ni_atdir != NULL) {
564 startdir = ndp->ni_atdir;
565 } else {
566 startdir = curdir;
567 }
568 erootdir = NULL;
569 } else if (cnp->cn_flags & TRYEMULROOT && erootdir != NULL) {
570 startdir = erootdir;
571 } else {
572 startdir = rootdir;
573 erootdir = NULL;
574 }
575
576 state->ndp->ni_rootdir = rootdir;
577 state->ndp->ni_erootdir = erootdir;
578
579 /*
580 * Get a reference to the start dir so we can safely unlock cwdi.
581 *
582 * Must hold references to rootdir and erootdir while we're running.
583 * A multithreaded process may chroot during namei.
584 */
585 if (startdir != NULL)
586 vref(startdir);
587 if (state->ndp->ni_rootdir != NULL)
588 vref(state->ndp->ni_rootdir);
589 if (state->ndp->ni_erootdir != NULL)
590 vref(state->ndp->ni_erootdir);
591 state->root_referenced = 1;
592
593 rw_exit(&cwdi->cwdi_lock);
594 return startdir;
595 }
596
597 /*
598 * Get the directory context for the nfsd case, in parallel to
599 * getstartdir. Initializes the rootdir and erootdir state and
600 * returns a reference to the passed-in starting dir.
601 */
602 static struct vnode *
603 namei_getstartdir_for_nfsd(struct namei_state *state)
604 {
605 KASSERT(state->ndp->ni_atdir != NULL);
606
607 /* always use the real root, and never set an emulation root */
608 if (rootvnode == NULL) {
609 return NULL;
610 }
611 state->ndp->ni_rootdir = rootvnode;
612 state->ndp->ni_erootdir = NULL;
613
614 vref(state->ndp->ni_atdir);
615 KASSERT(! state->root_referenced);
616 vref(state->ndp->ni_rootdir);
617 state->root_referenced = 1;
618 return state->ndp->ni_atdir;
619 }
620
621
622 /*
623 * Ktrace the namei operation.
624 */
625 static void
626 namei_ktrace(struct namei_state *state)
627 {
628 struct nameidata *ndp = state->ndp;
629 struct componentname *cnp = state->cnp;
630 struct lwp *self = curlwp; /* thread doing namei() */
631 const char *emul_path;
632
633 if (ktrpoint(KTR_NAMEI)) {
634 if (ndp->ni_erootdir != NULL) {
635 /*
636 * To make any sense, the trace entry need to have the
637 * text of the emulation path prepended.
638 * Usually we can get this from the current process,
639 * but when called from emul_find_interp() it is only
640 * in the exec_package - so we get it passed in ni_next
641 * (this is a hack).
642 */
643 if (cnp->cn_flags & EMULROOTSET)
644 emul_path = ndp->ni_next;
645 else
646 emul_path = self->l_proc->p_emul->e_path;
647 ktrnamei2(emul_path, strlen(emul_path),
648 ndp->ni_pnbuf, ndp->ni_pathlen);
649 } else
650 ktrnamei(ndp->ni_pnbuf, ndp->ni_pathlen);
651 }
652 }
653
654 /*
655 * Start up namei. Find the root dir and cwd, establish the starting
656 * directory for lookup, and lock it. Also calls ktrace when
657 * appropriate.
658 */
659 static int
660 namei_start(struct namei_state *state, int isnfsd,
661 struct vnode **startdir_ret)
662 {
663 struct nameidata *ndp = state->ndp;
664 struct vnode *startdir;
665
666 /* length includes null terminator (was originally from copyinstr) */
667 ndp->ni_pathlen = strlen(ndp->ni_pnbuf) + 1;
668
669 /*
670 * POSIX.1 requirement: "" is not a valid file name.
671 */
672 if (ndp->ni_pathlen == 1) {
673 ndp->ni_erootdir = NULL;
674 return ENOENT;
675 }
676
677 ndp->ni_loopcnt = 0;
678
679 /* Get starting directory, set up root, and ktrace. */
680 if (isnfsd) {
681 startdir = namei_getstartdir_for_nfsd(state);
682 /* no ktrace */
683 } else {
684 startdir = namei_getstartdir(state);
685 namei_ktrace(state);
686 }
687
688 if (startdir == NULL) {
689 return ENOENT;
690 }
691
692 /* NDAT may feed us with a non directory namei_getstartdir */
693 if (startdir->v_type != VDIR) {
694 vrele(startdir);
695 return ENOTDIR;
696 }
697
698 *startdir_ret = startdir;
699 return 0;
700 }
701
702 /*
703 * Check for being at a symlink that we're going to follow.
704 */
705 static inline int
706 namei_atsymlink(struct namei_state *state, struct vnode *foundobj)
707 {
708 return (foundobj->v_type == VLNK) &&
709 (state->cnp->cn_flags & (FOLLOW|REQUIREDIR));
710 }
711
712 /*
713 * Follow a symlink.
714 *
715 * Updates searchdir. inhibitmagic causes magic symlinks to not be
716 * interpreted; this is used by nfsd.
717 *
718 * Unlocks foundobj on success (ugh)
719 */
720 static inline int
721 namei_follow(struct namei_state *state, int inhibitmagic,
722 struct vnode *searchdir, struct vnode *foundobj,
723 struct vnode **newsearchdir_ret)
724 {
725 struct nameidata *ndp = state->ndp;
726 struct componentname *cnp = state->cnp;
727
728 struct lwp *self = curlwp; /* thread doing namei() */
729 struct iovec aiov; /* uio for reading symbolic links */
730 struct uio auio;
731 char *cp; /* pointer into pathname argument */
732 size_t linklen;
733 int error;
734
735 if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
736 return ELOOP;
737 }
738
739 vn_lock(foundobj, LK_EXCLUSIVE | LK_RETRY);
740 if (foundobj->v_mount->mnt_flag & MNT_SYMPERM) {
741 error = VOP_ACCESS(foundobj, VEXEC, cnp->cn_cred);
742 if (error != 0) {
743 VOP_UNLOCK(foundobj);
744 return error;
745 }
746 }
747
748 /* FUTURE: fix this to not use a second buffer */
749 cp = PNBUF_GET();
750 aiov.iov_base = cp;
751 aiov.iov_len = MAXPATHLEN;
752 auio.uio_iov = &aiov;
753 auio.uio_iovcnt = 1;
754 auio.uio_offset = 0;
755 auio.uio_rw = UIO_READ;
756 auio.uio_resid = MAXPATHLEN;
757 UIO_SETUP_SYSSPACE(&auio);
758 error = VOP_READLINK(foundobj, &auio, cnp->cn_cred);
759 VOP_UNLOCK(foundobj);
760 if (error) {
761 PNBUF_PUT(cp);
762 return error;
763 }
764 linklen = MAXPATHLEN - auio.uio_resid;
765 if (linklen == 0) {
766 PNBUF_PUT(cp);
767 return ENOENT;
768 }
769
770 /*
771 * Do symlink substitution, if appropriate, and
772 * check length for potential overflow.
773 *
774 * Inhibit symlink substitution for nfsd.
775 * XXX: This is how it was before; is that a bug or a feature?
776 */
777 if ((!inhibitmagic && vfs_magiclinks &&
778 symlink_magic(self->l_proc, cp, &linklen)) ||
779 (linklen + ndp->ni_pathlen >= MAXPATHLEN)) {
780 PNBUF_PUT(cp);
781 return ENAMETOOLONG;
782 }
783 if (ndp->ni_pathlen > 1) {
784 /* includes a null-terminator */
785 memcpy(cp + linklen, ndp->ni_next, ndp->ni_pathlen);
786 } else {
787 cp[linklen] = '\0';
788 }
789 ndp->ni_pathlen += linklen;
790 memcpy(ndp->ni_pnbuf, cp, ndp->ni_pathlen);
791 PNBUF_PUT(cp);
792
793 /* we're now starting from the beginning of the buffer again */
794 cnp->cn_nameptr = ndp->ni_pnbuf;
795
796 /*
797 * Check if root directory should replace current directory.
798 */
799 if (ndp->ni_pnbuf[0] == '/') {
800 vrele(searchdir);
801 /* Keep absolute symbolic links inside emulation root */
802 searchdir = ndp->ni_erootdir;
803 if (searchdir == NULL ||
804 (ndp->ni_pnbuf[1] == '.'
805 && ndp->ni_pnbuf[2] == '.'
806 && ndp->ni_pnbuf[3] == '/')) {
807 ndp->ni_erootdir = NULL;
808 searchdir = ndp->ni_rootdir;
809 }
810 vref(searchdir);
811 while (cnp->cn_nameptr[0] == '/') {
812 cnp->cn_nameptr++;
813 ndp->ni_pathlen--;
814 }
815 }
816
817 *newsearchdir_ret = searchdir;
818 return 0;
819 }
820
821 //////////////////////////////
822
823 /*
824 * Inspect the leading path component and update the state accordingly.
825 */
826 static int
827 lookup_parsepath(struct namei_state *state, struct vnode *searchdir)
828 {
829 const char *cp; /* pointer into pathname argument */
830 int error;
831
832 struct componentname *cnp = state->cnp;
833 struct nameidata *ndp = state->ndp;
834
835 KASSERT(cnp == &ndp->ni_cnd);
836
837 /*
838 * Search a new directory.
839 *
840 * The last component of the filename is left accessible via
841 * cnp->cn_nameptr for callers that need the name. Callers needing
842 * the name set the SAVENAME flag. When done, they assume
843 * responsibility for freeing the pathname buffer.
844 *
845 * At this point, our only vnode state is that the search dir
846 * is held.
847 */
848 cnp->cn_consume = 0;
849 error = VOP_PARSEPATH(searchdir, cnp->cn_nameptr, &cnp->cn_namelen);
850 if (error) {
851 return error;
852 }
853 cp = cnp->cn_nameptr + cnp->cn_namelen;
854 if (cnp->cn_namelen > KERNEL_NAME_MAX) {
855 return ENAMETOOLONG;
856 }
857 #ifdef NAMEI_DIAGNOSTIC
858 { char c = *cp;
859 *(char *)cp = '\0';
860 printf("{%s}: ", cnp->cn_nameptr);
861 *(char *)cp = c; }
862 #endif /* NAMEI_DIAGNOSTIC */
863 ndp->ni_pathlen -= cnp->cn_namelen;
864 ndp->ni_next = cp;
865 /*
866 * If this component is followed by a slash, then move the pointer to
867 * the next component forward, and remember that this component must be
868 * a directory.
869 */
870 if (*cp == '/') {
871 do {
872 cp++;
873 } while (*cp == '/');
874 state->slashes = cp - ndp->ni_next;
875 ndp->ni_pathlen -= state->slashes;
876 ndp->ni_next = cp;
877 cnp->cn_flags |= REQUIREDIR;
878 } else {
879 state->slashes = 0;
880 cnp->cn_flags &= ~REQUIREDIR;
881 }
882 /*
883 * We do special processing on the last component, whether or not it's
884 * a directory. Cache all intervening lookups, but not the final one.
885 */
886 if (*cp == '\0') {
887 if (state->docache)
888 cnp->cn_flags |= MAKEENTRY;
889 else
890 cnp->cn_flags &= ~MAKEENTRY;
891 cnp->cn_flags |= ISLASTCN;
892 } else {
893 cnp->cn_flags |= MAKEENTRY;
894 cnp->cn_flags &= ~ISLASTCN;
895 }
896 if (cnp->cn_namelen == 2 &&
897 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
898 cnp->cn_flags |= ISDOTDOT;
899 else
900 cnp->cn_flags &= ~ISDOTDOT;
901
902 return 0;
903 }
904
905 /*
906 * Take care of crossing a mounted-on vnode. On error, foundobj_ret will be
907 * vrele'd, but searchdir is left alone.
908 */
909 static int
910 lookup_crossmount(struct namei_state *state,
911 struct vnode **searchdir_ret,
912 struct vnode **foundobj_ret,
913 bool *searchdir_locked)
914 {
915 struct componentname *cnp = state->cnp;
916 struct vnode *foundobj, *vp;
917 struct vnode *searchdir;
918 struct mount *mp;
919 int error, lktype;
920
921 searchdir = *searchdir_ret;
922 foundobj = *foundobj_ret;
923 error = 0;
924
925 KASSERT((cnp->cn_flags & NOCROSSMOUNT) == 0);
926
927 /* First, unlock searchdir (oof). */
928 if (*searchdir_locked) {
929 KASSERT(searchdir != NULL);
930 lktype = VOP_ISLOCKED(searchdir);
931 VOP_UNLOCK(searchdir);
932 *searchdir_locked = false;
933 } else {
934 lktype = LK_NONE;
935 }
936
937 /*
938 * Do an unlocked check to see if the vnode has been mounted on; if
939 * so find the root of the mounted file system.
940 */
941 while (foundobj->v_type == VDIR &&
942 (mp = foundobj->v_mountedhere) != NULL &&
943 (cnp->cn_flags & NOCROSSMOUNT) == 0) {
944 KASSERTMSG(searchdir != foundobj, "same vn %p", searchdir);
945
946 /*
947 * Try the namecache first. If that doesn't work, do
948 * it the hard way.
949 */
950 if (cache_lookup_mount(foundobj, &vp)) {
951 vrele(foundobj);
952 foundobj = vp;
953 } else {
954 /* First get the vnode stable. */
955 error = vn_lock(foundobj, LK_SHARED);
956 if (error != 0) {
957 vrele(foundobj);
958 foundobj = NULL;
959 break;
960 }
961
962 /*
963 * Check to see if something is still mounted on it.
964 */
965 if ((mp = foundobj->v_mountedhere) == NULL) {
966 VOP_UNLOCK(foundobj);
967 break;
968 }
969
970 /*
971 * Get a reference to the mountpoint, and unlock
972 * foundobj.
973 */
974 error = vfs_busy(mp);
975 VOP_UNLOCK(foundobj);
976 if (error != 0) {
977 vrele(foundobj);
978 foundobj = NULL;
979 break;
980 }
981
982 /*
983 * Now get a reference on the root vnode.
984 * XXX Future - maybe allow only VDIR here.
985 */
986 error = VFS_ROOT(mp, LK_NONE, &vp);
987
988 /*
989 * If successful, enter it into the cache while
990 * holding the mount busy (competing with unmount).
991 */
992 if (error == 0) {
993 cache_enter_mount(foundobj, vp);
994 }
995
996 /* Finally, drop references to foundobj & mountpoint. */
997 vrele(foundobj);
998 vfs_unbusy(mp);
999 if (error) {
1000 foundobj = NULL;
1001 break;
1002 }
1003 foundobj = vp;
1004 }
1005
1006 /*
1007 * Avoid locking vnodes from two filesystems because
1008 * it's prone to deadlock, e.g. when using puffs.
1009 * Also, it isn't a good idea to propagate slowness of
1010 * a filesystem up to the root directory. For now,
1011 * only handle the common case, where foundobj is
1012 * VDIR.
1013 *
1014 * In this case set searchdir to null to avoid using
1015 * it again. It is not correct to set searchdir ==
1016 * foundobj here as that will confuse the caller.
1017 * (See PR 40740.)
1018 */
1019 if (searchdir == NULL) {
1020 /* already been here once; do nothing further */
1021 } else if (foundobj->v_type == VDIR) {
1022 vrele(searchdir);
1023 *searchdir_ret = searchdir = NULL;
1024 lktype = LK_NONE;
1025 }
1026 }
1027
1028 /* If searchdir is still around, re-lock it. */
1029 if (error == 0 && lktype != LK_NONE) {
1030 vn_lock(searchdir, lktype | LK_RETRY);
1031 *searchdir_locked = true;
1032 }
1033 *foundobj_ret = foundobj;
1034 return error;
1035 }
1036
1037 /*
1038 * Determine the desired locking mode for the directory of a lookup.
1039 */
1040 static int
1041 lookup_lktype(struct vnode *searchdir, struct componentname *cnp)
1042 {
1043
1044 /*
1045 * If the file system supports VOP_LOOKUP() with a shared lock, and
1046 * we are not making any modifications (nameiop LOOKUP) or this is
1047 * not the last component then get a shared lock. Where we can't do
1048 * fast-forwarded lookups (for example with layered file systems)
1049 * then this is the fallback for reducing lock contention.
1050 */
1051 if ((searchdir->v_mount->mnt_iflag & IMNT_SHRLOOKUP) != 0 &&
1052 (cnp->cn_nameiop == LOOKUP || (cnp->cn_flags & ISLASTCN) == 0)) {
1053 return LK_SHARED;
1054 } else {
1055 return LK_EXCLUSIVE;
1056 }
1057 }
1058
1059 /*
1060 * Call VOP_LOOKUP for a single lookup; return a new search directory
1061 * (used when crossing mountpoints up or searching union mounts down) and
1062 * the found object, which for create operations may be NULL on success.
1063 *
1064 * Note that the new search directory may be null, which means the
1065 * searchdir was unlocked and released. This happens in the common case
1066 * when crossing a mount point downwards, in order to avoid coupling
1067 * locks between different file system volumes. Importantly, this can
1068 * happen even if the call fails. (XXX: this is gross and should be
1069 * tidied somehow.)
1070 */
1071 static int
1072 lookup_once(struct namei_state *state,
1073 struct vnode *searchdir,
1074 struct vnode **newsearchdir_ret,
1075 struct vnode **foundobj_ret,
1076 bool *newsearchdir_locked_ret)
1077 {
1078 struct vnode *tmpvn; /* scratch vnode */
1079 struct vnode *foundobj; /* result */
1080 struct lwp *l = curlwp;
1081 bool searchdir_locked = false;
1082 int error, lktype;
1083
1084 struct componentname *cnp = state->cnp;
1085 struct nameidata *ndp = state->ndp;
1086
1087 KASSERT(cnp == &ndp->ni_cnd);
1088 *newsearchdir_ret = searchdir;
1089
1090 /*
1091 * Handle "..": two special cases.
1092 * 1. If at root directory (e.g. after chroot)
1093 * or at absolute root directory
1094 * then ignore it so can't get out.
1095 * 1a. If at the root of the emulation filesystem go to the real
1096 * root. So "/../<path>" is always absolute.
1097 * 1b. If we have somehow gotten out of a jail, warn
1098 * and also ignore it so we can't get farther out.
1099 * 2. If this vnode is the root of a mounted
1100 * filesystem, then replace it with the
1101 * vnode which was mounted on so we take the
1102 * .. in the other file system.
1103 */
1104 if (cnp->cn_flags & ISDOTDOT) {
1105 struct proc *p = l->l_proc;
1106
1107 for (;;) {
1108 if (searchdir == ndp->ni_rootdir ||
1109 searchdir == rootvnode) {
1110 foundobj = searchdir;
1111 vref(foundobj);
1112 *foundobj_ret = foundobj;
1113 if (cnp->cn_flags & LOCKPARENT) {
1114 lktype = lookup_lktype(searchdir, cnp);
1115 vn_lock(searchdir, lktype | LK_RETRY);
1116 searchdir_locked = true;
1117 }
1118 error = 0;
1119 goto done;
1120 }
1121 if (ndp->ni_rootdir != rootvnode) {
1122 int retval;
1123
1124 retval = vn_isunder(searchdir, ndp->ni_rootdir, l);
1125 if (!retval) {
1126 /* Oops! We got out of jail! */
1127 log(LOG_WARNING,
1128 "chrooted pid %d uid %d (%s) "
1129 "detected outside of its chroot\n",
1130 p->p_pid, kauth_cred_geteuid(l->l_cred),
1131 p->p_comm);
1132 /* Put us at the jail root. */
1133 vrele(searchdir);
1134 searchdir = NULL;
1135 foundobj = ndp->ni_rootdir;
1136 vref(foundobj);
1137 vref(foundobj);
1138 *newsearchdir_ret = foundobj;
1139 *foundobj_ret = foundobj;
1140 error = 0;
1141 goto done;
1142 }
1143 }
1144 if ((searchdir->v_vflag & VV_ROOT) == 0 ||
1145 (cnp->cn_flags & NOCROSSMOUNT))
1146 break;
1147 tmpvn = searchdir;
1148 searchdir = searchdir->v_mount->mnt_vnodecovered;
1149 vref(searchdir);
1150 vrele(tmpvn);
1151 *newsearchdir_ret = searchdir;
1152 }
1153 }
1154
1155 lktype = lookup_lktype(searchdir, cnp);
1156
1157 /*
1158 * We now have a segment name to search for, and a directory to search.
1159 * Our vnode state here is that "searchdir" is held.
1160 */
1161 unionlookup:
1162 foundobj = NULL;
1163 if (!searchdir_locked) {
1164 vn_lock(searchdir, lktype | LK_RETRY);
1165 searchdir_locked = true;
1166 }
1167 error = VOP_LOOKUP(searchdir, &foundobj, cnp);
1168
1169 if (error != 0) {
1170 KASSERTMSG((foundobj == NULL),
1171 "leaf `%s' should be empty but is %p",
1172 cnp->cn_nameptr, foundobj);
1173 #ifdef NAMEI_DIAGNOSTIC
1174 printf("not found\n");
1175 #endif /* NAMEI_DIAGNOSTIC */
1176
1177 /*
1178 * If ENOLCK, the file system needs us to retry the lookup
1179 * with an exclusive lock. It's likely nothing was found in
1180 * cache and/or modifications need to be made.
1181 */
1182 if (error == ENOLCK) {
1183 KASSERT(VOP_ISLOCKED(searchdir) == LK_SHARED);
1184 KASSERT(searchdir_locked);
1185 if (vn_lock(searchdir, LK_UPGRADE | LK_NOWAIT)) {
1186 VOP_UNLOCK(searchdir);
1187 searchdir_locked = false;
1188 }
1189 lktype = LK_EXCLUSIVE;
1190 goto unionlookup;
1191 }
1192
1193 if ((error == ENOENT) &&
1194 (searchdir->v_vflag & VV_ROOT) &&
1195 (searchdir->v_mount->mnt_flag & MNT_UNION)) {
1196 tmpvn = searchdir;
1197 searchdir = searchdir->v_mount->mnt_vnodecovered;
1198 vref(searchdir);
1199 vput(tmpvn);
1200 searchdir_locked = false;
1201 *newsearchdir_ret = searchdir;
1202 goto unionlookup;
1203 }
1204
1205 if (error != EJUSTRETURN)
1206 goto done;
1207
1208 /*
1209 * If this was not the last component, or there were trailing
1210 * slashes, and we are not going to create a directory,
1211 * then the name must exist.
1212 */
1213 if ((cnp->cn_flags & (REQUIREDIR | CREATEDIR)) == REQUIREDIR) {
1214 error = ENOENT;
1215 goto done;
1216 }
1217
1218 /*
1219 * If creating and at end of pathname, then can consider
1220 * allowing file to be created.
1221 */
1222 if (state->rdonly) {
1223 error = EROFS;
1224 goto done;
1225 }
1226
1227 /*
1228 * We return success and a NULL foundobj to indicate
1229 * that the entry doesn't currently exist, leaving a
1230 * pointer to the (normally, locked) directory vnode
1231 * as searchdir.
1232 */
1233 *foundobj_ret = NULL;
1234 error = 0;
1235 goto done;
1236 }
1237 #ifdef NAMEI_DIAGNOSTIC
1238 printf("found\n");
1239 #endif /* NAMEI_DIAGNOSTIC */
1240
1241 /*
1242 * Take into account any additional components consumed by the
1243 * underlying filesystem. This will include any trailing slashes after
1244 * the last component consumed.
1245 */
1246 if (cnp->cn_consume > 0) {
1247 ndp->ni_pathlen -= cnp->cn_consume - state->slashes;
1248 ndp->ni_next += cnp->cn_consume - state->slashes;
1249 cnp->cn_consume = 0;
1250 if (ndp->ni_next[0] == '\0')
1251 cnp->cn_flags |= ISLASTCN;
1252 }
1253
1254 /* Unlock, unless the caller needs the parent locked. */
1255 if (searchdir != NULL) {
1256 KASSERT(searchdir_locked);
1257 if ((cnp->cn_flags & (ISLASTCN | LOCKPARENT)) !=
1258 (ISLASTCN | LOCKPARENT)) {
1259 VOP_UNLOCK(searchdir);
1260 searchdir_locked = false;
1261 }
1262 } else {
1263 KASSERT(!searchdir_locked);
1264 }
1265
1266 *foundobj_ret = foundobj;
1267 error = 0;
1268 done:
1269 *newsearchdir_locked_ret = searchdir_locked;
1270 return error;
1271 }
1272
1273 /*
1274 * Parse out the first path name component that we need to to consider.
1275 *
1276 * While doing this, attempt to use the name cache to fast-forward through
1277 * as many "easy" to find components of the path as possible.
1278 *
1279 * We use the namecache's node locks to form a chain, and avoid as many
1280 * vnode references and locks as possible. In the ideal case, only the
1281 * final vnode will have its reference count adjusted and lock taken.
1282 */
1283 static int
1284 lookup_fastforward(struct namei_state *state, struct vnode **searchdir_ret,
1285 struct vnode **foundobj_ret)
1286 {
1287 struct componentname *cnp = state->cnp;
1288 struct nameidata *ndp = state->ndp;
1289 krwlock_t *plock;
1290 struct vnode *foundobj, *searchdir;
1291 int error, error2;
1292 size_t oldpathlen;
1293 const char *oldnameptr;
1294 bool terminal;
1295
1296 /*
1297 * Eat as many path name components as possible before giving up and
1298 * letting lookup_once() handle it. Remember the starting point in
1299 * case we can't get vnode references and need to roll back.
1300 */
1301 plock = NULL;
1302 searchdir = *searchdir_ret;
1303 oldnameptr = cnp->cn_nameptr;
1304 oldpathlen = ndp->ni_pathlen;
1305 terminal = false;
1306 for (;;) {
1307 foundobj = NULL;
1308
1309 /*
1310 * Get the next component name. There should be no slashes
1311 * here, and we shouldn't have looped around if we were
1312 * done.
1313 */
1314 KASSERT(cnp->cn_nameptr[0] != '/');
1315 KASSERT(cnp->cn_nameptr[0] != '\0');
1316 if ((error = lookup_parsepath(state, searchdir)) != 0) {
1317 break;
1318 }
1319
1320 /*
1321 * Can't deal with DOTDOT lookups if NOCROSSMOUNT or the
1322 * lookup is chrooted.
1323 */
1324 if ((cnp->cn_flags & ISDOTDOT) != 0) {
1325 if ((searchdir->v_vflag & VV_ROOT) != 0 &&
1326 (cnp->cn_flags & NOCROSSMOUNT)) {
1327 error = EOPNOTSUPP;
1328 break;
1329 }
1330 if (ndp->ni_rootdir != rootvnode) {
1331 error = EOPNOTSUPP;
1332 break;
1333 }
1334 }
1335
1336 /*
1337 * Can't deal with last component when modifying; this needs
1338 * searchdir locked and VOP_LOOKUP() called (which can and
1339 * does modify state, despite the name). NB: this case means
1340 * terminal is never set true when LOCKPARENT.
1341 */
1342 if ((cnp->cn_flags & ISLASTCN) != 0) {
1343 if (cnp->cn_nameiop != LOOKUP ||
1344 (cnp->cn_flags & LOCKPARENT) != 0) {
1345 error = EOPNOTSUPP;
1346 break;
1347 }
1348 }
1349
1350 /*
1351 * Good, now look for it in cache. cache_lookup_linked()
1352 * will fail if there's nothing there, or if there's no
1353 * ownership info for the directory, or if the user doesn't
1354 * have permission to look up files in this directory.
1355 */
1356 if (!cache_lookup_linked(searchdir, cnp->cn_nameptr,
1357 cnp->cn_namelen, &foundobj, &plock, cnp->cn_cred)) {
1358 error = EOPNOTSUPP;
1359 break;
1360 }
1361 KASSERT(plock != NULL && rw_lock_held(plock));
1362
1363 /*
1364 * Scored a hit. Negative is good too (ENOENT). If there's
1365 * a '-o union' mount here, punt and let lookup_once() deal
1366 * with it.
1367 */
1368 if (foundobj == NULL) {
1369 if ((searchdir->v_vflag & VV_ROOT) != 0 &&
1370 (searchdir->v_mount->mnt_flag & MNT_UNION) != 0) {
1371 error = EOPNOTSUPP;
1372 } else {
1373 error = ENOENT;
1374 terminal = ((cnp->cn_flags & ISLASTCN) != 0);
1375 }
1376 break;
1377 }
1378
1379 /*
1380 * Stop and get a hold on the vnode if we've encountered
1381 * something other than a dirctory.
1382 */
1383 if (foundobj->v_type != VDIR) {
1384 error = vcache_tryvget(foundobj);
1385 if (error != 0) {
1386 foundobj = NULL;
1387 error = EOPNOTSUPP;
1388 } else {
1389 terminal = (foundobj->v_type != VLNK &&
1390 (cnp->cn_flags & ISLASTCN) != 0);
1391 }
1392 break;
1393 }
1394
1395 /*
1396 * Try to cross mountpoints, bearing in mind that they can
1397 * be stacked. If at any point we can't go further, stop
1398 * and try to get a reference on the vnode. If we are able
1399 * to get a ref then lookup_crossmount() will take care of
1400 * it, otherwise we'll fall through to lookup_once().
1401 */
1402 if (foundobj->v_mountedhere != NULL) {
1403 while (foundobj->v_mountedhere != NULL &&
1404 (cnp->cn_flags & NOCROSSMOUNT) == 0 &&
1405 cache_cross_mount(&foundobj, &plock)) {
1406 KASSERT(foundobj != NULL);
1407 KASSERT(foundobj->v_type == VDIR);
1408 }
1409 if (foundobj->v_mountedhere != NULL) {
1410 error = vcache_tryvget(foundobj);
1411 if (error != 0) {
1412 foundobj = NULL;
1413 error = EOPNOTSUPP;
1414 }
1415 break;
1416 } else {
1417 searchdir = NULL;
1418 }
1419 }
1420
1421 /*
1422 * Time to stop if we found the last component & traversed
1423 * all mounts.
1424 */
1425 if ((cnp->cn_flags & ISLASTCN) != 0) {
1426 error = vcache_tryvget(foundobj);
1427 if (error != 0) {
1428 foundobj = NULL;
1429 error = EOPNOTSUPP;
1430 } else {
1431 terminal = (foundobj->v_type != VLNK);
1432 }
1433 break;
1434 }
1435
1436 /*
1437 * Otherwise, we're still in business. Set the found VDIR
1438 * vnode as the search dir for the next component and
1439 * continue on to it.
1440 */
1441 cnp->cn_nameptr = ndp->ni_next;
1442 searchdir = foundobj;
1443 }
1444
1445 if (terminal) {
1446 /*
1447 * If we exited the loop above having successfully located
1448 * the last component with a zero error code, and it's not a
1449 * symbolic link, then the parent directory is not needed.
1450 * Release reference to the starting parent and make the
1451 * terminal parent disappear into thin air.
1452 */
1453 KASSERT(plock != NULL);
1454 rw_exit(plock);
1455 vrele(*searchdir_ret);
1456 *searchdir_ret = NULL;
1457 } else if (searchdir != *searchdir_ret) {
1458 /*
1459 * Otherwise we need to return the parent. If we ended up
1460 * with a new search dir, ref it before dropping the
1461 * namecache's lock. The lock prevents both searchdir and
1462 * foundobj from disappearing. If we can't ref the new
1463 * searchdir, we have a bit of a problem. Roll back the
1464 * fastforward to the beginning and let lookup_once() take
1465 * care of it.
1466 */
1467 if (searchdir == NULL) {
1468 /*
1469 * It's possible for searchdir to be NULL in the
1470 * case of a root vnode being reclaimed while
1471 * trying to cross a mount.
1472 */
1473 error2 = EOPNOTSUPP;
1474 } else {
1475 error2 = vcache_tryvget(searchdir);
1476 }
1477 KASSERT(plock != NULL);
1478 rw_exit(plock);
1479 if (__predict_true(error2 == 0)) {
1480 /* Returning new searchdir, and maybe new foundobj. */
1481 vrele(*searchdir_ret);
1482 *searchdir_ret = searchdir;
1483 } else {
1484 /* Returning nothing. */
1485 if (foundobj != NULL) {
1486 vrele(foundobj);
1487 foundobj = NULL;
1488 }
1489 cnp->cn_nameptr = oldnameptr;
1490 ndp->ni_pathlen = oldpathlen;
1491 if (searchdir == NULL) {
1492 error = EOPNOTSUPP;
1493 } else {
1494 error = lookup_parsepath(state, searchdir);
1495 if (error == 0) {
1496 error = EOPNOTSUPP;
1497 }
1498 }
1499 }
1500 } else if (plock != NULL) {
1501 /* Drop any namecache lock still held. */
1502 rw_exit(plock);
1503 }
1504
1505 KASSERT(error == 0 ? foundobj != NULL : foundobj == NULL);
1506 *foundobj_ret = foundobj;
1507 return error;
1508 }
1509
1510 //////////////////////////////
1511
1512 /*
1513 * Do a complete path search from a single root directory.
1514 * (This is called up to twice if TRYEMULROOT is in effect.)
1515 */
1516 static int
1517 namei_oneroot(struct namei_state *state,
1518 int neverfollow, int inhibitmagic, int isnfsd)
1519 {
1520 struct nameidata *ndp = state->ndp;
1521 struct componentname *cnp = state->cnp;
1522 struct vnode *searchdir, *foundobj;
1523 bool searchdir_locked = false;
1524 int error;
1525
1526 error = namei_start(state, isnfsd, &searchdir);
1527 if (error) {
1528 ndp->ni_dvp = NULL;
1529 ndp->ni_vp = NULL;
1530 return error;
1531 }
1532 KASSERT(searchdir->v_type == VDIR);
1533
1534 /*
1535 * Setup: break out flag bits into variables.
1536 */
1537 state->docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
1538 if (cnp->cn_nameiop == DELETE)
1539 state->docache = 0;
1540 state->rdonly = cnp->cn_flags & RDONLY;
1541
1542 /*
1543 * Keep going until we run out of path components.
1544 */
1545 cnp->cn_nameptr = ndp->ni_pnbuf;
1546
1547 /* drop leading slashes (already used them to choose startdir) */
1548 while (cnp->cn_nameptr[0] == '/') {
1549 cnp->cn_nameptr++;
1550 ndp->ni_pathlen--;
1551 }
1552 /* was it just "/"? */
1553 if (cnp->cn_nameptr[0] == '\0') {
1554 foundobj = searchdir;
1555 searchdir = NULL;
1556 cnp->cn_flags |= ISLASTCN;
1557
1558 /* bleh */
1559 goto skiploop;
1560 }
1561
1562 for (;;) {
1563 KASSERT(searchdir != NULL);
1564 KASSERT(!searchdir_locked);
1565
1566 /*
1567 * Parse out the first path name component that we need to
1568 * to consider. While doing this, attempt to use the name
1569 * cache to fast-forward through as many "easy" to find
1570 * components of the path as possible.
1571 */
1572 error = lookup_fastforward(state, &searchdir, &foundobj);
1573
1574 /*
1575 * If we didn't get a good answer from the namecache, then
1576 * go directly to the file system.
1577 */
1578 if (error == EOPNOTSUPP) {
1579 error = lookup_once(state, searchdir, &searchdir,
1580 &foundobj, &searchdir_locked);
1581 }
1582
1583 /*
1584 * If the vnode we found is mounted on, then cross the mount
1585 * and get the root vnode in foundobj. If this encounters
1586 * an error, it will dispose of foundobj, but searchdir is
1587 * untouched.
1588 */
1589 if (error == 0 && foundobj != NULL &&
1590 foundobj->v_type == VDIR &&
1591 foundobj->v_mountedhere != NULL &&
1592 (cnp->cn_flags & NOCROSSMOUNT) == 0) {
1593 error = lookup_crossmount(state, &searchdir,
1594 &foundobj, &searchdir_locked);
1595 }
1596
1597 if (error) {
1598 if (searchdir != NULL) {
1599 if (searchdir_locked) {
1600 searchdir_locked = false;
1601 vput(searchdir);
1602 } else {
1603 vrele(searchdir);
1604 }
1605 }
1606 ndp->ni_dvp = NULL;
1607 ndp->ni_vp = NULL;
1608 /*
1609 * Note that if we're doing TRYEMULROOT we can
1610 * retry with the normal root. Where this is
1611 * currently set matches previous practice,
1612 * but the previous practice didn't make much
1613 * sense and somebody should sit down and
1614 * figure out which cases should cause retry
1615 * and which shouldn't. XXX.
1616 */
1617 state->attempt_retry = 1;
1618 return (error);
1619 }
1620
1621 if (foundobj == NULL) {
1622 /*
1623 * Success with no object returned means we're
1624 * creating something and it isn't already
1625 * there. Break out of the main loop now so
1626 * the code below doesn't have to test for
1627 * foundobj == NULL.
1628 */
1629 /* lookup_once can't have dropped the searchdir */
1630 KASSERT(searchdir != NULL ||
1631 (cnp->cn_flags & ISLASTCN) != 0);
1632 break;
1633 }
1634
1635 /*
1636 * Check for symbolic link. If we've reached one,
1637 * follow it, unless we aren't supposed to. Back up
1638 * over any slashes that we skipped, as we will need
1639 * them again.
1640 */
1641 if (namei_atsymlink(state, foundobj)) {
1642 /* Don't need searchdir locked any more. */
1643 if (searchdir_locked) {
1644 searchdir_locked = false;
1645 VOP_UNLOCK(searchdir);
1646 }
1647 ndp->ni_pathlen += state->slashes;
1648 ndp->ni_next -= state->slashes;
1649 if (neverfollow) {
1650 error = EINVAL;
1651 } else if (searchdir == NULL) {
1652 /*
1653 * dholland 20160410: lookup_once only
1654 * drops searchdir if it crossed a
1655 * mount point. Therefore, if we get
1656 * here it means we crossed a mount
1657 * point to a mounted filesystem whose
1658 * root vnode is a symlink. In theory
1659 * we could continue at this point by
1660 * using the pre-crossing searchdir
1661 * (e.g. just take out an extra
1662 * reference on it before calling
1663 * lookup_once so we still have it),
1664 * but this will make an ugly mess and
1665 * it should never happen in practice
1666 * as only badly broken filesystems
1667 * have non-directory root vnodes. (I
1668 * have seen this sort of thing with
1669 * NFS occasionally but even then it
1670 * means something's badly wrong.)
1671 */
1672 error = ENOTDIR;
1673 } else {
1674 /*
1675 * dholland 20110410: if we're at a
1676 * union mount it might make sense to
1677 * use the top of the union stack here
1678 * rather than the layer we found the
1679 * symlink in. (FUTURE)
1680 */
1681 error = namei_follow(state, inhibitmagic,
1682 searchdir, foundobj,
1683 &searchdir);
1684 }
1685 if (error) {
1686 KASSERT(searchdir != foundobj);
1687 if (searchdir != NULL) {
1688 vrele(searchdir);
1689 }
1690 vrele(foundobj);
1691 ndp->ni_dvp = NULL;
1692 ndp->ni_vp = NULL;
1693 return error;
1694 }
1695 vrele(foundobj);
1696 foundobj = NULL;
1697
1698 /*
1699 * If we followed a symlink to `/' and there
1700 * are no more components after the symlink,
1701 * we're done with the loop and what we found
1702 * is the searchdir.
1703 */
1704 if (cnp->cn_nameptr[0] == '\0') {
1705 KASSERT(searchdir != NULL);
1706 foundobj = searchdir;
1707 searchdir = NULL;
1708 cnp->cn_flags |= ISLASTCN;
1709 break;
1710 }
1711
1712 continue;
1713 }
1714
1715 /*
1716 * Not a symbolic link.
1717 *
1718 * Check for directory, if the component was
1719 * followed by a series of slashes.
1720 */
1721 if ((foundobj->v_type != VDIR) &&
1722 (cnp->cn_flags & REQUIREDIR)) {
1723 KASSERT(foundobj != searchdir);
1724 if (searchdir) {
1725 if (searchdir_locked) {
1726 searchdir_locked = false;
1727 vput(searchdir);
1728 } else {
1729 vrele(searchdir);
1730 }
1731 } else {
1732 KASSERT(!searchdir_locked);
1733 }
1734 vrele(foundobj);
1735 ndp->ni_dvp = NULL;
1736 ndp->ni_vp = NULL;
1737 state->attempt_retry = 1;
1738 return ENOTDIR;
1739 }
1740
1741 /*
1742 * Stop if we've reached the last component.
1743 */
1744 if (cnp->cn_flags & ISLASTCN) {
1745 break;
1746 }
1747
1748 /*
1749 * Continue with the next component.
1750 */
1751 cnp->cn_nameptr = ndp->ni_next;
1752 if (searchdir != NULL) {
1753 if (searchdir_locked) {
1754 searchdir_locked = false;
1755 vput(searchdir);
1756 } else {
1757 vrele(searchdir);
1758 }
1759 }
1760 searchdir = foundobj;
1761 foundobj = NULL;
1762 }
1763
1764 KASSERT((cnp->cn_flags & LOCKPARENT) == 0 || searchdir == NULL ||
1765 VOP_ISLOCKED(searchdir) == LK_EXCLUSIVE);
1766
1767 skiploop:
1768
1769 if (foundobj != NULL) {
1770 if (foundobj == ndp->ni_erootdir) {
1771 /*
1772 * We are about to return the emulation root.
1773 * This isn't a good idea because code might
1774 * repeatedly lookup ".." until the file
1775 * matches that returned for "/" and loop
1776 * forever. So convert it to the real root.
1777 */
1778 if (searchdir != NULL) {
1779 if (searchdir_locked) {
1780 vput(searchdir);
1781 searchdir_locked = false;
1782 } else {
1783 vrele(searchdir);
1784 }
1785 searchdir = NULL;
1786 }
1787 vrele(foundobj);
1788 foundobj = ndp->ni_rootdir;
1789 vref(foundobj);
1790 }
1791
1792 /*
1793 * If the caller requested the parent node (i.e. it's
1794 * a CREATE, DELETE, or RENAME), and we don't have one
1795 * (because this is the root directory, or we crossed
1796 * a mount point), then we must fail.
1797 *
1798 * 20210604 dholland when NONEXCLHACK is set (open
1799 * with O_CREAT but not O_EXCL) skip this logic. Since
1800 * we have a foundobj, open will not be creating, so
1801 * it doesn't actually need or use the searchdir, so
1802 * it's ok to return it even if it's on a different
1803 * volume, and it's also ok to return NULL; by setting
1804 * NONEXCLHACK the open code promises to cope with
1805 * those cases correctly. (That is, it should do what
1806 * it would do anyway, that is, just release the
1807 * searchdir, except not crash if it's null.) This is
1808 * needed because otherwise opening mountpoints with
1809 * O_CREAT but not O_EXCL fails... which is a silly
1810 * thing to do but ought to work. (This whole issue
1811 * came to light because 3rd party code wanted to open
1812 * certain procfs nodes with O_CREAT for some 3rd
1813 * party reason, and it failed.)
1814 *
1815 * Note that NONEXCLHACK is properly a different
1816 * nameiop (it is partway between LOOKUP and CREATE)
1817 * but it was stuffed in as a flag instead to make the
1818 * resulting patch less invasive for pullup. Blah.
1819 */
1820 if (cnp->cn_nameiop != LOOKUP &&
1821 (searchdir == NULL ||
1822 searchdir->v_mount != foundobj->v_mount) &&
1823 (cnp->cn_flags & NONEXCLHACK) == 0) {
1824 if (searchdir) {
1825 if (searchdir_locked) {
1826 vput(searchdir);
1827 searchdir_locked = false;
1828 } else {
1829 vrele(searchdir);
1830 }
1831 searchdir = NULL;
1832 }
1833 vrele(foundobj);
1834 foundobj = NULL;
1835 ndp->ni_dvp = NULL;
1836 ndp->ni_vp = NULL;
1837 state->attempt_retry = 1;
1838
1839 switch (cnp->cn_nameiop) {
1840 case CREATE:
1841 return EEXIST;
1842 case DELETE:
1843 case RENAME:
1844 return EBUSY;
1845 default:
1846 break;
1847 }
1848 panic("Invalid nameiop\n");
1849 }
1850
1851 /*
1852 * Disallow directory write attempts on read-only lookups.
1853 * Prefers EEXIST over EROFS for the CREATE case.
1854 */
1855 if (state->rdonly &&
1856 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1857 if (searchdir) {
1858 if (searchdir_locked) {
1859 vput(searchdir);
1860 searchdir_locked = false;
1861 } else {
1862 vrele(searchdir);
1863 }
1864 searchdir = NULL;
1865 }
1866 vrele(foundobj);
1867 foundobj = NULL;
1868 ndp->ni_dvp = NULL;
1869 ndp->ni_vp = NULL;
1870 state->attempt_retry = 1;
1871 return EROFS;
1872 }
1873
1874 /* Lock the leaf node if requested. */
1875 if ((cnp->cn_flags & (LOCKLEAF | LOCKPARENT)) == LOCKPARENT &&
1876 searchdir == foundobj) {
1877 /*
1878 * Note: if LOCKPARENT but not LOCKLEAF is
1879 * set, and searchdir == foundobj, this code
1880 * necessarily unlocks the parent as well as
1881 * the leaf. That is, just because you specify
1882 * LOCKPARENT doesn't mean you necessarily get
1883 * a locked parent vnode. The code in
1884 * vfs_syscalls.c, and possibly elsewhere,
1885 * that uses this combination "knows" this, so
1886 * it can't be safely changed. Feh. XXX
1887 */
1888 KASSERT(searchdir_locked);
1889 VOP_UNLOCK(searchdir);
1890 searchdir_locked = false;
1891 } else if ((cnp->cn_flags & LOCKLEAF) != 0 &&
1892 (searchdir != foundobj ||
1893 (cnp->cn_flags & LOCKPARENT) == 0)) {
1894 const int lktype = (cnp->cn_flags & LOCKSHARED) != 0 ?
1895 LK_SHARED : LK_EXCLUSIVE;
1896 vn_lock(foundobj, lktype | LK_RETRY);
1897 }
1898 }
1899
1900 /*
1901 * Done.
1902 */
1903
1904 /*
1905 * If LOCKPARENT is not set, the parent directory isn't returned.
1906 */
1907 if ((cnp->cn_flags & LOCKPARENT) == 0 && searchdir != NULL) {
1908 vrele(searchdir);
1909 searchdir = NULL;
1910 }
1911
1912 ndp->ni_dvp = searchdir;
1913 ndp->ni_vp = foundobj;
1914 return 0;
1915 }
1916
1917 /*
1918 * Do namei; wrapper layer that handles TRYEMULROOT.
1919 */
1920 static int
1921 namei_tryemulroot(struct namei_state *state,
1922 int neverfollow, int inhibitmagic, int isnfsd)
1923 {
1924 int error;
1925
1926 struct nameidata *ndp = state->ndp;
1927 struct componentname *cnp = state->cnp;
1928 const char *savepath = NULL;
1929
1930 KASSERT(cnp == &ndp->ni_cnd);
1931
1932 if (cnp->cn_flags & TRYEMULROOT) {
1933 savepath = pathbuf_stringcopy_get(ndp->ni_pathbuf);
1934 }
1935
1936 emul_retry:
1937 state->attempt_retry = 0;
1938
1939 error = namei_oneroot(state, neverfollow, inhibitmagic, isnfsd);
1940 if (error) {
1941 /*
1942 * Once namei has started up, the existence of ni_erootdir
1943 * tells us whether we're working from an emulation root.
1944 * The TRYEMULROOT flag isn't necessarily authoritative.
1945 */
1946 if (ndp->ni_erootdir != NULL && state->attempt_retry) {
1947 /* Retry the whole thing using the normal root */
1948 cnp->cn_flags &= ~TRYEMULROOT;
1949 state->attempt_retry = 0;
1950
1951 /* kinda gross */
1952 strcpy(ndp->ni_pathbuf->pb_path, savepath);
1953 pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
1954 savepath = NULL;
1955
1956 goto emul_retry;
1957 }
1958 }
1959 if (savepath != NULL) {
1960 pathbuf_stringcopy_put(ndp->ni_pathbuf, savepath);
1961 }
1962 return error;
1963 }
1964
1965 /*
1966 * External interface.
1967 */
1968 int
1969 namei(struct nameidata *ndp)
1970 {
1971 struct namei_state state;
1972 int error;
1973
1974 namei_init(&state, ndp);
1975 error = namei_tryemulroot(&state,
1976 0/*!neverfollow*/, 0/*!inhibitmagic*/,
1977 0/*isnfsd*/);
1978 namei_cleanup(&state);
1979
1980 if (error) {
1981 /* make sure no stray refs leak out */
1982 KASSERT(ndp->ni_dvp == NULL);
1983 KASSERT(ndp->ni_vp == NULL);
1984 }
1985
1986 return error;
1987 }
1988
1989 ////////////////////////////////////////////////////////////
1990
1991 /*
1992 * External interface used by nfsd. This is basically different from
1993 * namei only in that it has the ability to pass in the "current
1994 * directory", and uses an extra flag "neverfollow" for which there's
1995 * no physical flag defined in namei.h. (There used to be a cut&paste
1996 * copy of about half of namei in nfsd to allow these minor
1997 * adjustments to exist.)
1998 *
1999 * XXX: the namei interface should be adjusted so nfsd can just use
2000 * ordinary namei().
2001 */
2002 int
2003 lookup_for_nfsd(struct nameidata *ndp, struct vnode *forcecwd, int neverfollow)
2004 {
2005 struct namei_state state;
2006 int error;
2007
2008 KASSERT(ndp->ni_atdir == NULL);
2009 ndp->ni_atdir = forcecwd;
2010
2011 namei_init(&state, ndp);
2012 error = namei_tryemulroot(&state,
2013 neverfollow, 1/*inhibitmagic*/, 1/*isnfsd*/);
2014 namei_cleanup(&state);
2015
2016 if (error) {
2017 /* make sure no stray refs leak out */
2018 KASSERT(ndp->ni_dvp == NULL);
2019 KASSERT(ndp->ni_vp == NULL);
2020 }
2021
2022 return error;
2023 }
2024
2025 /*
2026 * A second external interface used by nfsd. This turns out to be a
2027 * single lookup used by the WebNFS code (ha!) to get "index.html" or
2028 * equivalent when asked for a directory. It should eventually evolve
2029 * into some kind of namei_once() call; for the time being it's kind
2030 * of a mess. XXX.
2031 *
2032 * dholland 20110109: I don't think it works, and I don't think it
2033 * worked before I started hacking and slashing either, and I doubt
2034 * anyone will ever notice.
2035 */
2036
2037 /*
2038 * Internals. This calls lookup_once() after setting up the assorted
2039 * pieces of state the way they ought to be.
2040 */
2041 static int
2042 do_lookup_for_nfsd_index(struct namei_state *state)
2043 {
2044 int error;
2045
2046 struct componentname *cnp = state->cnp;
2047 struct nameidata *ndp = state->ndp;
2048 struct vnode *startdir;
2049 struct vnode *foundobj;
2050 bool startdir_locked;
2051 const char *cp; /* pointer into pathname argument */
2052
2053 KASSERT(cnp == &ndp->ni_cnd);
2054
2055 startdir = state->ndp->ni_atdir;
2056
2057 cnp->cn_nameptr = ndp->ni_pnbuf;
2058 state->docache = 1;
2059 state->rdonly = cnp->cn_flags & RDONLY;
2060 ndp->ni_dvp = NULL;
2061
2062 cnp->cn_consume = 0;
2063 error = VOP_PARSEPATH(startdir, cnp->cn_nameptr, &cnp->cn_namelen);
2064 if (error) {
2065 return error;
2066 }
2067
2068 cp = cnp->cn_nameptr + cnp->cn_namelen;
2069 KASSERT(cnp->cn_namelen <= KERNEL_NAME_MAX);
2070 ndp->ni_pathlen -= cnp->cn_namelen;
2071 ndp->ni_next = cp;
2072 state->slashes = 0;
2073 cnp->cn_flags &= ~REQUIREDIR;
2074 cnp->cn_flags |= MAKEENTRY|ISLASTCN;
2075
2076 if (cnp->cn_namelen == 2 &&
2077 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
2078 cnp->cn_flags |= ISDOTDOT;
2079 else
2080 cnp->cn_flags &= ~ISDOTDOT;
2081
2082 /*
2083 * Because lookup_once can change the startdir, we need our
2084 * own reference to it to avoid consuming the caller's.
2085 */
2086 vref(startdir);
2087 error = lookup_once(state, startdir, &startdir, &foundobj,
2088 &startdir_locked);
2089
2090 KASSERT((cnp->cn_flags & LOCKPARENT) == 0);
2091 if (startdir_locked) {
2092 VOP_UNLOCK(startdir);
2093 startdir_locked = false;
2094 }
2095
2096 /*
2097 * If the vnode we found is mounted on, then cross the mount and get
2098 * the root vnode in foundobj. If this encounters an error, it will
2099 * dispose of foundobj, but searchdir is untouched.
2100 */
2101 if (error == 0 && foundobj != NULL &&
2102 foundobj->v_type == VDIR &&
2103 foundobj->v_mountedhere != NULL &&
2104 (cnp->cn_flags & NOCROSSMOUNT) == 0) {
2105 error = lookup_crossmount(state, &startdir, &foundobj,
2106 &startdir_locked);
2107 }
2108
2109 /* Now toss startdir and see if we have an error. */
2110 if (startdir != NULL)
2111 vrele(startdir);
2112 if (error)
2113 foundobj = NULL;
2114 else if (foundobj != NULL && (cnp->cn_flags & LOCKLEAF) != 0)
2115 vn_lock(foundobj, LK_EXCLUSIVE | LK_RETRY);
2116
2117 ndp->ni_vp = foundobj;
2118 return (error);
2119 }
2120
2121 /*
2122 * External interface. The partitioning between this function and the
2123 * above isn't very clear - the above function exists mostly so code
2124 * that uses "state->" can be shuffled around without having to change
2125 * it to "state.".
2126 */
2127 int
2128 lookup_for_nfsd_index(struct nameidata *ndp, struct vnode *startdir)
2129 {
2130 struct namei_state state;
2131 int error;
2132
2133 KASSERT(ndp->ni_atdir == NULL);
2134 ndp->ni_atdir = startdir;
2135
2136 /*
2137 * Note: the name sent in here (is not|should not be) allowed
2138 * to contain a slash.
2139 */
2140 if (strlen(ndp->ni_pathbuf->pb_path) > KERNEL_NAME_MAX) {
2141 return ENAMETOOLONG;
2142 }
2143 if (strchr(ndp->ni_pathbuf->pb_path, '/')) {
2144 return EINVAL;
2145 }
2146
2147 ndp->ni_pathlen = strlen(ndp->ni_pathbuf->pb_path) + 1;
2148 ndp->ni_pnbuf = NULL;
2149 ndp->ni_cnd.cn_nameptr = NULL;
2150
2151 namei_init(&state, ndp);
2152 error = do_lookup_for_nfsd_index(&state);
2153 namei_cleanup(&state);
2154
2155 return error;
2156 }
2157
2158 ////////////////////////////////////////////////////////////
2159
2160 /*
2161 * Reacquire a path name component.
2162 * dvp is locked on entry and exit.
2163 * *vpp is locked on exit unless it's NULL.
2164 */
2165 int
2166 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp, int dummy)
2167 {
2168 int rdonly; /* lookup read-only flag bit */
2169 int error = 0;
2170 #ifdef DEBUG
2171 size_t newlen; /* DEBUG: check name len */
2172 const char *cp; /* DEBUG: check name ptr */
2173 #endif /* DEBUG */
2174
2175 (void)dummy;
2176
2177 /*
2178 * Setup: break out flag bits into variables.
2179 */
2180 rdonly = cnp->cn_flags & RDONLY;
2181
2182 /*
2183 * Search a new directory.
2184 *
2185 * The cn_hash value is for use by vfs_cache.
2186 * The last component of the filename is left accessible via
2187 * cnp->cn_nameptr for callers that need the name. Callers needing
2188 * the name set the SAVENAME flag. When done, they assume
2189 * responsibility for freeing the pathname buffer.
2190 */
2191 #ifdef DEBUG
2192 #if 0
2193 cp = NULL;
2194 newhash = namei_hash(cnp->cn_nameptr, &cp);
2195 if ((uint32_t)newhash != (uint32_t)cnp->cn_hash)
2196 panic("relookup: bad hash");
2197 #endif
2198 error = VOP_PARSEPATH(dvp, cnp->cn_nameptr, &newlen);
2199 if (error) {
2200 panic("relookup: parsepath failed with error %d", error);
2201 }
2202 if (cnp->cn_namelen != newlen)
2203 panic("relookup: bad len");
2204 cp = cnp->cn_nameptr + cnp->cn_namelen;
2205 while (*cp == '/')
2206 cp++;
2207 if (*cp != 0)
2208 panic("relookup: not last component");
2209 #endif /* DEBUG */
2210
2211 /*
2212 * Check for degenerate name (e.g. / or "")
2213 * which is a way of talking about a directory,
2214 * e.g. like "/." or ".".
2215 */
2216 if (cnp->cn_nameptr[0] == '\0')
2217 panic("relookup: null name");
2218
2219 if (cnp->cn_flags & ISDOTDOT)
2220 panic("relookup: lookup on dot-dot");
2221
2222 /*
2223 * We now have a segment name to search for, and a directory to search.
2224 */
2225 *vpp = NULL;
2226 error = VOP_LOOKUP(dvp, vpp, cnp);
2227 if ((error) != 0) {
2228 KASSERTMSG((*vpp == NULL),
2229 "leaf `%s' should be empty but is %p",
2230 cnp->cn_nameptr, *vpp);
2231 if (error != EJUSTRETURN)
2232 goto bad;
2233 }
2234
2235 /*
2236 * Check for symbolic link
2237 */
2238 KASSERTMSG((*vpp == NULL || (*vpp)->v_type != VLNK ||
2239 (cnp->cn_flags & FOLLOW) == 0),
2240 "relookup: symlink found");
2241
2242 /*
2243 * Check for read-only lookups.
2244 */
2245 if (rdonly && cnp->cn_nameiop != LOOKUP) {
2246 error = EROFS;
2247 if (*vpp) {
2248 vrele(*vpp);
2249 }
2250 goto bad;
2251 }
2252 /*
2253 * Lock result.
2254 */
2255 if (*vpp && *vpp != dvp) {
2256 error = vn_lock(*vpp, LK_EXCLUSIVE);
2257 if (error != 0) {
2258 vrele(*vpp);
2259 goto bad;
2260 }
2261 }
2262 return (0);
2263
2264 bad:
2265 *vpp = NULL;
2266 return (error);
2267 }
2268
2269 /*
2270 * namei_simple - simple forms of namei.
2271 *
2272 * These are wrappers to allow the simple case callers of namei to be
2273 * left alone while everything else changes under them.
2274 */
2275
2276 /* Flags */
2277 struct namei_simple_flags_type {
2278 int dummy;
2279 };
2280 static const struct namei_simple_flags_type ns_nn, ns_nt, ns_fn, ns_ft;
2281 const namei_simple_flags_t NSM_NOFOLLOW_NOEMULROOT = &ns_nn;
2282 const namei_simple_flags_t NSM_NOFOLLOW_TRYEMULROOT = &ns_nt;
2283 const namei_simple_flags_t NSM_FOLLOW_NOEMULROOT = &ns_fn;
2284 const namei_simple_flags_t NSM_FOLLOW_TRYEMULROOT = &ns_ft;
2285
2286 static
2287 int
2288 namei_simple_convert_flags(namei_simple_flags_t sflags)
2289 {
2290 if (sflags == NSM_NOFOLLOW_NOEMULROOT)
2291 return NOFOLLOW | 0;
2292 if (sflags == NSM_NOFOLLOW_TRYEMULROOT)
2293 return NOFOLLOW | TRYEMULROOT;
2294 if (sflags == NSM_FOLLOW_NOEMULROOT)
2295 return FOLLOW | 0;
2296 if (sflags == NSM_FOLLOW_TRYEMULROOT)
2297 return FOLLOW | TRYEMULROOT;
2298 panic("namei_simple_convert_flags: bogus sflags\n");
2299 return 0;
2300 }
2301
2302 int
2303 namei_simple_kernel(const char *path, namei_simple_flags_t sflags,
2304 struct vnode **vp_ret)
2305 {
2306 return nameiat_simple_kernel(NULL, path, sflags, vp_ret);
2307 }
2308
2309 int
2310 nameiat_simple_kernel(struct vnode *dvp, const char *path,
2311 namei_simple_flags_t sflags, struct vnode **vp_ret)
2312 {
2313 struct nameidata nd;
2314 struct pathbuf *pb;
2315 int err;
2316
2317 pb = pathbuf_create(path);
2318 if (pb == NULL) {
2319 return ENOMEM;
2320 }
2321
2322 NDINIT(&nd,
2323 LOOKUP,
2324 namei_simple_convert_flags(sflags),
2325 pb);
2326
2327 if (dvp != NULL)
2328 NDAT(&nd, dvp);
2329
2330 err = namei(&nd);
2331 if (err != 0) {
2332 pathbuf_destroy(pb);
2333 return err;
2334 }
2335 *vp_ret = nd.ni_vp;
2336 pathbuf_destroy(pb);
2337 return 0;
2338 }
2339
2340 int
2341 namei_simple_user(const char *path, namei_simple_flags_t sflags,
2342 struct vnode **vp_ret)
2343 {
2344 return nameiat_simple_user(NULL, path, sflags, vp_ret);
2345 }
2346
2347 int
2348 nameiat_simple_user(struct vnode *dvp, const char *path,
2349 namei_simple_flags_t sflags, struct vnode **vp_ret)
2350 {
2351 struct pathbuf *pb;
2352 struct nameidata nd;
2353 int err;
2354
2355 err = pathbuf_copyin(path, &pb);
2356 if (err) {
2357 return err;
2358 }
2359
2360 NDINIT(&nd,
2361 LOOKUP,
2362 namei_simple_convert_flags(sflags),
2363 pb);
2364
2365 if (dvp != NULL)
2366 NDAT(&nd, dvp);
2367
2368 err = namei(&nd);
2369 if (err != 0) {
2370 pathbuf_destroy(pb);
2371 return err;
2372 }
2373 *vp_ret = nd.ni_vp;
2374 pathbuf_destroy(pb);
2375 return 0;
2376 }
2377