e55dc7dbbf4099cc7a48fc76a6868922227f2609
[dragonfly.git] / lib / libstand / dosfs.c
1 /*
2  * Copyright (c) 1996, 1998 Robert Nordier
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in
12  *    the documentation and/or other materials provided with the
13  *    distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS
16  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY
19  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
21  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
23  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
25  * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  *
27  * $FreeBSD: src/lib/libstand/dosfs.c,v 1.4.2.1 2000/05/04 13:47:49 ps Exp $
28  * $DragonFly: src/lib/libstand/dosfs.c,v 1.2 2003/06/17 04:26:51 dillon Exp $
29  */
30
31 /*
32  * Readonly filesystem for Microsoft FAT12/FAT16/FAT32 filesystems,
33  * also supports VFAT.
34  */
35
36 #include <sys/types.h>
37 #include <string.h>
38 #include <stddef.h>
39
40 #include "stand.h"
41
42 #include "dosfs.h"
43
44
45 static int      dos_open(const char *path, struct open_file *fd);
46 static int      dos_close(struct open_file *fd);
47 static int      dos_read(struct open_file *fd, void *buf, size_t size, size_t *resid);
48 static off_t    dos_seek(struct open_file *fd, off_t offset, int whence);
49 static int      dos_stat(struct open_file *fd, struct stat *sb);
50
51 struct fs_ops dosfs_fsops = {
52         "dosfs",
53         dos_open,
54         dos_close,
55         dos_read,
56         null_write,
57         dos_seek,
58         dos_stat,
59         null_readdir
60 };
61
62 #define SECSIZ  512             /* sector size */
63 #define SSHIFT    9             /* SECSIZ shift */
64 #define DEPSEC   16             /* directory entries per sector */
65 #define DSHIFT    4             /* DEPSEC shift */
66 #define LOCLUS    2             /* lowest cluster number */
67
68 /* DOS "BIOS Parameter Block" */
69 typedef struct {
70     u_char secsiz[2];           /* sector size */
71     u_char spc;                 /* sectors per cluster */
72     u_char ressec[2];           /* reserved sectors */
73     u_char fats;                /* FATs */
74     u_char dirents[2];          /* root directory entries */
75     u_char secs[2];             /* total sectors */
76     u_char media;               /* media descriptor */
77     u_char spf[2];              /* sectors per FAT */
78     u_char spt[2];              /* sectors per track */
79     u_char heads[2];            /* drive heads */
80     u_char hidsec[4];           /* hidden sectors */
81     u_char lsecs[4];            /* huge sectors */
82     u_char lspf[4];             /* huge sectors per FAT */
83     u_char xflg[2];             /* flags */
84     u_char vers[2];             /* filesystem version */
85     u_char rdcl[4];             /* root directory start cluster */
86     u_char infs[2];             /* filesystem info sector */
87     u_char bkbs[2];             /* backup boot sector */
88 } DOS_BPB;
89
90 /* Initial portion of DOS boot sector */
91 typedef struct {
92     u_char jmp[3];              /* usually 80x86 'jmp' opcode */
93     u_char oem[8];              /* OEM name and version */
94     DOS_BPB bpb;                /* BPB */
95 } DOS_BS;
96
97 /* Supply missing "." and ".." root directory entries */
98 static const char *const dotstr[2] = {".", ".."};
99 static DOS_DE dot[2] = {
100     {".       ", "   ", FA_DIR, {0, 0, {0, 0}, {0, 0}, {0, 0}, {0, 0}},
101      {0, 0}, {0x21, 0}, {0, 0}, {0, 0, 0, 0}},
102     {"..      ", "   ", FA_DIR, {0, 0, {0, 0}, {0, 0}, {0, 0}, {0, 0}},
103      {0, 0}, {0x21, 0}, {0, 0}, {0, 0, 0, 0}}
104 };
105
106 /* The usual conversion macros to avoid multiplication and division */
107 #define bytsec(n)      ((n) >> SSHIFT)
108 #define secbyt(s)      ((s) << SSHIFT)
109 #define entsec(e)      ((e) >> DSHIFT)
110 #define bytblk(fs, n)  ((n) >> (fs)->bshift)
111 #define blkbyt(fs, b)  ((b) << (fs)->bshift)
112 #define secblk(fs, s)  ((s) >> ((fs)->bshift - SSHIFT))
113 #define blksec(fs, b)  ((b) << ((fs)->bshift - SSHIFT))
114
115 /* Convert cluster number to offset within filesystem */
116 #define blkoff(fs, b) (secbyt((fs)->lsndta) + blkbyt(fs, (b) - LOCLUS))
117
118 /* Convert cluster number to logical sector number */
119 #define blklsn(fs, b)  ((fs)->lsndta + blksec(fs, (b) - LOCLUS))
120
121 /* Convert cluster number to offset within FAT */
122 #define fatoff(sz, c)  ((sz) == 12 ? (c) + ((c) >> 1) :  \
123                         (sz) == 16 ? (c) << 1 :          \
124                         (c) << 2)
125
126 /* Does cluster number reference a valid data cluster? */
127 #define okclus(fs, c)  ((c) >= LOCLUS && (c) <= (fs)->xclus)
128
129 /* Get start cluster from directory entry */
130 #define stclus(sz, de)  ((sz) != 32 ? cv2((de)->clus) :          \
131                          ((u_int)cv2((de)->dex.h_clus) << 16) |  \
132                          cv2((de)->clus))
133     
134 static int dosunmount(DOS_FS *);
135 static int parsebs(DOS_FS *, DOS_BS *);
136 static int namede(DOS_FS *, const char *, DOS_DE **);
137 static int lookup(DOS_FS *, u_int, const char *, DOS_DE **);
138 static void cp_xdnm(u_char *, DOS_XDE *);
139 static void cp_sfn(u_char *, DOS_DE *);
140 static off_t fsize(DOS_FS *, DOS_DE *);
141 static int fatcnt(DOS_FS *, u_int);
142 static int fatget(DOS_FS *, u_int *);
143 static int fatend(u_int, u_int);
144 static int ioread(DOS_FS *, u_int, void *, u_int);
145 static int iobuf(DOS_FS *, u_int);
146 static int ioget(struct open_file *, u_int, void *, u_int);
147
148 /*
149  * Mount DOS filesystem
150  */
151 static int
152 dos_mount(DOS_FS *fs, struct open_file *fd)
153 {
154     int err;
155
156     bzero(fs, sizeof(DOS_FS));
157     fs->fd = fd;
158     if ((err = !(fs->buf = malloc(SECSIZ)) ? errno : 0) ||
159         (err = ioget(fs->fd, 0, fs->buf, 1)) ||
160         (err = parsebs(fs, (DOS_BS *)fs->buf))) {
161         (void)dosunmount(fs);
162         return(err);
163     }
164     return 0;
165 }
166
167 /*
168  * Unmount mounted filesystem
169  */
170 static int
171 dos_unmount(DOS_FS *fs)
172 {
173     int err;
174
175     if (fs->links)
176         return(EBUSY);
177     if ((err = dosunmount(fs)))
178         return(err);
179     return 0;
180 }
181
182 /*
183  * Common code shared by dos_mount() and dos_unmount()
184  */
185 static int
186 dosunmount(DOS_FS *fs)
187 {
188     if (fs->buf)
189         free(fs->buf);
190     free(fs);
191     return(0);
192 }
193
194 /*
195  * Open DOS file
196  */
197 static int
198 dos_open(const char *path, struct open_file *fd)
199 {
200     DOS_DE *de;
201     DOS_FILE *f;
202     DOS_FS *fs;
203     u_int size, clus;
204     int err = 0;
205
206     /* Allocate mount structure, associate with open */
207     fs = malloc(sizeof(DOS_FS));
208     
209     if ((err = dos_mount(fs, fd)))
210         goto out;
211
212     if ((err = namede(fs, path, &de)))
213         goto out;
214
215     clus = stclus(fs->fatsz, de);
216     size = cv4(de->size);
217
218     if ((!(de->attr & FA_DIR) && (!clus != !size)) ||
219         ((de->attr & FA_DIR) && size) ||
220         (clus && !okclus(fs, clus))) {
221         err = EINVAL;
222         goto out;
223     }
224     f = malloc(sizeof(DOS_FILE));
225     bzero(f, sizeof(DOS_FILE));
226     f->fs = fs;
227     fs->links++;
228     f->de = *de;
229     fd->f_fsdata = (void *)f;
230
231  out:
232     return(err);
233 }
234
235 /*
236  * Read from file
237  */
238 static int
239 dos_read(struct open_file *fd, void *buf, size_t nbyte, size_t *resid)
240 {
241     off_t size;
242     u_int nb, off, clus, c, cnt, n;
243     DOS_FILE *f = (DOS_FILE *)fd->f_fsdata;
244     int err = 0;
245
246     nb = (u_int)nbyte;
247     if ((size = fsize(f->fs, &f->de)) == -1)
248         return EINVAL;
249     if (nb > (n = size - f->offset))
250         nb = n;
251     off = f->offset;
252     if ((clus = stclus(f->fs->fatsz, &f->de)))
253         off &= f->fs->bsize - 1;
254     c = f->c;
255     cnt = nb;
256     while (cnt) {
257         n = 0;
258         if (!c) {
259             if ((c = clus))
260                 n = bytblk(f->fs, f->offset);
261         } else if (!off)
262             n++;
263         while (n--) {
264             if ((err = fatget(f->fs, &c)))
265                 goto out;
266             if (!okclus(f->fs, c)) {
267                 err = EINVAL;
268                 goto out;
269             }
270         }
271         if (!clus || (n = f->fs->bsize - off) > cnt)
272             n = cnt;
273         if ((err = ioread(f->fs, (c ? blkoff(f->fs, c) :
274                                       secbyt(f->fs->lsndir)) + off,
275                           buf, n)))
276             goto out;
277         f->offset += n;
278         f->c = c;
279         off = 0;
280         buf += n;
281         cnt -= n;
282     }
283  out:
284     if (resid)
285         *resid = nbyte - nb + cnt;
286     return(err);
287 }
288
289 /*
290  * Reposition within file
291  */
292 static off_t
293 dos_seek(struct open_file *fd, off_t offset, int whence)
294 {
295     off_t off;
296     u_int size;
297     DOS_FILE *f = (DOS_FILE *)fd->f_fsdata;
298
299     size = cv4(f->de.size);
300     switch (whence) {
301     case SEEK_SET:
302         off = 0;
303         break;
304     case SEEK_CUR:
305         off = f->offset;
306         break;
307     case SEEK_END:
308         off = size;
309         break;
310     default:
311         return(-1);
312     }
313     off += offset;
314     if (off < 0 || off > size)
315         return(-1);
316     f->offset = (u_int)off;
317     f->c = 0;
318     return(off);
319 }
320
321 /*
322  * Close open file
323  */
324 static int
325 dos_close(struct open_file *fd)
326 {
327     DOS_FILE *f = (DOS_FILE *)fd->f_fsdata;
328     DOS_FS *fs = f->fs;
329
330     f->fs->links--;
331     free(f);
332     dos_unmount(fs);
333     return 0;
334 }
335
336 /*
337  * Return some stat information on a file.
338  */
339 static int
340 dos_stat(struct open_file *fd, struct stat *sb)
341 {
342     DOS_FILE *f = (DOS_FILE *)fd->f_fsdata;
343
344     /* only important stuff */
345     sb->st_mode = f->de.attr & FA_DIR ? S_IFDIR | 0555 : S_IFREG | 0444;
346     sb->st_nlink = 1;
347     sb->st_uid = 0;
348     sb->st_gid = 0;
349     if ((sb->st_size = fsize(f->fs, &f->de)) == -1)
350         return EINVAL;
351     return (0);
352 }
353
354 /*
355  * Parse DOS boot sector
356  */
357 static int
358 parsebs(DOS_FS *fs, DOS_BS *bs)
359 {
360     u_int sc;
361
362     if ((bs->jmp[0] != 0x69 &&
363          bs->jmp[0] != 0xe9 &&
364          (bs->jmp[0] != 0xeb || bs->jmp[2] != 0x90)) ||
365         bs->bpb.media < 0xf0)
366         return EINVAL;
367     if (cv2(bs->bpb.secsiz) != SECSIZ)
368         return EINVAL;
369     if (!(fs->spc = bs->bpb.spc) || fs->spc & (fs->spc - 1))
370         return EINVAL;
371     fs->bsize = secbyt(fs->spc);
372     fs->bshift = ffs(fs->bsize) - 1;
373     if ((fs->spf = cv2(bs->bpb.spf))) {
374         if (bs->bpb.fats != 2)
375             return EINVAL;
376         if (!(fs->dirents = cv2(bs->bpb.dirents)))
377             return EINVAL;
378     } else {
379         if (!(fs->spf = cv4(bs->bpb.lspf)))
380             return EINVAL;
381         if (!bs->bpb.fats || bs->bpb.fats > 16)
382             return EINVAL;
383         if ((fs->rdcl = cv4(bs->bpb.rdcl)) < LOCLUS)
384             return EINVAL;
385     }
386     if (!(fs->lsnfat = cv2(bs->bpb.ressec)))
387         return EINVAL;
388     fs->lsndir = fs->lsnfat + fs->spf * bs->bpb.fats;
389     fs->lsndta = fs->lsndir + entsec(fs->dirents);
390     if (!(sc = cv2(bs->bpb.secs)) && !(sc = cv4(bs->bpb.lsecs)))
391         return EINVAL;
392     if (fs->lsndta > sc)
393         return EINVAL;
394     if ((fs->xclus = secblk(fs, sc - fs->lsndta) + 1) < LOCLUS)
395         return EINVAL;
396     fs->fatsz = fs->dirents ? fs->xclus < 0xff6 ? 12 : 16 : 32;
397     sc = (secbyt(fs->spf) << 1) / (fs->fatsz >> 2) - 1;
398     if (fs->xclus > sc)
399         fs->xclus = sc;
400     return 0;
401 }
402
403 /*
404  * Return directory entry from path
405  */
406 static int
407 namede(DOS_FS *fs, const char *path, DOS_DE **dep)
408 {
409     char name[256];
410     DOS_DE *de;
411     char *s;
412     size_t n;
413     int err;
414
415     err = 0;
416     de = dot;
417     if (*path == '/')
418         path++;
419     while (*path) {
420         if (!(s = strchr(path, '/')))
421             s = strchr(path, 0);
422         if ((n = s - path) > 255)
423             return ENAMETOOLONG;
424         memcpy(name, path, n);
425         name[n] = 0;
426         path = s;
427         if (!(de->attr & FA_DIR))
428             return ENOTDIR;
429         if ((err = lookup(fs, stclus(fs->fatsz, de), name, &de)))
430             return err;
431         if (*path == '/')
432             path++;
433     }
434     *dep = de;
435     return 0;
436 }
437
438 /*
439  * Lookup path segment
440  */
441 static int
442 lookup(DOS_FS *fs, u_int clus, const char *name, DOS_DE **dep)
443 {
444     static DOS_DIR dir[DEPSEC];
445     u_char lfn[261];
446     u_char sfn[13];
447     u_int nsec, lsec, xdn, chk, sec, ent, x;
448     int err, ok, i;
449
450     if (!clus)
451         for (ent = 0; ent < 2; ent++)
452             if (!strcasecmp(name, dotstr[ent])) {
453                 *dep = dot + ent;
454                 return 0;
455             }
456     if (!clus && fs->fatsz == 32)
457         clus = fs->rdcl;
458     nsec = !clus ? entsec(fs->dirents) : fs->spc;
459     lsec = 0;
460     xdn = chk = 0;
461     for (;;) {
462         if (!clus && !lsec)
463             lsec = fs->lsndir;
464         else if (okclus(fs, clus))
465             lsec = blklsn(fs, clus);
466         else
467             return EINVAL;
468         for (sec = 0; sec < nsec; sec++) {
469             if ((err = ioget(fs->fd, lsec + sec, dir, 1)))
470                 return err;
471             for (ent = 0; ent < DEPSEC; ent++) {
472                 if (!*dir[ent].de.name)
473                     return ENOENT;
474                 if (*dir[ent].de.name != 0xe5) {
475                     if ((dir[ent].de.attr & FA_MASK) == FA_XDE) {
476                         x = dir[ent].xde.seq;
477                         if (x & 0x40 || (x + 1 == xdn &&
478                                          dir[ent].xde.chk == chk)) {
479                             if (x & 0x40) {
480                                 chk = dir[ent].xde.chk;
481                                 x &= ~0x40;
482                             }
483                             if (x >= 1 && x <= 20) {
484                                 cp_xdnm(lfn, &dir[ent].xde);
485                                 xdn = x;
486                                 continue;
487                             }
488                         }
489                     } else if (!(dir[ent].de.attr & FA_LABEL)) {
490                         if ((ok = xdn == 1)) {
491                             for (x = 0, i = 0; i < 11; i++)
492                                 x = ((((x & 1) << 7) | (x >> 1)) +
493                                      dir[ent].de.name[i]) & 0xff;
494                             ok = chk == x &&
495                                 !strcasecmp(name, (const char *)lfn);
496                         }
497                         if (!ok) {
498                             cp_sfn(sfn, &dir[ent].de);
499                             ok = !strcasecmp(name, (const char *)sfn);
500                         }
501                         if (ok) {
502                             *dep = &dir[ent].de;
503                             return 0;
504                         }
505                     }
506                 }
507                 xdn = 0;
508             }
509         }
510         if (!clus)
511             break;
512         if ((err = fatget(fs, &clus)))
513             return err;
514         if (fatend(fs->fatsz, clus))
515             break;
516     }
517     return ENOENT;
518 }
519
520 /*
521  * Copy name from extended directory entry
522  */
523 static void
524 cp_xdnm(u_char *lfn, DOS_XDE *xde)
525 {
526     static struct {
527         u_int off;
528         u_int dim;
529     } ix[3] = {
530         {offsetof(DOS_XDE, name1), sizeof(xde->name1) / 2},
531         {offsetof(DOS_XDE, name2), sizeof(xde->name2) / 2},
532         {offsetof(DOS_XDE, name3), sizeof(xde->name3) / 2}
533     };
534     u_char *p;
535     u_int n, x, c;
536
537     lfn += 13 * ((xde->seq & ~0x40) - 1);
538     for (n = 0; n < 3; n++)
539         for (p = (u_char *)xde + ix[n].off, x = ix[n].dim; x;
540              p += 2, x--) {
541             if ((c = cv2(p)) && (c < 32 || c > 127))
542                 c = '?';
543             if (!(*lfn++ = c))
544                 return;
545         }
546     if (xde->seq & 0x40)
547         *lfn = 0;
548 }
549
550 /*
551  * Copy short filename
552  */
553 static void
554 cp_sfn(u_char *sfn, DOS_DE *de)
555 {
556     u_char *p;
557     int j, i;
558
559     p = sfn;
560     if (*de->name != ' ') {
561         for (j = 7; de->name[j] == ' '; j--);
562         for (i = 0; i <= j; i++)
563             *p++ = de->name[i];
564         if (*de->ext != ' ') {
565             *p++ = '.';
566             for (j = 2; de->ext[j] == ' '; j--);
567             for (i = 0; i <= j; i++)
568                 *p++ = de->ext[i];
569         }
570     }
571     *p = 0;
572     if (*sfn == 5)
573         *sfn = 0xe5;
574 }
575
576 /*
577  * Return size of file in bytes
578  */
579 static off_t
580 fsize(DOS_FS *fs, DOS_DE *de)
581 {
582    u_long size;
583    u_int c;
584    int n;
585
586    if (!(size = cv4(de->size)) && de->attr & FA_DIR) {
587       if (!(c = cv2(de->clus)))
588          size = fs->dirents * sizeof(DOS_DE);
589       else {
590          if ((n = fatcnt(fs, c)) == -1)
591             return n;
592          size = blkbyt(fs, n);
593       }
594    }
595    return size;
596 }
597
598 /*
599  * Count number of clusters in chain
600  */
601 static int
602 fatcnt(DOS_FS *fs, u_int c)
603 {
604    int n;
605
606    for (n = 0; okclus(fs, c); n++)
607       if (fatget(fs, &c))
608           return -1;
609    return fatend(fs->fatsz, c) ? n : -1;
610 }
611
612 /*
613  * Get next cluster in cluster chain
614  */
615 static int
616 fatget(DOS_FS *fs, u_int *c)
617 {
618     u_char buf[4];
619     u_int x;
620     int err;
621
622     err = ioread(fs, secbyt(fs->lsnfat) + fatoff(fs->fatsz, *c), buf,
623                  fs->fatsz != 32 ? 2 : 4);
624     if (err)
625         return err;
626     x = fs->fatsz != 32 ? cv2(buf) : cv4(buf);
627     *c = fs->fatsz == 12 ? *c & 1 ? x >> 4 : x & 0xfff : x;
628     return 0;
629 }
630
631 /*
632  * Is cluster an end-of-chain marker?
633  */
634 static int
635 fatend(u_int sz, u_int c)
636 {
637     return c > (sz == 12 ? 0xff7U : sz == 16 ? 0xfff7U : 0xffffff7);
638 }
639
640 /*
641  * Offset-based I/O primitive
642  */
643 static int
644 ioread(DOS_FS *fs, u_int offset, void *buf, u_int nbyte)
645 {
646     char *s;
647     u_int off, n;
648     int err;
649
650     s = buf;
651     if ((off = offset & (SECSIZ - 1))) {
652         offset -= off;
653         if ((err = iobuf(fs, bytsec(offset))))
654             return err;
655         offset += SECSIZ;
656         if ((n = SECSIZ - off) > nbyte)
657             n = nbyte;
658         memcpy(s, fs->buf + off, n);
659         s += n;
660         nbyte -= n;
661     }
662     n = nbyte & (SECSIZ - 1);
663     if (nbyte -= n) {
664         if ((err = ioget(fs->fd, bytsec(offset), s, bytsec(nbyte))))
665             return err;
666         offset += nbyte;
667         s += nbyte;
668     }
669     if (n) {
670         if ((err = iobuf(fs, bytsec(offset))))
671             return err;
672         memcpy(s, fs->buf, n);
673     }
674     return 0;
675 }
676
677 /*
678  * Buffered sector-based I/O primitive
679  */
680 static int
681 iobuf(DOS_FS *fs, u_int lsec)
682 {
683     int err;
684
685     if (fs->bufsec != lsec) {
686         if ((err = ioget(fs->fd, lsec, fs->buf, 1)))
687             return err;
688         fs->bufsec = lsec;
689     }
690     return 0;
691 }
692
693 /*
694  * Sector-based I/O primitive
695  */
696 static int
697 ioget(struct open_file *fd, u_int lsec, void *buf, u_int nsec)
698 {
699     int err;
700     
701     if ((err = (fd->f_dev->dv_strategy)(fd->f_devdata, F_READ, lsec, 
702                                         secbyt(nsec), buf, NULL)))
703         return(err);
704     return(0);
705 }