-
Notifications
You must be signed in to change notification settings - Fork 2
/
mimic_fat.c
1894 lines (1647 loc) · 65.6 KB
/
mimic_fat.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
/*
* mimic FAT file system functions
*
* Copyright 2024, Hiroyuki OYAMA. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "mimic_fat.h"
#define ANSI_RED "\e[31m"
#define ANSI_CLEAR "\e[0m"
#ifdef ENABLE_TRACE
#define TRACE(...) (printf(__VA_ARGS__))
#else
#define TRACE(...) ((void)0)
#endif
static const struct lfs_config *littlefs_lfs_config = NULL;
#define FAT_SHORT_NAME_MAX 11
#define FAT_LONG_FILENAME_CHUNK_MAX 13
static uint8_t fat_disk_image[1][DISK_SECTOR_SIZE] = {
//------------- Block0: Boot Sector -------------//
{
0xEB, 0x3C, 0x90, // BS_JmpBoot
'M', 'S', 'D', 'O', 'S', '5', '.', '0', // BS_OEMName
0x00, 0x02, // BPB_BytsPerSec
0x01, // BPB_SecPerClus
0x01, 0x00, // BPB_RsvdSecCnt
0x01, // BPB_NumFATs
0x10, 0x00, // BPB_RootEntCnt
0x00, 0x00, // BPB_TotSec16, to be set up later
0xF8, // BPB_Media
0x01, 0x00, // BPB_FATSz16
0x01, 0x00, // BPB_SecPerTrk
0x01, 0x00, // BPB_NumHeads
0x00, 0x00, 0x00, 0x00, // BPB_HiddSec
0x00, 0x00, 0x00, 0x00, // BPB_TotSec32
0x80, // BS_DrvNum
0x00, // BS_Reserved
0x29, // BS_BootSig
0x34, 0x12, 0x00, 0x00, // BS_VolID
'l' , 'i' , 't' , 't' , 'l' , 'e' , 'f' , 's' , 'U' , 'S' , 'B' , // BS_VolLab
0x46, 0x41, 0x54, 0x31, 0x32, 0x20, 0x20, 0x20, // BS_FilSysType
0x00, 0x00,
// Zero up to 2 last bytes of FAT magic code
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xAA
}
};
static lfs_t real_filesystem;
static bool usb_device_is_enabled = false;
static lfs_file_t fat_cache;
void mimic_fat_init(const struct lfs_config *c) {
littlefs_lfs_config = c;
}
bool mimic_fat_usb_device_is_enabled(void) {
return usb_device_is_enabled;
}
void mimic_fat_update_usb_device_is_enabled(bool enable) {
usb_device_is_enabled = enable;
}
static void print_block(uint8_t *buffer, size_t l) {
size_t offset = 0;
for (size_t i = 0; i < l; ++i) {
if (i % 16 == 0)
printf("0x%04u%s", offset, (i % 512) == 0 ? ">" : " ");
if (isalnum(buffer[i])) {
printf("'%c' ", buffer[i]);
} else {
printf("0x%02x", buffer[i]);
}
if (i % 16 == 15) {
printf("\n");
offset += 16;
} else {
printf(", ");
}
}
}
static void print_hex(uint8_t *buffer, size_t l) {
size_t offset = 0;
for (size_t i = 0; i < l; ++i) {
if (i % 16 == 0)
printf("0x%04u%s ", offset, (i % 512) == 0 ? ">" : " ");
printf("0x%02x,", buffer[i]);
if (i % 16 == 15) {
printf("\n");
offset += 16;
}
}
}
static void print_dir_entry(void *buffer) {
uint8_t pbuffer[11+1];
fat_dir_entry_t *dir = (fat_dir_entry_t *)buffer;
TRACE("--------\n");
for (size_t i = 0; i < DISK_SECTOR_SIZE / sizeof(fat_dir_entry_t); i++) {
if (dir->DIR_Name[0] == '\0') {
break;
}
if ((dir->DIR_Attr & 0x0F) != 0x0F) {
memcpy(pbuffer, &dir->DIR_Name, 11);
pbuffer[11] = '\0';
TRACE("name='%s' attr=0x%02X size=%lu cluster=%u\n",
pbuffer,
dir->DIR_Attr,
dir->DIR_FileSize,
dir->DIR_FstClusLO);
} else {
fat_lfn_t *lfn = (fat_lfn_t *)dir;
uint16_t utf16le[13 + 1];
memcpy(utf16le, lfn->LDIR_Name1, 5*2);
memcpy(utf16le + 5, lfn->LDIR_Name2, 6*2);
memcpy(utf16le + 5 + 6, lfn->LDIR_Name3, 2*2);
utf16le[13] = '\0';
char utf8[13 * 4 + 1];
utf16le_to_utf8(utf8, sizeof(utf8), utf16le, 13);
TRACE("name='%s' attr=0x%02X ord=0x%02X checksum=%u cluster=%u\n",
utf8, lfn->LDIR_Attr, lfn->LDIR_Ord, lfn->LDIR_Chksum, dir->DIR_FstClusLO);
}
dir++;
}
}
static int is_fat_sfn_symbol(uint8_t c) {
switch (c) {
case '$':
case '%':
case '\'':
case '-':
case '_':
case '@':
case '~':
case '`':
case '!':
case '(':
case ')':
case '{':
case '}':
case '^':
case '#':
case '&':
return 1;
break;
default:
return 0;
}
}
static uint16_t read_fat(int cluster) {
uint16_t offset = (uint16_t)floor((float)cluster + ((float)cluster / 2));
lfs_soff_t o = lfs_file_seek(&real_filesystem, &fat_cache, offset, LFS_SEEK_SET);
if (o < 0) {
printf("read_fat: lfs_file_seek error=%ld\n", o);
return 0xFFF;
}
uint8_t current[2] = {0};
lfs_ssize_t s = lfs_file_read(&real_filesystem, &fat_cache, current, sizeof(current));
if (s < 0) {
printf("read_fat: lfs_file_read error=%ld\n", s);
}
int16_t result = 0;
if (cluster & 0x01) {
result = (current[0] >> 4) | ((uint16_t)current[1] << 4);
} else {
result = current[0] | ((uint16_t)(current[1] & 0x0F) << 8);
}
return result;
}
static void update_fat(uint32_t cluster, uint16_t value) {
size_t offset = (size_t)floor((float)cluster + ((float)cluster / 2));
uint8_t previous[2] = {0};
lfs_soff_t o = lfs_file_seek(&real_filesystem, &fat_cache, offset, LFS_SEEK_SET);
if (o < 0) {
printf("update_fat: lfs_file_seek error=%ld\n", o);
return;
}
lfs_ssize_t s = lfs_file_read(&real_filesystem, &fat_cache, previous, sizeof(previous));
if (s < 0) {
printf("update_fat: lfs_file_read error=%ld\n", s);
return;
}
if (cluster & 0x01) {
previous[0] = (previous[0] & 0x0F) | (value << 4);
previous[1] = value >> 4;
} else {
previous[0] = value;
previous[1] = (previous[1] & 0xF0) | ((value >> 8) & 0x0F);
}
o = lfs_file_seek(&real_filesystem, &fat_cache, offset, LFS_SEEK_SET);
if (o < 0) {
printf("update_fat: lfs_file_seek error=%ld\n", o);
return;
}
s = lfs_file_write(&real_filesystem, &fat_cache, previous, sizeof(previous));
if (s != sizeof(previous)) {
printf("update_fat: lfs_file_write error=%ld\n", s);
}
}
#define BUFFER_SIZE 512
#define END_OF_CLUSTER_CHAIN 0xFFF
static size_t bulk_update_fat_buffer_read(size_t offset, void *buffer, size_t size) {
lfs_soff_t o = lfs_file_seek(&real_filesystem, &fat_cache, offset, LFS_SEEK_SET);
if (o < 0) {
printf("bulk_update_fat_buffer_read: lfs_file_seek error=%ld\n", o);
return 0;
}
lfs_ssize_t s = lfs_file_read(&real_filesystem, &fat_cache, buffer, size);
if (s < 0) {
printf("bulk_update_fat_buffer_read: lfs_file_read error=%ld\n", s);
return 0;
}
return (size_t)s;
}
static size_t bulk_update_fat_buffer_write(size_t offset, void *buffer, size_t size) {
lfs_soff_t o = lfs_file_seek(&real_filesystem, &fat_cache, offset, LFS_SEEK_SET);
if (o < 0) {
printf("bulk_update_fat_buffer_write: lfs_file_seek error=%ld\n", o);
return 0;
}
lfs_ssize_t s = lfs_file_write(&real_filesystem, &fat_cache, buffer, size);
if (s < 0) {
printf("bulk_update_fat_buffer_write: lfs_file_read error=%ld\n", s);
return 0;
}
return (size_t)s;
}
static size_t bulk_update_fat(uint32_t start_cluster, size_t size) {
size_t num_clusters = ceil((double)size / 512);
unsigned char buffer[BUFFER_SIZE];
unsigned int current_cluster = start_cluster;
unsigned int next_cluster;
int initial_offset = (3 * start_cluster) / 2;
int initial_sector = initial_offset / BUFFER_SIZE;
size_t read = bulk_update_fat_buffer_read(initial_sector * BUFFER_SIZE, buffer, sizeof(buffer));
if (read == 0)
return 0;
int sector_size = 512;
for (unsigned int i = 0; i < num_clusters; i++) {
int offset = floor((3 * current_cluster) / 2.0);
int buffer_index = offset % sector_size;
next_cluster = (i < num_clusters - 1) ? current_cluster + 1 : END_OF_CLUSTER_CHAIN;
if (current_cluster & 0x01) {
buffer[buffer_index] = (buffer[buffer_index] & 0x0F) | (next_cluster << 4);
buffer[buffer_index + 1] = (next_cluster >> 4) & 0xFF;
} else {
buffer[buffer_index] = next_cluster & 0xFF;
buffer[buffer_index + 1] = (buffer[buffer_index + 1] & 0xF0) | ((next_cluster >> 8) & 0x0F);
}
// FAT12 sector boundaries
if (((current_cluster & 0x01) && buffer_index + 2 >= sector_size) ||
(buffer_index + 1 >= sector_size))
{
size_t write = bulk_update_fat_buffer_write(initial_sector * BUFFER_SIZE, buffer, sizeof(buffer));
if (write == 0)
return 0;
initial_sector++;
read = bulk_update_fat_buffer_read(initial_sector * BUFFER_SIZE, buffer, sizeof(buffer));
if (read == 0)
return 0;
buffer_index = 0;
if (current_cluster & 0x01) {
buffer[buffer_index] = (next_cluster >> 4) & 0xFF;
} else {
buffer[buffer_index] = (buffer[buffer_index] & 0xF0) | ((next_cluster >> 8) & 0x0F);
}
}
current_cluster++;
}
size_t write = bulk_update_fat_buffer_write(initial_sector * BUFFER_SIZE, buffer, sizeof(buffer));
if (write == 0)
return 0;
return start_cluster + num_clusters + 1;
}
static void init_fat(void) {
uint64_t storage_size = littlefs_lfs_config->block_count * littlefs_lfs_config->block_size;
uint32_t cluster_size = storage_size / (DISK_SECTOR_SIZE * 1);
struct lfs_info finfo;
int err = lfs_stat(&real_filesystem, ".mimic", &finfo);
if (err == LFS_ERR_NOENT) {
err = lfs_mkdir(&real_filesystem, ".mimic");
if (err != LFS_ERR_OK) {
printf("init_fat: can't create .mimic directory: err=%d\n", err);
return;
}
}
err = lfs_file_open(&real_filesystem, &fat_cache, ".mimic/FAT", LFS_O_RDWR|LFS_O_CREAT);
assert(err == 0);
uint8_t head[3] = {0xF8, 0xFF, 0xFF};
head[0] = 0xF8;
head[1] = 0xFF;
head[2] = 0xFF;
lfs_ssize_t s = lfs_file_write(&real_filesystem, &fat_cache, head, sizeof(head));
if (s != sizeof(head)) {
printf("init_fat: lfs_file_write error=%ld\n", s);
return;
}
uint8_t pair[3] = {0x00, 0x00, 0x00};
for (size_t i = 0; i < (float)cluster_size / 2; i++) {
s = lfs_file_write(&real_filesystem, &fat_cache, pair, sizeof(pair));
if (s != sizeof(pair)) {
printf("init_fat: lfs_file_write error=%ld\n", s);
break;
}
}
}
static void print_fat(size_t l) {
TRACE("FAT table-------\n");
for (size_t i = 0; i < l; i++) {
TRACE(" cluster=%d fat=%03x\n", i, read_fat(i));
}
}
static void set_fat_short_filename(uint8_t *short_filename, const char *filename) {
uint8_t buffer[LFS_NAME_MAX + 1];
strncpy((char *)buffer, filename, sizeof(buffer));
char *basename = strtok((char *)buffer, ".");
char *ext = strtok(NULL, ".");
snprintf((char *)short_filename, sizeof(buffer), "%-8s%-3s", basename, ext);
}
static void restore_from_short_filename(char *filename, const char *short_filename) {
char buffer[FAT_SHORT_NAME_MAX + 1];
strncpy(buffer, short_filename, sizeof(buffer) - 1);
uint8_t basename[8 + 1];
uint8_t fileext[3 + 1];
for (int i = 0; i < 8; i++) {
if (buffer[i] != ' ') {
basename[i] = buffer[i];
} else {
basename[i] = '\0';
break;
}
}
basename[sizeof(basename)-1] = '\0';
for (int i = 0; i < 3; i++) {
if (buffer[8+i] != ' ') {
fileext[i] = buffer[8+i];
} else {
fileext[i] = '\0';
break;
}
}
fileext[sizeof(fileext)-1] = '\0';
sprintf((char *)filename, "%s.%s", basename, fileext);
}
static void restore_from_short_dirname(char *filename, const char *short_dirname) {
strcpy(filename, short_dirname);
size_t length = FAT_SHORT_NAME_MAX;
while (length > 0 && filename[length - 1] == ' ') {
--length;
}
filename[length] = '\0';
}
static bool is_short_filename_file(uint8_t *filename) {
char buffer[LFS_NAME_MAX + 1];
if (filename[0] == '.')
return false;
strncpy(buffer, (const char *)filename, sizeof(buffer));
unsigned char *name = (unsigned char *)strtok(buffer, ".");
if (strlen((char *)name) > 8) {
return false;
}
unsigned char *ext = (unsigned char *)strtok(NULL, ".");
if (strlen((char *)ext) > 3) {
return false;
}
for (int i = 0; i < 8; i++) {
if (name[i] == '\0') {
break;
}
if (isalnum(name[i]) == 0 && is_fat_sfn_symbol(name[i]) == 0) {
return false;
}
if (isalpha(name[i]) > 0 && isupper(name[i]) == 0) {
return false;
}
}
for (int i = 0; i < 3; i++) {
if (ext[i] == '\0') {
break;
}
if (isalpha(ext[i]) > 0 && isupper(ext[i]) == 0) {
return false;
}
if ((isalnum(ext[i]) == 0) && (is_fat_sfn_symbol(ext[i]) == 0)) {
return false;
}
}
return true;
}
static void to_uppercase(char *str) {
if (str == NULL)
return;
while (*str) {
*str = toupper((unsigned char) *str);
str++;
}
}
static bool is_short_filename_dir(uint8_t *filename) {
uint8_t buffer[LFS_NAME_MAX + 1];
strncpy((char *)buffer, (const char *)filename, sizeof(buffer));
if (strlen((const char *)filename) > FAT_SHORT_NAME_MAX) {
return false;
}
for (size_t i = 0; i < FAT_SHORT_NAME_MAX; i++) {
if (filename[i] == '\0') {
break;
}
if (isalnum(filename[i]) == 0 && is_fat_sfn_symbol(filename[i]) == 0) {
return false;
}
if (isalpha(filename[i]) > 0 && isupper(filename[i]) == 0) {
return false;
}
}
return true;
}
static void create_shortened_short_filename(uint8_t *sfn, const char *long_filename) {
uint8_t buffer[LFS_NAME_MAX + 1];
uint8_t filename[FAT_SHORT_NAME_MAX + 1];
strncpy((char *)buffer, long_filename, sizeof(buffer));
char *name = strtok((char *)buffer, ".");
(void)name;
char *ext = strtok(NULL, ".");
ext[3] = '\0';
to_uppercase(ext);
snprintf((char *)filename, sizeof(filename), "FIL~%04X%-3s", rand() % 0xFFFF, ext);
memcpy(sfn, filename, FAT_SHORT_NAME_MAX);
}
static void create_shortened_short_filename_dir(uint8_t *sfn, const char *long_filename) {
(void)long_filename;
uint8_t filename[FAT_SHORT_NAME_MAX + 1];
snprintf((char *)filename, sizeof(filename), "DIR~%04X ", rand() % 0xFFFF);
memcpy(sfn, filename, FAT_SHORT_NAME_MAX);
}
static uint8_t filename_check_sum(const uint8_t *filename) {
uint8_t i, sum;
for (i = sum = 0; i < FAT_SHORT_NAME_MAX; i++) {
sum = (sum >> 1) + (sum << 7) + filename[i];
}
return sum;
}
static void set_LFN_name123(fat_lfn_t *dir, const uint16_t *filename) {
memcpy(&dir->LDIR_Name1, filename + 0, sizeof(uint16_t) * 5);
memcpy(&dir->LDIR_Name2, filename + 5, sizeof(uint16_t) * 6);
memcpy(&dir->LDIR_Name3, filename + 5+6, sizeof(uint16_t) * 2);
}
void set_volume_label_entry(fat_dir_entry_t *dir, const char *name) {
uint8_t sfn_name[FAT_SHORT_NAME_MAX + 1];
snprintf((char *)sfn_name, sizeof(sfn_name), "%-11s", name);
memcpy(dir->DIR_Name, sfn_name, FAT_SHORT_NAME_MAX);
dir->DIR_Attr = 0x08;
dir->DIR_NTRes = 0;
dir->DIR_CrtTimeTenth = 0;
dir->DIR_CrtTime = 0;
dir->DIR_CrtDate = 0;
dir->DIR_LstAccDate = 0;
dir->DIR_FstClusHI = 0;
dir->DIR_WrtTime = LITTLE_ENDIAN16(0x4F6D);
dir->DIR_WrtDate = LITTLE_ENDIAN16(0x6543);
dir->DIR_FstClusLO = 0;
dir->DIR_FileSize = 0;
}
static void set_directory_entry(fat_dir_entry_t *dir, const char *name, int cluster) {
uint8_t sfn_name[LFS_NAME_MAX + 1];
snprintf((char *)sfn_name, sizeof(sfn_name), "%-11s", name);
memcpy(dir->DIR_Name, sfn_name, FAT_SHORT_NAME_MAX);
dir->DIR_Attr = 0x10; // directory
dir->DIR_NTRes = 0;
dir->DIR_CrtTimeTenth = 0xC6;
dir->DIR_CrtTime = LITTLE_ENDIAN16(0x526D);
dir->DIR_CrtDate = LITTLE_ENDIAN16(0x6543);
dir->DIR_LstAccDate = LITTLE_ENDIAN16(0x6543);
dir->DIR_FstClusHI = 0;
dir->DIR_WrtTime = LITTLE_ENDIAN16(0x526D);
dir->DIR_WrtDate = LITTLE_ENDIAN16(0x6543);
dir->DIR_FstClusLO = cluster;
dir->DIR_FileSize = 0;
}
static void set_file_entry(fat_dir_entry_t *dir, struct lfs_info *info, int cluster) {
set_fat_short_filename(dir->DIR_Name, info->name);
dir->DIR_Attr = 0x20;
dir->DIR_NTRes = 0;
dir->DIR_CrtTimeTenth = 0xC6;
dir->DIR_CrtTime = LITTLE_ENDIAN16(0x526D);
dir->DIR_CrtDate = LITTLE_ENDIAN16(0x6543);
dir->DIR_LstAccDate = LITTLE_ENDIAN16(0x6543);
dir->DIR_FstClusHI = 0;
dir->DIR_WrtTime = LITTLE_ENDIAN16(0x526D);
dir->DIR_WrtDate = LITTLE_ENDIAN16(0x6543);
dir->DIR_FstClusLO = info->size > 0 ? LITTLE_ENDIAN16(cluster) : 0;
dir->DIR_FileSize = LITTLE_ENDIAN32(info->size);
}
static void set_long_file_entry(fat_dir_entry_t *dir, uint16_t *lfn_chunk, uint8_t lfn_order, uint8_t check_sum) {
fat_lfn_t *long_dir_entry = (fat_lfn_t *)dir;
set_LFN_name123(long_dir_entry, lfn_chunk);
long_dir_entry->LDIR_Ord = lfn_order;
long_dir_entry->LDIR_Attr = 0x0F;
long_dir_entry->LDIR_Type = 0x00;
long_dir_entry->LDIR_Chksum = check_sum;
long_dir_entry->LDIR_FstClusLO[0] = 0x00;
long_dir_entry->LDIR_FstClusLO[1] = 0x00;
}
/*
* Save buffers sent by the host to LFS temporary files
*/
static bool save_temporary_file(uint32_t cluster, void *buffer) {
TRACE("save_temporary_file: cluster=%lu\n", cluster);
char filename[LFS_NAME_MAX + 1];
int tens = (cluster / 10) % 10;
int hundreds = (cluster / 100) % 10;
int thousands = (cluster / 1000) % 10;
snprintf(filename, sizeof(filename), ".mimic/%d", thousands);
struct lfs_info finfo;
int err = lfs_stat(&real_filesystem, filename, &finfo);
if (err == LFS_ERR_NOENT) {
err = lfs_mkdir(&real_filesystem, filename);
if (err != LFS_ERR_OK) {
printf("save_temporary_file: can't create '%s' directory: err=%d\n", filename, err);
return false;
}
}
snprintf(filename, sizeof(filename), ".mimic/%d/%1d", thousands, hundreds);
err = lfs_stat(&real_filesystem, filename, &finfo);
if (err == LFS_ERR_NOENT) {
err = lfs_mkdir(&real_filesystem, filename);
if (err != LFS_ERR_OK) {
printf("save_temporary_file: can't create '%s' directory: err=%d\n", filename, err);
return false;
}
}
snprintf(filename, sizeof(filename), ".mimic/%d/%1d/%1d", thousands, hundreds, tens);
err = lfs_stat(&real_filesystem, filename, &finfo);
if (err == LFS_ERR_NOENT) {
err = lfs_mkdir(&real_filesystem, filename);
if (err != LFS_ERR_OK) {
printf("save_temporary_file: can't create '%s' directory: err=%d\n", filename, err);
return false;
}
}
snprintf(filename, sizeof(filename), ".mimic/%d/%1d/%1d/%04ld", thousands, hundreds,tens, cluster);
lfs_file_t f;
err = lfs_file_open(&real_filesystem, &f, filename, LFS_O_RDWR|LFS_O_CREAT);
if (err != LFS_ERR_OK) {
printf("save_temporary_file: can't lfs_file_open '%s' err=%d\n", filename, err);
return false;
}
lfs_file_write(&real_filesystem, &f, buffer, 512);
lfs_file_close(&real_filesystem, &f);
return 1;
}
static int read_temporary_file(uint32_t cluster, void *buffer) {
lfs_file_t f;
char filename[LFS_NAME_MAX + 1];
int tens = (cluster/ 10) % 10;
int hundreds = (cluster/ 100) % 10;
int thousands = (cluster/ 1000) % 10;
snprintf(filename, sizeof(filename), ".mimic/%d/%1d/%1d/%04ld", thousands, hundreds,tens, cluster);
int err = lfs_file_open(&real_filesystem, &f, filename, LFS_O_RDONLY);
if (err != LFS_ERR_OK) {
if (err == LFS_ERR_NOENT)
return err;
printf("read_temporary_file: can't open '%s': err=%d\n", filename, err);
return err;
}
lfs_ssize_t size = lfs_file_read(&real_filesystem, &f, buffer, 512);
if (size != 512) {
printf("read_temporary_file: can't read '%s': size=%lu\n", filename, size);
lfs_file_close(&real_filesystem, &f);
return err;
}
lfs_file_close(&real_filesystem, &f);
return LFS_ERR_OK;
}
/*
static bool delete_temporary_file(uint32_t cluster) {
printf("delete_temporary_file: cluster=%lu\n", cluster);
char filename[LFS_NAME_MAX + 1];
int tens = (file_id / 10) % 10;
int hundreds = (file_id / 100) % 10;
int thousands = (file_id / 1000) % 10;
snprintf(filename, sizeof(filename), ".mimic/%d/%1d/%1d/%04ld", thousands, hundreds,tens, cluster);
int err = lfs_remove(&real_filesystem, filename);
if (err != LFS_ERR_OK) {
printf("delete_temporary_file: can't lfs_remove '%s' error=%d\n", filename, err);
return false;
}
return true;
}
*/
static fat_dir_entry_t *append_dir_entry_volume_label(fat_dir_entry_t *entry, const char *volume_label) {
uint8_t name[FAT_SHORT_NAME_MAX + 1];
snprintf((char *)name, sizeof(name), "%-11s", volume_label);
memcpy(entry->DIR_Name, name, FAT_SHORT_NAME_MAX);
entry->DIR_Attr = 0x08;
entry->DIR_NTRes = 0;
entry->DIR_CrtTimeTenth = 0;
entry->DIR_CrtTime = 0;
entry->DIR_CrtDate = 0;
entry->DIR_LstAccDate = 0;
entry->DIR_FstClusHI = 0;
entry->DIR_WrtTime = LITTLE_ENDIAN16(0x4F6D);
entry->DIR_WrtDate = LITTLE_ENDIAN16(0x6543);
entry->DIR_FstClusLO = 0;
entry->DIR_FileSize = 0;
entry++;
return entry;
}
static void long_filename_padding(uint16_t *filename, size_t length, size_t size) {
for (size_t i = length; i < size; i++) {
if (i == length)
filename[i] = 0x0000;
else
filename[i] = 0xFFFF;
}
}
static fat_dir_entry_t *append_dir_entry_directory(fat_dir_entry_t *entry, struct lfs_info *finfo, uint32_t cluster) {
TRACE("append_dir_entry_directory '%s'\n", finfo->name);
if (strcmp(finfo->name, ".") == 0 || strcmp(finfo->name, "..") == 0) {
set_directory_entry(entry, finfo->name, cluster == 1 ? 0 : cluster);
}
else if (is_short_filename_dir((uint8_t *)finfo->name)) {
set_directory_entry(entry, finfo->name, cluster);
} else {
fat_dir_entry_t short_dir_entry;
set_directory_entry(&short_dir_entry, finfo->name, cluster);
create_shortened_short_filename_dir(short_dir_entry.DIR_Name, finfo->name);
uint8_t check_sum = filename_check_sum(short_dir_entry.DIR_Name);
uint16_t filename[LFS_NAME_MAX + 1];
size_t len = utf8_to_utf16le(filename, sizeof(filename), finfo->name, strlen(finfo->name));
long_filename_padding(filename, len, LFS_NAME_MAX + 1);
int long_filename_num = floor((len - 1) / FAT_LONG_FILENAME_CHUNK_MAX);
for (int i = long_filename_num; i >= 0; i--) {
uint8_t order = i + 1;
uint16_t chunk[FAT_LONG_FILENAME_CHUNK_MAX];
uint16_t *head = (uint16_t *)&(filename[i * FAT_LONG_FILENAME_CHUNK_MAX]);
memcpy(chunk, head, sizeof(chunk));
if (i == long_filename_num)
order |= 0x40;
set_long_file_entry(entry, chunk, order, check_sum);
entry++;
}
memcpy(entry, &short_dir_entry, sizeof(short_dir_entry));
}
entry++;
return entry;
}
static fat_dir_entry_t *append_dir_entry_file(fat_dir_entry_t *entry, struct lfs_info *finfo, uint32_t cluster) {
TRACE("append_dir_entry_file '%s' cluster=%lu\n", finfo->name, cluster);
if (is_short_filename_file((uint8_t *)finfo->name)) {
set_file_entry(entry, finfo, cluster);
} else {
fat_dir_entry_t short_dir_entry;
set_file_entry(&short_dir_entry, finfo, cluster);
create_shortened_short_filename(short_dir_entry.DIR_Name, finfo->name);
uint8_t check_sum = filename_check_sum(short_dir_entry.DIR_Name);
uint16_t filename[LFS_NAME_MAX + 1];
size_t len = utf8_to_utf16le(filename, sizeof(filename), finfo->name, strlen(finfo->name));
long_filename_padding(filename, len, LFS_NAME_MAX + 1);
int long_filename_num = floor((len - 1) / FAT_LONG_FILENAME_CHUNK_MAX);
for (int i = long_filename_num; i >= 0; i--) {
uint8_t order = i + 1;
uint16_t chunk[FAT_LONG_FILENAME_CHUNK_MAX];
uint16_t *head = (uint16_t *)&(filename[i * FAT_LONG_FILENAME_CHUNK_MAX]);
memcpy(chunk, head, sizeof(chunk));
if (i == long_filename_num)
order |= 0x40;
set_long_file_entry(entry, chunk, order, check_sum);
entry++;
}
memcpy(entry, &short_dir_entry, sizeof(short_dir_entry));
}
entry++;
return entry;
}
/*
* Create a directory entry cache corresponding to the base file system
*
* Recursively traverse the specified base file system directory and update cache and allocation tables.
*/
static int create_dir_entry_cache(const char *path, uint32_t parent_cluster, uint32_t *allocated_cluster) {
TRACE("create_dir_entry_cache('%s', %lu, %lu)\n", path, parent_cluster, *allocated_cluster);
uint32_t current_cluster = *allocated_cluster;
fat_dir_entry_t *entry;
fat_dir_entry_t dir_entry[DISK_SECTOR_SIZE / sizeof(fat_dir_entry_t)] = {0};
lfs_dir_t dir;
struct lfs_info finfo;
char directory_path[LFS_NAME_MAX * 2 + 1 + 1]; // for sprintf "%s/%s"
entry = dir_entry;
if (parent_cluster == 0) {
entry = append_dir_entry_volume_label(entry, "littlefsUSB");
current_cluster = 1;
}
update_fat(current_cluster, 0xFFF);
int err = lfs_dir_open(&real_filesystem, &dir, path);
if (err != LFS_ERR_OK) {
printf("create_dir_entry_cache: lfs_dir_open('%s') error=%d\n", path, err);
return err;
}
while (true) {
err = lfs_dir_read(&real_filesystem, &dir, &finfo);
if (err == 0)
break;
if (err < 0) {
printf("create_dir_entry_cache: lfs_dir_read('%s') error=%d\n", path, err);
break;
}
if (finfo.type == LFS_TYPE_DIR && parent_cluster == 0 && strcmp(finfo.name, ".mimic") == 0) {
continue;
}
if (finfo.type == LFS_TYPE_DIR && parent_cluster == 0
&& (strcmp(finfo.name, ".") == 0 || strcmp(finfo.name, "..") == 0))
{
continue;
}
if (finfo.type == LFS_TYPE_DIR && strcmp(finfo.name, ".") == 0) {
entry = append_dir_entry_directory(entry, &finfo, current_cluster);
continue;
}
if (finfo.type == LFS_TYPE_DIR && strcmp(finfo.name, "..") == 0) {
if (parent_cluster == 0)
entry = append_dir_entry_directory(entry, &finfo, 0);
else
entry = append_dir_entry_directory(entry, &finfo, parent_cluster);
continue;
}
if (finfo.type == LFS_TYPE_DIR) {
*allocated_cluster += 1;
update_fat(*allocated_cluster, 0xFFF);
entry = append_dir_entry_directory(entry, &finfo, *allocated_cluster);
if (parent_cluster == 0)
strncpy(directory_path, finfo.name, sizeof(directory_path));
else
snprintf(directory_path, sizeof(directory_path), "%s/%s", path, finfo.name);
directory_path[LFS_NAME_MAX] = '\0';
err = create_dir_entry_cache((const char *)directory_path, current_cluster, allocated_cluster);
if (err < 0) {
lfs_dir_close(&real_filesystem, &dir);
return err;
}
} else if (finfo.type == LFS_TYPE_REG) {
uint32_t file_cluster = *allocated_cluster + 1;
if (finfo.size > 0)
*allocated_cluster = bulk_update_fat(file_cluster, finfo.size);
entry = append_dir_entry_file(entry, &finfo, file_cluster);
}
}
lfs_dir_close(&real_filesystem, &dir);
save_temporary_file(current_cluster, dir_entry);
return 0;
}
/*
* Rebuild the directory entry cache.
*
* Execute when USB is connected.
*/
void mimic_fat_create_cache(void) {
TRACE(ANSI_RED "mimic_fat_create_cache()\n" ANSI_CLEAR);
lfs_unmount(&real_filesystem);
int err = lfs_mount(&real_filesystem, littlefs_lfs_config);
if (err < 0) {
printf("mimic_fat_create_cache: lfs_mount error=%d\n", err);
return;
}
mimic_fat_cleanup_cache();
init_fat();
uint32_t allocated_cluster = 1;
create_dir_entry_cache("", 0, &allocated_cluster);
}
static void delete_directory(const char *path) {
uint8_t filename[LFS_NAME_MAX + 1 + 8];
lfs_dir_t dir;
struct lfs_info finfo;
int err = lfs_dir_open(&real_filesystem, &dir, path);
if (err != LFS_ERR_OK) {
return;
}
while (true) {
err = lfs_dir_read(&real_filesystem, &dir, &finfo);
if (err == 0)
break;
if (err < 0) {
printf("delete_directory: lfs_dir_read('%s') error=%d\n", path, err);
break;
}
if (strcmp(finfo.name, ".") == 0 ||
strcmp(finfo.name, "..") == 0)
{
continue;
}
snprintf((char *)filename, sizeof(filename), "%s/%s", path, finfo.name);
if (finfo.type == LFS_TYPE_DIR)
delete_directory((const char *)filename);
err = lfs_remove(&real_filesystem, (const char *)filename);
if (err != LFS_ERR_OK) {
printf("delete_directory: lfs_remove('%s') error=%d\n", filename, err);
continue;
}
}
lfs_dir_close(&real_filesystem, &dir);
}
void mimic_fat_cleanup_cache(void) {
uint8_t filename[LFS_NAME_MAX + 1 + 8];
lfs_dir_t dir;
struct lfs_info finfo;
int err = lfs_dir_open(&real_filesystem, &dir, ".mimic");
if (err != LFS_ERR_OK) {
return;
}
while (true) {
err = lfs_dir_read(&real_filesystem, &dir, &finfo);
if (err == 0)
break;
if (err < 0) {
printf("mimic_fat_cleanup_cache: lfs_dir_read('%s') error=%d\n", ".mimic", err);
break;
}
if (strcmp(finfo.name, ".") == 0 ||
strcmp(finfo.name, "..") == 0)
{
continue;
}
snprintf((char *)filename, sizeof(filename), "%s/%s", ".mimic", finfo.name);
delete_directory((const char *)filename);
}
lfs_dir_close(&real_filesystem, &dir);
}
static uint32_t cluster_size(void) {
uint64_t storage_size = littlefs_lfs_config->block_count * littlefs_lfs_config->block_size;
return storage_size / (DISK_SECTOR_SIZE * 1);
}
static size_t fat_sector_size(void) {
return ceil((double)cluster_size() / DISK_SECTOR_SIZE);
}
static bool is_fat_sector(uint32_t sector) {
return sector > 0 && fat_sector_size() >= sector;
}
size_t mimic_fat_total_sector_size(void) {
uint64_t storage_size = littlefs_lfs_config->block_count * littlefs_lfs_config->block_size;
return (double)storage_size / DISK_SECTOR_SIZE;
}
/*
* Returns the boot sector of the FAT image when USB requests sector 0
*/
static void read_boot_sector(void *buffer, uint32_t bufsize) {
TRACE("\e[36mRead read_boot_sector()\e[0m\n");
// BPB_TotSec16
fat_disk_image[0][19] = (uint8_t)(mimic_fat_total_sector_size() & 0xFF);
fat_disk_image[0][20] = (uint8_t)(mimic_fat_total_sector_size() >> 8);
// BPB_FATSz16
size_t fat_size = ceil((double)mimic_fat_total_sector_size() / DISK_SECTOR_SIZE);
fat_disk_image[0][22] = fat_size & 0xFF;
fat_disk_image[0][23] = (fat_size & 0xFF00) >> 8;