xref: /netbsd-src/sys/kern/vfs_getcwd.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
1 /* $NetBSD: vfs_getcwd.c,v 1.46 2010/07/21 09:01:36 hannken 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.46 2010/07/21 09:01:36 hannken 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_pnbuf = NULL;
132 	cn.cn_nameptr = "..";
133 	cn.cn_namelen = 2;
134 	cn.cn_hash = 0;
135 	cn.cn_consume = 0;
136 
137 	/*
138 	 * At this point, lvp is locked.
139 	 * On successful return, *uvpp will be locked
140 	 */
141 	error = VOP_LOOKUP(lvp, uvpp, &cn);
142 	vput(lvp);
143 	if (error) {
144 		*lvpp = NULL;
145 		*uvpp = NULL;
146 		return error;
147 	}
148 	uvp = *uvpp;
149 
150 	/* If we don't care about the pathname, we're done */
151 	if (bufp == NULL) {
152 		*lvpp = NULL;
153 		return 0;
154 	}
155 
156 	fileno = va.va_fileid;
157 
158 	dirbuflen = DIRBLKSIZ;
159 	if (dirbuflen < va.va_blocksize)
160 		dirbuflen = va.va_blocksize;
161 	dirbuf = kmem_alloc(dirbuflen, KM_SLEEP);
162 
163 #if 0
164 unionread:
165 #endif
166 	off = 0;
167 	do {
168 		/* call VOP_READDIR of parent */
169 		iov.iov_base = dirbuf;
170 		iov.iov_len = dirbuflen;
171 
172 		uio.uio_iov = &iov;
173 		uio.uio_iovcnt = 1;
174 		uio.uio_offset = off;
175 		uio.uio_resid = dirbuflen;
176 		uio.uio_rw = UIO_READ;
177 		UIO_SETUP_SYSSPACE(&uio);
178 
179 		eofflag = 0;
180 
181 		error = VOP_READDIR(uvp, &uio, cred, &eofflag, 0, 0);
182 
183 		off = uio.uio_offset;
184 
185 		/*
186 		 * Try again if NFS tosses its cookies.
187 		 * XXX this can still loop forever if the directory is busted
188 		 * such that the second or subsequent page of it always
189 		 * returns EINVAL
190 		 */
191 		if ((error == EINVAL) && (tries < 3)) {
192 			off = 0;
193 			tries++;
194 			continue;	/* once more, with feeling */
195 		}
196 
197 		if (!error) {
198 			char   *cpos;
199 			struct dirent *dp;
200 
201 			cpos = dirbuf;
202 			tries = 0;
203 
204 			/* scan directory page looking for matching vnode */
205 			for (len = (dirbuflen - uio.uio_resid); len > 0;
206 			    len -= reclen) {
207 				dp = (struct dirent *) cpos;
208 				reclen = dp->d_reclen;
209 
210 				/* check for malformed directory.. */
211 				if (reclen < _DIRENT_MINSIZE(dp)) {
212 					error = EINVAL;
213 					goto out;
214 				}
215 				/*
216 				 * XXX should perhaps do VOP_LOOKUP to
217 				 * check that we got back to the right place,
218 				 * but getting the locking games for that
219 				 * right would be heinous.
220 				 */
221 				if ((dp->d_type != DT_WHT) &&
222 				    (dp->d_fileno == fileno)) {
223 					char *bp = *bpp;
224 
225 					bp -= dp->d_namlen;
226 					if (bp <= bufp) {
227 						error = ERANGE;
228 						goto out;
229 					}
230 					memcpy(bp, dp->d_name, dp->d_namlen);
231 					error = 0;
232 					*bpp = bp;
233 					goto out;
234 				}
235 				cpos += reclen;
236 			}
237 		} else
238 			goto out;
239 	} while (!eofflag);
240 #if 0
241 	/*
242 	 * Deal with mount -o union, which unions only the
243 	 * root directory of the mount.
244 	 */
245 	if ((uvp->v_vflag & VV_ROOT) &&
246 	    (uvp->v_mount->mnt_flag & MNT_UNION)) {
247 		struct vnode *tvp = uvp;
248 
249 		uvp = uvp->v_mount->mnt_vnodecovered;
250 		vput(tvp);
251 		vref(uvp);
252 		*uvpp = uvp;
253 		vn_lock(uvp, LK_EXCLUSIVE | LK_RETRY);
254 		goto unionread;
255 	}
256 #endif
257 	error = ENOENT;
258 
259 out:
260 	*lvpp = NULL;
261 	kmem_free(dirbuf, dirbuflen);
262 	return error;
263 }
264 
265 /*
266  * Look in the vnode-to-name reverse cache to see if
267  * we can find things the easy way.
268  *
269  * XXX vget failure path is untested.
270  *
271  * On entry, *lvpp is a locked vnode reference.
272  * On exit, one of the following is the case:
273  *	0) Both *lvpp and *uvpp are NULL and failure is returned.
274  * 	1) *uvpp is NULL, *lvpp remains locked and -1 is returned (cache miss)
275  *	2) *uvpp is a locked vnode reference, *lvpp is vput and NULL'ed
276  *	   and 0 is returned (cache hit)
277  */
278 
279 static int
280 getcwd_getcache(struct vnode **lvpp, struct vnode **uvpp, char **bpp,
281     char *bufp)
282 {
283 	struct vnode *lvp, *uvp = NULL;
284 	int error;
285 
286 	lvp = *lvpp;
287 
288 	/*
289 	 * This returns 0 on a cache hit, -1 on a clean cache miss,
290 	 * or an errno on other failure.
291 	 */
292 	error = cache_revlookup(lvp, uvpp, bpp, bufp);
293 	if (error) {
294 		if (error != -1) {
295 			vput(lvp);
296 			*lvpp = NULL;
297 			*uvpp = NULL;
298 		}
299 		return error;
300 	}
301 	uvp = *uvpp;
302 
303 	/*
304 	 * Since we're going up, we have to release the current lock
305 	 * before we take the parent lock.
306 	 */
307 
308 	VOP_UNLOCK(lvp);
309 	vn_lock(uvp, LK_EXCLUSIVE | LK_RETRY);
310 	vrele(lvp);
311 	*lvpp = NULL;
312 
313 	return error;
314 }
315 
316 /*
317  * common routine shared by sys___getcwd() and vn_isunder()
318  */
319 
320 int
321 getcwd_common(struct vnode *lvp, struct vnode *rvp, char **bpp, char *bufp,
322     int limit, int flags, struct lwp *l)
323 {
324 	struct cwdinfo *cwdi = l->l_proc->p_cwdi;
325 	kauth_cred_t cred = l->l_cred;
326 	struct vnode *uvp = NULL;
327 	char *bp = NULL;
328 	int error;
329 	int perms = VEXEC;
330 
331 	error = 0;
332 	if (rvp == NULL) {
333 		rvp = cwdi->cwdi_rdir;
334 		if (rvp == NULL)
335 			rvp = rootvnode;
336 	}
337 
338 	vref(rvp);
339 	vref(lvp);
340 
341 	/*
342 	 * Error handling invariant:
343 	 * Before a `goto out':
344 	 *	lvp is either NULL, or locked and held.
345 	 *	uvp is either NULL, or locked and held.
346 	 */
347 
348 	vn_lock(lvp, LK_EXCLUSIVE | LK_RETRY);
349 	if (bufp)
350 		bp = *bpp;
351 
352 	/*
353 	 * this loop will terminate when one of the following happens:
354 	 *	- we hit the root
355 	 *	- getdirentries or lookup fails
356 	 *	- we run out of space in the buffer.
357 	 */
358 	if (lvp == rvp) {
359 		if (bp)
360 			*(--bp) = '/';
361 		goto out;
362 	}
363 	do {
364 		/*
365 		 * access check here is optional, depending on
366 		 * whether or not caller cares.
367 		 */
368 		if (flags & GETCWD_CHECK_ACCESS) {
369 			error = VOP_ACCESS(lvp, perms, cred);
370 			if (error)
371 				goto out;
372 			perms = VEXEC|VREAD;
373 		}
374 
375 		/*
376 		 * step up if we're a covered vnode..
377 		 */
378 		while (lvp->v_vflag & VV_ROOT) {
379 			struct vnode *tvp;
380 
381 			if (lvp == rvp)
382 				goto out;
383 
384 			tvp = lvp;
385 			lvp = lvp->v_mount->mnt_vnodecovered;
386 			vput(tvp);
387 			/*
388 			 * hodie natus est radici frater
389 			 */
390 			if (lvp == NULL) {
391 				error = ENOENT;
392 				goto out;
393 			}
394 			vref(lvp);
395 			error = vn_lock(lvp, LK_EXCLUSIVE | LK_RETRY);
396 			if (error != 0) {
397 				vrele(lvp);
398 				lvp = NULL;
399 				goto out;
400 			}
401 		}
402 		/*
403 		 * Look in the name cache; if that fails, look in the
404 		 * directory..
405 		 */
406 		error = getcwd_getcache(&lvp, &uvp, &bp, bufp);
407 		if (error == -1) {
408 			if (lvp->v_type != VDIR) {
409 				error = ENOTDIR;
410 				goto out;
411 			}
412 			error = getcwd_scandir(&lvp, &uvp, &bp, bufp, l);
413 		}
414 		if (error)
415 			goto out;
416 #if DIAGNOSTIC
417 		if (lvp != NULL)
418 			panic("getcwd: oops, forgot to null lvp");
419 		if (bufp && (bp <= bufp)) {
420 			panic("getcwd: oops, went back too far");
421 		}
422 #endif
423 		if (bp)
424 			*(--bp) = '/';
425 		lvp = uvp;
426 		uvp = NULL;
427 		limit--;
428 	} while ((lvp != rvp) && (limit > 0));
429 
430 out:
431 	if (bpp)
432 		*bpp = bp;
433 	if (uvp)
434 		vput(uvp);
435 	if (lvp)
436 		vput(lvp);
437 	vrele(rvp);
438 	return error;
439 }
440 
441 /*
442  * Check if one directory can be found inside another in the directory
443  * hierarchy.
444  *
445  * Intended to be used in chroot, chdir, fchdir, etc., to ensure that
446  * chroot() actually means something.
447  */
448 int
449 vn_isunder(struct vnode *lvp, struct vnode *rvp, struct lwp *l)
450 {
451 	int error;
452 
453 	error = getcwd_common(lvp, rvp, NULL, NULL, MAXPATHLEN / 2, 0, l);
454 
455 	if (!error)
456 		return 1;
457 	else
458 		return 0;
459 }
460 
461 /*
462  * Returns true if proc p1's root directory equal to or under p2's
463  * root directory.
464  *
465  * Intended to be used from ptrace/procfs sorts of things.
466  */
467 
468 int
469 proc_isunder(struct proc *p1, struct lwp *l2)
470 {
471 	struct vnode *r1 = p1->p_cwdi->cwdi_rdir;
472 	struct vnode *r2 = l2->l_proc->p_cwdi->cwdi_rdir;
473 
474 	if (r1 == NULL)
475 		return (r2 == NULL);
476 	else if (r2 == NULL)
477 		return 1;
478 	else
479 		return vn_isunder(r1, r2, l2);
480 }
481 
482 /*
483  * Find pathname of process's current directory.
484  *
485  * Use vfs vnode-to-name reverse cache; if that fails, fall back
486  * to reading directory contents.
487  */
488 
489 int
490 sys___getcwd(struct lwp *l, const struct sys___getcwd_args *uap, register_t *retval)
491 {
492 	/* {
493 		syscallarg(char *) bufp;
494 		syscallarg(size_t) length;
495 	} */
496 
497 	int     error;
498 	char   *path;
499 	char   *bp, *bend;
500 	int     len = SCARG(uap, length);
501 	int	lenused;
502 	struct	cwdinfo *cwdi;
503 
504 	if (len > MAXPATHLEN * 4)
505 		len = MAXPATHLEN * 4;
506 	else if (len < 2)
507 		return ERANGE;
508 
509 	path = kmem_alloc(len, KM_SLEEP);
510 	if (!path)
511 		return ENOMEM;
512 
513 	bp = &path[len];
514 	bend = bp;
515 	*(--bp) = '\0';
516 
517 	/*
518 	 * 5th argument here is "max number of vnodes to traverse".
519 	 * Since each entry takes up at least 2 bytes in the output buffer,
520 	 * limit it to N/2 vnodes for an N byte buffer.
521 	 */
522 	cwdi = l->l_proc->p_cwdi;
523 	rw_enter(&cwdi->cwdi_lock, RW_READER);
524 	error = getcwd_common(cwdi->cwdi_cdir, NULL, &bp, path,
525 	    len/2, GETCWD_CHECK_ACCESS, l);
526 	rw_exit(&cwdi->cwdi_lock);
527 
528 	if (error)
529 		goto out;
530 	lenused = bend - bp;
531 	*retval = lenused;
532 	/* put the result into user buffer */
533 	error = copyout(bp, SCARG(uap, bufp), lenused);
534 
535 out:
536 	kmem_free(path, len);
537 	return error;
538 }
539 
540 /*
541  * Try to find a pathname for a vnode. Since there is no mapping
542  * vnode -> parent directory, this needs the NAMECACHE_ENTER_REVERSE
543  * option to work (to make cache_revlookup succeed). Caller holds a
544  * reference to the vnode.
545  */
546 int
547 vnode_to_path(char *path, size_t len, struct vnode *vp, struct lwp *curl,
548     struct proc *p)
549 {
550 	struct proc *curp = curl->l_proc;
551 	int error, lenused, elen;
552 	char *bp, *bend;
553 	struct vnode *dvp;
554 
555 	KASSERT(vp->v_usecount > 0);
556 
557 	bp = bend = &path[len];
558 	*(--bp) = '\0';
559 
560 	error = vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
561 	if (error != 0)
562 		return error;
563 	error = cache_revlookup(vp, &dvp, &bp, path);
564 	VOP_UNLOCK(vp);
565 	if (error != 0)
566 		return (error == -1 ? ENOENT : error);
567 
568 	*(--bp) = '/';
569 	error = getcwd_common(dvp, NULL, &bp, path, len / 2,
570 	    GETCWD_CHECK_ACCESS, curl);
571 	vrele(dvp);
572 
573 	/*
574 	 * Strip off emulation path for emulated processes looking at
575 	 * the maps file of a process of the same emulation. (Won't
576 	 * work if /emul/xxx is a symlink..)
577 	 */
578 	if (curp->p_emul == p->p_emul && curp->p_emul->e_path != NULL) {
579 		elen = strlen(curp->p_emul->e_path);
580 		if (!strncmp(bp, curp->p_emul->e_path, elen))
581 			bp = &bp[elen];
582 	}
583 
584 	lenused = bend - bp;
585 
586 	memcpy(path, bp, lenused);
587 	path[lenused] = 0;
588 
589 	return 0;
590 }
591