Replace ReadDir method with one that uses IDirNode.

This commit is contained in:
2022-12-21 20:03:24 +00:00
parent 5ae8c92a32
commit 3becc0833c
20 changed files with 184 additions and 690 deletions

View File

@@ -47,7 +47,7 @@ public sealed partial class Sidecar
{ {
var contents = new FilesystemContents(); var contents = new FilesystemContents();
ErrorNumber ret = filesystem.ReadDir("/", out List<string> dirents); ErrorNumber ret = filesystem.OpenDir("/", out IDirNode node);
if(ret != ErrorNumber.NoError) if(ret != ErrorNumber.NoError)
return null; return null;
@@ -55,7 +55,8 @@ public sealed partial class Sidecar
List<Directory> directories = new(); List<Directory> directories = new();
List<ContentsFile> files = new(); List<ContentsFile> files = new();
foreach(string dirent in dirents) while(filesystem.ReadDir(node, out string dirent) == ErrorNumber.NoError &&
dirent is not null)
{ {
ret = filesystem.Stat(dirent, out FileEntryInfo stat); ret = filesystem.Stat(dirent, out FileEntryInfo stat);
@@ -76,6 +77,8 @@ public sealed partial class Sidecar
files.Add(SidecarFile(filesystem, "", dirent, stat)); files.Add(SidecarFile(filesystem, "", dirent, stat));
} }
filesystem.CloseDir(node);
if(files.Count > 0) if(files.Count > 0)
contents.Files = files.OrderBy(f => f.Name).ToList(); contents.Files = files.OrderBy(f => f.Name).ToList();
@@ -104,7 +107,7 @@ public sealed partial class Sidecar
StatusChangeTime = stat.StatusChangeTimeUtc StatusChangeTime = stat.StatusChangeTimeUtc
}; };
ErrorNumber ret = filesystem.ReadDir(path + "/" + filename, out List<string> dirents); ErrorNumber ret = filesystem.OpenDir(path + "/" + filename, out IDirNode node);
if(ret != ErrorNumber.NoError) if(ret != ErrorNumber.NoError)
return null; return null;
@@ -112,7 +115,8 @@ public sealed partial class Sidecar
List<Directory> directories = new(); List<Directory> directories = new();
List<ContentsFile> files = new(); List<ContentsFile> files = new();
foreach(string dirent in dirents) while(filesystem.ReadDir(node, out string dirent) == ErrorNumber.NoError &&
dirent is not null)
{ {
ret = filesystem.Stat(path + "/" + filename + "/" + dirent, out FileEntryInfo entryStat); ret = filesystem.Stat(path + "/" + filename + "/" + dirent, out FileEntryInfo entryStat);

View File

@@ -84,27 +84,23 @@ public sealed partial class AppleDOS
} }
/// <inheritdoc /> /// <inheritdoc />
public ErrorNumber ReadDir(string path, out List<string> contents) public ErrorNumber ReadDir(IDirNode node, out string filename)
{ {
contents = null; filename = null;
if(!_mounted) if(!_mounted)
return ErrorNumber.AccessDenied; return ErrorNumber.AccessDenied;
if(!string.IsNullOrEmpty(path) && if(node is not AppleDosDirNode mynode)
string.Compare(path, "/", StringComparison.OrdinalIgnoreCase) != 0) return ErrorNumber.InvalidArgument;
return ErrorNumber.NotSupported;
contents = _catalogCache.Keys.ToList(); if(mynode._position < 0)
return ErrorNumber.InvalidArgument;
if(_debug) if(mynode._position >= mynode._contents.Length)
{ return ErrorNumber.NoError;
contents.Add("$");
contents.Add("$Boot");
contents.Add("$Vtoc");
}
contents.Sort(); filename = mynode._contents[mynode._position++];
return ErrorNumber.NoError; return ErrorNumber.NoError;
} }
@@ -121,7 +117,6 @@ public sealed partial class AppleDOS
return ErrorNumber.NoError; return ErrorNumber.NoError;
} }
ErrorNumber ReadCatalog() ErrorNumber ReadCatalog()
{ {
var catalogMs = new MemoryStream(); var catalogMs = new MemoryStream();

View File

@@ -76,30 +76,23 @@ public sealed partial class AppleMFS
} }
/// <inheritdoc /> /// <inheritdoc />
public ErrorNumber ReadDir(string path, out List<string> contents) public ErrorNumber ReadDir(IDirNode node, out string filename)
{ {
contents = null; filename = null;
if(!_mounted) if(!_mounted)
return ErrorNumber.AccessDenied; return ErrorNumber.AccessDenied;
if(!string.IsNullOrEmpty(path) && if(node is not AppleMfsDirNode mynode)
string.Compare(path, "/", StringComparison.OrdinalIgnoreCase) != 0) return ErrorNumber.InvalidArgument;
return ErrorNumber.NotSupported;
contents = _idToFilename.Select(kvp => kvp.Value).ToList(); if(mynode._position < 0)
return ErrorNumber.InvalidArgument;
if(_debug) if(mynode._position >= mynode._contents.Length)
{ return ErrorNumber.NoError;
contents.Add("$");
contents.Add("$Bitmap");
contents.Add("$MDB");
if(_bootBlocks != null) filename = mynode._contents[mynode._position++];
contents.Add("$Boot");
}
contents.Sort();
return ErrorNumber.NoError; return ErrorNumber.NoError;
} }

View File

@@ -31,7 +31,6 @@
// ****************************************************************************/ // ****************************************************************************/
using System; using System;
using System.Collections.Generic;
using System.Text; using System.Text;
using Aaru.CommonTypes.Enums; using Aaru.CommonTypes.Enums;
using Aaru.CommonTypes.Interfaces; using Aaru.CommonTypes.Interfaces;
@@ -64,18 +63,23 @@ public sealed partial class CPM
} }
/// <inheritdoc /> /// <inheritdoc />
public ErrorNumber ReadDir(string path, out List<string> contents) public ErrorNumber ReadDir(IDirNode node, out string filename)
{ {
contents = null; filename = null;
if(!_mounted) if(!_mounted)
return ErrorNumber.AccessDenied; return ErrorNumber.AccessDenied;
if(!string.IsNullOrEmpty(path) && if(node is not CpmDirNode mynode)
string.Compare(path, "/", StringComparison.OrdinalIgnoreCase) != 0) return ErrorNumber.InvalidArgument;
return ErrorNumber.NotSupported;
contents = new List<string>(_dirList); if(mynode._position < 0)
return ErrorNumber.InvalidArgument;
if(mynode._position >= mynode._contents.Length)
return ErrorNumber.NoError;
filename = mynode._contents[mynode._position++];
return ErrorNumber.NoError; return ErrorNumber.NoError;
} }

View File

@@ -413,341 +413,35 @@ public sealed partial class FAT
} }
/// <inheritdoc /> /// <inheritdoc />
/// <summary>Lists contents from a directory.</summary> public ErrorNumber ReadDir(IDirNode node, out string filename)
/// <param name="path">Directory path.</param>
/// <param name="contents">Directory contents.</param>
public ErrorNumber ReadDir(string path, out List<string> contents)
{ {
contents = null; filename = null;
if(!_mounted) if(!_mounted)
return ErrorNumber.AccessDenied; return ErrorNumber.AccessDenied;
if(string.IsNullOrWhiteSpace(path) || if(node is not FatDirNode mynode)
path == "/")
{
contents = _rootDirectoryCache.Keys.ToList();
return ErrorNumber.NoError;
}
string cutPath = path.StartsWith("/", StringComparison.Ordinal) ? path[1..].ToLower(_cultureInfo)
: path.ToLower(_cultureInfo);
if(_directoryCache.TryGetValue(cutPath, out Dictionary<string, CompleteDirectoryEntry> currentDirectory))
{
contents = currentDirectory.Keys.ToList();
return ErrorNumber.NoError;
}
string[] pieces = cutPath.Split(new[]
{
'/'
}, StringSplitOptions.RemoveEmptyEntries);
KeyValuePair<string, CompleteDirectoryEntry> entry =
_rootDirectoryCache.FirstOrDefault(t => t.Key.ToLower(_cultureInfo) == pieces[0]);
if(string.IsNullOrEmpty(entry.Key))
return ErrorNumber.NoSuchFile;
if(!entry.Value.Dirent.attributes.HasFlag(FatAttributes.Subdirectory))
return ErrorNumber.NotDirectory;
string currentPath = pieces[0];
currentDirectory = _rootDirectoryCache;
for(int p = 0; p < pieces.Length; p++)
{
entry = currentDirectory.FirstOrDefault(t => t.Key.ToLower(_cultureInfo) == pieces[p]);
if(string.IsNullOrEmpty(entry.Key))
return ErrorNumber.NoSuchFile;
if(!entry.Value.Dirent.attributes.HasFlag(FatAttributes.Subdirectory))
return ErrorNumber.NotDirectory;
currentPath = p == 0 ? pieces[0] : $"{currentPath}/{pieces[p]}";
uint currentCluster = entry.Value.Dirent.start_cluster;
if(_fat32)
currentCluster += (uint)(entry.Value.Dirent.ea_handle << 16);
if(_directoryCache.TryGetValue(currentPath, out currentDirectory))
continue;
// Reserved unallocated directory, seen in Atari ST
if(currentCluster == 0)
{
_directoryCache[currentPath] = new Dictionary<string, CompleteDirectoryEntry>();
contents = new List<string>();
return ErrorNumber.NoError;
}
uint[] clusters = GetClusters(currentCluster);
if(clusters is null)
return ErrorNumber.InvalidArgument; return ErrorNumber.InvalidArgument;
byte[] directoryBuffer = new byte[_bytesPerCluster * clusters.Length]; if(mynode._position < 0)
return ErrorNumber.InvalidArgument;
for(int i = 0; i < clusters.Length; i++) if(mynode._position >= mynode._entries.Length)
return ErrorNumber.NoError;
CompleteDirectoryEntry entry = mynode._entries[mynode._position];
filename = _namespace switch
{ {
ErrorNumber errno = _image.ReadSectors(_firstClusterSector + (clusters[i] * _sectorsPerCluster), Namespace.Ecs when entry.Longname is not null => entry.Longname,
_sectorsPerCluster, out byte[] buffer); Namespace.Ecs when entry.Longname is null && entry.Lfn is not null => entry.Lfn,
Namespace.Lfn when entry.Lfn is not null => entry.Lfn,
if(errno != ErrorNumber.NoError) Namespace.Human when entry.HumanName is not null => entry.HumanName,
return errno; Namespace.Os2 when entry.Longname is not null => entry.Longname,
_ => entry.Shortname
Array.Copy(buffer, 0, directoryBuffer, i * _bytesPerCluster, _bytesPerCluster);
}
currentDirectory = new Dictionary<string, CompleteDirectoryEntry>();
byte[] lastLfnName = null;
byte lastLfnChecksum = 0;
for(int pos = 0; pos < directoryBuffer.Length; pos += Marshal.SizeOf<DirectoryEntry>())
{
DirectoryEntry dirent =
Marshal.ByteArrayToStructureLittleEndian<DirectoryEntry>(directoryBuffer, pos,
Marshal.SizeOf<DirectoryEntry>());
if(dirent.filename[0] == DIRENT_FINISHED)
break;
if(dirent.attributes.HasFlag(FatAttributes.LFN))
{
if(_namespace != Namespace.Lfn &&
_namespace != Namespace.Ecs)
continue;
LfnEntry lfnEntry =
Marshal.ByteArrayToStructureLittleEndian<LfnEntry>(directoryBuffer, pos,
Marshal.SizeOf<LfnEntry>());
int lfnSequence = lfnEntry.sequence & LFN_MASK;
if((lfnEntry.sequence & LFN_ERASED) > 0)
continue;
if((lfnEntry.sequence & LFN_LAST) > 0)
{
lastLfnName = new byte[lfnSequence * 26];
lastLfnChecksum = lfnEntry.checksum;
}
if(lastLfnName is null)
continue;
if(lfnEntry.checksum != lastLfnChecksum)
continue;
lfnSequence--;
Array.Copy(lfnEntry.name1, 0, lastLfnName, lfnSequence * 26, 10);
Array.Copy(lfnEntry.name2, 0, lastLfnName, (lfnSequence * 26) + 10, 12);
Array.Copy(lfnEntry.name3, 0, lastLfnName, (lfnSequence * 26) + 22, 4);
continue;
}
// Not a correct entry
if(dirent.filename[0] < DIRENT_MIN &&
dirent.filename[0] != DIRENT_E5)
continue;
// Self
if(_encoding.GetString(dirent.filename).TrimEnd() == ".")
continue;
// Parent
if(_encoding.GetString(dirent.filename).TrimEnd() == "..")
continue;
// Deleted
if(dirent.filename[0] == DIRENT_DELETED)
continue;
string filename;
if(dirent.attributes.HasFlag(FatAttributes.VolumeLabel))
continue;
var completeEntry = new CompleteDirectoryEntry
{
Dirent = dirent
}; };
if(_namespace is Namespace.Lfn or Namespace.Ecs && mynode._position++;
lastLfnName != null)
{
byte calculatedLfnChecksum = LfnChecksum(dirent.filename, dirent.extension);
if(calculatedLfnChecksum == lastLfnChecksum)
{
filename = StringHandlers.CToString(lastLfnName, Encoding.Unicode, true);
completeEntry.Lfn = filename;
lastLfnName = null;
lastLfnChecksum = 0;
}
}
if(dirent.filename[0] == DIRENT_E5)
dirent.filename[0] = DIRENT_DELETED;
string name = _encoding.GetString(dirent.filename).TrimEnd();
string extension = _encoding.GetString(dirent.extension).TrimEnd();
if(name == "" &&
extension == "")
{
AaruConsole.DebugWriteLine("FAT filesystem", Localization.Found_empty_filename_in_0, path);
if(!_debug ||
dirent is { size: > 0, start_cluster: 0 })
continue; // Skip invalid name
// If debug, add it
name = ":{EMPTYNAME}:";
// Try to create a unique filename with an extension from 000 to 999
for(int uniq = 0; uniq < 1000; uniq++)
{
extension = $"{uniq:D03}";
if(!currentDirectory.ContainsKey($"{name}.{extension}"))
break;
}
// If we couldn't find it, just skip over
if(currentDirectory.ContainsKey($"{name}.{extension}"))
continue;
}
if(_namespace == Namespace.Nt)
{
if(dirent.caseinfo.HasFlag(CaseInfo.LowerCaseExtension))
extension = extension.ToLower(CultureInfo.CurrentCulture);
if(dirent.caseinfo.HasFlag(CaseInfo.LowerCaseBasename))
name = name.ToLower(CultureInfo.CurrentCulture);
}
if(extension != "")
filename = name + "." + extension;
else
filename = name;
if(_namespace == Namespace.Human)
{
HumanDirectoryEntry humanEntry =
Marshal.ByteArrayToStructureLittleEndian<HumanDirectoryEntry>(directoryBuffer, pos,
Marshal.SizeOf<HumanDirectoryEntry>());
completeEntry.HumanDirent = humanEntry;
name = StringHandlers.CToString(humanEntry.name1, _encoding).TrimEnd();
extension = StringHandlers.CToString(humanEntry.extension, _encoding).TrimEnd();
string name2 = StringHandlers.CToString(humanEntry.name2, _encoding).TrimEnd();
if(extension != "")
filename = name + name2 + "." + extension;
else
filename = name + name2;
completeEntry.HumanName = filename;
}
// Atari ST allows slash AND colon so cannot simply substitute one for the other like in Mac filesystems
filename = filename.Replace('/', '\u2215');
// Using array accessor ensures that repeated entries just get substituted.
// Repeated entries are not allowed but some bad implementations (e.g. FAT32.IFS)allow to create them
// when using spaces
completeEntry.Shortname = filename;
currentDirectory[completeEntry.ToString()] = completeEntry;
}
// Check OS/2 .LONGNAME
if(_eaCache != null &&
_namespace is Namespace.Os2 or Namespace.Ecs &&
!_fat32)
{
List<KeyValuePair<string, CompleteDirectoryEntry>> filesWithEas =
currentDirectory.Where(t => t.Value.Dirent.ea_handle != 0).ToList();
foreach(KeyValuePair<string, CompleteDirectoryEntry> fileWithEa in filesWithEas)
{
Dictionary<string, byte[]> eas = GetEas(fileWithEa.Value.Dirent.ea_handle);
if(eas is null)
continue;
if(!eas.TryGetValue("com.microsoft.os2.longname", out byte[] longnameEa))
continue;
if(BitConverter.ToUInt16(longnameEa, 0) != EAT_ASCII)
continue;
ushort longnameSize = BitConverter.ToUInt16(longnameEa, 2);
if(longnameSize + 4 > longnameEa.Length)
continue;
byte[] longnameBytes = new byte[longnameSize];
Array.Copy(longnameEa, 4, longnameBytes, 0, longnameSize);
string longname = StringHandlers.CToString(longnameBytes, _encoding);
if(string.IsNullOrWhiteSpace(longname))
continue;
// Forward slash is allowed in .LONGNAME, so change it to visually similar division slash
longname = longname.Replace('/', '\u2215');
fileWithEa.Value.Longname = longname;
currentDirectory.Remove(fileWithEa.Key);
currentDirectory[fileWithEa.Value.ToString()] = fileWithEa.Value;
}
}
// Check FAT32.IFS EAs
if(_fat32 || _debug)
{
List<KeyValuePair<string, CompleteDirectoryEntry>> fat32EaSidecars =
currentDirectory.Where(t => t.Key.EndsWith(FAT32_EA_TAIL, true, _cultureInfo)).ToList();
foreach(KeyValuePair<string, CompleteDirectoryEntry> sidecar in fat32EaSidecars)
{
// No real file this sidecar accompanies
if(!currentDirectory.TryGetValue(sidecar.Key[..^FAT32_EA_TAIL.Length],
out CompleteDirectoryEntry fileWithEa))
continue;
// If not in debug mode we will consider the lack of EA bitflags to mean the EAs are corrupted or not real
if(!_debug)
if(!fileWithEa.Dirent.caseinfo.HasFlag(CaseInfo.NormalEaOld) &&
!fileWithEa.Dirent.caseinfo.HasFlag(CaseInfo.CriticalEa) &&
!fileWithEa.Dirent.caseinfo.HasFlag(CaseInfo.NormalEa) &&
!fileWithEa.Dirent.caseinfo.HasFlag(CaseInfo.CriticalEa))
continue;
fileWithEa.Fat32Ea = sidecar.Value.Dirent;
if(!_debug)
currentDirectory.Remove(sidecar.Key);
}
}
_directoryCache.Add(currentPath, currentDirectory);
}
contents = currentDirectory?.Keys.ToList();
return ErrorNumber.NoError; return ErrorNumber.NoError;
} }

View File

@@ -313,10 +313,12 @@ public sealed partial class FAT
if(!_directoryCache.TryGetValue(parentPath, out _)) if(!_directoryCache.TryGetValue(parentPath, out _))
{ {
ErrorNumber err = ReadDir(parentPath, out _); ErrorNumber err = OpenDir(parentPath, out IDirNode node);
if(err != ErrorNumber.NoError) if(err != ErrorNumber.NoError)
return err; return err;
CloseDir(node);
} }
Dictionary<string, CompleteDirectoryEntry> parent; Dictionary<string, CompleteDirectoryEntry> parent;

View File

@@ -167,112 +167,26 @@ public sealed partial class XboxFatPlugin
} }
/// <inheritdoc /> /// <inheritdoc />
public ErrorNumber ReadDir(string path, out List<string> contents) public ErrorNumber ReadDir(IDirNode node, out string filename)
{ {
contents = null; filename = null;
if(!_mounted) if(!_mounted)
return ErrorNumber.AccessDenied; return ErrorNumber.AccessDenied;
if(string.IsNullOrWhiteSpace(path) || if(node is not FatxDirNode mynode)
path == "/")
{
contents = _rootDirectory.Keys.ToList();
return ErrorNumber.NoError;
}
string cutPath = path.StartsWith('/') ? path[1..].ToLower(_cultureInfo) : path.ToLower(_cultureInfo);
if(_directoryCache.TryGetValue(cutPath, out Dictionary<string, DirectoryEntry> currentDirectory))
{
contents = currentDirectory.Keys.ToList();
return ErrorNumber.NoError;
}
string[] pieces = cutPath.Split(new[]
{
'/'
}, StringSplitOptions.RemoveEmptyEntries);
KeyValuePair<string, DirectoryEntry> entry =
_rootDirectory.FirstOrDefault(t => t.Key.ToLower(_cultureInfo) == pieces[0]);
if(string.IsNullOrEmpty(entry.Key))
return ErrorNumber.NoSuchFile;
if(!entry.Value.attributes.HasFlag(Attributes.Directory))
return ErrorNumber.NotDirectory;
string currentPath = pieces[0];
currentDirectory = _rootDirectory;
for(int p = 0; p < pieces.Length; p++)
{
entry = currentDirectory.FirstOrDefault(t => t.Key.ToLower(_cultureInfo) == pieces[p]);
if(string.IsNullOrEmpty(entry.Key))
return ErrorNumber.NoSuchFile;
if(!entry.Value.attributes.HasFlag(Attributes.Directory))
return ErrorNumber.NotDirectory;
currentPath = p == 0 ? pieces[0] : $"{currentPath}/{pieces[p]}";
uint currentCluster = entry.Value.firstCluster;
if(_directoryCache.TryGetValue(currentPath, out currentDirectory))
continue;
uint[] clusters = GetClusters(currentCluster);
if(clusters is null)
return ErrorNumber.InvalidArgument; return ErrorNumber.InvalidArgument;
byte[] directoryBuffer = new byte[_bytesPerCluster * clusters.Length]; if(mynode._position < 0)
return ErrorNumber.InvalidArgument;
for(int i = 0; i < clusters.Length; i++) if(mynode._position >= mynode._entries.Length)
{ return ErrorNumber.NoError;
ErrorNumber errno =
_imagePlugin.ReadSectors(_firstClusterSector + ((clusters[i] - 1) * _sectorsPerCluster),
_sectorsPerCluster, out byte[] buffer);
if(errno != ErrorNumber.NoError) filename = _encoding.GetString(mynode._entries[mynode._position].filename, 0,
return errno; mynode._entries[mynode._position].filenameSize);
Array.Copy(buffer, 0, directoryBuffer, i * _bytesPerCluster, _bytesPerCluster); mynode._position++;
}
currentDirectory = new Dictionary<string, DirectoryEntry>();
int pos = 0;
while(pos < directoryBuffer.Length)
{
DirectoryEntry dirent = _littleEndian
? Marshal.ByteArrayToStructureLittleEndian<DirectoryEntry>(directoryBuffer,
pos, Marshal.SizeOf<DirectoryEntry>())
: Marshal.ByteArrayToStructureBigEndian<DirectoryEntry>(directoryBuffer,
pos, Marshal.SizeOf<DirectoryEntry>());
pos += Marshal.SizeOf<DirectoryEntry>();
if(dirent.filenameSize is UNUSED_DIRENTRY or FINISHED_DIRENTRY)
break;
if(dirent.filenameSize is DELETED_DIRENTRY or > MAX_FILENAME)
continue;
string filename = _encoding.GetString(dirent.filename, 0, dirent.filenameSize);
currentDirectory.Add(filename, dirent);
}
_directoryCache.Add(currentPath, currentDirectory);
}
contents = currentDirectory?.Keys.ToList();
return ErrorNumber.NoError; return ErrorNumber.NoError;
} }

View File

@@ -276,11 +276,13 @@ public sealed partial class XboxFatPlugin
string parentPath = string.Join("/", pieces, 0, pieces.Length - 1); string parentPath = string.Join("/", pieces, 0, pieces.Length - 1);
ErrorNumber err = ReadDir(parentPath, out _); ErrorNumber err = OpenDir(parentPath, out IDirNode node);
if(err != ErrorNumber.NoError) if(err != ErrorNumber.NoError)
return err; return err;
CloseDir(node);
Dictionary<string, DirectoryEntry> parent; Dictionary<string, DirectoryEntry> parent;
if(pieces.Length == 1) if(pieces.Length == 1)

View File

@@ -150,89 +150,41 @@ public sealed partial class ISO9660
} }
/// <inheritdoc /> /// <inheritdoc />
public ErrorNumber ReadDir(string path, out List<string> contents) public ErrorNumber ReadDir(IDirNode node, out string filename)
{ {
contents = null; filename = null;
if(!_mounted) if(!_mounted)
return ErrorNumber.AccessDenied; return ErrorNumber.AccessDenied;
if(string.IsNullOrWhiteSpace(path) || if(node is not Iso9660DirNode mynode)
path == "/")
{
contents = GetFilenames(_rootDirectoryCache);
return ErrorNumber.NoError;
}
string cutPath = path.StartsWith("/", StringComparison.Ordinal)
? path[1..].ToLower(CultureInfo.CurrentUICulture)
: path.ToLower(CultureInfo.CurrentUICulture);
if(_directoryCache.TryGetValue(cutPath, out Dictionary<string, DecodedDirectoryEntry> currentDirectory))
{
contents = currentDirectory.Keys.ToList();
return ErrorNumber.NoError;
}
string[] pieces = cutPath.Split(new[]
{
'/'
}, StringSplitOptions.RemoveEmptyEntries);
KeyValuePair<string, DecodedDirectoryEntry> entry =
_rootDirectoryCache.FirstOrDefault(t => t.Key.ToLower(CultureInfo.CurrentUICulture) == pieces[0]);
if(string.IsNullOrEmpty(entry.Key))
return ErrorNumber.NoSuchFile;
if(!entry.Value.Flags.HasFlag(FileFlags.Directory))
return ErrorNumber.NotDirectory;
string currentPath = pieces[0];
currentDirectory = _rootDirectoryCache;
for(int p = 0; p < pieces.Length; p++)
{
entry = currentDirectory.FirstOrDefault(t => t.Key.ToLower(CultureInfo.CurrentUICulture) == pieces[p]);
if(string.IsNullOrEmpty(entry.Key))
return ErrorNumber.NoSuchFile;
if(!entry.Value.Flags.HasFlag(FileFlags.Directory))
return ErrorNumber.NotDirectory;
currentPath = p == 0 ? pieces[0] : $"{currentPath}/{pieces[p]}";
if(_directoryCache.TryGetValue(currentPath, out currentDirectory))
continue;
if(entry.Value.Extents.Count == 0)
return ErrorNumber.InvalidArgument; return ErrorNumber.InvalidArgument;
currentDirectory = _cdi if(mynode._position < 0)
? DecodeCdiDirectory(entry.Value.Extents[0].extent + entry.Value.XattrLength, return ErrorNumber.InvalidArgument;
entry.Value.Extents[0].size)
: _highSierra
? DecodeHighSierraDirectory(entry.Value.Extents[0].extent + entry.Value.XattrLength,
entry.Value.Extents[0].size)
: DecodeIsoDirectory(entry.Value.Extents[0].extent + entry.Value.XattrLength,
entry.Value.Extents[0].size);
if(_usePathTable) if(mynode._position >= mynode._entries.Length)
foreach(DecodedDirectoryEntry subDirectory in _cdi return ErrorNumber.NoError;
? GetSubdirsFromCdiPathTable(currentPath)
: _highSierra
? GetSubdirsFromHighSierraPathTable(currentPath)
: GetSubdirsFromIsoPathTable(currentPath))
currentDirectory[subDirectory.Filename] = subDirectory;
_directoryCache.Add(currentPath, currentDirectory); switch(_namespace)
{
case Namespace.Normal:
filename = mynode._entries[mynode._position].Filename.EndsWith(";1", StringComparison.Ordinal)
? mynode._entries[mynode._position].Filename[..^2]
: mynode._entries[mynode._position].Filename;
break;
case Namespace.Vms:
case Namespace.Joliet:
case Namespace.Rrip:
case Namespace.Romeo:
filename = mynode._entries[mynode._position].Filename;
break;
default: return ErrorNumber.InvalidArgument;
} }
contents = GetFilenames(currentDirectory); mynode._position++;
return ErrorNumber.NoError; return ErrorNumber.NoError;
} }
@@ -249,31 +201,6 @@ public sealed partial class ISO9660
return ErrorNumber.NoError; return ErrorNumber.NoError;
} }
List<string> GetFilenames(Dictionary<string, DecodedDirectoryEntry> dirents)
{
List<string> contents = new();
foreach(DecodedDirectoryEntry entry in dirents.Values)
switch(_namespace)
{
case Namespace.Normal:
contents.Add(entry.Filename.EndsWith(";1", StringComparison.Ordinal) ? entry.Filename[..^2]
: entry.Filename);
break;
case Namespace.Vms:
case Namespace.Joliet:
case Namespace.Rrip:
case Namespace.Romeo:
contents.Add(entry.Filename);
break;
default: throw new ArgumentOutOfRangeException();
}
return contents;
}
Dictionary<string, DecodedDirectoryEntry> DecodeCdiDirectory(ulong start, uint size) Dictionary<string, DecodedDirectoryEntry> DecodeCdiDirectory(ulong start, uint size)
{ {
Dictionary<string, DecodedDirectoryEntry> entries = new(); Dictionary<string, DecodedDirectoryEntry> entries = new();

View File

@@ -481,10 +481,12 @@ public sealed partial class ISO9660
if(!_directoryCache.TryGetValue(parentPath, out _)) if(!_directoryCache.TryGetValue(parentPath, out _))
{ {
ErrorNumber err = ReadDir(parentPath, out _); ErrorNumber err = OpenDir(parentPath, out IDirNode node);
if(err != ErrorNumber.NoError) if(err != ErrorNumber.NoError)
return err; return err;
CloseDir(node);
} }
Dictionary<string, DecodedDirectoryEntry> parent; Dictionary<string, DecodedDirectoryEntry> parent;

View File

@@ -96,37 +96,23 @@ public sealed partial class LisaFS
} }
/// <inheritdoc /> /// <inheritdoc />
public ErrorNumber ReadDir(string path, out List<string> contents) public ErrorNumber ReadDir(IDirNode node, out string filename)
{ {
contents = null; filename = null;
ErrorNumber error = LookupFileId(path, out short fileId, out bool isDir);
if(error != ErrorNumber.NoError) if(!_mounted)
return error; return ErrorNumber.AccessDenied;
if(!isDir) if(node is not LisaDirNode mynode)
return ErrorNumber.NotDirectory; return ErrorNumber.InvalidArgument;
/*List<CatalogEntry> catalog; if(mynode._position < 0)
error = ReadCatalog(fileId, out catalog); return ErrorNumber.InvalidArgument;
if(error != ErrorNumber.NoError)
return error;*/
ReadDir(fileId, out contents); if(mynode._position >= mynode._contents.Length)
return ErrorNumber.NoError;
// On debug add system files as readable files filename = mynode._contents[mynode._position++];
// Syntax similar to NTFS
if(_debug && fileId == DIRID_ROOT)
{
contents.Add("$MDDF");
contents.Add("$Boot");
contents.Add("$Loader");
contents.Add("$Bitmap");
contents.Add("$S-Record");
contents.Add("$");
}
contents.Sort();
return ErrorNumber.NoError; return ErrorNumber.NoError;
} }

View File

@@ -130,74 +130,23 @@ public sealed partial class OperaFS
} }
/// <inheritdoc /> /// <inheritdoc />
public ErrorNumber ReadDir(string path, out List<string> contents) public ErrorNumber ReadDir(IDirNode node, out string filename)
{ {
contents = null; filename = null;
if(!_mounted) if(!_mounted)
return ErrorNumber.AccessDenied; return ErrorNumber.AccessDenied;
if(string.IsNullOrWhiteSpace(path) || if(node is not OperaDirNode mynode)
path == "/")
{
contents = _rootDirectoryCache.Keys.ToList();
return ErrorNumber.NoError;
}
string cutPath = path.StartsWith("/", StringComparison.Ordinal)
? path[1..].ToLower(CultureInfo.CurrentUICulture)
: path.ToLower(CultureInfo.CurrentUICulture);
if(_directoryCache.TryGetValue(cutPath, out Dictionary<string, DirectoryEntryWithPointers> currentDirectory))
{
contents = currentDirectory.Keys.ToList();
return ErrorNumber.NoError;
}
string[] pieces = cutPath.Split(new[]
{
'/'
}, StringSplitOptions.RemoveEmptyEntries);
KeyValuePair<string, DirectoryEntryWithPointers> entry =
_rootDirectoryCache.FirstOrDefault(t => t.Key.ToLower(CultureInfo.CurrentUICulture) == pieces[0]);
if(string.IsNullOrEmpty(entry.Key))
return ErrorNumber.NoSuchFile;
if((entry.Value.Entry.flags & FLAGS_MASK) != (int)FileFlags.Directory)
return ErrorNumber.NotDirectory;
string currentPath = pieces[0];
currentDirectory = _rootDirectoryCache;
for(int p = 0; p < pieces.Length; p++)
{
entry = currentDirectory.FirstOrDefault(t => t.Key.ToLower(CultureInfo.CurrentUICulture) == pieces[p]);
if(string.IsNullOrEmpty(entry.Key))
return ErrorNumber.NoSuchFile;
if((entry.Value.Entry.flags & FLAGS_MASK) != (int)FileFlags.Directory)
return ErrorNumber.NotDirectory;
currentPath = p == 0 ? pieces[0] : $"{currentPath}/{pieces[p]}";
if(_directoryCache.TryGetValue(currentPath, out currentDirectory))
continue;
if(entry.Value.Pointers.Length < 1)
return ErrorNumber.InvalidArgument; return ErrorNumber.InvalidArgument;
currentDirectory = DecodeDirectory((int)entry.Value.Pointers[0]); if(mynode._position < 0)
return ErrorNumber.InvalidArgument;
_directoryCache.Add(currentPath, currentDirectory); if(mynode._position >= mynode._contents.Length)
} return ErrorNumber.NoError;
contents = currentDirectory?.Keys.ToList(); filename = mynode._contents[mynode._position++];
return ErrorNumber.NoError; return ErrorNumber.NoError;
} }

View File

@@ -212,10 +212,12 @@ public sealed partial class OperaFS
if(!_directoryCache.TryGetValue(parentPath, out _)) if(!_directoryCache.TryGetValue(parentPath, out _))
{ {
ErrorNumber err = ReadDir(parentPath, out _); ErrorNumber err = OpenDir(parentPath, out IDirNode node);
if(err != ErrorNumber.NoError) if(err != ErrorNumber.NoError)
return err; return err;
CloseDir(node);
} }
Dictionary<string, DirectoryEntryWithPointers> parent; Dictionary<string, DirectoryEntryWithPointers> parent;

View File

@@ -76,26 +76,23 @@ public sealed partial class PascalPlugin
} }
/// <inheritdoc /> /// <inheritdoc />
public ErrorNumber ReadDir(string path, out List<string> contents) public ErrorNumber ReadDir(IDirNode node, out string filename)
{ {
contents = null; filename = null;
if(!_mounted) if(!_mounted)
return ErrorNumber.AccessDenied; return ErrorNumber.AccessDenied;
if(!string.IsNullOrEmpty(path) && if(node is not PascalDirNode mynode)
string.Compare(path, "/", StringComparison.OrdinalIgnoreCase) != 0) return ErrorNumber.InvalidArgument;
return ErrorNumber.NotSupported;
contents = _fileEntries.Select(ent => StringHandlers.PascalToString(ent.Filename, _encoding)).ToList(); if(mynode._position < 0)
return ErrorNumber.InvalidArgument;
if(_debug) if(mynode._position >= mynode._contents.Length)
{ return ErrorNumber.NoError;
contents.Add("$");
contents.Add("$Boot");
}
contents.Sort(); filename = mynode._contents[mynode._position++];
return ErrorNumber.NoError; return ErrorNumber.NoError;
} }

View File

@@ -67,7 +67,7 @@ public sealed class SubdirectoryViewModel
_model = model; _model = model;
_view = view; _view = view;
ErrorNumber errno = model.Plugin.ReadDir(model.Path, out List<string> dirents); ErrorNumber errno = model.Plugin.OpenDir(model.Path, out IDirNode node);
if(errno != ErrorNumber.NoError) if(errno != ErrorNumber.NoError)
{ {
@@ -80,7 +80,8 @@ public sealed class SubdirectoryViewModel
return; return;
} }
foreach(string dirent in dirents) while(model.Plugin.ReadDir(node, out string dirent) == ErrorNumber.NoError &&
dirent is not null)
{ {
errno = model.Plugin.Stat(model.Path + "/" + dirent, out FileEntryInfo stat); errno = model.Plugin.Stat(model.Path + "/" + dirent, out FileEntryInfo stat);
@@ -112,6 +113,8 @@ public sealed class SubdirectoryViewModel
Stat = stat Stat = stat
}); });
} }
model.Plugin.CloseDir(node);
} }
public ObservableCollection<FileModel> Entries { get; } public ObservableCollection<FileModel> Entries { get; }

View File

@@ -267,12 +267,13 @@ public abstract class ReadOnlyFilesystemTest : FilesystemTest
path = ""; path = "";
Dictionary<string, FileData> children = new(); Dictionary<string, FileData> children = new();
fs.ReadDir(path, out List<string> contents); ErrorNumber ret = fs.OpenDir(path, out IDirNode node);
if(contents is null) if(ret != ErrorNumber.NoError)
return children; return children;
foreach(string child in contents) while(fs.ReadDir(node, out string child) == ErrorNumber.NoError &&
child is not null)
{ {
string childPath = $"{path}/{child}"; string childPath = $"{path}/{child}";
fs.Stat(childPath, out FileEntryInfo stat); fs.Stat(childPath, out FileEntryInfo stat);
@@ -303,6 +304,8 @@ public abstract class ReadOnlyFilesystemTest : FilesystemTest
children[child] = data; children[child] = data;
} }
fs.CloseDir(node);
return children; return children;
} }
@@ -351,7 +354,7 @@ public abstract class ReadOnlyFilesystemTest : FilesystemTest
{ {
currentDepth++; currentDepth++;
nextLevels = new List<NextLevel>(); nextLevels = new List<NextLevel>();
ErrorNumber ret = fs.ReadDir(path, out List<string> contents); ErrorNumber ret = fs.OpenDir(path, out IDirNode node);
// Directory is not readable, probably filled the volume, just ignore it // Directory is not readable, probably filled the volume, just ignore it
if(ret == ErrorNumber.InvalidArgument) if(ret == ErrorNumber.InvalidArgument)
@@ -364,6 +367,14 @@ public abstract class ReadOnlyFilesystemTest : FilesystemTest
if(ret != ErrorNumber.NoError) if(ret != ErrorNumber.NoError)
return; return;
List<string> contents = new();
while(fs.ReadDir(node, out string filename) == ErrorNumber.NoError &&
filename is not null)
contents.Add(filename);
fs.CloseDir(node);
if(children.Count == 0 && if(children.Count == 0 &&
contents.Count == 0) contents.Count == 0)
return; return;

View File

@@ -162,12 +162,13 @@ public abstract class FsExtractHashIssueTest
if(path.StartsWith('/')) if(path.StartsWith('/'))
path = path[1..]; path = path[1..];
ErrorNumber error = fs.ReadDir(path, out List<string> directory); ErrorNumber error = fs.OpenDir(path, out IDirNode node);
Assert.AreEqual(ErrorNumber.NoError, error, Assert.AreEqual(ErrorNumber.NoError, error,
string.Format(Localization.Error_0_reading_root_directory_0, error.ToString())); string.Format(Localization.Error_0_reading_root_directory_0, error.ToString()));
foreach(string entry in directory) while(fs.ReadDir(node, out string entry) == ErrorNumber.NoError &&
entry is not null)
{ {
error = fs.Stat(path + "/" + entry, out FileEntryInfo stat); error = fs.Stat(path + "/" + entry, out FileEntryInfo stat);
@@ -273,5 +274,7 @@ public abstract class FsExtractHashIssueTest
Assert.AreEqual(fileData.Md5, calculatedMd5, Assert.AreEqual(fileData.Md5, calculatedMd5,
string.Format(Localization.Invalid_checksum_for_file_0, path + "/" + entry)); string.Format(Localization.Invalid_checksum_for_file_0, path + "/" + entry));
} }
fs.CloseDir(node);
} }
} }

View File

@@ -129,12 +129,13 @@ public abstract class FsExtractIssueTest
if(path.StartsWith('/')) if(path.StartsWith('/'))
path = path[1..]; path = path[1..];
ErrorNumber error = fs.ReadDir(path, out List<string> directory); ErrorNumber error = fs.OpenDir(path, out IDirNode node);
Assert.AreEqual(ErrorNumber.NoError, error, Assert.AreEqual(ErrorNumber.NoError, error,
string.Format(Localization.Error_0_reading_root_directory_0, error.ToString())); string.Format(Localization.Error_0_reading_root_directory_0, error.ToString()));
foreach(string entry in directory) while(fs.ReadDir(node, out string entry) == ErrorNumber.NoError &&
entry is not null)
{ {
error = fs.Stat(path + "/" + entry, out FileEntryInfo stat); error = fs.Stat(path + "/" + entry, out FileEntryInfo stat);
@@ -183,5 +184,7 @@ public abstract class FsExtractIssueTest
string.Format(Localization.Error_0_reading_file_1, readBytes, stat.Length, string.Format(Localization.Error_0_reading_file_1, readBytes, stat.Length,
path + "/" + entry)); path + "/" + entry));
} }
fs.CloseDir(node);
} }
} }

View File

@@ -394,7 +394,7 @@ sealed class ExtractFilesCommand : Command
if(path.StartsWith('/')) if(path.StartsWith('/'))
path = path[1..]; path = path[1..];
ErrorNumber error = fs.ReadDir(path, out List<string> directory); ErrorNumber error = fs.OpenDir(path, out IDirNode node);
if(error != ErrorNumber.NoError) if(error != ErrorNumber.NoError)
{ {
@@ -403,7 +403,8 @@ sealed class ExtractFilesCommand : Command
return; return;
} }
foreach(string entry in directory) while(fs.ReadDir(node, out string entry) == ErrorNumber.NoError &&
entry is not null)
{ {
FileEntryInfo stat = new(); FileEntryInfo stat = new();
@@ -679,5 +680,7 @@ sealed class ExtractFilesCommand : Command
else else
AaruConsole.ErrorWriteLine(UI.Error_reading_file_0, Markup.Escape(entry)); AaruConsole.ErrorWriteLine(UI.Error_reading_file_0, Markup.Escape(entry));
} }
fs.CloseDir(node);
} }
} }

View File

@@ -354,7 +354,7 @@ sealed class LsCommand : Command
static void ListFilesInDir(string path, [NotNull] IReadOnlyFilesystem fs, bool longFormat) static void ListFilesInDir(string path, [NotNull] IReadOnlyFilesystem fs, bool longFormat)
{ {
ErrorNumber error = ErrorNumber.InvalidArgument; ErrorNumber error = ErrorNumber.InvalidArgument;
List<string> directory = new(); IDirNode node = null;
if(path.StartsWith('/')) if(path.StartsWith('/'))
path = path[1..]; path = path[1..];
@@ -365,7 +365,7 @@ sealed class LsCommand : Command
Core.Spectre.ProgressSingleSpinner(ctx => Core.Spectre.ProgressSingleSpinner(ctx =>
{ {
ctx.AddTask(UI.Reading_directory).IsIndeterminate(); ctx.AddTask(UI.Reading_directory).IsIndeterminate();
error = fs.ReadDir(path, out directory); error = fs.OpenDir(path, out node);
}); });
if(error != ErrorNumber.NoError) if(error != ErrorNumber.NoError)
@@ -377,19 +377,19 @@ sealed class LsCommand : Command
Dictionary<string, FileEntryInfo> stats = new(); Dictionary<string, FileEntryInfo> stats = new();
AnsiConsole.Progress().AutoClear(true).HideCompleted(true). Core.Spectre.ProgressSingleSpinner(ctx =>
Columns(new TaskDescriptionColumn(), new ProgressBarColumn(), new PercentageColumn()).Start(ctx =>
{ {
ProgressTask task = ctx.AddTask(UI.Retrieving_file_information); ctx.AddTask(UI.Retrieving_file_information).IsIndeterminate();
task.MaxValue = directory.Count;
foreach(string entry in directory) while(fs.ReadDir(node, out string entry) == ErrorNumber.NoError &&
entry is not null)
{ {
task.Increment(1);
fs.Stat(path + "/" + entry, out FileEntryInfo stat); fs.Stat(path + "/" + entry, out FileEntryInfo stat);
stats.Add(entry, stat); stats.Add(entry, stat);
} }
fs.CloseDir(node);
}); });
foreach(KeyValuePair<string, FileEntryInfo> entry in foreach(KeyValuePair<string, FileEntryInfo> entry in