| 1 | using System.Text; |
| 2 | using System.Text.Json; |
| 3 | |
| 4 | namespace Cage.GuestClipboard; |
| 5 | |
| 6 | |
| 7 | |
| 8 | internal static class WindowsEditorPreferences |
| 9 | { |
| 10 | internal const string TrustKey = "security.workspace.trust.enabled"; |
| 11 | internal static bool? TrustDefault(string cageEditorHome) |
| 12 | { |
| 13 | var user = Path.Combine(cageEditorHome, "User"); |
| 14 | if (Directory.Exists(cageEditorHome) && new DirectoryInfo(cageEditorHome).Attributes.HasFlag(FileAttributes.ReparsePoint) || Directory.Exists(user) && new DirectoryInfo(user).Attributes.HasFlag(FileAttributes.ReparsePoint)) |
| 15 | throw new InvalidDataException("editor_package_invalid"); |
| 16 | Directory.CreateDirectory(user); |
| 17 | var file = Path.Combine(user, "settings.json"); |
| 18 | var original = "{}"; |
| 19 | if (File.Exists(file)) |
| 20 | { |
| 21 | var info = new FileInfo(file); |
| 22 | if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.Length > 1 << 20) return null; |
| 23 | using var snapshot = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); |
| 24 | if (snapshot.Length > 1 << 20) return null; |
| 25 | using var reader = new StreamReader(snapshot); |
| 26 | original = reader.ReadToEnd(); |
| 27 | } |
| 28 | try |
| 29 | { |
| 30 | using var document = JsonDocument.Parse(original, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }); |
| 31 | if (document.RootElement.ValueKind != JsonValueKind.Object) return null; |
| 32 | if (document.RootElement.TryGetProperty(TrustKey, out var existing)) |
| 33 | return existing.ValueKind is JsonValueKind.True or JsonValueKind.False ? existing.GetBoolean() : null; |
| 34 | |
| 35 | |
| 36 | var bytes = Encoding.UTF8.GetBytes(original); |
| 37 | var reader = new Utf8JsonReader(bytes, new JsonReaderOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }); |
| 38 | if (!reader.Read() || reader.TokenType != JsonTokenType.StartObject) return null; |
| 39 | var offset = Encoding.UTF8.GetCharCount(bytes.AsSpan(0, (int)reader.BytesConsumed)); |
| 40 | var property = "\n \"" + TrustKey + "\": false" + (document.RootElement.EnumerateObject().Any() ? "," : "") + "\n"; |
| 41 | var updated = original.Insert(offset, property); |
| 42 | var temporary = file + "." + Guid.NewGuid().ToString("N") + ".tmp"; |
| 43 | try |
| 44 | { |
| 45 | File.WriteAllText(temporary, updated, new UTF8Encoding(false)); |
| 46 | WindowsFilePublication.Replace(temporary, file, default).GetAwaiter().GetResult(); |
| 47 | } |
| 48 | finally { if (File.Exists(temporary)) File.Delete(temporary); } |
| 49 | return false; |
| 50 | } |
| 51 | catch (JsonException) { return null; } |
| 52 | } |
| 53 | } |