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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
|
/****************************************************************************
* fs/fat/fs_fat32dirent.c
*
* Copyright (C) 2011 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <spudmonkey@racsa.co.cr>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* NOTE: If CONFIG_FAT_LFN is defined, then there may be some legal, patent
* issues. The following was extracted from the entry "File Allocation Table
* from Wikipedia, the free encyclopedia:
*
* "On December 3, 2003 Microsoft announced it would be offering licenses
* for use of its FAT specification and 'associated intellectual property',
* at the cost of a US$0.25 royalty per unit sold, with a $250,000 maximum
* royalty per license agreement.
*
* o "U.S. Patent 5,745,902 (http://www.google.com/patents?vid=5745902) -
* Method and system for accessing a file using file names having
* different file name formats. ...
* o "U.S. Patent 5,579,517 (http://www.google.com/patents?vid=5579517) -
* Common name space for long and short filenames. ...
* o "U.S. Patent 5,758,352 (http://www.google.com/patents?vid=5758352) -
* Common name space for long and short filenames. ...
* o "U.S. Patent 6,286,013 (http://www.google.com/patents?vid=6286013) -
* Method and system for providing a common name space for long and
* short file names in an operating system. ...
*
* "Many technical commentators have concluded that these patents only cover
* FAT implementations that include support for long filenames, and that
* removable solid state media and consumer devices only using short names
* would be unaffected. ..."
*
* So you have been forewarned: Use the long filename at your own risk!
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <errno.h>
#include <debug.h>
#include <nuttx/fs.h>
#include <nuttx/fat.h>
#include "fs_internal.h"
#include "fs_fat32.h"
/****************************************************************************
* Definitions
****************************************************************************/
/****************************************************************************
* Private Types
****************************************************************************/
enum fat_case_e
{
FATCASE_UNKNOWN = 0,
FATCASE_UPPER,
FATCASE_LOWER
};
/****************************************************************************
* Private Function Prototypes
****************************************************************************/
#ifdef CONFIG_FAT_LFN
static uint8_t fat_lfnchecksum(const uint8_t *sfname);
#endif
static inline int fat_parsesfname(const char **path,
struct fat_dirinfo_s *dirinfo,
char *terminator);
#ifdef CONFIG_FAT_LFN
static inline int fat_parselfname(const char **path,
struct fat_dirinfo_s *dirinfo,
char *terminator);
static inline int fat_createalias(struct fat_dirinfo_s *dirinfo);
static inline int fat_findalias(struct fat_mountpt_s *fs,
struct fat_dirinfo_s *dirinfo);
static inline int fat_uniquealias(struct fat_mountpt_s *fs,
struct fat_dirinfo_s *dirinfo);
#endif
static int fat_path2dirname(const char **path, struct fat_dirinfo_s *dirinfo,
char *terminator);
static int fat_findsfnentry(struct fat_mountpt_s *fs,
struct fat_dirinfo_s *dirinfo);
#ifdef CONFIG_FAT_LFN
static bool fat_cmplfnchunk(uint8_t *chunk, const uint8_t *substr, int nchunk);
static bool fat_cmplfname(const uint8_t *direntry, const uint8_t *substr);
static inline int fat_findlfnentry(struct fat_mountpt_s *fs,
struct fat_dirinfo_s *dirinfo);
#endif
static inline int fat_allocatesfnentry(struct fat_mountpt_s *fs,
struct fat_dirinfo_s *dirinfo);
#ifdef CONFIG_FAT_LFN
static inline int fat_allocatelfnentry(struct fat_mountpt_s *fs,
struct fat_dirinfo_s *dirinfo);
#endif
static inline int fat_getsfname(uint8_t *direntry, char *buffer,
unsigned int buflen);
#ifdef CONFIG_FAT_LFN
static void fat_getlfnchunk(uint8_t *chunk, uint8_t *dest, int nchunk);
static inline int fat_getlfname(struct fat_mountpt_s *fs, struct fs_dirent_s *dir);
#endif
static int fat_dirverify(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo,
uint16_t offset);
static int fat_putsfname(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo);
#ifdef CONFIG_FAT_LFN
static void fat_initlfname(uint8_t *chunk, int nchunk);
static void fat_putlfnchunk(uint8_t *chunk, const uint8_t *src, int nchunk);
static int fat_putlfname(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo);
#endif
static int fat_putsfdirentry(struct fat_mountpt_s *fs,
struct fat_dirinfo_s *dirinfo,
uint8_t attributes, uint32_t fattime);
/****************************************************************************
* Private Variables
****************************************************************************/
/****************************************************************************
* Public Variables
****************************************************************************/
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: fat_lfnchecksum
*
* Desciption: Caculate the checksum of .
*
****************************************************************************/
#ifdef CONFIG_FAT_LFN
static uint8_t fat_lfnchecksum(const uint8_t *sfname)
{
uint8_t sum = 0;
int i;
for (i = DIR_MAXFNAME; i; i--)
{
sum = ((sum & 1) << 7) + (sum >> 1) + *sfname++;
}
return sum;
}
#endif
/****************************************************************************
* Name: fat_parsesfname
*
* Desciption: Convert a user filename into a properly formatted FAT
* (short 8.3) filename as it would appear in a directory entry. Here are
* the rules for the 8+3 short file name in the directory:
*
* The first byte:
*
* 0xe5 = The directory is free
* 0x00 = This directory and all following directories are free
* 0x05 = Really 0xe5
* 0x20 = May NOT be ' '
*
* Other characters may be any characters except for the following:
*
* 0x00-0x1f = (except for 0x00 and 0x05 in the first byte)
* 0x22 = '"'
* 0x2a-0x2c = '*', '+', ','
* 0x2e-0x2f = '.', '/'
* 0x3a-0x3f = ':', ';', '<', '=', '>', '?'
* 0x5b-0x5d = '[', '\\', ;]'
* 0x7c = '|'
*
* '.' May only occur once within string and only within the first 9
* bytes. The '.' is not save in the directory, but is implicit in
* 8+3 format.
*
* Lower case characters are not allowed in directory names (without some
* poorly documented operations on the NTRes directory byte). Lower case
* codes may represent different characters in other character sets ("DOS
* code pages". The logic below does not, at present, support any other
* character sets.
*
* Returned value:
* OK - The path refers to a valid 8.3 FAT file name and has been properly
* converted and stored in dirinfo.
* <0 - Otherwise an negated error is returned meaning that the string is
* not a valid 8+3 because:
*
* 1. Contains characters not in the printable character set,
* 2. Contains forbidden characters or multiple '.' characters
* 3. File name or extension is too long.
*
* If CONFIG_FAT_LFN is defined and CONFIG_FAT_LCNAMES is NOT
* defined, then:
*
* 4a. File name or extension contains lower case characters.
*
* If CONFIG_FAT_LFN is defined and CONFIG_FAT_LCNAMES is defined,
* then:
*
* 4b. File name or extension is not all the same case.
*
****************************************************************************/
static inline int fat_parsesfname(const char **path,
struct fat_dirinfo_s *dirinfo,
char *terminator)
{
#ifdef CONFIG_FAT_LCNAMES
unsigned int ntlcenable = FATNTRES_LCNAME | FATNTRES_LCEXT;
unsigned int ntlcfound = 0;
#ifdef CONFIG_FAT_LFN
enum fat_case_e namecase = FATCASE_UNKNOWN;
enum fat_case_e extcase = FATCASE_UNKNOWN;
#endif
#endif
const char *node = *path;
int endndx;
uint8_t ch;
int ndx = 0;
/* Initialized the name with all spaces */
memset(dirinfo->fd_name, ' ', DIR_MAXFNAME);
/* Loop until the name is successfully parsed or an error occurs */
endndx = 8;
for (;;)
{
/* Get the next byte from the path */
ch = *node++;
/* Check if this the last byte in this node of the name */
if ((ch == '\0' || ch == '/') && ndx != 0 )
{
/* Return the accumulated NT flags and the terminating character */
#ifdef CONFIG_FAT_LCNAMES
dirinfo->fd_ntflags = ntlcfound & ntlcenable;
#endif
*terminator = ch;
*path = node;
return OK;
}
/* Accept only the printable character set (excluding space). Note
* that the first byte of the name could be 0x05 meaning that is it
* 0xe5, but this is not a printable character in this character in
* either case.
*/
else if (!isgraph(ch))
{
goto errout;
}
/* Check for transition from name to extension. Only one '.' is
* permitted and it must be within first 9 characters
*/
else if (ch == '.' && endndx == 8)
{
/* Starting the extension */
ndx = 8;
endndx = 11;
continue;
}
/* Reject printable characters forbidden by FAT */
else if (ch == '"' || (ch >= '*' && ch <= ',') ||
ch == '.' || ch == '/' ||
(ch >= ':' && ch <= '?') ||
(ch >= '[' && ch <= ']') ||
(ch == '|'))
{
goto errout;
}
/* Check for upper case characters */
#ifdef CONFIG_FAT_LCNAMES
else if (isupper(ch))
{
/* Some or all of the characters in the name or extension
* are upper case. Force all of the characters to be interpreted
* as upper case.
*/
if (endndx == 8)
{
/* Is there mixed case in the name? */
#ifdef CONFIG_FAT_LFN
if (namecase == FATCASE_LOWER)
{
/* Mixed case in the name -- use the long file name */
goto errout;
}
/* So far, only upper case in the name*/
namecase = FATCASE_UPPER;
#endif
/* Clear lower case name bit in mask*/
ntlcenable &= ~FATNTRES_LCNAME;
}
else
{
/* Is there mixed case in the extension? */
#ifdef CONFIG_FAT_LFN
if (extcase == FATCASE_LOWER)
{
/* Mixed case in the extension -- use the long file name */
goto errout;
}
/* So far, only upper case in the extension*/
extcase = FATCASE_UPPER;
#endif
/* Clear lower case extension in mask */
ntlcenable &= ~FATNTRES_LCEXT;
}
}
#endif
/* Check for lower case characters */
else if (islower(ch))
{
#if defined(CONFIG_FAT_LFN) && !defined(CONFIG_FAT_LCNAMES)
/* If lower case characters are present, then a long file
* name will be constructed.
*/
goto errout;
#else
/* Convert the character to upper case */
ch = toupper(ch);
/* Some or all of the characters in the name or extension
* are lower case. They can be interpreted as lower case if
* only if all of the characters in the name or extension are
* lower case.
*/
#ifdef CONFIG_FAT_LCNAMES
if (endndx == 8)
{
/* Is there mixed case in the name? */
#ifdef CONFIG_FAT_LFN
if (namecase == FATCASE_UPPER)
{
/* Mixed case in the name -- use the long file name */
goto errout;
}
/* So far, only lower case in the name*/
namecase = FATCASE_LOWER;
#endif
/* Set lower case name bit */
ntlcfound |= FATNTRES_LCNAME;
}
else
{
/* Is there mixed case in the extension? */
#ifdef CONFIG_FAT_LFN
if (extcase == FATCASE_UPPER)
{
/* Mixed case in the extension -- use the long file name */
goto errout;
}
/* So far, only lower case in the extension*/
extcase = FATCASE_LOWER;
#endif
/* Set lower case extension bit */
ntlcfound |= FATNTRES_LCEXT;
}
#endif
#endif /* CONFIG_FAT_LFN && !CONFIG_FAT_LCNAMES */
}
/* Check if the file name exceeds the size permitted (without
* long file name support).
*/
if (ndx >= endndx)
{
goto errout;
}
/* Save next character in the accumulated name */
dirinfo->fd_name[ndx++] = ch;
}
errout:
return -EINVAL;
}
/****************************************************************************
* Name: fat_parselfname
*
* Desciption: Convert a user filename into a properly formatted FAT
* long filename as it would appear in a directory entry. Here are
* the rules for the long file name in the directory:
*
* Valid characters are the same as for short file names EXCEPT:
*
* 1. '+', ',', ';', '=', '[', and ']' are accepted in the file name
* 2. '.' (dot) can occur more than once in a filename. Extension is
* the substring after the last dot.
*
* Returned value:
* OK - The path refers to a valid long file name and has been properly
* stored in dirinfo.
* <0 - Otherwise an negated error is returned meaning that the string is
* not a valid long file name:
*
* 1. Contains characters not in the printable character set,
* 2. Contains forbidden characters
* 3. File name is too long.
*
****************************************************************************/
#ifdef CONFIG_FAT_LFN
static inline int fat_parselfname(const char **path,
struct fat_dirinfo_s *dirinfo,
char *terminator)
{
const char *node = *path;
uint8_t ch;
int ndx = 0;
/* Loop until the name is successfully parsed or an error occurs */
for (;;)
{
/* Get the next byte from the path */
ch = *node++;
/* Check if this the last byte in this node of the name */
if ((ch == '\0' || ch == '/') && ndx != 0 )
{
/* Null terminate the string */
dirinfo->fd_lfname[ndx] = '\0';
/* Return the remaining sub-string and the terminating character. */
*terminator = ch;
*path = node;
return OK;
}
/* Accept only the printable character set (including space) */
else if (!isprint(ch))
{
goto errout;
}
/* Reject printable characters forbidden by FAT */
else if (ch == '"' || ch == '*' || ch == '/' || ch == ':' ||
ch == '<' || ch == '>' || ch == '?' || ch == '\\' ||
ch == '|')
{
goto errout;
}
/* Check if the file name exceeds the size permitted. */
if (ndx >= LDIR_MAXFNAME)
{
goto errout;
}
/* Save next character in the accumulated name */
dirinfo->fd_lfname[ndx++] = ch;
}
errout:
dirinfo->fd_lfname[0] = '\0';
return -EINVAL;
}
#endif
/****************************************************************************
* Name: fat_createalias
*
* Desciption: Given a valid long file name, create a short filename alias.
* Here are the rules for creation of the alias:
*
* 1. All uppercase
* 2. All dots except the last deleted
* 3. First 6 (uppercase) characters used as a base
* 4. Then ~1. The number is increased if the file already exists in the
* directory. If the number exeeds >10, then character stripped off the
* base.
* 5. The extension is the first 3 uppercase chars of extension.
*
* This function is called only from fat_putlfname()
*
* Returned value:
* OK - The alias was created correctly.
* <0 - Otherwise an negated error is returned.
*
****************************************************************************/
#ifdef CONFIG_FAT_LFN
static inline int fat_createalias(struct fat_dirinfo_s *dirinfo)
{
uint8_t ch; /* Current character being processed */
char *ext; /* Pointer to the extension substring */
char *src; /* Pointer to the long file name source */
int len; /* Total length of the long file name */
int namechars; /* Number of characters available in long name */
int extchars; /* Number of characters available in long name extension */
int endndx; /* Maximum index into the short name array */
int ndx; /* Index to store next character */
/* First, let's decide what is name and what is extension */
len = strlen((char*)dirinfo->fd_lfname);
ext = strrchr((char*)dirinfo->fd_lfname, '.');
if (ext)
{
ptrdiff_t tmp;
/* ext points to the final '.'. The difference in bytes from the
* beginning of the string is then the name length.
*/
tmp = ext - (char*)dirinfo->fd_lfname;
namechars = tmp;
/* And the rest, exluding the '.' is the extension. */
extchars = len - namechars - 1;
ext++;
}
else
{
/* No '.' found. It is all name and no extension. */
namechars = len;
extchars = 0;
}
/* Alias are always all upper case */
#ifdef CONFIG_FAT_LCNAMES
dirinfo->fd_ntflags = 0;
#endif
/* Initialized the short name with all spaces */
memset(dirinfo->fd_name, ' ', DIR_MAXFNAME);
/* Handle a special case where there is no name. Windows seems to use
* the extension plus random stuff then ~1 to pat to 8 bytes. Some
* examples:
*
* a.b -> a.b No long name
* a., -> A26BE~1._ Padded name to make unique, _ replaces ,
* .b -> B1DD2~1 Extension used as name
* .bbbbbbb -> BBBBBB~1 Extension used as name
* a.bbbbbbb -> AAD39~1.BBB Padded name to make unique.
* aaa.bbbbbbb -> AAA~1.BBBB Not padded, already unique?
* ,.bbbbbbb -> _82AF~1.BBB _ replaces ,
* +[],.bbbbbbb -> ____~1.BBB _ replaces +[],
*/
if (namechars < 1)
{
/* Use the extension as the name */
DEBUGASSERT(ext && extchars > 0);
src = ext;
ext = NULL;
namechars = extchars;
extchars = 0;
}
else
{
src = (char*)dirinfo->fd_lfname;
}
/* Then copy the name and extension, handling upper case conversions and
* excluding forbidden characters.
*/
ndx = 0; /* Position to write the next name character */
endndx = 6; /* Maximum index before we write ~! and switch to the extension */
for (;;)
{
/* Get the next byte from the path. Break out of the loop if we
* encounter the end of null-terminated the long file name string.
*/
ch = *src++;
if (ch == '\0')
{
/* This is the end of the source string. Do we need to add ~1. We
* will do that if we were parsing the name part when the endo of
* string was encountered.
*/
if (endndx == 6)
{
/* Write the ~1 at the end of the name */
dirinfo->fd_name[ndx++] = '~';
dirinfo->fd_name[ndx] = '1';
}
/* In any event, we are done */
return OK;
}
/* Exclude those few characters included in long file names, but
* excluded in short file name: '+', ',', ';', '=', '[', ']', and '.'
*/
if (ch == '+' || ch == ',' || ch == '.' || ch == ';' ||
ch == '=' || ch == '[' || ch == ']' || ch == '|')
{
/* Use the underbar character instead */
ch = '_';
}
/* Handle lower case characters */
ch = toupper(ch);
/* We now have a valid character to add to the name or extension. */
dirinfo->fd_name[ndx++] = ch;
/* Did we just add a character to the name? */
if (endndx == 6)
{
/* Decrement the number of characters available in the name
* portion of the long name.
*/
namechars--;
/* Is it time to add ~1 to the string? We will do that if
* either (1) we have already added the maximum number of
* characters to the short name, or (2) if there are no further
* characters available in the name portion of the long name.
*/
if (namechars < 1 || ndx == 6)
{
/* Write the ~1 at the end of the name */
dirinfo->fd_name[ndx++] = '~';
dirinfo->fd_name[ndx] = '1';
/* Then switch to the extension (if there is one) */
if (!ext || extchars < 1)
{
return OK;
}
ndx = 8;
endndx = 11;
src = ext;
}
}
/* No.. we just added a character to the extension */
else
{
/* Decrement the number of characters available in the name
* portion of the long name
*/
extchars--;
/* Is the extension complete? */
if (extchars < 1 || ndx == 11)
{
return OK;
}
}
}
}
#endif
/****************************************************************************
* Name: fat_findalias
*
* Desciption: Make sure that the short alias for the long file name is
* unique, ie., that there is no other
*
* NOTE: This function does not restore the directory entry that was in the
* sector cache
*
* Returned value:
* OK - The alias is unique.
* <0 - Otherwise an negated error is returned.
*
****************************************************************************/
#ifdef CONFIG_FAT_LFN
static inline int fat_findalias(struct fat_mountpt_s *fs,
struct fat_dirinfo_s *dirinfo)
{
struct fat_dirinfo_s tmpinfo;
/* Save the current directory info. */
memcpy(&tmpinfo, dirinfo, sizeof(struct fat_dirinfo_s));
/* Then re-initialize to the beginning of the current directory, skipping
* over the first entry (unused in the root directory and '.' entry in other
* directories).
*/
tmpinfo.dir.fd_startcluster = tmpinfo.dir.fd_currcluster;
tmpinfo.dir.fd_currsector = tmpinfo.fd_seq.ds_startsector;
tmpinfo.dir.fd_index = 1;
/* Search for the single short file name directory entry in this directory */
return fat_findsfnentry(fs, &tmpinfo);
}
#endif
/****************************************************************************
* Name: fat_uniquealias
*
* Desciption: Make sure that the short alias for the long file name is
* unique, modifying the alias as necessary to assure uniqueness.
*
* NOTE: This function does not restore the directory entry that was in the
* sector cache
*
* information upon return.
* Returned value:
* OK - The alias is unique.
* <0 - Otherwise an negated error is returned.
*
****************************************************************************/
#ifdef CONFIG_FAT_LFN
static inline int fat_uniquealias(struct fat_mountpt_s *fs,
struct fat_dirinfo_s *dirinfo)
{
int tilde;
int lsdigit;
int ret;
int i;
/* Find the position of the tilde character in the short name. The tilde
* can not occur in positions 0 or 7:
*/
for (tilde = 1; tilde < 7 && dirinfo->fd_name[tilde] != '~'; tilde++);
if (tilde >= 7)
{
return -EINVAL;
}
/* The least significant number follows the digit (and must be '1') */
lsdigit = tilde + 1;
DEBUGASSERT(dirinfo->fd_name[lsdigit] == '1');
/* Search for the single short file name directory entry in this directory */
while ((ret = fat_findalias(fs, dirinfo)) == OK)
{
/* Adjust the numeric value after the '~' to make the file name unique */
for (i = lsdigit; i > 0; i--)
{
/* If we have backed up to the tilde position, then we have to move
* the tilde back one position.
*/
if (i == tilde)
{
/* Is there space to back up the tilde? */
if (tilde <= 1)
{
/* No.. then we cannot add the name to the directory.
* What is the likelihood of that happening?
*/
return -ENOSPC;
}
/* Back up the tilde and break out of the inner loop */
tilde--;
dirinfo->fd_name[tilde] = '~';
dirinfo->fd_name[tilde+1] = '1';
break;
}
/* We are not yet at the tilde,. Check if this digit has already
* reached its maximum value.
*/
else if (dirinfo->fd_name[i] < '9')
{
/* No, it has not.. just increment the LS digit and break out of
* the inner loop.
*/
dirinfo->fd_name[i]++;
break;
}
/* Yes.. Reset the digit to '0' and loop to adjust the digit before
* this one.
*/
else
{
dirinfo->fd_name[i] = '0';
}
}
}
/* The while loop terminated because of an error; fat_findalias()
* returned something other than OK. The only acceptable error is
* -ENOENT, meaning that the short file name directory does not
* exist in this directory.
*/
if (ret == -ENOENT)
{
ret = OK;
}
return ret;
}
#endif
/****************************************************************************
* Name: fat_path2dirname
*
* Desciption: Convert a user filename into a properly formatted FAT
* (short 8.3) filename as it would appear in a directory entry.
*
****************************************************************************/
static int fat_path2dirname(const char **path, struct fat_dirinfo_s *dirinfo,
char *terminator)
{
#ifdef CONFIG_FAT_LFN
int ret;
/* Assume no long file name */
dirinfo->fd_lfname[0] = '\0';
/* Then parse the (assumed) 8+3 short file name */
ret = fat_parsesfname(path, dirinfo, terminator);
if (ret < 0)
{
/* No, the name is not a valid short 8+3 file name. Try parsing
* the long file name.
*/
ret = fat_parselfname(path, dirinfo, terminator);
}
return ret;
#else
/* Only short, 8+3 filenames supported */
return fat_parsesfname(path, dirinfo, terminator);
#endif
}
/****************************************************************************
* Name: fat_findsfnentry
*
* Desciption: Find a short file name directory entry. Returns OK if the
* directory exists; -ENOENT if it does not.
*
****************************************************************************/
static int fat_findsfnentry(struct fat_mountpt_s *fs,
struct fat_dirinfo_s *dirinfo)
{
uint16_t diroffset;
uint8_t *direntry;
#ifdef CONFIG_FAT_LFN
off_t startsector;
#endif
int ret;
/* Save the starting sector of the directory. This is not really needed
* for short name entries, but this keeps things consistent with long
* file name entries..
*/
#ifdef CONFIG_FAT_LFN
startsector = dirinfo->dir.fd_currsector;
#endif
/* Search, beginning with the current sector, for a directory entry with
* the matching short name
*/
for (;;)
{
/* Read the next sector into memory */
ret = fat_fscacheread(fs, dirinfo->dir.fd_currsector);
if (ret < 0)
{
return ret;
}
/* Get a pointer to the directory entry */
diroffset = DIRSEC_BYTENDX(fs, dirinfo->dir.fd_index);
direntry = &fs->fs_buffer[diroffset];
/* Check if we are at the end of the directory */
if (direntry[DIR_NAME] == DIR0_ALLEMPTY)
{
return -ENOENT;
}
/* Check if we have found the directory entry that we are looking for */
if (direntry[DIR_NAME] != DIR0_EMPTY &&
!(DIR_GETATTRIBUTES(direntry) & FATATTR_VOLUMEID) &&
!memcmp(&direntry[DIR_NAME], dirinfo->fd_name, DIR_MAXFNAME) )
{
/* Yes.. Return success */
dirinfo->fd_seq.ds_sector = fs->fs_currentsector;
dirinfo->fd_seq.ds_offset = diroffset;
#ifdef CONFIG_FAT_LFN
dirinfo->fd_seq.ds_cluster = dirinfo->dir.fd_currcluster;
dirinfo->fd_seq.ds_startsector = startsector;
/* Position the last long file name directory entry at the same
* position.
*/
dirinfo->fd_seq.ds_lfnsector = dirinfo->fd_seq.ds_sector;
dirinfo->fd_seq.ds_lfnoffset = dirinfo->fd_seq.ds_offset;
dirinfo->fd_seq.ds_lfncluster = dirinfo->fd_seq.ds_cluster;
#endif
return OK;
}
/* No... get the next directory index and try again */
if (fat_nextdirentry(fs, &dirinfo->dir) != OK)
{
return -ENOENT;
}
}
}
/****************************************************************************
* Name: fat_cmplfnchunk
*
* Desciption: There are 13 characters per LFN entry, broken up into three
* chunks for characts 1-5, 6-11, and 12-13. This function will perform
* the comparison of a single chunk.
*
****************************************************************************/
#ifdef CONFIG_FAT_LFN
static bool fat_cmplfnchunk(uint8_t *chunk, const uint8_t *substr, int nchunk)
{
wchar_t wch;
uint8_t ch;
int i;
/* Check bytes 1-nchunk */
for (i = 0; i < nchunk; i++)
{
/* Get the next character from the name string (which might be the NUL
* terminating character).
*/
if (*substr == '\0')
{
ch = '\0';
}
else
{
ch = *substr++;
}
/* Get the next unicode character from the chunk. We only handle
* ASCII. For ASCII, the upper byte should be zero and the lower
* should match the ASCII code.
*/
wch = (wchar_t)fat_getuint16((uint8_t*)chunk);
if ((wch & 0xff) != (wchar_t)ch)
{
return false;
}
/* The characters match. If we just matched the NUL terminating
* character, then the strings match and we are finished.
*/
if (ch == '\0')
{
return true;
}
/* Try the next character from the directory entry. */
chunk += sizeof(wchar_t);
}
/* All of the characters in the chunk match.. Return success */
return true;
}
#endif
/****************************************************************************
* Name: fat_cmplfname
*
* Desciption: Given an LFN directory entry, compare a substring of the name
* to a portion in the directory entry.
*
****************************************************************************/
#ifdef CONFIG_FAT_LFN
static bool fat_cmplfname(const uint8_t *direntry, const uint8_t *substr)
{
uint8_t *chunk;
int len;
bool match;
/* How much of string do we have to compare? (including the NUL
* terminator).
*/
len = strlen((char*)substr) + 1;
/* Check bytes 1-5 */
chunk = LDIR_PTRWCHAR1_5(direntry);
match = fat_cmplfnchunk(chunk, substr, 5);
if (match && len > 5)
{
/* Check bytes 6-11 */
chunk = LDIR_PTRWCHAR6_11(direntry);
match = fat_cmplfnchunk(chunk, &substr[5], 6);
if (match && len > 11)
{
/* Check bytes 12-13 */
chunk = LDIR_PTRWCHAR12_13(direntry);
match = fat_cmplfnchunk(chunk, &substr[11], 2);
}
}
return match;
}
#endif
/****************************************************************************
* Name: fat_findlfnentry
*
* Desciption: Find a sequence of long file name directory entries.
*
* NOTE: As a side effect, this function returns with the sector containing
* the short file name directory entry in the cache.
*
****************************************************************************/
#ifdef CONFIG_FAT_LFN
static inline int fat_findlfnentry(struct fat_mountpt_s *fs,
struct fat_dirinfo_s *dirinfo)
{
uint16_t diroffset;
uint8_t *direntry;
uint8_t lastseq;
uint8_t seqno;
uint8_t nfullentries;
uint8_t nentries;
uint8_t remainder;
uint8_t checksum = 0;
off_t startsector;
int offset;
int namelen;
int ret;
/* Get the length of the long file name (size of the fd_lfname array is
* LDIR_MAXFNAME+1 we do not have to check the length of the string).
*/
namelen = strlen((char*)dirinfo->fd_lfname);
DEBUGASSERT(namelen <= LDIR_MAXFNAME+1);
/* How many LFN directory entries are we expecting? */
nfullentries = namelen / LDIR_MAXLFNCHARS;
remainder = namelen - nfullentries * LDIR_MAXLFNCHARS;
nentries = nfullentries;
if (remainder > 0)
{
nentries++;
}
DEBUGASSERT(nentries > 0 && nentries <= LDIR_MAXLFNS);
/* This is the first sequency number we are looking for, the sequence
* number of the last LFN entry (remember that they appear in reverse
* order.. from last to first).
*/
lastseq = LDIR0_LAST | nentries;
seqno = lastseq;
/* Save the starting sector of the directory. This is needed later to
* re-scan the directory, looking duplicate short alias names.
*/
startsector = dirinfo->dir.fd_currsector;
/* Search, beginning with the current sector, for a directory entry this
* the match shore name
*/
for (;;)
{
/* Read the next sector into memory */
ret = fat_fscacheread(fs, dirinfo->dir.fd_currsector);
if (ret < 0)
{
return ret;
}
/* Get a pointer to the directory entry */
diroffset = DIRSEC_BYTENDX(fs, dirinfo->dir.fd_index);
direntry = &fs->fs_buffer[diroffset];
/* Check if we are at the end of the directory */
if (direntry[DIR_NAME] == DIR0_ALLEMPTY)
{
return -ENOENT;
}
/* Is this an LFN entry? Does it have the sequence number we are
* looking for?
*/
if (LDIR_GETATTRIBUTES(direntry) != LDDIR_LFNATTR ||
LDIR_GETSEQ(direntry) != seqno)
{
/* No, restart the search at the next entry */
seqno = lastseq;
goto next_entry;
}
/* Yes.. If this is not the "last" LFN entry, then the checksum must
* also be the same.
*/
if (seqno == lastseq)
{
/* Just save the checksum for subsequent checks */
checksum = LDIR_GETCHECKSUM(direntry);
}
/* Not the first entry in the sequence. Does the checksum match the
* previous sequences?
*/
else if (checksum != LDIR_GETCHECKSUM(direntry))
{
/* No, restart the search at the next entry */
seqno = lastseq;
goto next_entry;
}
/* Check if the name substring in this LFN matches the corresponding
* substring of the name we are looking for.
*/
offset = ((seqno & LDIR0_SEQ_MASK) - 1) * LDIR_MAXLFNCHARS;
if (fat_cmplfname(direntry, &dirinfo->fd_lfname[offset]))
{
/* Yes.. it matches. Check the sequence number. Is this the
* "last" LFN entry (i.e., the one that appears first)?
*/
if (seqno == lastseq)
{
/* Yes.. Save information about this LFN entry position */
dirinfo->fd_seq.ds_lfnsector = fs->fs_currentsector;
dirinfo->fd_seq.ds_lfnoffset = diroffset;
dirinfo->fd_seq.ds_lfncluster = dirinfo->dir.fd_currcluster;
dirinfo->fd_seq.ds_startsector = startsector;
seqno &= LDIR0_SEQ_MASK;
}
/* Is this the first sequence number (i.e., the LFN entry that
* will appear last)?
*/
if (seqno == 1)
{
/* We have found all of the LFN entries. The next directory
* entry should be the one containing the short file name
* alias and all of the meat about the file or directory.
*/
if (fat_nextdirentry(fs, &dirinfo->dir) != OK)
{
return -ENOENT;
}
/* Make sure that the directory entry is in the sector cache */
ret = fat_fscacheread(fs, dirinfo->dir.fd_currsector);
if (ret < 0)
{
return ret;
}
/* Get a pointer to the directory entry */
diroffset = DIRSEC_BYTENDX(fs, dirinfo->dir.fd_index);
direntry = &fs->fs_buffer[diroffset];
/* Verify the checksum */
if (fat_lfnchecksum(&direntry[DIR_NAME]) == checksum)
{
/* Success! Save the position of the directory entry and
* return success.
*/
dirinfo->fd_seq.ds_sector = fs->fs_currentsector;
dirinfo->fd_seq.ds_offset = diroffset;
dirinfo->fd_seq.ds_cluster = dirinfo->dir.fd_currcluster;
return OK;
}
/* Bad news.. reset and continue with this entry (which is
* probably not an LFN entry unless the file systen is
* seriously corrupted.
*/
seqno = lastseq;
continue;
}
/* No.. there are more LFN entries to go. Decrement the sequence
* number and check the next directory entry.
*/
seqno--;
}
else
{
/* No.. the names do not match. Restart the search at the next
* entry.
*/
seqno = lastseq;
}
/* Continue at the next directory entry */
next_entry:
if (fat_nextdirentry(fs, &dirinfo->dir) != OK)
{
return -ENOENT;
}
}
}
#endif
/****************************************************************************
* Name: fat_allocatesfnentry
*
* Desciption: Find a free directory entry for a short file name entry.
*
****************************************************************************/
static inline int fat_allocatesfnentry(struct fat_mountpt_s *fs,
struct fat_dirinfo_s *dirinfo)
{
uint16_t diroffset;
uint8_t *direntry;
#ifdef CONFIG_FAT_LFN
off_t startsector;
#endif
uint8_t ch;
int ret;
/* Save the sector number of the first sector of the directory. We don't
* really need this for short file name entries; this is just done for
* consistency with the long file name logic.
*/
#ifdef CONFIG_FAT_LFN
startsector = dirinfo->dir.fd_currsector;
#endif
/* Then search for a free short file name directory entry */
for (;;)
{
/* Read the directory sector into fs_buffer */
ret = fat_fscacheread(fs, dirinfo->dir.fd_currsector);
if (ret < 0)
{
/* Make sure that the return value is NOT -ENOSPC */
return -EIO;
}
/* Get a pointer to the entry at fd_index */
diroffset = (dirinfo->dir.fd_index & DIRSEC_NDXMASK(fs)) * DIR_SIZE;
direntry = &fs->fs_buffer[diroffset];
/* Check if this directory entry is empty */
ch = direntry[DIR_NAME];
if (ch == DIR0_ALLEMPTY || ch == DIR0_EMPTY)
{
/* It is empty -- we have found a directory entry */
dirinfo->fd_seq.ds_sector = fs->fs_currentsector;
dirinfo->fd_seq.ds_offset = diroffset;
#ifdef CONFIG_FAT_LFN
dirinfo->fd_seq.ds_cluster = dirinfo->dir.fd_currcluster;
dirinfo->fd_seq.ds_startsector = startsector;
/* Set the "last" long file name offset to the same entry */
dirinfo->fd_seq.ds_lfnsector = dirinfo->fd_seq.ds_sector;
dirinfo->fd_seq.ds_lfnoffset = dirinfo->fd_seq.ds_offset;
dirinfo->fd_seq.ds_lfncluster = dirinfo->fd_seq.ds_cluster;
#endif
return OK;
}
/* It is not empty try the next one */
ret = fat_nextdirentry(fs, &dirinfo->dir);
if (ret < 0)
{
/* This will return -ENOSPC if we have examined all of the
* directory entries without finding a free entry.
*/
return ret;
}
}
}
/****************************************************************************
* Name: fat_allocatelfnentry
*
* Desciption: Find a sequence of free directory entries for a several long
* and one short file name entry.
*
* On entry, dirinfo.dir refers to the first interesting entry the directory.
*
****************************************************************************/
#ifdef CONFIG_FAT_LFN
static inline int fat_allocatelfnentry(struct fat_mountpt_s *fs,
struct fat_dirinfo_s *dirinfo)
{
uint16_t diroffset;
uint8_t *direntry;
off_t startsector;
uint8_t nentries;
uint8_t remainder;
uint8_t needed;
uint8_t ch;
int namelen;
int ret;
/* Get the length of the long file name (size of the fd_lfname array is
* LDIR_MAXFNAME+1 we do not have to check the length of the string).
*/
namelen = strlen((char *)dirinfo->fd_lfname);
DEBUGASSERT(namelen <= LDIR_MAXFNAME+1);
/* How many LFN directory entries are we expecting? */
nentries = namelen / LDIR_MAXLFNCHARS;
remainder = namelen - nentries * LDIR_MAXLFNCHARS;
if (remainder > 0)
{
nentries++;
}
DEBUGASSERT(nentries > 0 && nentries <= LDIR_MAXLFNS);
/* Plus another for short file name entry that follows the sequence of LFN
* entries.
*/
nentries++;
/* Save the sector number of the first sector of the directory. We will
* need this later for re-scanning the directory to verify that a FAT file
* name is unique.
*/
startsector = dirinfo->dir.fd_currsector;
/* Now, search the directory looking for a sequence for free entries that
* long.
*/
needed = nentries;
for (;;)
{
/* Read the directory sector into fs_buffer */
ret = fat_fscacheread(fs, dirinfo->dir.fd_currsector);
if (ret < 0)
{
/* Make sure that the return value is NOT -ENOSPC */
return -EIO;
}
/* Get a pointer to the entry at fd_index */
diroffset = (dirinfo->dir.fd_index & DIRSEC_NDXMASK(fs)) * DIR_SIZE;
direntry = &fs->fs_buffer[diroffset];
/* Check if this directory entry is empty */
ch = LDIR_GETSEQ(direntry);
if (ch == DIR0_ALLEMPTY || ch == DIR0_EMPTY)
{
/* It is empty -- we have found a directory entry. Is this the
* "last" LFN entry (i.e., the one that occurs first)?
*/
if (needed == nentries)
{
/* Yes.. remember the position of this entry */
dirinfo->fd_seq.ds_lfnsector = fs->fs_currentsector;
dirinfo->fd_seq.ds_lfnoffset = diroffset;
dirinfo->fd_seq.ds_lfncluster = dirinfo->dir.fd_currcluster;
dirinfo->fd_seq.ds_startsector = startsector;
}
/* Is this last entry we need (i.e., the entry for the short
* file name entry)?
*/
if (needed <= 1)
{
/* Yes.. remember the position of this entry and return
* success.
*/
dirinfo->fd_seq.ds_sector = fs->fs_currentsector;
dirinfo->fd_seq.ds_offset = diroffset;
dirinfo->fd_seq.ds_cluster = dirinfo->dir.fd_currcluster;
return OK;
}
/* Otherwise, just decrement the number of directory entries
* needed and continue looking.
*/
needed--;
}
/* The directory entry is not available */
else
{
/* Reset the search and continue looking */
needed = nentries;
}
/* Try the next directory entry */
ret = fat_nextdirentry(fs, &dirinfo->dir);
if (ret < 0)
{
/* This will return -ENOSPC if we have examined all of the
* directory entries without finding a free entry.
*/
return ret;
}
}
}
#endif
/****************************************************************************
* Name: fat_getsfname
*
* Desciption: Get the 8.3 filename from a directory entry. On entry, the
* short file name entry is already in the cache.
*
****************************************************************************/
static inline int fat_getsfname(uint8_t *direntry, char *buffer,
unsigned int buflen)
{
#ifdef CONFIG_FAT_LCNAMES
uint8_t ntflags;
#endif
int ch;
int ndx;
/* Check if we will be doing upper to lower case conversions */
#ifdef CONFIG_FAT_LCNAMES
ntflags = DIR_GETNTRES(direntry);
#endif
/* Reserve a byte for the NUL terminator */
buflen--;
/* Get the 8-byte filename */
for (ndx = 0; ndx < 8 && buflen > 0; ndx++)
{
/* Get the next filename character from the directory entry */
ch = direntry[ndx];
/* Any space (or ndx==8) terminates the filename */
if (ch == ' ')
{
break;
}
/* In this version, we never write 0xe5 in the directory filenames
* (because we do not handle any character sets where 0xe5 is valid
* in a filaname), but we could encounted this in a filesystem
* written by some other system
*/
if (ndx == 0 && ch == DIR0_E5)
{
ch = 0xe5;
}
/* Check if we should perform upper to lower case conversion
* of the (whole) filename.
*/
#ifdef CONFIG_FAT_LCNAMES
if (ntflags & FATNTRES_LCNAME && isupper(ch))
{
ch = tolower(ch);
}
#endif
/* Copy the next character into the filename */
*buffer++ = ch;
buflen--;
}
/* Check if there is an extension */
if (direntry[8] != ' ' && buflen > 0)
{
/* Yes, output the dot before the extension */
*buffer++ = '.';
buflen--;
/* Then output the (up to) 3 character extension */
for (ndx = 8; ndx < 11 && buflen > 0; ndx++)
{
/* Get the next extensions character from the directory entry */
ch = direntry[DIR_NAME + ndx];
/* Any space (or ndx==11) terminates the extension */
if (ch == ' ')
{
break;
}
/* Check if we should perform upper to lower case conversion
* of the (whole) filename.
*/
#ifdef CONFIG_FAT_LCNAMES
if (ntflags & FATNTRES_LCEXT && isupper(ch))
{
ch = tolower(ch);
}
#endif
/* Copy the next character into the filename */
*buffer++ = ch;
buflen--;
}
}
/* Put a null terminator at the end of the filename. We don't have to
* check if there is room because we reserved a byte for the NUL
* terminator at the beginning of this function.
*/
*buffer = '\0';
return OK;
}
/****************************************************************************
* Name: fat_getlfnchunk
*
* Desciption: There are 13 characters per LFN entry, broken up into three
* chunks for characts 1-5, 6-11, and 12-13. This function will get the
* file name characters from one chunk.
*
****************************************************************************/
#ifdef CONFIG_FAT_LFN
static void fat_getlfnchunk(uint8_t *chunk, uint8_t *dest, int nchunk)
{
wchar_t wch;
int i;
/* Copy bytes 1-nchunk */
for (i = 0; i < nchunk; i++)
{
/* Get the next unicode character from the chunk. We only handle ASCII.
* For ASCII, the upper byte should be zero and the lower should match
* the ASCII code.
*/
wch = (wchar_t)fat_getuint16(chunk);
*dest++ = (uint8_t)(wch & 0xff);
chunk += sizeof(wchar_t);
}
}
#endif
/****************************************************************************
* Name: fat_getlfname
*
* Desciption: Get the long filename from a sequence of directory entries.
* On entry, the "last" long file name entry is in the cache. Returns with
* the short file name entry in the cache.
*
****************************************************************************/
#ifdef CONFIG_FAT_LFN
static inline int fat_getlfname(struct fat_mountpt_s *fs, struct fs_dirent_s *dir)
{
uint8_t lfname[LDIR_MAXLFNCHARS];
uint16_t diroffset;
uint8_t *direntry;
uint8_t seqno;
uint8_t rawseq;
uint8_t offset;
uint8_t checksum;
int nsrc;
int ret;
int i;
/* Get a reference to the current directory entry */
diroffset = (dir->u.fat.fd_index & DIRSEC_NDXMASK(fs)) * DIR_SIZE;
direntry = &fs->fs_buffer[diroffset];
/* Get the starting sequence number */
seqno = LDIR_GETSEQ(direntry);
DEBUGASSERT((seqno & LDIR0_LAST) != 0);
/* Sanity check */
rawseq = (seqno & LDIR0_SEQ_MASK);
if (rawseq < 1 || rawseq > LDIR_MAXLFNS)
{
return -EINVAL;
}
/* Save the checksum value */
checksum = LDIR_GETCHECKSUM(direntry);
/* Loop until the whole file name has been transferred */
for (;;)
{
/* Get the string offset associated with the "last" entry. */
offset = (rawseq - 1) * LDIR_MAXLFNCHARS;
/* Will any of this file name fit into the destination buffer? */
if (offset < NAME_MAX)
{
/* Yes.. extract and convert the unicode name */
fat_getlfnchunk(LDIR_PTRWCHAR1_5(direntry), lfname, 5);
fat_getlfnchunk(LDIR_PTRWCHAR6_11(direntry), &lfname[5], 6);
fat_getlfnchunk(LDIR_PTRWCHAR12_13(direntry), &lfname[11], 2);
/* Ignore trailing spaces on the "last" directory entry. The
* number of characters avaiable is LDIR_MAXLFNCHARS or that
* minus the number of trailing spaces on the "last" directory
* entry.
*/
nsrc = LDIR_MAXLFNCHARS;
if ((seqno & LDIR0_LAST) != 0)
{
/* Reduce the number of characters by the number of trailing
* spaces.
*/
for (; nsrc > 0 && lfname[nsrc-1] == ' '; nsrc--);
/* Further reduce the length so that it fits in the destination
* buffer.
*/
if (offset + nsrc > NAME_MAX)
{
nsrc = NAME_MAX - offset;
}
/* Add a null terminator to the destination string (the actual
* length of the destination buffer is NAME_MAX+1, so the NUL
* terminator will fit).
*/
dir->fd_dir.d_name[offset+nsrc] = '\0';
}
/* Then transfer the characters */
for (i = 0; i < nsrc && offset+i < NAME_MAX; i++)
{
dir->fd_dir.d_name[offset+i] = lfname[i];
}
}
/* Read next directory entry */
if (fat_nextdirentry(fs, &dir->u.fat) != OK)
{
return -ENOENT;
}
/* Make sure that the directory sector into the sector cache */
ret = fat_fscacheread(fs, dir->u.fat.fd_currsector);
if (ret < 0)
{
return ret;
}
/* Get a reference to the current directory entry */
diroffset = (dir->u.fat.fd_index & DIRSEC_NDXMASK(fs)) * DIR_SIZE;
direntry = &fs->fs_buffer[diroffset];
/* Get the next expected sequence number. */
seqno = --rawseq;
if (seqno < 1)
{
/* We just completed processing the "first" long file name entry
* and we just read the short file name entry. Verify that the
* checksum of the short file name matches the checksum that we
* found in the long file name entries.
*/
if (fat_lfnchecksum(direntry) == checksum)
{
/* Yes.. return success! */
return OK;
}
/* No, the checksum is bad. */
return -EINVAL;
}
/* Verify the next long file name entry. Is this an LFN entry? Does it
* have the sequence number we are looking for? Does the checksum
* match the previous entries?
*/
if (LDIR_GETATTRIBUTES(direntry) != LDDIR_LFNATTR ||
LDIR_GETSEQ(direntry) != seqno ||
LDIR_GETCHECKSUM(direntry) != checksum)
{
return -EINVAL;
}
}
}
#endif
/****************************************************************************
* Name: fat_dirverify
*
* Desciption:
* Verify that every entry preceding this one is marked with something
* other than DIR0_ALLEMPTY. This is necessary only in the root directory
* of freshly formatted volumes. In that case, all entries are set to
* zero.
*
* This function also assures that the sector containing the entry is in
* the sector cache.
*
****************************************************************************/
static int fat_dirverify(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo,
uint16_t offset)
{
uint8_t *direntry;
uint16_t i;
int ret;
/* Make sure that the sector containing the directory entry is in the sector
* cache.
*/
ret = fat_fscacheread(fs, dirinfo->dir.fd_currsector);
if (ret < 0)
{
return ret;
}
/* Check every entry preceding this one */
for (i = 0; i < offset; i += DIR_SIZE)
{
/* Is the rest of the directory marked empty? */
direntry = &fs->fs_buffer[i];
if (direntry[DIR_NAME] == DIR0_ALLEMPTY)
{
/* Then mark the just the entry as empty */
fs->fs_dirty = true;
direntry[DIR_NAME] = DIR0_EMPTY;
}
}
return OK;
}
/****************************************************************************
* Name: fat_putsfname
*
* Desciption: Write the short directory entry name.
*
* Assumption: The directory sector is in the cache.
*
****************************************************************************/
static int fat_putsfname(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo)
{
uint8_t *direntry = &fs->fs_buffer[dirinfo->fd_seq.ds_offset];
/* Write the short directory entry */
memcpy(&direntry[DIR_NAME], dirinfo->fd_name, DIR_MAXFNAME);
#ifdef CONFIG_FAT_LCNAMES
DIR_PUTNTRES(direntry, dirinfo->fd_ntflags);
#else
DIR_PUTNTRES(direntry, 0);
#endif
fs->fs_dirty = true;
return OK;
}
/****************************************************************************
* Name: fat_initlfname
*
* Desciption: There are 13 characters per LFN entry, broken up into three
* chunks for characts 1-5, 6-11, and 12-13. This function will put the
* 0xffff characters into one chunk.
*
****************************************************************************/
#ifdef CONFIG_FAT_LFN
static void fat_initlfname(uint8_t *chunk, int nchunk)
{
int i;
/* Initialize unicode characters 1-nchunk */
for (i = 0; i < nchunk; i++)
{
/* The write the 16-bit 0xffff character into the directory entry. */
fat_putuint16((uint8_t *)chunk, (uint16_t)0xffff);
chunk += sizeof(wchar_t);
}
}
#endif
/****************************************************************************
* Name: fat_putlfnchunk
*
* Desciption: There are 13 characters per LFN entry, broken up into three
* chunks for characts 1-5, 6-11, and 12-13. This function will put the
* file name characters into one chunk.
*
****************************************************************************/
#ifdef CONFIG_FAT_LFN
static void fat_putlfnchunk(uint8_t *chunk, const uint8_t *src, int nchunk)
{
uint16_t wch;
int i;
/* Write bytes 1-nchunk */
for (i = 0; i < nchunk; i++)
{
/* Get the next ascii character from the name substring and convert it
* to unicode. The upper byte should be zero and the lower should be
* the ASCII code. The write the unicode character into the directory
* entry.
*/
wch = (uint16_t)*src++;
fat_putuint16(chunk, wch);
chunk += sizeof(wchar_t);
}
}
#endif
/****************************************************************************
* Name: fat_putlfname
*
* Desciption: Write the long filename into a sequence of directory entries.
* On entry, the "last" long file name entry is in the cache. Returns with
* the short file name entry in the cache.
*
****************************************************************************/
#ifdef CONFIG_FAT_LFN
static int fat_putlfname(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo)
{
uint16_t diroffset;
uint8_t *direntry;
uint8_t nfullentries;
uint8_t nentries;
uint8_t remainder;
uint8_t offset;
uint8_t seqno;
uint8_t checksum;
int namelen;
int ret;
/* Some special handling in case we are writing the first entry of the
* root directory in a freshly formatted volume.
*/
(void)fat_dirverify(fs, dirinfo, dirinfo->fd_seq.ds_lfnoffset);
/* Get the length of the long file name (size of the fd_lfname array is
* LDIR_MAXFNAME+1 we do not have to check the length of the string).
* NOTE that remainder is conditionally incremented to include the NUL
* terminating character that may also need be written to the directory
* entry. NUL terminating is not required if length is multiple of
* LDIR_MAXLFNCHARS (13).
*/
namelen = strlen((char*)dirinfo->fd_lfname);
DEBUGASSERT(namelen <= LDIR_MAXFNAME+1);
/* How many LFN directory entries do we need to write? */
nfullentries = namelen / LDIR_MAXLFNCHARS;
remainder = namelen - nfullentries * LDIR_MAXLFNCHARS;
nentries = nfullentries;
if (remainder > 0)
{
nentries++;
remainder++;
}
DEBUGASSERT(nentries > 0 && nentries <= LDIR_MAXLFNS);
/* Create the short file name alias */
ret = fat_createalias(dirinfo);
if (ret < 0)
{
return ret;
}
/* Set up the initial positional data */
dirinfo->dir.fd_currcluster = dirinfo->fd_seq.ds_lfncluster;
dirinfo->dir.fd_currsector = dirinfo->fd_seq.ds_lfnsector;
dirinfo->dir.fd_index = dirinfo->fd_seq.ds_lfnoffset / DIR_SIZE;
/* Make sure that the alias is unique in this directory*/
ret = fat_uniquealias(fs, dirinfo);
if (ret < 0)
{
return ret;
}
/* Get the short file name checksum */
checksum = fat_lfnchecksum(dirinfo->fd_name);
/* Setup the starting sequence number */
seqno = LDIR0_LAST | nentries;
/* Now loop, writing each long file name entry. We know that the sector
* is in the sector cache because fat_dirverify() assures us that that is
* so.
*/
for (;;)
{
/* Get the string offset associated with the directory entry. */
offset = (nentries - 1) * LDIR_MAXLFNCHARS;
/* Get a reference to the current directory entry */
diroffset = (dirinfo->dir.fd_index & DIRSEC_NDXMASK(fs)) * DIR_SIZE;
direntry = &fs->fs_buffer[diroffset];
/* Is this the "last" LFN directory entry? */
if ((seqno & LDIR0_LAST) != 0 && remainder != 0)
{
int nbytes;
/* Initialize the "last" directory entry name to all 0xffff */
fat_initlfname(LDIR_PTRWCHAR1_5(direntry), 5);
fat_initlfname(LDIR_PTRWCHAR6_11(direntry), 6);
fat_initlfname(LDIR_PTRWCHAR12_13(direntry), 2);
/* Store the tail portion of the long file name in directory entry */
nbytes = MIN(5, remainder);
fat_putlfnchunk(LDIR_PTRWCHAR1_5(direntry),
&dirinfo->fd_lfname[offset], nbytes);
remainder -= nbytes;
if (remainder > 0)
{
nbytes = MIN(6, remainder);
fat_putlfnchunk(LDIR_PTRWCHAR6_11(direntry),
&dirinfo->fd_lfname[offset+5], nbytes);
remainder -= nbytes;
}
if (remainder > 0)
{
nbytes = MIN(2, remainder);
fat_putlfnchunk(LDIR_PTRWCHAR12_13(direntry),
&dirinfo->fd_lfname[offset+11], nbytes);
remainder -= nbytes;
}
/* The remainder should now be zero */
DEBUGASSERT(remainder == 0);
}
else
{
/* Store a portion long file name in this directory entry */
fat_putlfnchunk(LDIR_PTRWCHAR1_5(direntry),
&dirinfo->fd_lfname[offset], 5);
fat_putlfnchunk(LDIR_PTRWCHAR6_11(direntry),
&dirinfo->fd_lfname[offset+5], 6);
fat_putlfnchunk(LDIR_PTRWCHAR12_13(direntry),
&dirinfo->fd_lfname[offset+11], 2);
}
/* Write the remaining directory entries */
LDIR_PUTSEQ(direntry, seqno);
LDIR_PUTATTRIBUTES(direntry, LDDIR_LFNATTR);
LDIR_PUTNTRES(direntry, 0);
LDIR_PUTCHECKSUM(direntry, checksum);
fs->fs_dirty = true;
/* Read next directory entry */
if (fat_nextdirentry(fs, &dirinfo->dir) != OK)
{
return -ENOENT;
}
/* Make sure that the sector containing the directory entry is in the
* sector cache
*/
ret = fat_fscacheread(fs, dirinfo->dir.fd_currsector);
if (ret < 0)
{
return ret;
}
/* Decrement the number of entries and get the next sequence number. */
if (--nentries <= 0)
{
/* We have written all of the long file name entries to the media
* and we have the short file name entry in the cache. We can
* just return success.
*/
return OK;
}
/* The sequence number is just the number of entries left to be
* written.
*/
seqno = nentries;
}
}
#endif
/****************************************************************************
* Name: fat_putsfdirentry
*
* Desciption: Write a short file name directory entry
*
* Assumption: The directory sector is in the cache. The caller will write
* sector information.
*
****************************************************************************/
static int fat_putsfdirentry(struct fat_mountpt_s *fs,
struct fat_dirinfo_s *dirinfo,
uint8_t attributes, uint32_t fattime)
{
uint8_t *direntry;
/* Some special handling in case we are writing the first entry of the
* root directory in a freshly formatted volume.
*/
(void)fat_dirverify(fs, dirinfo, dirinfo->fd_seq.ds_offset);
/* Initialize the 32-byte directory entry */
direntry = &fs->fs_buffer[dirinfo->fd_seq.ds_offset];
memset(direntry, 0, DIR_SIZE);
/* Directory name info */
(void)fat_putsfname(fs, dirinfo);
/* Set the attribute attribute, write time, creation time */
DIR_PUTATTRIBUTES(direntry, attributes);
/* Set the time information */
DIR_PUTWRTTIME(direntry, fattime & 0xffff);
DIR_PUTCRTIME(direntry, fattime & 0xffff);
DIR_PUTWRTDATE(direntry, fattime >> 16);
DIR_PUTCRDATE(direntry, fattime >> 16);
fs->fs_dirty = true;
return OK;
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: fat_finddirentry
*
* Desciption: Given a path to something that may or may not be in the file
* system, return the description of the directory entry of the requested
* item.
*
* NOTE: As a side effect, this function returns with the sector containing
* the short file name directory entry in the cache.
*
****************************************************************************/
int fat_finddirentry(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo,
const char *path)
{
off_t cluster;
uint8_t *direntry;
char terminator;
int ret;
/* Initialize to traverse the chain. Set it to the cluster of the root
* directory
*/
cluster = fs->fs_rootbase;
if (fs->fs_type == FSTYPE_FAT32)
{
/* For FAT32, the root directory is variable sized and is a cluster
* chain like any other directory. fs_rootbase holds the first
* cluster of the root directory.
*/
dirinfo->dir.fd_startcluster = cluster;
dirinfo->dir.fd_currcluster = cluster;
dirinfo->dir.fd_currsector = fat_cluster2sector(fs, cluster);
}
else
{
/* For FAT12/16, the first sector of the root directory is a sector
* relative to the first sector of the fat volume.
*/
dirinfo->dir.fd_startcluster = 0;
dirinfo->dir.fd_currcluster = 0;
dirinfo->dir.fd_currsector = cluster;
}
/* fd_index is the index into the current directory table. It is set to one
* to skip over the first, unused entry in the root directory.
*/
dirinfo->dir.fd_index = 1;
/* If no path was provided, then the root directory must be exactly what
* the caller is looking for.
*/
if (*path == '\0')
{
dirinfo->fd_root = true;
return OK;
}
/* This is not the root directory */
dirinfo->fd_root = false;
/* Now loop until the directory entry corresponding to the path is found */
for (;;)
{
/* Convert the next the path segment name into the kind of name that
* we would see in the directory entry.
*/
ret = fat_path2dirname(&path, dirinfo, &terminator);
if (ret < 0)
{
/* ERROR: The filename contains invalid characters or is
* too long.
*/
return ret;
}
/* Is this a path segment a long or a short file. Was a long file
* name parsed?
*/
#ifdef CONFIG_FAT_LFN
if (dirinfo->fd_lfname[0] != '\0')
{
/* Yes.. Search for the sequence of long file name directory
* entries. NOTE: As a side effect, this function returns with
* the sector containing the short file name directory entry
* in the cache.
*/
ret = fat_findlfnentry(fs, dirinfo);
}
else
#endif
{
/* No.. Search for the single short file name directory entry */
ret = fat_findsfnentry(fs, dirinfo);
}
/* Did we find the directory entries? */
if (ret < 0)
{
return ret;
}
/* If the terminator character in the path was the end of the string
* then we have successfully found the directory entry that describes
* the path.
*/
if (!terminator)
{
/* Return success meaning that the description the matching
* directory entry is in dirinfo.
*/
return OK;
}
/* No.. then we have found one of the intermediate directories on
* the way to the final path target. In this case, make sure
* the thing that we found is, indeed, a directory.
*/
direntry = &fs->fs_buffer[dirinfo->fd_seq.ds_offset];
if (!(DIR_GETATTRIBUTES(direntry) & FATATTR_DIRECTORY))
{
/* Ooops.. we found something else */
return -ENOTDIR;
}
/* Get the cluster number of this directory */
cluster =
((uint32_t)DIR_GETFSTCLUSTHI(direntry) << 16) |
DIR_GETFSTCLUSTLO(direntry);
/* Then restart scanning at the new directory, skipping over both the
* '.' and '..' entries that exist in all directories EXCEPT the root
* directory.
*/
dirinfo->dir.fd_startcluster = cluster;
dirinfo->dir.fd_currcluster = cluster;
dirinfo->dir.fd_currsector = fat_cluster2sector(fs, cluster);
dirinfo->dir.fd_index = 2;
}
}
/****************************************************************************
* Name: fat_allocatedirentry
*
* Desciption: Find a free directory entry
*
****************************************************************************/
int fat_allocatedirentry(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo)
{
int32_t cluster;
off_t sector;
int ret;
int i;
/* Re-initialize directory object */
cluster = dirinfo->dir.fd_startcluster;
/* Loop until we successfully allocate the sequence of directory entries
* or until to fail to extend the directory cluster chain.
*/
for (;;)
{
/* Can this cluster chain be extended */
if (cluster)
{
/* Cluster chain can be extended */
dirinfo->dir.fd_currcluster = cluster;
dirinfo->dir.fd_currsector = fat_cluster2sector(fs, cluster);
}
else
{
/* Fixed size FAT12/16 root directory is at fixed offset/size */
dirinfo->dir.fd_currsector = fs->fs_rootbase;
}
/* Skip over the first, unused entry in the root directory. */
dirinfo->dir.fd_index = 1;
/* Is this a path segment a long or a short file. Was a long file
* name parsed?
*/
#ifdef CONFIG_FAT_LFN
if (dirinfo->fd_lfname[0] != '\0')
{
/* Yes.. Allocate for the sequence of long file name directory
* entries plus a short file name directory entry.
*/
ret = fat_allocatelfnentry(fs, dirinfo);
}
/* No.. Allocate only a short file name directory entry */
else
#endif
{
ret = fat_allocatesfnentry(fs, dirinfo);
}
/* Did we successfully allocate the directory entries? If the error
* value is -ENOSPC, then we can try to extend the directory cluster
* (we can't handle other return values)
*/
if (ret == OK || ret != -ENOSPC)
{
return ret;
}
/* If we get here, then we have reached the end of the directory table
* in this sector without finding a free directory entry.
*
* It this is a fixed size directory entry, then this is an error.
* Otherwise, we can try to extend the directory cluster chain to
* make space for the new directory entry.
*/
if (!cluster)
{
/* The size is fixed */
return -ENOSPC;
}
/* Try to extend the cluster chain for this directory */
cluster = fat_extendchain(fs, dirinfo->dir.fd_currcluster);
if (cluster < 0)
{
return cluster;
}
/* Flush out any cached data in fs_buffer.. we are going to use
* it to initialize the new directory cluster.
*/
ret = fat_fscacheflush(fs);
if (ret < 0)
{
return ret;
}
/* Clear all sectors comprising the new directory cluster */
fs->fs_currentsector = fat_cluster2sector(fs, cluster);
memset(fs->fs_buffer, 0, fs->fs_hwsectorsize);
sector = fs->fs_currentsector;
for (i = fs->fs_fatsecperclus; i; i--)
{
ret = fat_hwwrite(fs, fs->fs_buffer, sector, 1);
if (ret < 0)
{
return ret;
}
sector++;
}
}
}
/****************************************************************************
* Name: fat_freedirentry
*
* Desciption: Free the directory entry.
*
* NOTE: As a side effect, this function returns with the sector containing
* the deleted short file name directory entry in the cache.
*
****************************************************************************/
int fat_freedirentry(struct fat_mountpt_s *fs, struct fat_dirseq_s *seq)
{
#ifdef CONFIG_FAT_LFN
struct fs_fatdir_s dir;
uint16_t diroffset;
uint8_t *direntry;
int ret;
/* Set it to the cluster containing the "last" LFN entry (that appears
* first on the media).
*/
dir.fd_currcluster = seq->ds_lfncluster;
dir.fd_currsector = seq->ds_lfnsector;
dir.fd_index = seq->ds_lfnoffset / DIR_SIZE;
/* Free all of the directory entries used for the sequence of long file name
* and for the single short file name entry.
*/
for (;;)
{
/* Read the directory sector into the sector cache */
ret = fat_fscacheread(fs, dir.fd_currsector);
if (ret < 0)
{
return ret;
}
/* Get a pointer to the directory entry */
diroffset = (dir.fd_index & DIRSEC_NDXMASK(fs)) * DIR_SIZE;
direntry = &fs->fs_buffer[diroffset];
/* Then mark the entry as deleted */
direntry[DIR_NAME] = DIR0_EMPTY;
fs->fs_dirty = true;
/* Did we just free the single short file name entry? */
if (dir.fd_currsector == seq->ds_sector &&
diroffset == seq->ds_offset)
{
/* Yes.. then we are finished. flush anything remaining in the
* cache and return, probably successfully.
*/
return fat_fscacheflush(fs);
}
/* There are more entries to go.. Try the next directory entry */
ret = fat_nextdirentry(fs, &dir);
if (ret < 0)
{
return ret;
}
}
#else
uint8_t *direntry;
int ret;
/* Free the single short file name entry.
*
* Make sure that the sector containing the directory entry is in the
* cache.
*/
ret = fat_fscacheread(fs, seq->ds_sector);
if (ret == OK)
{
/* Then mark the entry as deleted */
direntry = &fs->fs_buffer[seq->ds_offset];
direntry[DIR_NAME] = DIR0_EMPTY;
fs->fs_dirty = true;
}
return ret;
#endif
}
/****************************************************************************
* Name: fat_dirname2path
*
* Desciption: Convert a filename in a raw directory entry into a user
* filename. This is essentially the inverse operation of that performed
* by fat_path2dirname. See that function for more details.
*
****************************************************************************/
int fat_dirname2path(struct fat_mountpt_s *fs, struct fs_dirent_s *dir)
{
uint16_t diroffset;
uint8_t *direntry;
#ifdef CONFIG_FAT_LFN
uint8_t attribute;
#endif
/* Get a reference to the current directory entry */
diroffset = (dir->u.fat.fd_index & DIRSEC_NDXMASK(fs)) * DIR_SIZE;
direntry = &fs->fs_buffer[diroffset];
/* Does this entry refer to the last entry of a long file name? */
#ifdef CONFIG_FAT_LFN
attribute = DIR_GETATTRIBUTES(direntry);
if (((*direntry & LDIR0_LAST) != 0 && attribute == LDDIR_LFNATTR))
{
/* Yes.. Get the name from a sequence of long file name directory
* entries.
*/
return fat_getlfname(fs, dir);
}
else
#endif
{
/* No.. Get the name from a short file name directory entries */
return fat_getsfname(direntry, dir->fd_dir.d_name, NAME_MAX+1);
}
}
/****************************************************************************
* Name: fat_dirnamewrite
*
* Desciption: Write the (possibly long) directory entry name. This function
* is called only from fat_rename to write the new file name.
*
* Assumption: The directory sector containing the short file name entry
* is in the cache. *NOT* the sector containing the last long file name
* entry!
*
****************************************************************************/
int fat_dirnamewrite(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo)
{
#ifdef CONFIG_FAT_LFN
int ret;
/* Is this a long file name? */
if (dirinfo->fd_lfname[0] != '\0')
{
/* Write the sequence of long file name directory entries (this function
* also creates the short file name alias).
*/
ret = fat_putlfname(fs, dirinfo);
if (ret != OK)
{
return ret;
}
}
/* On return, fat_lfsfname() will leave the short file name entry in the
* cache. So we can just fall throught to write that directory entry, perhaps
* using the short file name alias for the long file name.
*/
#endif
return fat_putsfname(fs, dirinfo);
}
/****************************************************************************
* Name: fat_dirwrite
*
* Desciption: Write a directory entry, possibly with a long file name.
* Called from:
*
* fat_mkdir() to write the new FAT directory entry.
* fat_dircreate() to create any new directory entry.
*
* Assumption: The directory sector is in the cache. The caller will write
* sector information.
*
****************************************************************************/
int fat_dirwrite(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo,
uint8_t attributes, uint32_t fattime)
{
#ifdef CONFIG_FAT_LFN
int ret;
/* Does this directory entry have a long file name? */
if (dirinfo->fd_lfname[0] != '\0')
{
/* Write the sequence of long file name directory entries (this function
* also creates the short file name alias).
*/
ret = fat_putlfname(fs, dirinfo);
if (ret != OK)
{
return ret;
}
}
/* On return, fat_lfsfname() will leave the short file name entry in the
* cache. So we can just fall throught to write that directory entry, perhaps
* using the short file name alias for the long file name.
*/
#endif
/* Put the short file name entry data */
return fat_putsfdirentry(fs, dirinfo, attributes, fattime);
}
/****************************************************************************
* Name: fat_dircreate
*
* Desciption: Create a directory entry for a new file
*
****************************************************************************/
int fat_dircreate(struct fat_mountpt_s *fs, struct fat_dirinfo_s *dirinfo)
{
uint32_t fattime;
int ret;
/* Allocate a directory entry. If long file name support is enabled, then
* this might, in fact, allocate a sequence of directory entries.
*/
ret = fat_allocatedirentry(fs, dirinfo);
if (ret != OK)
{
/* Failed to allocate the required directory entry or entries. */
return ret;
}
/* Write the directory entry (or entries) with the current time and the
* ARCHIVE attribute.
*/
fattime = fat_systime2fattime();
return fat_dirwrite(fs, dirinfo, FATATTR_ARCHIVE, fattime);
}
/****************************************************************************
* Name: fat_remove
*
* Desciption: Remove a directory or file from the file system. This
* implements both rmdir() and unlink().
*
****************************************************************************/
int fat_remove(struct fat_mountpt_s *fs, const char *relpath, bool directory)
{
struct fat_dirinfo_s dirinfo;
uint32_t dircluster;
uint8_t *direntry;
int ret;
/* Find the directory entry referring to the entry to be deleted */
ret = fat_finddirentry(fs, &dirinfo, relpath);
if (ret != OK)
{
/* No such path */
return -ENOENT;
}
/* Check if this is a FAT12/16 root directory */
if (dirinfo.fd_root)
{
/* The root directory cannot be removed */
return -EPERM;
}
/* The object has to have write access to be deleted */
direntry = &fs->fs_buffer[dirinfo.fd_seq.ds_offset];
if ((DIR_GETATTRIBUTES(direntry) & FATATTR_READONLY) != 0)
{
/* It is a read-only entry */
return -EACCES;
}
/* Get the directory sector and cluster containing the entry to be deleted. */
dircluster =
((uint32_t)DIR_GETFSTCLUSTHI(direntry) << 16) |
DIR_GETFSTCLUSTLO(direntry);
/* Is this entry a directory? */
if (DIR_GETATTRIBUTES(direntry) & FATATTR_DIRECTORY)
{
/* It is a sub-directory. Check if we are be asked to remove
* a directory or a file.
*/
if (!directory)
{
/* We are asked to delete a file */
return -EISDIR;
}
/* We are asked to delete a directory. Check if this sub-directory is
* empty (i.e., that there are no valid entries other than the initial
* '.' and '..' entries).
*/
dirinfo.dir.fd_currcluster = dircluster;
dirinfo.dir.fd_currsector = fat_cluster2sector(fs, dircluster);
dirinfo.dir.fd_index = 2;
/* Loop until either (1) an entry is found in the directory (error),
* (2) the directory is found to be empty, or (3) some error occurs.
*/
for (;;)
{
unsigned int subdirindex;
uint8_t *subdirentry;
/* Make sure that the sector containing the of the subdirectory
* sector is in the cache
*/
ret = fat_fscacheread(fs, dirinfo.dir.fd_currsector);
if (ret < 0)
{
return ret;
}
/* Get a reference to the next entry in the directory */
subdirindex = (dirinfo.dir.fd_index & DIRSEC_NDXMASK(fs)) * DIR_SIZE;
subdirentry = &fs->fs_buffer[subdirindex];
/* Is this the last entry in the direcory? */
if (subdirentry[DIR_NAME] == DIR0_ALLEMPTY)
{
/* Yes then the directory is empty. Break out of the
* loop and delete the directory.
*/
break;
}
/* Check if the next entry refers to a file or directory */
if (subdirentry[DIR_NAME] != DIR0_EMPTY &&
!(DIR_GETATTRIBUTES(subdirentry) & FATATTR_VOLUMEID))
{
/* The directory is not empty */
return -ENOTEMPTY;
}
/* Get the next directory entry */
ret = fat_nextdirentry(fs, &dirinfo.dir);
if (ret < 0)
{
return ret;
}
}
}
else
{
/* It is a file. Check if we are be asked to remove a directory
* or a file.
*/
if (directory)
{
/* We are asked to remove a directory */
return -ENOTDIR;
}
}
/* Mark the directory entry 'deleted'. If long file name support is
* enabled, then multiple directory entries may be freed.
*/
ret = fat_freedirentry(fs, &dirinfo.fd_seq);
if (ret < 0)
{
return ret;
}
/* And remove the cluster chain making up the subdirectory */
ret = fat_removechain(fs, dircluster);
if (ret < 0)
{
return ret;
}
/* Update the FSINFO sector (FAT32) */
ret = fat_updatefsinfo(fs);
if (ret < 0)
{
return ret;
}
return OK;
}
|