Smb save servers, auth
This commit is contained in:
@@ -5,9 +5,10 @@
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Core\FileTime.Core\FileTime.Core.csproj"/>
|
||||
<ProjectReference Include="..\..\Core\FileTime.Core\FileTime.Core.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="SMBLibrary" Version="1.4.8"/>
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" />
|
||||
<PackageReference Include="SMBLibrary" Version="1.4.8" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,133 @@
|
||||
using System.Text.Json;
|
||||
using FileTime.Core.Persistence;
|
||||
using System.Security.Cryptography;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace FileTime.Providers.Smb.Persistence
|
||||
{
|
||||
public class PersistenceService
|
||||
{
|
||||
private const string smbFolderName = "smb";
|
||||
private const string serverFileName = "servers.json";
|
||||
private readonly PersistenceSettings _persistenceSettings;
|
||||
private readonly JsonSerializerOptions _jsonOptions;
|
||||
private static readonly byte[] _encryptionKey = {
|
||||
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
|
||||
0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16
|
||||
};
|
||||
private readonly ILogger<PersistenceService> _logger;
|
||||
|
||||
public PersistenceService(PersistenceSettings persistenceSettings, ILogger<PersistenceService> logger)
|
||||
{
|
||||
_persistenceSettings = persistenceSettings;
|
||||
_logger = logger;
|
||||
|
||||
_jsonOptions = new JsonSerializerOptions()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
WriteIndented = true
|
||||
};
|
||||
}
|
||||
public async Task SaveServers(IEnumerable<Smb.SmbServer> servers)
|
||||
{
|
||||
ServersPersistenceRoot root;
|
||||
string? encodedIV = null;
|
||||
|
||||
using (Aes aes = Aes.Create())
|
||||
{
|
||||
aes.Key = _encryptionKey;
|
||||
|
||||
encodedIV = Convert.ToBase64String(aes.IV);
|
||||
|
||||
root = new ServersPersistenceRoot()
|
||||
{
|
||||
Key = encodedIV,
|
||||
Servers = servers.Select(s => SaveServer(s, aes)).ToList()
|
||||
};
|
||||
}
|
||||
|
||||
var smbDirectory = new DirectoryInfo(Path.Combine(_persistenceSettings.RootAppDataPath, smbFolderName));
|
||||
if (!smbDirectory.Exists) smbDirectory.Create();
|
||||
|
||||
var serversPath = Path.Combine(_persistenceSettings.RootAppDataPath, smbFolderName, serverFileName);
|
||||
|
||||
using var stream = File.Create(serversPath);
|
||||
await JsonSerializer.SerializeAsync(stream, root, _jsonOptions);
|
||||
}
|
||||
|
||||
public async Task<List<SmbServer>> LoadServers()
|
||||
{
|
||||
var serverFilePath = Path.Combine(_persistenceSettings.RootAppDataPath, smbFolderName, serverFileName);
|
||||
var servers = new List<SmbServer>();
|
||||
|
||||
if (!new FileInfo(serverFilePath).Exists) return servers;
|
||||
|
||||
using var stream = File.OpenRead(serverFilePath);
|
||||
var serversRoot = await JsonSerializer.DeserializeAsync<ServersPersistenceRoot>(stream);
|
||||
|
||||
if (serversRoot == null) return servers;
|
||||
|
||||
if (!string.IsNullOrEmpty(serversRoot.Key))
|
||||
{
|
||||
var iv = Convert.FromBase64String(serversRoot.Key);
|
||||
|
||||
using Aes aes = Aes.Create();
|
||||
foreach (var server in serversRoot.Servers)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(server.Password)) continue;
|
||||
|
||||
using var memoryStream = new MemoryStream();
|
||||
memoryStream.Write(Convert.FromBase64String(server.Password));
|
||||
memoryStream.Position = 0;
|
||||
|
||||
using CryptoStream cryptoStream = new(
|
||||
memoryStream,
|
||||
aes.CreateDecryptor(_encryptionKey, iv),
|
||||
CryptoStreamMode.Read);
|
||||
using StreamReader decryptReader = new(cryptoStream);
|
||||
server.Password = await decryptReader.ReadToEndAsync();
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
_logger.LogError(e, "Unkown error while decrypting password for {0}", server.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
servers.AddRange(serversRoot.Servers);
|
||||
|
||||
return servers;
|
||||
}
|
||||
|
||||
private static SmbServer SaveServer(Smb.SmbServer server, Aes aes)
|
||||
{
|
||||
var encryptedPassword = "";
|
||||
using (var memoryStream = new MemoryStream())
|
||||
{
|
||||
using CryptoStream cryptoStream = new(
|
||||
memoryStream,
|
||||
aes.CreateEncryptor(),
|
||||
CryptoStreamMode.Write);
|
||||
using StreamWriter encryptWriter = new(cryptoStream);
|
||||
{
|
||||
encryptWriter.Write(server.Password);
|
||||
encryptWriter.Flush();
|
||||
cryptoStream.FlushFinalBlock();
|
||||
}
|
||||
|
||||
var a = memoryStream.ToArray();
|
||||
encryptedPassword = Convert.ToBase64String(a);
|
||||
}
|
||||
|
||||
return new SmbServer()
|
||||
{
|
||||
Path = server.Name,
|
||||
Name = server.Name,
|
||||
UserName = server.Username,
|
||||
Password = encryptedPassword
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace FileTime.Providers.Smb.Persistence
|
||||
{
|
||||
public class ServersPersistenceRoot
|
||||
{
|
||||
public string Key { get; set; }
|
||||
public List<SmbServer> Servers { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace FileTime.Providers.Smb.Persistence
|
||||
{
|
||||
public class SmbServer
|
||||
{
|
||||
public string Path { get; set; }
|
||||
public string Name { get; set; }
|
||||
public string? UserName { get; set; }
|
||||
public string? Password { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ namespace FileTime.Providers.Smb
|
||||
private readonly Func<Task<ISMBClient>> _getSmbClient;
|
||||
private readonly Action _disposeClient;
|
||||
private bool _isRunning;
|
||||
private readonly object _lock = new object();
|
||||
private readonly object _lock = new();
|
||||
|
||||
public SmbClientContext(Func<Task<ISMBClient>> getSmbClient, Action disposeClient)
|
||||
{
|
||||
|
||||
@@ -3,17 +3,23 @@ using AsyncEvent;
|
||||
using FileTime.Core.Interactions;
|
||||
using FileTime.Core.Models;
|
||||
using FileTime.Core.Providers;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace FileTime.Providers.Smb
|
||||
{
|
||||
public class SmbContentProvider : IContentProvider
|
||||
{
|
||||
private readonly object _initializationGuard = new object();
|
||||
private bool _initialized;
|
||||
private bool _initializing;
|
||||
private IContainer? _parent;
|
||||
private readonly IInputInterface _inputInterface;
|
||||
private readonly List<IContainer> _rootContainers;
|
||||
private readonly IReadOnlyList<IContainer> _rootContainersReadOnly;
|
||||
private IReadOnlyList<IItem>? _items;
|
||||
private readonly IReadOnlyList<IElement>? _elements = new List<IElement>().AsReadOnly();
|
||||
private IReadOnlyList<IItem> _items;
|
||||
private readonly IReadOnlyList<IElement> _elements = new List<IElement>().AsReadOnly();
|
||||
private readonly Persistence.PersistenceService _persistenceService;
|
||||
private readonly ILogger<SmbContentProvider> _logger;
|
||||
|
||||
public string Name { get; } = "smb";
|
||||
|
||||
@@ -33,12 +39,14 @@ namespace FileTime.Providers.Smb
|
||||
|
||||
public bool IsDestroyed => false;
|
||||
|
||||
public SmbContentProvider(IInputInterface inputInterface)
|
||||
public SmbContentProvider(IInputInterface inputInterface, Persistence.PersistenceService persistenceService, ILogger<SmbContentProvider> logger)
|
||||
{
|
||||
_rootContainers = new List<IContainer>();
|
||||
_items = new List<IItem>();
|
||||
_rootContainersReadOnly = _rootContainers.AsReadOnly();
|
||||
_inputInterface = inputInterface;
|
||||
_persistenceService = persistenceService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<IContainer> CreateContainer(string name)
|
||||
@@ -55,6 +63,8 @@ namespace FileTime.Providers.Smb
|
||||
|
||||
await RefreshAsync();
|
||||
|
||||
await SaveServers();
|
||||
|
||||
return container;
|
||||
}
|
||||
|
||||
@@ -74,7 +84,7 @@ namespace FileTime.Providers.Smb
|
||||
|
||||
var pathParts = path.TrimStart(Constants.SeparatorChar).Split(Constants.SeparatorChar);
|
||||
|
||||
var rootContainer = _rootContainers.Find(c => c.Name == pathParts[0]);
|
||||
var rootContainer = (await GetContainers())?.FirstOrDefault(c => c.Name == pathParts[0]);
|
||||
|
||||
if (rootContainer == null)
|
||||
{
|
||||
@@ -98,9 +108,19 @@ namespace FileTime.Providers.Smb
|
||||
public void SetParent(IContainer container) => _parent = container;
|
||||
public Task<IReadOnlyList<IContainer>> GetRootContainers(CancellationToken token = default) => Task.FromResult(_rootContainersReadOnly);
|
||||
|
||||
public Task<IReadOnlyList<IItem>?> GetItems(CancellationToken token = default) => Task.FromResult(_items);
|
||||
public Task<IReadOnlyList<IContainer>?> GetContainers(CancellationToken token = default) => Task.FromResult((IReadOnlyList<IContainer>?)_rootContainersReadOnly);
|
||||
public Task<IReadOnlyList<IElement>?> GetElements(CancellationToken token = default) => Task.FromResult(_elements);
|
||||
public async Task<IReadOnlyList<IItem>?> GetItems(CancellationToken token = default)
|
||||
{
|
||||
await Init();
|
||||
return _items;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<IContainer>?> GetContainers(CancellationToken token = default)
|
||||
{
|
||||
await Init();
|
||||
return _rootContainersReadOnly;
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<IElement>?> GetElements(CancellationToken token = default) => Task.FromResult((IReadOnlyList<IElement>?)_elements);
|
||||
|
||||
public Task Rename(string newName) => throw new NotSupportedException();
|
||||
public Task<bool> CanOpen() => Task.FromResult(true);
|
||||
@@ -108,5 +128,54 @@ namespace FileTime.Providers.Smb
|
||||
public void Destroy() { }
|
||||
|
||||
public void Unload() { }
|
||||
|
||||
public async Task SaveServers()
|
||||
{
|
||||
try
|
||||
{
|
||||
await _persistenceService.SaveServers(_rootContainers.OfType<SmbServer>());
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogError(e, "Unkown error while saving smb server states.");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task Init()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
lock (_initializationGuard)
|
||||
{
|
||||
if (!_initializing)
|
||||
{
|
||||
_initializing = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
await Task.Delay(1);
|
||||
}
|
||||
try
|
||||
{
|
||||
if (_initialized) return;
|
||||
if (_items.Count > 0) return;
|
||||
_initialized = true;
|
||||
|
||||
var servers = await _persistenceService.LoadServers();
|
||||
foreach (var server in servers)
|
||||
{
|
||||
var smbServer = new SmbServer(server.Path, this, _inputInterface, server.UserName, server.Password);
|
||||
_rootContainers.Add(smbServer);
|
||||
}
|
||||
_items = _rootContainers.OrderBy(c => c.Name).ToList().AsReadOnly();
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_initializationGuard)
|
||||
{
|
||||
_initializing = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,25 +55,6 @@ namespace FileTime.Providers.Smb
|
||||
|
||||
public Task<IContainer> Clone() => Task.FromResult((IContainer)this);
|
||||
|
||||
public async Task<IItem?> GetByPath(string path, bool acceptDeepestMatch = false)
|
||||
{
|
||||
var paths = path.Split(Constants.SeparatorChar);
|
||||
|
||||
var item = (await GetItems())?.FirstOrDefault(i => i.Name == paths[0]);
|
||||
|
||||
if (paths.Length == 1)
|
||||
{
|
||||
return item;
|
||||
}
|
||||
|
||||
if (item is IContainer container)
|
||||
{
|
||||
return await container.GetByPath(string.Join(Constants.SeparatorChar, paths.Skip(1)), acceptDeepestMatch);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public IContainer? GetParent() => _parent;
|
||||
|
||||
public Task<bool> IsExists(string name)
|
||||
|
||||
@@ -10,17 +10,18 @@ namespace FileTime.Providers.Smb
|
||||
{
|
||||
public class SmbServer : IContainer
|
||||
{
|
||||
private string? _username;
|
||||
private string? _password;
|
||||
private bool _reenterCredentials;
|
||||
|
||||
private IReadOnlyList<IContainer>? _shares;
|
||||
private IReadOnlyList<IItem>? _items;
|
||||
private readonly IReadOnlyList<IElement>? _elements = new List<IElement>().AsReadOnly();
|
||||
private ISMBClient? _client;
|
||||
private readonly object _clientGuard = new object();
|
||||
private readonly object _clientGuard = new();
|
||||
private bool _refreshingClient;
|
||||
private readonly IInputInterface _inputInterface;
|
||||
private readonly SmbClientContext _smbClientContext;
|
||||
public string? Username { get; private set; }
|
||||
public string? Password { get; private set; }
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
@@ -42,10 +43,12 @@ namespace FileTime.Providers.Smb
|
||||
|
||||
public bool IsDestroyed => false;
|
||||
|
||||
public SmbServer(string path, SmbContentProvider contentProvider, IInputInterface inputInterface)
|
||||
public SmbServer(string path, SmbContentProvider contentProvider, IInputInterface inputInterface, string? username = null, string? password = null)
|
||||
{
|
||||
_inputInterface = inputInterface;
|
||||
_smbClientContext = new SmbClientContext(GetSmbClient, DisposeSmbClient);
|
||||
Username = username;
|
||||
Password = password;
|
||||
|
||||
Provider = contentProvider;
|
||||
FullName = Name = path;
|
||||
@@ -53,12 +56,12 @@ namespace FileTime.Providers.Smb
|
||||
|
||||
public async Task<IReadOnlyList<IItem>?> GetItems(CancellationToken token = default)
|
||||
{
|
||||
if (_shares == null) await RefreshAsync();
|
||||
if (_shares == null) await RefreshAsync(token);
|
||||
return _shares;
|
||||
}
|
||||
public async Task<IReadOnlyList<IContainer>?> GetContainers(CancellationToken token = default)
|
||||
{
|
||||
if (_shares == null) await RefreshAsync();
|
||||
if (_shares == null) await RefreshAsync(token);
|
||||
return _shares;
|
||||
}
|
||||
public Task<IReadOnlyList<IElement>?> GetElements(CancellationToken token = default)
|
||||
@@ -81,9 +84,24 @@ namespace FileTime.Providers.Smb
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<IItem?> GetByPath(string path, bool acceptDeepestMatch = false)
|
||||
public async Task<IItem?> GetByPath(string path, bool acceptDeepestMatch = false)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
var paths = path.Split(Constants.SeparatorChar);
|
||||
|
||||
var item = (await GetItems())!.FirstOrDefault(i => i.Name == paths[0]);
|
||||
|
||||
if (paths.Length == 1)
|
||||
{
|
||||
return item;
|
||||
}
|
||||
|
||||
if (item is IContainer container)
|
||||
{
|
||||
var result = await container.GetByPath(string.Join(Constants.SeparatorChar, paths.Skip(1)), acceptDeepestMatch);
|
||||
return result == null && acceptDeepestMatch ? this : result;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public IContainer? GetParent() => Provider;
|
||||
@@ -152,30 +170,32 @@ namespace FileTime.Providers.Smb
|
||||
|
||||
if (connected)
|
||||
{
|
||||
if (_username == null && _password == null)
|
||||
if (_reenterCredentials || Username == null || Password == null)
|
||||
{
|
||||
var inputs = await _inputInterface.ReadInputs(
|
||||
new InputElement[]
|
||||
{
|
||||
new InputElement($"Username for '{Name}'", InputType.Text),
|
||||
new InputElement($"Password for '{Name}'", InputType.Password)
|
||||
new InputElement($"Username for '{Name}'", InputType.Text, Username ?? ""),
|
||||
new InputElement($"Password for '{Name}'", InputType.Password, Password ?? "")
|
||||
});
|
||||
|
||||
_username = inputs[0];
|
||||
_password = inputs[1];
|
||||
Username = inputs[0];
|
||||
Password = inputs[1];
|
||||
}
|
||||
|
||||
if (client.Login(string.Empty, _username, _password) != NTStatus.STATUS_SUCCESS)
|
||||
if (client.Login(string.Empty, Username, Password) != NTStatus.STATUS_SUCCESS)
|
||||
{
|
||||
_username = null;
|
||||
_password = null;
|
||||
_reenterCredentials = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
_reenterCredentials = false;
|
||||
lock (_clientGuard)
|
||||
{
|
||||
_client = client;
|
||||
}
|
||||
|
||||
await Provider.SaveServers();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ namespace FileTime.Providers.Smb
|
||||
private IReadOnlyList<IItem>? _items;
|
||||
private IReadOnlyList<IContainer>? _containers;
|
||||
private IReadOnlyList<IElement>? _elements;
|
||||
private SmbClientContext _smbClientContext;
|
||||
private readonly SmbClientContext _smbClientContext;
|
||||
private readonly IContainer? _parent;
|
||||
|
||||
public string Name { get; }
|
||||
@@ -45,17 +45,17 @@ namespace FileTime.Providers.Smb
|
||||
|
||||
public async Task<IReadOnlyList<IItem>?> GetItems(CancellationToken token = default)
|
||||
{
|
||||
if (_items == null) await RefreshAsync();
|
||||
if (_items == null) await RefreshAsync(token);
|
||||
return _items;
|
||||
}
|
||||
public async Task<IReadOnlyList<IContainer>?> GetContainers(CancellationToken token = default)
|
||||
{
|
||||
if (_containers == null) await RefreshAsync();
|
||||
if (_containers == null) await RefreshAsync(token);
|
||||
return _containers;
|
||||
}
|
||||
public async Task<IReadOnlyList<IElement>?> GetElements(CancellationToken token = default)
|
||||
{
|
||||
if (_elements == null) await RefreshAsync();
|
||||
if (_elements == null) await RefreshAsync(token);
|
||||
return _elements;
|
||||
}
|
||||
|
||||
@@ -74,25 +74,6 @@ namespace FileTime.Providers.Smb
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<IItem?> GetByPath(string path, bool acceptDeepestMatch = false)
|
||||
{
|
||||
var paths = path.Split(Constants.SeparatorChar);
|
||||
|
||||
var item = (await GetItems())?.FirstOrDefault(i => i.Name == paths[0]);
|
||||
|
||||
if (paths.Length == 1)
|
||||
{
|
||||
return item;
|
||||
}
|
||||
|
||||
if (item is IContainer container)
|
||||
{
|
||||
return await container.GetByPath(string.Join(Constants.SeparatorChar, paths.Skip(1)), acceptDeepestMatch);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public IContainer? GetParent() => _parent;
|
||||
|
||||
public Task<IContainer> Clone() => Task.FromResult((IContainer)this);
|
||||
|
||||
14
src/Providers/FileTime.Providers.Smb/Startup.cs
Normal file
14
src/Providers/FileTime.Providers.Smb/Startup.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
using FileTime.Providers.Smb.Persistence;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace FileTime.Providers.Smb
|
||||
{
|
||||
public static class Startup
|
||||
{
|
||||
public static IServiceCollection AddSmbServices(this IServiceCollection serviceCollection)
|
||||
{
|
||||
return serviceCollection
|
||||
.AddSingleton<PersistenceService>();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user