1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
|
// <copyright file="ShareService.cs" company="JP Dillingham">
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ Copyright (c) JP Dillingham.
// │
// │ 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, version 3.
// │
// │ 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/.
// │
// │ This program is distributed with Additional Terms pursuant to Section 7
// │ of the AGPLv3. See the LICENSE file in the root directory of this
// │ project for the complete terms and conditions.
// │
// │ https://slskd.org
// │
// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
// │ SPDX-FileCopyrightText: JP Dillingham
// │ SPDX-License-Identifier: AGPL-3.0-only
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
// </copyright>
using Microsoft.Extensions.Options;
namespace slskd.Shares
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Serilog;
using slskd.Files;
using slskd.Relay;
using Soulseek;
/// <summary>
/// Provides control and interactions with configured shares and shared files.
/// </summary>
public class ShareService : IShareService
{
/// <summary>
/// Initializes a new instance of the <see cref="ShareService"/> class.
/// </summary>
/// <param name="fileService"></param>
/// <param name="shareRepositoryFactory"></param>
/// <param name="optionsMonitor"></param>
/// <param name="scanner"></param>
public ShareService(
FileService fileService,
IShareRepositoryFactory shareRepositoryFactory,
IOptionsMonitor<Options> optionsMonitor,
IShareScanner scanner = null)
{
var options = optionsMonitor.CurrentValue;
CacheStorageMode = options.Shares.Cache.StorageMode.ToEnum<StorageMode>();
ShareRepositoryFactory = shareRepositoryFactory;
var host = new Host(Program.LocalHostName);
var repository = ShareRepositoryFactory.CreateFromHost(host.Name);
Local = (host, repository);
AllRepositories = [repository];
Scanner = scanner ?? new ShareScanner(
workerCount: options.Shares.Cache.Workers,
fileService: fileService);
Scanner.StateMonitor.OnChange(cacheState =>
{
var (previous, current) = cacheState;
State.SetValue(state => state with
{
// scan is pending if faulted, or if state DIDN'T just transition from filling to not filling AND a scan was already pending
ScanPending = current.Faulted || current.Cancelled || (!(previous.Filling && !current.Filling) && state.ScanPending),
Scanning = current.Filling,
Faulted = current.Faulted,
Cancelled = current.Cancelled,
ScanProgress = current.FillProgress,
Directories = current.Directories,
Files = current.Files,
});
});
OptionsMonitor = optionsMonitor;
OptionsMonitor.OnChange(options => Configure(options));
StateMonitor = State;
Configure(OptionsMonitor.CurrentValue);
}
/// <summary>
/// Gets the list of share hosts.
/// </summary>
public IReadOnlyList<Host> Hosts => HostDictionary.Values.Select(v => v.Host).Prepend(Local.Host).ToList().AsReadOnly();
/// <summary>
/// Gets the local share host.
/// </summary>
public Host LocalHost => Local.Host;
/// <summary>
/// Gets the state monitor for the service.
/// </summary>
public IStateMonitor<ShareState> StateMonitor { get; }
private IShareRepositoryFactory ShareRepositoryFactory { get; }
private IShareScanner Scanner { get; }
private SemaphoreSlim ScannerSyncRoot { get; } = new SemaphoreSlim(1, 1);
private string LastOptionsHash { get; set; }
private IOptionsMonitor<Options> OptionsMonitor { get; }
private ConcurrentDictionary<string, (Host Host, IShareRepository Repository)> HostDictionary { get; set; } = new();
private IManagedState<ShareState> State { get; } = new ManagedState<ShareState>();
private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1);
private StorageMode CacheStorageMode { get; }
private ILogger Log { get; } = Serilog.Log.ForContext<ShareService>();
private (Host Host, IShareRepository Repository) Local { get; set; }
private IReadOnlyList<IShareRepository> AllRepositories { get; set; }
/// <summary>
/// Adds a new, or updates an existing, share host.
/// </summary>
/// <param name="host">The host to add or update.</param>
public void AddOrUpdateHost(Host host)
{
// we assume that if this method is called that the caller has verified that the
// file for the host exists and is valid.
HostDictionary.AddOrUpdate(
key: host.Name,
addValueFactory: (key) => (host, ShareRepositoryFactory.CreateFromHost(host.Name)),
updateValueFactory: (_, existing) => (host, existing.Repository));
AllRepositories = HostDictionary.Values
.Select(value => value.Repository)
.Prepend(Local.Repository)
.ToList()
.AsReadOnly();
State.SetValue(state => state with
{
Hosts = Hosts.Select(host => host.Name).ToArray(),
Directories = Hosts.SelectMany(host => host.Shares).Sum(share => share.Directories ?? 0),
Files = Hosts.SelectMany(host => host.Shares).Sum(share => share.Files ?? 0),
});
}
/// <summary>
/// Returns the entire contents of the share.
/// </summary>
/// <returns>The entire contents of the share.</returns>
public Task<IEnumerable<Directory>> BrowseAsync(Share share = null)
{
var directories = new ConcurrentDictionary<string, Directory>();
string prefix = null;
if (share != null)
{
prefix = share.RemotePath + (share.RemotePath.EndsWith('\\') ? string.Empty : '\\');
}
// snapshot the current list of repositories
var repositories = AllRepositories.ToList();
// Soulseek requires that each directory in the tree have an entry in the list returned in a browse response. if
// missing, files that are nested within directories which contain only directories (no files) are displayed as being
// 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 repositories.SelectMany(r => r.ListDirectories(prefix)))
{
directories.TryAdd(directory, new Directory(directory));
}
var files = repositories.SelectMany(r => r.ListFiles(
parentDirectory: prefix,
includeFullPath: true)); // includes the full *masked* filename; directory and file name and extension. not the local filename.
var groups = files
.GroupBy(file => file.Filename.GetNormalizedDirectoryName())
.Select(group => new Directory(group.Key, group.Select(f =>
{
return new File(
f.Code,
f.Filename.GetNormalizedFileName(), // we can send the full path, or just the filename. save bandwidth and omit the path.
f.Size,
f.Extension,
f.Attributes);
}).OrderBy(f => f.Filename)));
// merge the dictionary containing all directories with the Soulseek.Directory instances containing their files.
// entries with no files will remain untouched.
foreach (var group in groups)
{
directories.AddOrUpdate(group.Name, group, (_, _) => group);
}
var results = directories.Values.AsEnumerable();
return Task.FromResult(results);
}
/// <summary>
/// Dumps the local share cache to a file.
/// </summary>
/// <param name="filename">The destination file.</param>
/// <returns>The operation context.</returns>
public Task DumpAsync(string filename)
{
Local.Repository.DumpTo(filename);
return Task.CompletedTask;
}
/// <summary>
/// Returns the share host with the specified <paramref name="name"/>.
/// </summary>
/// <param name="name">The name of the host.</param>
/// <param name="host">The host, if found.</param>
/// <returns>A value indicating whether the host was found.</returns>
public bool TryGetHost(string name, out Host host)
{
if (HostDictionary.TryGetValue(name, out var record))
{
host = record.Host;
return true;
}
host = null;
return false;
}
/// <summary>
/// Removes the share host with the specified <paramref name="name"/>.
/// </summary>
/// <param name="name">The name of the host.</param>
/// <returns>A value indicating whether the host was removed.</returns>
public bool TryRemoveHost(string name)
{
var removed = false;
if (HostDictionary.TryRemove(name, out _))
{
removed = true;
}
AllRepositories = HostDictionary.Values
.Select(value => value.Repository)
.Prepend(Local.Repository)
.ToList()
.AsReadOnly();
State.SetValue(state => state with
{
Hosts = Hosts.Select(host => host.Name).ToArray(),
Directories = Hosts.SelectMany(host => host.Shares).Sum(share => share.Directories ?? 0),
Files = Hosts.SelectMany(host => host.Shares).Sum(share => share.Files ?? 0),
});
return removed;
}
/// <summary>
/// Returns the contents of the specified <paramref name="directory"/>.
/// </summary>
/// <param name="directory">The directory for which the contents are to be listed.</param>
/// <returns>The contents of the directory.</returns>
public Task<Directory> ListDirectoryAsync(string directory)
{
var files = AllRepositories.SelectMany(r => r.ListFiles(directory, includeFullPath: false));
return Task.FromResult(new Directory(directory, files));
}
/// <summary>
/// Resolves the local filename of the specified <paramref name="remoteFilename"/>, if the mask is associated with a
/// configured share.
/// </summary>
/// <param name="remoteFilename">The fully qualified filename to resolve.</param>
/// <returns>The resolved local filename.</returns>
/// <exception cref="NotFoundException">
/// Thrown when the specified remote filename can not be associated with a configured share.
/// </exception>
public Task<(string Host, string Filename, long Size)> ResolveFileAsync(string remoteFilename)
{
var (resolvedFilename, size) = Local.Repository.FindFileInfo(remoteFilename);
// when we're debugging the relay (running as both controller and agent on the same instance)
// always resolve files from remote hosts, ignoring local. this is a crappy hack, but it is the
// least crappy way to maintain sanity while trying to debug this feature.
if (OptionsMonitor.CurrentValue.Relay.Mode.ToEnum<RelayMode>() == RelayMode.Debug)
{
Log.Warning("Ignoring resolved local file to facilitate Relay debugging.");
}
else if (!string.IsNullOrEmpty(resolvedFilename))
{
Log.Debug("Resolved remote file to {ResolvedFilename} on local host", resolvedFilename);
return Task.FromResult((Program.LocalHostName, resolvedFilename, size));
}
else
{
Log.Debug("Failed to resolve remote file on local host; searching remote hosts: {Hosts}", HostDictionary.Values.Select(h => h.Host.Name));
}
// file not found locally. begin searching other hosts one by one.
// this is the slow, dumb way to do this, but it's plenty fast in this context.
foreach (var host in HostDictionary.Values)
{
(resolvedFilename, size) = host.Repository.FindFileInfo(remoteFilename);
if (!string.IsNullOrEmpty(resolvedFilename))
{
Log.Debug("Resolved remote file to {ResolvedFilename} on host {Host}", remoteFilename, host.Host.Name);
return Task.FromResult((host.Host.Name, resolvedFilename, size));
}
Log.Debug("Failed to resolve remote file on host {Host}", host.Host.Name);
}
throw new NotFoundException($"The requested filename '{remoteFilename}' could not be resolved to a physical file");
}
/// <summary>
/// Returns the list of all <see cref="Scan"/> started at or after the specified <paramref name="startedAtOrAfter"/>
/// unix timestamp.
/// </summary>
/// <remarks>
/// Note that this returns the scan history for local shares only.
/// </remarks>
/// <param name="startedAtOrAfter">A unix timestamp that serves as the lower bound of the time-based listing.</param>
/// <returns>The operation context, including the list of found scans.</returns>
public Task<IEnumerable<Scan>> ListScansAsync(long startedAtOrAfter = 0)
=> Task.FromResult(Local.Repository.ListScans(startedAtOrAfter));
/// <summary>
/// Requests that a share scan is performed.
/// </summary>
public void RequestScan()
{
Local.Repository.FlagLatestScanAsSuspect();
State.SetValue(state => state with { ScanPending = true });
}
/// <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>
/// <param name="limit">An optional row limit.</param>
/// <returns>The matching files.</returns>
public Task<IEnumerable<File>> SearchAsync(SearchQuery query, int? limit = null)
{
var results = AllRepositories.SelectMany(r => r.Search(query, limit));
return Task.FromResult(results);
}
/// <summary>
/// Scans the configured shares.
/// </summary>
/// <returns>The operation context.</returns>
/// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception>
public async Task ScanAsync()
{
// try to obtain the semaphore, or fail if it has already been obtained
// the scanner has an identical check, but because this method changes state we need it here, too
if (!await ScannerSyncRoot.WaitAsync(millisecondsTimeout: 0))
{
Log.Warning("Shared file scan rejected; scan is already in progress.");
throw new ShareScanInProgressException("Shared files are already being scanned.");
}
try
{
State.SetValue(state => state with { Ready = false });
await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares, Local.Repository);
Log.Debug("Backing up shared file cache database...");
Local.Repository.BackupTo(ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name));
Log.Debug("Shared file cache database backup complete");
Log.Debug("Recomputing share statistics...");
ComputeShareStatistics();
Log.Debug("Share statistics updated: {Shares}", Local.Host.Shares.ToJson());
State.SetValue(state => state with
{
Directories = Hosts.SelectMany(host => host.Shares).Sum(share => share.Directories ?? 0),
Files = Hosts.SelectMany(host => host.Shares).Sum(share => share.Files ?? 0),
Ready = true,
});
}
finally
{
ScannerSyncRoot.Release();
}
}
/// <summary>
/// Cancels the currently running scan, if one is running.
/// </summary>
/// <returns>A value indicating whether a scan was cancelled.</returns>
public bool TryCancelScan()
{
return Scanner.TryCancelScan();
}
/// <summary>
/// Initializes the service and shares.
/// </summary>
/// <param name="forceRescan">A value indicating whether a full re-scan of shares should be performed.</param>
/// <returns>The operation context.</returns>
public async Task InitializeAsync(bool forceRescan = false)
{
Log.Information("Initializing shares");
// _probably_ redundant, but to be safe
State.SetValue(state => state with { Ready = false });
try
{
if (forceRescan)
{
Log.Warning("Performing a forced re-scan of shares");
await ScanAsync();
}
else if (CacheStorageMode == StorageMode.Memory)
{
Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup...");
var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name);
if (backupRepository.TryValidate(out _))
{
Log.Information("Share cache backup validated. Attempting to restore...");
Local.Repository.RestoreFrom(backupRepository);
Log.Information("Share cache successfully restored from backup");
}
else
{
Log.Warning("Share cache backup is missing, corrupt, or is out of date");
throw new ShareInitializationException("Share cache backup is missing, corrupt, or is out of date");
}
}
else if (CacheStorageMode == StorageMode.Disk)
{
Log.Information("Share cache StorageMode is 'Disk'. Attempting to validate...");
if (Local.Repository.TryValidate(out _))
{
// no-op
}
else
{
Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup...");
var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name);
if (backupRepository.TryValidate(out _))
{
Log.Information("Share cache backup validated. Attempting to restore...");
Local.Repository.RestoreFrom(backupRepository);
Log.Information("Share cache successfully restored from backup");
}
else
{
Log.Warning("Share cache and backup are both missing, corrupt, or is out of date");
throw new ShareInitializationException("Share cache and backup are both missing, corrupt, or is out of date");
}
}
}
var options = OptionsMonitor.CurrentValue.Shares;
var latestScan = Local.Repository.FindLatestScan();
Log.Debug("Latest scan: {Scan}, current options {@Options}", latestScan, options);
if (latestScan == default)
{
throw new ShareInitializationException("Shares not yet scanned");
}
if (!latestScan.EndedAt.HasValue)
{
throw new ShareInitializationException("Previous share scan did not complete");
}
if (latestScan.Suspect)
{
throw new ShareInitializationException("Previous share scan was marked as suspect");
}
if (latestScan.OptionsJson != options.ToJson())
{
throw new ShareInitializationException("Share options changed since previous scan");
}
Local.Repository.EnableKeepalive(true);
Log.Debug("Recomputing share statistics...");
ComputeShareStatistics();
Log.Debug("Share statistics updated");
// one of several things happened above before we got here:
// this method was called with forceRescan = true
// the storage mode is memory, and we loaded the in-memory db from a valid backup
// the storage mode is disk, and the file is there and valid
// the storage mode is disk but either missing or invalid, and we restored from a valid backup
// we failed to load the cache from disk or backup, and performed a full scan successfully
// at this point there is a valid (existing, schema matching expected schema) database at the primary connection string
State.SetValue(state => state with
{
Scanning = false,
Faulted = false,
Ready = true,
ScanProgress = 1,
Hosts = Hosts.Select(host => host.Name).ToList().AsReadOnly(),
Directories = Hosts.SelectMany(host => host.Shares).Sum(share => share.Directories ?? 0),
Files = Hosts.SelectMany(host => host.Shares).Sum(share => share.Files ?? 0),
});
}
catch (Exception ex)
{
Log.Warning(ex, "Error initializing shares: {Message}", ex.Message);
if (!forceRescan)
{
Log.Warning("Re-attempting initialization");
await InitializeAsync(forceRescan: true);
}
else
{
Log.Error("Failed to initialize shares, and an attempt to force a full scan to repair failed");
throw;
}
}
}
private void ComputeShareStatistics()
{
foreach (var share in Local.Host.Shares)
{
var prefix = share.RemotePath + (share.RemotePath.EndsWith('\\') ? string.Empty : '\\');
var dirs = Local.Repository.CountDirectories(prefix);
var files = Local.Repository.CountFiles(prefix);
share.UpdateStatistics(dirs, files);
}
}
private void Configure(Options options)
{
SyncRoot.Wait();
try
{
var optionsHash = Compute.Sha1Hash(string.Join(';', options.Shares.Directories));
if (optionsHash == LastOptionsHash)
{
return;
}
var shares = options.Shares.Directories
.Select(share => share.TrimEnd('/', '\\'))
.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();
Local = (Local.Host with { Shares = shares }, Local.Repository);
LastOptionsHash = optionsHash;
}
finally
{
SyncRoot.Release();
}
}
}
}
|