aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/slskd/Application/Application.cs3
-rw-r--r--src/slskd/Application/ApplicationState.cs2
-rw-r--r--src/slskd/Application/ISharedFileCache.cs8
-rw-r--r--src/slskd/Application/SharedFileCache.cs95
-rw-r--r--src/slskd/Common/Compute.cs18
-rw-r--r--src/slskd/Common/Extensions.cs49
-rw-r--r--src/slskd/Properties/analysis.ruleset1
7 files changed, 139 insertions, 37 deletions
diff --git a/src/slskd/Application/Application.cs b/src/slskd/Application/Application.cs
index f1361b6e..7096867a 100644
--- a/src/slskd/Application/Application.cs
+++ b/src/slskd/Application/Application.cs
@@ -592,7 +592,8 @@ namespace slskd
private Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker)
{
_ = endpoint;
- var localFilename = filename.ToLocalOSPath();
+ var localFilename = SharedFileCache.Resolve(filename).ToLocalOSPath();
+
var fileInfo = new FileInfo(localFilename);
if (!fileInfo.Exists)
diff --git a/src/slskd/Application/ApplicationState.cs b/src/slskd/Application/ApplicationState.cs
index 58f086bb..9db79f5c 100644
--- a/src/slskd/Application/ApplicationState.cs
+++ b/src/slskd/Application/ApplicationState.cs
@@ -25,6 +25,6 @@ namespace slskd
public bool PendingReconnect { get; init; }
public bool PendingRestart { get; init; }
public bool PendingShareRescan { get; init; }
- public SharedFileCacheState SharedFileCache { get; init; }
+ public SharedFileCacheState SharedFileCache { get; init; } = new SharedFileCacheState();
}
} \ No newline at end of file
diff --git a/src/slskd/Application/ISharedFileCache.cs b/src/slskd/Application/ISharedFileCache.cs
index 291d78e4..4bc3f593 100644
--- a/src/slskd/Application/ISharedFileCache.cs
+++ b/src/slskd/Application/ISharedFileCache.cs
@@ -44,6 +44,14 @@ namespace slskd
Task FillAsync();
/// <summary>
+ /// Substitutes the mask in the specified <paramref name="filename"/> with the original path, if the mask is tracked
+ /// by the cache.
+ /// </summary>
+ /// <param name="filename">The fully qualified filename to unmask.</param>
+ /// <returns>The unmasked filename.</returns>
+ public string Resolve(string filename);
+
+ /// <summary>
/// Searches the cache for the specified <paramref name="query"/> and returns the matching files.
/// </summary>
/// <param name="query">The query for which to search.</param>
diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs
index 9a5770b6..ce1d796f 100644
--- a/src/slskd/Application/SharedFileCache.cs
+++ b/src/slskd/Application/SharedFileCache.cs
@@ -51,12 +51,14 @@ namespace slskd
/// </summary>
public IStateMonitor<SharedFileCacheState> State { get; } = new StateMonitor<SharedFileCacheState>();
- private HashSet<string> Directories { get; set; }
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 SqliteConnection SQLite { get; set; }
private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1);
+ private HashSet<string> UnmaskedDirectories { get; set; }
/// <summary>
/// Returns the contents of the cache.
@@ -71,7 +73,7 @@ namespace slskd
// in the root. to get around this, prime a dictionary with all known directories, and an empty Soulseek.Directory. if
// there are any files in the directory, this entry will be overwritten with a new Soulseek.Directory containing the
// files. if not they'll be left as is.
- foreach (var directory in Directories)
+ foreach (var directory in MaskedDirectories)
{
directories.TryAdd(directory, new Directory(directory));
}
@@ -117,42 +119,49 @@ namespace slskd
try
{
+ // todo: don't do this, but rather build a new cache and then swap it in
+ ResetCache();
+
State.SetValue(state => state with { Filling = true, FillProgress = 0 });
Log.Debug("Starting shared file scan");
var sw = new Stopwatch();
- sw.Start();
var swSnapshot = 0L;
+ sw.Start();
- // this destroys the old table and creates a new one. empty the other cached fields to reflect this
- // todo: use an A/B style table naming schema so that the cache remains available while it is filling
- CreateTable();
- Directories = new HashSet<string>();
- Files = new Dictionary<string, File>();
- State.SetValue(state => state with { Directories = 0, Files = 0 });
+ var shares = OptionsMonitor.CurrentValue.Directories.Shared.ToList(); // copy it so it can't change as we scan
+
+ 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());
Log.Debug("Enumerating shared directories");
swSnapshot = sw.ElapsedMilliseconds;
- var directories = OptionsMonitor.CurrentValue.Directories.Shared
+ var unmaskedDirectories = shares
.SelectMany(share => System.IO.Directory.GetDirectories(share, "*", SearchOption.AllDirectories))
+ .Concat(shares)
.ToHashSet();
- State.SetValue(state => state with { Directories = directories.Count });
-
- Log.Debug("Found {Directories} shared directories in {Elapsed}ms. Starting file scan.", sw.ElapsedMilliseconds - swSnapshot, directories.Count);
+ State.SetValue(state => state with { Directories = unmaskedDirectories.Count });
+ Log.Debug("Found {Directories} shared directories in {Elapsed}ms. Starting file scan.", sw.ElapsedMilliseconds - swSnapshot, unmaskedDirectories.Count);
swSnapshot = sw.ElapsedMilliseconds;
var files = new Dictionary<string, File>();
+ var maskedDirectories = new HashSet<string>();
var current = 0;
- foreach (var directory in directories)
+ foreach (var directory in unmaskedDirectories)
{
+ var mask = masks.First(m => directory.StartsWith(m.Value));
+
+ maskedDirectories.Add(directory.ReplaceFirst(mask.Value, mask.Key));
+
// 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("/", @"\"), new FileInfo(f).Length, Path.GetExtension(f)))
- .ToDictionary(f => f.Filename, f => f);
+ .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.
@@ -167,7 +176,7 @@ namespace slskd
}
current++;
- State.SetValue(state => state with { FillProgress = current / (double)directories.Count, Files = files.Count });
+ State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = files.Count });
}
Log.Debug("Directory scan found {Files} in {Elapsed}ms. Populating filename database", files.Count, sw.ElapsedMilliseconds - swSnapshot);
@@ -181,29 +190,17 @@ namespace slskd
Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot);
- Directories = directories;
+ UnmaskedDirectories = unmaskedDirectories;
+ MaskedDirectories = maskedDirectories;
+ Masks = masks;
Files = files;
- State.SetValue(state => state with
- {
- Filling = false,
- Faulted = false,
- FillProgress = 1,
- Directories = Directories.Count,
- Files = Files.Count,
- });
-
- Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {directories.Count}, Files: {files.Count}");
+ State.SetValue(state => state with { Filling = false, Faulted = false, FillProgress = 1, Directories = UnmaskedDirectories.Count, Files = Files.Count });
+ Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}");
}
catch (Exception ex)
{
- State.SetValue(state => state with
- {
- Filling = false,
- Faulted = true,
- FillProgress = 0,
- });
-
+ State.SetValue(state => state with { Filling = false, Faulted = true, FillProgress = 0 });
Log.Warning(ex, "Encountered error during scan of shared files: {Message}", ex.Message);
throw;
}
@@ -214,6 +211,24 @@ namespace slskd
}
/// <summary>
+ /// Substitutes the mask in the specified <paramref name="filename"/> with the original path, if the mask is tracked
+ /// by the cache.
+ /// </summary>
+ /// <param name="filename">The fully qualified filename to unmask.</param>
+ /// <returns>The unmasked filename.</returns>
+ public string Resolve(string filename)
+ {
+ var mask = filename.Split(new[] { '/', '\\' }).FirstOrDefault();
+
+ if (Masks.ContainsKey(mask))
+ {
+ return filename.ReplaceFirst(mask, Masks[mask]);
+ }
+
+ return filename;
+ }
+
+ /// <summary>
/// Searches the cache for the specified <paramref name="query"/> and returns the matching files.
/// </summary>
/// <param name="query">The query for which to search.</param>
@@ -269,5 +284,15 @@ namespace slskd
using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite);
cmd.ExecuteNonQuery();
}
+
+ private void ResetCache()
+ {
+ 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 });
+ }
}
} \ No newline at end of file
diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs
index 3d913d27..464a932d 100644
--- a/src/slskd/Common/Compute.cs
+++ b/src/slskd/Common/Compute.cs
@@ -20,6 +20,7 @@ namespace slskd
using System;
using System.Security.Cryptography;
using System.Text;
+ using System.Text.RegularExpressions;
/// <summary>
/// Computational functions.
@@ -43,5 +44,22 @@ namespace slskd
using var sha1 = new SHA1Managed();
return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty);
}
+
+ public static string MaskHash(string str)
+ {
+ var hash = Sha1Hash(str);
+ hash = Convert.ToBase64String(Encoding.UTF8.GetBytes(hash));
+ hash = Regex.Replace(hash, @"[\d=]", string.Empty).ToLowerInvariant();
+
+ // in some very unlucky circumstances, the sha1 might end up being all or mostly numbers.
+ // if this is the case the resulting hash could be fewer than the 5 characters we need,
+ // so copy it until we get to 5
+ while (hash.Length < 5)
+ {
+ hash += hash;
+ }
+
+ return $"@@{hash.Substring(0, 5)}";
+ }
}
} \ No newline at end of file
diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs
index 51c0d147..20620e44 100644
--- a/src/slskd/Common/Extensions.cs
+++ b/src/slskd/Common/Extensions.cs
@@ -69,6 +69,55 @@ namespace slskd
}
/// <summary>
+ /// Replaces the first occurance of <paramref name="phrase"/> in the string with <paramref name="replacement"/>.
+ /// </summary>
+ /// <param name="str">The string on which to perform the replacement.</param>
+ /// <param name="phrase">The phrase or substring to replace.</param>
+ /// <param name="replacement">The replacement string.</param>
+ /// <returns>The string, with the desired phrase replaced.</returns>
+ public static string ReplaceFirst(this string str, string phrase, string replacement)
+ {
+ int pos = str.IndexOf(phrase);
+
+ if (pos < 0)
+ {
+ return str;
+ }
+
+ return str.Substring(0, pos) + replacement + str.Substring(pos + phrase.Length);
+ }
+
+ /// <summary>
+ /// Computes a stable/consistent hash code for strings.
+ /// </summary>
+ /// <remarks>
+ /// https://stackoverflow.com/questions/5154970/how-do-i-create-a-hashcode-in-net-c-for-a-string-that-is-safe-to-store-in-a
+ /// </remarks>
+ /// <param name="str">The string for which the hash code is to be computed.</param>
+ /// <returns>The hash code.</returns>
+ public static int GetStableHashCode(this string str)
+ {
+ unchecked
+ {
+ int hash1 = 5381;
+ int hash2 = hash1;
+
+ for (int i = 0; i < str.Length && str[i] != '\0'; i += 2)
+ {
+ hash1 = ((hash1 << 5) + hash1) ^ str[i];
+ if (i == str.Length - 1 || str[i + 1] == '\0')
+ {
+ break;
+ }
+
+ hash2 = ((hash2 << 5) + hash2) ^ str[i + 1];
+ }
+
+ return hash1 + (hash2 * 1566083941);
+ }
+ }
+
+ /// <summary>
/// Deeply compares this object with the specified object and returns a list of properties that are different.
/// </summary>
/// <param name="left">The left side of the comparison.</param>
diff --git a/src/slskd/Properties/analysis.ruleset b/src/slskd/Properties/analysis.ruleset
index 4e4ae5cf..3e0f3586 100644
--- a/src/slskd/Properties/analysis.ruleset
+++ b/src/slskd/Properties/analysis.ruleset
@@ -37,6 +37,7 @@
<Rule Id="S2589" Action="None" />
<Rule Id="S3011" Action="None" />
<Rule Id="S3427" Action="Info" />
+ <Rule Id="S1643" Action="Info" />
</Rules>
<Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
<Rule Id="SA1008" Action="None" />