|
| 1 | +using System.Text; |
| 2 | + |
| 3 | +namespace OpenClaw.SetupEngine; |
| 4 | + |
| 5 | +internal static class DistroInstallPathPolicy |
| 6 | +{ |
| 7 | + public const string LegacyReplacementGuidance = |
| 8 | + "To replace an existing distro with an unsupported legacy name, rerun SetupEngine with --uninstall --confirm-destructive and the same distro name, then rerun setup with a supported name."; |
| 9 | + |
| 10 | + private const int MaxDistroNameLength = 64; |
| 11 | + private const StringComparison PathComparison = StringComparison.OrdinalIgnoreCase; |
| 12 | + private static readonly char[] InvalidFileNameChars = Path.GetInvalidFileNameChars(); |
| 13 | + private static readonly HashSet<string> ReservedDeviceNames = new(StringComparer.OrdinalIgnoreCase) |
| 14 | + { |
| 15 | + "CON", "PRN", "AUX", "NUL", |
| 16 | + "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", |
| 17 | + "COM¹", "COM²", "COM³", |
| 18 | + "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", |
| 19 | + "LPT¹", "LPT²", "LPT³", |
| 20 | + }; |
| 21 | + |
| 22 | + public static bool TryGetNewInstallPath( |
| 23 | + string localDataDir, |
| 24 | + string? distroName, |
| 25 | + out string installPath, |
| 26 | + out string error) |
| 27 | + { |
| 28 | + installPath = ""; |
| 29 | + |
| 30 | + if (string.IsNullOrWhiteSpace(distroName)) |
| 31 | + { |
| 32 | + error = "WSL distro name is required."; |
| 33 | + return false; |
| 34 | + } |
| 35 | + |
| 36 | + if (!IsValidDistroName(distroName)) |
| 37 | + { |
| 38 | + error = $"Invalid WSL distro name '{distroName}'. Use 1-{MaxDistroNameLength} ASCII letters, digits, periods, underscores, or hyphens, starting and ending with a letter or digit."; |
| 39 | + return false; |
| 40 | + } |
| 41 | + |
| 42 | + return TryGetManagedInstallPath(localDataDir, distroName, out installPath, out error); |
| 43 | + } |
| 44 | + |
| 45 | + public static bool TryGetManagedInstallPath( |
| 46 | + string localDataDir, |
| 47 | + string? distroName, |
| 48 | + out string installPath, |
| 49 | + out string error) |
| 50 | + { |
| 51 | + installPath = ""; |
| 52 | + |
| 53 | + if (!IsSafeManagedPathSegment(distroName, out error)) |
| 54 | + return false; |
| 55 | + |
| 56 | + string localDataRoot; |
| 57 | + string wslRoot; |
| 58 | + try |
| 59 | + { |
| 60 | + localDataRoot = NormalizePath(localDataDir); |
| 61 | + wslRoot = NormalizePath(Path.Combine(localDataRoot, "wsl")); |
| 62 | + installPath = NormalizePath(Path.Combine(wslRoot, distroName!)); |
| 63 | + } |
| 64 | + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) |
| 65 | + { |
| 66 | + installPath = ""; |
| 67 | + error = $"Invalid WSL distro install path: {ex.Message}"; |
| 68 | + return false; |
| 69 | + } |
| 70 | + |
| 71 | + if (!PathEquals(Path.GetDirectoryName(installPath), wslRoot)) |
| 72 | + { |
| 73 | + error = $"WSL distro install path '{installPath}' must be an immediate child of '{wslRoot}'."; |
| 74 | + installPath = ""; |
| 75 | + return false; |
| 76 | + } |
| 77 | + |
| 78 | + if (!TryValidateAncestors(localDataRoot, wslRoot, out error)) |
| 79 | + { |
| 80 | + installPath = ""; |
| 81 | + return false; |
| 82 | + } |
| 83 | + |
| 84 | + if (TryResolveUnambiguousManagedChild(wslRoot, distroName!, ref installPath, out error)) |
| 85 | + return true; |
| 86 | + |
| 87 | + installPath = ""; |
| 88 | + return false; |
| 89 | + } |
| 90 | + |
| 91 | + public static string WithLegacyReplacementGuidance(string? distroName, string error) |
| 92 | + => IsLegacyTeardownOnlyName(distroName) |
| 93 | + ? $"{error} {LegacyReplacementGuidance}" |
| 94 | + : error; |
| 95 | + |
| 96 | + public static bool TryValidateDeleteTarget( |
| 97 | + string localDataDir, |
| 98 | + string? distroName, |
| 99 | + string candidatePath, |
| 100 | + out string deletePath, |
| 101 | + out string error) |
| 102 | + { |
| 103 | + if (!TryGetManagedInstallPath(localDataDir, distroName, out deletePath, out error)) |
| 104 | + return false; |
| 105 | + |
| 106 | + string candidate; |
| 107 | + try |
| 108 | + { |
| 109 | + candidate = NormalizePath(candidatePath); |
| 110 | + } |
| 111 | + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) |
| 112 | + { |
| 113 | + error = $"Invalid WSL distro deletion path: {ex.Message}"; |
| 114 | + return false; |
| 115 | + } |
| 116 | + |
| 117 | + if (!PathEquals(candidate, deletePath)) |
| 118 | + { |
| 119 | + error = $"Refusing to delete WSL path '{candidate}'; expected the app-owned distro path '{deletePath}'."; |
| 120 | + return false; |
| 121 | + } |
| 122 | + |
| 123 | + return true; |
| 124 | + } |
| 125 | + |
| 126 | + private static bool TryValidateAncestors(string localDataRoot, string wslRoot, out string error) |
| 127 | + { |
| 128 | + string? current = wslRoot; |
| 129 | + while (current is not null) |
| 130 | + { |
| 131 | + if (!TryGetExistingAttributes(current, out var exists, out var attributes, out error)) |
| 132 | + return false; |
| 133 | + |
| 134 | + if (exists && attributes.HasFlag(FileAttributes.ReparsePoint)) |
| 135 | + { |
| 136 | + error = $"Refusing to operate under '{current}' because it is a reparse point; remove it manually and retry setup."; |
| 137 | + return false; |
| 138 | + } |
| 139 | + |
| 140 | + if (PathEquals(current, wslRoot) && |
| 141 | + exists && |
| 142 | + !attributes.HasFlag(FileAttributes.Directory)) |
| 143 | + { |
| 144 | + error = $"App-owned WSL root '{current}' is not a directory; remove it manually and retry setup."; |
| 145 | + return false; |
| 146 | + } |
| 147 | + |
| 148 | + if (PathEquals(current, localDataRoot)) |
| 149 | + { |
| 150 | + error = ""; |
| 151 | + return true; |
| 152 | + } |
| 153 | + |
| 154 | + current = Path.GetDirectoryName(current); |
| 155 | + } |
| 156 | + |
| 157 | + error = $"WSL install path '{wslRoot}' is not contained within '{localDataRoot}'."; |
| 158 | + return false; |
| 159 | + } |
| 160 | + |
| 161 | + private static bool TryResolveUnambiguousManagedChild( |
| 162 | + string wslRoot, |
| 163 | + string distroName, |
| 164 | + ref string installPath, |
| 165 | + out string error) |
| 166 | + { |
| 167 | + if (!Directory.Exists(wslRoot)) |
| 168 | + { |
| 169 | + error = ""; |
| 170 | + return true; |
| 171 | + } |
| 172 | + |
| 173 | + string[] children; |
| 174 | + try |
| 175 | + { |
| 176 | + children = Directory.GetFileSystemEntries(wslRoot); |
| 177 | + } |
| 178 | + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException) |
| 179 | + { |
| 180 | + error = $"Cannot enumerate app-owned WSL root '{wslRoot}': {ex.Message}"; |
| 181 | + return false; |
| 182 | + } |
| 183 | + |
| 184 | + var requestedNormalized = distroName.Normalize(NormalizationForm.FormC); |
| 185 | + var caseMatches = children |
| 186 | + .Where(path => string.Equals(Path.GetFileName(path), distroName, PathComparison)) |
| 187 | + .ToArray(); |
| 188 | + var normalizationMatches = children |
| 189 | + .Where(path => string.Equals( |
| 190 | + Path.GetFileName(path).Normalize(NormalizationForm.FormC), |
| 191 | + requestedNormalized, |
| 192 | + PathComparison)) |
| 193 | + .ToArray(); |
| 194 | + |
| 195 | + if (caseMatches.Length > 1 || normalizationMatches.Length > 1) |
| 196 | + { |
| 197 | + error = $"Managed WSL distro name '{distroName}' is ambiguous because multiple app-owned path entries differ only by case or Unicode normalization."; |
| 198 | + return false; |
| 199 | + } |
| 200 | + |
| 201 | + if (caseMatches.Length == 0 && normalizationMatches.Length == 1) |
| 202 | + { |
| 203 | + error = $"Managed WSL distro name '{distroName}' aliases existing app-owned path entry '{Path.GetFileName(normalizationMatches[0])}'; use the exact stored name."; |
| 204 | + return false; |
| 205 | + } |
| 206 | + |
| 207 | + if (caseMatches.Length == 1) |
| 208 | + installPath = NormalizePath(caseMatches[0]); |
| 209 | + |
| 210 | + if (!TryGetExistingAttributes(installPath, out var exists, out var attributes, out error)) |
| 211 | + return false; |
| 212 | + |
| 213 | + if (exists && caseMatches.Length == 0) |
| 214 | + { |
| 215 | + error = $"Managed WSL distro name '{distroName}' resolves through a filesystem alias instead of an exact app-owned path entry."; |
| 216 | + return false; |
| 217 | + } |
| 218 | + |
| 219 | + if (exists && attributes.HasFlag(FileAttributes.ReparsePoint)) |
| 220 | + { |
| 221 | + error = $"App-owned WSL path '{installPath}' is a reparse point; remove it manually and retry setup."; |
| 222 | + return false; |
| 223 | + } |
| 224 | + |
| 225 | + error = ""; |
| 226 | + return true; |
| 227 | + } |
| 228 | + |
| 229 | + private static bool TryGetExistingAttributes( |
| 230 | + string path, |
| 231 | + out bool exists, |
| 232 | + out FileAttributes attributes, |
| 233 | + out string error) |
| 234 | + { |
| 235 | + try |
| 236 | + { |
| 237 | + attributes = File.GetAttributes(path); |
| 238 | + exists = true; |
| 239 | + error = ""; |
| 240 | + return true; |
| 241 | + } |
| 242 | + catch (FileNotFoundException) |
| 243 | + { |
| 244 | + attributes = default; |
| 245 | + exists = false; |
| 246 | + error = ""; |
| 247 | + return true; |
| 248 | + } |
| 249 | + catch (DirectoryNotFoundException) |
| 250 | + { |
| 251 | + attributes = default; |
| 252 | + exists = false; |
| 253 | + error = ""; |
| 254 | + return true; |
| 255 | + } |
| 256 | + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException) |
| 257 | + { |
| 258 | + attributes = default; |
| 259 | + exists = false; |
| 260 | + error = $"Cannot verify managed WSL path '{path}': {ex.Message}"; |
| 261 | + return false; |
| 262 | + } |
| 263 | + } |
| 264 | + |
| 265 | + private static bool IsValidDistroName(string name) |
| 266 | + => name.Length <= MaxDistroNameLength && |
| 267 | + char.IsAsciiLetterOrDigit(name[0]) && |
| 268 | + char.IsAsciiLetterOrDigit(name[^1]) && |
| 269 | + name.All(IsAllowedDistroNameCharacter); |
| 270 | + |
| 271 | + private static bool IsAllowedDistroNameCharacter(char value) |
| 272 | + => char.IsAsciiLetterOrDigit(value) || value is '.' or '_' or '-'; |
| 273 | + |
| 274 | + private static bool IsLegacyTeardownOnlyName(string? name) |
| 275 | + => !string.IsNullOrWhiteSpace(name) && |
| 276 | + !IsValidDistroName(name) && |
| 277 | + IsSafeManagedPathSegment(name, out _); |
| 278 | + |
| 279 | + private static bool IsSafeManagedPathSegment(string? name, out string error) |
| 280 | + { |
| 281 | + if (string.IsNullOrWhiteSpace(name)) |
| 282 | + { |
| 283 | + error = "WSL distro name is required."; |
| 284 | + return false; |
| 285 | + } |
| 286 | + |
| 287 | + if (!string.Equals(name, name.Trim(), StringComparison.Ordinal) || |
| 288 | + name.EndsWith('.') || |
| 289 | + name is "." or ".." || |
| 290 | + Path.IsPathRooted(name) || |
| 291 | + name.IndexOfAny(InvalidFileNameChars) >= 0 || |
| 292 | + name.Contains(Path.DirectorySeparatorChar) || |
| 293 | + name.Contains(Path.AltDirectorySeparatorChar) || |
| 294 | + IsReservedDeviceName(name)) |
| 295 | + { |
| 296 | + error = $"Invalid managed WSL distro name '{name}'. The name must be one unambiguous Windows path segment."; |
| 297 | + return false; |
| 298 | + } |
| 299 | + |
| 300 | + error = ""; |
| 301 | + return true; |
| 302 | + } |
| 303 | + |
| 304 | + private static bool IsReservedDeviceName(string name) |
| 305 | + { |
| 306 | + var stem = name.Split('.')[0].TrimEnd(' ', '.'); |
| 307 | + return ReservedDeviceNames.Contains(stem); |
| 308 | + } |
| 309 | + |
| 310 | + private static string NormalizePath(string path) |
| 311 | + => Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); |
| 312 | + |
| 313 | + private static bool PathEquals(string? left, string right) |
| 314 | + => string.Equals(left, right, PathComparison); |
| 315 | +} |
0 commit comments