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