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