cat-dev 0.0.13

A library for interacting with the CAT-DEV hardware units distributed by Nintendo (i.e. a type of Wii-U DevKits).
Documentation
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
//! A representation of the filesystem folder we end up serving a cat-dev
//! client.

use crate::{
	TitleID,
	errors::{CatBridgeError, FSError},
	fsemul::{
		bsf::BootSystemFile,
		dlf::DiskLayoutFile,
		errors::{FSEmulAPIError, FSEmulFSError},
		pcfs::errors::PcfsApiError,
	},
};
use bytes::{Bytes, BytesMut};
use scc::{
	HashMap as ConcurrentMap, HashSet as ConcurrentSet, hash_map::OccupiedEntry as CMOccupiedEntry,
};
use std::{
	collections::HashMap,
	ffi::OsString,
	fs::{
		DirEntry, copy as copy_file_sync, create_dir_all as create_dir_all_sync,
		read_dir as read_dir_sync, read_link as read_link_sync,
		remove_dir_all as remove_dir_all_sync, remove_file as remove_file_sync,
		rename as rename_sync,
	},
	hash::RandomState,
	io::{Error as IOError, SeekFrom},
	path::{Path, PathBuf},
	sync::{
		Arc,
		atomic::{AtomicBool, AtomicI32, Ordering as AtomicOrdering},
	},
};
use tokio::{
	fs::{File, OpenOptions, read as fs_read, write as fs_write},
	io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt},
	sync::Mutex,
};
use tracing::{info, warn};
use valuable::{Fields, NamedField, NamedValues, StructDef, Structable, Valuable, Value, Visit};
use walkdir::WalkDir;
use whoami::username;

/// A way to create truly unique file fd's. Just a counter going up.
static UNIQUE_FILE_FD: AtomicI32 = AtomicI32::new(1);
/// Current "FD" for directories. Just a counter going up.
static FOLDER_FD: AtomicI32 = AtomicI32::new(1);

/// A wrapper around interacting with the 'host' or PC filesystem for the
/// various times a cat-dev will reach out to the host.
///
/// This is little more than a wrapper around a [`PathBuf`], and targeted
/// methods to make getting files/generating default files/etc. easy. Most of
/// the actual logic for turning a request from `SDIO`, `ATAPI`, etc. all come
/// from those client/server implementations rather than the logic living here.
#[allow(
	// Clippy the type is _not_ that complex.
	clippy::type_complexity,
)]
#[derive(Clone, Debug)]
pub struct HostFilesystem {
	/// The path to the base data directory to serve a filesystem out of.
	cafe_sdk_path: PathBuf,
	/// The actively mounted "disc".
	///
	/// This is a tuple of (isSLC, isSystem, [`TitleID`]).
	///
	/// When a disc is mounted we will copy the title from SLC/MLC
	/// directory, into `disc/` recursively.
	disc_mounted: Arc<Mutex<Option<(bool, bool, TitleID)>>>,
	/// List of open file handles.
	///
	/// This contains a value of (file, file size, path, stream owner).
	open_file_handles: Arc<ConcurrentMap<i32, (File, u64, PathBuf, Option<u64>)>>,
	/// List of open folder "handles".
	///
	/// This contains a value of (directory items, index, is end, path, stream owner)
	open_folder_handles:
		Arc<ConcurrentMap<i32, (Vec<DirEntry>, usize, bool, PathBuf, Option<u64>)>>,
	/// A set of folders that we've "marked" as read-only.
	///
	/// We don't actually synchronize this to the filesystem because the original
	/// cafe-sdk was written for Windows 7 which silently ignores "Read-Only"
	/// attributes on directories. Still allowing you to create files within
	/// directories, modify them, etc.
	///
	/// This is not the case on older windows distributions, unix based distros,
	/// or similar.
	folders_marked_read_only: Arc<ConcurrentSet<PathBuf>>,
	/// If we are forcing unique file fd's. This should only be changed
	/// if we have not opened a file yet.
	is_using_unique_fds: bool,
	/// If we've opened a file, used to safely ensure we don't switch from
	/// unique fdf's to not.
	has_opened_file: Arc<AtomicBool>,
}

impl HostFilesystem {
	/// Create a filesystem from a root cafe dir.
	///
	/// If no cafe dir is provided, we will attempt to locate the default
	/// installation path for cafe sdk which is:
	///
	/// - `C:\cafe_sdk` on windows.
	/// - `/opt/cafe_sdk` on any unix/bsd like OS.
	///
	/// NOTE: This will validate that all title id paths are lowercase, as
	/// files are always expected to be lowercase when dealing with CAFE. Other
	/// files are usually kept in the correct naming format. HOWEVER, users may
	/// notice spurious errors with case-insensitivity on linux specifically. If
	/// transferring an SDK from a Windows/Mac Case Insensitive to a Mac/Linux
	/// case sensitive file system. It is recommended users
	/// create their own folder using our recovery tools, rather than
	/// rsync'ing a path over from case-insensitive, to case-sensitive.
	///
	/// ## Errors
	///
	/// If the Cafe SDK folder is corrupt, or can't be found. A Cafe SDK
	/// folder is considered corrupt if it is missing core files that we
	/// _need_ to be able to serve a Cafe-OS distribution. These file
	/// requirements may change from version to version of this crate, but should
	/// always be compatible with a clean cafe sdk folder.
	pub async fn from_cafe_dir(cafe_dir: Option<PathBuf>) -> Result<Self, FSError> {
		let Some(cafe_sdk_path) = cafe_dir.or_else(Self::default_cafe_folder) else {
			return Err(FSEmulFSError::CantFindCafeSdkPath.into());
		};

		Self::patch_case_sensitivity(&cafe_sdk_path).await?;

		for path in [
			&[
				"data", "mlc", "sys", "title", "00050030", "1001000a", "code", "app.xml",
			] as &[&str],
			&[
				"data", "mlc", "sys", "title", "00050030", "1001010a", "code", "app.xml",
			],
			&[
				"data", "mlc", "sys", "title", "00050030", "1001020a", "code", "app.xml",
			],
			&[
				"data", "mlc", "sys", "title", "00050010", "1f700500", "code",
			],
			&[
				"data", "mlc", "sys", "title", "00050010", "1f700500", "content",
			],
			&[
				"data", "mlc", "sys", "title", "00050010", "1f700500", "meta",
			],
			// Can't generate a `fw.img` for now.... :(
			&[
				"data", "slc", "sys", "title", "00050010", "1000400a", "code", "fw.img",
			],
		] {
			if !Self::join_many(&cafe_sdk_path, path).exists() {
				return Err(FSEmulFSError::CafeSdkPathCorrupt.into());
			}
		}

		Self::prepare_for_serving(&cafe_sdk_path).await?;
		let ro_folders = Self::get_default_read_only_folders(&cafe_sdk_path);

		Ok(Self {
			cafe_sdk_path,
			disc_mounted: Arc::new(Mutex::new(None)),
			folders_marked_read_only: Arc::new(ro_folders),
			open_file_handles: Arc::new(ConcurrentMap::new()),
			open_folder_handles: Arc::new(ConcurrentMap::new()),
			is_using_unique_fds: false,
			has_opened_file: Arc::new(AtomicBool::new(false)),
		})
	}

	/// The root path to the Cafe SDK.
	///
	/// *note: although we do expose this for logging, and other info... we do
	/// not recommend manually interacting with the SDK path. There are much
	/// better alternatives.*
	#[must_use]
	pub const fn cafe_sdk_path(&self) -> &PathBuf {
		&self.cafe_sdk_path
	}

	/// The root path to the Cafe SDK.
	///
	/// *note: although we do expose this for logging, and other info... we do
	/// not recommend manually interacting with the SDK path. There are much
	/// better alternatives.*
	#[must_use]
	pub fn disc_emu_path(&self) -> PathBuf {
		Self::join_many(&self.cafe_sdk_path, ["data", "disc"])
	}

	/// Force unique file descriptors for open files.
	///
	/// Certain OS's _can_ return duplicate fd's especially when opening,
	/// and closing files. This can make deciphering logs harder because the
	/// same FD may appear multiple times, when you're trying to just find
	/// the logs related to one file descriptor.
	///
	/// When unique fd's is turned on, similar to folders we just use a global
	/// wrapping counter so that way every file descriptor is guaranteed to be
	/// unique.
	///
	/// ## Errors
	///
	/// This will error if any file has ever been opened. This is because once
	/// a client has already connected, and done some stuff with file stuff it
	/// expects one set of behaviors, we cannot change another one.
	pub fn force_unique_fds(&mut self) -> Result<(), FSEmulAPIError> {
		if self.has_opened_file.load(AtomicOrdering::Relaxed) {
			Err(FSEmulAPIError::CannotSwapFdStrategy)
		} else {
			self.is_using_unique_fds = true;
			Ok(())
		}
	}

	/// Open a file, and return it's file descriptor number.
	///
	/// ## Errors
	///
	/// If we cannot open our file with the open options provided.
	pub async fn open_file(
		&self,
		open_options: OpenOptions,
		path: &PathBuf,
		stream_owner: Option<u64>,
	) -> Result<i32, FSError> {
		self.has_opened_file.store(true, AtomicOrdering::Relaxed);
		let fd = open_options.open(path).await?;
		let raw_fd;
		#[cfg(unix)]
		{
			use std::os::fd::AsRawFd;
			raw_fd = fd.as_raw_fd();
		}
		#[cfg(target_os = "windows")]
		{
			use std::os::windows::io::AsRawHandle;
			raw_fd = fd.as_raw_handle() as i32;
		}

		let md = fd.metadata().await?;
		let final_fd = if self.is_using_unique_fds {
			UNIQUE_FILE_FD.fetch_add(1, AtomicOrdering::SeqCst)
		} else {
			raw_fd
		};

		self.open_file_handles
			.insert_async(final_fd, (fd, md.len(), path.clone(), stream_owner))
			.await
			.map_err(|_| IOError::other("somehow got duplicate fd?"))?;
		Ok(final_fd)
	}

	/// Get a file from a file descriptor number.
	///
	/// This file must already be opened (in order to get the file descriptor).
	pub async fn get_file(
		&self,
		fd: i32,
		for_stream: Option<u64>,
	) -> Option<CMOccupiedEntry<'_, i32, (File, u64, PathBuf, Option<u64>), RandomState>> {
		self.open_file_handles
			.get_async(&fd)
			.await
			.and_then(|entry| {
				if Self::allow_file_access(&entry, for_stream) {
					Some(entry)
				} else {
					None
				}
			})
	}

	/// Get the file length from a file descriptor number.
	///
	/// This file must already be opened (in order to get the file descriptor).
	pub async fn file_length(&self, fd: i32, for_stream: Option<u64>) -> Option<u64> {
		self.open_file_handles
			.get_async(&fd)
			.await
			.and_then(|entry| {
				if Self::allow_file_access(&entry, for_stream) {
					Some(entry.1)
				} else {
					None
				}
			})
	}

	/// Read from a file descriptor that is actively open.
	///
	/// This will read from a currently open file descriptor, in it's current
	/// location. You might want to set your file location for this FD before
	/// if you aren't already in the same location.
	///
	/// ## Errors
	///
	/// If the file descriptor is open, but we could not read from the open file
	/// descriptor.
	pub async fn read_file(
		&self,
		fd: i32,
		mut total_data_to_read: usize,
		for_stream: Option<u64>,
	) -> Result<Option<Bytes>, FSError> {
		let Some(mut real_entry) = self.open_file_handles.get_async(&fd).await else {
			return Ok(None);
		};
		if !Self::allow_file_access(&real_entry, for_stream) {
			return Ok(None);
		}
		let file_reader = &mut real_entry.0;

		let mut file_buff = BytesMut::zeroed(total_data_to_read);
		let mut total_bytes_read = 0_usize;
		while total_data_to_read > 0 {
			let bytes_read = file_reader.read(&mut file_buff[total_bytes_read..]).await?;
			if bytes_read == 0 {
				break;
			}
			total_data_to_read -= bytes_read;
			total_bytes_read += bytes_read;
		}
		if file_buff.len() > total_bytes_read {
			file_buff.truncate(total_bytes_read);
		}

		Ok(Some(file_buff.freeze()))
	}

	/// Write to a file descriptor that is actively open.
	///
	/// This will write from a currently open file descriptor, in it's current
	/// location. You might want to set your file location for this FD before
	/// if you aren't already in the same location.
	///
	/// ## Errors
	///
	/// If the file descriptor is open, but we could not write to the open file
	/// descriptor.
	pub async fn write_file(
		&self,
		fd: i32,
		data_to_write: Bytes,
		for_stream: Option<u64>,
	) -> Result<(), FSError> {
		let Some(mut real_entry) = self.open_file_handles.get_async(&fd).await else {
			return Err(FSError::IO(IOError::other("file not open")));
		};
		if !Self::allow_file_access(&real_entry, for_stream) {
			return Err(FSError::IO(IOError::other("file not open")));
		}
		let file_writer = &mut real_entry.0;
		file_writer.write_all(&data_to_write).await?;

		Ok(())
	}

	/// Seek to the beginning or end of a file.
	///
	/// If `begin` is true then we will seek to the beginning of the file
	/// otherwise we will sync to the end of the file. Precise seeking is _not_
	/// supported at this time.
	///
	/// ## Errors
	///
	/// If we cannot seek to the beginning or end of the file.
	pub async fn seek_file(
		&self,
		fd: i32,
		begin: bool,
		for_stream: Option<u64>,
	) -> Result<(), FSError> {
		let Some(mut real_entry) = self.open_file_handles.get_async(&fd).await else {
			return Ok(());
		};
		if !Self::allow_file_access(&real_entry, for_stream) {
			return Ok(());
		}
		let file_reader = &mut real_entry.0;

		if begin {
			file_reader.seek(SeekFrom::Start(0)).await?;
		} else {
			file_reader.seek(SeekFrom::End(0)).await?;
		}

		Ok(())
	}

	/// Decrement the ref count of handles to a file.
	///
	/// If ref count reaches 0 close the underlying file handle.
	///
	/// ## Errors
	///
	/// If we cannot close our file handle when our ref count reaches 0, or if
	/// the file isn't open at all.
	pub async fn close_file(&self, fd: i32, for_stream: Option<u64>) {
		if let Some(entry) = self.open_file_handles.get_async(&fd).await
			&& !Self::allow_file_access(&entry, for_stream)
		{
			// Don't allow streams to close other streams files.
			return;
		}

		self.open_file_handles.remove_async(&fd).await;
	}

	/// "Open" a folder, or an iterator over a directory.
	///
	/// There's no real "open file handle", or reversible directory iterator,
	/// so we just create an id from scratch.
	///
	/// ## Errors
	///
	/// If the path doesn't exist, then we can't open the folder.
	pub fn open_folder(&self, path: &PathBuf, for_stream: Option<u64>) -> Result<i32, FSError> {
		let mut dhandle = read_dir_sync(path)?
			.filter_map(Result::ok)
			.collect::<Vec<_>>();
		dhandle.sort_by_key(DirEntry::path);

		let fake_fd = FOLDER_FD.fetch_add(1, AtomicOrdering::SeqCst);

		self.open_folder_handles
			.insert_sync(fake_fd, (dhandle, 0, false, path.clone(), for_stream))
			.map_err(|_| IOError::other("OS returned duplicate fd?"))?;
		Ok(fake_fd)
	}

	/// Mark a folder as being 'read-only' for this session.
	///
	/// ## Errors
	///
	/// If we could not actually insert the folder into the read only map.
	pub async fn mark_folder_read_only(&self, path: PathBuf) {
		_ = self.folders_marked_read_only.insert_async(path).await;
	}

	/// Mark a folder as being 'read-write' for this session.
	pub async fn ensure_folder_not_read_only(&self, path: &PathBuf) {
		self.folders_marked_read_only.remove_async(path).await;
	}

	/// Check if a folder is marked as being read only.
	pub async fn folder_is_read_only(&self, path: &PathBuf) -> bool {
		self.folders_marked_read_only.contains_async(path).await
	}

	/// Get the next filename/foldername available in a particular folder, and
	/// how many pieces to remove to get just the filename.
	///
	/// This will always return none even if it's already at the end, unlike a
	/// particular iterator.
	///
	/// ## Errors
	///
	/// If we get an IO error from the underlying filesystem.
	pub async fn next_in_folder(
		&self,
		fd: i32,
		for_stream: Option<u64>,
	) -> Result<Option<(PathBuf, usize)>, FSError> {
		let Some(mut entry) = self.open_folder_handles.get_async(&fd).await else {
			return Ok(None);
		};
		if !Self::allow_folder_access(&entry, for_stream) {
			return Ok(None);
		}

		let component_count = entry.3.components().count();
		let mut value: Option<PathBuf> = None;
		if !entry.2 {
			loop {
				if entry.1 < entry.0.len() {
					let ref_value = entry.0[entry.1].path();
					entry.1 += 1;

					if (!ref_value.is_file() && !ref_value.is_dir()) || ref_value.is_symlink() {
						continue;
					}

					value = Some(ref_value);
				}

				break;
			}
			if value.is_none() {
				entry.2 = true;
			}
		}

		Ok(value.map(|val| (val, component_count)))
	}

	/// Reverse a particular iterator over a folder by one.
	///
	/// Note: This will recreate the directory iterator, and will temporarily
	/// hold _two_ references to [`ReadDir`] at a time because the underlying
	/// iterator from read directory is not a reversible iterator.
	///
	/// ## Errors
	///
	/// If opening another read dir call does not work.
	pub async fn reverse_folder(&self, fd: i32, for_stream: Option<u64>) -> Result<(), FSError> {
		let Some(mut real_entry) = self.open_folder_handles.get_async(&fd).await else {
			return Ok(());
		};
		if !Self::allow_folder_access(&real_entry, for_stream) {
			return Ok(());
		}
		if real_entry.1 == 0 {
			return Ok(());
		}

		real_entry.1 -= 1;
		real_entry.2 = false;
		Ok(())
	}

	/// Decrement the ref count of handles to a folder.
	///
	/// If ref count reaches 0 close the underlying folder handle.
	///
	/// ## Errors
	///
	/// If we cannot close our folder handle when our ref count reaches 0, or if
	/// the folder isn't open at all.
	pub async fn close_folder(&self, fd: i32, for_stream: Option<u64>) {
		if let Some(real_entry) = self.open_folder_handles.get_async(&fd).await
			&& !Self::allow_folder_access(&real_entry, for_stream)
		{
			return;
		}

		self.open_folder_handles.remove_async(&fd).await;
	}

	/// Get the path to the current boot1 `.bsf` file.
	///
	/// This function will create the boot1 system file, if it does not yet
	/// exist. As a result it may error, if we can't create, and place the
	/// boot system file.
	///
	/// ## Errors
	///
	/// - If the temp directory does not exist, and we can't create it.
	/// - If the boot system file does not exist, and we can't write it to disk.
	pub async fn boot1_sytstem_path(&self) -> Result<PathBuf, FSError> {
		let mut path = self.temp_path()?;
		path.push("caferun");
		if !path.exists() {
			create_dir_all_sync(&path)?;
		}
		path.push("ppc.bsf");

		if !path.exists() {
			fs_write(&path, Bytes::from(BootSystemFile::default())).await?;
		}

		Ok(path)
	}

	/// Get the path to the current `diskid.bin`.
	///
	/// If the current Disk ID does not exist, we will write a blank diskid to
	/// this path.
	///
	/// ## Errors
	///
	/// - If the temporary directory does not exist, and we can't create it.
	/// - If the disk ID path does not exist, and we can't write it to disk.
	pub async fn disk_id_path(&self) -> Result<PathBuf, FSError> {
		let mut path = self.temp_path()?;
		path.push("caferun");
		if !path.exists() {
			create_dir_all_sync(&path)?;
		}
		path.push("diskid.bin");

		if !path.exists() {
			fs_write(&path, BytesMut::zeroed(32).freeze()).await?;
		}

		Ok(path)
	}

	#[doc(
		// This is not yet finished and the signature may change....
		hidden,
	)]
	/// Mount a particular title as if it were a disc.
	///
	/// ## Errors
	///
	/// - If we cannot remove any existing disc that may be present.
	/// - If we cannot copy the title to the disc id path.
	pub async fn mount_disk_title(
		&mut self,
		is_slc: bool,
		is_sys: bool,
		title_id: TitleID,
	) -> Result<(), FSError> {
		let source_path = Self::join_many(
			&self.cafe_sdk_path,
			[
				"data".to_owned(),
				if is_slc { "slc" } else { "mlc" }.to_owned(),
				if is_sys { "sys" } else { "usr" }.to_owned(),
				"title".to_owned(),
				format!("{:08x}", title_id.0),
				format!("{:08x}", title_id.1),
			],
		);
		let dest_path = Self::join_many(&self.cafe_sdk_path, ["data", "disc"]);
		if dest_path.exists() {
			remove_dir_all_sync(&dest_path).map_err(FSError::IO)?;
		}

		Self::copy_dir(&source_path, &dest_path)?;
		// Mount was successful!
		{
			let mut guard = self.disc_mounted.lock().await;
			guard.replace((is_slc, is_sys, title_id));
		}
		todo!("figure out how to mount diskid.bin")
	}

	/// Get the path to the current firmware file to boot on the MION.
	///
	/// This is guaranteed to always exist, as it's part of our check for a
	/// corrupt SDK.
	#[must_use]
	pub fn firmware_file_path(&self) -> PathBuf {
		Self::join_many(
			&self.slc_path_for((0x0005_0010, 0x1000_400A)),
			["code", "fw.img"],
		)
	}

	/// Get the path to the disk layout file for the PPC booting process.
	///
	/// This function will create a disk layout file, as well as a Boot System
	/// File, and a disk id file if they do not yet exist.
	///
	/// ## Errors
	///
	/// - If the temp directory does not exist, and we can't create it.
	/// - If the boot system file does not exist, and we can't write it to disk.
	/// - If the diskid file does not exist, and we can't write it to disk.
	/// - If the firmware image file does not exist.
	/// - If the dlf file does not exist, and we can't create it.
	pub async fn ppc_boot_dlf_path(&self) -> Result<PathBuf, CatBridgeError> {
		let mut path = self.temp_path()?;
		path.push("caferun");
		if !path.exists() {
			create_dir_all_sync(&path).map_err(FSError::from)?;
		}
		path.push("ppc_boot.dlf");

		if !path.exists() {
			// This probably isn't the right set of defaults for everyone, but i'm
			// not yet smart enough to figure all this out.
			let mut root_dlf = DiskLayoutFile::new(0x00B8_8200_u128);
			root_dlf.upsert_addressed_path(0_u128, &self.disk_id_path().await?)?;
			root_dlf.upsert_addressed_path(0x80000_u128, &self.boot1_sytstem_path().await?)?;
			root_dlf.upsert_addressed_path(0x90000_u128, &self.firmware_file_path())?;
			fs_write(&path, Bytes::from(root_dlf))
				.await
				.map_err(FSError::from)?;
		}

		Ok(path)
	}

	/// Check if a path is allowed to be writable.
	#[must_use]
	pub fn path_allows_writes(&self, path: &Path) -> bool {
		// TODO(mythra): check FSEmulAttributeRules
		let lossy_path = path.to_string_lossy();
		let trimmed_lossy_path = lossy_path
			.trim_start_matches("/vol/pc")
			.trim_start_matches('/');
		if trimmed_lossy_path.starts_with("%DISC_EMU_DIR") {
			return trimmed_lossy_path.starts_with("%DISC_EMU_DIR/save");
		}
		if path.starts_with(Self::join_many(&self.cafe_sdk_path, ["data", "disc"])) {
			return path.starts_with(Self::join_many(
				&self.cafe_sdk_path,
				["data", "disc", "save"],
			));
		}

		true
	}

	/// Given a UTF-8 string path, get a pathbuf reference.
	///
	/// This understands the current following implementations:
	///
	/// - `/%MLC_EMU_DIR`
	/// - `/%SLC_EMU_DIR`
	/// - `/%DISC_EMU_DIR`
	/// - `/%SAVE_EMU_DIR`
	/// - `/%NETWORK`
	///
	/// Most of these are just quick ways of referncing the current set of
	/// directories, within cafe sdk. `%NETWORK` is the special one which
	/// references a currently mounted network share.
	///
	/// ## Errors
	///
	/// If the path requested is not in a mounted path.
	pub fn resolve_path(
		&self,
		potentially_prefixed_path: &str,
	) -> Result<ResolvedLocation, CatBridgeError> {
		// Requests coming may optionally have `/vol/pc` prefixed if they're built
		// wrong.
		//
		// Or if a user is trying to get cat-dev style paths working with this api
		// directly. CLean it up.
		let path = potentially_prefixed_path.trim_start_matches("/vol/pc");
		if path.starts_with("/%NETWORK") {
			todo!("NETWORK shares not yet implemented :( sorry!")
		}

		let non_canonical_path = if path.starts_with("/%MLC_EMU_DIR") {
			self.replace_emu_dir(path, "mlc")
		} else if path.starts_with("/%SLC_EMU_DIR") {
			self.replace_emu_dir(path, "slc")
		} else if path.starts_with("/%DISC_EMU_DIR") {
			self.replace_emu_dir(path, "disc")
		} else if path.starts_with("/%SAVE_EMU_DIR") {
			self.replace_emu_dir(path, "save")
		} else {
			PathBuf::from(path)
		};

		// We can't actually just call `canonicalize`, as that will fail if the
		// file doesn't exist, and we could be requesting to resolve a path we want
		// to turn around and create.
		//
		// So instead we try to canonicalize to the closest possible directory, and
		// check if it is underneath our directory.
		let mut closest_canonical_directory = non_canonical_path.clone();
		let mut changed_at_all = false;
		while !closest_canonical_directory.as_os_str().is_empty() {
			if let Ok(canonicalized) = closest_canonical_directory.canonicalize() {
				closest_canonical_directory = canonicalized;
				break;
			}

			changed_at_all = true;
			closest_canonical_directory.pop();
		}
		// We failed to find any directory, which means we're nowhere close to
		// where we want to be.
		if closest_canonical_directory.as_os_str().is_empty() {
			return Err(PcfsApiError::PathNotMapped(path.to_owned()).into());
		}
		// Check for mapped directories...
		let canonicalized_cafe = self
			.cafe_sdk_path()
			.canonicalize()
			.unwrap_or_else(|_| self.cafe_sdk_path().clone());
		if !closest_canonical_directory.starts_with(canonicalized_cafe) {
			return Err(PcfsApiError::PathNotMapped(path.to_owned()).into());
		}

		Ok(ResolvedLocation::Filesystem(FilesystemLocation::new(
			non_canonical_path,
			closest_canonical_directory,
			!changed_at_all,
		)))
	}

	/// Create a directory within a particular path.
	///
	/// ## Errors
	///
	/// If we cannot end up creating this directory due to a filesystem error.
	pub fn create_directory(&self, at: &Path) -> Result<(), FSError> {
		create_dir_all_sync(at).map_err(FSError::IO)
	}

	/// Copy a file, symlink, or directory.
	///
	/// ## Errors
	///
	/// If we run into any filesystem error renaming a source, or directory.
	pub fn copy(&self, from: &Path, to: &Path) -> Result<(), FSError> {
		if from.is_dir() {
			Self::copy_dir(from, to)
		} else {
			copy_file_sync(from, to).map_err(FSError::IO).map(|_| ())
		}
	}

	/// Rename a file, symlink, or directory.
	///
	/// This is implemented so we can rename directories, and files without
	/// having to worry about the logic. Especially given the fact the built in
	/// rename doesn't support directories.
	///
	/// ## Errors
	///
	/// - If we run into any filesystem error renaming a source, or directory.
	pub fn rename(&self, from: &Path, to: &Path) -> Result<(), FSError> {
		if from.is_dir() {
			Self::rename_dir(from, to)
		} else {
			rename_sync(from, to).map_err(FSError::IO)
		}
	}

	/// Get a file from the SLC.
	///
	/// The SLC always serves "sys" files, and are relative to a title id, almost
	/// always a system title id such as (`00050010`).
	///
	/// *note: the file is not guaranteed to exist! It's just a path!*
	#[must_use]
	pub fn slc_path_for(&self, title_id: TitleID) -> PathBuf {
		Self::join_many(
			&self.cafe_sdk_path,
			[
				"data".to_owned(),
				"slc".to_owned(),
				"sys".to_owned(),
				"title".to_owned(),
				format!("{:08x}", title_id.0),
				format!("{:08x}", title_id.1),
			],
		)
	}

	/// Get the current OS's default directory path.
	///
	/// For Windows this is: `C:\cafe_sdk`.
	/// For Unix/BSD likes this is: `/opt/cafe_sdk`
	#[allow(
    // Not actually unreachable unless on unsupported OS.
    unreachable_code,
  )]
	#[must_use]
	pub fn default_cafe_folder() -> Option<PathBuf> {
		#[cfg(target_os = "windows")]
		{
			return Some(PathBuf::from(r"C:\cafe_sdk"));
		}

		#[cfg(any(
			target_os = "linux",
			target_os = "freebsd",
			target_os = "openbsd",
			target_os = "netbsd",
			target_os = "macos"
		))]
		{
			return Some(PathBuf::from("/opt/cafe_sdk"));
		}

		None
	}

	/// Get the current path to the temporary directory for this Cafe SDK
	/// install.
	///
	/// ## Errors
	///
	/// - If the temporary path does not exist and could not be created.
	fn temp_path(&self) -> Result<PathBuf, FSError> {
		let temp_path = Self::join_many(
			&self.cafe_sdk_path,
			["temp".to_owned(), username().to_lowercase()],
		);
		if !temp_path.exists() {
			create_dir_all_sync(&temp_path)?;
		}
		Ok(temp_path)
	}

	/// A small utility function to join many paths into a single path effeciently.
	#[must_use]
	fn join_many<PathTy, IterTy>(base: &Path, parts: IterTy) -> PathBuf
	where
		PathTy: AsRef<Path>,
		IterTy: IntoIterator<Item = PathTy>,
	{
		let mut as_owned = PathBuf::from(base);
		for part in parts {
			as_owned = as_owned.join(part.as_ref());
		}
		as_owned
	}

	/// Replace a particular emu directory string in a path.
	fn replace_emu_dir(&self, path: &str, dir: &str) -> PathBuf {
		let path_minus = path
			.trim_start_matches(&format!("/%{}_EMU_DIR", dir.to_ascii_uppercase()))
			.trim_start_matches('/')
			.trim_start_matches('\\')
			.replace('\\', "/");

		Self::join_many(
			&Self::join_many(self.cafe_sdk_path(), ["data", dir]),
			path_minus.split('/'),
		)
	}

	async fn patch_case_sensitivity(cafe_sdk_path: &Path) -> Result<(), FSError> {
		// First we need to check if we're even on a temporary filesystem/path.
		if !cafe_sdk_path.exists() {
			return Ok(());
		}
		let capital_path = Self::join_many(cafe_sdk_path, ["InsensitiveCheck.txt"]);
		let _ = File::create(&capital_path).await?;
		let is_insensitive = File::open(Self::join_many(cafe_sdk_path, ["insensitivecheck.txt"]))
			.await
			.is_ok();
		remove_file_sync(capital_path)?;
		if is_insensitive {
			return Ok(());
		}

		info!(
			"Your Host OS is not case-insensitive for file-paths... ensuring CafeSDK is all lowercase, this may take awhile..."
		);
		let cafe_sdk_components = cafe_sdk_path.components().count();
		let mut had_rename = true;
		while had_rename {
			had_rename = false;
			for directory in [
				Self::join_many(cafe_sdk_path, ["data", "slc", "sys", "title"]),
				Self::join_many(cafe_sdk_path, ["data", "slc", "usr", "title"]),
				Self::join_many(cafe_sdk_path, ["data", "mlc", "sys", "title"]),
				Self::join_many(cafe_sdk_path, ["data", "mlc", "usr", "title"]),
			] {
				if !directory.exists() {
					// Don't need to patch directories that don't exist.
					continue;
				}

				let mut iter = WalkDir::new(&directory)
					.contents_first(false)
					.follow_links(false)
					.follow_root_links(false)
					.into_iter();
				while let Some(Ok(entry)) = iter.next() {
					let p = entry.path();
					if !p.exists() {
						continue;
					}

					let path_minus_cafe = p
						.components()
						.skip(cafe_sdk_components)
						.collect::<PathBuf>();
					let Some(path_as_utf8) = path_minus_cafe.as_os_str().to_str() else {
						warn!(problematic_path = %p.display(), "Path in Cafe SDK directory is not UTF-8! This may cause errors fetching!");
						continue;
					};
					let new_path = path_as_utf8.to_ascii_lowercase();
					if path_as_utf8 != new_path {
						let mut final_new_path = cafe_sdk_path.as_os_str().to_owned();
						final_new_path.push("/");
						final_new_path.push(&new_path);
						let new = PathBuf::from(final_new_path);

						if p.is_dir() {
							Self::rename_dir(p, &new)?;
							had_rename = true;
						} else {
							rename_sync(p, new)?;
							had_rename = true;
						}
					}
				}
			}
		}
		info!("ensure CafeSDK path is now case-insensitive by renaming to all lowercase...");

		Ok(())
	}

	fn allow_file_access(
		entry: &CMOccupiedEntry<i32, (File, u64, PathBuf, Option<u64>), RandomState>,
		requester: Option<u64>,
	) -> bool {
		let Some(requesting_stream_id) = requester else {
			return true;
		};
		let Some(owned_stream_id) = entry.3 else {
			return true;
		};

		requesting_stream_id == owned_stream_id
	}

	#[allow(
		// TODO(mythra): fix
		clippy::type_complexity
	)]
	fn allow_folder_access(
		entry: &CMOccupiedEntry<
			i32,
			(Vec<DirEntry>, usize, bool, PathBuf, Option<u64>),
			RandomState,
		>,
		requester: Option<u64>,
	) -> bool {
		let Some(requesting_stream_id) = requester else {
			return true;
		};
		let Some(owned_stream_id) = entry.4 else {
			return true;
		};

		requesting_stream_id == owned_stream_id
	}

	/// Enusre an SDK path is ready for serving this means:
	///
	/// - Create some configuration files that SDKs don't come with, but will
	///   help the OS boot up.
	/// - Mount the `DISC` directory if one is not present.
	async fn prepare_for_serving(cafe_sdk_path: &Path) -> Result<(), FSError> {
		if !Self::join_many(cafe_sdk_path, ["data", "slc", "sys", "config", "eco.xml"]).exists() {
			Self::generate_eco_xml(cafe_sdk_path).await?;
		}
		if !Self::join_many(
			cafe_sdk_path,
			["data", "slc", "sys", "proc", "prefs", "wii_acct.xml"],
		)
		.exists()
		{
			Self::generate_wii_acct_xml(cafe_sdk_path).await?;
		}

		// Unmount any leftover discs....
		if Self::join_many(cafe_sdk_path, ["data", "disc"]).exists() {
			remove_dir_all_sync(Self::join_many(cafe_sdk_path, ["data", "disc"]))
				.map_err(FSError::IO)?;
		}
		// Manually mount in SysConfigTool.....
		//
		// This doesn't actually create a discid.bin, but the files do exist.
		let disc_dir = Self::join_many(cafe_sdk_path, ["data", "disc"]);
		let sctt_dir = Self::join_many(
			cafe_sdk_path,
			["data", "mlc", "sys", "title", "00050010", "1f700500"],
		);
		for subpath in ["code", "content", "meta"] {
			Self::copy_dir(
				&Self::join_many(&sctt_dir, [subpath]),
				&Self::join_many(&disc_dir, [subpath]),
			)?;
		}
		// Manually capitilize the title id in app.xml, the normal PCFS
		// tooling does this, even though it is case-insensitive, but for matching.
		let app_xml_path = Self::join_many(cafe_sdk_path, ["data", "disc", "code", "app.xml"]);
		// app.xml must be utf-8 to be read by the OS completely, so if we end up
		// writing a corrupt app.xml, would be the exact same as the OS
		// interpreting that.
		let base_app_xml = String::from_utf8_lossy(&fs_read(&app_xml_path).await?).to_string();
		fs_write(&app_xml_path, Self::capitilize_title_id(base_app_xml)).await?;

		Ok(())
	}

	fn copy_dir(source_path: &Path, dest_path: &Path) -> Result<(), FSError> {
		if !dest_path.exists() {
			create_dir_all_sync(dest_path)?;
		}
		let new_path_as_str_bytes = dest_path.as_os_str().as_encoded_bytes();
		let old_path_bytes = source_path.as_os_str().as_encoded_bytes();

		for result in WalkDir::new(source_path)
			.follow_links(false)
			.follow_root_links(false)
		{
			let rpb = result?.into_path();
			let os_str_for_entry = rpb.as_os_str().as_encoded_bytes();
			let mut new_bytes = Vec::with_capacity(os_str_for_entry.len() + 3);
			new_bytes.extend_from_slice(new_path_as_str_bytes);
			new_bytes.extend_from_slice(&os_str_for_entry[old_path_bytes.len()..]);
			let as_new_path =
				PathBuf::from(unsafe { OsString::from_encoded_bytes_unchecked(new_bytes) });

			if rpb.is_symlink() {
				let mut resolved_path = read_link_sync(&rpb)?;
				{
					// If this symlink is a symlink to another path within the same
					// directory, then rewrite it as well to start under our new directory.
					let os_str_for_resolved = resolved_path.as_os_str().as_encoded_bytes();
					if os_str_for_resolved.starts_with(old_path_bytes) {
						let mut new_bytes = Vec::with_capacity(os_str_for_resolved.len() + 3);
						new_bytes.extend_from_slice(new_path_as_str_bytes);
						new_bytes.extend_from_slice(&os_str_for_entry[old_path_bytes.len()..]);
						resolved_path = PathBuf::from(unsafe {
							OsString::from_encoded_bytes_unchecked(new_bytes)
						});
					}
				}

				#[cfg(unix)]
				{
					use std::os::unix::fs::symlink;
					symlink(resolved_path, &as_new_path)?;
				}

				#[cfg(target_os = "windows")]
				{
					use std::os::windows::fs::{symlink_dir, symlink_file};

					if resolved_path.is_dir() {
						symlink_dir(resolved_path, &as_new_path)?;
					} else {
						symlink_file(resolved_path, &as_new_path)?;
					}
				}
			} else if rpb.is_file() {
				copy_file_sync(&rpb, &as_new_path)?;
			} else if rpb.is_dir() {
				create_dir_all_sync(&as_new_path)?;
			}
		}

		Ok(())
	}

	/// Rename an entire directory.
	///
	/// We have to implement this ourselves, because [`tokio::fs::rename`], and
	/// [`std::fs::rename`] don't support renaming a directory at all on windows,
	/// which is one of the critical OS's that we need to support.
	///
	/// This 'rename' works by actually creating a new directory. Then
	/// moving all the files over with rename. This is slow, but
	/// works.
	fn rename_dir(source_path: &Path, dest_path: &Path) -> Result<(), FSError> {
		if !dest_path.exists() {
			create_dir_all_sync(dest_path)?;
		}
		let new_path_as_str_bytes = dest_path.as_os_str().as_encoded_bytes();
		let old_path_bytes = source_path.as_os_str().as_encoded_bytes();

		for result in WalkDir::new(source_path)
			.follow_links(false)
			.follow_root_links(false)
		{
			let rpb = result?.into_path();
			let os_str_for_entry = rpb.as_os_str().as_encoded_bytes();
			let mut new_bytes = Vec::with_capacity(os_str_for_entry.len() + 3);
			new_bytes.extend_from_slice(new_path_as_str_bytes);
			new_bytes.extend_from_slice(&os_str_for_entry[old_path_bytes.len()..]);
			let as_new_path =
				PathBuf::from(unsafe { OsString::from_encoded_bytes_unchecked(new_bytes) });

			if rpb.is_symlink() {
				let mut resolved_path = read_link_sync(&rpb)?;
				{
					// If this symlink is a symlink to another path within the same
					// directory, then rewrite it as well to start under our new directory.
					let os_str_for_resolved = resolved_path.as_os_str().as_encoded_bytes();
					if os_str_for_resolved.starts_with(old_path_bytes) {
						let mut new_bytes = Vec::with_capacity(os_str_for_resolved.len() + 3);
						new_bytes.extend_from_slice(new_path_as_str_bytes);
						new_bytes.extend_from_slice(&os_str_for_entry[old_path_bytes.len()..]);
						resolved_path = PathBuf::from(unsafe {
							OsString::from_encoded_bytes_unchecked(new_bytes)
						});
					}
				}

				// Symlinks to directories on Windows run into
				// edge cases, and will frequently get permission denied when
				// attempting to remove them.
				//
				// They will instead be cleaned up by the final folder cleanup which
				// will not run into any such errors.
				let should_remove: bool;
				#[cfg(unix)]
				{
					use std::os::unix::fs::symlink;
					symlink(resolved_path, &as_new_path)?;
					should_remove = true;
				}

				#[cfg(target_os = "windows")]
				{
					use std::os::windows::fs::{symlink_dir, symlink_file};

					if resolved_path.is_dir() {
						symlink_dir(resolved_path, &as_new_path)?;
						should_remove = false;
					} else {
						symlink_file(resolved_path, &as_new_path)?;
						should_remove = true;
					}
				}

				// Remove the original link, we renamed this....
				if should_remove {
					remove_file_sync(&rpb)?;
				}
			} else if rpb.is_file() {
				rename_sync(&rpb, &as_new_path)?;
			} else if rpb.is_dir() {
				create_dir_all_sync(&as_new_path)?;
			}
		}
		// Clean up after ourselves...
		remove_dir_all_sync(source_path)?;

		Ok(())
	}

	/// Generate an `eco.xml` if one is not present.
	///
	/// This is _required_ in order to provide an actual functional PCFS install,
	/// and not actually normally created on the host filesystem with the
	/// official tools. It just generates it in memory.
	///
	/// ## Errors
	///
	/// If we cannot create the config directory, or write the eco config
	/// file to disk.
	async fn generate_eco_xml(cafe_os_path: &Path) -> Result<(), FSError> {
		let mut eco_path = Self::join_many(cafe_os_path, ["data", "slc", "sys", "config"]);
		if !eco_path.exists() {
			create_dir_all_sync(&eco_path).map_err(FSError::IO)?;
		}
		eco_path.push("eco.xml");

		let mut eco_file = File::create(eco_path).await.map_err(FSError::IO)?;
		eco_file
			.write_all(
				br#"<?xml version="1.0" encoding="utf-8"?>
<eco type="complex" access="777">
  <enable type="unsignedInt" length="4">0</enable>
  <max_on_time type="unsignedInt" length="4">3601</max_on_time>
  <default_off_time type="unsignedInt" length="4">15</default_off_time>
  <wd_disable type="unsignedInt" length="4">1</wd_disable>
</eco>"#,
			)
			.await
			.map_err(FSError::IO)?;

		#[cfg(unix)]
		{
			use std::{fs::Permissions, os::unix::prelude::*};
			eco_file
				.set_permissions(Permissions::from_mode(0o770))
				.await?;
		}

		Ok(())
	}

	/// Generate a `wii_acct.xml` if one is not present.
	///
	/// This is _required_ in order to provide an actual functional PCFS install,
	/// and not actually normally created on the host filesystem with the
	/// official tools. It just generates it in memory.
	///
	/// ## Errors
	///
	/// If we cannot create the config directory, or write the wii acct config
	/// file to disk.
	async fn generate_wii_acct_xml(cafe_os_path: &Path) -> Result<(), FSError> {
		let mut wii_path = Self::join_many(cafe_os_path, ["data", "slc", "sys", "proc", "prefs"]);
		if !wii_path.exists() {
			create_dir_all_sync(&wii_path).map_err(FSError::IO)?;
		}
		wii_path.push("wii_acct.xml");

		let mut wii_file = File::create(wii_path).await.map_err(FSError::IO)?;
		wii_file
			.write_all(
				br#"<?xml version="1.0" encoding="utf-8"?>
<wii_acct type="complex">
  <profile type="complex">
    <nickname type="hexBinary" length="22">00570069006900000000000000000000000000000000</nickname>

    <language type="unsignedInt" length="4">0</language>
    <country type="unsignedInt" length="4">1</country>
  </profile>
  <pc type="complex">
    <rating type="unsignedInt" length="4">18</rating>
    <organization type="unsignedInt" length="4">0</organization>
    <rst_internet_ch type="unsignedByte" length="1">0</rst_internet_ch>
    <rst_nw_access type="unsignedByte" length="1">0</rst_nw_access>
    <rst_pt_order type="unsignedByte" length="1">0</rst_pt_order>
  </pc>
</wii_acct>"#,
			)
			.await
			.map_err(FSError::IO)?;

		#[cfg(unix)]
		{
			use std::{fs::Permissions, os::unix::prelude::*};
			wii_file
				.set_permissions(Permissions::from_mode(0o770))
				.await?;
		}

		Ok(())
	}

	/// Take an app.xml, and capitilize the title id. Used for byte-matching
	/// perfectly with the official SDK.
	#[must_use]
	fn capitilize_title_id(app_xml: String) -> String {
		let Some(title_id_xml_tag_start) = app_xml.find("<title_id") else {
			return app_xml;
		};
		let Some(title_id_tag_end) = app_xml[title_id_xml_tag_start..].find('>') else {
			return app_xml;
		};

		let tid_start = title_id_xml_tag_start + title_id_tag_end;
		let Some(title_slash_location) = app_xml[tid_start..].find("</title_id>") else {
			return app_xml;
		};
		let tid_end = tid_start + title_slash_location;
		let title_id = &app_xml[tid_start..tid_end];
		let mut final_xml = String::with_capacity(app_xml.len());
		final_xml += &app_xml[..tid_start];
		final_xml += &title_id.to_uppercase();
		final_xml += &app_xml[tid_end..];

		final_xml
	}

	fn get_default_read_only_folders(cafe_dir: &Path) -> ConcurrentSet<PathBuf> {
		let set = ConcurrentSet::new();

		for cafe_sub_paths in [
			&["data", "slc", "sys", "config"] as &[&str],
			&["data", "slc", "sys", "proc"],
			&["data", "slc", "sys", "logs"],
			&["data", "mlc", "usr"],
			&["data", "mlc", "usr", "import"],
			&["data", "mlc", "usr", "title"],
		] {
			_ = set.insert_sync(Self::join_many(cafe_dir, cafe_sub_paths));
		}

		set
	}
}

const HOST_FILESYSTEM_FIELDS: &[NamedField<'static>] = &[
	NamedField::new("cafe_sdk_path"),
	NamedField::new("open_file_handles"),
	NamedField::new("open_folder_handles"),
];

impl Structable for HostFilesystem {
	fn definition(&self) -> StructDef<'_> {
		StructDef::new_static("HostFilesystem", Fields::Named(HOST_FILESYSTEM_FIELDS))
	}
}

impl Valuable for HostFilesystem {
	fn as_value(&self) -> Value<'_> {
		Value::Structable(self)
	}

	fn visit(&self, visitor: &mut dyn Visit) {
		let mut values = HashMap::with_capacity(self.open_file_handles.len());
		self.open_file_handles.iter_sync(|k, v| {
			values.insert(*k, format!("{}", v.2.display()));
			true
		});
		let mut folder_values = HashMap::with_capacity(self.open_folder_handles.len());
		self.open_folder_handles.iter_sync(|k, v| {
			folder_values.insert(*k, format!("{}", v.3.display()));
			true
		});

		visitor.visit_named_fields(&NamedValues::new(
			HOST_FILESYSTEM_FIELDS,
			&[
				Valuable::as_value(&self.cafe_sdk_path),
				Valuable::as_value(&values),
				Valuable::as_value(&folder_values),
			],
		));
	}
}

/// A resolved location given an arbitrary path.
#[derive(Clone, Debug, PartialEq, Eq, Valuable)]
pub enum ResolvedLocation {
	/// A location on a particular filesystem.
	///
	/// This location _may not exist_. There is a boolean in this struct that
	/// tells you the final resolved location, the closest resolved location for
	/// permission checks, and if the path exists and is the same between
	/// resolution, and what actually exists.
	Filesystem(FilesystemLocation),
	/// A network location to fetch.
	///
	/// TODO(mythra): figure out type.
	Network(()),
}

/// A location that's been resolved, and is guaranteed to be in one of our
/// mounted paths.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FilesystemLocation {
	/// The final resolved path (may not exist).
	resolved_path: PathBuf,
	/// The resolved path that may not be the same as the final path, but is
	/// enough to confirm we're in the same directory.
	closest_resolved_path: PathBuf,
	/// If the canonicalized path is the same as the resolved path.
	canonicalized_is_exact: bool,
}
impl FilesystemLocation {
	#[must_use]
	pub const fn new(
		resolved_path: PathBuf,
		closest_resolved_path: PathBuf,
		canonicalized_is_exact: bool,
	) -> Self {
		Self {
			resolved_path,
			closest_resolved_path,
			canonicalized_is_exact,
		}
	}

	#[must_use]
	pub const fn resolved_path(&self) -> &PathBuf {
		&self.resolved_path
	}
	#[must_use]
	pub const fn closest_resolved_path(&self) -> &PathBuf {
		&self.closest_resolved_path
	}
	#[must_use]
	pub const fn canonicalized_is_exact(&self) -> bool {
		self.canonicalized_is_exact
	}
}

const FILESYSTEM_LOCATION_FIELDS: &[NamedField<'static>] = &[
	NamedField::new("resolved_path"),
	NamedField::new("closest_resolved_path"),
	NamedField::new("canonicalized_is_exact"),
];

impl Structable for FilesystemLocation {
	fn definition(&self) -> StructDef<'_> {
		StructDef::new_static(
			"FilesystemLocation",
			Fields::Named(FILESYSTEM_LOCATION_FIELDS),
		)
	}
}

impl Valuable for FilesystemLocation {
	fn as_value(&self) -> Value<'_> {
		Value::Structable(self)
	}

	fn visit(&self, visitor: &mut dyn Visit) {
		visitor.visit_named_fields(&NamedValues::new(
			FILESYSTEM_LOCATION_FIELDS,
			&[
				Valuable::as_value(&self.resolved_path),
				Valuable::as_value(&self.closest_resolved_path),
				Valuable::as_value(&self.canonicalized_is_exact),
			],
		));
	}
}

#[cfg_attr(docsrs, doc(cfg(test)))]
#[cfg(test)]
pub mod test_helpers {
	use super::*;
	use std::fs::{File, create_dir_all};
	use tempfile::{TempDir, tempdir};

	/// Test helper that creates a simple host filesystem.
	#[allow(
		// Allow anyone to write a test for this internally on any feature set.
		dead_code,
	)]
	pub async fn create_temporary_host_filesystem() -> (TempDir, HostFilesystem) {
		let dir = tempdir().expect("Failed to create temporary directory!");

		for directory_to_create in vec![
			// Create data directories
			vec!["data", "slc"],
			vec!["data", "mlc"],
			vec!["data", "disc"],
			vec!["data", "save"],
			// Create necessary to pass checks.
			vec![
				"data", "mlc", "sys", "title", "00050030", "1001000a", "code",
			],
			vec![
				"data", "mlc", "sys", "title", "00050010", "1f700500", "code",
			],
			vec![
				"data", "mlc", "sys", "title", "00050010", "1f700500", "content",
			],
			vec![
				"data", "mlc", "sys", "title", "00050010", "1f700500", "meta",
			],
			// Purposefully create capital so we can validate renaming works!
			vec![
				"data", "mlc", "sys", "title", "00050030", "1001010A", "code",
			],
			vec![
				"data", "mlc", "sys", "title", "00050030", "1001020a", "code",
			],
			vec![
				"data", "slc", "sys", "title", "00050010", "1000400a", "code",
			],
			vec!["data", "mlc", "sys", "update", "nand", "os_v10_ndebug"],
			vec!["data", "mlc", "sys", "update", "nand", "os_v10_debug"],
			vec!["data", "slc", "sys", "proc", "prefs"],
			vec![
				"data", "slc", "sys", "title", "00050010", "1000800a", "code",
			],
			vec![
				"data", "slc", "sys", "title", "00050010", "1000400a", "code",
			],
		] {
			create_dir_all(HostFilesystem::join_many(dir.path(), directory_to_create))
				.expect("Failed to create directories necessary for host filesystem to work.");
		}

		// Place files that need to exist, they are not real, but enough to "fool"
		// our basic check.
		File::create(HostFilesystem::join_many(
			dir.path(),
			[
				"data", "mlc", "sys", "title", "00050030", "1001000a", "code", "app.xml",
			],
		))
		.expect("Failed to create needed app.xml!");
		File::create(HostFilesystem::join_many(
			dir.path(),
			[
				"data", "mlc", "sys", "title", "00050030", "1001010A", "code", "app.xml",
			],
		))
		.expect("Failed to create needed app.xml!");
		File::create(HostFilesystem::join_many(
			dir.path(),
			[
				"data", "mlc", "sys", "title", "00050030", "1001020a", "code", "app.xml",
			],
		))
		.expect("Failed to create needed app.xml!");

		File::create(HostFilesystem::join_many(
			dir.path(),
			[
				"data", "slc", "sys", "title", "00050010", "1000400a", "code", "fw.img",
			],
		))
		.expect("Failed to create needed fw.img!");
		File::create(HostFilesystem::join_many(
			dir.path(),
			[
				"data", "mlc", "sys", "title", "00050010", "1f700500", "code", "app.xml",
			],
		))
		.expect("Failed to create needed app.xml for disc!");

		let fs = HostFilesystem::from_cafe_dir(Some(PathBuf::from(dir.path())))
			.await
			.expect("Failed to load empty host filesystem!");

		(dir, fs)
	}

	/// Re-export host file system join many for tests.
	#[allow(
		// Allow anyone to write a test for this internally on any feature set.
		dead_code,
	)]
	#[must_use]
	pub fn join_many<PathTy, IterTy>(base: &Path, parts: IterTy) -> PathBuf
	where
		PathTy: AsRef<Path>,
		IterTy: IntoIterator<Item = PathTy>,
	{
		HostFilesystem::join_many(base, parts)
	}
}

#[cfg(test)]
mod unit_tests {
	use super::test_helpers::*;
	use super::*;
	use std::fs::read;

	fn only_accepts_send_sync<T: Send + Sync>(_opt: Option<T>) {}

	#[test]
	pub fn is_send_sync() {
		only_accepts_send_sync::<HostFilesystem>(None);
	}

	#[test]
	pub fn can_find_default_cafe_directory() {
		assert!(
			HostFilesystem::default_cafe_folder().is_some(),
			"Failed to find default cafe directory for your OS",
		);
	}

	#[tokio::test]
	pub async fn creatable_files() {
		// Validate that our functions that create files can actually, well, create
		// those files.
		let (tempdir, fs) = create_temporary_host_filesystem().await;

		let expected_bsf_path = HostFilesystem::join_many(
			tempdir.path(),
			[
				"temp".to_owned(),
				username().to_lowercase(),
				"caferun".to_owned(),
				"ppc.bsf".to_owned(),
			],
		);
		assert!(
			!expected_bsf_path.exists(),
			"ppc.bsf existed before we asked for it?"
		);
		let bsf_path = fs
			.boot1_sytstem_path()
			.await
			.expect("Failed to create bsf!");
		assert_eq!(expected_bsf_path, bsf_path);
		assert!(
			BootSystemFile::try_from(Bytes::from(
				read(bsf_path).expect("Failed to read written boot system file!")
			))
			.is_ok(),
			"Failed to read generated boot system file!"
		);

		let expected_diskid_path = HostFilesystem::join_many(
			tempdir.path(),
			[
				"temp".to_owned(),
				username().to_lowercase(),
				"caferun".to_owned(),
				"diskid.bin".to_owned(),
			],
		);
		assert!(
			!expected_diskid_path.exists(),
			"diskid.bin existed before we asked for it?"
		);
		let diskid_path = fs
			.disk_id_path()
			.await
			.expect("Failed to create diskid.bin!");
		assert_eq!(expected_diskid_path, diskid_path);
		assert_eq!(
			read(diskid_path).expect("Failed to read written diskid.bin!"),
			vec![0; 32],
			"Failed to read generated diskid.bin!"
		);

		// Can't generate firmware files for now.
		assert_eq!(
			fs.firmware_file_path(),
			HostFilesystem::join_many(
				tempdir.path(),
				[
					"data", "slc", "sys", "title", "00050010", "1000400a", "code", "fw.img"
				],
			),
		);

		let expected_ppc_boot_dlf_path = HostFilesystem::join_many(
			tempdir.path(),
			[
				"temp".to_owned(),
				username().to_lowercase(),
				"caferun".to_owned(),
				"ppc_boot.dlf".to_owned(),
			],
		);
		assert!(
			!expected_ppc_boot_dlf_path.exists(),
			"ppc_boot.dlf existed before we asked for it?"
		);
		let ppc_boot_dlf_path = fs
			.ppc_boot_dlf_path()
			.await
			.expect("Failed to create ppc_boot.dlf!");
		assert_eq!(expected_ppc_boot_dlf_path, ppc_boot_dlf_path);
		assert!(
			DiskLayoutFile::try_from(Bytes::from(
				read(ppc_boot_dlf_path).expect("Failed to read written ppc_boot.dlf!")
			))
			.is_ok(),
			"Failed to read generated ppc_boot.dlf!"
		);
	}

	#[tokio::test]
	pub async fn path_allows_writes() {
		let (_tempdir, fs) = create_temporary_host_filesystem().await;

		// DIRECTORIES BESIDES DISC should allow writes.
		// unless excluded by fsemul attrs.
		assert!(fs.path_allows_writes(&PathBuf::from("/vol/pc/%MLC_EMU_DIR/")));
		assert!(fs.path_allows_writes(&PathBuf::from("/vol/pc/%SLC_EMU_DIR/")));
		assert!(fs.path_allows_writes(&PathBuf::from("/vol/pc/%SAVE_EMU_DIR/")));
		assert!(!fs.path_allows_writes(&PathBuf::from("/vol/pc/%DISC_EMU_DIR/")));
		assert!(!fs.path_allows_writes(&PathBuf::from("/vol/pc/%DISC_EMU_DIR/")));
	}

	#[tokio::test]
	pub async fn resolve_path() {
		// Validate that our functions that create files can actually, well, create
		// those files.
		let (tempdir, fs) = create_temporary_host_filesystem().await;

		// Validate each of the regular directories work.
		for (dir, name) in [
			("/%MLC_EMU_DIR", "mlc"),
			("/%SLC_EMU_DIR", "slc"),
			("/%DISC_EMU_DIR", "disc"),
			("/%SAVE_EMU_DIR", "save"),
		] {
			assert!(
				fs.resolve_path(&format!("{dir}")).is_ok(),
				"Failed to resolve: `{}`: {:?}",
				dir,
				fs.resolve_path(&format!("{dir}"))
			);
			assert!(
				fs.resolve_path(&format!("{dir}/")).is_ok(),
				"Failed to resolve: `{}/`",
				dir,
			);
			assert!(
				fs.resolve_path(&format!("{dir}/./")).is_ok(),
				"Failed to resolve: `{}/./`",
				dir,
			);
			assert!(
				fs.resolve_path(&format!("{dir}/../{name}")).is_ok(),
				"Failed to resolve: `{}/../{}`",
				dir,
				name,
			);
		}

		// Validate that paths outside of our root directory don't work.
		let mut out_of_path = PathBuf::from(tempdir.path());
		// We now left tempdir, and this path isn't mounted, so we should error out
		// on this.
		out_of_path.pop();

		// We shouldn't be able to resolve paths outside of our directory.
		assert!(
			fs.resolve_path(
				&out_of_path
					.clone()
					.into_os_string()
					.into_string()
					.expect("Failed to convert pathbuf to string!")
			)
			.is_err()
		);
		assert!(fs.resolve_path("/%MLC_EMU_DIR/../../../").is_err());

		#[cfg(unix)]
		{
			use std::os::unix::fs::symlink;

			let mut tempdir_symlink = PathBuf::from(tempdir.path());
			tempdir_symlink.push("symlink");
			symlink(out_of_path, tempdir_symlink.clone()).expect("Failed to do symlink!");
			assert!(
				fs.resolve_path(&format!(
					"{}/symlink",
					tempdir_symlink
						.into_os_string()
						.into_string()
						.expect("tempdir symlink wasn't utf8?"),
				))
				.is_err()
			);
		}

		#[cfg(target_os = "windows")]
		{
			use std::os::windows::fs::symlink_dir;

			let mut tempdir_symlink = PathBuf::from(tempdir.path());
			tempdir_symlink.push("symlink");
			symlink_dir(out_of_path, tempdir_symlink.clone()).expect("Failed to do symlink!");
			assert!(
				fs.resolve_path(&format!(
					"{}/symlink",
					tempdir_symlink
						.into_os_string()
						.into_string()
						.expect("tempdir symlink wasn't utf8?"),
				))
				.is_err()
			);
		}
	}

	#[tokio::test]
	pub async fn opening_files() {
		let (tempdir, fs) = create_temporary_host_filesystem().await;
		let path = HostFilesystem::join_many(tempdir.path(), ["file.txt"]);
		tokio::fs::write(path.clone(), vec![0; 1307])
			.await
			.expect("Failed to write test file!");
		let create_path = HostFilesystem::join_many(tempdir.path(), ["new-file.txt"]);

		let mut oo = OpenOptions::new();
		oo.create(false).write(true).read(true);
		assert!(
			fs.open_file(oo, &create_path, None).await.is_err(),
			"Somehow succeeding opening a file that doesn't exist with no create flag?",
		);
		oo = OpenOptions::new();
		oo.create(true).write(true).truncate(true);
		let fd = fs
			.open_file(oo, &create_path, None)
			.await
			.expect("Failed opening a file that doesn't exist with a create flag?");
		assert!(
			fs.open_file_handles.len() == 1 && fs.open_file_handles.get_sync(&fd).is_some(),
			"Open file wasn't in open files list!",
		);
		fs.close_file(fd, None).await;
		assert!(
			fs.open_file_handles.is_empty(),
			"Somehow after opening/closing, open file handles was not empty?",
		);
	}

	#[tokio::test]
	pub async fn seek_and_read() {
		let (tempdir, fs) = create_temporary_host_filesystem().await;
		let path = HostFilesystem::join_many(tempdir.path(), ["file.txt"]);
		tokio::fs::write(path.clone(), vec![0; 1307])
			.await
			.expect("Failed to write test file!");

		let mut oo = OpenOptions::new();
		oo.read(true).create(false).write(false);
		let fd = fs
			.open_file(oo, &path, None)
			.await
			.expect("Failed to open existing file!");

		// Should be possible to read all bytes.
		assert_eq!(
			Some(BytesMut::zeroed(1307).freeze()),
			fs.read_file(fd, 1307, None)
				.await
				.expect("Failed to read from FD!"),
		);
		fs.seek_file(fd, true, None)
			.await
			.expect("Failed to sync to beginning of file!");
		// Can read all bytes again!
		assert_eq!(
			Some(BytesMut::zeroed(1307).freeze()),
			fs.read_file(fd, 1307, None)
				.await
				.expect("Failed to read from FD!"),
		);
		fs.close_file(fd, None).await;
		assert!(
			fs.open_file_handles.is_empty(),
			"Somehow after opening/closing, open file handles was not empty?",
		);
	}

	#[tokio::test]
	pub async fn open_and_close_folder() {
		let (tempdir, fs) = create_temporary_host_filesystem().await;
		let path = HostFilesystem::join_many(tempdir.path(), ["a", "b"]);
		tokio::fs::create_dir_all(path.clone())
			.await
			.expect("Failed to create test directory!");

		let fd = fs
			.open_folder(&path, None)
			.expect("Failed to open existing folder!");
		assert!(
			fs.open_folder_handles.len() == 1,
			"Expected one open folder handle",
		);
		fs.close_folder(fd, None).await;

		assert!(
			fs.open_folder_handles.is_empty(),
			"Somehow after opening/closing, open folder handles was not empty?",
		);
	}

	#[tokio::test]
	pub async fn seek_within_folder() {
		let (tempdir, fs) = create_temporary_host_filesystem().await;
		let path = HostFilesystem::join_many(tempdir.path(), ["a", "b"]);
		tokio::fs::create_dir_all(path.clone())
			.await
			.expect("Failed to create test directory!");

		// Only `c`, `d`, and `f` should be returned.
		//
		// `e` is a symlink   (ignored)
		// `d/a` is an item in a subdirectory (ignored)
		_ = tokio::fs::File::create(HostFilesystem::join_many(&path, ["c"]))
			.await
			.expect("Failed to create file to use!");
		tokio::fs::create_dir(HostFilesystem::join_many(&path, ["d"]))
			.await
			.expect("Failed to create directory to use!");
		#[cfg(unix)]
		{
			use std::os::unix::fs::symlink;

			let mut tempdir_symlink = path.clone();
			tempdir_symlink.push("e");
			symlink(tempdir.path(), tempdir_symlink).expect("Failed to do symlink!");
		}
		#[cfg(target_os = "windows")]
		{
			use std::os::windows::fs::symlink_dir;

			let mut tempdir_symlink = path.clone();
			tempdir_symlink.push("e");
			symlink_dir(tempdir.path(), tempdir_symlink).expect("Failed to do symlink!");
		}
		_ = tokio::fs::File::create(HostFilesystem::join_many(&path, ["f"]))
			.await
			.expect("Failed to create file to use!");
		_ = tokio::fs::File::create(HostFilesystem::join_many(&path, ["d", "a"]))
			.await
			.expect("Failed to create file to use!");

		let dfd = fs.open_folder(&path, None).expect("Failed to open folder!");
		assert!(
			fs.next_in_folder(dfd, None)
				.await
				.expect("Failed to query for next in folder! 1.1!")
				.is_some()
		);
		assert!(
			fs.next_in_folder(dfd, None)
				.await
				.expect("Failed to query for next in folder! 1.2!")
				.is_some()
		);
		assert!(
			fs.next_in_folder(dfd, None)
				.await
				.expect("Failed to query for next in folder! 1.3!")
				.is_some()
		);
		// We should have hit the end...
		assert!(
			fs.next_in_folder(dfd, None)
				.await
				.expect("Failed to query for next in folder! 1.4!")
				.is_none()
		);
		// We can call as many times as we want.
		assert!(
			fs.next_in_folder(dfd, None)
				.await
				.expect("Failed to query for next in folder! 1.5!")
				.is_none()
		);
		// Rewind to get to reads again!
		fs.reverse_folder(dfd, None)
			.await
			.expect("Failed to reverse directory search!");
		assert!(
			fs.next_in_folder(dfd, None)
				.await
				.expect("Failed to query for next in folder! 2.1!")
				.is_some()
		);
		assert!(
			fs.next_in_folder(dfd, None)
				.await
				.expect("Failed to query for next in folder! 2.2!")
				.is_none()
		);
	}

	#[test]
	pub fn can_capitilize_ids() {
		assert_eq!(
			HostFilesystem::capitilize_title_id(
				r#"<?xml version="1.0" encoding = "utf-8"?>
<app type="complex" access="777">
  <version type="unsignedInt" length="4">16</version>
  <os_version type="hexBinary" length="8">000500101000400A</os_version>
  <title_id type="hexBinary" length="8">000500101f700500</title_id>
  <title_version type="hexBinary" length="2">090D</title_version>
  <sdk_version type="unsignedInt" length="4">21213</sdk_version>
  <app_type type="hexBinary" length="4">90000001</app_type>
  <group_id type="hexBinary" length="4">00000400</group_id>
  <os_mask  type="hexBinary" length="32">0</os_mask>
  <common_id type="hexBinary" length="8">0000000000000000</common_id>
</app>"#
					.to_owned()
			),
			r#"<?xml version="1.0" encoding = "utf-8"?>
<app type="complex" access="777">
  <version type="unsignedInt" length="4">16</version>
  <os_version type="hexBinary" length="8">000500101000400A</os_version>
  <title_id type="hexBinary" length="8">000500101F700500</title_id>
  <title_version type="hexBinary" length="2">090D</title_version>
  <sdk_version type="unsignedInt" length="4">21213</sdk_version>
  <app_type type="hexBinary" length="4">90000001</app_type>
  <group_id type="hexBinary" length="4">00000400</group_id>
  <os_mask  type="hexBinary" length="32">0</os_mask>
  <common_id type="hexBinary" length="8">0000000000000000</common_id>
</app>"#
				.to_owned(),
		);

		assert_eq!(
			HostFilesystem::capitilize_title_id(
				r#"<?xml version="1.0" encoding = "utf-8"?>
<app type="complex" access="777">
  <version type="unsignedInt" length="4">16</version>
  <os_version type="hexBinary" length="8">000500101000400A</os_version>
  <title_id type="hexBinary" length="8">000500101F700500</title_id>
  <title_version type="hexBinary" length="2">090D</title_version>
  <sdk_version type="unsignedInt" length="4">21213</sdk_version>
  <app_type type="hexBinary" length="4">90000001</app_type>
  <group_id type="hexBinary" length="4">00000400</group_id>
  <os_mask  type="hexBinary" length="32">0</os_mask>
  <common_id type="hexBinary" length="8">0000000000000000</common_id>
</app>"#
					.to_owned()
			),
			r#"<?xml version="1.0" encoding = "utf-8"?>
<app type="complex" access="777">
  <version type="unsignedInt" length="4">16</version>
  <os_version type="hexBinary" length="8">000500101000400A</os_version>
  <title_id type="hexBinary" length="8">000500101F700500</title_id>
  <title_version type="hexBinary" length="2">090D</title_version>
  <sdk_version type="unsignedInt" length="4">21213</sdk_version>
  <app_type type="hexBinary" length="4">90000001</app_type>
  <group_id type="hexBinary" length="4">00000400</group_id>
  <os_mask  type="hexBinary" length="32">0</os_mask>
  <common_id type="hexBinary" length="8">0000000000000000</common_id>
</app>"#
				.to_owned(),
		);

		assert_eq!(
			HostFilesystem::capitilize_title_id(
				r#"<?xml version="1.0" encoding = "utf-8"?>
<app type="complex" access="777">
  <version type="unsignedInt" length="4">16</version>
  <os_version type="hexBinary" length="8">000500101000400A</os_version>
  <title_version type="hexBinary" length="2">090D</title_version>
  <sdk_version type="unsignedInt" length="4">21213</sdk_version>
  <app_type type="hexBinary" length="4">90000001</app_type>
  <group_id type="hexBinary" length="4">00000400</group_id>
  <os_mask  type="hexBinary" length="32">0</os_mask>
  <common_id type="hexBinary" length="8">0000000000000000</common_id>
</app>"#
					.to_owned()
			),
			r#"<?xml version="1.0" encoding = "utf-8"?>
<app type="complex" access="777">
  <version type="unsignedInt" length="4">16</version>
  <os_version type="hexBinary" length="8">000500101000400A</os_version>
  <title_version type="hexBinary" length="2">090D</title_version>
  <sdk_version type="unsignedInt" length="4">21213</sdk_version>
  <app_type type="hexBinary" length="4">90000001</app_type>
  <group_id type="hexBinary" length="4">00000400</group_id>
  <os_mask  type="hexBinary" length="32">0</os_mask>
  <common_id type="hexBinary" length="8">0000000000000000</common_id>
</app>"#
				.to_owned(),
		);

		assert_eq!(
			HostFilesystem::capitilize_title_id(r#"<?xml version="1.0" encoding = "utf-8"?>
<app type="complex" access="777">
  <version type="unsignedInt" length="4">16</version>
  <os_version type="hexBinary" length="8">000500101000400A</os_version><title_id type="hexBinary" length="8">000500101f700500</title_id><title_version type="hexBinary" length="2">090D</title_version>
  <sdk_version type="unsignedInt" length="4">21213</sdk_version>
  <app_type type="hexBinary" length="4">90000001</app_type>
  <group_id type="hexBinary" length="4">00000400</group_id>
  <os_mask  type="hexBinary" length="32">0</os_mask>
  <common_id type="hexBinary" length="8">0000000000000000</common_id>
</app>"#.to_owned()),
			r#"<?xml version="1.0" encoding = "utf-8"?>
<app type="complex" access="777">
  <version type="unsignedInt" length="4">16</version>
  <os_version type="hexBinary" length="8">000500101000400A</os_version><title_id type="hexBinary" length="8">000500101F700500</title_id><title_version type="hexBinary" length="2">090D</title_version>
  <sdk_version type="unsignedInt" length="4">21213</sdk_version>
  <app_type type="hexBinary" length="4">90000001</app_type>
  <group_id type="hexBinary" length="4">00000400</group_id>
  <os_mask  type="hexBinary" length="32">0</os_mask>
  <common_id type="hexBinary" length="8">0000000000000000</common_id>
</app>"#.to_owned(),
		);
	}
}