-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathproj3-clean.c
2777 lines (2422 loc) · 109 KB
/
proj3-clean.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define FAT12 0
#define FAT16 1
#define FAT32 2
//FAT constants
#define Partition_LBA_Begin 0 //first byte of the partition
#define ENTRIES_PER_SECTOR 16
#define DIR_SIZE 32 //in bytes
#define SECTOR_SIZE 64//in bytes
#define FAT_ENTRY_SIZE 4//in bytes
#define MAX_FILENAME_SIZE 8
#define MAX_EXTENTION_SIZE 3
//file table
#define TBL_OPEN_FILES 75 //Max size of open file table
#define TBL_DIR_STATS 75 //Max size of open directory table
//open file codes
#define MODE_READ 0
#define MODE_WRITE 1
#define MODE_BOTH 2
#define MODE_UNKNOWN 3 //when first created and directories
//boolean support
#define TRUE 1
#define FALSE 0
typedef int bool;
//generic
#define SUCCESS 0
const char * ROOT = "/";
const char * PARENT = "..";
const char * SELF = ".";
const char * PATH_DELIMITER = "/";
const char * DEBUG_FLAG = "-d";
bool DEBUG;
//Parsing
#define PERIOD 46
#define ALPHA_NUMBERS_LOWER_BOUND 48
#define ALPHA_NUMBERS_UPPER_BOUND 57
#define ALPHA_UPPERCASE_LOWER_BOUND 65
#define ALPHA_UPPERCASE_UPPER_BOUND 90
#define ALPHA_LOWERCASE_LOWER_BOUND 97
#define ALPHA_LOWERCASE_UPPER_BOUND 122
//File attributes
const uint8_t ATTR_READ_ONLY = 0x01;
const uint8_t ATTR_HIDDEN = 0x02;
const uint8_t ATTR_SYSTEM = 0x04;
const uint8_t ATTR_VOLUME_ID = 0x08;
const uint8_t ATTR_DIRECTORY = 0x10;
const uint8_t ATTR_ARCHIVE = 0x20;
const uint8_t ATTR_LONG_NAME = 0x0F;
//Clusters
uint32_t FAT_FREE_CLUSTER = 0x00000000;
uint32_t FAT_EOC = 0x0FFFFFF8;
uint32_t MASK_IGNORE_MSB = 0x0FFFFFFF;
/*
*
* BEGIN STRUCTURE DEFINITIONS
*
*/
struct BS_BPB {
uint8_t BS_jmpBoot[3]; //1-3
uint8_t BS_OEMName[8]; //4-11
uint16_t BPB_BytsPerSec;//12-13
uint8_t BPB_SecPerClus; //14
uint16_t BPB_RsvdSecCnt; //15-16
uint8_t BPB_NumFATs; //17
uint16_t BPB_RootEntCnt; //18-19
uint16_t BPB_TotSec16; //20-21
uint8_t BPB_Media; //22
uint16_t BPB_FATSz16; //23-24
uint16_t BPB_SecPerTrk; //25-26
uint16_t BPB_NumHeads; //27-28
uint32_t BPB_HiddSec; //29-32
uint32_t BPB_TotSec32; //33-36
uint32_t BPB_FATSz32 ; //37-40
uint16_t BPB_ExtFlags ; //41-42
uint16_t BPB_FSVer ; //43-44
uint32_t BPB_RootClus ;//45-48
uint16_t BPB_FSInfo ; //49-50
uint16_t BPB_BkBootSec ;//51-52
uint8_t BPB_Reserved[12]; //53-64
uint8_t BS_DrvNum ;//65
uint8_t BS_Reserved1 ;//66
uint8_t BS_BootSig ;//67
uint32_t BS_VolID ;//68-71
uint8_t BS_VolLab[11]; //72-82
uint8_t BS_FilSysType[8]; //83-89
} __attribute__((packed));
struct DIR_ENTRY {
uint8_t filename[11];
uint8_t attributes;
uint8_t r1;
uint8_t r2;
uint16_t crtTime;
uint16_t crtDate;
uint16_t accessDate;
uint8_t hiCluster[2];
uint16_t lastWrTime;
uint16_t lastWrDate;
uint8_t loCluster[2];
uint32_t fileSize;
} __attribute__((packed));
struct FILEDESCRIPTOR {
uint8_t filename[9];
uint8_t extention[4];
char parent[100];
uint32_t firstCluster;
int mode;
uint32_t size;
bool dir; //is it a directory
bool isOpen;
uint8_t fullFilename[13];
} __attribute__((packed));
struct ENVIRONMENT {
char pwd[100];
char imageName[100];
int pwd_cluster;
uint32_t io_writeCluster; //< - deprecated
int tbl_dirStatsIndex;
int tbl_openFilesIndex;
int tbl_dirStatsSize;
int tbl_openFilesSize;
char last_pwd[100];
struct FILEDESCRIPTOR * openFilesTbl; //open file history table
struct FILEDESCRIPTOR * dirStatsTbl; //directory history table
} environment;
int checkForFileError(FILE * f) {
if(f == NULL) {
printf("FATAL ERROR: Problem openning image -- EXITTING!\n");
exit(EXIT_FAILURE);
}
}
//-------------END BOOT SECTOR FUNCTIONS -----------------------
/* notes: the alias shown above the functions match up the variables from
* the Microsoft FAT specificatiions
*/
//alias := rootDirSectors
int rootDirSectorCount(struct BS_BPB * bs) {
return (bs->BPB_RootEntCnt * 32) + (bs->BPB_BytsPerSec - 1) / bs->BPB_BytsPerSec ;
}
//alias := FirstDataSector
int firstDataSector(struct BS_BPB * bs) {
int FATSz;
if(bs->BPB_FATSz16 != 0)
FATSz = bs->BPB_FATSz16;
else
FATSz = bs->BPB_FATSz32;
return bs->BPB_RsvdSecCnt + (bs->BPB_NumFATs * FATSz) + rootDirSectorCount(bs);
}
//alias := FirstSectorofCluster
uint32_t firstSectorofCluster(struct BS_BPB * bs, uint32_t clusterNum) {
return (clusterNum - 2) * (bs->BPB_SecPerClus) + firstDataSector(bs);
}
/* decription: feed it a cluster and it returns the byte offset
* of the beginning of that cluster's data
* */
uint32_t byteOffsetOfCluster(struct BS_BPB *bs, uint32_t clusterNum) {
return firstSectorofCluster(bs, clusterNum) * bs->BPB_BytsPerSec;
}
//alias := DataSec
int sectorsInDataRegion(struct BS_BPB * bs) {
int FATSz;
int TotSec;
if(bs->BPB_FATSz16 != 0)
FATSz = bs->BPB_FATSz16;
else
FATSz = bs->BPB_FATSz32;
if(bs->BPB_TotSec16 != 0)
TotSec = bs->BPB_TotSec16;
else
TotSec = bs->BPB_TotSec32;
return TotSec - (bs->BPB_RsvdSecCnt + (bs->BPB_NumFATs * FATSz) + rootDirSectorCount(bs));
}
//alias := CountofClusters
int countOfClusters(struct BS_BPB * bs) {
return sectorsInDataRegion(bs) / bs->BPB_SecPerClus;
}
int getFatType(struct BS_BPB * bs) {
int clusterCount = countOfClusters(bs);
if(clusterCount < 4085)
return FAT12;
else if(clusterCount < 65525)
return FAT16;
else
return FAT32;
}
int firstFatTableSector(struct BS_BPB *bs) {
return Partition_LBA_Begin + bs->BPB_RsvdSecCnt;
}
//the sector of the first clustor
//cluster_begin_lba
int firstClusterSector(struct BS_BPB *bs) {
return Partition_LBA_Begin + bs->BPB_RsvdSecCnt + (bs->BPB_NumFATs * bs->BPB_SecPerClus);
}
//----------------OPEN FILE/DIRECTORY TABLES-----------------
/* create a new file to be put in the file descriptor table
* */
struct FILEDESCRIPTOR * TBL_createFile(
const char * filename,
const char * extention,
const char * parent,
uint32_t firstCluster,
int mode,
uint32_t size,
int dir,
int isOpen) {
struct FILEDESCRIPTOR * newFile = (struct FILEDESCRIPTOR *) malloc(sizeof(struct FILEDESCRIPTOR));
strcpy(newFile->filename, filename);
strcpy(newFile->extention, extention);
strcpy(newFile->parent, parent);
if(strlen(newFile->extention) > 0) {
strcpy(newFile->fullFilename, newFile->filename);
strcat(newFile->fullFilename, ".");
strcat(newFile->fullFilename, newFile->extention);
} else {
strcpy(newFile->fullFilename, newFile->filename);
}
newFile->firstCluster = firstCluster;
newFile->mode = mode;
newFile->size = size;
newFile->dir = dir;
newFile->isOpen = isOpen;
return newFile;
}
/* adds a file object to either the fd table or the dir history table
*/
int TBL_addFileToTbl(struct FILEDESCRIPTOR * file, int isDir) {
if(isDir == TRUE) {
if(environment.tbl_dirStatsSize < TBL_DIR_STATS) {
environment.dirStatsTbl[environment.tbl_dirStatsIndex % TBL_DIR_STATS] = *file;
if(DEBUG == TRUE) printf("adding %s\n", environment.dirStatsTbl[environment.tbl_dirStatsIndex % TBL_DIR_STATS].filename);
environment.tbl_dirStatsSize++;
environment.tbl_dirStatsIndex = ++environment.tbl_dirStatsIndex % TBL_DIR_STATS;
return 0;
}else {
environment.dirStatsTbl[environment.tbl_dirStatsIndex % TBL_DIR_STATS] = *file;
environment.tbl_dirStatsIndex = ++environment.tbl_dirStatsIndex % TBL_DIR_STATS;
return 0;
}
} else {
if(environment.tbl_openFilesSize < TBL_OPEN_FILES) {
environment.openFilesTbl[environment.tbl_openFilesIndex % TBL_OPEN_FILES] = *file;
environment.tbl_openFilesSize++;
environment.tbl_openFilesIndex = ++environment.tbl_openFilesIndex % TBL_OPEN_FILES;
return 0;
} else {
environment.openFilesTbl[environment.tbl_openFilesIndex % TBL_OPEN_FILES] = *file;
environment.tbl_openFilesIndex = ++environment.tbl_openFilesIndex % TBL_OPEN_FILES;
return 0;
}
}
}
/* description: if <isDir> is set prints the content of the open files table
* if not prints the open directory table
*/
int TBL_printFileTbl(int isDir) {
if(DEBUG == TRUE) printf("environment.tbl_dirStatsSize: %d\n", environment.tbl_dirStatsSize);
if(DEBUG == TRUE) printf("environment.tbl_openFilesSize: %d\n", environment.tbl_openFilesSize);
if(isDir == TRUE) {
puts("\nDirectory Table\n");
if(environment.tbl_dirStatsSize > 0) {
int x;
for(x = 0; x < environment.tbl_dirStatsSize; x++) {
printf("[%d] filename: %s, parent: %s, isOpen: %d, Size: %d, mode: %d\n",
x,environment.dirStatsTbl[x % TBL_DIR_STATS].fullFilename,
environment.dirStatsTbl[x % TBL_DIR_STATS].parent,
environment.dirStatsTbl[x % TBL_DIR_STATS].isOpen,
environment.dirStatsTbl[x % TBL_DIR_STATS].size,
environment.dirStatsTbl[x % TBL_DIR_STATS].mode);
}
return 0;
} else {
return 1;
}
} else {
puts("\nOpen File Table\n");
if(environment.tbl_openFilesSize > 0) {
int x;
for(x = 0; x < environment.tbl_openFilesSize; x++) {
printf("[%d] filename: %s, parent:%s, isOpen: %d, Size: %d, mode: %d\n",
x,environment.openFilesTbl[x % TBL_OPEN_FILES].fullFilename,
environment.openFilesTbl[x % TBL_OPEN_FILES].parent,
environment.openFilesTbl[x % TBL_OPEN_FILES].isOpen,
environment.openFilesTbl[x % TBL_OPEN_FILES].size,
environment.openFilesTbl[x % TBL_OPEN_FILES].mode);
}
return 0;
} else {
return 1;
}
}
}
/* desctipion searches the open directory table for entry if it finds it,
* it returns the name of the parent directory, else it returns an empty string
*/
const char * TBL_getParent(const char * dirName) {
if(environment.tbl_dirStatsSize > 0) {
int x;
for(x = 0; x < environment.tbl_dirStatsSize; x++) {
if(DEBUG == TRUE) printf("searching for %s in table, found %s\n", dirName, environment.dirStatsTbl[x % TBL_DIR_STATS].filename);
if(strcmp(environment.dirStatsTbl[x % TBL_DIR_STATS].filename, dirName) == 0)
return environment.dirStatsTbl[x % TBL_DIR_STATS].parent;
}
return "";
} else {
return "";
}
}
/* description: "index" is set to the index where the found element resides
* returns TRUE if file was found in the file table
*
*/
bool TBL_getFileDescriptor(int * index, const char * filename, bool isDir){
struct FILEDESCRIPTOR * b;
if(isDir == TRUE) {
if(environment.tbl_dirStatsSize > 0) {
int x;
for(x = 0; x < environment.tbl_dirStatsSize; x++) {
if(DEBUG == TRUE) printf("searching for %s in table, found %s\n", filename, environment.dirStatsTbl[x % TBL_DIR_STATS].filename);
if(strcmp(environment.dirStatsTbl[x % TBL_DIR_STATS].fullFilename, filename) == 0) {
*index = x;
return TRUE;
}
}
} else
return FALSE;
} else {
if(environment.tbl_openFilesSize > 0) {
int x;
for(x = 0; x < environment.tbl_openFilesSize; x++) {
if(strcmp(environment.openFilesTbl[x % TBL_OPEN_FILES].fullFilename, filename) == 0) {
*index = x;
return TRUE;
}
}
} else
return FALSE;
}
return FALSE;
}
//-----------------------------------------------------------------------------
/*description: feed this a cluster and it returns an offset, in bytes, where the
* fat entry for this cluster is locted
*
* use: use the result to seek to the place in the image and read
* the FAT entry
* */
uint32_t getFatAddressByCluster(struct BS_BPB * bs, uint32_t clusterNum) {
uint32_t FATOffset = clusterNum * 4;
uint32_t ThisFATSecNum = bs->BPB_RsvdSecCnt + (FATOffset / bs->BPB_BytsPerSec);
uint32_t ThisFATEntOffset = FATOffset % bs->BPB_BytsPerSec;
return (ThisFATSecNum * bs->BPB_BytsPerSec + ThisFATEntOffset);
}
/*description: finds the location of this clusters FAT entry, reads
* and returns the entry value
*
* use: use the result to seek to the place in the image and read
* the FAT entry
* */
uint32_t FAT_getFatEntry(struct BS_BPB * bs, uint32_t clusterNum) {
FILE* f = fopen(environment.imageName, "r");
checkForFileError(f);
uint8_t aFatEntry[FAT_ENTRY_SIZE];
uint32_t FATOffset = clusterNum * 4;
fseek(f, getFatAddressByCluster(bs, clusterNum), 0);
fread(aFatEntry, 1, FAT_ENTRY_SIZE, f);
fclose(f);
uint32_t fatEntry = 0x00000000;
int x;
for(x = 0; x < 4; x++) {
fatEntry |= aFatEntry[(FATOffset % FAT_ENTRY_SIZE ) + x] << 8 * x;
}
return fatEntry;
}
/* description: takes a value, newFatVal, and writes it to the destination
* cluster,
*/
int FAT_writeFatEntry(struct BS_BPB * bs, uint32_t destinationCluster, uint32_t * newFatVal) {
FILE* f = fopen(environment.imageName, "r+");
checkForFileError(f);
fseek(f, getFatAddressByCluster(bs, destinationCluster), 0);
fwrite(newFatVal, 4, 1, f);
fclose(f);
if(DEBUG == TRUE) printf("FAT_writeEntry: wrote->%d to cluster %d", *newFatVal, destinationCluster);
return 0;
}
/* desctipion: NOT USED but might be in future to clear newly freed clusters
*/
void clearCluster(struct BS_BPB * bs, uint32_t targetCluster) {
uint8_t clearedCluster[bs->BPB_BytsPerSec];
//i didn't want to do it this way but compiler wont let me initalize
//an array that's sized with a variable :(
int x;
for(x = 0; x < bs->BPB_BytsPerSec; x++) { clearedCluster[x] = 0x00; }
FILE* f = fopen(environment.imageName, "r+");
checkForFileError(f);
fseek(f, byteOffsetOfCluster(bs, targetCluster), 0);
fwrite(clearedCluster, 1, bs->BPB_BytsPerSec, f);
fclose(f);
}
/*description:walks a FAT chain until 0x0fffffff, returns the number of iterations
* which is the size of the cluster chiain
*/
int getFileSizeInClusters(struct BS_BPB * bs, uint32_t firstClusterVal) {
int size = 1;
firstClusterVal = (int) FAT_getFatEntry(bs, firstClusterVal);
while((firstClusterVal = (firstClusterVal & MASK_IGNORE_MSB)) < FAT_EOC) {
size++;
firstClusterVal = FAT_getFatEntry(bs, firstClusterVal);
}
return size;
}
/*description: walks a FAT chain until returns the last cluster, where
* the current EOC is. returns the cluster number passed in if it's empty,
* , you should probly call getFirstFreeCluster if you intend to write to
* the FAT to keep things orderly
*/
uint32_t getLastClusterInChain(struct BS_BPB * bs, uint32_t firstClusterVal) {
int size = 1;
uint32_t lastCluster = firstClusterVal;
firstClusterVal = (int) FAT_getFatEntry(bs, firstClusterVal);
//if cluster is empty return cluster number passed in
if((((firstClusterVal & MASK_IGNORE_MSB) | FAT_FREE_CLUSTER) == FAT_FREE_CLUSTER) )
return lastCluster;
//mask the 1st 4 msb, they are special and don't count
while((firstClusterVal = (firstClusterVal & MASK_IGNORE_MSB)) < FAT_EOC) {
lastCluster = firstClusterVal;
firstClusterVal = FAT_getFatEntry(bs, firstClusterVal);
}
return lastCluster;
}
/* description: traverses the FAT sequentially and find the first open cluster
*/
int FAT_findFirstFreeCluster(struct BS_BPB * bs) {
int i = 0;
int totalClusters = countOfClusters(bs);
while(i < totalClusters) {
if(((FAT_getFatEntry(bs, i) & MASK_IGNORE_MSB) | FAT_FREE_CLUSTER) == FAT_FREE_CLUSTER)
break;
i++;
}
return i;
}
/* decription: returns the total number of open clusters
*/
int FAT_findTotalFreeCluster(struct BS_BPB * bs) {
int i = 0;
int fatIndex = 0;
int totalClusters = countOfClusters(bs);
while(fatIndex < totalClusters) {
if((((FAT_getFatEntry(bs, fatIndex) & MASK_IGNORE_MSB) | FAT_FREE_CLUSTER) == FAT_FREE_CLUSTER))
i++;
fatIndex++;
}
return i;
}
/* description: pass in a entry and this properly formats the
* "firstCluster" from the 2 byte segments in the file structure
*/
uint32_t buildClusterAddress(struct DIR_ENTRY * entry) {
uint32_t firstCluster = 0x00000000;
firstCluster |= entry->hiCluster[1] << 24;
firstCluster |= entry->hiCluster[0] << 16;
firstCluster |= entry->loCluster[1] << 8;
firstCluster |= entry->loCluster[0];
return firstCluster;
}
/* description: convert uint32_t to hiCluster and loCluster byte array
* and stores it into <entry>
*/
int deconstructClusterAddress(struct DIR_ENTRY * entry, uint32_t cluster) {
entry->loCluster[0] = cluster;
entry->loCluster[1] = cluster >> 8;
entry->hiCluster[0] = cluster >> 16;
entry->hiCluster[1] = cluster >> 24;
return 0;
}
/* description: takes a directory entry populates a file descriptor
* to be used in the file tables
* */
struct FILEDESCRIPTOR * makeFileDecriptor(struct DIR_ENTRY * entry, struct FILEDESCRIPTOR * fd) {
char newFilename[12];
bzero(fd->filename, 9);
bzero(fd->extention, 4);
memcpy(newFilename, entry->filename, 11);
newFilename[11] = '\0';
int x;
for(x = 0; x < 8; x++) {
if(newFilename[x] == ' ')
break;
fd->filename[x] = newFilename[x];
}
fd->filename[++x] = '\0';
for(x = 8; x < 11; x++) {
if(newFilename[x] == ' ')
break;
fd->extention[x - 8] = newFilename[x];
}
fd->extention[++x - 8] = '\0';
if(strlen(fd->extention) > 0) {
strcpy(fd->fullFilename, fd->filename);
strcat(fd->fullFilename, ".");
strcat(fd->fullFilename, fd->extention);
} else {
strcpy(fd->fullFilename, fd->filename);
}
fd->firstCluster = buildClusterAddress(entry);
fd->size = entry->fileSize;
fd->mode = MODE_UNKNOWN;
if((entry->attributes & ATTR_DIRECTORY) == ATTR_DIRECTORY)
fd->dir = TRUE;
else
fd->dir = FALSE;
return fd;
}
/* description: prints the contents of a directory entry
*/
int showEntry(struct DIR_ENTRY * entry) {
puts("First Cluster\n");
printf("lo[0]%02x, lo[1]%02x, hi[0]%02x, hi[1]%02x\n", entry->loCluster[0],
entry->loCluster[1],
entry->hiCluster[0],
entry->hiCluster[1]);
int x;
for(x = 0; x < 11; x++) {
if(entry->filename[x] == ' ')
printf("filename[%d]->%s\n", x, "SPACE");
else
printf("filename[%d]->%c\n", x, entry->filename[x]);
}
printf("\nattr->0x%x, size->0x%x ", entry->attributes, entry->fileSize);
}
/* description: takes a cluster number where bunch of directories are and
* the offst of the directory you want read and it will store that directory
* info into the variable dir
*/
struct DIR_ENTRY * readEntry(struct BS_BPB * bs, struct DIR_ENTRY * entry, uint32_t clusterNum, int offset){
offset *= 32;
uint32_t dataAddress = byteOffsetOfCluster(bs, clusterNum);
FILE* f = fopen(environment.imageName, "r");
checkForFileError(f);
fseek(f, dataAddress + offset, 0);
fread(entry, sizeof(struct DIR_ENTRY), 1, f);
fclose(f);
return entry;
}
/* description: takes a cluster number and offset where you want an entry written and write to that
* position
*/
struct DIR_ENTRY * writeEntry(struct BS_BPB * bs, struct DIR_ENTRY * entry, uint32_t clusterNum, int offset){
offset *= 32;
uint32_t dataAddress = byteOffsetOfCluster(bs, clusterNum);
FILE* f = fopen(environment.imageName, "r+");
checkForFileError(f);
fseek(f, dataAddress + offset, 0);
fwrite(entry, 1, sizeof(struct DIR_ENTRY), f);
if(DEBUG == TRUE) printf("writeEntry-> address: %d...Calling showEntry()\n", dataAddress);
if(DEBUG == TRUE) showEntry(entry);
fclose(f);
return entry;
}
/* description: takes a directory cluster and give you the byte address of the entry at
* the offset provided. used to write dot entries. POSSIBLY REDUNDANT
*/
uint32_t byteOffsetofDirectoryEntry(struct BS_BPB * bs, uint32_t clusterNum, int offset) {
if(DEBUG == TRUE) printf("\nbyteOffsetofDirectoryEntry: passed in offset->%d\n", offset);
offset *= 32;
if(DEBUG == TRUE) printf("\nbyteOffsetofDirectoryEntry: offset*32->%d\n", offset);
uint32_t dataAddress = byteOffsetOfCluster(bs, clusterNum);
if(DEBUG == TRUE) printf("\nbyteOffsetofDirectoryEntry: clusterNum: %d, offset: %d, returning: %d\n", clusterNum, offset, (dataAddress + offset));
return (dataAddress + offset);
}
/* This is the workhorse. It is used for ls, cd, filesearching.
* Directory Functionality:
* It is used to perform cd, which you use by setting <cd>. if <goingUp> is set it uses
* the open directory table to find the pwd's parent. if not it searches the pwd for
* <directoryName>. If <cd> is not set this prits the contents of the pwd to the screen
*
* Search Functionality
* if <useAsSearch> is set this short circuits the cd functionality and returns TRUE
* if found
*
* ls(bs, environment.pwd_cluster, TRUE, fileName, FALSE, searchFile, TRUE, searchForDirectory)
*/
int ls(struct BS_BPB * bs, uint32_t clusterNum, bool cd, const char * directoryName, bool goingUp, struct FILEDESCRIPTOR * searchFile, bool useAsSearch, bool searchForDir) {
struct DIR_ENTRY dir;
int dirSizeInCluster = getFileSizeInClusters(bs, clusterNum);
int clusterCount;
char fileName[13];
char f[12];
int offset;
int increment;
for(clusterCount = 0; clusterCount < dirSizeInCluster; clusterCount++) {
//root doesn't have . and .., so we traverse it differently
// we only increment 1 to get . and .. then we go in 2's to avoid longname entries
if(strcmp(directoryName, ROOT) == 0) {
offset = 1;
increment = 2;
} else {
offset = 0;
increment = 1;
}
for(; offset < ENTRIES_PER_SECTOR; offset += increment) {
//this is a hack to properly display the dir contents of folders
//with . and .. w/o displaying longname entries
//if not root folder we need to read the 1st 2 entries (. and ..)
//sequential then resume skipping longnames by incrementing by 2
if(strcmp(directoryName, ROOT) != 0 && offset == 2) {
increment = 2;
offset -= 1;
continue;
}
readEntry(bs, &dir, clusterNum, offset);
makeFileDecriptor(&dir, searchFile);
if( cd == FALSE ) {
//we don't want to print 0xE5 to the screen
if(searchFile->filename[0] != 0xE5) {
if(searchFile->dir == TRUE)
printf("dir->%s ", searchFile->fullFilename);
else
printf("%s ", searchFile->fullFilename);
}
} else {
//if there's an extention we expect the user must type it in with the '.' and the extention
//because of this we must compare it to a recontructed filename with the implied '.' put
//back in. also searchForDir tells us whether the file being searched for is a directory or not
if(useAsSearch == TRUE) {
if(strcmp(searchFile->fullFilename, directoryName) == 0 && searchFile->dir == searchForDir )
return TRUE;
} else {
/* if we're going down we search pwd for directory with the name passed in.
* if we find it we add it to the directory table and return TRUE. else
* we fall out of this loop and return FALSE at the end of the function
*/
if(searchFile->dir == TRUE && strcmp(searchFile->fullFilename, directoryName) == 0 && goingUp == FALSE) {// <--------CHANGED
environment.pwd_cluster = searchFile->firstCluster;
if(strcmp(TBL_getParent(directoryName), "") == 0)//if directory not already in open dir history table
TBL_addFileToTbl(TBL_createFile(searchFile->filename, "", environment.pwd, searchFile->firstCluster, searchFile->mode, searchFile->size, TRUE, FALSE), TRUE);
FAT_setIoWriteCluster(bs, environment.pwd_cluster);
return TRUE;
}
//fetch parent cluster from the directory table
if(searchFile->dir == TRUE && strcmp(directoryName, PARENT) == 0 && goingUp == TRUE) {
const char * parent = TBL_getParent(environment.pwd);
if(strcmp(parent, "") != 0) { //we found parent in the table
if(strcmp(parent, "/") == 0)
environment.pwd_cluster = 2; //sets pwd_cluster to where we're headed
else
environment.pwd_cluster = searchFile->firstCluster;
strcpy(environment.last_pwd, environment.pwd);
strcpy(environment.pwd, TBL_getParent(environment.pwd));
FAT_setIoWriteCluster(bs, environment.pwd_cluster);
return TRUE; //cd to parent was successful
} else
return FALSE; //cd to parent not successful
}
} // end cd block
}
}
clusterNum = FAT_getFatEntry(bs, clusterNum);
//printf("next cluster: %d\n", FAT_getFatEntry(bs, clusterNum));
}
return FALSE;
}
/* descriptioin: takes a FILEDESCRIPTOR and checks if the entry it was
* created from is empty. Helper function
*/
bool isEntryEmpty(struct FILEDESCRIPTOR * fd) {
if((fd->filename[0] != 0x00) && (fd->filename[0] != 0xE5) )
return FALSE;
else
return TRUE;
}
/* description: walks a directory cluster chain looking for empty entries, if it finds one
* it returns the byte offset of that entry. If it finds none then it returns -1;
*/
uint32_t FAT_findNextOpenEntry(struct BS_BPB * bs, uint32_t pwdCluster) {
struct DIR_ENTRY dir;
struct FILEDESCRIPTOR fd;
int dirSizeInCluster = getFileSizeInClusters(bs, pwdCluster);
int clusterCount;
char fileName[12];
int offset;
int increment;
for(clusterCount = 0; clusterCount < dirSizeInCluster; clusterCount++) {
if(strcmp(environment.pwd, ROOT) == 0) {
offset = 1;
increment = 2;
} else {
offset = 0;
increment = 1;
}
for(; offset < ENTRIES_PER_SECTOR; offset += increment) {
if(strcmp(environment.pwd, ROOT) != 0 && offset == 2) {
increment = 2;
offset -= 1;
continue;
}
if(DEBUG == TRUE) printf("\nFAT_findNextOpenEntry: offset->%d\n", offset);
readEntry(bs, &dir, pwdCluster, offset);
makeFileDecriptor(&dir, &fd);
if( isEntryEmpty(&fd) == TRUE ) {
//this should tell me exactly where to write my new entry to
//printf("cluster #%d, byte offset: %d: ", offset, byteOffsetofDirectoryEntry(bs, pwdCluster, offset));
return byteOffsetofDirectoryEntry(bs, pwdCluster, offset);
}
}
//pwdCluster becomes the next cluster in the chain starting at the passed in pwdCluster
pwdCluster = FAT_getFatEntry(bs, pwdCluster);
}
return -1; //cluster chain is full
}
/* description: wrapper for ls. tries to change the pwd to <directoryName>
* This doesn't use the print to screen functinoality of ls. if <goingUp>
* is set it uses the open directory table to find the pwd's parent
*/
int cd(struct BS_BPB * bs, const char * directoryName, int goingUp, struct FILEDESCRIPTOR * searchFile) {
return ls(bs, environment.pwd_cluster, TRUE, directoryName, goingUp, searchFile, FALSE, FALSE);
}
/* desctipion: wrapper that uses ls to search a pwd for a file and puts its info
* into searchFile if found. if <useAsFileSearch> is set it disables the printing enabling
* it to be used as a file search utility. if <searchForDirectory> is set it excludes
* files from the search
*/
bool searchOrPrintFileSize(struct BS_BPB * bs, const char * fileName, bool useAsFileSearch, bool searchForDirectory, struct FILEDESCRIPTOR * searchFile) {
if(ls(bs, environment.pwd_cluster, TRUE, fileName, FALSE, searchFile, TRUE, searchForDirectory) == TRUE) {
if(useAsFileSearch == FALSE)
printf("File: %s is %d byte(s) in size", fileName ,searchFile->size);
return TRUE;
} else {
if(useAsFileSearch == FALSE)
printf("ERROR: File: %s was not found", fileName);
return FALSE;
}
}
/* desctipion: wrapper that uses ls to search a pwd for a file and puts its info
* into searchFile if found. Prints result for both file and directories
*/
bool printFileOrDirectorySize(struct BS_BPB * bs, const char * fileName, struct FILEDESCRIPTOR * searchFile) {
if(ls(bs, environment.pwd_cluster, TRUE, fileName, FALSE, searchFile, TRUE, TRUE) == TRUE ||
ls(bs, environment.pwd_cluster, TRUE, fileName, FALSE, searchFile, TRUE, FALSE) == TRUE) {
printf("File: %s is %d byte(s) in size", fileName ,searchFile->size);
return TRUE;
} else
return FALSE;
}
/* description: wrapper for searchOrPrintFileSize searchs pwd for filename.
* returns TRUE if found, if found the resulting entry is put into searchFile
* for use outside the function. if <searchForDirectory> is set it excludes
* files from the search
*/
bool searchForFile(struct BS_BPB * bs, const char * fileName, bool searchForDirectory, struct FILEDESCRIPTOR * searchFile) {
return searchOrPrintFileSize(bs, fileName, TRUE, searchForDirectory, searchFile);
}
/* decription: feed this a cluster number that's part of a chain and this
* traverses it to find the last entry as well as finding the first available
* free cluster and adds that free cluster to the chain
*/
uint32_t FAT_extendClusterChain(struct BS_BPB * bs, uint32_t clusterChainMember) {
uint32_t firstFreeCluster = FAT_findFirstFreeCluster(bs);
uint32_t lastClusterinChain = getLastClusterInChain(bs, clusterChainMember);
FAT_writeFatEntry(bs, lastClusterinChain, &firstFreeCluster);
FAT_writeFatEntry(bs, firstFreeCluster, &FAT_EOC);
return firstFreeCluster;
}
/* desctipion: pass in a free cluster and this marks it with EOC and sets
* the environment.io_writeCluster to the end of newly created cluster
* chain
*/
int FAT_allocateClusterChain(struct BS_BPB * bs, uint32_t clusterNum) {
FAT_writeFatEntry(bs, clusterNum, &FAT_EOC);
return 0;
}
/* desctipion: pass in the 1st cluster of a chain and this traverses the
* chain and writes FAT_FREE_CLUSTER to every link, thereby freeing the
* chain for reallocation
*/
int FAT_freeClusterChain(struct BS_BPB * bs, uint32_t firstClusterOfChain){
int dirSizeInCluster = getFileSizeInClusters(bs, firstClusterOfChain);
if(DEBUG == TRUE) printf("dir Size: %d\n", dirSizeInCluster);
int currentCluster= firstClusterOfChain;
int nextCluster;
int clusterCount;
for(clusterCount = 0; clusterCount < dirSizeInCluster; clusterCount++) {
nextCluster = FAT_getFatEntry(bs, currentCluster);
FAT_writeFatEntry(bs, currentCluster, &FAT_FREE_CLUSTER);
currentCluster = nextCluster;
}
return 0;
}
/* description: feed this a cluster that's a member of a chain and this
* sets your environment variable "io_writeCluster" to the last in that
* chain. The thinking is this is where you'll write in order to grow
* that file. before writing to cluster check with FAT_findNextOpenEntry()
* to see if there's space or you need to extend the chain using FAT_extendClusterChain()
*/
int FAT_setIoWriteCluster(struct BS_BPB * bs, uint32_t clusterChainMember) {
environment.io_writeCluster = getLastClusterInChain(bs, clusterChainMember);
return 0;
}
/* description: this will write a new entry to <destinationCluster>. if that cluster
* is full it grows the cluster chain and write the entry in the first spot
* of the new cluster. if <isDotEntries> is set this automatically writes both
* '.' and '..' to offsets 0 and 1 of <destinationCluster>
*
*/
int writeFileEntry(struct BS_BPB * bs, struct DIR_ENTRY * entry, uint32_t destinationCluster, bool isDotEntries) {
int dataAddress;
int freshCluster;
FILE* f = fopen(environment.imageName, "r+");
checkForFileError(f);
if(isDotEntries == FALSE) {
if((dataAddress = FAT_findNextOpenEntry(bs, destinationCluster)) != -1) {//-1 means current cluster is at capacity
fseek(f, dataAddress, 0);
fwrite (entry , 1 , sizeof(struct DIR_ENTRY) , f );
} else {
freshCluster = FAT_extendClusterChain(bs, destinationCluster);
dataAddress = FAT_findNextOpenEntry(bs, freshCluster);
fseek(f, dataAddress, 0);
fwrite (entry , 1 , sizeof(struct DIR_ENTRY) , f );
}
} else {
struct DIR_ENTRY dotEntry;
struct DIR_ENTRY dotDotEntry;
makeSpecialDirEntries(&dotEntry, &dotDotEntry, destinationCluster, environment.pwd_cluster);
//seek to first spot in new dir cluster chin and write the '.' entry
dataAddress = byteOffsetofDirectoryEntry(bs, destinationCluster, 0);
fseek(f, dataAddress, 0);
fwrite (&dotEntry , 1 , sizeof(struct DIR_ENTRY) , f );
//seek to second spot in new dir cluster chin and write the '..' entry
dataAddress = byteOffsetofDirectoryEntry(bs, destinationCluster, 1);
fseek(f, dataAddress, 0);
fwrite (&dotDotEntry , 1 , sizeof(struct DIR_ENTRY) , f );
}
fclose(f);
return 0;
}
/* description: takes a directory entry and all the necesary info
and populates the entry with the info in a correct format for
insertion into a disk.
*/
int createEntry(struct DIR_ENTRY * entry,
const char * filename,
const char * ext,
int isDir,
uint32_t firstCluster,
uint32_t filesize,
bool emptyAfterThis,
bool emptyDirectory) {
//set the same no matter the entry
entry->r1 = 0;
entry->r2 = 0;
entry->crtTime = 0;
entry->crtDate = 0;
entry->accessDate = 0;
entry->lastWrTime = 0;
entry->lastWrDate = 0;
if(emptyAfterThis == FALSE && emptyDirectory == FALSE) { //if both are false
int x;
for(x = 0; x < MAX_FILENAME_SIZE; x++) {
if(x < strlen(filename))
entry->filename[x] = filename[x];
else
entry->filename[x] = ' ';
}
for(x = 0; x < MAX_EXTENTION_SIZE; x++) {
if(x < strlen(ext))
entry->filename[MAX_FILENAME_SIZE + x] = ext[x];
else
entry->filename[MAX_FILENAME_SIZE + x] = ' ';
}
deconstructClusterAddress(entry, firstCluster);
if(isDir == TRUE) {
entry->fileSize = 0;
entry->attributes = ATTR_DIRECTORY;
} else {
entry->fileSize = filesize;
entry->attributes = ATTR_ARCHIVE;
}
return 0; //stops execution so we don't flow out into empty entry config code below
} else if(emptyAfterThis == TRUE) { //if this isn't true, then the other must be
entry->filename[0] = 0xE5;