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