xref: /haiku/src/add-ons/kernel/file_systems/fat/bsd/fs/msdosfs/msdosfs_lookup.c (revision 342a1b221b5bb385410f758df2c625b70cafdd03)
1 /*	$NetBSD: msdosfs_lookup.c,v 1.37 1997/11/17 15:36:54 ws Exp $	*/
2 
3 /*-
4  * SPDX-License-Identifier: BSD-4-Clause
5  *
6  * Copyright (C) 1994, 1995, 1997 Wolfgang Solfrank.
7  * Copyright (C) 1994, 1995, 1997 TooLs GmbH.
8  * All rights reserved.
9  * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below).
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *	This product includes software developed by TooLs GmbH.
22  * 4. The name of TooLs GmbH may not be used to endorse or promote products
23  *    derived from this software without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
26  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
31  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
32  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
33  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
34  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35  */
36 /*-
37  * Written by Paul Popelka (paulp@uts.amdahl.com)
38  *
39  * You can do anything you want with this software, just don't say you wrote
40  * it, and don't remove this notice.
41  *
42  * This software is provided "as is".
43  *
44  * The author supplies this software to be publicly redistributed on the
45  * understanding that the author is not responsible for the correct
46  * functioning of this software in any circumstances and is not liable for
47  * any damages caused by this software.
48  *
49  * October 1992
50  */
51 
52 
53 // Modified to support the Haiku FAT driver
54 
55 #include <sys/param.h>
56 #include <sys/systm.h>
57 #include <sys/buf.h>
58 #include <sys/mount.h>
59 #include <sys/namei.h>
60 #include <sys/vnode.h>
61 
62 #include <fs/msdosfs/bpb.h>
63 #include <fs/msdosfs/direntry.h>
64 #include <fs/msdosfs/denode.h>
65 #include <fs/msdosfs/fat.h>
66 #include <fs/msdosfs/msdosfsmount.h>
67 
68 static int
msdosfs_lookup_checker(struct msdosfsmount * pmp,struct vnode * dvp,struct denode * tdp,struct vnode ** vpp)69 msdosfs_lookup_checker(struct msdosfsmount *pmp, struct vnode *dvp,
70     struct denode *tdp, struct vnode **vpp)
71 {
72 	struct vnode *vp;
73 
74 	vp = DETOV(tdp);
75 
76 	/*
77 	 * Lookup assumes that directory cannot be hardlinked.
78 	 * Corrupted msdosfs filesystem could break this assumption.
79 	 */
80 	if (vp == dvp) {
81 		vput(vp);
82 		msdosfs_integrity_error(pmp);
83 		*vpp = NULL;
84 		return (EBADF);
85 	}
86 
87 	*vpp = vp;
88 	return (0);
89 }
90 
91 // Haiku port:  unused FreeBSD hook function
92 #if 0
93 int
94 msdosfs_lookup(struct vop_cachedlookup_args *ap)
95 {
96 
97 	return (msdosfs_lookup_ino(ap->a_dvp, ap->a_vpp, ap->a_cnp, NULL,
98 	    NULL));
99 }
100 #endif // 0
101 
102 struct deget_dotdot {
103 	u_long cluster;
104 	int blkoff;
105 };
106 
107 static int
msdosfs_deget_dotdot(struct mount * mp,void * arg,int lkflags,struct vnode ** rvp)108 msdosfs_deget_dotdot(struct mount *mp, void *arg, int lkflags,
109     struct vnode **rvp)
110 {
111 	struct deget_dotdot *dd_arg;
112 	struct denode *rdp;
113 	struct msdosfsmount *pmp;
114 	int error;
115 
116 	pmp = VFSTOMSDOSFS(mp);
117 	dd_arg = arg;
118 	error = deget(pmp, dd_arg->cluster, dd_arg->blkoff,
119 	    LK_EXCLUSIVE, &rdp);
120 	if (error == 0)
121 		*rvp = DETOV(rdp);
122 	return (error);
123 }
124 
125 /*
126  * When we search a directory the blocks containing directory entries are
127  * read and examined.  The directory entries contain information that would
128  * normally be in the inode of a unix filesystem.  This means that some of
129  * a directory's contents may also be in memory resident denodes (sort of
130  * an inode).  This can cause problems if we are searching while some other
131  * process is modifying a directory.  To prevent one process from accessing
132  * incompletely modified directory information we depend upon being the
133  * sole owner of a directory block.  bread/brelse provide this service.
134  * This being the case, when a process modifies a directory it must first
135  * acquire the disk block that contains the directory entry to be modified.
136  * Then update the disk block and the denode, and then write the disk block
137  * out to disk.  This way disk blocks containing directory entries and in
138  * memory denode's will be in synch.
139  */
140 int
msdosfs_lookup_ino(struct vnode * vdp,struct vnode ** vpp,struct componentname * cnp,daddr_t * scnp,u_long * blkoffp)141 msdosfs_lookup_ino(struct vnode *vdp, struct vnode **vpp, struct componentname
142     *cnp, daddr_t *scnp, u_long *blkoffp)
143 {
144 	struct mbnambuf nb;
145 	daddr_t bn;
146 	int error;
147 	int slotcount;
148 	int slotoffset = 0;
149 	int frcn;
150 	u_long cluster;
151 	u_long blkoff;
152 	int diroff;
153 	int blsize;
154 	int isadir;		/* ~0 if found direntry is a directory	 */
155 	u_long scn;		/* starting cluster number		 */
156 		// Haiku port:  type changed to avoid compiler warning
157 	struct vnode *pdp;
158 	struct denode *dp;
159 	struct denode *tdp;
160 	struct msdosfsmount *pmp;
161 	struct buf *bp = NULL;
162 	struct direntry *dep = NULL;
163 	struct deget_dotdot dd_arg;
164 	u_char dosfilename[12];
165 	int flags = cnp->cn_flags;
166 	int nameiop = cnp->cn_nameiop;
167 	int unlen;
168 	uint64_t inode1;
169 
170 	int wincnt = 1;
171 	int chksum = -1, chksum_ok;
172 	int olddos = 1;
173 
174 #ifdef MSDOSFS_DEBUG
175 	printf("msdosfs_lookup(): looking for %s\n", cnp->cn_nameptr);
176 #endif
177 	dp = VTODE(vdp);
178 	pmp = dp->de_pmp;
179 #ifdef MSDOSFS_DEBUG
180 	printf("msdosfs_lookup(): vdp %p, dp %p, Attr %02x\n",
181 	    vdp, dp, dp->de_Attributes);
182 #endif
183 
184  restart:
185 	if (vpp != NULL)
186 		*vpp = NULL;
187 	/*
188 	 * If they are going after the . or .. entry in the root directory,
189 	 * they won't find it.  DOS filesystems don't have them in the root
190 	 * directory.  So, we fake it. deget() is in on this scam too.
191 	 */
192 	if ((vdp->v_vflag & VV_ROOT) && cnp->cn_nameptr[0] == '.' &&
193 	    (cnp->cn_namelen == 1 ||
194 		(cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.'))) {
195 		isadir = ATTR_DIRECTORY;
196 		scn = MSDOSFSROOT;
197 #ifdef MSDOSFS_DEBUG
198 		printf("msdosfs_lookup(): looking for . or .. in root directory\n");
199 #endif
200 		cluster = MSDOSFSROOT;
201 		blkoff = MSDOSFSROOT_OFS;
202 		goto foundroot;
203 	}
204 
205 	switch (unix2dosfn((const u_char *)cnp->cn_nameptr, dosfilename,
206 	    cnp->cn_namelen, 0, pmp)) {
207 	case 0:
208 		return (EINVAL);
209 	case 1:
210 		break;
211 	case 2:
212 		wincnt = winSlotCnt((const u_char *)cnp->cn_nameptr,
213 		    cnp->cn_namelen, pmp) + 1;
214 		break;
215 	case 3:
216 		olddos = 0;
217 		wincnt = winSlotCnt((const u_char *)cnp->cn_nameptr,
218 		    cnp->cn_namelen, pmp) + 1;
219 		break;
220 	}
221 	if (pmp->pm_flags & MSDOSFSMNT_SHORTNAME) {
222 		wincnt = 1;
223 		olddos = 1;
224 	}
225 	unlen = winLenFixup((u_char *)cnp->cn_nameptr, cnp->cn_namelen);
226 		// Haiku port:  cast added to avoid compiler warning
227 
228 	/*
229 	 * Suppress search for slots unless creating
230 	 * file and at end of pathname, in which case
231 	 * we watch for a place to put the new file in
232 	 * case it doesn't already exist.
233 	 */
234 	slotcount = wincnt;
235 	if ((nameiop == CREATE || nameiop == RENAME) &&
236 	    (flags & ISLASTCN))
237 		slotcount = 0;
238 
239 #ifdef MSDOSFS_DEBUG
240 	printf("msdosfs_lookup(): dos version of filename %s, length %ld\n",
241 	    dosfilename, cnp->cn_namelen);
242 #endif
243 	/*
244 	 * Search the directory pointed at by vdp for the name pointed at
245 	 * by cnp->cn_nameptr.
246 	 */
247 	tdp = NULL;
248 	mbnambuf_init(&nb);
249 	/*
250 	 * The outer loop ranges over the clusters that make up the
251 	 * directory.  Note that the root directory is different from all
252 	 * other directories.  It has a fixed number of blocks that are not
253 	 * part of the pool of allocatable clusters.  So, we treat it a
254 	 * little differently. The root directory starts at "cluster" 0.
255 	 */
256 	diroff = 0;
257 	for (frcn = 0;; frcn++) {
258 		error = pcbmap(dp, frcn, &bn, &cluster, &blsize);
259 		if (error) {
260 			if (error == E2BIG)
261 				break;
262 			return (error);
263 		}
264 		error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp);
265 		if (error) {
266 			return (error);
267 		}
268 		for (blkoff = 0; blkoff < (u_long)blsize;
269 		     blkoff += sizeof(struct direntry),
270 		     diroff += sizeof(struct direntry)) {
271 			 // Haiku port:  cast added to avoid compiler warning
272 			dep = (struct direntry *)(bp->b_data + blkoff);
273 			/*
274 			 * If the slot is empty and we are still looking
275 			 * for an empty then remember this one.  If the
276 			 * slot is not empty then check to see if it
277 			 * matches what we are looking for.  If the slot
278 			 * has never been filled with anything, then the
279 			 * remainder of the directory has never been used,
280 			 * so there is no point in searching it.
281 			 */
282 			if (dep->deName[0] == SLOT_EMPTY ||
283 			    dep->deName[0] == SLOT_DELETED) {
284 				/*
285 				 * Drop memory of previous long matches
286 				 */
287 				chksum = -1;
288 				mbnambuf_init(&nb);
289 
290 				if (slotcount < wincnt) {
291 					slotcount++;
292 					slotoffset = diroff;
293 				}
294 				if (dep->deName[0] == SLOT_EMPTY) {
295 					brelse(bp);
296 					goto notfound;
297 				}
298 			} else {
299 				/*
300 				 * If there wasn't enough space for our winentries,
301 				 * forget about the empty space
302 				 */
303 				if (slotcount < wincnt)
304 					slotcount = 0;
305 
306 				/*
307 				 * Check for Win95 long filename entry
308 				 */
309 				if (dep->deAttributes == ATTR_WIN95) {
310 					if (pmp->pm_flags & MSDOSFSMNT_SHORTNAME)
311 						continue;
312 
313 					chksum = win2unixfn(&nb,
314 					    (struct winentry *)dep, chksum,
315 					    pmp);
316 					continue;
317 				}
318 
319 				chksum = winChkName(&nb,
320 				    (const u_char *)cnp->cn_nameptr, unlen,
321 				    chksum, pmp);
322 				if (chksum == -2) {
323 					chksum = -1;
324 					continue;
325 				}
326 
327 				/*
328 				 * Ignore volume labels (anywhere, not just
329 				 * the root directory).
330 				 */
331 				if (dep->deAttributes & ATTR_VOLUME) {
332 					chksum = -1;
333 					continue;
334 				}
335 
336 				/*
337 				 * Check for a checksum or name match
338 				 */
339 				chksum_ok = (chksum == winChksum(dep->deName));
340 				if (!chksum_ok
341 				    && (!olddos || bcmp(dosfilename, dep->deName, 11))) {
342 					chksum = -1;
343 					continue;
344 				}
345 #ifdef MSDOSFS_DEBUG
346 				printf("msdosfs_lookup(): match blkoff %lu, diroff %d\n",
347 				    blkoff, diroff);
348 #endif
349 				/*
350 				 * Remember where this directory
351 				 * entry came from for whoever did
352 				 * this lookup.
353 				 */
354 				dp->de_fndoffset = diroff;
355 				if (chksum_ok && nameiop == RENAME) {
356 					/*
357 					 * Target had correct long name
358 					 * directory entries, reuse them
359 					 * as needed.
360 					 */
361 					dp->de_fndcnt = wincnt - 1;
362 				} else {
363 					/*
364 					 * Long name directory entries
365 					 * not present or corrupt, can only
366 					 * reuse dos directory entry.
367 					 */
368 					dp->de_fndcnt = 0;
369 				}
370 
371 				goto found;
372 			}
373 		}	/* for (blkoff = 0; .... */
374 		/*
375 		 * Release the buffer holding the directory cluster just
376 		 * searched.
377 		 */
378 		brelse(bp);
379 	}	/* for (frcn = 0; ; frcn++) */
380 
381 notfound:
382 	/*
383 	 * We hold no disk buffers at this point.
384 	 */
385 
386 	/*
387 	 * Fixup the slot description to point to the place where
388 	 * we might put the new DOS direntry (putting the Win95
389 	 * long name entries before that)
390 	 */
391 	if (!slotcount) {
392 		slotcount = 1;
393 		slotoffset = diroff;
394 	}
395 	if (wincnt > slotcount)
396 		slotoffset += sizeof(struct direntry) * (wincnt - slotcount);
397 
398 	/*
399 	 * If we get here we didn't find the entry we were looking for. But
400 	 * that's ok if we are creating or renaming and are at the end of
401 	 * the pathname and the directory hasn't been removed.
402 	 */
403 #ifdef MSDOSFS_DEBUG
404 	printf("msdosfs_lookup(): op %d, refcnt %ld\n",
405 	    nameiop, dp->de_refcnt);
406 	printf("               slotcount %d, slotoffset %d\n",
407 	       slotcount, slotoffset);
408 #endif
409 	if ((nameiop == CREATE || nameiop == RENAME) &&
410 	    (flags & ISLASTCN) && dp->de_refcnt != 0) {
411 		/*
412 		 * Access for write is interpreted as allowing
413 		 * creation of files in the directory.
414 		 */
415 		error = VOP_ACCESS(vdp, VWRITE, cnp->cn_cred, curthread);
416 		if (error)
417 			return (error);
418 		/*
419 		 * Return an indication of where the new directory
420 		 * entry should be put.
421 		 */
422 		dp->de_fndoffset = slotoffset;
423 		dp->de_fndcnt = wincnt - 1;
424 
425 		/*
426 		 * We return with the directory locked, so that
427 		 * the parameters we set up above will still be
428 		 * valid if we actually decide to do a direnter().
429 		 * We return ni_vp == NULL to indicate that the entry
430 		 * does not currently exist; we leave a pointer to
431 		 * the (locked) directory inode in ndp->ni_dvp.
432 		 *
433 		 * NB - if the directory is unlocked, then this
434 		 * information cannot be used.
435 		 */
436 		return (EJUSTRETURN);
437 	}
438 #if 0
439 	/*
440 	 * Insert name into cache (as non-existent) if appropriate.
441 	 *
442 	 * XXX Negative caching is broken for msdosfs because the name
443 	 * cache doesn't understand peculiarities such as case insensitivity
444 	 * and 8.3 filenames.  Hence, it may not invalidate all negative
445 	 * entries if a file with this name is later created.
446 	 */
447 	if ((cnp->cn_flags & MAKEENTRY) != 0)
448 		cache_enter(vdp, *vpp, cnp);
449 #endif
450 	return (ENOENT);
451 
452 found:
453 	/*
454 	 * NOTE:  We still have the buffer with matched directory entry at
455 	 * this point.
456 	 */
457 	isadir = dep->deAttributes & ATTR_DIRECTORY;
458 	scn = getushort(dep->deStartCluster);
459 	if (FAT32(pmp)) {
460 		scn |= getushort(dep->deHighClust) << 16;
461 		if (scn == pmp->pm_rootdirblk) {
462 			/*
463 			 * There should actually be 0 here.
464 			 * Just ignore the error.
465 			 */
466 			scn = MSDOSFSROOT;
467 		}
468 	}
469 
470 	if (isadir) {
471 		cluster = scn;
472 		if (cluster == MSDOSFSROOT)
473 			blkoff = MSDOSFSROOT_OFS;
474 		else
475 			blkoff = 0;
476 	} else if (cluster == MSDOSFSROOT)
477 		blkoff = diroff;
478 
479 	/*
480 	 * Now release buf to allow deget to read the entry again.
481 	 * Reserving it here and giving it to deget could result
482 	 * in a deadlock.
483 	 */
484 	brelse(bp);
485 	bp = NULL;
486 
487 foundroot:
488 	/*
489 	 * If we entered at foundroot, then we are looking for the . or ..
490 	 * entry of the filesystems root directory.  isadir and scn were
491 	 * setup before jumping here.  And, bp is already null.
492 	 */
493 	if (FAT32(pmp) && scn == MSDOSFSROOT)
494 		scn = pmp->pm_rootdirblk;
495 
496 	if (scnp != NULL) {
497 		*scnp = cluster;
498 		*blkoffp = blkoff;
499 		return (0);
500 	}
501 
502 	/*
503 	 * If deleting, and at end of pathname, return
504 	 * parameters which can be used to remove file.
505 	 */
506 	if (nameiop == DELETE && (flags & ISLASTCN)) {
507 		/*
508 		 * Don't allow deleting the root.
509 		 */
510 		if (blkoff == MSDOSFSROOT_OFS)
511 			return (EBUSY);
512 
513 		/*
514 		 * Write access to directory required to delete files.
515 		 */
516 		error = VOP_ACCESS(vdp, VWRITE, cnp->cn_cred, curthread);
517 		if (error)
518 			return (error);
519 
520 		/*
521 		 * Return pointer to current entry in dp->i_offset.
522 		 * Save directory inode pointer in ndp->ni_dvp for dirremove().
523 		 */
524 		if (dp->de_StartCluster == scn && isadir) {	/* "." */
525 			VREF(vdp);
526 			*vpp = vdp;
527 			return (0);
528 		}
529 		error = deget(pmp, cluster, blkoff, LK_EXCLUSIVE, &tdp);
530 		if (error)
531 			return (error);
532 		return (msdosfs_lookup_checker(pmp, vdp, tdp, vpp));
533 	}
534 
535 	/*
536 	 * If rewriting (RENAME), return the inode and the
537 	 * information required to rewrite the present directory
538 	 * Must get inode of directory entry to verify it's a
539 	 * regular file, or empty directory.
540 	 */
541 	if (nameiop == RENAME && (flags & ISLASTCN)) {
542 		if (blkoff == MSDOSFSROOT_OFS)
543 			return (EBUSY);
544 
545 		error = VOP_ACCESS(vdp, VWRITE, cnp->cn_cred, curthread);
546 		if (error)
547 			return (error);
548 
549 		/*
550 		 * Careful about locking second inode.
551 		 * This can only occur if the target is ".".
552 		 */
553 		if (dp->de_StartCluster == scn && isadir)
554 			return (EISDIR);
555 
556 		if ((error = deget(pmp, cluster, blkoff, LK_EXCLUSIVE,
557 		    &tdp)) != 0)
558 			return (error);
559 		if ((error = msdosfs_lookup_checker(pmp, vdp, tdp, vpp))
560 		    != 0)
561 			return (error);
562 		return (0);
563 	}
564 
565 	/*
566 	 * Step through the translation in the name.  We do not `vput' the
567 	 * directory because we may need it again if a symbolic link
568 	 * is relative to the current directory.  Instead we save it
569 	 * unlocked as "pdp".  We must get the target inode before unlocking
570 	 * the directory to insure that the inode will not be removed
571 	 * before we get it.  We prevent deadlock by always fetching
572 	 * inodes from the root, moving down the directory tree. Thus
573 	 * when following backward pointers ".." we must unlock the
574 	 * parent directory before getting the requested directory.
575 	 */
576 	pdp = vdp;
577 	if (flags & ISDOTDOT) {
578 		dd_arg.cluster = cluster;
579 		dd_arg.blkoff = blkoff;
580 		error = vn_vget_ino_gen(vdp, msdosfs_deget_dotdot,
581 		    &dd_arg, cnp->cn_lkflags, vpp);
582 		if (error != 0) {
583 			*vpp = NULL;
584 			return (error);
585 		}
586 		/*
587 		 * Recheck that ".." still points to the inode we
588 		 * looked up before pdp lock was dropped.
589 		 */
590 		error = msdosfs_lookup_ino(pdp, NULL, cnp, (daddr_t *)&scn, &blkoff);
591 			// Haiku port:  cast added to avoid compiler warning
592 		if (error) {
593 			vput(*vpp);
594 			*vpp = NULL;
595 			return (error);
596 		}
597 		if (FAT32(pmp) && scn == MSDOSFSROOT)
598 			scn = pmp->pm_rootdirblk;
599 		inode1 = DETOI(pmp, scn, blkoff);
600 		if (VTODE(*vpp)->de_inode != inode1) {
601 			vput(*vpp);
602 			goto restart;
603 		}
604 		error = msdosfs_lookup_checker(pmp, vdp, VTODE(*vpp), vpp);
605 		if (error != 0)
606 			return (error);
607 	} else if (dp->de_StartCluster == scn && isadir) {
608 		if (cnp->cn_namelen != 1 || cnp->cn_nameptr[0] != '.') {
609 			/* fs is corrupted, non-dot lookup returned dvp */
610 			msdosfs_integrity_error(pmp);
611 			return (EBADF);
612 		}
613 		VREF(vdp);	/* we want ourself, ie "." */
614 		*vpp = vdp;
615 	} else {
616 		if ((error = deget(pmp, cluster, blkoff, LK_EXCLUSIVE,
617 		    &tdp)) != 0)
618 			return (error);
619 		if ((error = msdosfs_lookup_checker(pmp, vdp, tdp, vpp)) != 0)
620 			return (error);
621 	}
622 
623 	/*
624 	 * Insert name into cache if appropriate.
625 	 */
626 	if (cnp->cn_flags & MAKEENTRY)
627 		cache_enter(vdp, *vpp, cnp);
628 	return (0);
629 }
630 
631 /*
632  * dep  - directory entry to copy into the directory
633  * ddep - directory to add to
634  * depp - return the address of the denode for the created directory entry
635  *	  if depp != 0
636  * cnp  - componentname needed for Win95 long filenames
637  */
638 int
createde(struct denode * dep,struct denode * ddep,struct denode ** depp,struct componentname * cnp)639 createde(struct denode *dep, struct denode *ddep, struct denode **depp,
640     struct componentname *cnp)
641 {
642 	int error;
643 	u_long dirclust, diroffset;
644 	struct direntry *ndep;
645 	struct msdosfsmount *pmp = ddep->de_pmp;
646 	struct buf *bp;
647 	daddr_t bn;
648 	int blsize;
649 
650 #ifdef MSDOSFS_DEBUG
651 	printf("createde(dep %p, ddep %p, depp %p, cnp %p)\n",
652 	    dep, ddep, depp, cnp);
653 #endif
654 
655 	/*
656 	 * If no space left in the directory then allocate another cluster
657 	 * and chain it onto the end of the file.  There is one exception
658 	 * to this.  That is, if the root directory has no more space it
659 	 * can NOT be expanded.  extendfile() checks for and fails attempts
660 	 * to extend the root directory.  We just return an error in that
661 	 * case.
662 	 */
663 	if (ddep->de_fndoffset >= ddep->de_FileSize) {
664 		diroffset = ddep->de_fndoffset + sizeof(struct direntry)
665 		    - ddep->de_FileSize;
666 		dirclust = de_clcount(pmp, diroffset);
667 		error = extendfile(ddep, dirclust, 0, 0, DE_CLEAR);
668 		if (error) {
669 			(void)detrunc(ddep, ddep->de_FileSize, 0, NOCRED);
670 			return error;
671 		}
672 
673 		/*
674 		 * Update the size of the directory
675 		 */
676 		ddep->de_FileSize += de_cn2off(pmp, dirclust);
677 	}
678 
679 	/*
680 	 * We just read in the cluster with space.  Copy the new directory
681 	 * entry in.  Then write it to disk. NOTE:  DOS directories
682 	 * do not get smaller as clusters are emptied.
683 	 */
684 	error = pcbmap(ddep, de_cluster(pmp, ddep->de_fndoffset),
685 		       &bn, &dirclust, &blsize);
686 	if (error)
687 		return error;
688 	diroffset = ddep->de_fndoffset;
689 	if (dirclust != MSDOSFSROOT)
690 		diroffset &= pmp->pm_crbomask;
691 	if ((error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp)) != 0) {
692 		brelse(bp);
693 		return error;
694 	}
695 	ndep = bptoep(pmp, bp, ddep->de_fndoffset);
696 	rootde_alloced(ddep);
697 
698 	DE_EXTERNALIZE(ndep, dep);
699 
700 	/*
701 	 * Now write the Win95 long name
702 	 */
703 	if (ddep->de_fndcnt > 0) {
704 		uint8_t chksum = winChksum(ndep->deName);
705 		const u_char *un = (const u_char *)cnp->cn_nameptr;
706 		int unlen = cnp->cn_namelen;
707 		int cnt = 1;
708 
709 		while (--ddep->de_fndcnt >= 0) {
710 			if (!(ddep->de_fndoffset & pmp->pm_crbomask)) {
711 				if (DOINGASYNC(DETOV(ddep)))
712 					bdwrite(bp);
713 				else if ((error = bwrite(bp)) != 0)
714 					return error;
715 
716 				ddep->de_fndoffset -= sizeof(struct direntry);
717 				error = pcbmap(ddep,
718 					       de_cluster(pmp,
719 							  ddep->de_fndoffset),
720 					       &bn, 0, &blsize);
721 				if (error)
722 					return error;
723 
724 				error = bread(pmp->pm_devvp, bn, blsize,
725 					      NOCRED, &bp);
726 				if (error) {
727 					return error;
728 				}
729 				ndep = bptoep(pmp, bp, ddep->de_fndoffset);
730 			} else {
731 				ndep--;
732 				ddep->de_fndoffset -= sizeof(struct direntry);
733 			}
734 			rootde_alloced(ddep);
735 			if (!unix2winfn(un, unlen, (struct winentry *)ndep,
736 					cnt++, chksum, pmp))
737 				break;
738 		}
739 	}
740 
741 	if (DOINGASYNC(DETOV(ddep)))
742 		bdwrite(bp);
743 	else if ((error = bwrite(bp)) != 0)
744 		return error;
745 
746 	/*
747 	 * If they want us to return with the denode gotten.
748 	 */
749 	if (depp) {
750 		if (dep->de_Attributes & ATTR_DIRECTORY) {
751 			dirclust = dep->de_StartCluster;
752 			if (FAT32(pmp) && dirclust == pmp->pm_rootdirblk)
753 				dirclust = MSDOSFSROOT;
754 			if (dirclust == MSDOSFSROOT)
755 				diroffset = MSDOSFSROOT_OFS;
756 			else
757 				diroffset = 0;
758 		}
759 		return (deget(pmp, dirclust, diroffset, LK_EXCLUSIVE, depp));
760 	}
761 
762 	return 0;
763 }
764 
765 /*
766  * Be sure a directory is empty except for "." and "..". Return 1 if empty,
767  * return 0 if not empty or error.
768  */
769 int
dosdirempty(struct denode * dep)770 dosdirempty(struct denode *dep)
771 {
772 	int blsize;
773 	int error;
774 	u_long cn;
775 	daddr_t bn;
776 	struct buf *bp;
777 	struct msdosfsmount *pmp = dep->de_pmp;
778 	struct direntry *dentp;
779 
780 	/*
781 	 * Since the filesize field in directory entries for a directory is
782 	 * zero, we just have to feel our way through the directory until
783 	 * we hit end of file.
784 	 */
785 	for (cn = 0;; cn++) {
786 		if ((error = pcbmap(dep, cn, &bn, 0, &blsize)) != 0) {
787 			if (error == E2BIG)
788 				return (1);	/* it's empty */
789 			return (0);
790 		}
791 		error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp);
792 		if (error) {
793 			return (0);
794 		}
795 		for (dentp = (struct direntry *)bp->b_data;
796 		     (char *)dentp < bp->b_data + blsize;
797 		     dentp++) {
798 			if (dentp->deName[0] != SLOT_DELETED &&
799 			    (dentp->deAttributes & ATTR_VOLUME) == 0) {
800 				/*
801 				 * In dos directories an entry whose name
802 				 * starts with SLOT_EMPTY (0) starts the
803 				 * beginning of the unused part of the
804 				 * directory, so we can just return that it
805 				 * is empty.
806 				 */
807 				if (dentp->deName[0] == SLOT_EMPTY) {
808 					brelse(bp);
809 					return (1);
810 				}
811 				/*
812 				 * Any names other than "." and ".." in a
813 				 * directory mean it is not empty.
814 				 */
815 				if (bcmp(dentp->deName, ".          ", 11) &&
816 				    bcmp(dentp->deName, "..         ", 11)) {
817 					brelse(bp);
818 #ifdef MSDOSFS_DEBUG
819 					printf("dosdirempty(): entry found %02x, %02x\n",
820 					    dentp->deName[0], dentp->deName[1]);
821 #endif
822 					return (0);	/* not empty */
823 				}
824 			}
825 		}
826 		brelse(bp);
827 	}
828 	/* NOTREACHED */
829 }
830 
831 /*
832  * Check to see if the directory described by target is in some
833  * subdirectory of source.  This prevents something like the following from
834  * succeeding and leaving a bunch or files and directories orphaned. mv
835  * /a/b/c /a/b/c/d/e/f Where c and f are directories.
836  *
837  * source - the inode for /a/b/c
838  * target - the inode for /a/b/c/d/e/f
839  *
840  * Returns 0 if target is NOT a subdirectory of source.
841  * Otherwise returns a non-zero error number.
842  */
843 int
doscheckpath(struct denode * source,struct denode * target,daddr_t * wait_scn)844 doscheckpath(struct denode *source, struct denode *target, daddr_t *wait_scn)
845 {
846 	u_long scn;
847 		// Haiku port:  type changed to avoid compiler warning
848 	struct msdosfsmount *pmp;
849 	struct direntry *ep;
850 	struct denode *dep;
851 	struct buf *bp = NULL;
852 	int error = 0;
853 
854 	*wait_scn = 0;
855 
856 	pmp = target->de_pmp;
857 	lockmgr_assert(&pmp->pm_checkpath_lock, KA_XLOCKED);
858 	KASSERT(pmp == source->de_pmp,
859 	    ("doscheckpath: source and target on different filesystems"));
860 
861 	if ((target->de_Attributes & ATTR_DIRECTORY) == 0 ||
862 	    (source->de_Attributes & ATTR_DIRECTORY) == 0)
863 		return (ENOTDIR);
864 
865 	if (target->de_StartCluster == source->de_StartCluster)
866 		return (EEXIST);
867 
868 	if (target->de_StartCluster == MSDOSFSROOT ||
869 	    (FAT32(pmp) && target->de_StartCluster == pmp->pm_rootdirblk))
870 		return (0);
871 
872 	dep = target;
873 	vget(DETOV(dep), LK_EXCLUSIVE);
874 	for (;;) {
875 		if ((dep->de_Attributes & ATTR_DIRECTORY) == 0) {
876 			error = ENOTDIR;
877 			break;
878 		}
879 		scn = dep->de_StartCluster;
880 		error = bread(pmp->pm_devvp, cntobn(pmp, scn),
881 		    pmp->pm_bpcluster, NOCRED, &bp);
882 		if (error != 0)
883 			break;
884 
885 		ep = (struct direntry *)bp->b_data + 1;
886 		if ((ep->deAttributes & ATTR_DIRECTORY) == 0 ||
887 		    bcmp(ep->deName, "..         ", 11) != 0) {
888 			error = ENOTDIR;
889 			brelse(bp);
890 			break;
891 		}
892 
893 		scn = getushort(ep->deStartCluster);
894 		if (FAT32(pmp))
895 			scn |= getushort(ep->deHighClust) << 16;
896 		brelse(bp);
897 
898 		if (scn == source->de_StartCluster) {
899 			error = EINVAL;
900 			break;
901 		}
902 		if (scn == MSDOSFSROOT)
903 			break;
904 		if (FAT32(pmp) && scn == pmp->pm_rootdirblk) {
905 			/*
906 			 * scn should be 0 in this case,
907 			 * but we silently ignore the error.
908 			 */
909 			break;
910 		}
911 
912 		vput(DETOV(dep));
913 		dep = NULL;
914 		/* NOTE: deget() clears dep on error */
915 		error = deget(pmp, scn, 0, LK_EXCLUSIVE | LK_NOWAIT, &dep);
916 		if (error != 0) {
917 			*wait_scn = scn;
918 			break;
919 		}
920 	}
921 #ifdef MSDOSFS_DEBUG
922 	if (error == ENOTDIR)
923 		printf("doscheckpath(): .. not a directory?\n");
924 #endif
925 	if (dep != NULL)
926 		vput(DETOV(dep));
927 	return (error);
928 }
929 
930 /*
931  * Read in the disk block containing the directory entry (dirclu, dirofs)
932  * and return the address of the buf header, and the address of the
933  * directory entry within the block.
934  */
935 int
readep(struct msdosfsmount * pmp,u_long dirclust,u_long diroffset,struct buf ** bpp,struct direntry ** epp)936 readep(struct msdosfsmount *pmp, u_long dirclust, u_long diroffset,
937     struct buf **bpp, struct direntry **epp)
938 {
939 	int error;
940 	daddr_t bn;
941 	int blsize;
942 
943 	blsize = pmp->pm_bpcluster;
944 	if (dirclust == MSDOSFSROOT
945 	    && de_blk(pmp, diroffset + blsize) > pmp->pm_rootdirsize)
946 		blsize = de_bn2off(pmp, pmp->pm_rootdirsize) & pmp->pm_crbomask;
947 	bn = detobn(pmp, dirclust, diroffset);
948 	if ((error = bread(pmp->pm_devvp, bn, blsize, NOCRED, bpp)) != 0) {
949 		brelse(*bpp);
950 		*bpp = NULL;
951 		return (error);
952 	}
953 	if (epp)
954 		*epp = bptoep(pmp, *bpp, diroffset);
955 	return (0);
956 }
957 
958 /*
959  * Read in the disk block containing the directory entry dep came from and
960  * return the address of the buf header, and the address of the directory
961  * entry within the block.
962  */
963 int
readde(struct denode * dep,struct buf ** bpp,struct direntry ** epp)964 readde(struct denode *dep, struct buf **bpp, struct direntry **epp)
965 {
966 
967 	return (readep(dep->de_pmp, dep->de_dirclust, dep->de_diroffset,
968 	    bpp, epp));
969 }
970 
971 /*
972  * Remove a directory entry. At this point the file represented by the
973  * directory entry to be removed is still full length until no one has it
974  * open.  When the file no longer being used msdosfs_inactive() is called
975  * and will truncate the file to 0 length.  When the vnode containing the
976  * denode is needed for some other purpose by VFS it will call
977  * msdosfs_reclaim() which will remove the denode from the denode cache.
978  *
979  * pdep	directory where the entry is removed
980  * dep	file to be removed
981  */
982 int
removede(struct denode * pdep,struct denode * dep)983 removede(struct denode *pdep, struct denode *dep)
984 {
985 	int error;
986 	struct direntry *ep;
987 	struct buf *bp;
988 	daddr_t bn;
989 	int blsize;
990 	struct msdosfsmount *pmp = pdep->de_pmp;
991 	u_long offset = pdep->de_fndoffset;
992 
993 #ifdef MSDOSFS_DEBUG
994 	printf("removede(): filename %s, dep %p, offset %08lx\n",
995 	    dep->de_Name, dep, offset);
996 #endif
997 
998 	dep->de_refcnt--;
999 	offset += sizeof(struct direntry);
1000 	do {
1001 		offset -= sizeof(struct direntry);
1002 		error = pcbmap(pdep, de_cluster(pmp, offset), &bn, 0, &blsize);
1003 		if (error)
1004 			return error;
1005 		error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp);
1006 		if (error) {
1007 			return error;
1008 		}
1009 		ep = bptoep(pmp, bp, offset);
1010 		/*
1011 		 * Check whether, if we came here the second time, i.e.
1012 		 * when underflowing into the previous block, the last
1013 		 * entry in this block is a longfilename entry, too.
1014 		 */
1015 		if (ep->deAttributes != ATTR_WIN95
1016 		    && offset != pdep->de_fndoffset) {
1017 			brelse(bp);
1018 			break;
1019 		}
1020 		offset += sizeof(struct direntry);
1021 		while (1) {
1022 			/*
1023 			 * We are a bit aggressive here in that we delete any Win95
1024 			 * entries preceding this entry, not just the ones we "own".
1025 			 * Since these presumably aren't valid anyway,
1026 			 * there should be no harm.
1027 			 */
1028 			offset -= sizeof(struct direntry);
1029 			ep--->deName[0] = SLOT_DELETED;
1030 			rootde_freed(pdep);
1031 			if ((pmp->pm_flags & MSDOSFSMNT_NOWIN95)
1032 			    || !(offset & pmp->pm_crbomask)
1033 			    || ep->deAttributes != ATTR_WIN95)
1034 				break;
1035 		}
1036 		if (DOINGASYNC(DETOV(pdep)))
1037 			bdwrite(bp);
1038 		else if ((error = bwrite(bp)) != 0)
1039 			return error;
1040 	} while (!(pmp->pm_flags & MSDOSFSMNT_NOWIN95)
1041 	    && !(offset & pmp->pm_crbomask)
1042 	    && offset);
1043 	return 0;
1044 }
1045 
1046 /*
1047  * Create a unique DOS name in dvp
1048  */
1049 int
uniqdosname(struct denode * dep,struct componentname * cnp,u_char * cp)1050 uniqdosname(struct denode *dep, struct componentname *cnp, u_char *cp)
1051 {
1052 	struct msdosfsmount *pmp = dep->de_pmp;
1053 	struct direntry *dentp;
1054 	int gen;
1055 	int blsize;
1056 	u_long cn;
1057 	daddr_t bn;
1058 	struct buf *bp;
1059 	int error;
1060 
1061 	if (pmp->pm_flags & MSDOSFSMNT_SHORTNAME)
1062 		return (unix2dosfn((const u_char *)cnp->cn_nameptr, cp,
1063 		    cnp->cn_namelen, 0, pmp) ? 0 : EINVAL);
1064 
1065 	for (gen = 1;; gen++) {
1066 		/*
1067 		 * Generate DOS name with generation number
1068 		 */
1069 		if (!unix2dosfn((const u_char *)cnp->cn_nameptr, cp,
1070 		    cnp->cn_namelen, gen, pmp))
1071 			return gen == 1 ? EINVAL : EEXIST;
1072 
1073 		/*
1074 		 * Now look for a dir entry with this exact name
1075 		 */
1076 		for (cn = error = 0; !error; cn++) {
1077 			if ((error = pcbmap(dep, cn, &bn, 0, &blsize)) != 0) {
1078 				if (error == E2BIG)	/* EOF reached and not found */
1079 					return 0;
1080 				return error;
1081 			}
1082 			error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp);
1083 			if (error) {
1084 				return error;
1085 			}
1086 			for (dentp = (struct direntry *)bp->b_data;
1087 			     (char *)dentp < bp->b_data + blsize;
1088 			     dentp++) {
1089 				if (dentp->deName[0] == SLOT_EMPTY) {
1090 					/*
1091 					 * Last used entry and not found
1092 					 */
1093 					brelse(bp);
1094 					return 0;
1095 				}
1096 				/*
1097 				 * Ignore volume labels and Win95 entries
1098 				 */
1099 				if (dentp->deAttributes & ATTR_VOLUME)
1100 					continue;
1101 				if (!bcmp(dentp->deName, cp, 11)) {
1102 					error = EEXIST;
1103 					break;
1104 				}
1105 			}
1106 			brelse(bp);
1107 		}
1108 	}
1109 }
1110