xref: /freebsd/sys/fs/cd9660/cd9660_lookup.c (revision 8ab2f5ecc596131f6ca790d6ae35540c06ed7985)
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  * 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  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	from: @(#)ufs_lookup.c	7.33 (Berkeley) 5/19/91
35  *	@(#)cd9660_lookup.c	8.2 (Berkeley) 1/23/94
36  */
37 
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/namei.h>
44 #include <sys/bio.h>
45 #include <sys/buf.h>
46 #include <sys/vnode.h>
47 #include <sys/mount.h>
48 
49 #include <isofs/cd9660/iso.h>
50 #include <isofs/cd9660/cd9660_node.h>
51 #include <isofs/cd9660/iso_rrip.h>
52 
53 /*
54  * Convert a component of a pathname into a pointer to a locked inode.
55  * This is a very central and rather complicated routine.
56  * If the filesystem is not maintained in a strict tree hierarchy,
57  * this can result in a deadlock situation (see comments in code below).
58  *
59  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
60  * whether the name is to be looked up, created, renamed, or deleted.
61  * When CREATE, RENAME, or DELETE is specified, information usable in
62  * creating, renaming, or deleting a directory entry may be calculated.
63  * If flag has LOCKPARENT or'ed into it and the target of the pathname
64  * exists, lookup returns both the target and its parent directory locked.
65  * When creating or renaming and LOCKPARENT is specified, the target may
66  * not be ".".  When deleting and LOCKPARENT is specified, the target may
67  * be "."., but the caller must check to ensure it does an vrele and iput
68  * instead of two iputs.
69  *
70  * Overall outline of ufs_lookup:
71  *
72  *	search for name in directory, to found or notfound
73  * notfound:
74  *	if creating, return locked directory, leaving info on available slots
75  *	else return error
76  * found:
77  *	if at end of path and deleting, return information to allow delete
78  *	if at end of path and rewriting (RENAME and LOCKPARENT), lock target
79  *	  inode and return info to allow rewrite
80  *	if not at end, add name to cache; if at end and neither creating
81  *	  nor deleting, add name to cache
82  *
83  * NOTE: (LOOKUP | LOCKPARENT) currently returns the parent inode unlocked.
84  */
85 int
86 cd9660_lookup(ap)
87 	struct vop_cachedlookup_args /* {
88 		struct vnode *a_dvp;
89 		struct vnode **a_vpp;
90 		struct componentname *a_cnp;
91 	} */ *ap;
92 {
93 	struct vnode *vdp;		/* vnode for directory being searched */
94 	struct iso_node *dp;		/* inode for directory being searched */
95 	struct iso_mnt *imp;		/* filesystem that directory is in */
96 	struct buf *bp;			/* a buffer of directory entries */
97 	struct iso_directory_record *ep = 0;/* the current directory entry */
98 	int entryoffsetinblock;		/* offset of ep in bp's buffer */
99 	int saveoffset = 0;		/* offset of last directory entry in dir */
100 	int numdirpasses;		/* strategy for directory search */
101 	doff_t endsearch;		/* offset to end directory search */
102 	struct vnode *pdp;		/* saved dp during symlink work */
103 	struct vnode *tdp;		/* returned by cd9660_vget_internal */
104 	u_long bmask;			/* block offset mask */
105 	int lockparent;			/* 1 => lockparent flag is set */
106 	int error;
107 	ino_t ino = 0;
108 	int reclen;
109 	u_short namelen;
110 	int isoflags;
111 	char altname[NAME_MAX];
112 	int res;
113 	int assoc, len;
114 	char *name;
115 	struct vnode **vpp = ap->a_vpp;
116 	struct componentname *cnp = ap->a_cnp;
117 	int flags = cnp->cn_flags;
118 	int nameiop = cnp->cn_nameiop;
119 	struct thread *td = cnp->cn_thread;
120 
121 	bp = NULL;
122 	*vpp = NULL;
123 	vdp = ap->a_dvp;
124 	dp = VTOI(vdp);
125 	imp = dp->i_mnt;
126 	lockparent = flags & LOCKPARENT;
127 	cnp->cn_flags &= ~PDIRUNLOCK;
128 
129 	/*
130 	 * We now have a segment name to search for, and a directory to search.
131 	 */
132 
133 	len = cnp->cn_namelen;
134 	name = cnp->cn_nameptr;
135 	/*
136 	 * A leading `=' means, we are looking for an associated file
137 	 */
138 	if ((assoc = (imp->iso_ftype != ISO_FTYPE_RRIP && *name == ASSOCCHAR)))
139 	{
140 		len--;
141 		name++;
142 	}
143 
144 	/*
145 	 * If there is cached information on a previous search of
146 	 * this directory, pick up where we last left off.
147 	 * We cache only lookups as these are the most common
148 	 * and have the greatest payoff. Caching CREATE has little
149 	 * benefit as it usually must search the entire directory
150 	 * to determine that the entry does not exist. Caching the
151 	 * location of the last DELETE or RENAME has not reduced
152 	 * profiling time and hence has been removed in the interest
153 	 * of simplicity.
154 	 */
155 	bmask = imp->im_bmask;
156 	if (nameiop != LOOKUP || dp->i_diroff == 0 ||
157 	    dp->i_diroff > dp->i_size) {
158 		entryoffsetinblock = 0;
159 		dp->i_offset = 0;
160 		numdirpasses = 1;
161 	} else {
162 		dp->i_offset = dp->i_diroff;
163 		if ((entryoffsetinblock = dp->i_offset & bmask) &&
164 		    (error = cd9660_blkatoff(vdp, (off_t)dp->i_offset, NULL, &bp)))
165 				return (error);
166 		numdirpasses = 2;
167 		nchstats.ncs_2passes++;
168 	}
169 	endsearch = dp->i_size;
170 
171 searchloop:
172 	while (dp->i_offset < endsearch) {
173 		/*
174 		 * If offset is on a block boundary,
175 		 * read the next directory block.
176 		 * Release previous if it exists.
177 		 */
178 		if ((dp->i_offset & bmask) == 0) {
179 			if (bp != NULL)
180 				brelse(bp);
181 			if ((error =
182 			    cd9660_blkatoff(vdp, (off_t)dp->i_offset, NULL, &bp)) != 0)
183 				return (error);
184 			entryoffsetinblock = 0;
185 		}
186 		/*
187 		 * Get pointer to next entry.
188 		 */
189 		ep = (struct iso_directory_record *)
190 			((char *)bp->b_data + entryoffsetinblock);
191 
192 		reclen = isonum_711(ep->length);
193 		if (reclen == 0) {
194 			/* skip to next block, if any */
195 			dp->i_offset =
196 			    (dp->i_offset & ~bmask) + imp->logical_block_size;
197 			continue;
198 		}
199 
200 		if (reclen < ISO_DIRECTORY_RECORD_SIZE)
201 			/* illegal entry, stop */
202 			break;
203 
204 		if (entryoffsetinblock + reclen > imp->logical_block_size)
205 			/* entries are not allowed to cross boundaries */
206 			break;
207 
208 		namelen = isonum_711(ep->name_len);
209 		isoflags = isonum_711(imp->iso_ftype == ISO_FTYPE_HIGH_SIERRA?
210 				      &ep->date[6]: ep->flags);
211 
212 		if (reclen < ISO_DIRECTORY_RECORD_SIZE + namelen)
213 			/* illegal entry, stop */
214 			break;
215 
216 		/*
217 		 * Check for a name match.
218 		 */
219 		switch (imp->iso_ftype) {
220 		default:
221 			if (!(isoflags & 4) == !assoc) {
222 				if ((len == 1
223 				     && *name == '.')
224 				    || (flags & ISDOTDOT)) {
225 					if (namelen == 1
226 					    && ep->name[0] == ((flags & ISDOTDOT) ? 1 : 0)) {
227 						/*
228 						 * Save directory entry's inode number and
229 						 * release directory buffer.
230 						 */
231 						dp->i_ino = isodirino(ep, imp);
232 						goto found;
233 					}
234 					if (namelen != 1
235 					    || ep->name[0] != 0)
236 						goto notfound;
237 				} else if (!(res = isofncmp(name, len,
238 							    ep->name, namelen,
239 							    imp->joliet_level,
240 							    imp->im_flags,
241 							    imp->im_d2l,
242 							    imp->im_l2d))) {
243 					if (isoflags & 2)
244 						ino = isodirino(ep, imp);
245 					else
246 						ino = dbtob(bp->b_blkno)
247 							+ entryoffsetinblock;
248 					saveoffset = dp->i_offset;
249 				} else if (ino)
250 					goto foundino;
251 #ifdef	NOSORTBUG	/* On some CDs directory entries are not sorted correctly */
252 				else if (res < 0)
253 					goto notfound;
254 				else if (res > 0 && numdirpasses == 2)
255 					numdirpasses++;
256 #endif
257 			}
258 			break;
259 		case ISO_FTYPE_RRIP:
260 			if (isonum_711(ep->flags)&2)
261 				ino = isodirino(ep, imp);
262 			else
263 				ino = dbtob(bp->b_blkno) + entryoffsetinblock;
264 			dp->i_ino = ino;
265 			cd9660_rrip_getname(ep,altname,&namelen,&dp->i_ino,imp);
266 			if (namelen == cnp->cn_namelen
267 			    && !bcmp(name,altname,namelen))
268 				goto found;
269 			ino = 0;
270 			break;
271 		}
272 		dp->i_offset += reclen;
273 		entryoffsetinblock += reclen;
274 	}
275 	if (ino) {
276 foundino:
277 		dp->i_ino = ino;
278 		if (saveoffset != dp->i_offset) {
279 			if (lblkno(imp, dp->i_offset) !=
280 			    lblkno(imp, saveoffset)) {
281 				if (bp != NULL)
282 					brelse(bp);
283 				if ((error = cd9660_blkatoff(vdp,
284 				    (off_t)saveoffset, NULL, &bp)) != 0)
285 					return (error);
286 			}
287 			entryoffsetinblock = saveoffset & bmask;
288 			ep = (struct iso_directory_record *)
289 				((char *)bp->b_data + entryoffsetinblock);
290 			dp->i_offset = saveoffset;
291 		}
292 		goto found;
293 	}
294 notfound:
295 	/*
296 	 * If we started in the middle of the directory and failed
297 	 * to find our target, we must check the beginning as well.
298 	 */
299 	if (numdirpasses == 2) {
300 		numdirpasses--;
301 		dp->i_offset = 0;
302 		endsearch = dp->i_diroff;
303 		goto searchloop;
304 	}
305 	if (bp != NULL)
306 		brelse(bp);
307 
308 	/*
309 	 * Insert name into cache (as non-existent) if appropriate.
310 	 */
311 	if (cnp->cn_flags & MAKEENTRY)
312 		cache_enter(vdp, *vpp, cnp);
313 	if (nameiop == CREATE || nameiop == RENAME)
314 		return (EROFS);
315 	return (ENOENT);
316 
317 found:
318 	if (numdirpasses == 2)
319 		nchstats.ncs_pass2++;
320 
321 	/*
322 	 * Found component in pathname.
323 	 * If the final component of path name, save information
324 	 * in the cache as to where the entry was found.
325 	 */
326 	if ((flags & ISLASTCN) && nameiop == LOOKUP)
327 		dp->i_diroff = dp->i_offset;
328 
329 	/*
330 	 * Step through the translation in the name.  We do not `iput' the
331 	 * directory because we may need it again if a symbolic link
332 	 * is relative to the current directory.  Instead we save it
333 	 * unlocked as "pdp".  We must get the target inode before unlocking
334 	 * the directory to insure that the inode will not be removed
335 	 * before we get it.  We prevent deadlock by always fetching
336 	 * inodes from the root, moving down the directory tree. Thus
337 	 * when following backward pointers ".." we must unlock the
338 	 * parent directory before getting the requested directory.
339 	 * There is a potential race condition here if both the current
340 	 * and parent directories are removed before the `iget' for the
341 	 * inode associated with ".." returns.  We hope that this occurs
342 	 * infrequently since we cannot avoid this race condition without
343 	 * implementing a sophisticated deadlock detection algorithm.
344 	 * Note also that this simple deadlock detection scheme will not
345 	 * work if the filesystem has any hard links other than ".."
346 	 * that point backwards in the directory structure.
347 	 */
348 	pdp = vdp;
349 	/*
350 	 * If ino is different from dp->i_ino,
351 	 * it's a relocated directory.
352 	 */
353 	if (flags & ISDOTDOT) {
354 		VOP_UNLOCK(pdp, 0, td);	/* race to get the inode */
355 		error = cd9660_vget_internal(vdp->v_mount, dp->i_ino,
356 					     LK_EXCLUSIVE, &tdp,
357 					     dp->i_ino != ino, ep);
358 		brelse(bp);
359 		if (error) {
360 			vn_lock(pdp, LK_EXCLUSIVE | LK_RETRY, td);
361 			return (error);
362 		}
363 		if (lockparent && (flags & ISLASTCN)) {
364 			if ((error = vn_lock(pdp, LK_EXCLUSIVE, td)) != 0) {
365 				cnp->cn_flags |= PDIRUNLOCK;
366 				vput(tdp);
367 				return (error);
368 			}
369 		} else
370 			cnp->cn_flags |= PDIRUNLOCK;
371 		*vpp = tdp;
372 	} else if (dp->i_number == dp->i_ino) {
373 		brelse(bp);
374 		VREF(vdp);	/* we want ourself, ie "." */
375 		*vpp = vdp;
376 	} else {
377 		error = cd9660_vget_internal(vdp->v_mount, dp->i_ino,
378 					     LK_EXCLUSIVE, &tdp,
379 					     dp->i_ino != ino, ep);
380 		brelse(bp);
381 		if (error)
382 			return (error);
383 		if (!lockparent || !(flags & ISLASTCN)) {
384 			cnp->cn_flags |= PDIRUNLOCK;
385 			VOP_UNLOCK(pdp, 0, td);
386 		}
387 		*vpp = tdp;
388 	}
389 
390 	/*
391 	 * Insert name into cache if appropriate.
392 	 */
393 	if (cnp->cn_flags & MAKEENTRY)
394 		cache_enter(vdp, *vpp, cnp);
395 	return (0);
396 }
397 
398 /*
399  * Return buffer with the contents of block "offset" from the beginning of
400  * directory "ip".  If "res" is non-zero, fill it in with a pointer to the
401  * remaining space in the directory.
402  */
403 int
404 cd9660_blkatoff(vp, offset, res, bpp)
405 	struct vnode *vp;
406 	off_t offset;
407 	char **res;
408 	struct buf **bpp;
409 {
410 	struct iso_node *ip;
411 	struct iso_mnt *imp;
412 	struct buf *bp;
413 	daddr_t lbn;
414 	int bsize, bshift, error;
415 
416 	ip = VTOI(vp);
417 	imp = ip->i_mnt;
418 	lbn = lblkno(imp, offset);
419 	bsize = blksize(imp, ip, lbn);
420 	bshift = imp->im_bshift;
421 
422 	if ((error = bread(vp, lbn, bsize, NOCRED, &bp)) != 0) {
423 		brelse(bp);
424 		*bpp = NULL;
425 		return (error);
426 	}
427 
428 	/*
429 	 * We must BMAP the buffer because the directory code may use b_blkno
430 	 * to calculate the inode for certain types of directory entries.
431 	 * We could get away with not doing it before we VMIO-backed the
432 	 * directories because the buffers would get freed atomically with
433 	 * the invalidation of their data.  But with VMIO-backed buffers
434 	 * the buffers may be freed and then later reconstituted - and the
435 	 * reconstituted buffer will have no knowledge of b_blkno.
436 	 */
437 	if (bp->b_blkno == bp->b_lblkno) {
438 	        bp->b_blkno = (ip->iso_start + bp->b_lblkno) << (bshift - DEV_BSHIFT);
439         }
440 
441 	if (res)
442 		*res = (char *)bp->b_data + blkoff(imp, offset);
443 	*bpp = bp;
444 	return (0);
445 }
446