Admin mode WIP

This commit is contained in:
2023-07-26 10:24:22 +02:00
parent ba1210b2c4
commit 0c49071a3b
46 changed files with 695 additions and 55 deletions

View File

@@ -0,0 +1,6 @@
namespace FileTime.Providers.Local;
public static class LocalContentProviderConstants
{
public const string ContentProviderId = "local";
}

View File

@@ -21,6 +21,7 @@
<ProjectReference Include="..\..\Core\FileTime.Core.Models\FileTime.Core.Models.csproj" />
<ProjectReference Include="..\..\Core\FileTime.Core.Services\FileTime.Core.Services.csproj" />
<ProjectReference Include="..\FileTime.Providers.Local.Abstractions\FileTime.Providers.Local.Abstractions.csproj" />
<ProjectReference Include="..\FileTime.Providers.LocalAdmin.Abstractions\FileTime.Providers.LocalAdmin.Abstractions.csproj" />
</ItemGroup>
</Project>

View File

@@ -14,7 +14,7 @@ public sealed partial class LocalContentProvider : ContentProviderBase, ILocalCo
private readonly ITimelessContentProvider _timelessContentProvider;
private readonly bool _isCaseInsensitive;
public LocalContentProvider(ITimelessContentProvider timelessContentProvider) : base("local")
public LocalContentProvider(ITimelessContentProvider timelessContentProvider) : base(LocalContentProviderConstants.ContentProviderId)
{
_timelessContentProvider = timelessContentProvider;
_isCaseInsensitive = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

View File

@@ -6,7 +6,7 @@ public class LocalContentWriter : IContentWriter
{
private readonly FileStream _writerStream;
private readonly BinaryWriter _binaryWriter;
private bool disposed;
private bool _disposed;
public int PreferredBufferSize => 1024 * 1024;
public LocalContentWriter(FileStream writerStream)
@@ -47,7 +47,7 @@ public class LocalContentWriter : IContentWriter
private void Dispose(bool disposing)
{
if (!disposed)
if (!_disposed)
{
if (disposing)
{
@@ -55,6 +55,6 @@ public class LocalContentWriter : IContentWriter
_binaryWriter.Dispose();
}
}
disposed = true;
_disposed = true;
}
}

View File

@@ -6,5 +6,7 @@ namespace FileTime.Providers.Local;
public class LocalContentWriterFactory : IContentWriterFactory<ILocalContentProvider>
{
public Task<IContentWriter> CreateContentWriterAsync(IElement element)
=> Task.FromResult((IContentWriter)new LocalContentWriter(File.OpenWrite(element.NativePath!.Path)));
{
return Task.FromResult((IContentWriter) new LocalContentWriter(File.OpenWrite(element.NativePath!.Path)));
}
}

View File

@@ -1,23 +1,57 @@
using FileTime.Core.ContentAccess;
using FileTime.Core.Models;
using FileTime.Providers.LocalAdmin;
namespace FileTime.Providers.Local;
public class LocalItemCreator : ItemCreatorBase<ILocalContentProvider>
{
public override Task CreateContainerAsync(ILocalContentProvider contentProvider, FullName fullName)
private readonly IAdminContentAccessorFactory _adminContentAccessorFactory;
private readonly IAdminContentProvider _adminContentProvider;
public LocalItemCreator(
IAdminContentAccessorFactory adminContentAccessorFactory,
IAdminContentProvider adminContentProvider)
{
_adminContentAccessorFactory = adminContentAccessorFactory;
_adminContentProvider = adminContentProvider;
}
public override async Task CreateContainerAsync(ILocalContentProvider contentProvider, FullName fullName)
{
var path = contentProvider.GetNativePath(fullName).Path;
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
if (Directory.Exists(path)) return;
return Task.CompletedTask;
try
{
Directory.CreateDirectory(path);
}
catch (UnauthorizedAccessException)
{
if (!_adminContentAccessorFactory.IsAdminModeSupported) throw;
var adminContentAccessor = await _adminContentAccessorFactory.CreateAdminItemCreatorAsync();
await adminContentAccessor.CreateContainerAsync(_adminContentProvider, fullName);
}
}
public override async Task CreateElementAsync(ILocalContentProvider contentProvider, FullName fullName)
{
var path = contentProvider.GetNativePath(fullName).Path;
await using (File.Create(path))
if (File.Exists(path)) return;
try
{
await using (File.Create(path))
{
}
}
catch (UnauthorizedAccessException)
{
if (!_adminContentAccessorFactory.IsAdminModeSupported) throw;
var adminContentAccessor = await _adminContentAccessorFactory.CreateAdminItemCreatorAsync();
await adminContentAccessor.CreateElementAsync(_adminContentProvider, fullName);
}
}
}

View File

@@ -6,7 +6,7 @@ namespace FileTime.Providers.Local;
public static class Startup
{
public static IServiceCollection AddLocalServices(this IServiceCollection serviceCollection)
public static IServiceCollection AddLocalProviderServices(this IServiceCollection serviceCollection)
{
serviceCollection.TryAddSingleton<ILocalContentProvider, LocalContentProvider>();
serviceCollection.TryAddSingleton<IContentProvider>(sp => sp.GetRequiredService<ILocalContentProvider>());

View File

@@ -0,0 +1,9 @@
namespace FileTime.Providers.LocalAdmin;
public class AdminElevationConfiguration
{
public const string SectionName = "AdminElevation";
public string ServerExecutablePath { get; set; }
public int? ServerPort { get; set; }
public bool? StartProcess { get; set; }
}

View File

@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>FileTime.Providers.LocalAdmin</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Core\FileTime.Core.Abstraction\FileTime.Core.Abstraction.csproj" />
<ProjectReference Include="..\FileTime.Providers.Remote.Abstractions\FileTime.Providers.Remote.Abstractions.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,9 @@
using FileTime.Providers.Remote;
namespace FileTime.Providers.LocalAdmin;
public interface IAdminContentAccessorFactory
{
bool IsAdminModeSupported { get; }
Task<IRemoteItemCreator> CreateAdminItemCreatorAsync();
}

View File

@@ -0,0 +1,8 @@
using FileTime.Core.ContentAccess;
namespace FileTime.Providers.LocalAdmin;
public interface IAdminContentProvider : IContentProvider
{
}

View File

@@ -0,0 +1,12 @@
using FileTime.Server.Common;
namespace FileTime.Providers.LocalAdmin;
public interface IAdminElevationManager
{
bool IsAdminModeSupported { get; }
bool IsAdminInstanceRunning { get; }
Task<IRemoteConnection> CreateConnectionAsync();
string ProviderName { get; }
Task CreateAdminInstanceIfNecessaryAsync(string? confirmationMessage = null);
}

View File

@@ -0,0 +1,36 @@
using System.Diagnostics;
using FileTime.Providers.Remote;
using InitableService;
namespace FileTime.Providers.LocalAdmin;
public class AdminContentAccessorFactory : IAdminContentAccessorFactory
{
private readonly IAdminElevationManager _adminElevationManager;
private readonly IServiceProvider _serviceProvider;
public AdminContentAccessorFactory(
IAdminElevationManager adminElevationManager,
IServiceProvider serviceProvider
)
{
_adminElevationManager = adminElevationManager;
_serviceProvider = serviceProvider;
}
public bool IsAdminModeSupported => _adminElevationManager.IsAdminModeSupported;
public async Task<IRemoteItemCreator> CreateAdminItemCreatorAsync()
{
await _adminElevationManager.CreateAdminInstanceIfNecessaryAsync();
var connection = await _adminElevationManager.CreateConnectionAsync();
Debug.Assert(connection != null);
var adminItemCreator = _serviceProvider.GetInitableResolver(
connection,
_adminElevationManager.ProviderName)
.GetRequiredService<IRemoteItemCreator>();
return adminItemCreator;
}
}

View File

@@ -0,0 +1,30 @@
using FileTime.Core.ContentAccess;
using FileTime.Core.Enums;
using FileTime.Core.Models;
using FileTime.Core.Timeline;
using FileTime.Providers.Remote;
namespace FileTime.Providers.LocalAdmin;
//TODO: this should be a RemoteContentProvider if there will be one
public class AdminContentProvider : RemoteContentProvider, IAdminContentProvider
{
public AdminContentProvider() : base("local", "localAdmin")
{
}
public override Task<IItem> GetItemByNativePathAsync(NativePath nativePath, PointInTime pointInTime, bool forceResolve = false, AbsolutePathType forceResolvePathType = AbsolutePathType.Unknown, ItemInitializationSettings itemInitializationSettings = default)
=> throw new NotImplementedException();
public override NativePath GetNativePath(FullName fullName)
=> throw new NotImplementedException();
public override FullName GetFullName(NativePath nativePath)
=> throw new NotImplementedException();
public override Task<byte[]?> GetContentAsync(IElement element, int? maxLength = null, CancellationToken cancellationToken = default)
=> throw new NotImplementedException();
public override bool CanHandlePath(NativePath path)
=> throw new NotImplementedException();
}

View File

@@ -0,0 +1,197 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using FileTime.App.Core.Services;
using FileTime.Core.Interactions;
using FileTime.Providers.Local;
using FileTime.Server.Common;
using FileTime.Server.Common.Connections.SignalR;
using InitableService;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace FileTime.Providers.LocalAdmin;
public class AdminElevationManager : IAdminElevationManager, INotifyPropertyChanged, IExitHandler
{
private class ConnectionInfo
{
public string? SignalRBaseUrl { get; init; }
}
private readonly SemaphoreSlim _lock = new(1, 1);
private readonly IUserCommunicationService _dialogService;
private readonly ILogger<AdminElevationManager> _logger;
private readonly IOptionsMonitor<AdminElevationConfiguration> _configuration;
private readonly IServiceProvider _serviceProvider;
private ConnectionInfo? _connectionInfo;
private bool _isAdminInstanceRunning;
private Process? _adminProcess;
public bool IsAdminModeSupported => true;
private bool StartProcess => _configuration.CurrentValue.StartProcess ?? true;
public bool IsAdminInstanceRunning
{
get => _isAdminInstanceRunning;
private set => SetField(ref _isAdminInstanceRunning, value);
}
public string ProviderName => LocalContentProviderConstants.ContentProviderId;
public AdminElevationManager(
IUserCommunicationService dialogService,
ILogger<AdminElevationManager> logger,
IOptionsMonitor<AdminElevationConfiguration> configuration,
IServiceProvider serviceProvider
)
{
_dialogService = dialogService;
_logger = logger;
_configuration = configuration;
_serviceProvider = serviceProvider;
}
public async Task CreateAdminInstanceIfNecessaryAsync(string? confirmationMessage = null)
{
ArgumentNullException.ThrowIfNull(_configuration.CurrentValue.ServerExecutablePath, "ServerExecutablePath");
await _lock.WaitAsync();
try
{
if (IsAdminInstanceRunning) return;
confirmationMessage ??= "This operation requires admin privileges. Please confirm to continue.";
var confirmationResult = await _dialogService.ShowMessageBox(confirmationMessage);
if (confirmationResult == MessageBoxResult.Cancel) return;
var port = _configuration.CurrentValue.ServerPort;
_logger.LogTrace("Admin server port is {Port}", port is null ? "<not set>" : $"{port}");
if (StartProcess || port is null)
{
var portFileName = Path.GetTempFileName();
var process = new Process
{
StartInfo = new()
{
FileName = _configuration.CurrentValue.ServerExecutablePath,
ArgumentList =
{
"--PortWriter:FileName",
portFileName
},
UseShellExecute = true,
Verb = "runas"
},
EnableRaisingEvents = true
};
process.Exited += ProcessExitHandler;
process.Start();
_adminProcess = process;
IsAdminInstanceRunning = true;
//TODO: timeout
while (!File.Exists(portFileName) || new FileInfo(portFileName).Length == 0)
await Task.Delay(10);
var content = await File.ReadAllLinesAsync(portFileName);
if (int.TryParse(content.FirstOrDefault(), out var parsedPort))
{
port = parsedPort;
}
else
{
_logger.LogError(
"Could not parse port from content {Content}",
string.Join(Environment.NewLine, content)
);
}
}
var connectionInfo = new ConnectionInfo
{
SignalRBaseUrl = $"http://localhost:{port}/RemoteHub"
};
_connectionInfo = connectionInfo;
}
catch (Exception ex)
{
IsAdminInstanceRunning = false;
_logger.LogError(ex, "Error creating admin instance");
}
finally
{
_lock.Release();
}
}
public async Task<IRemoteConnection> CreateConnectionAsync()
{
ArgumentNullException.ThrowIfNull(_connectionInfo);
try
{
//TODO: use other connections too (if there will be any)
ArgumentNullException.ThrowIfNull(_connectionInfo.SignalRBaseUrl);
var connection = await _serviceProvider
.GetAsyncInitableResolver(_connectionInfo.SignalRBaseUrl)
.GetRequiredServiceAsync<SignalRConnection>();
return connection;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error creating SignalR connection");
throw;
}
}
private void ProcessExitHandler(object? sender, EventArgs e)
{
_lock.Wait();
IsAdminInstanceRunning = false;
_lock.Release();
}
public event PropertyChangedEventHandler? PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string? propertyName = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
private bool SetField<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
public async Task ExitAsync()
{
if (!StartProcess)
{
_logger.LogTrace("Not stopping admin process as it was not started by this instance");
return;
}
if (!IsAdminInstanceRunning)
{
_logger.LogTrace("Not stopping admin process as it is not running");
return;
}
try
{
_logger.LogInformation("Stopping admin process");
var connection = await CreateConnectionAsync();
await connection.Exit();
_logger.LogInformation("Admin process stopped successfully");
}
catch(Exception ex)
{
_logger.LogError(ex, "Error stopping admin process, trying to kill it");
_adminProcess?.Kill();
}
}
}

View File

@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Core\FileTime.Core.ContentAccess\FileTime.Core.ContentAccess.csproj" />
<ProjectReference Include="..\..\Server\FileTime.Server.Common\FileTime.Server.Common.csproj" />
<ProjectReference Include="..\FileTime.Providers.Local.Abstractions\FileTime.Providers.Local.Abstractions.csproj" />
<ProjectReference Include="..\FileTime.Providers.LocalAdmin.Abstractions\FileTime.Providers.LocalAdmin.Abstractions.csproj" />
<ProjectReference Include="..\FileTime.Providers.Remote\FileTime.Providers.Remote.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.Extensions.Configuration.Abstractions">
<HintPath>..\..\..\..\..\Program Files\dotnet\shared\Microsoft.AspNetCore.App\7.0.9\Microsoft.Extensions.Configuration.Abstractions.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,20 @@
using FileTime.App.Core.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace FileTime.Providers.LocalAdmin;
public static class Startup
{
public static IServiceCollection AddLocalAdminProviderServices(this IServiceCollection services, IConfigurationRoot configuration)
{
services.AddOptions<AdminElevationConfiguration>().Bind(configuration.GetSection(AdminElevationConfiguration.SectionName));
services.TryAddSingleton<IAdminContentAccessorFactory, AdminContentAccessorFactory>();
services.TryAddSingleton<IAdminContentProvider, AdminContentProvider>();
services.TryAddSingleton<AdminElevationManager>();
services.TryAddSingleton<IAdminElevationManager>(sp => sp.GetRequiredService<AdminElevationManager>());
services.AddSingleton<IExitHandler>(sp => sp.GetRequiredService<AdminElevationManager>());
return services;
}
}

View File

@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>FileTime.Providers.Remote</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Core\FileTime.Core.Abstraction\FileTime.Core.Abstraction.csproj" />
<ProjectReference Include="..\..\Server\FileTime.Server.Common.Abstractions\FileTime.Server.Common.Abstractions.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,8 @@
using FileTime.Core.ContentAccess;
namespace FileTime.Providers.Remote;
public interface IRemoteContentProvider : IContentProvider
{
}

View File

@@ -0,0 +1,12 @@
using FileTime.Core.ContentAccess;
using FileTime.Server.Common;
using InitableService;
namespace FileTime.Providers.Remote;
public interface IRemoteItemCreator :
IItemCreator<IRemoteContentProvider>,
IInitable<IRemoteConnection, string>
{
}

View File

@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Core\FileTime.Core.Abstraction\FileTime.Core.Abstraction.csproj" />
<ProjectReference Include="..\..\Core\FileTime.Core.ContentAccess\FileTime.Core.ContentAccess.csproj" />
<ProjectReference Include="..\FileTime.Providers.Remote.Abstractions\FileTime.Providers.Remote.Abstractions.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,24 @@
using FileTime.Core.ContentAccess;
using FileTime.Core.Enums;
using FileTime.Core.Models;
using FileTime.Core.Timeline;
namespace FileTime.Providers.Remote;
public class RemoteContentProvider : ContentProviderBase, IRemoteContentProvider
{
public RemoteContentProvider(string remoteName, string name = "remote") : base(name)
{
}
//TODO implement
public override Task<IItem> GetItemByNativePathAsync(NativePath nativePath, PointInTime pointInTime, bool forceResolve = false, AbsolutePathType forceResolvePathType = AbsolutePathType.Unknown, ItemInitializationSettings itemInitializationSettings = default) => throw new NotImplementedException();
public override NativePath GetNativePath(FullName fullName) => throw new NotImplementedException();
public override FullName GetFullName(NativePath nativePath) => throw new NotImplementedException();
public override Task<byte[]?> GetContentAsync(IElement element, int? maxLength = null, CancellationToken cancellationToken = default) => throw new NotImplementedException();
public override bool CanHandlePath(NativePath path) => throw new NotImplementedException();
}

View File

@@ -0,0 +1,24 @@
using FileTime.Core.ContentAccess;
using FileTime.Core.Models;
using FileTime.Server.Common;
namespace FileTime.Providers.Remote;
public class RemoteItemCreator :
ItemCreatorBase<IRemoteContentProvider>,
IRemoteItemCreator
{
private IRemoteConnection _remoteConnection = null!;
private string _remoteContentProviderId = null!;
public void Init(IRemoteConnection remoteConnection, string remoteContentProviderId)
{
_remoteConnection = remoteConnection;
_remoteContentProviderId = remoteContentProviderId;
}
public override async Task CreateContainerAsync(IRemoteContentProvider contentProvider, FullName fullName)
=> await _remoteConnection.CreateContainerAsync(_remoteContentProviderId, fullName);
public override async Task CreateElementAsync(IRemoteContentProvider contentProvider, FullName fullName)
=> await _remoteConnection.CreateElementAsync(_remoteContentProviderId, fullName);
}

View File

@@ -0,0 +1,16 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace FileTime.Providers.Remote;
public static class Startup
{
public static IServiceCollection AddRemoteProviderServices(this IServiceCollection serviceCollection)
{
serviceCollection.TryAddSingleton<IRemoteContentProvider, RemoteContentProvider>();
serviceCollection.TryAddTransient<IRemoteItemCreator, RemoteItemCreator>();
return serviceCollection;
}
}