From 58a7558dd8f6a38ab7835e6f56178d54411084a1 Mon Sep 17 00:00:00 2001 From: Matt Nadareski Date: Sat, 4 Jan 2025 23:30:45 -0500 Subject: [PATCH] Make GetFileType safer --- SabreTools.FileTypes/FileTypeTool.cs | 43 ++++++++++++++++------------ 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/SabreTools.FileTypes/FileTypeTool.cs b/SabreTools.FileTypes/FileTypeTool.cs index 62447caa..8195f44b 100644 --- a/SabreTools.FileTypes/FileTypeTool.cs +++ b/SabreTools.FileTypes/FileTypeTool.cs @@ -254,62 +254,67 @@ namespace SabreTools.FileTypes /// FileType of inputted file (null on error) public static FileType? GetFileType(string input) { - FileType? outFileType = null; - // If the file is null, then we have no archive type - if (input == null) - return outFileType; + if (string.IsNullOrEmpty(input)) + return null; // First line of defense is going to be the extension, for better or worse if (!HasValidArchiveExtension(input)) - return outFileType; + return null; // Read the first bytes of the file and get the magic number - BinaryReader br = new(File.OpenRead(input)); - byte[] magic = br.ReadBytes(8); -#if NET40_OR_GREATER - br.Dispose(); -#endif + byte[] magic; + try + { + using Stream stream = File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + magic = stream.ReadBytes(8); + } + catch + { + // Exceptions are currently not logged + // TODO: Log exceptions + return null; + } // Now try to match it to a known signature if (magic.StartsWith(SevenZipSignature)) { - outFileType = FileType.SevenZipArchive; + return FileType.SevenZipArchive; } else if (magic.StartsWith(AaruFormatSignature)) { - outFileType = FileType.AaruFormat; + return FileType.AaruFormat; } else if (magic.StartsWith(CHDSignature)) { - outFileType = FileType.CHD; + return FileType.CHD; } else if (magic.StartsWith(GzSignature)) { - outFileType = FileType.GZipArchive; + return FileType.GZipArchive; } else if (magic.StartsWith(RarSignature) || magic.StartsWith(RarFiveSignature)) { - outFileType = FileType.RarArchive; + return FileType.RarArchive; } else if (magic.StartsWith(TarSignature) || magic.StartsWith(TarZeroSignature)) { - outFileType = FileType.TapeArchive; + return FileType.TapeArchive; } else if (magic.StartsWith(XZSignature)) { - outFileType = FileType.XZArchive; + return FileType.XZArchive; } else if (magic.StartsWith(Models.PKZIP.Constants.LocalFileHeaderSignatureBytes) || magic.StartsWith(Models.PKZIP.Constants.EndOfCentralDirectoryRecordSignatureBytes) || magic.StartsWith(Models.PKZIP.Constants.DataDescriptorSignatureBytes)) { - outFileType = FileType.ZipArchive; + return FileType.ZipArchive; } - return outFileType; + return null; } ///