From 7d40ac22de820019a3c6f4722ea8c139018308f2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Aug 2021 09:23:45 -0500 Subject: add MaskHash --- src/slskd/Common/Compute.cs | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs index 3d913d27..60a2eeaf 100644 --- a/src/slskd/Common/Compute.cs +++ b/src/slskd/Common/Compute.cs @@ -43,5 +43,13 @@ 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 hashCode = str.GetStableHashCode(); + var bytes = BitConverter.GetBytes(hashCode); + var base64 = Convert.ToBase64String(bytes); + return $"@@{base64.ToLowerInvariant().Replace("=", string.Empty)}"; + } } } \ No newline at end of file -- cgit v1.2.3 From ebe5af7084001012630a2e030247cf2c23e5a67d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Aug 2021 09:35:30 -0500 Subject: add ReplaceFirst() and GetStableHashCode() --- src/slskd/Common/Extensions.cs | 49 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index 51c0d147..0da0e128 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -68,6 +68,55 @@ namespace slskd return props; } + /// + /// Replaces the first occurance of in the string with . + /// + /// The string on which to perform the replacement. + /// The phrase or substring to replace. + /// The replacement string. + /// The string, with the desired phrase replaced. + 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); + } + + /// + /// Computes a stable/consistent hash code for strings. + /// + /// + /// https://stackoverflow.com/questions/5154970/how-do-i-create-a-hashcode-in-net-c-for-a-string-that-is-safe-to-store-in-a + /// + /// The string for which the hash code is to be computed. + /// The hash code + 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); + } + } + /// /// Deeply compares this object with the specified object and returns a list of properties that are different. /// -- cgit v1.2.3 From 39a1483ce5bef53c6e6d613c4251203d3531fae9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Aug 2021 09:35:48 -0500 Subject: add missing . --- src/slskd/Common/Extensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index 0da0e128..20620e44 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -94,7 +94,7 @@ namespace slskd /// https://stackoverflow.com/questions/5154970/how-do-i-create-a-hashcode-in-net-c-for-a-string-that-is-safe-to-store-in-a /// /// The string for which the hash code is to be computed. - /// The hash code + /// The hash code. public static int GetStableHashCode(this string str) { unchecked -- cgit v1.2.3 From f9be54cfc4ccb30f7f4601b91580ea01e48c9075 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Aug 2021 09:52:39 -0500 Subject: implement share masking --- src/slskd/Application/ISharedFileCache.cs | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'src') 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 @@ -43,6 +43,14 @@ namespace slskd /// The operation context. Task FillAsync(); + /// + /// Substitutes the mask in the specified with the original path, if the mask is tracked + /// by the cache. + /// + /// The fully qualified filename to unmask. + /// The unmasked filename. + public string Resolve(string filename); + /// /// Searches the cache for the specified and returns the matching files. /// -- cgit v1.2.3 From c8cda28935846068bcfdf37c86f3a13c5170e61d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Aug 2021 10:01:08 -0500 Subject: implement masking --- src/slskd/Application/Application.cs | 5 +- src/slskd/Application/SharedFileCache.cs | 93 ++++++++++++++++++++------------ 2 files changed, 63 insertions(+), 35 deletions(-) (limited to 'src') diff --git a/src/slskd/Application/Application.cs b/src/slskd/Application/Application.cs index f1361b6e..407b70a1 100644 --- a/src/slskd/Application/Application.cs +++ b/src/slskd/Application/Application.cs @@ -21,6 +21,7 @@ namespace slskd using System.Collections.Concurrent; using System.IO; using System.Linq; + //using System.Linq; using System.Net; using System.Reflection; using System.Threading; @@ -592,7 +593,9 @@ namespace slskd private Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) { _ = endpoint; - var localFilename = filename.ToLocalOSPath(); + var localFilename = SharedFileCache.Resolve(filename).ToLocalOSPath(); + Console.WriteLine($"Local: {localFilename}"); + var fileInfo = new FileInfo(localFilename); if (!fileInfo.Exists) diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index 9a5770b6..761941f2 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -51,12 +51,14 @@ namespace slskd /// public IStateMonitor State { get; } = new StateMonitor(); - private HashSet Directories { get; set; } private Dictionary Files { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext(); + private HashSet MaskedDirectories { get; set; } + private Dictionary Masks { get; set; } = new Dictionary(); private IOptionsMonitor OptionsMonitor { get; set; } private SqliteConnection SQLite { get; set; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); + private HashSet UnmaskedDirectories { get; set; } /// /// 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,37 +119,44 @@ 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(); - Files = new Dictionary(); - 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(shares + .Select(s => System.IO.Directory.GetParent(s).FullName) + .Select(s => new KeyValuePair(Compute.MaskHash(s), s))); 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(); + var maskedDirectories = new HashSet(); 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) @@ -163,11 +172,11 @@ namespace slskd 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.ReplaceFirst(mask.Value, mask.Key)] = file.Value; } 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; } @@ -213,6 +210,24 @@ namespace slskd } } + /// + /// Substitutes the mask in the specified with the original path, if the mask is tracked + /// by the cache. + /// + /// The fully qualified filename to unmask. + /// The unmasked filename. + public string Resolve(string filename) + { + var mask = filename.Split(new[] { '/', '\\' }).FirstOrDefault(); + + if (Masks.ContainsKey(mask)) + { + return filename.ReplaceFirst(mask, Masks[mask]); + } + + return filename; + } + /// /// Searches the cache for the specified and returns the matching files. /// @@ -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(); + MaskedDirectories = new HashSet(); + Masks = new Dictionary(); + Files = new Dictionary(); + State.SetValue(state => state with { Directories = 0, Files = 0 }); + } } } \ No newline at end of file -- cgit v1.2.3 From f6b3a8f9e15ce8d1cd16ef611d9c4806bd5e778d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Aug 2021 10:01:44 -0500 Subject: remove log --- src/slskd/Application/Application.cs | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application/Application.cs b/src/slskd/Application/Application.cs index 407b70a1..732c9c4a 100644 --- a/src/slskd/Application/Application.cs +++ b/src/slskd/Application/Application.cs @@ -594,7 +594,6 @@ namespace slskd { _ = endpoint; var localFilename = SharedFileCache.Resolve(filename).ToLocalOSPath(); - Console.WriteLine($"Local: {localFilename}"); var fileInfo = new FileInfo(localFilename); -- cgit v1.2.3 From 4ea48efb812b2c820755a3b31130612851113d20 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Aug 2021 10:02:52 -0500 Subject: remove commented out using --- src/slskd/Application/Application.cs | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application/Application.cs b/src/slskd/Application/Application.cs index 732c9c4a..7096867a 100644 --- a/src/slskd/Application/Application.cs +++ b/src/slskd/Application/Application.cs @@ -21,7 +21,6 @@ namespace slskd using System.Collections.Concurrent; using System.IO; using System.Linq; - //using System.Linq; using System.Net; using System.Reflection; using System.Threading; -- cgit v1.2.3 From b8053991348e73501494af0faa37222f4d98253f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Aug 2021 10:15:56 -0500 Subject: mask filenames in File objects also --- src/slskd/Application/SharedFileCache.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index 761941f2..f52f298a 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -160,7 +160,7 @@ namespace slskd // 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))) + .Select(f => new File(1, f.Replace("/", @"\").ReplaceFirst(mask.Value, mask.Key), 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 -- cgit v1.2.3 From f6b798d3f53b630f0d5a4b2dd8e5f0c154bbe4b0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Aug 2021 10:31:09 -0500 Subject: mask filenames as we convert to a dictionary --- src/slskd/Application/SharedFileCache.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index f52f298a..b03d3019 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -161,7 +161,7 @@ namespace slskd // 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, f => 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. @@ -172,7 +172,7 @@ namespace slskd 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.ReplaceFirst(mask.Value, mask.Key)] = file.Value; + files[file.Key] = file.Value; } current++; -- cgit v1.2.3 From 181fcf9d3cae59f25ad5413661a7eb86831b0c1a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Aug 2021 10:11:00 -0500 Subject: initialize cache state --- src/slskd/Application/ApplicationState.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') 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 -- cgit v1.2.3 From 9dbd757fc474df7d34a163b6f42ea4973a07b608 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Aug 2021 10:11:13 -0500 Subject: deduplicate share hashes --- src/slskd/Application/SharedFileCache.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index b03d3019..ce1d796f 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -133,7 +133,7 @@ namespace slskd var masks = new Dictionary(shares .Select(s => System.IO.Directory.GetParent(s).FullName) - .Select(s => new KeyValuePair(Compute.MaskHash(s), s))); + .Select(s => new KeyValuePair(Compute.MaskHash(s), s)).ToHashSet()); Log.Debug("Enumerating shared directories"); swSnapshot = sw.ElapsedMilliseconds; -- cgit v1.2.3 From dc802fcc5c89761197f6d6ef9a9a6e6a25b13910 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Aug 2021 10:11:37 -0500 Subject: compute soulseek-compliant hashes --- src/slskd/Common/Compute.cs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs index 60a2eeaf..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; /// /// Computational functions. @@ -46,10 +47,19 @@ namespace slskd public static string MaskHash(string str) { - var hashCode = str.GetStableHashCode(); - var bytes = BitConverter.GetBytes(hashCode); - var base64 = Convert.ToBase64String(bytes); - return $"@@{base64.ToLowerInvariant().Replace("=", string.Empty)}"; + 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 -- cgit v1.2.3 From d45ce99daf66967ab6ad8daf4d37be73a5626a54 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Aug 2021 10:11:48 -0500 Subject: hide stringbuilder warning --- src/slskd/Properties/analysis.ruleset | 1 + 1 file changed, 1 insertion(+) (limited to 'src') 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 @@ + -- cgit v1.2.3