xref: /netbsd-src/sys/kern/vfs_getcwd.c (revision a4ddc2c8fb9af816efe3b1c375a5530aef0e89e9)
1 /* $NetBSD: vfs_getcwd.c,v 1.48 2012/11/05 17:24:11 dholland Exp $ */
2 
3 /*-
4  * Copyright (c) 1999 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Bill Sommerfeld.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 __KERNEL_RCSID(0, "$NetBSD: vfs_getcwd.c,v 1.48 2012/11/05 17:24:11 dholland Exp $");
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/namei.h>
38 #include <sys/filedesc.h>
39 #include <sys/kernel.h>
40 #include <sys/file.h>
41 #include <sys/stat.h>
42 #include <sys/vnode.h>
43 #include <sys/mount.h>
44 #include <sys/proc.h>
45 #include <sys/uio.h>
46 #include <sys/kmem.h>
47 #include <sys/dirent.h>
48 #include <sys/kauth.h>
49 
50 #include <ufs/ufs/dir.h>	/* XXX only for DIRBLKSIZ */
51 
52 #include <sys/syscallargs.h>
53 
54 /*
55  * Vnode variable naming conventions in this file:
56  *
57  * rvp: the current root we're aiming towards.
58  * lvp, *lvpp: the "lower" vnode
59  * uvp, *uvpp: the "upper" vnode.
60  *
61  * Since all the vnodes we're dealing with are directories, and the
62  * lookups are going *up* in the filesystem rather than *down*, the
63  * usual "pvp" (parent) or "dvp" (directory) naming conventions are
64  * too confusing.
65  */
66 
67 /*
68  * XXX Will infinite loop in certain cases if a directory read reliably
69  *	returns EINVAL on last block.
70  * XXX is EINVAL the right thing to return if a directory is malformed?
71  */
72 
73 /*
74  * XXX Untested vs. mount -o union; probably does the wrong thing.
75  */
76 
77 /*
78  * Find parent vnode of *lvpp, return in *uvpp
79  *
80  * If we care about the name, scan it looking for name of directory
81  * entry pointing at lvp.
82  *
83  * Place the name in the buffer which starts at bufp, immediately
84  * before *bpp, and move bpp backwards to point at the start of it.
85  *
86  * On entry, *lvpp is a locked vnode reference; on exit, it is vput and NULL'ed
87  * On exit, *uvpp is either NULL or is a locked vnode reference.
88  */
89 static int
90 getcwd_scandir(struct vnode **lvpp, struct vnode **uvpp, char **bpp,
91     char *bufp, struct lwp *l)
92 {
93 	int     error = 0;
94 	int     eofflag;
95 	off_t   off;
96 	int     tries;
97 	struct uio uio;
98 	struct iovec iov;
99 	char   *dirbuf = NULL;
100 	int	dirbuflen;
101 	ino_t   fileno;
102 	struct vattr va;
103 	struct vnode *uvp = NULL;
104 	struct vnode *lvp = *lvpp;
105 	kauth_cred_t cred = l->l_cred;
106 	struct componentname cn;
107 	int len, reclen;
108 	tries = 0;
109 
110 	/*
111 	 * If we want the filename, get some info we need while the
112 	 * current directory is still locked.
113 	 */
114 	if (bufp != NULL) {
115 		error = VOP_GETATTR(lvp, &va, cred);
116 		if (error) {
117 			vput(lvp);
118 			*lvpp = NULL;
119 			*uvpp = NULL;
120 			return error;
121 		}
122 	}
123 
124 	/*
125 	 * Ok, we have to do it the hard way..
126 	 * Next, get parent vnode using lookup of ..
127 	 */
128 	cn.cn_nameiop = LOOKUP;
129 	cn.cn_flags = ISLASTCN | ISDOTDOT | RDONLY;
130 	cn.cn_cred = cred;
131 	cn.cn_nameptr = "..";
132 	cn.cn_namelen = 2;
133 	cn.cn_consume = 0;
134 
135 	/*
136 	 * At this point, lvp is locked.
137 	 * On successful return, *uvpp will be locked
138 	 */
139 	error = VOP_LOOKUP(lvp, uvpp, &cn);
140 	vput(lvp);
141 	if (error) {
142 		*lvpp = NULL;
143 		*uvpp = NULL;
144 		return error;
145 	}
146 	uvp = *uvpp;
147 
148 	/* If we don't care about the pathname, we're done */
149 	if (bufp == NULL) {
150 		*lvpp = NULL;
151 		return 0;
152 	}
153 
154 	fileno = va.va_fileid;
155 
156 	dirbuflen = DIRBLKSIZ;
157 	if (dirbuflen < va.va_blocksize)
158 		dirbuflen = va.va_blocksize;
159 	dirbuf = kmem_alloc(dirbuflen, KM_SLEEP);
160 
161 #if 0
162 unionread:
163 #endif
164 	off = 0;
165 	do {
166 		/* call VOP_READDIR of parent */
167 		iov.iov_base = dirbuf;
168 		iov.iov_len = dirbuflen;
169 
170 		uio.uio_iov = &iov;
171 		uio.uio_iovcnt = 1;
172 		uio.uio_offset = off;
173 		uio.uio_resid = dirbuflen;
174 		uio.uio_rw = UIO_READ;
175 		UIO_SETUP_SYSSPACE(&uio);
176 
177 		eofflag = 0;
178 
179 		error = VOP_READDIR(uvp, &uio, cred, &eofflag, 0, 0);
180 
181 		off = uio.uio_offset;
182 
183 		/*
184 		 * Try again if NFS tosses its cookies.
185 		 * XXX this can still loop forever if the directory is busted
186 		 * such that the second or subsequent page of it always
187 		 * returns EINVAL
188 		 */
189 		if ((error == EINVAL) && (tries < 3)) {
190 			off = 0;
191 			tries++;
192 			continue;	/* once more, with feeling */
193 		}
194 
195 		if (!error) {
196 			char   *cpos;
197 			struct dirent *dp;
198 
199 			cpos = dirbuf;
200 			tries = 0;
201 
202 			/* scan directory page looking for matching vnode */
203 			for (len = (dirbuflen - uio.uio_resid); len > 0;
204 			    len -= reclen) {
205 				dp = (struct dirent *) cpos;
206 				reclen = dp->d_reclen;
207 
208 				/* check for malformed directory.. */
209 				if (reclen < _DIRENT_MINSIZE(dp)) {
210 					error = EINVAL;
211 					goto out;
212 				}
213 				/*
214 				 * XXX should perhaps do VOP_LOOKUP to
215 				 * check that we got back to the right place,
216 				 * but getting the locking games for that
217 				 * right would be heinous.
218 				 */
219 				if ((dp->d_type != DT_WHT) &&
220 				    (dp->d_fileno == fileno)) {
221 					char *bp = *bpp;
222 
223 					bp -= dp->d_namlen;
224 					if (bp <= bufp) {
225 						error = ERANGE;
226 						goto out;
227 					}
228 					memcpy(bp, dp->d_name, dp->d_namlen);
229 					error = 0;
230 					*bpp = bp;
231 					goto out;
232 				}
233 				cpos += reclen;
234 			}
235 		} else
236 			goto out;
237 	} while (!eofflag);
238 #if 0
239 	/*
240 	 * Deal with mount -o union, which unions only the
241 	 * root directory of the mount.
242 	 */
243 	if ((uvp->v_vflag & VV_ROOT) &&
244 	    (uvp->v_mount->mnt_flag & MNT_UNION)) {
245 		struct vnode *tvp = uvp;
246 
247 		uvp = uvp->v_mount->mnt_vnodecovered;
248 		vput(tvp);
249 		vref(uvp);
250 		*uvpp = uvp;
251 		vn_lock(uvp, LK_EXCLUSIVE | LK_RETRY);
252 		goto unionread;
253 	}
254 #endif
255 	error = ENOENT;
256 
257 out:
258 	*lvpp = NULL;
259 	kmem_free(dirbuf, dirbuflen);
260 	return error;
261 }
262 
263 /*
264  * Look in the vnode-to-name reverse cache to see if
265  * we can find things the easy way.
266  *
267  * XXX vget failure path is untested.
268  *
269  * On entry, *lvpp is a locked vnode reference.
270  * On exit, one of the following is the case:
271  *	0) Both *lvpp and *uvpp are NULL and failure is returned.
272  * 	1) *uvpp is NULL, *lvpp remains locked and -1 is returned (cache miss)
273  *	2) *uvpp is a locked vnode reference, *lvpp is vput and NULL'ed
274  *	   and 0 is returned (cache hit)
275  */
276 
277 static int
278 getcwd_getcache(struct vnode **lvpp, struct vnode **uvpp, char **bpp,
279     char *bufp)
280 {
281 	struct vnode *lvp, *uvp = NULL;
282 	int error;
283 
284 	lvp = *lvpp;
285 
286 	/*
287 	 * This returns 0 on a cache hit, -1 on a clean cache miss,
288 	 * or an errno on other failure.
289 	 */
290 	error = cache_revlookup(lvp, uvpp, bpp, bufp);
291 	if (error) {
292 		if (error != -1) {
293 			vput(lvp);
294 			*lvpp = NULL;
295 			*uvpp = NULL;
296 		}
297 		return error;
298 	}
299 	uvp = *uvpp;
300 
301 	/*
302 	 * Since we're going up, we have to release the current lock
303 	 * before we take the parent lock.
304 	 */
305 
306 	VOP_UNLOCK(lvp);
307 	vn_lock(uvp, LK_EXCLUSIVE | LK_RETRY);
308 	vrele(lvp);
309 	*lvpp = NULL;
310 
311 	return error;
312 }
313 
314 /*
315  * common routine shared by sys___getcwd() and vn_isunder()
316  */
317 
318 int
319 getcwd_common(struct vnode *lvp, struct vnode *rvp, char **bpp, char *bufp,
320     int limit, int flags, struct lwp *l)
321 {
322 	struct cwdinfo *cwdi = l->l_proc->p_cwdi;
323 	kauth_cred_t cred = l->l_cred;
324 	struct vnode *uvp = NULL;
325 	char *bp = NULL;
326 	int error;
327 	int perms = VEXEC;
328 
329 	error = 0;
330 	if (rvp == NULL) {
331 		rvp = cwdi->cwdi_rdir;
332 		if (rvp == NULL)
333 			rvp = rootvnode;
334 	}
335 
336 	vref(rvp);
337 	vref(lvp);
338 
339 	/*
340 	 * Error handling invariant:
341 	 * Before a `goto out':
342 	 *	lvp is either NULL, or locked and held.
343 	 *	uvp is either NULL, or locked and held.
344 	 */
345 
346 	vn_lock(lvp, LK_EXCLUSIVE | LK_RETRY);
347 	if (bufp)
348 		bp = *bpp;
349 
350 	/*
351 	 * this loop will terminate when one of the following happens:
352 	 *	- we hit the root
353 	 *	- getdirentries or lookup fails
354 	 *	- we run out of space in the buffer.
355 	 */
356 	if (lvp == rvp) {
357 		if (bp)
358 			*(--bp) = '/';
359 		goto out;
360 	}
361 	do {
362 		/*
363 		 * access check here is optional, depending on
364 		 * whether or not caller cares.
365 		 */
366 		if (flags & GETCWD_CHECK_ACCESS) {
367 			error = VOP_ACCESS(lvp, perms, cred);
368 			if (error)
369 				goto out;
370 			perms = VEXEC|VREAD;
371 		}
372 
373 		/*
374 		 * step up if we're a covered vnode..
375 		 */
376 		while (lvp->v_vflag & VV_ROOT) {
377 			struct vnode *tvp;
378 
379 			if (lvp == rvp)
380 				goto out;
381 
382 			tvp = lvp;
383 			lvp = lvp->v_mount->mnt_vnodecovered;
384 			vput(tvp);
385 			/*
386 			 * hodie natus est radici frater
387 			 */
388 			if (lvp == NULL) {
389 				error = ENOENT;
390 				goto out;
391 			}
392 			vref(lvp);
393 			error = vn_lock(lvp, LK_EXCLUSIVE | LK_RETRY);
394 			if (error != 0) {
395 				vrele(lvp);
396 				lvp = NULL;
397 				goto out;
398 			}
399 		}
400 		/*
401 		 * Look in the name cache; if that fails, look in the
402 		 * directory..
403 		 */
404 		error = getcwd_getcache(&lvp, &uvp, &bp, bufp);
405 		if (error == -1) {
406 			if (lvp->v_type != VDIR) {
407 				error = ENOTDIR;
408 				goto out;
409 			}
410 			error = getcwd_scandir(&lvp, &uvp, &bp, bufp, l);
411 		}
412 		if (error)
413 			goto out;
414 #if DIAGNOSTIC
415 		if (lvp != NULL)
416 			panic("getcwd: oops, forgot to null lvp");
417 		if (bufp && (bp <= bufp)) {
418 			panic("getcwd: oops, went back too far");
419 		}
420 #endif
421 		if (bp)
422 			*(--bp) = '/';
423 		lvp = uvp;
424 		uvp = NULL;
425 		limit--;
426 	} while ((lvp != rvp) && (limit > 0));
427 
428 out:
429 	if (bpp)
430 		*bpp = bp;
431 	if (uvp)
432 		vput(uvp);
433 	if (lvp)
434 		vput(lvp);
435 	vrele(rvp);
436 	return error;
437 }
438 
439 /*
440  * Check if one directory can be found inside another in the directory
441  * hierarchy.
442  *
443  * Intended to be used in chroot, chdir, fchdir, etc., to ensure that
444  * chroot() actually means something.
445  */
446 int
447 vn_isunder(struct vnode *lvp, struct vnode *rvp, struct lwp *l)
448 {
449 	int error;
450 
451 	error = getcwd_common(lvp, rvp, NULL, NULL, MAXPATHLEN / 2, 0, l);
452 
453 	if (!error)
454 		return 1;
455 	else
456 		return 0;
457 }
458 
459 /*
460  * Returns true if proc p1's root directory equal to or under p2's
461  * root directory.
462  *
463  * Intended to be used from ptrace/procfs sorts of things.
464  */
465 
466 int
467 proc_isunder(struct proc *p1, struct lwp *l2)
468 {
469 	struct vnode *r1 = p1->p_cwdi->cwdi_rdir;
470 	struct vnode *r2 = l2->l_proc->p_cwdi->cwdi_rdir;
471 
472 	if (r1 == NULL)
473 		return (r2 == NULL);
474 	else if (r2 == NULL)
475 		return 1;
476 	else
477 		return vn_isunder(r1, r2, l2);
478 }
479 
480 /*
481  * Find pathname of process's current directory.
482  *
483  * Use vfs vnode-to-name reverse cache; if that fails, fall back
484  * to reading directory contents.
485  */
486 
487 int
488 sys___getcwd(struct lwp *l, const struct sys___getcwd_args *uap, register_t *retval)
489 {
490 	/* {
491 		syscallarg(char *) bufp;
492 		syscallarg(size_t) length;
493 	} */
494 
495 	int     error;
496 	char   *path;
497 	char   *bp, *bend;
498 	int     len = SCARG(uap, length);
499 	int	lenused;
500 	struct	cwdinfo *cwdi;
501 
502 	if (len > MAXPATHLEN * 4)
503 		len = MAXPATHLEN * 4;
504 	else if (len < 2)
505 		return ERANGE;
506 
507 	path = kmem_alloc(len, KM_SLEEP);
508 	if (!path)
509 		return ENOMEM;
510 
511 	bp = &path[len];
512 	bend = bp;
513 	*(--bp) = '\0';
514 
515 	/*
516 	 * 5th argument here is "max number of vnodes to traverse".
517 	 * Since each entry takes up at least 2 bytes in the output buffer,
518 	 * limit it to N/2 vnodes for an N byte buffer.
519 	 */
520 	cwdi = l->l_proc->p_cwdi;
521 	rw_enter(&cwdi->cwdi_lock, RW_READER);
522 	error = getcwd_common(cwdi->cwdi_cdir, NULL, &bp, path,
523 	    len/2, GETCWD_CHECK_ACCESS, l);
524 	rw_exit(&cwdi->cwdi_lock);
525 
526 	if (error)
527 		goto out;
528 	lenused = bend - bp;
529 	*retval = lenused;
530 	/* put the result into user buffer */
531 	error = copyout(bp, SCARG(uap, bufp), lenused);
532 
533 out:
534 	kmem_free(path, len);
535 	return error;
536 }
537 
538 /*
539  * Try to find a pathname for a vnode. Since there is no mapping
540  * vnode -> parent directory, this needs the NAMECACHE_ENTER_REVERSE
541  * option to work (to make cache_revlookup succeed). Caller holds a
542  * reference to the vnode.
543  */
544 int
545 vnode_to_path(char *path, size_t len, struct vnode *vp, struct lwp *curl,
546     struct proc *p)
547 {
548 	struct proc *curp = curl->l_proc;
549 	int error, lenused, elen;
550 	char *bp, *bend;
551 	struct vnode *dvp;
552 
553 	KASSERT(vp->v_usecount > 0);
554 
555 	bp = bend = &path[len];
556 	*(--bp) = '\0';
557 
558 	error = vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
559 	if (error != 0)
560 		return error;
561 	error = cache_revlookup(vp, &dvp, &bp, path);
562 	VOP_UNLOCK(vp);
563 	if (error != 0)
564 		return (error == -1 ? ENOENT : error);
565 
566 	*(--bp) = '/';
567 	error = getcwd_common(dvp, NULL, &bp, path, len / 2,
568 	    GETCWD_CHECK_ACCESS, curl);
569 	vrele(dvp);
570 
571 	/*
572 	 * Strip off emulation path for emulated processes looking at
573 	 * the maps file of a process of the same emulation. (Won't
574 	 * work if /emul/xxx is a symlink..)
575 	 */
576 	if (curp->p_emul == p->p_emul && curp->p_emul->e_path != NULL) {
577 		elen = strlen(curp->p_emul->e_path);
578 		if (!strncmp(bp, curp->p_emul->e_path, elen))
579 			bp = &bp[elen];
580 	}
581 
582 	lenused = bend - bp;
583 
584 	memcpy(path, bp, lenused);
585 	path[lenused] = 0;
586 
587 	return 0;
588 }
589