From 02444a36017bc094d9f28fa71a782dabb320190d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Jul 2024 18:22:14 -0500 Subject: add ResolveFileInfo() --- src/slskd/Files/FileService.cs | 52 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) (limited to 'src/slskd/Files/FileService.cs') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index c5c0382f..ccd1f904 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -23,6 +23,7 @@ namespace slskd.Files using System.Collections.Generic; using System.IO; using System.Linq; + using System.Security; using System.Threading.Tasks; using OneOf; using Serilog; @@ -50,6 +51,57 @@ namespace slskd.Files private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } + /// + /// Resolves an instance of for the specified , following + /// any symlinks that may be present to their final target. + /// + /// The fully qualified filename for which to resolve the FileInfo instance. + /// The resolved FileInfo instance. + /// Thrown if the specified filename is null or contains only whitespace. + /// Thrown if the specified or linked file is restricted. + /// Thrown if the specified or linked file can't be accessed for some reason. + public virtual FileInfo ResolveFileInfo(string filename) + { + ArgumentException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); + + FileInfo info; + + try + { + info = new FileInfo(filename); + } + catch (Exception ex) when (ex is UnauthorizedAccessException || ex is SecurityException) + { + throw new UnauthorizedException($"Access to the file '{filename}' was denied: {ex.Message}", ex); + } + catch (Exception ex) + { + throw new IOException($"Failed to access file '{filename}': {ex.Message}", ex); + } + + // if the above didn't throw we are guaranteed a valid instance of FileInfo regardless of whether + // the file exists or if it is a symlink. if it doesn't exist it can't be a symlink, so just return it + if (!info.Exists) + { + return info; + } + + // LinkTarget is guaranteed to be null if the file isn't a symlink. docs: + // > Gets the target path of the link located in FullName, or null if this FileSystemInfo instance doesn't represent a link. + if (info.LinkTarget is null) + { + return info; + } + + // ResolveLinkTarget returns an instance of FileSystemInfo (which is being cast to FileInfo here) as long as + // the link itself exists (which we've checked), and regardless of whether the link target itself exists. + // we should only get this far if: + // 1) the given file exists and + // 2) it is a symlink, meaning + // this line _SHOULD_ be guaranteed to return an instance of FileInfo. + return (FileInfo)info.ResolveLinkTarget(returnFinalTarget: true); + } + /// /// Deletes the specified . /// -- cgit v1.2.3