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(Fs,
370 (This->PreviousAbsCluNr-2) * Fs->cluster_size +
371 Fs->clus_start) + to_mt_off_t(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 < where) {
387 maximize(*len, Fs->dir_len * Fs->sector_size - where);
391 *res = sectorsToBytes(Fs, Fs->dir_start) +
397 static ssize_t read_file(Stream_t *Stream, char *buf, mt_off_t iwhere,
403 uint32_t where = truncMtOffTo32u(iwhere);
404 uint32_t len = truncSizeTo32u(ilen);
406 Stream_t *Disk = This->Fs->Next;
408 err = This->map(This, where, &len, MT_READ, &pos);
411 return READS(Disk, buf, pos, len);
414 static ssize_t write_file(Stream_t *Stream, char *buf,
415 mt_off_t iwhere, size_t ilen)
420 uint32_t requestedLen;
421 uint32_t bytesWritten;
422 Stream_t *Disk = This->Fs->Next;
423 uint32_t where = truncMtOffTo32u(iwhere);
424 uint32_t maxLen = UINT32_MAX-where;
431 len = (uint32_t) ilen;
433 err = This->map(This, where, &len, MT_WRITE, &pos);
437 ret = force_write(Disk, buf, pos, len);
439 ret = WRITES(Disk, buf, pos, len);
443 if((uint32_t)ret > requestedLen)
444 bytesWritten = requestedLen;
446 bytesWritten = requestedLen;
447 if (where + bytesWritten > This->FileSize )
448 This->FileSize = where + bytesWritten;
449 recalcPreallocSize(This);
455 * Convert an MSDOS time & date stamp to the Unix time() format
458 static int month[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334,
460 static __inline__ time_t conv_stamp(struct directory *dir)
466 accum = DOS_YEAR(dir) - 1970; /* years past */
469 accum = accum * 365L + month[DOS_MONTH(dir)-1] + DOS_DAY(dir);
472 accum += (DOS_YEAR(dir) - 1972) / 4L;
474 /* back off 1 day if before 29 Feb */
475 if (!(DOS_YEAR(dir) % 4) && DOS_MONTH(dir) < 3)
477 accum = accum * 24L + DOS_HOUR(dir); /* hours passed */
478 accum = accum * 60L + DOS_MINUTE(dir); /* minutes passed */
479 accum = accum * 60L + DOS_SEC(dir); /* seconds passed */
481 /* correct for Time Zone */
482 #ifdef HAVE_GETTIMEOFDAY
487 gettimeofday(&tv, &tz);
488 tzone = tz.tz_minuteswest * 60L;
491 #if defined HAVE_TZSET && !defined OS_mingw32msvc
493 #if !defined OS_ultrix && !defined OS_cygwin
494 /* Ultrix defines this to be a different type */
495 extern long timezone;
498 tzone = (long) timezone;
502 #endif /* HAVE_TZSET */
503 #endif /* HAVE_GETTIMEOFDAY */
507 /* correct for Daylight Saving Time */
509 tmbuf = localtime(&tmp);
511 dst = (tmbuf->tm_isdst) ? (-60L * 60L) : 0L;
518 static int get_file_data(Stream_t *Stream, time_t *date, mt_off_t *size,
519 int *type, uint32_t *address)
524 *date = conv_stamp(& This->direntry.dir);
526 *size = to_mt_off_t(This->FileSize);
528 *type = This->direntry.dir.attr & ATTR_DIR;
530 *address = This->FirstAbsCluNr;
535 static int free_file(Stream_t *Stream)
539 fsReleasePreallocateClusters(Fs, This->preallocatedClusters);
540 FREE(&This->direntry.Dir);
541 freeDirCache(Stream);
542 return hash_remove(filehash, (void *) Stream, This->hint);
546 static int flush_file(Stream_t *Stream)
549 direntry_t *entry = &This->direntry;
551 if(isRootDir(Stream)) {
555 if(This->FirstAbsCluNr != getStart(entry->Dir, &entry->dir)) {
556 set_word(entry->dir.start, This->FirstAbsCluNr & 0xffff);
557 set_word(entry->dir.startHi, This->FirstAbsCluNr >> 16);
564 static int pre_allocate_file(Stream_t *Stream, mt_off_t isize)
568 uint32_t size = truncMtOffTo32u(isize);
570 if(size > This->FileSize &&
571 size > This->preallocatedSize) {
572 This->preallocatedSize = size;
573 return recalcPreallocSize(This);
578 static Class_t FileClass = {
581 flush_file, /* flush */
582 free_file, /* free */
586 get_dosConvert_pass_through,
590 static unsigned int getAbsCluNr(File_t *This)
592 if(This->FirstAbsCluNr)
593 return This->FirstAbsCluNr;
594 if(isRootDir((Stream_t *) This))
599 static uint32_t func1(void *Stream)
603 return getAbsCluNr(This) ^ (uint32_t) (unsigned long) This->Fs;
606 static uint32_t func2(void *Stream)
610 return getAbsCluNr(This);
613 static int comp(void *Stream, void *Stream2)
617 File_t *This2 = (File_t *) Stream2;
619 return This->Fs != This2->Fs ||
620 getAbsCluNr(This) != getAbsCluNr(This2);
623 static void init_hash(void)
625 static int is_initialised=0;
628 make_ht(func1, func2, comp, 20, &filehash);
634 static Stream_t *_internalFileOpen(Stream_t *Dir, unsigned int first,
635 uint32_t size, direntry_t *entry)
637 Stream_t *Stream = GetFs(Dir);
646 /* we use the illegal cluster 1 to mark newly created files.
647 * do not manage those by hashtable */
649 Pattern.Class = &FileClass;
650 if(first || (entry && !IS_DIR(entry)))
651 Pattern.map = normal_map;
653 Pattern.map = root_map;
654 Pattern.FirstAbsCluNr = first;
655 Pattern.loopDetectRel = 0;
656 Pattern.loopDetectAbs = first;
657 if(!hash_lookup(filehash, (T_HashTableEl) &Pattern,
658 (T_HashTableEl **)&File, 0)){
661 return (Stream_t *) File;
669 File->preallocatedClusters = 0;
670 File->preallocatedSize = 0;
671 /* memorize dir for date and attrib */
672 File->direntry = *entry;
673 if(entry->entry == -3)
674 File->direntry.Dir = (Stream_t *) File; /* root directory */
676 COPY(File->direntry.Dir);
678 File->Class = &FileClass;
680 if(first || (entry && !IS_DIR(entry)))
681 File->map = normal_map;
683 File->map = root_map; /* FAT 12/16 root directory */
685 File->FirstAbsCluNr = 0;
687 File->FirstAbsCluNr = first;
689 File->loopDetectRel = 0;
690 File->loopDetectAbs = 0;
692 File->PreviousRelCluNr = 0xffff;
693 File->FileSize = size;
696 hash_add(filehash, (void *) File, &File->hint);
697 return (Stream_t *) File;
700 Stream_t *OpenRoot(Stream_t *Dir)
707 memset(&entry, 0, sizeof(direntry_t));
709 num = fat32RootCluster(Dir);
711 /* make the directory entry */
713 entry.name[0] = '\0';
714 mk_entry_from_base("/", ATTR_DIR, num, 0, 0, &entry.dir);
717 size = countBytes(Dir, num);
719 Fs_t *Fs = (Fs_t *) GetFs(Dir);
720 size = Fs->dir_len * Fs->sector_size;
722 file = _internalFileOpen(Dir, num, size, &entry);
728 Stream_t *OpenFileByDirentry(direntry_t *entry)
734 first = getStart(entry->Dir, &entry->dir);
736 if(!first && IS_DIR(entry))
737 return OpenRoot(entry->Dir);
739 size = countBytes(entry->Dir, first);
741 size = FILE_SIZE(&entry->dir);
742 file = _internalFileOpen(entry->Dir, first, size, entry);
753 int isRootDir(Stream_t *Stream)
755 File_t *This = getUnbufferedFile(Stream);
757 return This->map == root_map;