From 05b662b6cf4b777c3922d3cf57f3a9550499c96d Mon Sep 17 00:00:00 2001 From: Alejandro Mora Date: Fri, 6 Nov 2026 07:52:10 -0500 Subject: [PATCH 1/4] feat: elevate only the link step instead of restarting as admin When a symbolic link needs administrator rights (no admin, no Developer Mode), Symlinker used to offer to restart the whole app elevated. That meant a restart, a UAC prompt, and a new window without drag and drop. Now the window stays unelevated. Create link starts a hidden copy of Symlinker.exe (--link-helper) with runas, which shows one UAC prompt and creates the link over a named pipe. It is started before anything on disk changes (deleting an existing item or the move-and-link flow), so declining the prompt quietly stops and leaves everything as it was. - LinkCommand runs mklink for both the window and the helper, and rejects paths with quotes or line breaks. - Both pipe ends verify the other's process ID. - Remove the restart dialog, the footer restart link and their strings. - Footer notice now says Windows will ask for permission. Co-Authored-By: Claude Opus 5.5 --- Symlinker/ElevatedLinker.cs | 178 +++++++++++++++++++++ Symlinker/Elevation.cs | 90 +---------- Symlinker/LinkCommand.cs | 107 +++++++++++++ Symlinker/MainWindow.Inputs.cs | 78 ++++----- Symlinker/MainWindow.xaml | 11 +- Symlinker/MainWindow.xaml.cs | 83 ++++++---- Symlinker/Program.cs | 12 +- Symlinker/Properties/Resources.Designer.cs | 47 ++---- Symlinker/Properties/Resources.de.resx | 17 +- Symlinker/Properties/Resources.es.resx | 17 +- Symlinker/Properties/Resources.fr.resx | 17 +- Symlinker/Properties/Resources.hi.resx | 17 +- Symlinker/Properties/Resources.it.resx | 17 +- Symlinker/Properties/Resources.ja.resx | 17 +- Symlinker/Properties/Resources.pt.resx | 17 +- Symlinker/Properties/Resources.resx | 17 +- Symlinker/Properties/Resources.zh.resx | 17 +- 17 files changed, 427 insertions(+), 332 deletions(-) create mode 100644 Symlinker/ElevatedLinker.cs create mode 100644 Symlinker/LinkCommand.cs diff --git a/Symlinker/ElevatedLinker.cs b/Symlinker/ElevatedLinker.cs new file mode 100644 index 0000000..5eead46 --- /dev/null +++ b/Symlinker/ElevatedLinker.cs @@ -0,0 +1,178 @@ +namespace Symlinker +{ + using System; + using System.ComponentModel; + using System.Diagnostics; + using System.Globalization; + using System.IO; + using System.IO.Pipes; + using System.Runtime.InteropServices; + using System.Text; + using System.Text.Json; + using System.Threading; + using System.Threading.Tasks; + + using Res = Symlinker.Properties.Resources; + + /// + /// Creates links through a copy of Symlinker running as administrator, so the window itself + /// stays unelevated (and keeps drag and drop). Starting it shows one UAC prompt. It then waits + /// on a named pipe for link requests until disposed, so a caller can elevate before changing + /// anything on disk and create the link later. + /// + internal sealed class ElevatedLinker : IDisposable + { + /// Command line switch that runs Symlinker as the helper instead of opening the window. + public const string HelperArg = "--link-helper"; + + private const int ErrorCancelled = 1223; + private const int HelperConnectTimeoutMs = 10000; + private static readonly TimeSpan StartTimeout = TimeSpan.FromSeconds(30); + private static readonly Encoding PipeEncoding = new UTF8Encoding(false); + + private readonly NamedPipeServerStream pipe; + private readonly Process process; + private readonly StreamReader reader; + private readonly StreamWriter writer; + + private ElevatedLinker(NamedPipeServerStream pipe, Process process) + { + this.pipe = pipe; + this.process = process; + reader = new StreamReader(pipe, PipeEncoding, false, 1024, leaveOpen: true); + writer = new StreamWriter(pipe, PipeEncoding, 1024, leaveOpen: true) { AutoFlush = true }; + } + + /// + /// Starts the helper as administrator. Returns null when the user cancels the UAC prompt. + /// Throws when the helper starts but can't be reached. + /// + public static async Task StartAsync() + { + var pipeName = "Symlinker-" + Guid.NewGuid().ToString("N"); + + // One instance only, so nothing else can open a second end with the same name + var pipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); + Process process = null; + try + { + var startInfo = new ProcessStartInfo + { + FileName = Environment.ProcessPath, + Arguments = string.Join(" ", HelperArg, pipeName, Environment.ProcessId.ToString(CultureInfo.InvariantCulture)), + UseShellExecute = true, + Verb = "runas", + }; + + try + { + // Waits for the UAC prompt, so keep it off the UI thread + process = await Task.Run(() => Process.Start(startInfo)); + } + catch (Win32Exception exception) when (exception.NativeErrorCode == ErrorCancelled) + { + pipe.Dispose(); + return null; + } + + if (process == null) + throw new InvalidOperationException(Res.ElevationHelperFailed); + + using var timeout = new CancellationTokenSource(StartTimeout); + var connected = pipe.WaitForConnectionAsync(timeout.Token); + var exited = process.WaitForExitAsync(timeout.Token); + await Task.WhenAny(connected, exited); + if (!connected.IsCompletedSuccessfully) + throw new InvalidOperationException(Res.ElevationHelperFailed); + + // Make sure the other end is the helper just started, not some other program + if (!GetNamedPipeClientProcessId(pipe.SafePipeHandle, out var clientId) || clientId != (uint)process.Id) + throw new InvalidOperationException(Res.ElevationHelperFailed); + + return new ElevatedLinker(pipe, process); + } + catch + { + pipe.Dispose(); + process?.Dispose(); + throw; + } + } + + /// Creates a link as administrator. + public async Task CreateLinkAsync(LinkRequest request) + { + await writer.WriteLineAsync(JsonSerializer.Serialize(request)); + var line = await reader.ReadLineAsync(); + if (line == null) + throw new IOException("The administrator helper closed unexpectedly."); + + return JsonSerializer.Deserialize(line) ?? throw new IOException("The administrator helper sent an empty reply."); + } + + /// Closes the connection; the helper exits when it sees that. + public void Dispose() + { + reader.Dispose(); + writer.Dispose(); + pipe.Dispose(); + process.Dispose(); + } + + /// + /// Runs in the elevated copy: connects back to the window that started it and creates + /// each link it is sent, until the window closes the connection. Returns the exit code. + /// + public static int RunHelper(string[] args) + { + if (args.Length != 3 || !uint.TryParse(args[2], NumberStyles.None, CultureInfo.InvariantCulture, out var parentId)) + return 2; + + try + { + using var pipe = new NamedPipeClientStream(".", args[1], PipeDirection.InOut); + pipe.Connect(HelperConnectTimeoutMs); + + // Only take requests from the window that asked for elevation + if (!GetNamedPipeServerProcessId(pipe.SafePipeHandle, out var serverId) || serverId != parentId) + return 3; + + // Not disposed: the window closing the pipe is the normal way to finish, and + // disposing a writer then would flush into the closed pipe and throw + var reader = new StreamReader(pipe, PipeEncoding, false, 1024, leaveOpen: true); + var writer = new StreamWriter(pipe, PipeEncoding, 1024, leaveOpen: true) { AutoFlush = true }; + + string line; + while ((line = reader.ReadLine()) != null) + { + LinkResult result; + try + { + var request = JsonSerializer.Deserialize(line); + result = LinkCommand.RunAsync(request).GetAwaiter().GetResult(); + } + catch (Exception exception) + { + result = LinkResult.Failed(exception.Message); + } + + writer.WriteLine(JsonSerializer.Serialize(result)); + } + + return 0; + } + catch (Exception) + { + return 1; + } + } + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetNamedPipeClientProcessId(Microsoft.Win32.SafeHandles.SafePipeHandle pipe, out uint clientProcessId); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetNamedPipeServerProcessId(Microsoft.Win32.SafeHandles.SafePipeHandle pipe, out uint serverProcessId); + } +} diff --git a/Symlinker/Elevation.cs b/Symlinker/Elevation.cs index aa1ba13..1b29be7 100644 --- a/Symlinker/Elevation.cs +++ b/Symlinker/Elevation.cs @@ -1,21 +1,15 @@ namespace Symlinker { using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Security.Principal; - using System.Text; using System.Windows; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; - /// - /// Values the window starts with. Used to carry the form over when restarting as administrator. - /// + /// Values the window starts with, read from the command line. internal sealed class LaunchOptions { private const string ModeArg = "--mode"; @@ -58,64 +52,15 @@ public static LaunchOptions Parse(string[] args) return options; } - - /// Builds a command line that turns back into these options. - public string ToArguments() - { - var parts = new List(); - void Add(string name, string value) - { - if (!string.IsNullOrEmpty(value)) - { - parts.Add(name); - parts.Add(QuoteArgument(value)); - } - } - - Add(ModeArg, Mode); - Add(TypeArg, LinkType); - Add(LocationArg, LinkLocation); - Add(NameArg, LinkName); - Add(TargetArg, Target); - return string.Join(" ", parts); - } - - /// - /// Quotes one argument so Windows splits it back exactly as given, including spaces - /// and trailing backslashes (like "C:\"). - /// - internal static string QuoteArgument(string value) - { - if (value.Length != 0 && value.IndexOfAny(new[] { ' ', '\t', '\n', '\v', '"' }) < 0) - return value; - - var quoted = new StringBuilder("\""); - var backslashes = 0; - foreach (var c in value) - { - if (c == '\\') - { - backslashes++; - continue; - } - - // Backslashes only need escaping when a quote follows them - quoted.Append('\\', c == '"' ? (backslashes * 2) + 1 : backslashes); - quoted.Append(c); - backslashes = 0; - } - - quoted.Append('\\', backslashes * 2); - quoted.Append('"'); - return quoted.ToString(); - } } - /// Administrator rights helpers. Symlinker runs unelevated and only asks for them when needed. + /// + /// Administrator rights helpers. Symlinker runs unelevated and only elevates the link + /// creation step when needed (see ). + /// internal static class Elevation { private const int ErrorPrivilegeNotHeld = 1314; - private const int ErrorCancelled = 1223; public static bool IsElevated { @@ -155,31 +100,6 @@ public static bool CanCreateSymbolicLinks() } } - /// - /// Starts a new elevated instance with the given options. - /// Returns false when the user declines the UAC prompt. - /// - public static bool RestartElevated(LaunchOptions options) - { - var startInfo = new ProcessStartInfo - { - FileName = Environment.ProcessPath, - Arguments = options.ToArguments(), - UseShellExecute = true, - Verb = "runas", - }; - - try - { - Process.Start(startInfo)?.Dispose(); - return true; - } - catch (Win32Exception exception) when (exception.NativeErrorCode == ErrorCancelled) - { - return false; - } - } - /// /// The Windows UAC shield (small size), shown on actions that need administrator rights. /// Returns null if Windows doesn't provide it. diff --git a/Symlinker/LinkCommand.cs b/Symlinker/LinkCommand.cs new file mode 100644 index 0000000..091ca39 --- /dev/null +++ b/Symlinker/LinkCommand.cs @@ -0,0 +1,107 @@ +namespace Symlinker +{ + using System; + using System.Diagnostics; + using System.IO; + using System.Threading.Tasks; + + using Res = Symlinker.Properties.Resources; + + /// One link to create. Sent to the elevated helper as JSON, so it only holds plain values. + internal sealed class LinkRequest + { + /// "symbolic", "hard" or "junction". + public string Type { get; set; } + + /// Full path of the link to create. + public string Link { get; set; } + + /// What the link points to, as entered (a relative target stays relative). + public string Target { get; set; } + + /// Whether the link is for a folder. + public bool Directory { get; set; } + } + + /// Outcome of a , with the message to show the user. + internal sealed class LinkResult + { + public bool Success { get; set; } + + public string Message { get; set; } + + public static LinkResult Failed(string message) => new() { Success = false, Message = message }; + } + + /// Creates links with mklink. Used by the window and by the elevated helper. + internal static class LinkCommand + { + public static async Task RunAsync(LinkRequest request) + { + var arguments = BuildArguments(request); + if (arguments == null) + return LinkResult.Failed(Res.InvalidQuoteInPath); + + try + { + var startInfo = new ProcessStartInfo + { + FileName = "cmd", + Arguments = arguments, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardError = true, + RedirectStandardOutput = true, + }; + + using var process = new Process { StartInfo = startInfo }; + process.Start(); + var output = process.StandardOutput.ReadToEndAsync(); + var error = process.StandardError.ReadToEndAsync(); + await process.WaitForExitAsync(); + + var outputText = (await output).Trim(); + var errorText = (await error).Trim(); + + if (process.ExitCode == 0) + return new LinkResult { Success = true, Message = outputText.Length > 0 ? outputText : Res.LinkSuccessfullyCreated }; + + return LinkResult.Failed(errorText.Length > 0 ? errorText : outputText); + } + catch (Exception) + { + return LinkResult.Failed(Res.CmdNotFound); + } + } + + /// + /// Builds the cmd.exe arguments. Returns null for anything that could break out of the + /// quotes, since the elevated helper runs whatever it is sent. + /// + private static string BuildArguments(LinkRequest request) + { + if (request == null || string.IsNullOrWhiteSpace(request.Link) || string.IsNullOrWhiteSpace(request.Target)) + return null; + + if (request.Link.IndexOfAny(UnsafeChars) >= 0 || request.Target.IndexOfAny(UnsafeChars) >= 0) + return null; + + var typeFlag = request.Type switch + { + "hard" => "/H ", + "junction" => "/J ", + "symbolic" => string.Empty, + _ => null, + }; + + if (typeFlag == null) + return null; + + var directory = request.Directory ? "/D " : string.Empty; + return $"/c mklink {directory}{typeFlag}\"{request.Link}\" \"{request.Target}\""; + } + + // Quotes end the quoted path; line breaks end the command + private static readonly char[] UnsafeChars = { '"', '\r', '\n', '\0' }; + } +} diff --git a/Symlinker/MainWindow.Inputs.cs b/Symlinker/MainWindow.Inputs.cs index ec7db1a..cf2e051 100644 --- a/Symlinker/MainWindow.Inputs.cs +++ b/Symlinker/MainWindow.Inputs.cs @@ -31,7 +31,7 @@ public static class InputError public static void SetHasError(DependencyObject element, bool value) => element.SetValue(HasErrorProperty, value); } - /// Input checks, inline errors, launch options and the administrator restart. + /// Input checks, inline errors, launch options and administrator rights for symbolic links. public partial class MainWindow { private const string ErrorBrushKey = "Symlinker.Brushes.Error"; @@ -46,10 +46,13 @@ public partial class MainWindow private LaunchOptions launchOptions; - // Whether creating a symbolic link would need a restart as administrator + // Whether creating a symbolic link needs administrator rights (no admin, no Developer Mode) private bool symlinksNeedAdmin; private bool checkingSymlinkAccess; + // Administrator helper for the link being created, started on demand + private ElevatedLinker elevatedLinker; + private void InitializeInputs() { // The app theme is applied after the window is created, so refresh again once loaded @@ -117,8 +120,6 @@ private void UpdateAdminNotice() adminPanel.Visibility = needsAdmin && inputErrors.Count == 0 ? Visibility.Visible : Visibility.Collapsed; } - private async void RestartAsAdmin_Click(object sender, RoutedEventArgs e) => await RestartAsAdminAsync(); - private void OnThemeChanged(object sender, ThemeChangedEventArgs e) => UpdateThemeBrushes(); private void UpdateThemeBrushes() @@ -170,7 +171,7 @@ static double Channel(byte value) return (Math.Max(la, lb) + 0.05) / (Math.Min(la, lb) + 0.05); } - /// Fills the form from the command line, e.g. after restarting as administrator. + /// Fills the form from the command line. private void ApplyLaunchOptions() { var options = launchOptions; @@ -200,63 +201,48 @@ private void ApplyLaunchOptions() linkNameTextBox.Text = options.LinkName; } - private LaunchOptions GetCurrentOptions() => new() - { - Mode = isFolder ? "folder" : "file", - LinkType = hardLinkRadio.IsChecked == true ? "hard" : junctionRadio.IsChecked == true ? "junction" : "symbolic", - LinkLocation = linkLocationTextBox.Text, - LinkName = linkNameTextBox.Text, - Target = destinationLocationTextBox.Text, - }; - /// - /// Symbolic links need administrator rights unless Developer Mode is on. Checked before - /// anything runs, so nothing on disk changes when the link can't be created anyway. - /// Returns false when link creation should stop here. + /// Checks again whether a symbolic link would need administrator rights, since Developer + /// Mode may have been turned on since the window opened. /// - private async Task EnsureCanCreateLinkAsync() + private void RefreshSymlinkAccessNow() { - if (hardLinkRadio.IsChecked == true || junctionRadio.IsChecked == true) - return true; + if (symLinkRadio.IsChecked != true) + return; - // Check again: Developer Mode may have been turned on since the window opened symlinksNeedAdmin = !Elevation.CanCreateSymbolicLinks(); UpdateAdminNotice(); - if (!symlinksNeedAdmin) - return true; - - var settings = new MetroDialogSettings - { - AnimateShow = false, - AnimateHide = false, - AffirmativeButtonText = Res.ButtonRestartAsAdmin, - NegativeButtonText = Res.ButtonNotNow, - DefaultButtonFocus = MessageDialogResult.Affirmative, - - // Smaller title so long translations fit the short window without scrolling - DialogTitleFontSize = 20, - }; - - var answer = await this.ShowMessageAsync(Res.DialogElevationTitle, Res.DialogElevation, MessageDialogStyle.AffirmativeAndNegative, settings); - if (answer == MessageDialogResult.Affirmative) - await RestartAsAdminAsync(); - - return false; } - /// Restarts as administrator with the current form values. This window closes if the user accepts the UAC prompt. - private async Task RestartAsAdminAsync() + /// + /// Starts the administrator helper if this link needs it (one UAC prompt). Call it before + /// anything on disk changes, so a declined prompt leaves everything as it was. + /// Returns false when link creation should stop: the user canceled the prompt (nothing is + /// shown then) or the helper couldn't start (an error is shown). + /// + private async Task ElevateIfNeededAsync() { + if (elevatedLinker != null || !symlinksNeedAdmin || symLinkRadio.IsChecked != true) + return true; + try { - // The new window opens with the same values; this one closes - if (Elevation.RestartElevated(GetCurrentOptions())) - Close(); + elevatedLinker = await ElevatedLinker.StartAsync(); } catch (Exception exception) { await this.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.MessageBoxExceptionOcurred + "\n" + exception.Message, settings: FastDialog); + return false; } + + return elevatedLinker != null; + } + + /// Closes the administrator helper, if one was started for this link. + private void StopElevatedLinker() + { + elevatedLinker?.Dispose(); + elevatedLinker = null; } /// Checks every field, marks the bad ones and shows what's wrong. Returns true when all are fine. diff --git a/Symlinker/MainWindow.xaml b/Symlinker/MainWindow.xaml index fa9abde..ffd66b7 100644 --- a/Symlinker/MainWindow.xaml +++ b/Symlinker/MainWindow.xaml @@ -536,14 +536,9 @@ VerticalAlignment="Top" Margin="0,1,6,0"/> - - - - - + Foreground="{DynamicResource MahApps.Brushes.ThemeForeground}" + Text="{x:Static p:Resources.NoticeSymlinkNeedsAdmin}" + ToolTip="{x:Static p:Resources.NoticeSymlinkNeedsAdmin}"/>