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