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