1 /*-
2  * Copyright (c) 1989, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley
6  * by Pace Willisson (pace@blitz.com).  The Rock Ridge Extension
7  * Support code is derived from software contributed to Berkeley
8  * by Atsushi Murai (amurai@spec.co.jp).
9  *
10  * %sccs.include.redist.c%
11  *
12  *	from: @(#)ufs_lookup.c	7.33 (Berkeley) 5/19/91
13  *
14  *	@(#)cd9660_lookup.c	8.6 (Berkeley) 05/14/95
15  */
16 
17 #include <sys/param.h>
18 #include <sys/namei.h>
19 #include <sys/buf.h>
20 #include <sys/file.h>
21 #include <sys/vnode.h>
22 #include <sys/mount.h>
23 
24 #include <isofs/cd9660/iso.h>
25 #include <isofs/cd9660/cd9660_node.h>
26 #include <isofs/cd9660/iso_rrip.h>
27 #include <isofs/cd9660/cd9660_rrip.h>
28 
29 struct	nchstats iso_nchstats;
30 
31 /*
32  * Convert a component of a pathname into a pointer to a locked inode.
33  * This is a very central and rather complicated routine.
34  * If the file system is not maintained in a strict tree hierarchy,
35  * this can result in a deadlock situation (see comments in code below).
36  *
37  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
38  * whether the name is to be looked up, created, renamed, or deleted.
39  * When CREATE, RENAME, or DELETE is specified, information usable in
40  * creating, renaming, or deleting a directory entry may be calculated.
41  * If flag has LOCKPARENT or'ed into it and the target of the pathname
42  * exists, lookup returns both the target and its parent directory locked.
43  * When creating or renaming and LOCKPARENT is specified, the target may
44  * not be ".".  When deleting and LOCKPARENT is specified, the target may
45  * be "."., but the caller must check to ensure it does an vrele and iput
46  * instead of two iputs.
47  *
48  * Overall outline of ufs_lookup:
49  *
50  *	check accessibility of directory
51  *	look for name in cache, if found, then if at end of path
52  *	  and deleting or creating, drop it, else return name
53  *	search for name in directory, to found or notfound
54  * notfound:
55  *	if creating, return locked directory, leaving info on available slots
56  *	else return error
57  * found:
58  *	if at end of path and deleting, return information to allow delete
59  *	if at end of path and rewriting (RENAME and LOCKPARENT), lock target
60  *	  inode and return info to allow rewrite
61  *	if not at end, add name to cache; if at end and neither creating
62  *	  nor deleting, add name to cache
63  *
64  * NOTE: (LOOKUP | LOCKPARENT) currently returns the parent inode unlocked.
65  */
66 cd9660_lookup(ap)
67 	struct vop_lookup_args /* {
68 		struct vnode *a_dvp;
69 		struct vnode **a_vpp;
70 		struct componentname *a_cnp;
71 	} */ *ap;
72 {
73 	register struct vnode *vdp;	/* vnode for directory being searched */
74 	register struct iso_node *dp;	/* inode for directory being searched */
75 	register struct iso_mnt *imp;	/* file system that directory is in */
76 	struct buf *bp;			/* a buffer of directory entries */
77 	struct iso_directory_record *ep;/* the current directory entry */
78 	int entryoffsetinblock;		/* offset of ep in bp's buffer */
79 	int saveoffset;			/* offset of last directory entry in dir */
80 	int numdirpasses;		/* strategy for directory search */
81 	doff_t endsearch;		/* offset to end directory search */
82 	struct vnode *pdp;		/* saved dp during symlink work */
83 	struct vnode *tdp;		/* returned by cd9660_vget_internal */
84 	u_long bmask;			/* block offset mask */
85 	int lockparent;			/* 1 => lockparent flag is set */
86 	int wantparent;			/* 1 => wantparent or lockparent flag */
87 	int error;
88 	ino_t ino = 0;
89 	int reclen;
90 	u_short namelen;
91 	char altname[NAME_MAX];
92 	int res;
93 	int assoc, len;
94 	char *name;
95 	struct vnode **vpp = ap->a_vpp;
96 	struct componentname *cnp = ap->a_cnp;
97 	struct ucred *cred = cnp->cn_cred;
98 	int flags = cnp->cn_flags;
99 	int nameiop = cnp->cn_nameiop;
100 	struct proc *p = cnp->cn_proc;
101 
102 	bp = NULL;
103 	*vpp = NULL;
104 	vdp = ap->a_dvp;
105 	dp = VTOI(vdp);
106 	imp = dp->i_mnt;
107 	lockparent = flags & LOCKPARENT;
108 	wantparent = flags & (LOCKPARENT|WANTPARENT);
109 
110 	/*
111 	 * Check accessiblity of directory.
112 	 */
113 	if (vdp->v_type != VDIR)
114 		return (ENOTDIR);
115 	if (error = VOP_ACCESS(vdp, VEXEC, cred, cnp->cn_proc))
116 		return (error);
117 
118 	/*
119 	 * We now have a segment name to search for, and a directory to search.
120 	 *
121 	 * Before tediously performing a linear scan of the directory,
122 	 * check the name cache to see if the directory/name pair
123 	 * we are looking for is known already.
124 	 */
125 	if (error = cache_lookup(vdp, vpp, cnp)) {
126 		int vpid;	/* capability number of vnode */
127 
128 		if (error == ENOENT)
129 			return (error);
130 #ifdef PARANOID
131 		if ((vdp->v_flag & VROOT) && (flags & ISDOTDOT))
132 			panic("cd9660_lookup: .. through root");
133 #endif
134 		/*
135 		 * Get the next vnode in the path.
136 		 * See comment below starting `Step through' for
137 		 * an explaination of the locking protocol.
138 		 */
139 		pdp = vdp;
140 		dp = VTOI(*vpp);
141 		vdp = *vpp;
142 		vpid = vdp->v_id;
143 		if (pdp == vdp) {
144 			VREF(vdp);
145 			error = 0;
146 		} else if (flags & ISDOTDOT) {
147 			VOP_UNLOCK(pdp, 0, p);
148 			error = vget(vdp, LK_EXCLUSIVE, p);
149 			if (!error && lockparent && (flags & ISLASTCN))
150 				error = vn_lock(pdp, LK_EXCLUSIVE, p);
151 		} else {
152 			error = vget(vdp, LK_EXCLUSIVE, p);
153 			if (!lockparent || error || !(flags & ISLASTCN))
154 				VOP_UNLOCK(pdp, 0, p);
155 		}
156 		/*
157 		 * Check that the capability number did not change
158 		 * while we were waiting for the lock.
159 		 */
160 		if (!error) {
161 			if (vpid == vdp->v_id)
162 				return (0);
163 			vput(vdp);
164 			if (lockparent && pdp != vdp && (flags & ISLASTCN))
165 				VOP_UNLOCK(pdp, 0, p);
166 		}
167 		if (error = vn_lock(pdp, LK_EXCLUSIVE, p))
168 			return (error);
169 		vdp = pdp;
170 		dp = VTOI(pdp);
171 		*vpp = NULL;
172 	}
173 
174 	len = cnp->cn_namelen;
175 	name = cnp->cn_nameptr;
176 	/*
177 	 * A leading `=' means, we are looking for an associated file
178 	 */
179 	if (assoc = (imp->iso_ftype != ISO_FTYPE_RRIP && *name == ASSOCCHAR)) {
180 		len--;
181 		name++;
182 	}
183 
184 	/*
185 	 * If there is cached information on a previous search of
186 	 * this directory, pick up where we last left off.
187 	 * We cache only lookups as these are the most common
188 	 * and have the greatest payoff. Caching CREATE has little
189 	 * benefit as it usually must search the entire directory
190 	 * to determine that the entry does not exist. Caching the
191 	 * location of the last DELETE or RENAME has not reduced
192 	 * profiling time and hence has been removed in the interest
193 	 * of simplicity.
194 	 */
195 	bmask = imp->im_bmask;
196 	if (nameiop != LOOKUP || dp->i_diroff == 0 ||
197 	    dp->i_diroff > dp->i_size) {
198 		entryoffsetinblock = 0;
199 		dp->i_offset = 0;
200 		numdirpasses = 1;
201 	} else {
202 		dp->i_offset = dp->i_diroff;
203 		if ((entryoffsetinblock = dp->i_offset & bmask) &&
204 		    (error = VOP_BLKATOFF(vdp, (off_t)dp->i_offset, NULL, &bp)))
205 				return (error);
206 		numdirpasses = 2;
207 		iso_nchstats.ncs_2passes++;
208 	}
209 	endsearch = dp->i_size;
210 
211 searchloop:
212 	while (dp->i_offset < endsearch) {
213 		/*
214 		 * If offset is on a block boundary,
215 		 * read the next directory block.
216 		 * Release previous if it exists.
217 		 */
218 		if ((dp->i_offset & bmask) == 0) {
219 			if (bp != NULL)
220 				brelse(bp);
221 			if (error =
222 			    VOP_BLKATOFF(vdp, (off_t)dp->i_offset, NULL, &bp))
223 				return (error);
224 			entryoffsetinblock = 0;
225 		}
226 		/*
227 		 * Get pointer to next entry.
228 		 */
229 		ep = (struct iso_directory_record *)
230 			((char *)bp->b_data + entryoffsetinblock);
231 
232 		reclen = isonum_711(ep->length);
233 		if (reclen == 0) {
234 			/* skip to next block, if any */
235 			dp->i_offset =
236 			    (dp->i_offset & ~bmask) + imp->logical_block_size;
237 			continue;
238 		}
239 
240 		if (reclen < ISO_DIRECTORY_RECORD_SIZE)
241 			/* illegal entry, stop */
242 			break;
243 
244 		if (entryoffsetinblock + reclen > imp->logical_block_size)
245 			/* entries are not allowed to cross boundaries */
246 			break;
247 
248 		namelen = isonum_711(ep->name_len);
249 
250 		if (reclen < ISO_DIRECTORY_RECORD_SIZE + namelen)
251 			/* illegal entry, stop */
252 			break;
253 
254 		/*
255 		 * Check for a name match.
256 		 */
257 		switch (imp->iso_ftype) {
258 		default:
259 			if ((!(isonum_711(ep->flags)&4)) == !assoc) {
260 				if ((len == 1
261 				     && *name == '.')
262 				    || (flags & ISDOTDOT)) {
263 					if (namelen == 1
264 					    && ep->name[0] == ((flags & ISDOTDOT) ? 1 : 0)) {
265 						/*
266 						 * Save directory entry's inode number and
267 						 * release directory buffer.
268 						 */
269 						dp->i_ino = isodirino(ep, imp);
270 						goto found;
271 					}
272 					if (namelen != 1
273 					    || ep->name[0] != 0)
274 						goto notfound;
275 				} else if (!(res = isofncmp(name,len,
276 							    ep->name,namelen))) {
277 					if (isonum_711(ep->flags)&2)
278 						ino = isodirino(ep, imp);
279 					else
280 						ino = dbtob(bp->b_blkno)
281 							+ entryoffsetinblock;
282 					saveoffset = dp->i_offset;
283 				} else if (ino)
284 					goto foundino;
285 #ifdef	NOSORTBUG	/* On some CDs directory entries are not sorted correctly */
286 				else if (res < 0)
287 					goto notfound;
288 				else if (res > 0 && numdirpasses == 2)
289 					numdirpasses++;
290 #endif
291 			}
292 			break;
293 		case ISO_FTYPE_RRIP:
294 			if (isonum_711(ep->flags)&2)
295 				ino = isodirino(ep, imp);
296 			else
297 				ino = dbtob(bp->b_blkno) + entryoffsetinblock;
298 			dp->i_ino = ino;
299 			cd9660_rrip_getname(ep,altname,&namelen,&dp->i_ino,imp);
300 			if (namelen == cnp->cn_namelen
301 			    && !bcmp(name,altname,namelen))
302 				goto found;
303 			ino = 0;
304 			break;
305 		}
306 		dp->i_offset += reclen;
307 		entryoffsetinblock += reclen;
308 	}
309 	if (ino) {
310 foundino:
311 		dp->i_ino = ino;
312 		if (saveoffset != dp->i_offset) {
313 			if (lblkno(imp, dp->i_offset) !=
314 			    lblkno(imp, saveoffset)) {
315 				if (bp != NULL)
316 					brelse(bp);
317 				if (error = VOP_BLKATOFF(vdp,
318 				    (off_t)saveoffset, NULL, &bp))
319 					return (error);
320 			}
321 			entryoffsetinblock = saveoffset & bmask;
322 			ep = (struct iso_directory_record *)
323 				((char *)bp->b_data + entryoffsetinblock);
324 			dp->i_offset = saveoffset;
325 		}
326 		goto found;
327 	}
328 notfound:
329 	/*
330 	 * If we started in the middle of the directory and failed
331 	 * to find our target, we must check the beginning as well.
332 	 */
333 	if (numdirpasses == 2) {
334 		numdirpasses--;
335 		dp->i_offset = 0;
336 		endsearch = dp->i_diroff;
337 		goto searchloop;
338 	}
339 	if (bp != NULL)
340 		brelse(bp);
341 
342 	/*
343 	 * Insert name into cache (as non-existent) if appropriate.
344 	 */
345 	if (cnp->cn_flags & MAKEENTRY)
346 		cache_enter(vdp, *vpp, cnp);
347 	if (nameiop == CREATE || nameiop == RENAME)
348 		return (EJUSTRETURN);
349 	return (ENOENT);
350 
351 found:
352 	if (numdirpasses == 2)
353 		iso_nchstats.ncs_pass2++;
354 
355 	/*
356 	 * Found component in pathname.
357 	 * If the final component of path name, save information
358 	 * in the cache as to where the entry was found.
359 	 */
360 	if ((flags & ISLASTCN) && nameiop == LOOKUP)
361 		dp->i_diroff = dp->i_offset;
362 
363 	/*
364 	 * Step through the translation in the name.  We do not `iput' the
365 	 * directory because we may need it again if a symbolic link
366 	 * is relative to the current directory.  Instead we save it
367 	 * unlocked as "pdp".  We must get the target inode before unlocking
368 	 * the directory to insure that the inode will not be removed
369 	 * before we get it.  We prevent deadlock by always fetching
370 	 * inodes from the root, moving down the directory tree. Thus
371 	 * when following backward pointers ".." we must unlock the
372 	 * parent directory before getting the requested directory.
373 	 * There is a potential race condition here if both the current
374 	 * and parent directories are removed before the `iget' for the
375 	 * inode associated with ".." returns.  We hope that this occurs
376 	 * infrequently since we cannot avoid this race condition without
377 	 * implementing a sophisticated deadlock detection algorithm.
378 	 * Note also that this simple deadlock detection scheme will not
379 	 * work if the file system has any hard links other than ".."
380 	 * that point backwards in the directory structure.
381 	 */
382 	pdp = vdp;
383 	/*
384 	 * If ino is different from dp->i_ino,
385 	 * it's a relocated directory.
386 	 */
387 	if (flags & ISDOTDOT) {
388 		VOP_UNLOCK(pdp, 0, p);	/* race to get the inode */
389 		error = cd9660_vget_internal(vdp->v_mount, dp->i_ino, &tdp,
390 					     dp->i_ino != ino, ep);
391 		brelse(bp);
392 		if (error) {
393 			vn_lock(pdp, LK_EXCLUSIVE | LK_RETRY, p);
394 			return (error);
395 		}
396 		if (lockparent && (flags & ISLASTCN) &&
397 		    (error = vn_lock(pdp, LK_EXCLUSIVE, p))) {
398 			vput(tdp);
399 			return (error);
400 		}
401 		*vpp = tdp;
402 	} else if (dp->i_number == dp->i_ino) {
403 		brelse(bp);
404 		VREF(vdp);	/* we want ourself, ie "." */
405 		*vpp = vdp;
406 	} else {
407 		error = cd9660_vget_internal(vdp->v_mount, dp->i_ino, &tdp,
408 					     dp->i_ino != ino, ep);
409 		brelse(bp);
410 		if (error)
411 			return (error);
412 		if (!lockparent || !(flags & ISLASTCN))
413 			VOP_UNLOCK(pdp, 0, p);
414 		*vpp = tdp;
415 	}
416 
417 	/*
418 	 * Insert name into cache if appropriate.
419 	 */
420 	if (cnp->cn_flags & MAKEENTRY)
421 		cache_enter(vdp, *vpp, cnp);
422 	return (0);
423 }
424 
425 /*
426  * Return buffer with the contents of block "offset" from the beginning of
427  * directory "ip".  If "res" is non-zero, fill it in with a pointer to the
428  * remaining space in the directory.
429  */
430 int
431 cd9660_blkatoff(ap)
432 	struct vop_blkatoff_args /* {
433 		struct vnode *a_vp;
434 		off_t a_offset;
435 		char **a_res;
436 		struct buf **a_bpp;
437 	} */ *ap;
438 {
439 	struct iso_node *ip;
440 	register struct iso_mnt *imp;
441 	struct buf *bp;
442 	daddr_t lbn;
443 	int bsize, error;
444 
445 	ip = VTOI(ap->a_vp);
446 	imp = ip->i_mnt;
447 	lbn = lblkno(imp, ap->a_offset);
448 	bsize = blksize(imp, ip, lbn);
449 
450 	if (error = bread(ap->a_vp, lbn, bsize, NOCRED, &bp)) {
451 		brelse(bp);
452 		*ap->a_bpp = NULL;
453 		return (error);
454 	}
455 	if (ap->a_res)
456 		*ap->a_res = (char *)bp->b_data + blkoff(imp, ap->a_offset);
457 	*ap->a_bpp = bp;
458 	return (0);
459 }
460