Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 5 additions & 10 deletions src/Files.App.Server/AppService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,15 @@ public sealed partial class AppService : IDisposable
internal bool IsDisposed => disposed != 0;

public bool CanRestorePreviousSession { get; }
public int ProcessId => Environment.ProcessId;
public PinnedFoldersService PinnedFolders { get; }
public RecycleBinService RecycleBin { get; }

public AppService(int processId)
{
(ClientId, CanRestorePreviousSession) = ServerHost.AddClient(processId);
PinnedFolders = new(this);
RecycleBin = new(this);
}

~AppService() => Dispose();
Expand All @@ -31,16 +36,6 @@ public event EventHandler<string> Changed

public static IAsyncAction InitializeAsync() => ServerAsync.Run(token => StartupServices.InitializeAsync().WaitAsync(token));

public static IAsyncOperation<IReadOnlyList<LibraryInfo>> GetLibrariesAsync() => ServerAsync.Run(token => InitializationCache.Libraries.GetAsync().WaitAsync(token));

public static IAsyncOperation<IReadOnlyList<PinnedFolderInfo>> GetPinnedFoldersAsync() => ServerAsync.Run(token => InitializationCache.PinnedFolders.GetAsync().WaitAsync(token));

public static void InvalidatePinnedFolders()
{
InitializationCache.PinnedFolders.Invalidate();
ServerEvents.Notify(ServerChangeNames.PinnedFolders);
}

public void Dispose()
{
if (Interlocked.Exchange(ref disposed, 1) == 0)
Expand Down
90 changes: 90 additions & 0 deletions src/Files.App.Server/Caching/DeviceRemovalMonitor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// Copyright (c) Files Community
// Licensed under the MIT License.

using Microsoft.Extensions.Logging;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Windows.Win32;
using Windows.Win32.Devices.DeviceAndDriverInstallation;
using Windows.Win32.Foundation;
using Windows.Win32.Storage.FileSystem;

namespace Files.App.Server;

internal sealed partial class DeviceRemovalMonitor : IDisposable
{
private GCHandle context;
private HCMNOTIFICATION notification;

internal unsafe DeviceRemovalMonitor(string root, Action<bool> changed)
{
using var handle = PInvoke.CreateFile(root, 0,
FILE_SHARE_MODE.FILE_SHARE_READ | FILE_SHARE_MODE.FILE_SHARE_WRITE | FILE_SHARE_MODE.FILE_SHARE_DELETE,
null, FILE_CREATION_DISPOSITION.OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_BACKUP_SEMANTICS, null);
if (handle.IsInvalid)
throw new Win32Exception(Marshal.GetLastPInvokeError());

CM_NOTIFY_FILTER filter = new()
{
cbSize = (uint)sizeof(CM_NOTIFY_FILTER),
FilterType = CM_NOTIFY_FILTER_TYPE.CM_NOTIFY_FILTER_TYPE_DEVICEHANDLE,
};
filter.u.DeviceHandle.hTarget = new HANDLE(handle.DangerousGetHandle());
context = GCHandle.Alloc(changed);
HCMNOTIFICATION registration = default;
var result = PInvoke.CM_Register_Notification(&filter, (void*)GCHandle.ToIntPtr(context), &OnNotification, &registration);
GC.KeepAlive(handle);
if (result != CONFIGRET.CR_SUCCESS)
{
context.Free();
throw new InvalidOperationException($"Could not register device removal notifications: {result}.");
}
notification = registration;
// The registration remains valid after its target handle is closed.
}

[UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])]
private static unsafe uint OnNotification(HCMNOTIFICATION notification, void* context, CM_NOTIFY_ACTION action, CM_NOTIFY_EVENT_DATA* data, uint size)
{
try
{
var changed = (Action<bool>)GCHandle.FromIntPtr((nint)context).Target!;
if (action is CM_NOTIFY_ACTION.CM_NOTIFY_ACTION_DEVICEQUERYREMOVE or
CM_NOTIFY_ACTION.CM_NOTIFY_ACTION_DEVICEREMOVEPENDING or CM_NOTIFY_ACTION.CM_NOTIFY_ACTION_DEVICEREMOVECOMPLETE)
changed(true);
else if (action == CM_NOTIFY_ACTION.CM_NOTIFY_ACTION_DEVICEQUERYREMOVEFAILED)
changed(false);
else if (action == CM_NOTIFY_ACTION.CM_NOTIFY_ACTION_DEVICECUSTOMEVENT && data is not null &&
data->FilterType == CM_NOTIFY_FILTER_TYPE.CM_NOTIFY_FILTER_TYPE_DEVICEHANDLE)
{
var eventGuid = data->u.DeviceHandle.EventGuid;
if (eventGuid == PInvoke.GUID_IO_VOLUME_LOCK || eventGuid == PInvoke.GUID_IO_VOLUME_DISMOUNT)
changed(true);
else if (eventGuid == PInvoke.GUID_IO_VOLUME_LOCK_FAILED || eventGuid == PInvoke.GUID_IO_VOLUME_DISMOUNT_FAILED ||
eventGuid == PInvoke.GUID_IO_VOLUME_UNLOCK || eventGuid == PInvoke.GUID_IO_VOLUME_MOUNT)
changed(false);
}
}
catch (Exception ex)
{
Program.Logger.LogWarning(ex, "Could not update directory watches for device removal.");
}
return 0;
}

public void Dispose()
{
if (!context.IsAllocated)
return;

// Wait for callbacks before freeing their context; never unregister from a callback.
var result = PInvoke.CM_Unregister_Notification(notification);
if (result != CONFIGRET.CR_SUCCESS)
{
Program.Logger.LogWarning("Could not unregister device removal notifications: {Result}.", result);
return;
}
context.Free();
}
}
247 changes: 247 additions & 0 deletions src/Files.App.Server/Caching/DirectoryChangeMonitor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,247 @@
// Copyright (c) Files Community
// Licensed under the MIT License.

using Microsoft.Extensions.Logging;
using System.IO.Enumeration;

namespace Files.App.Server;

internal sealed partial class DirectoryChangeMonitor : IDisposable
{
private readonly Lock gate = new();
private readonly Lock configureGate = new();
private readonly string directory;
private readonly string filter;
private readonly bool recursive;
private readonly Action<FileSystemEventArgs> changed;
private readonly DeviceRemovalMonitor? deviceRemoval;
private FileSystemWatcher? watcher;
private FileSystemWatcher? parentWatcher;
private bool watchingTarget;
private bool disposed;
private bool suspended;
private long configurationVersion;

internal DirectoryChangeMonitor(string directory, string filter, bool recursive, Action<FileSystemEventArgs> changed, bool watchDeviceRemoval = false)
{
this.directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory));
this.filter = filter;
this.recursive = recursive;
this.changed = changed;
try
{
if (watchDeviceRemoval)
deviceRemoval = new DeviceRemovalMonitor(Path.GetPathRoot(this.directory)!, OnDeviceRemoval);
Configure();
}
catch
{
Dispose();
throw;
}
}

private void Configure()
{
long version;
lock (gate)
{
if (disposed || suspended)
return;
version = ++configurationVersion;
}
var existing = directory;
var next = directory;
while (!Directory.Exists(existing))
{
next = existing;
existing = Path.GetDirectoryName(existing);
if (string.IsNullOrEmpty(existing))
return;
}

var targetExists = string.Equals(existing, directory, StringComparison.OrdinalIgnoreCase);
var replacement = CreateWatcher(existing, targetExists ? filter : Path.GetFileName(next), targetExists && recursive,
NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite);
FileSystemWatcher? replacementParent = null;
try
{
if (targetExists && Path.GetDirectoryName(directory) is { } parent)
replacementParent = CreateWatcher(parent, Path.GetFileName(directory), false, NotifyFilters.DirectoryName);
}
catch
{
replacement.Dispose();
throw;
}
FileSystemWatcher? previous;
FileSystemWatcher? previousParent;
lock (gate)
{
if (disposed || suspended || version != configurationVersion)
{
previous = replacement;
previousParent = replacementParent;
}
else
{
try
{
// Serialize opening handles with the device-removal callback that closes them.
replacement.EnableRaisingEvents = true;
if (replacementParent is not null)
replacementParent.EnableRaisingEvents = true;
}
catch
{
replacement.Dispose();
replacementParent?.Dispose();
throw;
}
previous = watcher;
previousParent = parentWatcher;
watcher = replacement;
parentWatcher = replacementParent;
watchingTarget = targetExists;
}
previous?.Dispose();
previousParent?.Dispose();
}
// The missing component may have appeared before its parent watch was enabled.
if (!targetExists && Directory.Exists(next))
Configure();
}

private FileSystemWatcher CreateWatcher(string path, string pattern, bool includeSubdirectories, NotifyFilters notifyFilter)
{
var replacement = new FileSystemWatcher(path, pattern)
{
IncludeSubdirectories = includeSubdirectories,
NotifyFilter = notifyFilter,
};
try
{
replacement.Created += OnChanged;
replacement.Deleted += OnChanged;
replacement.Changed += OnChanged;
replacement.Renamed += OnChanged;
replacement.Error += OnError;
}
catch
{
replacement.Dispose();
throw;
}
return replacement;
}

private void OnDeviceRemoval(bool removing)
{
FileSystemWatcher? previous;
FileSystemWatcher? previousParent;
lock (gate)
{
if (disposed)
return;
suspended = removing;
configurationVersion++;
previous = watcher;
previousParent = parentWatcher;
watcher = null;
parentWatcher = null;
previous?.Dispose();
previousParent?.Dispose();
}
if (!removing)
{
// Reopening a device can block, so do it after returning from the PnP callback.
ThreadPool.QueueUserWorkItem(_ =>
{
SafetyExtensions.IgnoreExceptions(Configure, Program.Logger);
if (!Volatile.Read(ref disposed))
changed(new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty));
});
}
}

private bool Relevant(string path)
=> (recursive
? path.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)
: string.Equals(Path.GetDirectoryName(path), directory, StringComparison.OrdinalIgnoreCase))
&& FileSystemName.MatchesSimpleExpression(filter, Path.GetFileName(path), ignoreCase: true);

private void OnChanged(object sender, FileSystemEventArgs args)
{
bool reconfigure;
lock (gate)
{
if (disposed || (!ReferenceEquals(sender, watcher) && !ReferenceEquals(sender, parentWatcher)))
return;
reconfigure = ReferenceEquals(sender, parentWatcher) || !watchingTarget;
}
if (reconfigure || !Directory.Exists(directory))
{
if (!Reconfigure(sender))
return;
args = new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty);
}
else if (!Relevant(args.FullPath) && !(args is RenamedEventArgs renamed && Relevant(renamed.OldFullPath)))
return;
if (!Volatile.Read(ref disposed))
changed(args);
}

private void OnError(object sender, ErrorEventArgs args)
{
lock (gate)
{
if (disposed || (!ReferenceEquals(sender, watcher) && !ReferenceEquals(sender, parentWatcher)))
return;
}
if (args.GetException() is not InternalBufferOverflowException && !Reconfigure(sender))
return;
if (!Volatile.Read(ref disposed))
changed(new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty));
}

private bool Reconfigure(object sender)
{
lock (configureGate)
{
lock (gate)
{
if (disposed || (!ReferenceEquals(sender, watcher) && !ReferenceEquals(sender, parentWatcher)))
return false;
}
try
{
Configure();
}
catch (Exception ex)
{
Program.Logger.LogWarning(ex, "Could not update a directory watch.");
}
return !Volatile.Read(ref disposed);
}
}

public void Dispose()
{
FileSystemWatcher? previous;
FileSystemWatcher? previousParent;
lock (gate)
{
if (disposed)
return;
disposed = true;
configurationVersion++;
previous = watcher;
previousParent = parentWatcher;
watcher = null;
parentWatcher = null;
previous?.Dispose();
previousParent?.Dispose();
}
deviceRemoval?.Dispose();
}
}
Loading
Loading