1 /* Copyright 1996-1999,2001-2003,2007-2009,2011 Alain Knaff.
2 * This file is part of mtools.
4 * Mtools is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * Mtools is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with Mtools. If not, see <http://www.gnu.org/licenses/>.
18 #include "sysincludes.h"
27 typedef struct File_t {
30 struct Fs_t *Fs; /* Filesystem that this fat file belongs to */
33 int (*map)(struct File_t *this, uint32_t where, uint32_t *len, int mode,
37 /* How many bytes do we project to need for this file
38 (includes those already in FileSize) */
39 uint32_t preallocatedSize;
41 /* How many clusters we have asked the lower layer to reserve
42 for us (only what we will need in the future, excluding already
43 allocated clusters in FileSize) */
44 uint32_t preallocatedClusters;
46 /* Absolute position of first cluster of file */
47 unsigned int FirstAbsCluNr;
49 /* Absolute position of previous cluster */
50 unsigned int PreviousAbsCluNr;
52 /* Relative position of previous cluster */
53 unsigned int PreviousRelCluNr;
56 struct dirCache_t *dcp;
58 unsigned int loopDetectRel;
59 unsigned int loopDetectAbs;
62 static Class_t FileClass;
63 static T_HashTable *filehash;
65 static File_t *getUnbufferedFile(Stream_t *Stream)
67 while(Stream->Class != &FileClass)
68 Stream = Stream->Next;
69 return (File_t *) Stream;
72 Fs_t *getFs(Stream_t *Stream)
74 return getUnbufferedFile(Stream)->Fs;
77 struct dirCache_t **getDirCacheP(Stream_t *Stream)
79 return &getUnbufferedFile(Stream)->dcp;
82 direntry_t *getDirentry(Stream_t *Stream)
84 return &getUnbufferedFile(Stream)->direntry;
88 * Overflow-safe conversion of bytes to cluster
90 static uint32_t filebytesToClusters(uint32_t bytes, uint32_t clus_size) {
91 uint32_t ret = bytes / clus_size;
97 static int recalcPreallocSize(File_t *This)
99 uint32_t currentClusters, neededClusters;
100 unsigned int clus_size;
101 uint32_t neededPrealloc;
105 if(This->FileSize & 0xc0000000) {
106 fprintf(stderr, "Bad filesize\n");
108 if(This->preallocatedSize & 0xc0000000) {
109 fprintf(stderr, "Bad preallocated size %x\n",
110 (int) This->preallocatedSize);
113 clus_size = Fs->cluster_size * Fs->sector_size;
114 currentClusters = filebytesToClusters(This->FileSize, clus_size);
115 neededClusters = filebytesToClusters(This->preallocatedSize, clus_size);
116 if(neededClusters < currentClusters)
119 neededPrealloc = neededClusters - currentClusters;
120 if(neededPrealloc > This->preallocatedClusters) {
121 int r = fsPreallocateClusters(Fs, neededPrealloc-
122 This->preallocatedClusters);
126 fsReleasePreallocateClusters(Fs, This->preallocatedClusters -
129 This->preallocatedClusters = neededPrealloc;
133 static int _loopDetect(unsigned int *oldrel, unsigned int rel,
134 unsigned int *oldabs, unsigned int absol)
136 if(*oldrel && rel > *oldrel && absol == *oldabs) {
137 fprintf(stderr, "loop detected! oldrel=%d newrel=%d abs=%d\n",
138 *oldrel, rel, absol);
142 if(rel >= 2 * *oldrel + 1) {
150 static int loopDetect(File_t *This, unsigned int rel, unsigned int absol)
152 return _loopDetect(&This->loopDetectRel, rel, &This->loopDetectAbs, absol);
155 static unsigned int _countBlocks(Fs_t *This, unsigned int block)
158 unsigned int rel, oldabs, oldrel;
162 oldabs = oldrel = rel = 0;
164 while (block <= This->last_fat && block != 1 && block) {
166 block = fatDecode(This, block);
168 if(_loopDetect(&oldrel, rel, &oldabs, block) < 0)
174 unsigned int countBlocks(Stream_t *Dir, unsigned int block)
176 Stream_t *Stream = GetFs(Dir);
179 return _countBlocks(This, block);
182 /* returns number of bytes in a directory. Represents a file size, and
183 * can hence be not bigger than 2^32
185 static uint32_t countBytes(Stream_t *Dir, unsigned int block)
187 Stream_t *Stream = GetFs(Dir);
190 return _countBlocks(This, block) *
191 This->sector_size * This->cluster_size;
194 void printFat(Stream_t *Stream)
196 File_t *This = getUnbufferedFile(Stream);
199 unsigned long begin, end;
202 n = This->FirstAbsCluNr;
204 printf("Root directory or empty file\n");
212 if (first || n != end+1) {
219 printf("<%lu", begin);
224 n = fatDecode(This->Fs, n);
226 if(loopDetect(This, rel, n) < 0)
228 } while (n <= This->Fs->last_fat && n != 1);
236 void printFatWithOffset(Stream_t *Stream, off_t offset) {
237 File_t *This = getUnbufferedFile(Stream);
242 n = This->FirstAbsCluNr;
244 printf("Root directory or empty file\n");
248 clusSize = This->Fs->cluster_size * This->Fs->sector_size;
251 while(offset >= clusSize) {
252 n = fatDecode(This->Fs, n);
254 if(loopDetect(This, rel, n) < 0)
256 if(n > This->Fs->last_fat)
261 printf("%lu", (unsigned long) n);
264 static int normal_map(File_t *This, uint32_t where, uint32_t *len, int mode,
269 uint32_t NrClu; /* number of clusters to read */
278 clus_size = Fs->cluster_size * Fs->sector_size;
279 offset = where % clus_size;
282 maximize(*len, This->FileSize - where);
286 if (This->FirstAbsCluNr < 2){
287 if( mode == MT_READ || *len == 0){
291 NewCluNr = get_next_free_cluster(This->Fs, 1);
296 hash_remove(filehash, (void *) This, This->hint);
297 This->FirstAbsCluNr = NewCluNr;
298 hash_add(filehash, (void *) This, &This->hint);
299 fatAllocate(This->Fs, NewCluNr, Fs->end_fat);
302 RelCluNr = where / clus_size;
304 if (RelCluNr >= This->PreviousRelCluNr){
305 CurCluNr = This->PreviousRelCluNr;
306 AbsCluNr = This->PreviousAbsCluNr;
309 AbsCluNr = This->FirstAbsCluNr;
313 NrClu = (offset + *len - 1) / clus_size;
314 while (CurCluNr <= RelCluNr + NrClu){
315 if (CurCluNr == RelCluNr){
316 /* we have reached the beginning of our zone. Save
318 This->PreviousRelCluNr = RelCluNr;
319 This->PreviousAbsCluNr = AbsCluNr;
321 NewCluNr = fatDecode(This->Fs, AbsCluNr);
322 if (NewCluNr == 1 || NewCluNr == 0){
323 fprintf(stderr,"Fat problem while decoding %d %x\n",
327 if(CurCluNr == RelCluNr + NrClu)
329 if (NewCluNr > Fs->last_fat && mode == MT_WRITE){
330 /* if at end, and writing, extend it */
331 NewCluNr = get_next_free_cluster(This->Fs, AbsCluNr);
332 if (NewCluNr == 1 ){ /* no more space */
336 fatAppend(This->Fs, AbsCluNr, NewCluNr);
339 if (CurCluNr < RelCluNr && NewCluNr > Fs->last_fat){
344 if (CurCluNr >= RelCluNr && NewCluNr != AbsCluNr + 1)
348 if(loopDetect(This, CurCluNr, AbsCluNr)) {
354 maximize(*len, (1 + CurCluNr - RelCluNr) * clus_size - offset);
359 end >= This->FileSize) {
360 *len += ROUND_UP(end, clus_size) - end;
363 if((*len + offset) / clus_size + This->PreviousAbsCluNr-2 >
365 fprintf(stderr, "cluster too big\n");
369 *res = sectorsToBytes((Stream_t*)Fs,
370 (This->PreviousAbsCluNr-2) * Fs->cluster_size +
371 Fs->clus_start) + offset;
376 static int root_map(File_t *This, uint32_t where, uint32_t *len,
377 int mode UNUSEDP, mt_off_t *res)
381 if(Fs->dir_len * Fs->sector_size + 0u < (size_t) where) {
387 maximize(*len, Fs->dir_len * Fs->sector_size - where);
391 *res = sectorsToBytes((Stream_t*)Fs, Fs->dir_start) + where;
396 static ssize_t read_file(Stream_t *Stream, char *buf, mt_off_t iwhere,
402 uint32_t where = truncMtOffTo32u(iwhere);
403 uint32_t len = truncSizeTo32u(ilen);
405 Stream_t *Disk = This->Fs->Next;
407 err = This->map(This, where, &len, MT_READ, &pos);
410 return READS(Disk, buf, pos, len);
413 static ssize_t write_file(Stream_t *Stream, char *buf,
414 mt_off_t iwhere, size_t ilen)
419 uint32_t requestedLen;
420 uint32_t bytesWritten;
421 Stream_t *Disk = This->Fs->Next;
422 uint32_t where = truncMtOffTo32u(iwhere);
426 if(iwhere+(mt_off_t)ilen > UINT32_MAX) {
427 ilen=(size_t) (UINT32_MAX-iwhere);
429 len = truncSizeTo32u(ilen);
431 err = This->map(This, where, &len, MT_WRITE, &pos);
435 ret = force_write(Disk, buf, pos, len);
437 ret = WRITES(Disk, buf, pos, len);
441 if((uint32_t)ret > requestedLen)
442 bytesWritten = requestedLen;
444 bytesWritten = requestedLen;
445 if (where + bytesWritten > This->FileSize )
446 This->FileSize = where + bytesWritten;
447 recalcPreallocSize(This);
453 * Convert an MSDOS time & date stamp to the Unix time() format
456 static int month[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334,
458 static __inline__ time_t conv_stamp(struct directory *dir)
464 accum = DOS_YEAR(dir) - 1970; /* years past */
467 accum = accum * 365L + month[DOS_MONTH(dir)-1] + DOS_DAY(dir);
470 accum += (DOS_YEAR(dir) - 1972) / 4L;
472 /* back off 1 day if before 29 Feb */
473 if (!(DOS_YEAR(dir) % 4) && DOS_MONTH(dir) < 3)
475 accum = accum * 24L + DOS_HOUR(dir); /* hours passed */
476 accum = accum * 60L + DOS_MINUTE(dir); /* minutes passed */
477 accum = accum * 60L + DOS_SEC(dir); /* seconds passed */
479 /* correct for Time Zone */
480 #ifdef HAVE_GETTIMEOFDAY
485 gettimeofday(&tv, &tz);
486 tzone = tz.tz_minuteswest * 60L;
489 #if defined HAVE_TZSET && !defined OS_mingw32msvc
491 #if !defined OS_ultrix && !defined OS_cygwin
492 /* Ultrix defines this to be a different type */
493 extern long timezone;
496 tzone = (long) timezone;
500 #endif /* HAVE_TZSET */
501 #endif /* HAVE_GETTIMEOFDAY */
505 /* correct for Daylight Saving Time */
507 tmbuf = localtime(&tmp);
509 dst = (tmbuf->tm_isdst) ? (-60L * 60L) : 0L;
516 static int get_file_data(Stream_t *Stream, time_t *date, mt_size_t *size,
517 int *type, uint32_t *address)
522 *date = conv_stamp(& This->direntry.dir);
524 *size = (mt_size_t) This->FileSize;
526 *type = This->direntry.dir.attr & ATTR_DIR;
528 *address = This->FirstAbsCluNr;
533 static int free_file(Stream_t *Stream)
537 fsReleasePreallocateClusters(Fs, This->preallocatedClusters);
538 FREE(&This->direntry.Dir);
539 freeDirCache(Stream);
540 return hash_remove(filehash, (void *) Stream, This->hint);
544 static int flush_file(Stream_t *Stream)
547 direntry_t *entry = &This->direntry;
549 if(isRootDir(Stream)) {
553 if(This->FirstAbsCluNr != getStart(entry->Dir, &entry->dir)) {
554 set_word(entry->dir.start, This->FirstAbsCluNr & 0xffff);
555 set_word(entry->dir.startHi, This->FirstAbsCluNr >> 16);
562 static int pre_allocate_file(Stream_t *Stream, mt_off_t isize)
566 uint32_t size = truncMtOffTo32u(isize);
568 if(size > This->FileSize &&
569 size > This->preallocatedSize) {
570 This->preallocatedSize = size;
571 return recalcPreallocSize(This);
576 static Class_t FileClass = {
579 flush_file, /* flush */
580 free_file, /* free */
584 get_dosConvert_pass_through,
588 static unsigned int getAbsCluNr(File_t *This)
590 if(This->FirstAbsCluNr)
591 return This->FirstAbsCluNr;
592 if(isRootDir((Stream_t *) This))
597 static uint32_t func1(void *Stream)
601 return getAbsCluNr(This) ^ (uint32_t) (unsigned long) This->Fs;
604 static uint32_t func2(void *Stream)
608 return getAbsCluNr(This);
611 static int comp(void *Stream, void *Stream2)
615 File_t *This2 = (File_t *) Stream2;
617 return This->Fs != This2->Fs ||
618 getAbsCluNr(This) != getAbsCluNr(This2);
621 static void init_hash(void)
623 static int is_initialised=0;
626 make_ht(func1, func2, comp, 20, &filehash);
632 static Stream_t *_internalFileOpen(Stream_t *Dir, unsigned int first,
633 uint32_t size, direntry_t *entry)
635 Stream_t *Stream = GetFs(Dir);
644 /* we use the illegal cluster 1 to mark newly created files.
645 * do not manage those by hashtable */
647 Pattern.Class = &FileClass;
648 if(first || (entry && !IS_DIR(entry)))
649 Pattern.map = normal_map;
651 Pattern.map = root_map;
652 Pattern.FirstAbsCluNr = first;
653 Pattern.loopDetectRel = 0;
654 Pattern.loopDetectAbs = first;
655 if(!hash_lookup(filehash, (T_HashTableEl) &Pattern,
656 (T_HashTableEl **)&File, 0)){
659 return (Stream_t *) File;
667 File->preallocatedClusters = 0;
668 File->preallocatedSize = 0;
669 /* memorize dir for date and attrib */
670 File->direntry = *entry;
671 if(entry->entry == -3)
672 File->direntry.Dir = (Stream_t *) File; /* root directory */
674 COPY(File->direntry.Dir);
676 File->Class = &FileClass;
678 if(first || (entry && !IS_DIR(entry)))
679 File->map = normal_map;
681 File->map = root_map; /* FAT 12/16 root directory */
683 File->FirstAbsCluNr = 0;
685 File->FirstAbsCluNr = first;
687 File->loopDetectRel = 0;
688 File->loopDetectAbs = 0;
690 File->PreviousRelCluNr = 0xffff;
691 File->FileSize = size;
694 hash_add(filehash, (void *) File, &File->hint);
695 return (Stream_t *) File;
698 Stream_t *OpenRoot(Stream_t *Dir)
705 memset(&entry, 0, sizeof(direntry_t));
707 num = fat32RootCluster(Dir);
709 /* make the directory entry */
711 entry.name[0] = '\0';
712 mk_entry_from_base("/", ATTR_DIR, num, 0, 0, &entry.dir);
715 size = countBytes(Dir, num);
717 Fs_t *Fs = (Fs_t *) GetFs(Dir);
718 size = Fs->dir_len * Fs->sector_size;
720 file = _internalFileOpen(Dir, num, size, &entry);
726 Stream_t *OpenFileByDirentry(direntry_t *entry)
732 first = getStart(entry->Dir, &entry->dir);
734 if(!first && IS_DIR(entry))
735 return OpenRoot(entry->Dir);
737 size = countBytes(entry->Dir, first);
739 size = FILE_SIZE(&entry->dir);
740 file = _internalFileOpen(entry->Dir, first, size, entry);
751 int isRootDir(Stream_t *Stream)
753 File_t *This = getUnbufferedFile(Stream);
755 return This->map == root_map;