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