Skip to content

Commit 402385f

Browse files
authored
Resolve junctions in the elevated WinGet TEMP folder (#5526)
1 parent dc4e328 commit 402385f

8 files changed

Lines changed: 312 additions & 31 deletions

File tree

‎src/UniGetUI.Core.Logger/AppPaths.cs‎

Lines changed: 194 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,28 @@
1+
using System.Diagnostics;
2+
using System.Runtime.InteropServices;
3+
using Microsoft.Win32.SafeHandles;
4+
15
namespace UniGetUI.Core.Logging
26
{
3-
public static class AppPaths
7+
public static partial class AppPaths
48
{
59
private const string PortableMarkerFileName = "ForceUniGetUIPortable";
610
private const string PortableDataDirectoryName = "Settings";
711
private const string PortablePermissionTestFileName = "PermissionTestFile";
812
private const string PortableScratchDirectoryName = "Temp";
913
private const string FirstRunMarkerFileName = "FirstRun.pending";
1014
private const string ScratchDirectoryName = "UniGetUI";
15+
private const string ElevatedTempDirectoryName = "ElevatedWinGetTemp";
16+
private const uint FileReadAttributes = 0x00000080;
17+
private const uint FileShareAll = 0x00000007;
18+
private const uint OpenExisting = 3;
19+
private const uint FileFlagBackupSemantics = 0x02000000;
20+
private const uint FileNameNormalized = 0x00000000;
21+
private const uint VolumeNameGuid = 0x00000001;
22+
private const string VolumeGuidPathPrefix = @"\\?\Volume{";
23+
private const int PathBufferLength = 1024;
24+
private const string ExtendedPathPrefix = @"\\?\";
25+
private const string ExtendedUncPathPrefix = @"\\?\UNC\";
1126
private const string BundledModernAppDirectoryName = "Avalonia";
1227
private const string WindowsExecutableName = "UniGetUI.exe";
1328
private const string BundledPingetExecutableName = "pinget.exe";
@@ -16,6 +31,7 @@ public static class AppPaths
1631
private static string? __installation_directory;
1732
private static volatile bool __portable_mode_resolved;
1833
private static string? __portable_data_directory;
34+
private static ElevatedTempDirectoryCache? __elevated_temp_directory;
1935

2036
[ThreadStatic]
2137
private static bool __resolving_portable_mode;
@@ -109,6 +125,183 @@ PortableDataDirectory is { } portableDirectory
109125
? Path.Join(portableDirectory, PortableScratchDirectoryName)
110126
: Path.Join(Path.GetTempPath(), ScratchDirectoryName);
111127

128+
public static string ElevatedTempDirectory
129+
{
130+
get
131+
{
132+
string unresolved = Path.Join(ScratchDirectory, ElevatedTempDirectoryName);
133+
if (__elevated_temp_directory is { } cached && cached.Unresolved == unresolved)
134+
return cached.Resolved;
135+
136+
if (!TryResolveLinkedDirectories(unresolved, out string resolved))
137+
return resolved;
138+
139+
__elevated_temp_directory = new ElevatedTempDirectoryCache(unresolved, resolved);
140+
return resolved;
141+
}
142+
}
143+
144+
private sealed record ElevatedTempDirectoryCache(string Unresolved, string Resolved);
145+
146+
public static string RedirectTempToElevatedDirectory(ProcessStartInfo startInfo)
147+
{
148+
string directory = ElevatedTempDirectory;
149+
try
150+
{
151+
Directory.CreateDirectory(directory);
152+
}
153+
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
154+
{
155+
Logger.Warn($"Could not create the elevated temporary directory {directory}");
156+
Logger.Warn(ex);
157+
}
158+
159+
startInfo.Environment["TEMP"] = directory;
160+
startInfo.Environment["TMP"] = directory;
161+
return directory;
162+
}
163+
164+
public static string ResolveLinkedDirectories(string path)
165+
{
166+
TryResolveLinkedDirectories(path, out string resolved);
167+
return resolved;
168+
}
169+
170+
private static bool TryResolveLinkedDirectories(string path, out string resolved)
171+
{
172+
string fullPath = Path.GetFullPath(path);
173+
resolved = fullPath;
174+
if (!OperatingSystem.IsWindows())
175+
return true;
176+
177+
string existing = fullPath;
178+
while (!Directory.Exists(existing))
179+
{
180+
string? parent = Path.GetDirectoryName(existing);
181+
if (parent is null)
182+
return false;
183+
existing = parent;
184+
}
185+
186+
string? finalPath = GetFinalDirectoryPath(existing);
187+
if (finalPath is null)
188+
{
189+
Logger.Warn($"Could not resolve the links in {existing}, using the path as-is");
190+
return false;
191+
}
192+
193+
resolved = Path.Join(finalPath, fullPath[existing.Length..]);
194+
return true;
195+
}
196+
197+
private static string? GetFinalDirectoryPath(string directory)
198+
{
199+
using SafeFileHandle handle = CreateFile(
200+
directory,
201+
FileReadAttributes,
202+
FileShareAll,
203+
0,
204+
OpenExisting,
205+
FileFlagBackupSemantics,
206+
0
207+
);
208+
if (handle.IsInvalid)
209+
return null;
210+
211+
if (GetFinalPathName(handle, FileNameNormalized) is { } dosPath)
212+
return StripExtendedPathPrefix(dosPath);
213+
214+
if (
215+
GetFinalPathName(handle, VolumeNameGuid) is not { } guidPath
216+
|| !guidPath.StartsWith(VolumeGuidPathPrefix, StringComparison.OrdinalIgnoreCase)
217+
)
218+
return null;
219+
220+
int volumeEnd = guidPath.IndexOf('\\', VolumeGuidPathPrefix.Length);
221+
if (volumeEnd < 0)
222+
return null;
223+
224+
string? mountPath = GetVolumeMountPath(guidPath[..(volumeEnd + 1)]);
225+
return mountPath is null ? null : Path.Join(mountPath, guidPath[(volumeEnd + 1)..]);
226+
}
227+
228+
private static string? GetFinalPathName(SafeFileHandle handle, uint flags)
229+
{
230+
char[] buffer = new char[PathBufferLength];
231+
uint length = GetFinalPathNameByHandle(handle, ref buffer[0], (uint)buffer.Length, flags);
232+
if (length >= buffer.Length)
233+
{
234+
buffer = new char[length];
235+
length = GetFinalPathNameByHandle(handle, ref buffer[0], (uint)buffer.Length, flags);
236+
}
237+
238+
return length is 0 || length >= buffer.Length ? null : new string(buffer, 0, (int)length);
239+
}
240+
241+
private static string? GetVolumeMountPath(string volumeName)
242+
{
243+
char[] buffer = new char[PathBufferLength];
244+
if (!GetVolumePathNamesForVolumeName(volumeName, ref buffer[0], (uint)buffer.Length, out uint required))
245+
{
246+
if (required <= buffer.Length)
247+
return null;
248+
249+
buffer = new char[required];
250+
if (!GetVolumePathNamesForVolumeName(volumeName, ref buffer[0], (uint)buffer.Length, out _))
251+
return null;
252+
}
253+
254+
int end = Array.IndexOf(buffer, '\0');
255+
return end > 0 ? new string(buffer, 0, end) : null;
256+
}
257+
258+
private static string StripExtendedPathPrefix(string path)
259+
{
260+
if (path.StartsWith(ExtendedUncPathPrefix, StringComparison.Ordinal))
261+
return @"\\" + path[ExtendedUncPathPrefix.Length..];
262+
263+
return path.StartsWith(ExtendedPathPrefix, StringComparison.Ordinal)
264+
? path[ExtendedPathPrefix.Length..]
265+
: path;
266+
}
267+
268+
[LibraryImport(
269+
"kernel32.dll",
270+
EntryPoint = "CreateFileW",
271+
SetLastError = true,
272+
StringMarshalling = StringMarshalling.Utf16)]
273+
private static partial SafeFileHandle CreateFile(
274+
string fileName,
275+
uint desiredAccess,
276+
uint shareMode,
277+
nint securityAttributes,
278+
uint creationDisposition,
279+
uint flagsAndAttributes,
280+
nint templateFile);
281+
282+
[LibraryImport(
283+
"kernel32.dll",
284+
EntryPoint = "GetFinalPathNameByHandleW",
285+
SetLastError = true,
286+
StringMarshalling = StringMarshalling.Utf16)]
287+
private static partial uint GetFinalPathNameByHandle(
288+
SafeFileHandle file,
289+
ref char filePath,
290+
uint charCount,
291+
uint flags);
292+
293+
[LibraryImport(
294+
"kernel32.dll",
295+
EntryPoint = "GetVolumePathNamesForVolumeNameW",
296+
SetLastError = true,
297+
StringMarshalling = StringMarshalling.Utf16)]
298+
[return: MarshalAs(UnmanagedType.Bool)]
299+
private static partial bool GetVolumePathNamesForVolumeName(
300+
string volumeName,
301+
ref char volumePathNames,
302+
uint bufferLength,
303+
out uint returnLength);
304+
112305
public static string ResolveInstallationDirectory(
113306
string executableDirectory,
114307
Func<string, bool>? fileExists = null,

‎src/UniGetUI.Core.Logger/UniGetUI.Core.Logging.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
<Project Sdk="Microsoft.NET.Sdk">
22
<PropertyGroup>
33
<TargetFrameworks>$(SharedTargetFrameworks)</TargetFrameworks>
4+
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
45
</PropertyGroup>
56

67
<ItemGroup>

‎src/UniGetUI.Core.Logging.Tests/AppPathsTests.cs‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
using System.Diagnostics;
2+
13
[assembly: CollectionBehavior(DisableTestParallelization = true)]
24

35
namespace UniGetUI.Core.Logging.Tests
@@ -125,6 +127,111 @@ public void ScratchDirectoryMovesIntoThePortableFolderWhenPortable()
125127
Assert.Equal(Path.Join(portableDirectory, "Temp"), AppPaths.ScratchDirectory);
126128
}
127129

130+
[Fact]
131+
public void ResolveLinkedDirectoriesKeepsTheMissingTailOfAPlainPath()
132+
{
133+
Directory.CreateDirectory(Path.Join(_testRoot, "Settings"));
134+
string root = AppPaths.ResolveLinkedDirectories(_testRoot);
135+
136+
Assert.Equal(
137+
Path.Join(root, "Settings", "Temp", "ElevatedWinGetTemp"),
138+
AppPaths.ResolveLinkedDirectories(Path.Join(_testRoot, "Settings", "Temp", "ElevatedWinGetTemp")));
139+
}
140+
141+
[Fact]
142+
public void ResolveLinkedDirectoriesFollowsScoopJunctions()
143+
{
144+
if (!OperatingSystem.IsWindows())
145+
return;
146+
147+
string persisted = Path.Join(_testRoot, "persist", "unigetui", "Settings");
148+
string version = Path.Join(_testRoot, "apps", "unigetui", "2026.3.1");
149+
Directory.CreateDirectory(Path.Join(persisted, "Temp"));
150+
Directory.CreateDirectory(version);
151+
string settingsJunction = Path.Join(version, "Settings");
152+
string currentJunction = Path.Join(_testRoot, "apps", "unigetui", "current");
153+
try
154+
{
155+
CreateJunction(settingsJunction, persisted);
156+
CreateJunction(currentJunction, version);
157+
158+
string resolved = AppPaths.ResolveLinkedDirectories(
159+
Path.Join(currentJunction, "Settings", "Temp", "ElevatedWinGetTemp"));
160+
161+
Assert.Equal(
162+
Path.Join(AppPaths.ResolveLinkedDirectories(persisted), "Temp", "ElevatedWinGetTemp"),
163+
resolved);
164+
}
165+
finally
166+
{
167+
foreach (string junction in new[] { currentJunction, settingsJunction })
168+
{
169+
if (Directory.Exists(junction))
170+
Directory.Delete(junction);
171+
}
172+
}
173+
}
174+
175+
[Fact]
176+
public void ResolveLinkedDirectoriesFollowsSymbolicLinks()
177+
{
178+
if (!OperatingSystem.IsWindows())
179+
return;
180+
181+
string persisted = Path.Join(_testRoot, "persist", "unigetui", "Settings");
182+
string version = Path.Join(_testRoot, "apps", "unigetui", "2026.3.1");
183+
Directory.CreateDirectory(Path.Join(persisted, "Temp"));
184+
Directory.CreateDirectory(version);
185+
try
186+
{
187+
Directory.CreateSymbolicLink(Path.Join(version, "Settings"), persisted);
188+
Directory.CreateSymbolicLink(Path.Join(_testRoot, "apps", "unigetui", "current"), version);
189+
}
190+
catch (IOException ex) when (ex.HResult == ErrorPrivilegeNotHeld)
191+
{
192+
return;
193+
}
194+
195+
string resolved = AppPaths.ResolveLinkedDirectories(
196+
Path.Join(_testRoot, "apps", "unigetui", "current", "Settings", "Temp"));
197+
198+
Assert.Equal(Path.Join(AppPaths.ResolveLinkedDirectories(persisted), "Temp"), resolved);
199+
}
200+
201+
[Fact]
202+
public void RedirectTempToElevatedDirectorySetsTempAndTmp()
203+
{
204+
AppPaths.TEST_PortableDataDirectoryOverride = Path.Combine(_testRoot, "Settings");
205+
ProcessStartInfo startInfo = new();
206+
207+
string directory = AppPaths.RedirectTempToElevatedDirectory(startInfo);
208+
209+
Assert.Equal(AppPaths.ElevatedTempDirectory, directory);
210+
Assert.Equal(directory, startInfo.Environment["TEMP"]);
211+
Assert.Equal(directory, startInfo.Environment["TMP"]);
212+
Assert.EndsWith(Path.Join("Settings", "Temp", "ElevatedWinGetTemp"), directory);
213+
Assert.True(Directory.Exists(directory));
214+
}
215+
216+
private const int ErrorPrivilegeNotHeld = unchecked((int)0x80070522);
217+
218+
private static void CreateJunction(string link, string target)
219+
{
220+
ProcessStartInfo startInfo = new("cmd.exe")
221+
{
222+
UseShellExecute = false,
223+
CreateNoWindow = true,
224+
RedirectStandardOutput = true,
225+
};
226+
foreach (string argument in new[] { "/c", "mklink", "/J", link, target })
227+
startInfo.ArgumentList.Add(argument);
228+
229+
using Process process = Process.Start(startInfo)!;
230+
process.StandardOutput.ReadToEnd();
231+
process.WaitForExit();
232+
Assert.Equal(0, process.ExitCode);
233+
}
234+
128235
[Fact]
129236
public void SessionLogIsWrittenInsideThePortableFolderWhenPortable()
130237
{

‎src/UniGetUI.PackageEngine.Managers.WinGet/ClientHelpers/PingetCliHelper.cs‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -216,12 +216,10 @@ private T RunJson<T>(LoggableTaskType taskType, string arguments)
216216

217217
if (CoreTools.IsAdministrator())
218218
{
219-
string winGetTemp = Path.Join(AppPaths.ScratchDirectory, "ElevatedWinGetTemp");
219+
string winGetTemp = AppPaths.RedirectTempToElevatedDirectory(process.StartInfo);
220220
logger.AddToStdErr(
221221
$"[WARN] Redirecting %TEMP% folder to {winGetTemp}, since UniGetUI was run as admin"
222222
);
223-
process.StartInfo.Environment["TEMP"] = winGetTemp;
224-
process.StartInfo.Environment["TMP"] = winGetTemp;
225223
}
226224

227225
process.Start();

‎src/UniGetUI.PackageEngine.Managers.WinGet/ClientHelpers/PingetPackageDetailsProvider.cs‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -180,12 +180,10 @@ private string RunPinget(IReadOnlyList<string> arguments, INativeTaskLogger logg
180180

181181
if (CoreTools.IsAdministrator())
182182
{
183-
string winGetTemp = Path.Join(AppPaths.ScratchDirectory, "ElevatedWinGetTemp");
183+
string winGetTemp = AppPaths.RedirectTempToElevatedDirectory(process.StartInfo);
184184
logger.Log(
185185
$"[WARN] Redirecting %TEMP% folder to {winGetTemp}, since UniGetUI was run as admin"
186186
);
187-
process.StartInfo.Environment["TEMP"] = winGetTemp;
188-
process.StartInfo.Environment["TMP"] = winGetTemp;
189187
}
190188

191189
process.Start();

0 commit comments

Comments
 (0)