aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2021-08-17 07:41:54 -0500
committerGitHub <noreply@github.com>2021-08-17 07:41:54 -0500
commit6ac9eb746f3fd3eae32279d755511c2b22d3ddaa (patch)
treed7ca888a2a8529c1f33d2b5ba3e2284b014c1b5b /src
parent71ae35bd7088795157f218c7db0e70cb14e9c198 (diff)
parent2d24fb869e77ad817a21d72f238fbca80b564183 (diff)
downloadslskd-6ac9eb746f3fd3eae32279d755511c2b22d3ddaa.tar.gz
Merge pull request #152 from slskd/share-alias
Add share aliases
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application/Exceptions/ShareAliasException.cs72
-rw-r--r--src/slskd/Application/SharedFileCache.cs147
-rw-r--r--src/slskd/Options.cs57
-rw-r--r--src/slskd/Program.cs8
4 files changed, 242 insertions, 42 deletions
diff --git a/src/slskd/Application/Exceptions/ShareAliasException.cs b/src/slskd/Application/Exceptions/ShareAliasException.cs
new file mode 100644
index 00000000..3047d0a9
--- /dev/null
+++ b/src/slskd/Application/Exceptions/ShareAliasException.cs
@@ -0,0 +1,72 @@
+// <copyright file="ShareAliasException.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd
+{
+ using System;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Runtime.Serialization;
+
+ /// <summary>
+ /// Represents an error that occurs when multiple share scans are attempted concurrently.
+ /// </summary>
+ [ExcludeFromCodeCoverage]
+ [Serializable]
+ public class ShareAliasException : SlskdException
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ShareAliasException"/> class.
+ /// </summary>
+ public ShareAliasException()
+ : base()
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ShareAliasException"/> class with a specified error message.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ public ShareAliasException(string message)
+ : base(message)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ShareAliasException"/> class with a specified error message and a
+ /// reference to the inner exception that is the cause of this exception.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ /// <param name="innerException">
+ /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no
+ /// inner exception is specified.
+ /// </param>
+ public ShareAliasException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ShareAliasException"/> class with serialized data.
+ /// </summary>
+ /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param>
+ /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param>
+ protected ShareAliasException(SerializationInfo info, StreamingContext context)
+ : base(info, context)
+ {
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs
index 558cf46b..3f050086 100644
--- a/src/slskd/Application/SharedFileCache.cs
+++ b/src/slskd/Application/SharedFileCache.cs
@@ -25,6 +25,7 @@ namespace slskd
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
+ using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Sqlite;
@@ -54,8 +55,8 @@ namespace slskd
private Dictionary<string, File> Files { get; set; }
private ILogger Log { get; } = Serilog.Log.ForContext<SharedFileCache>();
private HashSet<string> MaskedDirectories { get; set; }
- private Dictionary<string, string> Masks { get; set; } = new Dictionary<string, string>();
private IOptionsMonitor<Options> OptionsMonitor { get; set; }
+ private List<Share> Shares { get; set; }
private SqliteConnection SQLite { get; set; }
private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1);
private HashSet<string> UnmaskedDirectories { get; set; }
@@ -98,7 +99,7 @@ namespace slskd
directories.AddOrUpdate(group.Name, group, (_, _) => group);
}
- return directories.Values;
+ return directories.Values.OrderBy(f => f.Name[8..]);
}
/// <summary>
@@ -129,24 +130,35 @@ namespace slskd
var swSnapshot = 0L;
sw.Start();
- var configuredShares = OptionsMonitor.CurrentValue.Directories.Shared.ToList(); // copy it so it can't change as we scan
- var shares = configuredShares.Where(s => !s.StartsWith('!') && !s.StartsWith('-'));
- var exclusions = configuredShares.Except(shares).Select(s => s[1..]);
-
- var masks = new Dictionary<string, string>(shares
- .Select(s => System.IO.Directory.GetParent(s).FullName)
- .Select(s => new KeyValuePair<string, string>(Compute.MaskHash(s), s)).ToHashSet());
+ Shares = OptionsMonitor.CurrentValue.Directories.Shared
+ .Select(share => Path.TrimEndingDirectorySeparator(share))
+ .ToHashSet() // remove duplicates
+ .Select(share => new Share(share)) // convert to Shares
+ .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent
+ .ToList();
Log.Debug("Enumerating shared directories");
swSnapshot = sw.ElapsedMilliseconds;
- var unmaskedDirectories = shares
- .SelectMany(share => System.IO.Directory.GetDirectories(share, "*", SearchOption.AllDirectories))
- .Concat(shares)
- .ToHashSet();
+ var unmaskedDirectories = Shares
+ .SelectMany(share =>
+ {
+ try
+ {
+ return System.IO.Directory.GetDirectories(share.LocalPath, "*", SearchOption.AllDirectories);
+ }
+ catch (Exception ex)
+ {
+ Log.Warning("Failed to scan share {Directory}: {Message}", share.LocalPath, ex.Message);
+ return Array.Empty<string>();
+ }
+ })
+ .Concat(Shares.Select(share => share.LocalPath)) // include the shares themselves (GetDirectories returns only subdirectories)
+ .Where(share => System.IO.Directory.Exists(share)) // discard any directories that don't exist. we already warned about them.
+ .ToHashSet(); // remove duplicates (in case shares overlap)
var excludedDirectories = unmaskedDirectories
- .Where(share => exclusions.Any(exclusions => share.StartsWith(exclusions)));
+ .Where(share => Shares.Where(share => share.IsExcluded).Any(exclusion => share.StartsWith(exclusion.LocalPath)));
unmaskedDirectories = unmaskedDirectories.Except(excludedDirectories).ToHashSet();
@@ -160,27 +172,35 @@ namespace slskd
foreach (var directory in unmaskedDirectories)
{
- var mask = masks.First(m => directory.StartsWith(m.Value));
+ var share = Shares.First(share => directory.StartsWith(share.LocalPath));
- maskedDirectories.Add(directory.ReplaceFirst(mask.Value, mask.Key));
+ maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath));
// recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized
// filename and with a value of a Soulseek.File object
- var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly)
- .Select(f => new File(1, f.Replace("/", @"\").ReplaceFirst(mask.Value, mask.Key), new FileInfo(f).Length, Path.GetExtension(f)))
- .ToDictionary(f => f.Filename.ReplaceFirst(mask.Value, mask.Key), f => f);
-
- // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully
- // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another.
- foreach (var file in newFiles)
+ try
{
- if (files.ContainsKey(file.Key))
+ var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly)
+ .Select(f => new File(1, f.Replace("/", @"\").ReplaceFirst(share.LocalPath, share.RemotePath), new FileInfo(f).Length, Path.GetExtension(f)))
+ .ToDictionary(f => f.Filename, f => f);
+
+ // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully
+ // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another.
+ foreach (var file in newFiles)
{
- Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?).");
- }
+ if (files.ContainsKey(file.Key))
+ {
+ Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?).");
+ }
- files[file.Key] = file.Value;
+ files[file.Key] = file.Value;
+ }
}
+ catch (Exception ex)
+ {
+ Log.Warning("Failed to scan files in directory {Directory}: {Message}", directory, ex.Message);
+ }
+
current++;
State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = files.Count });
@@ -199,7 +219,6 @@ namespace slskd
UnmaskedDirectories = unmaskedDirectories;
MaskedDirectories = maskedDirectories;
- Masks = masks;
Files = files;
State.SetValue(state => state with { Filling = false, Faulted = false, FillProgress = 1, Directories = UnmaskedDirectories.Count, Files = Files.Count });
@@ -225,14 +244,26 @@ namespace slskd
/// <returns>The unmasked filename.</returns>
public string Resolve(string filename)
{
- var mask = filename.Split(new[] { '/', '\\' }).FirstOrDefault();
+ var resolved = filename;
+
+ // a well-formed path will consist of a mask, either an alias or a local directory, and a fully qualified path to a
+ // file. split the requested filename so we can examine the first two segments
+ var parts = filename.Split(new[] { '/', '\\' });
+
+ if (parts.Length < 2)
+ {
+ return resolved;
+ }
+
+ // find the share with a matching mask and alias/local directory
+ var share = Shares.FirstOrDefault(share => share.Mask == parts[0] && share.Alias == parts[1]);
- if (Masks.ContainsKey(mask))
+ if (share == default)
{
- return filename.ReplaceFirst(mask, Masks[mask]);
+ return resolved;
}
- return filename;
+ return resolved.ReplaceFirst(share.RemotePath, share.LocalPath);
}
/// <summary>
@@ -297,9 +328,59 @@ namespace slskd
CreateTable();
UnmaskedDirectories = new HashSet<string>();
MaskedDirectories = new HashSet<string>();
- Masks = new Dictionary<string, string>();
Files = new Dictionary<string, File>();
State.SetValue(state => state with { Directories = 0, Files = 0 });
}
+
+ private class Share
+ {
+ public Share(string share)
+ {
+ Raw = share;
+ IsExcluded = share.StartsWith('-') || share.StartsWith('!');
+
+ if (IsExcluded)
+ {
+ share = share[1..];
+ }
+
+ // test to see whether an alias has been specified
+ var matches = Regex.Matches(share, @"^\[(.*)\](.*)$");
+
+ if (matches.Any())
+ {
+ // split the alias from the path, and validate the alias
+ var groups = matches[0].Groups;
+ Alias = groups[1].Value;
+ LocalPath = groups[2].Value;
+ }
+ else
+ {
+ Alias = new Uri(share).Segments.Last();
+ LocalPath = share;
+ }
+
+ Mask = Compute.MaskHash(System.IO.Directory.GetParent(LocalPath).FullName);
+
+ var maskedPath = LocalPath.ReplaceFirst(System.IO.Directory.GetParent(LocalPath).FullName, Mask);
+
+ if (!string.IsNullOrEmpty(Alias))
+ {
+ var aliasedSegment = LocalPath[(System.IO.Directory.GetParent(LocalPath).FullName.Length + 1)..];
+ RemotePath = maskedPath.ReplaceFirst(aliasedSegment, Alias);
+ }
+ else
+ {
+ RemotePath = LocalPath.ReplaceFirst(System.IO.Directory.GetParent(LocalPath).FullName, Mask);
+ }
+ }
+
+ public string Alias { get; init; }
+ public bool IsExcluded { get; init; }
+ public string LocalPath { get; init; }
+ public string Mask { get; init; }
+ public string Raw { get; init; }
+ public string RemotePath { get; init; }
+ }
}
} \ No newline at end of file
diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs
index bf83e74f..cd2dadd2 100644
--- a/src/slskd/Options.cs
+++ b/src/slskd/Options.cs
@@ -24,6 +24,9 @@ namespace slskd
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
+ using System.IO;
+ using System.Linq;
+ using System.Text.RegularExpressions;
using FluentFTP;
using slskd.Configuration;
using slskd.Validation;
@@ -219,7 +222,7 @@ namespace slskd
/// <summary>
/// Directory options.
/// </summary>
- public class DirectoriesOptions
+ public class DirectoriesOptions : IValidatableObject
{
/// <summary>
/// Gets the path where application data is saved.
@@ -258,6 +261,58 @@ namespace slskd
[EnvironmentVariable("SHARED_DIR")]
[Description("path to shared files")]
public string[] Shared { get; private set; } = new[] { Program.DefaultSharedDirectory };
+
+ /// <summary>
+ /// Extended validation.
+ /// </summary>
+ /// <param name="validationContext"></param>
+ /// <returns></returns>
+ public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
+ {
+ var results = new List<ValidationResult>();
+
+ (string Raw, string Mask, string Alias, string Path) Digest(string share)
+ {
+ var matches = Regex.Matches(share, @"^(-?)\[(.*)\](.*)$");
+
+ if (matches.Any())
+ {
+ return (share, Compute.MaskHash(Directory.GetParent(matches[0].Groups[3].Value).FullName), matches[0].Groups[2].Value, matches[0].Groups[3].Value);
+ }
+
+ return (share, Compute.MaskHash(Directory.GetParent(share).FullName), new Uri(share).Segments.Last(), share);
+ }
+
+ var digestedShared = Shared
+ .Select(share => Digest(Path.TrimEndingDirectorySeparator(share)))
+ .ToHashSet();
+
+ var overlapping = digestedShared.GroupBy(share => share.Mask + share.Alias).Where(group => group.Count() > 1);
+ foreach (var overlap in overlapping)
+ {
+ results.Add(new ValidationResult($"Shares {string.Join(", ", overlap.Select(s => $"'{s.Raw}'"))} overlap"));
+ }
+
+ var duplicates = digestedShared.GroupBy(share => share.Path).Where(group => group.Count() > 1);
+ foreach (var dupe in duplicates)
+ {
+ results.Add(new ValidationResult($"Shares {string.Join(", ", dupe.Select(s => $"'{s.Raw}'"))} alias the same path"));
+ }
+
+ foreach (var share in digestedShared.Where(s => s.Alias != null))
+ {
+ if (string.IsNullOrWhiteSpace(share.Alias))
+ {
+ results.Add(new ValidationResult($"Share '{share.Raw}' is invalid; alias may not be null, empty or consist of only whitespace"));
+ }
+ else if (share.Alias.Contains('\\') || share.Alias.Contains('/'))
+ {
+ results.Add(new ValidationResult($"Share '{share.Raw}' is invalid; aliases may not contain path separators '/' or '\\'"));
+ }
+ }
+
+ return results;
+ }
}
/// <summary>
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index fa1be786..b92a4a10 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -241,14 +241,6 @@ namespace slskd
VerifyDirectory(OptionsAtStartup.Directories.App, createIfMissing: true, verifyWriteable: true);
VerifyDirectory(OptionsAtStartup.Directories.Incomplete, createIfMissing: true, verifyWriteable: true);
VerifyDirectory(OptionsAtStartup.Directories.Downloads, createIfMissing: true, verifyWriteable: true);
-
- foreach (var share in OptionsAtStartup.Directories.Shared)
- {
- if (!VerifyDirectory(share, createIfMissing: false, verifyWriteable: false))
- {
- logger.Warning("Shared directory {Directory} does not exist", share);
- }
- }
}
catch (Exception ex)
{