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.5 (Berkeley) 12/05/94
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 
101 	bp = NULL;
102 	*vpp = NULL;
103 	vdp = ap->a_dvp;
104 	dp = VTOI(vdp);
105 	imp = dp->i_mnt;
106 	lockparent = flags & LOCKPARENT;
107 	wantparent = flags & (LOCKPARENT|WANTPARENT);
108 
109 	/*
110 	 * Check accessiblity of directory.
111 	 */
112 	if (vdp->v_type != VDIR)
113 		return (ENOTDIR);
114 	if (error = VOP_ACCESS(vdp, VEXEC, cred, cnp->cn_proc))
115 		return (error);
116 
117 	/*
118 	 * We now have a segment name to search for, and a directory to search.
119 	 *
120 	 * Before tediously performing a linear scan of the directory,
121 	 * check the name cache to see if the directory/name pair
122 	 * we are looking for is known already.
123 	 */
124 	if (error = cache_lookup(vdp, vpp, cnp)) {
125 		int vpid;	/* capability number of vnode */
126 
127 		if (error == ENOENT)
128 			return (error);
129 #ifdef PARANOID
130 		if ((vdp->v_flag & VROOT) && (flags & ISDOTDOT))
131 			panic("cd9660_lookup: .. through root");
132 #endif
133 		/*
134 		 * Get the next vnode in the path.
135 		 * See comment below starting `Step through' for
136 		 * an explaination of the locking protocol.
137 		 */
138 		pdp = vdp;
139 		dp = VTOI(*vpp);
140 		vdp = *vpp;
141 		vpid = vdp->v_id;
142 		if (pdp == vdp) {
143 			VREF(vdp);
144 			error = 0;
145 		} else if (flags & ISDOTDOT) {
146 			VOP_UNLOCK(pdp);
147 			error = vget(vdp, 1);
148 			if (!error && lockparent && (flags & ISLASTCN))
149 				error = VOP_LOCK(pdp);
150 		} else {
151 			error = vget(vdp, 1);
152 			if (!lockparent || error || !(flags & ISLASTCN))
153 				VOP_UNLOCK(pdp);
154 		}
155 		/*
156 		 * Check that the capability number did not change
157 		 * while we were waiting for the lock.
158 		 */
159 		if (!error) {
160 			if (vpid == vdp->v_id)
161 				return (0);
162 			vput(vdp);
163 			if (lockparent && pdp != vdp && (flags & ISLASTCN))
164 				VOP_UNLOCK(pdp);
165 		}
166 		if (error = VOP_LOCK(pdp))
167 			return (error);
168 		vdp = pdp;
169 		dp = VTOI(pdp);
170 		*vpp = NULL;
171 	}
172 
173 	len = cnp->cn_namelen;
174 	name = cnp->cn_nameptr;
175 	/*
176 	 * A leading `=' means, we are looking for an associated file
177 	 */
178 	if (assoc = (imp->iso_ftype != ISO_FTYPE_RRIP && *name == ASSOCCHAR)) {
179 		len--;
180 		name++;
181 	}
182 
183 	/*
184 	 * If there is cached information on a previous search of
185 	 * this directory, pick up where we last left off.
186 	 * We cache only lookups as these are the most common
187 	 * and have the greatest payoff. Caching CREATE has little
188 	 * benefit as it usually must search the entire directory
189 	 * to determine that the entry does not exist. Caching the
190 	 * location of the last DELETE or RENAME has not reduced
191 	 * profiling time and hence has been removed in the interest
192 	 * of simplicity.
193 	 */
194 	bmask = imp->im_bmask;
195 	if (nameiop != LOOKUP || dp->i_diroff == 0 ||
196 	    dp->i_diroff > dp->i_size) {
197 		entryoffsetinblock = 0;
198 		dp->i_offset = 0;
199 		numdirpasses = 1;
200 	} else {
201 		dp->i_offset = dp->i_diroff;
202 		if ((entryoffsetinblock = dp->i_offset & bmask) &&
203 		    (error = VOP_BLKATOFF(vdp, (off_t)dp->i_offset, NULL, &bp)))
204 				return (error);
205 		numdirpasses = 2;
206 		iso_nchstats.ncs_2passes++;
207 	}
208 	endsearch = dp->i_size;
209 
210 searchloop:
211 	while (dp->i_offset < endsearch) {
212 		/*
213 		 * If offset is on a block boundary,
214 		 * read the next directory block.
215 		 * Release previous if it exists.
216 		 */
217 		if ((dp->i_offset & bmask) == 0) {
218 			if (bp != NULL)
219 				brelse(bp);
220 			if (error =
221 			    VOP_BLKATOFF(vdp, (off_t)dp->i_offset, NULL, &bp))
222 				return (error);
223 			entryoffsetinblock = 0;
224 		}
225 		/*
226 		 * Get pointer to next entry.
227 		 */
228 		ep = (struct iso_directory_record *)
229 			((char *)bp->b_data + entryoffsetinblock);
230 
231 		reclen = isonum_711(ep->length);
232 		if (reclen == 0) {
233 			/* skip to next block, if any */
234 			dp->i_offset =
235 			    (dp->i_offset & ~bmask) + imp->logical_block_size;
236 			continue;
237 		}
238 
239 		if (reclen < ISO_DIRECTORY_RECORD_SIZE)
240 			/* illegal entry, stop */
241 			break;
242 
243 		if (entryoffsetinblock + reclen > imp->logical_block_size)
244 			/* entries are not allowed to cross boundaries */
245 			break;
246 
247 		namelen = isonum_711(ep->name_len);
248 
249 		if (reclen < ISO_DIRECTORY_RECORD_SIZE + namelen)
250 			/* illegal entry, stop */
251 			break;
252 
253 		/*
254 		 * Check for a name match.
255 		 */
256 		switch (imp->iso_ftype) {
257 		default:
258 			if ((!(isonum_711(ep->flags)&4)) == !assoc) {
259 				if ((len == 1
260 				     && *name == '.')
261 				    || (flags & ISDOTDOT)) {
262 					if (namelen == 1
263 					    && ep->name[0] == ((flags & ISDOTDOT) ? 1 : 0)) {
264 						/*
265 						 * Save directory entry's inode number and
266 						 * release directory buffer.
267 						 */
268 						dp->i_ino = isodirino(ep, imp);
269 						goto found;
270 					}
271 					if (namelen != 1
272 					    || ep->name[0] != 0)
273 						goto notfound;
274 				} else if (!(res = isofncmp(name,len,
275 							    ep->name,namelen))) {
276 					if (isonum_711(ep->flags)&2)
277 						ino = isodirino(ep, imp);
278 					else
279 						ino = dbtob(bp->b_blkno)
280 							+ entryoffsetinblock;
281 					saveoffset = dp->i_offset;
282 				} else if (ino)
283 					goto foundino;
284 #ifdef	NOSORTBUG	/* On some CDs directory entries are not sorted correctly */
285 				else if (res < 0)
286 					goto notfound;
287 				else if (res > 0 && numdirpasses == 2)
288 					numdirpasses++;
289 #endif
290 			}
291 			break;
292 		case ISO_FTYPE_RRIP:
293 			if (isonum_711(ep->flags)&2)
294 				ino = isodirino(ep, imp);
295 			else
296 				ino = dbtob(bp->b_blkno) + entryoffsetinblock;
297 			dp->i_ino = ino;
298 			cd9660_rrip_getname(ep,altname,&namelen,&dp->i_ino,imp);
299 			if (namelen == cnp->cn_namelen
300 			    && !bcmp(name,altname,namelen))
301 				goto found;
302 			ino = 0;
303 			break;
304 		}
305 		dp->i_offset += reclen;
306 		entryoffsetinblock += reclen;
307 	}
308 	if (ino) {
309 foundino:
310 		dp->i_ino = ino;
311 		if (saveoffset != dp->i_offset) {
312 			if (lblkno(imp, dp->i_offset) !=
313 			    lblkno(imp, saveoffset)) {
314 				if (bp != NULL)
315 					brelse(bp);
316 				if (error = VOP_BLKATOFF(vdp,
317 				    (off_t)saveoffset, NULL, &bp))
318 					return (error);
319 			}
320 			entryoffsetinblock = saveoffset & bmask;
321 			ep = (struct iso_directory_record *)
322 				((char *)bp->b_data + entryoffsetinblock);
323 			dp->i_offset = saveoffset;
324 		}
325 		goto found;
326 	}
327 notfound:
328 	/*
329 	 * If we started in the middle of the directory and failed
330 	 * to find our target, we must check the beginning as well.
331 	 */
332 	if (numdirpasses == 2) {
333 		numdirpasses--;
334 		dp->i_offset = 0;
335 		endsearch = dp->i_diroff;
336 		goto searchloop;
337 	}
338 	if (bp != NULL)
339 		brelse(bp);
340 
341 	/*
342 	 * Insert name into cache (as non-existent) if appropriate.
343 	 */
344 	if (cnp->cn_flags & MAKEENTRY)
345 		cache_enter(vdp, *vpp, cnp);
346 	if (nameiop == CREATE || nameiop == RENAME)
347 		return (EJUSTRETURN);
348 	return (ENOENT);
349 
350 found:
351 	if (numdirpasses == 2)
352 		iso_nchstats.ncs_pass2++;
353 
354 	/*
355 	 * Found component in pathname.
356 	 * If the final component of path name, save information
357 	 * in the cache as to where the entry was found.
358 	 */
359 	if ((flags & ISLASTCN) && nameiop == LOOKUP)
360 		dp->i_diroff = dp->i_offset;
361 
362 	/*
363 	 * Step through the translation in the name.  We do not `iput' the
364 	 * directory because we may need it again if a symbolic link
365 	 * is relative to the current directory.  Instead we save it
366 	 * unlocked as "pdp".  We must get the target inode before unlocking
367 	 * the directory to insure that the inode will not be removed
368 	 * before we get it.  We prevent deadlock by always fetching
369 	 * inodes from the root, moving down the directory tree. Thus
370 	 * when following backward pointers ".." we must unlock the
371 	 * parent directory before getting the requested directory.
372 	 * There is a potential race condition here if both the current
373 	 * and parent directories are removed before the `iget' for the
374 	 * inode associated with ".." returns.  We hope that this occurs
375 	 * infrequently since we cannot avoid this race condition without
376 	 * implementing a sophisticated deadlock detection algorithm.
377 	 * Note also that this simple deadlock detection scheme will not
378 	 * work if the file system has any hard links other than ".."
379 	 * that point backwards in the directory structure.
380 	 */
381 	pdp = vdp;
382 	/*
383 	 * If ino is different from dp->i_ino,
384 	 * it's a relocated directory.
385 	 */
386 	if (flags & ISDOTDOT) {
387 		VOP_UNLOCK(pdp);	/* race to get the inode */
388 		error = cd9660_vget_internal(vdp->v_mount, dp->i_ino, &tdp,
389 					     dp->i_ino != ino, ep);
390 		brelse(bp);
391 		if (error) {
392 			VOP_LOCK(pdp);
393 			return (error);
394 		}
395 		if (lockparent && (flags & ISLASTCN) &&
396 		    (error = VOP_LOCK(pdp))) {
397 			vput(tdp);
398 			return (error);
399 		}
400 		*vpp = tdp;
401 	} else if (dp->i_number == dp->i_ino) {
402 		brelse(bp);
403 		VREF(vdp);	/* we want ourself, ie "." */
404 		*vpp = vdp;
405 	} else {
406 		error = cd9660_vget_internal(vdp->v_mount, dp->i_ino, &tdp,
407 					     dp->i_ino != ino, ep);
408 		brelse(bp);
409 		if (error)
410 			return (error);
411 		if (!lockparent || !(flags & ISLASTCN))
412 			VOP_UNLOCK(pdp);
413 		*vpp = tdp;
414 	}
415 
416 	/*
417 	 * Insert name into cache if appropriate.
418 	 */
419 	if (cnp->cn_flags & MAKEENTRY)
420 		cache_enter(vdp, *vpp, cnp);
421 	return (0);
422 }
423 
424 /*
425  * Return buffer with the contents of block "offset" from the beginning of
426  * directory "ip".  If "res" is non-zero, fill it in with a pointer to the
427  * remaining space in the directory.
428  */
429 int
430 cd9660_blkatoff(ap)
431 	struct vop_blkatoff_args /* {
432 		struct vnode *a_vp;
433 		off_t a_offset;
434 		char **a_res;
435 		struct buf **a_bpp;
436 	} */ *ap;
437 {
438 	struct iso_node *ip;
439 	register struct iso_mnt *imp;
440 	struct buf *bp;
441 	daddr_t lbn;
442 	int bsize, error;
443 
444 	ip = VTOI(ap->a_vp);
445 	imp = ip->i_mnt;
446 	lbn = lblkno(imp, ap->a_offset);
447 	bsize = blksize(imp, ip, lbn);
448 
449 	if (error = bread(ap->a_vp, lbn, bsize, NOCRED, &bp)) {
450 		brelse(bp);
451 		*ap->a_bpp = NULL;
452 		return (error);
453 	}
454 	if (ap->a_res)
455 		*ap->a_res = (char *)bp->b_data + blkoff(imp, ap->a_offset);
456 	*ap->a_bpp = bp;
457 	return (0);
458 }
459