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, off_t where, size_t *len, int mode,
37 size_t preallocatedSize;
38 int preallocatedClusters;
40 /* Absolute position of first cluster of file */
41 unsigned int FirstAbsCluNr;
43 /* Absolute position of previous cluster */
44 unsigned int PreviousAbsCluNr;
46 /* Relative position of previous cluster */
47 unsigned int PreviousRelCluNr;
50 struct dirCache_t *dcp;
52 unsigned int loopDetectRel;
53 unsigned int loopDetectAbs;
56 static Class_t FileClass;
57 T_HashTable *filehash;
59 static File_t *getUnbufferedFile(Stream_t *Stream)
61 while(Stream->Class != &FileClass)
62 Stream = Stream->Next;
63 return (File_t *) Stream;
66 Fs_t *getFs(Stream_t *Stream)
68 return getUnbufferedFile(Stream)->Fs;
71 struct dirCache_t **getDirCacheP(Stream_t *Stream)
73 return &getUnbufferedFile(Stream)->dcp;
76 direntry_t *getDirentry(Stream_t *Stream)
78 return &getUnbufferedFile(Stream)->direntry;
82 static int recalcPreallocSize(File_t *This)
84 size_t currentClusters, neededClusters;
91 if(This->FileSize & 0xc0000000) {
92 fprintf(stderr, "Bad filesize\n");
94 if(This->preallocatedSize & 0xc0000000) {
95 fprintf(stderr, "Bad preallocated size %x\n",
96 (int) This->preallocatedSize);
99 clus_size = Fs->cluster_size * Fs->sector_size;
101 currentClusters = (This->FileSize + clus_size - 1) / clus_size;
102 neededClusters = (This->preallocatedSize + clus_size - 1) / clus_size;
103 neededPrealloc = neededClusters - currentClusters;
104 if(neededPrealloc < 0)
106 r = fsPreallocateClusters(Fs, neededPrealloc - This->preallocatedClusters);
109 This->preallocatedClusters = neededPrealloc;
113 static int _loopDetect(unsigned int *oldrel, unsigned int rel,
114 unsigned int *oldabs, unsigned int absol)
116 if(*oldrel && rel > *oldrel && absol == *oldabs) {
117 fprintf(stderr, "loop detected! oldrel=%d newrel=%d abs=%d\n",
118 *oldrel, rel, absol);
122 if(rel >= 2 * *oldrel + 1) {
130 static int loopDetect(File_t *This, unsigned int rel, unsigned int absol)
132 return _loopDetect(&This->loopDetectRel, rel, &This->loopDetectAbs, absol);
135 static unsigned int _countBlocks(Fs_t *This, unsigned int block)
138 unsigned int rel, oldabs, oldrel;
142 oldabs = oldrel = rel = 0;
144 while (block <= This->last_fat && block != 1 && block) {
146 block = fatDecode(This, block);
148 if(_loopDetect(&oldrel, rel, &oldabs, block) < 0)
154 unsigned int countBlocks(Stream_t *Dir, unsigned int block)
156 Stream_t *Stream = GetFs(Dir);
159 return _countBlocks(This, block);
162 /* returns number of bytes in a directory. Represents a file size, and
163 * can hence be not bigger than 2^32
165 static size_t countBytes(Stream_t *Dir, unsigned int block)
167 Stream_t *Stream = GetFs(Dir);
170 return _countBlocks(This, block) *
171 This->sector_size * This->cluster_size;
174 void printFat(Stream_t *Stream)
176 File_t *This = getUnbufferedFile(Stream);
179 unsigned long begin, end;
182 n = This->FirstAbsCluNr;
184 printf("Root directory or empty file\n");
192 if (first || n != end+1) {
199 printf("<%lu", begin);
204 n = fatDecode(This->Fs, n);
206 if(loopDetect(This, rel, n) < 0)
208 } while (n <= This->Fs->last_fat && n != 1);
216 void printFatWithOffset(Stream_t *Stream, off_t offset) {
217 File_t *This = getUnbufferedFile(Stream);
222 n = This->FirstAbsCluNr;
224 printf("Root directory or empty file\n");
228 clusSize = This->Fs->cluster_size * This->Fs->sector_size;
231 while(offset >= clusSize) {
232 n = fatDecode(This->Fs, n);
234 if(loopDetect(This, rel, n) < 0)
236 if(n > This->Fs->last_fat)
244 static int normal_map(File_t *This, off_t where, size_t *len, int mode,
249 int NrClu; /* number of clusters to read */
250 unsigned int RelCluNr;
251 unsigned int CurCluNr;
252 unsigned int NewCluNr;
253 unsigned int AbsCluNr;
258 clus_size = Fs->cluster_size * Fs->sector_size;
259 offset = where % clus_size;
262 maximize(*len, This->FileSize - where);
266 if (This->FirstAbsCluNr < 2){
267 if( mode == MT_READ || *len == 0){
271 NewCluNr = get_next_free_cluster(This->Fs, 1);
276 hash_remove(filehash, (void *) This, This->hint);
277 This->FirstAbsCluNr = NewCluNr;
278 hash_add(filehash, (void *) This, &This->hint);
279 fatAllocate(This->Fs, NewCluNr, Fs->end_fat);
282 RelCluNr = where / clus_size;
284 if (RelCluNr >= This->PreviousRelCluNr){
285 CurCluNr = This->PreviousRelCluNr;
286 AbsCluNr = This->PreviousAbsCluNr;
289 AbsCluNr = This->FirstAbsCluNr;
293 NrClu = (offset + *len - 1) / clus_size;
294 while (CurCluNr <= RelCluNr + NrClu){
295 if (CurCluNr == RelCluNr){
296 /* we have reached the beginning of our zone. Save
298 This->PreviousRelCluNr = RelCluNr;
299 This->PreviousAbsCluNr = AbsCluNr;
301 NewCluNr = fatDecode(This->Fs, AbsCluNr);
302 if (NewCluNr == 1 || NewCluNr == 0){
303 fprintf(stderr,"Fat problem while decoding %d %x\n",
307 if(CurCluNr == RelCluNr + NrClu)
309 if (NewCluNr > Fs->last_fat && mode == MT_WRITE){
310 /* if at end, and writing, extend it */
311 NewCluNr = get_next_free_cluster(This->Fs, AbsCluNr);
312 if (NewCluNr == 1 ){ /* no more space */
316 fatAppend(This->Fs, AbsCluNr, NewCluNr);
319 if (CurCluNr < RelCluNr && NewCluNr > Fs->last_fat){
324 if (CurCluNr >= RelCluNr && NewCluNr != AbsCluNr + 1)
328 if(loopDetect(This, CurCluNr, AbsCluNr)) {
334 maximize(*len, (1 + CurCluNr - RelCluNr) * clus_size - offset);
339 end >= This->FileSize) {
340 *len += ROUND_UP(end, clus_size) - end;
343 if((*len + offset) / clus_size + This->PreviousAbsCluNr-2 >
345 fprintf(stderr, "cluster too big\n");
349 *res = sectorsToBytes((Stream_t*)Fs,
350 (This->PreviousAbsCluNr-2) * Fs->cluster_size +
351 Fs->clus_start) + offset;
356 static int root_map(File_t *This, off_t where, size_t *len, int mode UNUSEDP,
361 if(Fs->dir_len * Fs->sector_size < (size_t) where) {
367 maximize(*len, Fs->dir_len * Fs->sector_size - where);
371 *res = sectorsToBytes((Stream_t*)Fs, Fs->dir_start) + where;
376 static int read_file(Stream_t *Stream, char *buf, mt_off_t iwhere,
382 off_t where = truncBytes32(iwhere);
384 Stream_t *Disk = This->Fs->Next;
386 err = This->map(This, where, &len, MT_READ, &pos);
389 return READS(Disk, buf, pos, len);
392 static int write_file(Stream_t *Stream, char *buf, mt_off_t iwhere, size_t len)
398 Stream_t *Disk = This->Fs->Next;
399 off_t where = truncBytes32(iwhere);
403 err = This->map(This, where, &len, MT_WRITE, &pos);
407 ret = force_write(Disk, buf, pos, len);
409 ret = WRITES(Disk, buf, pos, len);
410 if(ret > (signed int) requestedLen)
413 where + ret > (off_t) This->FileSize )
414 This->FileSize = where + ret;
415 recalcPreallocSize(This);
421 * Convert an MSDOS time & date stamp to the Unix time() format
424 static int month[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334,
426 static __inline__ time_t conv_stamp(struct directory *dir)
432 accum = DOS_YEAR(dir) - 1970; /* years past */
435 accum = accum * 365L + month[DOS_MONTH(dir)-1] + DOS_DAY(dir);
438 accum += (DOS_YEAR(dir) - 1972) / 4L;
440 /* back off 1 day if before 29 Feb */
441 if (!(DOS_YEAR(dir) % 4) && DOS_MONTH(dir) < 3)
443 accum = accum * 24L + DOS_HOUR(dir); /* hours passed */
444 accum = accum * 60L + DOS_MINUTE(dir); /* minutes passed */
445 accum = accum * 60L + DOS_SEC(dir); /* seconds passed */
447 /* correct for Time Zone */
448 #ifdef HAVE_GETTIMEOFDAY
453 gettimeofday(&tv, &tz);
454 tzone = tz.tz_minuteswest * 60L;
457 #if defined HAVE_TZSET && !defined OS_mingw32msvc
459 #if !defined OS_ultrix && !defined OS_cygwin
460 /* Ultrix defines this to be a different type */
461 extern long timezone;
464 tzone = (long) timezone;
468 #endif /* HAVE_TZSET */
469 #endif /* HAVE_GETTIMEOFDAY */
473 /* correct for Daylight Saving Time */
475 tmbuf = localtime(&tmp);
477 dst = (tmbuf->tm_isdst) ? (-60L * 60L) : 0L;
484 static int get_file_data(Stream_t *Stream, time_t *date, mt_size_t *size,
485 int *type, int *address)
490 *date = conv_stamp(& This->direntry.dir);
492 *size = (mt_size_t) This->FileSize;
494 *type = This->direntry.dir.attr & ATTR_DIR;
496 *address = This->FirstAbsCluNr;
501 static int free_file(Stream_t *Stream)
505 fsPreallocateClusters(Fs, -This->preallocatedClusters);
506 FREE(&This->direntry.Dir);
507 freeDirCache(Stream);
508 return hash_remove(filehash, (void *) Stream, This->hint);
512 static int flush_file(Stream_t *Stream)
515 direntry_t *entry = &This->direntry;
517 if(isRootDir(Stream)) {
521 if(This->FirstAbsCluNr != getStart(entry->Dir, &entry->dir)) {
522 set_word(entry->dir.start, This->FirstAbsCluNr & 0xffff);
523 set_word(entry->dir.startHi, This->FirstAbsCluNr >> 16);
530 static int pre_allocate_file(Stream_t *Stream, mt_size_t isize)
534 size_t size = truncBytes32(isize);
536 if(size > This->FileSize &&
537 size > This->preallocatedSize) {
538 This->preallocatedSize = size;
539 return recalcPreallocSize(This);
544 static Class_t FileClass = {
547 flush_file, /* flush */
548 free_file, /* free */
552 get_dosConvert_pass_through
555 static unsigned int getAbsCluNr(File_t *This)
557 if(This->FirstAbsCluNr)
558 return This->FirstAbsCluNr;
559 if(isRootDir((Stream_t *) This))
564 static unsigned int func1(void *Stream)
568 return getAbsCluNr(This) ^ (long) This->Fs;
571 static unsigned int func2(void *Stream)
575 return getAbsCluNr(This);
578 static int comp(void *Stream, void *Stream2)
582 File_t *This2 = (File_t *) Stream2;
584 return This->Fs != This2->Fs ||
585 getAbsCluNr(This) != getAbsCluNr(This2);
588 static void init_hash(void)
590 static int is_initialised=0;
593 make_ht(func1, func2, comp, 20, &filehash);
599 static Stream_t *_internalFileOpen(Stream_t *Dir, unsigned int first,
600 size_t size, direntry_t *entry)
602 Stream_t *Stream = GetFs(Dir);
611 /* we use the illegal cluster 1 to mark newly created files.
612 * do not manage those by hashtable */
614 Pattern.Class = &FileClass;
615 if(first || (entry && !IS_DIR(entry)))
616 Pattern.map = normal_map;
618 Pattern.map = root_map;
619 Pattern.FirstAbsCluNr = first;
620 Pattern.loopDetectRel = 0;
621 Pattern.loopDetectAbs = first;
622 if(!hash_lookup(filehash, (T_HashTableEl) &Pattern,
623 (T_HashTableEl **)&File, 0)){
626 return (Stream_t *) File;
634 File->preallocatedClusters = 0;
635 File->preallocatedSize = 0;
636 /* memorize dir for date and attrib */
637 File->direntry = *entry;
638 if(entry->entry == -3)
639 File->direntry.Dir = (Stream_t *) File; /* root directory */
641 COPY(File->direntry.Dir);
643 File->Class = &FileClass;
645 if(first || (entry && !IS_DIR(entry)))
646 File->map = normal_map;
648 File->map = root_map; /* FAT 12/16 root directory */
650 File->FirstAbsCluNr = 0;
652 File->FirstAbsCluNr = first;
654 File->loopDetectRel = 0;
655 File->loopDetectAbs = 0;
657 File->PreviousRelCluNr = 0xffff;
658 File->FileSize = size;
661 hash_add(filehash, (void *) File, &File->hint);
662 return (Stream_t *) File;
665 Stream_t *OpenRoot(Stream_t *Dir)
672 memset(&entry, 0, sizeof(direntry_t));
674 num = fat32RootCluster(Dir);
676 /* make the directory entry */
678 entry.name[0] = '\0';
679 mk_entry_from_base("/", ATTR_DIR, num, 0, 0, &entry.dir);
682 size = countBytes(Dir, num);
684 Fs_t *Fs = (Fs_t *) GetFs(Dir);
685 size = Fs->dir_len * Fs->sector_size;
687 file = _internalFileOpen(Dir, num, size, &entry);
693 Stream_t *OpenFileByDirentry(direntry_t *entry)
699 first = getStart(entry->Dir, &entry->dir);
701 if(!first && IS_DIR(entry))
702 return OpenRoot(entry->Dir);
704 size = countBytes(entry->Dir, first);
706 size = FILE_SIZE(&entry->dir);
707 file = _internalFileOpen(entry->Dir, first, size, entry);
718 int isRootDir(Stream_t *Stream)
720 File_t *This = getUnbufferedFile(Stream);
722 return This->map == root_map;