1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
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.4 (Berkeley) 2/16/94
37 */
38
39 #include <sys/cdefs.h>
40 #include "opt_capsicum.h"
41 #include "opt_ktrace.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/dirent.h>
46 #include <sys/kernel.h>
47 #include <sys/capsicum.h>
48 #include <sys/fcntl.h>
49 #include <sys/jail.h>
50 #include <sys/lock.h>
51 #include <sys/mutex.h>
52 #include <sys/namei.h>
53 #include <sys/vnode.h>
54 #include <sys/mount.h>
55 #include <sys/filedesc.h>
56 #include <sys/proc.h>
57 #include <sys/sdt.h>
58 #include <sys/syscallsubr.h>
59 #include <sys/sysctl.h>
60 #ifdef KTRACE
61 #include <sys/ktrace.h>
62 #endif
63 #ifdef INVARIANTS
64 #include <machine/_inttypes.h>
65 #endif
66
67 #include <security/audit/audit.h>
68 #include <security/mac/mac_framework.h>
69
70 #include <vm/uma.h>
71
72 #define NAMEI_DIAGNOSTIC 1
73 #undef NAMEI_DIAGNOSTIC
74
75 SDT_PROVIDER_DEFINE(vfs);
76 SDT_PROBE_DEFINE4(vfs, namei, lookup, entry, "struct vnode *", "char *",
77 "unsigned long", "bool");
78 SDT_PROBE_DEFINE4(vfs, namei, lookup, return, "int", "struct vnode *", "bool",
79 "struct nameidata");
80
81 /* Allocation zone for namei. */
82 uma_zone_t namei_zone;
83
84 /* Placeholder vnode for mp traversal. */
85 static struct vnode *vp_crossmp;
86
87 static int
crossmp_vop_islocked(struct vop_islocked_args * ap)88 crossmp_vop_islocked(struct vop_islocked_args *ap)
89 {
90
91 return (LK_SHARED);
92 }
93
94 static int
crossmp_vop_lock1(struct vop_lock1_args * ap)95 crossmp_vop_lock1(struct vop_lock1_args *ap)
96 {
97 struct vnode *vp;
98 struct lock *lk __unused;
99 const char *file __unused;
100 int flags, line __unused;
101
102 vp = ap->a_vp;
103 lk = vp->v_vnlock;
104 flags = ap->a_flags;
105 file = ap->a_file;
106 line = ap->a_line;
107
108 if ((flags & LK_SHARED) == 0)
109 panic("invalid lock request for crossmp");
110
111 WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER, file, line,
112 flags & LK_INTERLOCK ? &VI_MTX(vp)->lock_object : NULL);
113 WITNESS_LOCK(&lk->lock_object, 0, file, line);
114 if ((flags & LK_INTERLOCK) != 0)
115 VI_UNLOCK(vp);
116 LOCK_LOG_LOCK("SLOCK", &lk->lock_object, 0, 0, ap->a_file, line);
117 return (0);
118 }
119
120 static int
crossmp_vop_unlock(struct vop_unlock_args * ap)121 crossmp_vop_unlock(struct vop_unlock_args *ap)
122 {
123 struct vnode *vp;
124 struct lock *lk __unused;
125
126 vp = ap->a_vp;
127 lk = vp->v_vnlock;
128
129 WITNESS_UNLOCK(&lk->lock_object, 0, LOCK_FILE, LOCK_LINE);
130 LOCK_LOG_LOCK("SUNLOCK", &lk->lock_object, 0, 0, LOCK_FILE,
131 LOCK_LINE);
132 return (0);
133 }
134
135 static struct vop_vector crossmp_vnodeops = {
136 .vop_default = &default_vnodeops,
137 .vop_islocked = crossmp_vop_islocked,
138 .vop_lock1 = crossmp_vop_lock1,
139 .vop_unlock = crossmp_vop_unlock,
140 };
141 /*
142 * VFS_VOP_VECTOR_REGISTER(crossmp_vnodeops) is not used here since the vnode
143 * gets allocated early. See nameiinit for the direct call below.
144 */
145
146 struct nameicap_tracker {
147 struct vnode *dp;
148 TAILQ_ENTRY(nameicap_tracker) nm_link;
149 };
150
151 /* Zone for cap mode tracker elements used for dotdot capability checks. */
152 MALLOC_DEFINE(M_NAMEITRACKER, "namei_tracker", "namei tracking for dotdot");
153
154 static void
nameiinit(void * dummy __unused)155 nameiinit(void *dummy __unused)
156 {
157
158 namei_zone = uma_zcreate("NAMEI", MAXPATHLEN, NULL, NULL, NULL, NULL,
159 UMA_ALIGN_PTR, 0);
160 vfs_vector_op_register(&crossmp_vnodeops);
161 getnewvnode("crossmp", NULL, &crossmp_vnodeops, &vp_crossmp);
162 vp_crossmp->v_irflag |= VIRF_CROSSMP;
163 }
164 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nameiinit, NULL);
165
166 static int lookup_cap_dotdot = 1;
167 SYSCTL_INT(_vfs, OID_AUTO, lookup_cap_dotdot, CTLFLAG_RWTUN,
168 &lookup_cap_dotdot, 0,
169 "enables \"..\" components in path lookup in capability mode");
170 static int lookup_cap_dotdot_nonlocal = 1;
171 SYSCTL_INT(_vfs, OID_AUTO, lookup_cap_dotdot_nonlocal, CTLFLAG_RWTUN,
172 &lookup_cap_dotdot_nonlocal, 0,
173 "enables \"..\" components in path lookup in capability mode "
174 "on non-local mount");
175
176 static void
nameicap_tracker_add(struct nameidata * ndp,struct vnode * dp)177 nameicap_tracker_add(struct nameidata *ndp, struct vnode *dp)
178 {
179 struct nameicap_tracker *nt;
180 struct componentname *cnp;
181
182 if ((ndp->ni_lcf & NI_LCF_CAP_DOTDOT) == 0 || dp->v_type != VDIR)
183 return;
184 cnp = &ndp->ni_cnd;
185 nt = TAILQ_LAST(&ndp->ni_cap_tracker, nameicap_tracker_head);
186 if (nt != NULL && nt->dp == dp)
187 return;
188 nt = malloc(sizeof(*nt), M_NAMEITRACKER, M_WAITOK);
189 vhold(dp);
190 nt->dp = dp;
191 TAILQ_INSERT_TAIL(&ndp->ni_cap_tracker, nt, nm_link);
192 }
193
194 static void
nameicap_cleanup_from(struct nameidata * ndp,struct nameicap_tracker * first)195 nameicap_cleanup_from(struct nameidata *ndp, struct nameicap_tracker *first)
196 {
197 struct nameicap_tracker *nt, *nt1;
198
199 nt = first;
200 TAILQ_FOREACH_FROM_SAFE(nt, &ndp->ni_cap_tracker, nm_link, nt1) {
201 TAILQ_REMOVE(&ndp->ni_cap_tracker, nt, nm_link);
202 vdrop(nt->dp);
203 free(nt, M_NAMEITRACKER);
204 }
205 }
206
207 static void
nameicap_cleanup(struct nameidata * ndp)208 nameicap_cleanup(struct nameidata *ndp)
209 {
210 KASSERT(TAILQ_EMPTY(&ndp->ni_cap_tracker) ||
211 (ndp->ni_lcf & NI_LCF_CAP_DOTDOT) != 0, ("not strictrelative"));
212 nameicap_cleanup_from(ndp, NULL);
213 }
214
215 /*
216 * For dotdot lookups in capability mode, only allow the component
217 * lookup to succeed if the resulting directory was already traversed
218 * during the operation. This catches situations where already
219 * traversed directory is moved to different parent, and then we walk
220 * over it with dotdots.
221 *
222 * Also allow to force failure of dotdot lookups for non-local
223 * filesystems, where external agents might assist local lookups to
224 * escape the compartment.
225 */
226 static int
nameicap_check_dotdot(struct nameidata * ndp,struct vnode * dp)227 nameicap_check_dotdot(struct nameidata *ndp, struct vnode *dp)
228 {
229 struct nameicap_tracker *nt;
230 struct mount *mp;
231
232 if (dp == NULL || dp->v_type != VDIR || (ndp->ni_lcf &
233 NI_LCF_STRICTRELATIVE) == 0)
234 return (0);
235 if ((ndp->ni_lcf & NI_LCF_CAP_DOTDOT) == 0)
236 return (ENOTCAPABLE);
237 mp = dp->v_mount;
238 if (lookup_cap_dotdot_nonlocal == 0 && mp != NULL &&
239 (mp->mnt_flag & MNT_LOCAL) == 0)
240 return (ENOTCAPABLE);
241 TAILQ_FOREACH_REVERSE(nt, &ndp->ni_cap_tracker, nameicap_tracker_head,
242 nm_link) {
243 if (dp == nt->dp) {
244 nt = TAILQ_NEXT(nt, nm_link);
245 if (nt != NULL)
246 nameicap_cleanup_from(ndp, nt);
247 return (0);
248 }
249 }
250 return (ENOTCAPABLE);
251 }
252
253 static void
namei_cleanup_cnp(struct componentname * cnp)254 namei_cleanup_cnp(struct componentname *cnp)
255 {
256
257 uma_zfree(namei_zone, cnp->cn_pnbuf);
258 #ifdef DIAGNOSTIC
259 cnp->cn_pnbuf = NULL;
260 cnp->cn_nameptr = NULL;
261 #endif
262 }
263
264 static int
namei_handle_root(struct nameidata * ndp,struct vnode ** dpp)265 namei_handle_root(struct nameidata *ndp, struct vnode **dpp)
266 {
267 struct componentname *cnp;
268
269 cnp = &ndp->ni_cnd;
270 if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) != 0) {
271 #ifdef KTRACE
272 if (KTRPOINT(curthread, KTR_CAPFAIL))
273 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
274 #endif
275 return (ENOTCAPABLE);
276 }
277 while (*(cnp->cn_nameptr) == '/') {
278 cnp->cn_nameptr++;
279 ndp->ni_pathlen--;
280 }
281 *dpp = ndp->ni_rootdir;
282 vrefact(*dpp);
283 return (0);
284 }
285
286 static int
namei_setup(struct nameidata * ndp,struct vnode ** dpp,struct pwd ** pwdp)287 namei_setup(struct nameidata *ndp, struct vnode **dpp, struct pwd **pwdp)
288 {
289 struct componentname *cnp;
290 struct thread *td;
291 struct pwd *pwd;
292 int error;
293 bool startdir_used;
294
295 cnp = &ndp->ni_cnd;
296 td = cnp->cn_thread;
297
298 startdir_used = false;
299 *pwdp = NULL;
300 *dpp = NULL;
301
302 #ifdef CAPABILITY_MODE
303 /*
304 * In capability mode, lookups must be restricted to happen in
305 * the subtree with the root specified by the file descriptor:
306 * - The root must be real file descriptor, not the pseudo-descriptor
307 * AT_FDCWD.
308 * - The passed path must be relative and not absolute.
309 * - If lookup_cap_dotdot is disabled, path must not contain the
310 * '..' components.
311 * - If lookup_cap_dotdot is enabled, we verify that all '..'
312 * components lookups result in the directories which were
313 * previously walked by us, which prevents an escape from
314 * the relative root.
315 */
316 if (IN_CAPABILITY_MODE(td) && (cnp->cn_flags & NOCAPCHECK) == 0) {
317 ndp->ni_lcf |= NI_LCF_STRICTRELATIVE;
318 ndp->ni_resflags |= NIRES_STRICTREL;
319 if (ndp->ni_dirfd == AT_FDCWD) {
320 #ifdef KTRACE
321 if (KTRPOINT(td, KTR_CAPFAIL))
322 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
323 #endif
324 return (ECAPMODE);
325 }
326 }
327 #endif
328 error = 0;
329
330 /*
331 * Get starting point for the translation.
332 */
333 pwd = pwd_hold(td);
334 /*
335 * The reference on ni_rootdir is acquired in the block below to avoid
336 * back-to-back atomics for absolute lookups.
337 */
338 ndp->ni_rootdir = pwd->pwd_rdir;
339 ndp->ni_topdir = pwd->pwd_jdir;
340
341 if (cnp->cn_pnbuf[0] == '/') {
342 ndp->ni_resflags |= NIRES_ABS;
343 error = namei_handle_root(ndp, dpp);
344 } else {
345 if (ndp->ni_startdir != NULL) {
346 *dpp = ndp->ni_startdir;
347 startdir_used = true;
348 } else if (ndp->ni_dirfd == AT_FDCWD) {
349 *dpp = pwd->pwd_cdir;
350 vrefact(*dpp);
351 } else {
352 if (cnp->cn_flags & AUDITVNODE1)
353 AUDIT_ARG_ATFD1(ndp->ni_dirfd);
354 if (cnp->cn_flags & AUDITVNODE2)
355 AUDIT_ARG_ATFD2(ndp->ni_dirfd);
356
357 error = fgetvp_lookup(ndp->ni_dirfd, ndp, dpp);
358 }
359 if (error == 0 && (*dpp)->v_type != VDIR &&
360 (cnp->cn_pnbuf[0] != '\0' ||
361 (cnp->cn_flags & EMPTYPATH) == 0))
362 error = ENOTDIR;
363 }
364 if (error == 0 && (cnp->cn_flags & RBENEATH) != 0) {
365 if (cnp->cn_pnbuf[0] == '/') {
366 error = ENOTCAPABLE;
367 } else if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) == 0) {
368 ndp->ni_lcf |= NI_LCF_STRICTRELATIVE |
369 NI_LCF_CAP_DOTDOT;
370 }
371 }
372
373 /*
374 * If we are auditing the kernel pathname, save the user pathname.
375 */
376 if (cnp->cn_flags & AUDITVNODE1)
377 AUDIT_ARG_UPATH1_VP(td, ndp->ni_rootdir, *dpp, cnp->cn_pnbuf);
378 if (cnp->cn_flags & AUDITVNODE2)
379 AUDIT_ARG_UPATH2_VP(td, ndp->ni_rootdir, *dpp, cnp->cn_pnbuf);
380 if (ndp->ni_startdir != NULL && !startdir_used)
381 vrele(ndp->ni_startdir);
382 if (error != 0) {
383 if (*dpp != NULL)
384 vrele(*dpp);
385 pwd_drop(pwd);
386 return (error);
387 }
388 if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) != 0 &&
389 lookup_cap_dotdot != 0)
390 ndp->ni_lcf |= NI_LCF_CAP_DOTDOT;
391 SDT_PROBE4(vfs, namei, lookup, entry, *dpp, cnp->cn_pnbuf,
392 cnp->cn_flags, false);
393 *pwdp = pwd;
394 return (0);
395 }
396
397 static int
namei_getpath(struct nameidata * ndp)398 namei_getpath(struct nameidata *ndp)
399 {
400 struct componentname *cnp;
401 int error;
402
403 cnp = &ndp->ni_cnd;
404
405 /*
406 * Get a buffer for the name to be translated, and copy the
407 * name into the buffer.
408 */
409 cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
410 if (ndp->ni_segflg == UIO_SYSSPACE) {
411 error = copystr(ndp->ni_dirp, cnp->cn_pnbuf, MAXPATHLEN,
412 &ndp->ni_pathlen);
413 } else {
414 error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf, MAXPATHLEN,
415 &ndp->ni_pathlen);
416 }
417
418 if (__predict_false(error != 0))
419 return (error);
420
421 cnp->cn_nameptr = cnp->cn_pnbuf;
422 return (0);
423 }
424
425 static int
namei_emptypath(struct nameidata * ndp)426 namei_emptypath(struct nameidata *ndp)
427 {
428 struct componentname *cnp;
429 struct pwd *pwd;
430 struct vnode *dp;
431 int error;
432
433 cnp = &ndp->ni_cnd;
434 MPASS(*cnp->cn_pnbuf == '\0');
435 MPASS((cnp->cn_flags & EMPTYPATH) != 0);
436 MPASS((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) == 0);
437
438 ndp->ni_resflags |= NIRES_EMPTYPATH;
439 error = namei_setup(ndp, &dp, &pwd);
440 if (error != 0) {
441 namei_cleanup_cnp(cnp);
442 goto errout;
443 }
444
445 /*
446 * Usecount on dp already provided by namei_setup.
447 */
448 ndp->ni_vp = dp;
449 namei_cleanup_cnp(cnp);
450 pwd_drop(pwd);
451 NDVALIDATE(ndp);
452 if ((cnp->cn_flags & LOCKLEAF) != 0) {
453 VOP_LOCK(dp, (cnp->cn_flags & LOCKSHARED) != 0 ?
454 LK_SHARED : LK_EXCLUSIVE);
455 if (VN_IS_DOOMED(dp)) {
456 vput(dp);
457 error = ENOENT;
458 goto errout;
459 }
460 }
461 SDT_PROBE4(vfs, namei, lookup, return, 0, ndp->ni_vp, false, ndp);
462 return (0);
463
464 errout:
465 SDT_PROBE4(vfs, namei, lookup, return, error, NULL, false, ndp);
466 return (error);
467 }
468
469 /*
470 * Convert a pathname into a pointer to a locked vnode.
471 *
472 * The FOLLOW flag is set when symbolic links are to be followed
473 * when they occur at the end of the name translation process.
474 * Symbolic links are always followed for all other pathname
475 * components other than the last.
476 *
477 * The segflg defines whether the name is to be copied from user
478 * space or kernel space.
479 *
480 * Overall outline of namei:
481 *
482 * copy in name
483 * get starting directory
484 * while (!done && !error) {
485 * call lookup to search path.
486 * if symbolic link, massage name in buffer and continue
487 * }
488 */
489 int
namei(struct nameidata * ndp)490 namei(struct nameidata *ndp)
491 {
492 char *cp; /* pointer into pathname argument */
493 struct vnode *dp; /* the directory we are searching */
494 struct iovec aiov; /* uio for reading symbolic links */
495 struct componentname *cnp;
496 struct thread *td;
497 struct pwd *pwd;
498 struct uio auio;
499 int error, linklen;
500 enum cache_fpl_status status;
501
502 cnp = &ndp->ni_cnd;
503 td = cnp->cn_thread;
504 #ifdef INVARIANTS
505 KASSERT(cnp->cn_thread == curthread,
506 ("namei not using curthread"));
507 KASSERT((ndp->ni_debugflags & NAMEI_DBG_CALLED) == 0,
508 ("%s: repeated call to namei without NDREINIT", __func__));
509 KASSERT(ndp->ni_debugflags == NAMEI_DBG_INITED,
510 ("%s: bad debugflags %d", __func__, ndp->ni_debugflags));
511 ndp->ni_debugflags |= NAMEI_DBG_CALLED;
512 if (ndp->ni_startdir != NULL)
513 ndp->ni_debugflags |= NAMEI_DBG_HADSTARTDIR;
514 if (cnp->cn_flags & FAILIFEXISTS) {
515 KASSERT(cnp->cn_nameiop == CREATE,
516 ("%s: FAILIFEXISTS passed for op %d", __func__, cnp->cn_nameiop));
517 /*
518 * The limitation below is to restrict hairy corner cases.
519 */
520 KASSERT((cnp->cn_flags & (LOCKPARENT | LOCKLEAF)) == LOCKPARENT,
521 ("%s: FAILIFEXISTS must be passed with LOCKPARENT and without LOCKLEAF",
522 __func__));
523 }
524 /*
525 * For NDVALIDATE.
526 *
527 * While NDINIT may seem like a more natural place to do it, there are
528 * callers which directly modify flags past invoking init.
529 */
530 cnp->cn_origflags = cnp->cn_flags;
531 #endif
532 ndp->ni_cnd.cn_cred = ndp->ni_cnd.cn_thread->td_ucred;
533 KASSERT(ndp->ni_resflags == 0, ("%s: garbage in ni_resflags: %x\n",
534 __func__, ndp->ni_resflags));
535 KASSERT(cnp->cn_cred && td->td_proc, ("namei: bad cred/proc"));
536 KASSERT((cnp->cn_flags & NAMEI_INTERNAL_FLAGS) == 0,
537 ("namei: unexpected flags: %" PRIx64 "\n",
538 cnp->cn_flags & NAMEI_INTERNAL_FLAGS));
539 if (cnp->cn_flags & NOCACHE)
540 KASSERT(cnp->cn_nameiop != LOOKUP,
541 ("%s: NOCACHE passed with LOOKUP", __func__));
542 MPASS(ndp->ni_startdir == NULL || ndp->ni_startdir->v_type == VDIR ||
543 ndp->ni_startdir->v_type == VBAD);
544
545 ndp->ni_lcf = 0;
546 ndp->ni_loopcnt = 0;
547 ndp->ni_vp = NULL;
548
549 error = namei_getpath(ndp);
550 if (__predict_false(error != 0)) {
551 namei_cleanup_cnp(cnp);
552 SDT_PROBE4(vfs, namei, lookup, return, error, NULL,
553 false, ndp);
554 return (error);
555 }
556
557 #ifdef KTRACE
558 if (KTRPOINT(td, KTR_NAMEI)) {
559 ktrnamei(cnp->cn_pnbuf);
560 }
561 #endif
562 TSNAMEI(curthread->td_proc->p_pid, cnp->cn_pnbuf);
563
564 /*
565 * First try looking up the target without locking any vnodes.
566 *
567 * We may need to start from scratch or pick up where it left off.
568 */
569 error = cache_fplookup(ndp, &status, &pwd);
570 switch (status) {
571 case CACHE_FPL_STATUS_UNSET:
572 __assert_unreachable();
573 break;
574 case CACHE_FPL_STATUS_HANDLED:
575 if (error == 0)
576 NDVALIDATE(ndp);
577 return (error);
578 case CACHE_FPL_STATUS_PARTIAL:
579 TAILQ_INIT(&ndp->ni_cap_tracker);
580 dp = ndp->ni_startdir;
581 break;
582 case CACHE_FPL_STATUS_DESTROYED:
583 ndp->ni_loopcnt = 0;
584 error = namei_getpath(ndp);
585 if (__predict_false(error != 0)) {
586 namei_cleanup_cnp(cnp);
587 return (error);
588 }
589 /* FALLTHROUGH */
590 case CACHE_FPL_STATUS_ABORTED:
591 TAILQ_INIT(&ndp->ni_cap_tracker);
592 MPASS(ndp->ni_lcf == 0);
593 if (*cnp->cn_pnbuf == '\0') {
594 if ((cnp->cn_flags & EMPTYPATH) != 0) {
595 return (namei_emptypath(ndp));
596 }
597 namei_cleanup_cnp(cnp);
598 SDT_PROBE4(vfs, namei, lookup, return, ENOENT, NULL,
599 false, ndp);
600 return (ENOENT);
601 }
602 error = namei_setup(ndp, &dp, &pwd);
603 if (error != 0) {
604 namei_cleanup_cnp(cnp);
605 return (error);
606 }
607 break;
608 }
609
610 /*
611 * Locked lookup.
612 */
613 for (;;) {
614 ndp->ni_startdir = dp;
615 error = lookup(ndp);
616 if (error != 0)
617 goto out;
618
619 /*
620 * If not a symbolic link, we're done.
621 */
622 if ((cnp->cn_flags & ISSYMLINK) == 0) {
623 SDT_PROBE4(vfs, namei, lookup, return, error,
624 (error == 0 ? ndp->ni_vp : NULL), false, ndp);
625 if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0) {
626 namei_cleanup_cnp(cnp);
627 } else
628 cnp->cn_flags |= HASBUF;
629 nameicap_cleanup(ndp);
630 pwd_drop(pwd);
631 if (error == 0)
632 NDVALIDATE(ndp);
633 return (error);
634 }
635 if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
636 error = ELOOP;
637 break;
638 }
639 #ifdef MAC
640 if ((cnp->cn_flags & NOMACCHECK) == 0) {
641 error = mac_vnode_check_readlink(td->td_ucred,
642 ndp->ni_vp);
643 if (error != 0)
644 break;
645 }
646 #endif
647 if (ndp->ni_pathlen > 1)
648 cp = uma_zalloc(namei_zone, M_WAITOK);
649 else
650 cp = cnp->cn_pnbuf;
651 aiov.iov_base = cp;
652 aiov.iov_len = MAXPATHLEN;
653 auio.uio_iov = &aiov;
654 auio.uio_iovcnt = 1;
655 auio.uio_offset = 0;
656 auio.uio_rw = UIO_READ;
657 auio.uio_segflg = UIO_SYSSPACE;
658 auio.uio_td = td;
659 auio.uio_resid = MAXPATHLEN;
660 error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
661 if (error != 0) {
662 if (ndp->ni_pathlen > 1)
663 uma_zfree(namei_zone, cp);
664 break;
665 }
666 linklen = MAXPATHLEN - auio.uio_resid;
667 if (linklen == 0) {
668 if (ndp->ni_pathlen > 1)
669 uma_zfree(namei_zone, cp);
670 error = ENOENT;
671 break;
672 }
673 if (linklen + ndp->ni_pathlen > MAXPATHLEN) {
674 if (ndp->ni_pathlen > 1)
675 uma_zfree(namei_zone, cp);
676 error = ENAMETOOLONG;
677 break;
678 }
679 if (ndp->ni_pathlen > 1) {
680 bcopy(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
681 uma_zfree(namei_zone, cnp->cn_pnbuf);
682 cnp->cn_pnbuf = cp;
683 } else
684 cnp->cn_pnbuf[linklen] = '\0';
685 ndp->ni_pathlen += linklen;
686 vput(ndp->ni_vp);
687 dp = ndp->ni_dvp;
688 /*
689 * Check if root directory should replace current directory.
690 */
691 cnp->cn_nameptr = cnp->cn_pnbuf;
692 if (*(cnp->cn_nameptr) == '/') {
693 vrele(dp);
694 error = namei_handle_root(ndp, &dp);
695 if (error != 0)
696 goto out;
697 }
698 }
699 vput(ndp->ni_vp);
700 ndp->ni_vp = NULL;
701 vrele(ndp->ni_dvp);
702 out:
703 MPASS(error != 0);
704 SDT_PROBE4(vfs, namei, lookup, return, error, NULL, false, ndp);
705 namei_cleanup_cnp(cnp);
706 nameicap_cleanup(ndp);
707 pwd_drop(pwd);
708 return (error);
709 }
710
711 static int
compute_cn_lkflags(struct mount * mp,int lkflags,int cnflags)712 compute_cn_lkflags(struct mount *mp, int lkflags, int cnflags)
713 {
714
715 if (mp == NULL || ((lkflags & LK_SHARED) &&
716 (!(mp->mnt_kern_flag & MNTK_LOOKUP_SHARED) ||
717 ((cnflags & ISDOTDOT) &&
718 (mp->mnt_kern_flag & MNTK_LOOKUP_EXCL_DOTDOT))))) {
719 lkflags &= ~LK_SHARED;
720 lkflags |= LK_EXCLUSIVE;
721 }
722 lkflags |= LK_NODDLKTREAT;
723 return (lkflags);
724 }
725
726 static __inline int
needs_exclusive_leaf(struct mount * mp,int flags)727 needs_exclusive_leaf(struct mount *mp, int flags)
728 {
729
730 /*
731 * Intermediate nodes can use shared locks, we only need to
732 * force an exclusive lock for leaf nodes.
733 */
734 if ((flags & (ISLASTCN | LOCKLEAF)) != (ISLASTCN | LOCKLEAF))
735 return (0);
736
737 /* Always use exclusive locks if LOCKSHARED isn't set. */
738 if (!(flags & LOCKSHARED))
739 return (1);
740
741 /*
742 * For lookups during open(), if the mount point supports
743 * extended shared operations, then use a shared lock for the
744 * leaf node, otherwise use an exclusive lock.
745 */
746 if ((flags & ISOPEN) != 0)
747 return (!MNT_EXTENDED_SHARED(mp));
748
749 /*
750 * Lookup requests outside of open() that specify LOCKSHARED
751 * only need a shared lock on the leaf vnode.
752 */
753 return (0);
754 }
755
756 /*
757 * Various filesystems expect to be able to copy a name component with length
758 * bounded by NAME_MAX into a directory entry buffer of size MAXNAMLEN. Make
759 * sure that these are the same size.
760 */
761 _Static_assert(MAXNAMLEN == NAME_MAX,
762 "MAXNAMLEN and NAME_MAX have different values");
763
764 /*
765 * Search a pathname.
766 * This is a very central and rather complicated routine.
767 *
768 * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
769 * The starting directory is taken from ni_startdir. The pathname is
770 * descended until done, or a symbolic link is encountered. The variable
771 * ni_more is clear if the path is completed; it is set to one if a
772 * symbolic link needing interpretation is encountered.
773 *
774 * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
775 * whether the name is to be looked up, created, renamed, or deleted.
776 * When CREATE, RENAME, or DELETE is specified, information usable in
777 * creating, renaming, or deleting a directory entry may be calculated.
778 * If flag has LOCKPARENT or'ed into it, the parent directory is returned
779 * locked. If flag has WANTPARENT or'ed into it, the parent directory is
780 * returned unlocked. Otherwise the parent directory is not returned. If
781 * the target of the pathname exists and LOCKLEAF is or'ed into the flag
782 * the target is returned locked, otherwise it is returned unlocked.
783 * When creating or renaming and LOCKPARENT is specified, the target may not
784 * be ".". When deleting and LOCKPARENT is specified, the target may be ".".
785 *
786 * Overall outline of lookup:
787 *
788 * dirloop:
789 * identify next component of name at ndp->ni_ptr
790 * handle degenerate case where name is null string
791 * if .. and crossing mount points and on mounted filesys, find parent
792 * call VOP_LOOKUP routine for next component name
793 * directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
794 * component vnode returned in ni_vp (if it exists), locked.
795 * if result vnode is mounted on and crossing mount points,
796 * find mounted on vnode
797 * if more components of name, do next level at dirloop
798 * return the answer in ni_vp, locked if LOCKLEAF set
799 * if LOCKPARENT set, return locked parent in ni_dvp
800 * if WANTPARENT set, return unlocked parent in ni_dvp
801 */
802 int
lookup(struct nameidata * ndp)803 lookup(struct nameidata *ndp)
804 {
805 char *cp; /* pointer into pathname argument */
806 char *prev_ni_next; /* saved ndp->ni_next */
807 char *nulchar; /* location of '\0' in cn_pnbuf */
808 struct vnode *dp = NULL; /* the directory we are searching */
809 struct vnode *tdp; /* saved dp */
810 struct mount *mp; /* mount table entry */
811 struct prison *pr;
812 size_t prev_ni_pathlen; /* saved ndp->ni_pathlen */
813 int docache; /* == 0 do not cache last component */
814 int wantparent; /* 1 => wantparent or lockparent flag */
815 int rdonly; /* lookup read-only flag bit */
816 int error = 0;
817 int dpunlocked = 0; /* dp has already been unlocked */
818 int relookup = 0; /* do not consume the path component */
819 struct componentname *cnp = &ndp->ni_cnd;
820 int lkflags_save;
821 int ni_dvp_unlocked;
822
823 /*
824 * Setup: break out flag bits into variables.
825 */
826 ni_dvp_unlocked = 0;
827 wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
828 KASSERT(cnp->cn_nameiop == LOOKUP || wantparent,
829 ("CREATE, DELETE, RENAME require LOCKPARENT or WANTPARENT."));
830 /*
831 * When set to zero, docache causes the last component of the
832 * pathname to be deleted from the cache and the full lookup
833 * of the name to be done (via VOP_CACHEDLOOKUP()). Often
834 * filesystems need some pre-computed values that are made
835 * during the full lookup, for instance UFS sets dp->i_offset.
836 *
837 * The docache variable is set to zero when requested by the
838 * NOCACHE flag and for all modifying operations except CREATE.
839 */
840 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
841 if (cnp->cn_nameiop == DELETE ||
842 (wantparent && cnp->cn_nameiop != CREATE &&
843 cnp->cn_nameiop != LOOKUP))
844 docache = 0;
845 rdonly = cnp->cn_flags & RDONLY;
846 cnp->cn_flags &= ~ISSYMLINK;
847 ndp->ni_dvp = NULL;
848 /*
849 * We use shared locks until we hit the parent of the last cn then
850 * we adjust based on the requesting flags.
851 */
852 cnp->cn_lkflags = LK_SHARED;
853 dp = ndp->ni_startdir;
854 ndp->ni_startdir = NULLVP;
855 vn_lock(dp,
856 compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags | LK_RETRY,
857 cnp->cn_flags));
858
859 dirloop:
860 /*
861 * Search a new directory.
862 *
863 * The last component of the filename is left accessible via
864 * cnp->cn_nameptr for callers that need the name. Callers needing
865 * the name set the SAVENAME flag. When done, they assume
866 * responsibility for freeing the pathname buffer.
867 *
868 * Store / as a temporary sentinel so that we only have one character
869 * to test for. Pathnames tend to be short so this should not be
870 * resulting in cache misses.
871 */
872 nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
873 KASSERT(*nulchar == '\0',
874 ("%s: expected nul at %p; string [%s]\n", __func__, nulchar,
875 cnp->cn_pnbuf));
876 *nulchar = '/';
877 for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
878 KASSERT(*cp != '\0',
879 ("%s: encountered unexpected nul; string [%s]\n", __func__,
880 cnp->cn_nameptr));
881 continue;
882 }
883 *nulchar = '\0';
884 cnp->cn_namelen = cp - cnp->cn_nameptr;
885 if (cnp->cn_namelen > NAME_MAX) {
886 error = ENAMETOOLONG;
887 goto bad;
888 }
889 #ifdef NAMEI_DIAGNOSTIC
890 { char c = *cp;
891 *cp = '\0';
892 printf("{%s}: ", cnp->cn_nameptr);
893 *cp = c; }
894 #endif
895 prev_ni_pathlen = ndp->ni_pathlen;
896 ndp->ni_pathlen -= cnp->cn_namelen;
897 KASSERT(ndp->ni_pathlen <= PATH_MAX,
898 ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
899 prev_ni_next = ndp->ni_next;
900 ndp->ni_next = cp;
901
902 /*
903 * Replace multiple slashes by a single slash and trailing slashes
904 * by a null. This must be done before VOP_LOOKUP() because some
905 * fs's don't know about trailing slashes. Remember if there were
906 * trailing slashes to handle symlinks, existing non-directories
907 * and non-existing files that won't be directories specially later.
908 */
909 while (*cp == '/' && (cp[1] == '/' || cp[1] == '\0')) {
910 cp++;
911 ndp->ni_pathlen--;
912 if (*cp == '\0') {
913 *ndp->ni_next = '\0';
914 cnp->cn_flags |= TRAILINGSLASH;
915 }
916 }
917 ndp->ni_next = cp;
918
919 cnp->cn_flags |= MAKEENTRY;
920 if (*cp == '\0' && docache == 0)
921 cnp->cn_flags &= ~MAKEENTRY;
922 if (cnp->cn_namelen == 2 &&
923 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
924 cnp->cn_flags |= ISDOTDOT;
925 else
926 cnp->cn_flags &= ~ISDOTDOT;
927 if (*ndp->ni_next == 0)
928 cnp->cn_flags |= ISLASTCN;
929 else
930 cnp->cn_flags &= ~ISLASTCN;
931
932 if ((cnp->cn_flags & ISLASTCN) != 0 &&
933 cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.' &&
934 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
935 error = EINVAL;
936 goto bad;
937 }
938
939 nameicap_tracker_add(ndp, dp);
940
941 /*
942 * Check for degenerate name (e.g. / or "")
943 * which is a way of talking about a directory,
944 * e.g. like "/." or ".".
945 */
946 if (cnp->cn_nameptr[0] == '\0') {
947 if (dp->v_type != VDIR) {
948 error = ENOTDIR;
949 goto bad;
950 }
951 if (cnp->cn_nameiop != LOOKUP) {
952 error = EISDIR;
953 goto bad;
954 }
955 if (wantparent) {
956 ndp->ni_dvp = dp;
957 VREF(dp);
958 }
959 ndp->ni_vp = dp;
960
961 if (cnp->cn_flags & AUDITVNODE1)
962 AUDIT_ARG_VNODE1(dp);
963 else if (cnp->cn_flags & AUDITVNODE2)
964 AUDIT_ARG_VNODE2(dp);
965
966 if (!(cnp->cn_flags & (LOCKPARENT | LOCKLEAF)))
967 VOP_UNLOCK(dp);
968 /* XXX This should probably move to the top of function. */
969 if (cnp->cn_flags & SAVESTART)
970 panic("lookup: SAVESTART");
971 goto success;
972 }
973
974 /*
975 * Handle "..": five special cases.
976 * 0. If doing a capability lookup and lookup_cap_dotdot is
977 * disabled, return ENOTCAPABLE.
978 * 1. Return an error if this is the last component of
979 * the name and the operation is DELETE or RENAME.
980 * 2. If at root directory (e.g. after chroot)
981 * or at absolute root directory
982 * then ignore it so can't get out.
983 * 3. If this vnode is the root of a mounted
984 * filesystem, then replace it with the
985 * vnode which was mounted on so we take the
986 * .. in the other filesystem.
987 * 4. If the vnode is the top directory of
988 * the jail or chroot, don't let them out.
989 * 5. If doing a capability lookup and lookup_cap_dotdot is
990 * enabled, return ENOTCAPABLE if the lookup would escape
991 * from the initial file descriptor directory. Checks are
992 * done by ensuring that namei() already traversed the
993 * result of dotdot lookup.
994 */
995 if (cnp->cn_flags & ISDOTDOT) {
996 if ((ndp->ni_lcf & (NI_LCF_STRICTRELATIVE | NI_LCF_CAP_DOTDOT))
997 == NI_LCF_STRICTRELATIVE) {
998 #ifdef KTRACE
999 if (KTRPOINT(curthread, KTR_CAPFAIL))
1000 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1001 #endif
1002 error = ENOTCAPABLE;
1003 goto bad;
1004 }
1005 if ((cnp->cn_flags & ISLASTCN) != 0 &&
1006 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1007 error = EINVAL;
1008 goto bad;
1009 }
1010 for (;;) {
1011 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
1012 pr = pr->pr_parent)
1013 if (dp == pr->pr_root)
1014 break;
1015 bool isroot = dp == ndp->ni_rootdir ||
1016 dp == ndp->ni_topdir || dp == rootvnode ||
1017 pr != NULL;
1018 if (isroot && (ndp->ni_lcf &
1019 NI_LCF_STRICTRELATIVE) != 0) {
1020 error = ENOTCAPABLE;
1021 goto capdotdot;
1022 }
1023 if (isroot || ((dp->v_vflag & VV_ROOT) != 0 &&
1024 (cnp->cn_flags & NOCROSSMOUNT) != 0)) {
1025 ndp->ni_dvp = dp;
1026 ndp->ni_vp = dp;
1027 VREF(dp);
1028 goto nextname;
1029 }
1030 if ((dp->v_vflag & VV_ROOT) == 0)
1031 break;
1032 if (VN_IS_DOOMED(dp)) { /* forced unmount */
1033 error = ENOENT;
1034 goto bad;
1035 }
1036 tdp = dp;
1037 dp = dp->v_mount->mnt_vnodecovered;
1038 VREF(dp);
1039 vput(tdp);
1040 vn_lock(dp,
1041 compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags |
1042 LK_RETRY, ISDOTDOT));
1043 error = nameicap_check_dotdot(ndp, dp);
1044 if (error != 0) {
1045 capdotdot:
1046 #ifdef KTRACE
1047 if (KTRPOINT(curthread, KTR_CAPFAIL))
1048 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1049 #endif
1050 goto bad;
1051 }
1052 }
1053 }
1054
1055 /*
1056 * We now have a segment name to search for, and a directory to search.
1057 */
1058 unionlookup:
1059 #ifdef MAC
1060 error = mac_vnode_check_lookup(cnp->cn_thread->td_ucred, dp, cnp);
1061 if (error)
1062 goto bad;
1063 #endif
1064 ndp->ni_dvp = dp;
1065 ndp->ni_vp = NULL;
1066 ASSERT_VOP_LOCKED(dp, "lookup");
1067 /*
1068 * If we have a shared lock we may need to upgrade the lock for the
1069 * last operation.
1070 */
1071 if ((cnp->cn_flags & LOCKPARENT) && (cnp->cn_flags & ISLASTCN) &&
1072 dp != vp_crossmp && VOP_ISLOCKED(dp) == LK_SHARED)
1073 vn_lock(dp, LK_UPGRADE|LK_RETRY);
1074 if (VN_IS_DOOMED(dp)) {
1075 error = ENOENT;
1076 goto bad;
1077 }
1078 /*
1079 * If we're looking up the last component and we need an exclusive
1080 * lock, adjust our lkflags.
1081 */
1082 if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags))
1083 cnp->cn_lkflags = LK_EXCLUSIVE;
1084 #ifdef NAMEI_DIAGNOSTIC
1085 vn_printf(dp, "lookup in ");
1086 #endif
1087 lkflags_save = cnp->cn_lkflags;
1088 cnp->cn_lkflags = compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags,
1089 cnp->cn_flags);
1090 error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp);
1091 cnp->cn_lkflags = lkflags_save;
1092 if (error != 0) {
1093 KASSERT(ndp->ni_vp == NULL, ("leaf should be empty"));
1094 #ifdef NAMEI_DIAGNOSTIC
1095 printf("not found\n");
1096 #endif
1097 if ((error == ENOENT) &&
1098 (dp->v_vflag & VV_ROOT) && (dp->v_mount != NULL) &&
1099 (dp->v_mount->mnt_flag & MNT_UNION)) {
1100 tdp = dp;
1101 dp = dp->v_mount->mnt_vnodecovered;
1102 VREF(dp);
1103 vput(tdp);
1104 vn_lock(dp,
1105 compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags |
1106 LK_RETRY, cnp->cn_flags));
1107 nameicap_tracker_add(ndp, dp);
1108 goto unionlookup;
1109 }
1110
1111 if (error == ERELOOKUP) {
1112 vref(dp);
1113 ndp->ni_vp = dp;
1114 error = 0;
1115 relookup = 1;
1116 goto good;
1117 }
1118
1119 if (error != EJUSTRETURN)
1120 goto bad;
1121 /*
1122 * At this point, we know we're at the end of the
1123 * pathname. If creating / renaming, we can consider
1124 * allowing the file or directory to be created / renamed,
1125 * provided we're not on a read-only filesystem.
1126 */
1127 if (rdonly) {
1128 error = EROFS;
1129 goto bad;
1130 }
1131 /* trailing slash only allowed for directories */
1132 if ((cnp->cn_flags & TRAILINGSLASH) &&
1133 !(cnp->cn_flags & WILLBEDIR)) {
1134 error = ENOENT;
1135 goto bad;
1136 }
1137 if ((cnp->cn_flags & LOCKPARENT) == 0)
1138 VOP_UNLOCK(dp);
1139 /*
1140 * We return with ni_vp NULL to indicate that the entry
1141 * doesn't currently exist, leaving a pointer to the
1142 * (possibly locked) directory vnode in ndp->ni_dvp.
1143 */
1144 if (cnp->cn_flags & SAVESTART) {
1145 ndp->ni_startdir = ndp->ni_dvp;
1146 VREF(ndp->ni_startdir);
1147 }
1148 goto success;
1149 }
1150
1151 good:
1152 #ifdef NAMEI_DIAGNOSTIC
1153 printf("found\n");
1154 #endif
1155 dp = ndp->ni_vp;
1156
1157 /*
1158 * Check to see if the vnode has been mounted on;
1159 * if so find the root of the mounted filesystem.
1160 */
1161 while ((dp->v_type == VDIR || dp->v_type == VREG) &&
1162 (mp = dp->v_mountedhere) && (cnp->cn_flags & NOCROSSMOUNT) == 0) {
1163 if (vfs_busy(mp, 0))
1164 continue;
1165 vput(dp);
1166 if (dp != ndp->ni_dvp)
1167 vput(ndp->ni_dvp);
1168 else
1169 vrele(ndp->ni_dvp);
1170 vrefact(vp_crossmp);
1171 ndp->ni_dvp = vp_crossmp;
1172 error = VFS_ROOT(mp, compute_cn_lkflags(mp, cnp->cn_lkflags,
1173 cnp->cn_flags), &tdp);
1174 vfs_unbusy(mp);
1175 if (vn_lock(vp_crossmp, LK_SHARED | LK_NOWAIT))
1176 panic("vp_crossmp exclusively locked or reclaimed");
1177 if (error) {
1178 dpunlocked = 1;
1179 goto bad2;
1180 }
1181 ndp->ni_vp = dp = tdp;
1182 }
1183
1184 /*
1185 * Check for symbolic link
1186 */
1187 if ((dp->v_type == VLNK) &&
1188 ((cnp->cn_flags & FOLLOW) || (cnp->cn_flags & TRAILINGSLASH) ||
1189 *ndp->ni_next == '/')) {
1190 cnp->cn_flags |= ISSYMLINK;
1191 if (VN_IS_DOOMED(dp)) {
1192 /*
1193 * We can't know whether the directory was mounted with
1194 * NOSYMFOLLOW, so we can't follow safely.
1195 */
1196 error = ENOENT;
1197 goto bad2;
1198 }
1199 if (dp->v_mount->mnt_flag & MNT_NOSYMFOLLOW) {
1200 error = EACCES;
1201 goto bad2;
1202 }
1203 /*
1204 * Symlink code always expects an unlocked dvp.
1205 */
1206 if (ndp->ni_dvp != ndp->ni_vp) {
1207 VOP_UNLOCK(ndp->ni_dvp);
1208 ni_dvp_unlocked = 1;
1209 }
1210 goto success;
1211 }
1212
1213 nextname:
1214 /*
1215 * Not a symbolic link that we will follow. Continue with the
1216 * next component if there is any; otherwise, we're done.
1217 */
1218 KASSERT((cnp->cn_flags & ISLASTCN) || *ndp->ni_next == '/',
1219 ("lookup: invalid path state."));
1220 if (relookup) {
1221 relookup = 0;
1222 ndp->ni_pathlen = prev_ni_pathlen;
1223 ndp->ni_next = prev_ni_next;
1224 if (ndp->ni_dvp != dp)
1225 vput(ndp->ni_dvp);
1226 else
1227 vrele(ndp->ni_dvp);
1228 goto dirloop;
1229 }
1230 if (cnp->cn_flags & ISDOTDOT) {
1231 error = nameicap_check_dotdot(ndp, ndp->ni_vp);
1232 if (error != 0) {
1233 #ifdef KTRACE
1234 if (KTRPOINT(curthread, KTR_CAPFAIL))
1235 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1236 #endif
1237 goto bad2;
1238 }
1239 }
1240 if (*ndp->ni_next == '/') {
1241 cnp->cn_nameptr = ndp->ni_next;
1242 while (*cnp->cn_nameptr == '/') {
1243 cnp->cn_nameptr++;
1244 ndp->ni_pathlen--;
1245 }
1246 if (ndp->ni_dvp != dp)
1247 vput(ndp->ni_dvp);
1248 else
1249 vrele(ndp->ni_dvp);
1250 goto dirloop;
1251 }
1252 /*
1253 * If we're processing a path with a trailing slash,
1254 * check that the end result is a directory.
1255 */
1256 if ((cnp->cn_flags & TRAILINGSLASH) && dp->v_type != VDIR) {
1257 error = ENOTDIR;
1258 goto bad2;
1259 }
1260 /*
1261 * Disallow directory write attempts on read-only filesystems.
1262 */
1263 if (rdonly &&
1264 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1265 error = EROFS;
1266 goto bad2;
1267 }
1268 if (cnp->cn_flags & SAVESTART) {
1269 ndp->ni_startdir = ndp->ni_dvp;
1270 VREF(ndp->ni_startdir);
1271 }
1272 if (!wantparent) {
1273 ni_dvp_unlocked = 2;
1274 if (ndp->ni_dvp != dp)
1275 vput(ndp->ni_dvp);
1276 else
1277 vrele(ndp->ni_dvp);
1278 } else if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp != dp) {
1279 VOP_UNLOCK(ndp->ni_dvp);
1280 ni_dvp_unlocked = 1;
1281 }
1282
1283 if (cnp->cn_flags & AUDITVNODE1)
1284 AUDIT_ARG_VNODE1(dp);
1285 else if (cnp->cn_flags & AUDITVNODE2)
1286 AUDIT_ARG_VNODE2(dp);
1287
1288 if ((cnp->cn_flags & LOCKLEAF) == 0)
1289 VOP_UNLOCK(dp);
1290 success:
1291 /*
1292 * FIXME: for lookups which only cross a mount point to fetch the
1293 * root vnode, ni_dvp will be set to vp_crossmp. This can be a problem
1294 * if either WANTPARENT or LOCKPARENT is set.
1295 */
1296 /*
1297 * Because of shared lookup we may have the vnode shared locked, but
1298 * the caller may want it to be exclusively locked.
1299 */
1300 if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags) &&
1301 VOP_ISLOCKED(dp) != LK_EXCLUSIVE) {
1302 vn_lock(dp, LK_UPGRADE | LK_RETRY);
1303 if (VN_IS_DOOMED(dp)) {
1304 error = ENOENT;
1305 goto bad2;
1306 }
1307 }
1308 if (ndp->ni_vp != NULL) {
1309 if ((cnp->cn_flags & ISDOTDOT) == 0)
1310 nameicap_tracker_add(ndp, ndp->ni_vp);
1311 if ((cnp->cn_flags & (FAILIFEXISTS | ISSYMLINK)) == FAILIFEXISTS)
1312 goto bad_eexist;
1313 }
1314 return (0);
1315
1316 bad2:
1317 if (ni_dvp_unlocked != 2) {
1318 if (dp != ndp->ni_dvp && !ni_dvp_unlocked)
1319 vput(ndp->ni_dvp);
1320 else
1321 vrele(ndp->ni_dvp);
1322 }
1323 bad:
1324 if (!dpunlocked)
1325 vput(dp);
1326 ndp->ni_vp = NULL;
1327 return (error);
1328 bad_eexist:
1329 /*
1330 * FAILIFEXISTS handling.
1331 *
1332 * XXX namei called with LOCKPARENT but not LOCKLEAF has the strange
1333 * behaviour of leaving the vnode unlocked if the target is the same
1334 * vnode as the parent.
1335 */
1336 MPASS((cnp->cn_flags & ISSYMLINK) == 0);
1337 if (ndp->ni_vp == ndp->ni_dvp)
1338 vrele(ndp->ni_dvp);
1339 else
1340 vput(ndp->ni_dvp);
1341 vrele(ndp->ni_vp);
1342 ndp->ni_dvp = NULL;
1343 ndp->ni_vp = NULL;
1344 NDFREE(ndp, NDF_ONLY_PNBUF);
1345 return (EEXIST);
1346 }
1347
1348 /*
1349 * relookup - lookup a path name component
1350 * Used by lookup to re-acquire things.
1351 */
1352 int
relookup(struct vnode * dvp,struct vnode ** vpp,struct componentname * cnp)1353 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
1354 {
1355 struct vnode *dp = NULL; /* the directory we are searching */
1356 int rdonly; /* lookup read-only flag bit */
1357 int error = 0;
1358
1359 KASSERT(cnp->cn_flags & ISLASTCN,
1360 ("relookup: Not given last component."));
1361 /*
1362 * Setup: break out flag bits into variables.
1363 */
1364 KASSERT((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) != 0,
1365 ("relookup: parent not wanted"));
1366 rdonly = cnp->cn_flags & RDONLY;
1367 cnp->cn_flags &= ~ISSYMLINK;
1368 dp = dvp;
1369 cnp->cn_lkflags = LK_EXCLUSIVE;
1370 vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
1371
1372 /*
1373 * Search a new directory.
1374 *
1375 * The last component of the filename is left accessible via
1376 * cnp->cn_nameptr for callers that need the name. Callers needing
1377 * the name set the SAVENAME flag. When done, they assume
1378 * responsibility for freeing the pathname buffer.
1379 */
1380 #ifdef NAMEI_DIAGNOSTIC
1381 printf("{%s}: ", cnp->cn_nameptr);
1382 #endif
1383
1384 /*
1385 * Check for "" which represents the root directory after slash
1386 * removal.
1387 */
1388 if (cnp->cn_nameptr[0] == '\0') {
1389 /*
1390 * Support only LOOKUP for "/" because lookup()
1391 * can't succeed for CREATE, DELETE and RENAME.
1392 */
1393 KASSERT(cnp->cn_nameiop == LOOKUP, ("nameiop must be LOOKUP"));
1394 KASSERT(dp->v_type == VDIR, ("dp is not a directory"));
1395
1396 if (!(cnp->cn_flags & LOCKLEAF))
1397 VOP_UNLOCK(dp);
1398 *vpp = dp;
1399 /* XXX This should probably move to the top of function. */
1400 if (cnp->cn_flags & SAVESTART)
1401 panic("lookup: SAVESTART");
1402 return (0);
1403 }
1404
1405 if (cnp->cn_flags & ISDOTDOT)
1406 panic ("relookup: lookup on dot-dot");
1407
1408 /*
1409 * We now have a segment name to search for, and a directory to search.
1410 */
1411 #ifdef NAMEI_DIAGNOSTIC
1412 vn_printf(dp, "search in ");
1413 #endif
1414 if ((error = VOP_LOOKUP(dp, vpp, cnp)) != 0) {
1415 KASSERT(*vpp == NULL, ("leaf should be empty"));
1416 if (error != EJUSTRETURN)
1417 goto bad;
1418 /*
1419 * If creating and at end of pathname, then can consider
1420 * allowing file to be created.
1421 */
1422 if (rdonly) {
1423 error = EROFS;
1424 goto bad;
1425 }
1426 /* ASSERT(dvp == ndp->ni_startdir) */
1427 if (cnp->cn_flags & SAVESTART)
1428 VREF(dvp);
1429 if ((cnp->cn_flags & LOCKPARENT) == 0)
1430 VOP_UNLOCK(dp);
1431 /*
1432 * We return with ni_vp NULL to indicate that the entry
1433 * doesn't currently exist, leaving a pointer to the
1434 * (possibly locked) directory vnode in ndp->ni_dvp.
1435 */
1436 return (0);
1437 }
1438
1439 dp = *vpp;
1440
1441 /*
1442 * Disallow directory write attempts on read-only filesystems.
1443 */
1444 if (rdonly &&
1445 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1446 if (dvp == dp)
1447 vrele(dvp);
1448 else
1449 vput(dvp);
1450 error = EROFS;
1451 goto bad;
1452 }
1453 /*
1454 * Set the parent lock/ref state to the requested state.
1455 */
1456 if ((cnp->cn_flags & LOCKPARENT) == 0 && dvp != dp)
1457 VOP_UNLOCK(dvp);
1458 /*
1459 * Check for symbolic link
1460 */
1461 KASSERT(dp->v_type != VLNK || !(cnp->cn_flags & FOLLOW),
1462 ("relookup: symlink found.\n"));
1463
1464 /* ASSERT(dvp == ndp->ni_startdir) */
1465 if (cnp->cn_flags & SAVESTART)
1466 VREF(dvp);
1467
1468 if ((cnp->cn_flags & LOCKLEAF) == 0)
1469 VOP_UNLOCK(dp);
1470 return (0);
1471 bad:
1472 vput(dp);
1473 *vpp = NULL;
1474 return (error);
1475 }
1476
1477 /*
1478 * Free data allocated by namei(); see namei(9) for details.
1479 */
1480 void
NDFREE_PNBUF(struct nameidata * ndp)1481 NDFREE_PNBUF(struct nameidata *ndp)
1482 {
1483
1484 if ((ndp->ni_cnd.cn_flags & HASBUF) != 0) {
1485 MPASS((ndp->ni_cnd.cn_flags & (SAVENAME | SAVESTART)) != 0);
1486 uma_zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
1487 ndp->ni_cnd.cn_flags &= ~HASBUF;
1488 }
1489 }
1490
1491 /*
1492 * NDFREE_PNBUF replacement for callers that know there is no buffer.
1493 *
1494 * This is a hack. Preferably the VFS layer would not produce anything more
1495 * than it was asked to do. Unfortunately several non-LOOKUP cases can add the
1496 * HASBUF flag to the result. Even then an interface could be implemented where
1497 * the caller specifies what they expected to see in the result and what they
1498 * are going to take care of.
1499 *
1500 * In the meantime provide this kludge as a trivial replacement for NDFREE_PNBUF
1501 * calls scattered throughout the kernel where we know for a fact the flag must not
1502 * be seen.
1503 */
1504 #ifdef INVARIANTS
1505 void
NDFREE_NOTHING(struct nameidata * ndp)1506 NDFREE_NOTHING(struct nameidata *ndp)
1507 {
1508 struct componentname *cnp;
1509
1510 cnp = &ndp->ni_cnd;
1511 KASSERT(cnp->cn_nameiop == LOOKUP, ("%s: got non-LOOKUP op %d\n",
1512 __func__, cnp->cn_nameiop));
1513 KASSERT((cnp->cn_flags & (SAVENAME | HASBUF)) == 0,
1514 ("%s: bad flags \%" PRIx64 "\n", __func__, cnp->cn_flags));
1515 }
1516 #endif
1517
1518 void
1519 (NDFREE)(struct nameidata *ndp, const u_int flags)
1520 {
1521 int unlock_dvp;
1522 int unlock_vp;
1523
1524 unlock_dvp = 0;
1525 unlock_vp = 0;
1526
1527 if (!(flags & NDF_NO_FREE_PNBUF)) {
1528 NDFREE_PNBUF(ndp);
1529 }
1530 if (!(flags & NDF_NO_VP_UNLOCK) &&
1531 (ndp->ni_cnd.cn_flags & LOCKLEAF) && ndp->ni_vp)
1532 unlock_vp = 1;
1533 if (!(flags & NDF_NO_DVP_UNLOCK) &&
1534 (ndp->ni_cnd.cn_flags & LOCKPARENT) &&
1535 ndp->ni_dvp != ndp->ni_vp)
1536 unlock_dvp = 1;
1537 if (!(flags & NDF_NO_VP_RELE) && ndp->ni_vp) {
1538 if (unlock_vp) {
1539 vput(ndp->ni_vp);
1540 unlock_vp = 0;
1541 } else
1542 vrele(ndp->ni_vp);
1543 ndp->ni_vp = NULL;
1544 }
1545 if (unlock_vp)
1546 VOP_UNLOCK(ndp->ni_vp);
1547 if (!(flags & NDF_NO_DVP_RELE) &&
1548 (ndp->ni_cnd.cn_flags & (LOCKPARENT|WANTPARENT))) {
1549 if (unlock_dvp) {
1550 vput(ndp->ni_dvp);
1551 unlock_dvp = 0;
1552 } else
1553 vrele(ndp->ni_dvp);
1554 ndp->ni_dvp = NULL;
1555 }
1556 if (unlock_dvp)
1557 VOP_UNLOCK(ndp->ni_dvp);
1558 if (!(flags & NDF_NO_STARTDIR_RELE) &&
1559 (ndp->ni_cnd.cn_flags & SAVESTART)) {
1560 vrele(ndp->ni_startdir);
1561 ndp->ni_startdir = NULL;
1562 }
1563 }
1564
1565 #ifdef INVARIANTS
1566 /*
1567 * Validate the final state of ndp after the lookup.
1568 *
1569 * Historically filesystems were allowed to modify cn_flags. Most notably they
1570 * can add SAVENAME to the request, resulting in HASBUF and pushing subsequent
1571 * clean up to the consumer. In practice this seems to only concern != LOOKUP
1572 * operations.
1573 *
1574 * As a step towards stricter API contract this routine validates the state to
1575 * clean up. Note validation is a work in progress with the intent of becoming
1576 * stricter over time.
1577 */
1578 #define NDMODIFYINGFLAGS (LOCKLEAF | LOCKPARENT | WANTPARENT | SAVENAME | SAVESTART | HASBUF)
1579 void
NDVALIDATE(struct nameidata * ndp)1580 NDVALIDATE(struct nameidata *ndp)
1581 {
1582 struct componentname *cnp;
1583 u_int64_t used, orig;
1584
1585 cnp = &ndp->ni_cnd;
1586 orig = cnp->cn_origflags;
1587 used = cnp->cn_flags;
1588 switch (cnp->cn_nameiop) {
1589 case LOOKUP:
1590 /*
1591 * For plain lookup we require strict conformance -- nothing
1592 * to clean up if it was not requested by the caller.
1593 */
1594 orig &= NDMODIFYINGFLAGS;
1595 used &= NDMODIFYINGFLAGS;
1596 if ((orig & (SAVENAME | SAVESTART)) != 0)
1597 orig |= HASBUF;
1598 if (orig != used) {
1599 goto out_mismatch;
1600 }
1601 break;
1602 case CREATE:
1603 case DELETE:
1604 case RENAME:
1605 /*
1606 * Some filesystems set SAVENAME to provoke HASBUF, accommodate
1607 * for it until it gets fixed.
1608 */
1609 orig &= NDMODIFYINGFLAGS;
1610 orig |= (SAVENAME | HASBUF);
1611 used &= NDMODIFYINGFLAGS;
1612 used |= (SAVENAME | HASBUF);
1613 if (orig != used) {
1614 goto out_mismatch;
1615 }
1616 break;
1617 }
1618 return;
1619 out_mismatch:
1620 panic("%s: mismatched flags for op %d: added %" PRIx64 ", "
1621 "removed %" PRIx64" (%" PRIx64" != %" PRIx64"; stored %" PRIx64" != %" PRIx64")",
1622 __func__, cnp->cn_nameiop, used & ~orig, orig &~ used,
1623 orig, used, cnp->cn_origflags, cnp->cn_flags);
1624 }
1625 #endif
1626
1627 /*
1628 * Determine if there is a suitable alternate filename under the specified
1629 * prefix for the specified path. If the create flag is set, then the
1630 * alternate prefix will be used so long as the parent directory exists.
1631 * This is used by the various compatibility ABIs so that Linux binaries prefer
1632 * files under /compat/linux for example. The chosen path (whether under
1633 * the prefix or under /) is returned in a kernel malloc'd buffer pointed
1634 * to by pathbuf. The caller is responsible for free'ing the buffer from
1635 * the M_TEMP bucket if one is returned.
1636 */
1637 int
kern_alternate_path(struct thread * td,const char * prefix,const char * path,enum uio_seg pathseg,char ** pathbuf,int create,int dirfd)1638 kern_alternate_path(struct thread *td, const char *prefix, const char *path,
1639 enum uio_seg pathseg, char **pathbuf, int create, int dirfd)
1640 {
1641 struct nameidata nd, ndroot;
1642 char *ptr, *buf, *cp;
1643 size_t len, sz;
1644 int error;
1645
1646 buf = (char *) malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1647 *pathbuf = buf;
1648
1649 /* Copy the prefix into the new pathname as a starting point. */
1650 len = strlcpy(buf, prefix, MAXPATHLEN);
1651 if (len >= MAXPATHLEN) {
1652 *pathbuf = NULL;
1653 free(buf, M_TEMP);
1654 return (EINVAL);
1655 }
1656 sz = MAXPATHLEN - len;
1657 ptr = buf + len;
1658
1659 /* Append the filename to the prefix. */
1660 if (pathseg == UIO_SYSSPACE)
1661 error = copystr(path, ptr, sz, &len);
1662 else
1663 error = copyinstr(path, ptr, sz, &len);
1664
1665 if (error) {
1666 *pathbuf = NULL;
1667 free(buf, M_TEMP);
1668 return (error);
1669 }
1670
1671 /* Only use a prefix with absolute pathnames. */
1672 if (*ptr != '/') {
1673 error = EINVAL;
1674 goto keeporig;
1675 }
1676
1677 if (dirfd != AT_FDCWD) {
1678 /*
1679 * We want the original because the "prefix" is
1680 * included in the already opened dirfd.
1681 */
1682 bcopy(ptr, buf, len);
1683 return (0);
1684 }
1685
1686 /*
1687 * We know that there is a / somewhere in this pathname.
1688 * Search backwards for it, to find the file's parent dir
1689 * to see if it exists in the alternate tree. If it does,
1690 * and we want to create a file (cflag is set). We don't
1691 * need to worry about the root comparison in this case.
1692 */
1693
1694 if (create) {
1695 for (cp = &ptr[len] - 1; *cp != '/'; cp--);
1696 *cp = '\0';
1697
1698 NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, buf, td);
1699 error = namei(&nd);
1700 *cp = '/';
1701 if (error != 0)
1702 goto keeporig;
1703 } else {
1704 NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, buf, td);
1705
1706 error = namei(&nd);
1707 if (error != 0)
1708 goto keeporig;
1709
1710 /*
1711 * We now compare the vnode of the prefix to the one
1712 * vnode asked. If they resolve to be the same, then we
1713 * ignore the match so that the real root gets used.
1714 * This avoids the problem of traversing "../.." to find the
1715 * root directory and never finding it, because "/" resolves
1716 * to the emulation root directory. This is expensive :-(
1717 */
1718 NDINIT(&ndroot, LOOKUP, FOLLOW, UIO_SYSSPACE, prefix,
1719 td);
1720
1721 /* We shouldn't ever get an error from this namei(). */
1722 error = namei(&ndroot);
1723 if (error == 0) {
1724 if (nd.ni_vp == ndroot.ni_vp)
1725 error = ENOENT;
1726
1727 NDFREE(&ndroot, NDF_ONLY_PNBUF);
1728 vrele(ndroot.ni_vp);
1729 }
1730 }
1731
1732 NDFREE(&nd, NDF_ONLY_PNBUF);
1733 vrele(nd.ni_vp);
1734
1735 keeporig:
1736 /* If there was an error, use the original path name. */
1737 if (error)
1738 bcopy(ptr, buf, len);
1739 return (error);
1740 }
1741