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
31 changes: 20 additions & 11 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,27 +37,33 @@ The app starts unelevated. It only asks for administrator rights when a symbolic

### Key Components

1. **Program.cs**: Entry point. Parses command-line options (`LaunchOptions`) and opens the main window. It does not elevate.
1. **Program.cs**: Entry point. Parses command-line options (`LaunchOptions`) and opens the main window. It does not elevate. With `--link-helper` it runs the hidden elevated helper instead (see "Administrator rights").
2. **App.xaml / App.xaml.cs**: Loads MahApps.Metro styles and syncs the theme (light/dark and accent color) with Windows.
3. **MainWindow.xaml**: The whole UI. Two cards (link location, target), pill toggles for folder/file mode and link type, and a footer with the About button, an inline error line and the Create link button. Styles live in `Window.Resources`.
4. **MainWindow.xaml.cs**: Mode switching, link name auto-fill, file pickers, drag and drop, and link creation (`CreateLink()` and `SendCommand()`, which runs `cmd.exe /c mklink`).
5. **MainWindow.Inputs.cs**: Field validation with inline errors (`InputError.HasError` attached property plus the footer message), theme-dependent brushes, restoring launch options, the up-front admin notice, and the administrator restart prompt.
6. **Elevation.cs**: `LaunchOptions` (command-line parsing and correctly quoted argument building) and `Elevation` (admin check, symbolic link privilege probe, elevated restart with `runas`, the UAC shield icon).
4. **MainWindow.xaml.cs**: Mode switching, link name auto-fill, file pickers, drag and drop, and link creation (`CreateLink()`, `SendCommand()`, the move-and-link flow, and `RunMklinkAsync()`).
5. **MainWindow.Inputs.cs**: Field validation with inline errors (`InputError.HasError` attached property plus the footer message), theme-dependent brushes, restoring launch options, the up-front admin notice, and starting the elevated helper on demand (`ElevateIfNeededAsync()`).
6. **Elevation.cs**: `LaunchOptions` (command-line parsing) and `Elevation` (admin check, symbolic link privilege probe, the UAC shield icon).
7. **LinkCommand.cs**: `LinkRequest`/`LinkResult` and `LinkCommand.RunAsync()`, which runs `cmd.exe /c mklink`. Used by the window and by the elevated helper.
8. **ElevatedLinker.cs**: Starts `Symlinker.exe --link-helper` as administrator and sends it link requests over a named pipe.
9. **LinkMover.cs**: File system helpers for moving an existing file or folder to the target before linking.

### Link Creation Flow

1. User picks folder or file mode (pills) and a link type. Junction is folder-only, hard link is file-only.
2. User fills in the link location, link name and target (typing, browsing, or drag and drop).
3. Create link (or Enter, it is the default button) runs `ValidateInputs()`, which marks bad fields inline.
4. `EnsureCanCreateLinkAsync()` checks whether a symbolic link can be created. If not, it offers to restart as administrator.
5. `CreateLink()` handles an existing item at the link path, then `SendCommand()` runs mklink and shows the result.
4. `RefreshSymlinkAccessNow()` probes again whether a symbolic link needs administrator rights.
5. `CreateLink()` handles an existing item at the link path (delete it, or move it to the target), then `SendCommand()` runs mklink and shows the result. `ElevateIfNeededAsync()` is called before the first change on disk.

### Administrator rights

- Junctions and hard links never need admin. Symbolic links need admin unless Windows Developer Mode is on.
- `Elevation.CanCreateSymbolicLinks()` probes by creating a throwaway symlink in the temp folder.
- The probe runs when the window loads (and again on activation while admin is needed). If symbolic links need admin, Create link shows the UAC shield and the footer shows a notice with a "Restart as administrator" link, so the user knows before filling in the form. Field errors take the same footer spot and hide the notice.
- When elevation is needed, the app restarts itself with `runas` and passes the form values as quoted arguments (`--mode`, `--type`, `--location`, `--name`, `--target`). The old `--engage` flag is still accepted and ignored.
- The probe runs when the window loads (again on activation while admin is needed, and on Create link). If symbolic links need admin, Create link shows the UAC shield and the footer says Windows will ask for permission, so the user knows before filling in the form. Field errors take the same footer spot and hide the notice.
- The window never restarts or elevates itself, so drag and drop keeps working. When a symbolic link needs admin, `ElevateIfNeededAsync()` starts `Symlinker.exe --link-helper <pipe> <pid>` with `runas` (one UAC prompt). The helper has no window: it connects back over the named pipe and creates each link it is sent with mklink. It stays up until the window closes (or it is ended, then the next symbolic link starts a new one), so the user approves UAC once per session. While it runs, the shield and the footer notice are hidden. Only symbolic links that need admin go through it; junctions and hard links always run unelevated.
- Elevation happens before anything on disk changes (deleting an existing item, or the move-and-link flow), so declining the UAC prompt (Win32 error 1223) quietly stops and leaves everything as it was.
- Both ends check the other's process ID on the pipe (`GetNamedPipeClientProcessId` / `GetNamedPipeServerProcessId`), and `LinkCommand` rejects paths with quotes or line breaks, so the helper only ever runs a single mklink.
- Command-line options (`--mode`, `--type`, `--location`, `--name`, `--target`) still prefill the form. The old `--engage` flag is still accepted and ignored.

### Important Patterns

Expand All @@ -79,8 +85,11 @@ Symlinker/
│ ├── App.xaml(.cs) # Application, theme sync
│ ├── MainWindow.xaml # UI and styles
│ ├── MainWindow.xaml.cs # Core window logic and link creation
│ ├── MainWindow.Inputs.cs # Validation, inline errors, admin restart
│ ├── Elevation.cs # LaunchOptions and elevation helpers
│ ├── MainWindow.Inputs.cs # Validation, inline errors, admin notice
│ ├── Elevation.cs # LaunchOptions, symlink probe, UAC shield
│ ├── LinkCommand.cs # Runs mklink
│ ├── ElevatedLinker.cs # Elevated link helper over a named pipe
│ ├── LinkMover.cs # Move-and-link file system helpers
│ ├── Program.cs # Entry point
│ ├── Properties/
│ │ ├── Resources.resx # English strings
Expand All @@ -106,7 +115,7 @@ Releases are automated via GitHub Actions:

## Known Limitations

- **Drag and drop**: Works in the normal (unelevated) app. It does not work after restarting as administrator, because Windows blocks drops from a lower-privilege Explorer.
- **Drag and drop**: Works because the window always runs unelevated. It does not work if the user starts Symlinker as administrator themselves, because Windows blocks drops from a lower-privilege Explorer.
- **Platform**: Windows 10/11 only.

## Localization
Expand Down
194 changes: 194 additions & 0 deletions Symlinker/ElevatedLinker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
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;

/// <summary>
/// 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, create the link later, and keep using it for more links.
/// </summary>
internal sealed class ElevatedLinker : IDisposable
{
/// <summary>Command line switch that runs Symlinker as the helper instead of opening the window.</summary>
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 };
}

/// <summary>
/// Starts the helper as administrator. Returns null when the user cancels the UAC prompt.
/// Throws when the helper starts but can't be reached.
/// </summary>
public static async Task<ElevatedLinker> 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;
}
}

/// <summary>Whether the helper is still running and connected.</summary>
public bool IsAlive
{
get
{
try
{
return pipe.IsConnected && !process.HasExited;
}
catch (Exception)
{
return false;
}
}
}

/// <summary>Creates a link as administrator.</summary>
public async Task<LinkResult> 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<LinkResult>(line) ?? throw new IOException("The administrator helper sent an empty reply.");
}

/// <summary>Closes the connection; the helper exits when it sees that.</summary>
public void Dispose()
{
reader.Dispose();
writer.Dispose();
pipe.Dispose();
process.Dispose();
}

/// <summary>
/// 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.
/// </summary>
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<LinkRequest>(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);
}
}
90 changes: 5 additions & 85 deletions Symlinker/Elevation.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Values the window starts with. Used to carry the form over when restarting as administrator.
/// </summary>
/// <summary>Values the window starts with, read from the command line.</summary>
internal sealed class LaunchOptions
{
private const string ModeArg = "--mode";
Expand Down Expand Up @@ -58,64 +52,15 @@ public static LaunchOptions Parse(string[] args)

return options;
}

/// <summary>Builds a command line that <see cref="Parse"/> turns back into these options.</summary>
public string ToArguments()
{
var parts = new List<string>();
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);
}

/// <summary>
/// Quotes one argument so Windows splits it back exactly as given, including spaces
/// and trailing backslashes (like "C:\").
/// </summary>
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();
}
}

/// <summary>Administrator rights helpers. Symlinker runs unelevated and only asks for them when needed.</summary>
/// <summary>
/// Administrator rights helpers. Symlinker runs unelevated and only elevates the link
/// creation step when needed (see <see cref="ElevatedLinker"/>).
/// </summary>
internal static class Elevation
{
private const int ErrorPrivilegeNotHeld = 1314;
private const int ErrorCancelled = 1223;

public static bool IsElevated
{
Expand Down Expand Up @@ -155,31 +100,6 @@ public static bool CanCreateSymbolicLinks()
}
}

/// <summary>
/// Starts a new elevated instance with the given options.
/// Returns false when the user declines the UAC prompt.
/// </summary>
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;
}
}

/// <summary>
/// The Windows UAC shield (small size), shown on actions that need administrator rights.
/// Returns null if Windows doesn't provide it.
Expand Down
Loading
Loading