| 1 | using System.Security.AccessControl; |
| 2 | using System.Runtime.CompilerServices; |
| 3 | using System.Security.Principal; |
| 4 | using System.Text.Json; |
| 5 | using System.Text.RegularExpressions; |
| 6 | |
| 7 | namespace Cage.GuestClipboard; |
| 8 | |
| 9 | internal static class GuestDiagnostics |
| 10 | { |
| 11 | private const long FileBytes = 1 << 20; |
| 12 | private static readonly object Sync = new(); |
| 13 | private static readonly Regex Code = new("^[a-zA-Z][a-zA-Z0-9_]{0,95}$", RegexOptions.CultureInvariant); |
| 14 | private static string last = ""; |
| 15 | private static DateTime lastAt; |
| 16 | |
| 17 | private static IEnumerable<string> Files(string directory) => Enumerable.Range(0, 10) |
| 18 | .Select(index => Path.Combine(directory, index == 0 ? "events.jsonl" : $"events-{index}.jsonl")) |
| 19 | .Where(File.Exists); |
| 20 | |
| 21 | [ModuleInitializer] |
| 22 | internal static void Register() => GuestOperations.Register("diagnostics", Read); |
| 23 | |
| 24 | private static string DirectoryPath() |
| 25 | { |
| 26 | var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Cage", "Diagnostics"); |
| 27 | foreach (var current in new[] { Path.GetDirectoryName(directory)!, directory }) |
| 28 | { |
| 29 | Directory.CreateDirectory(current); |
| 30 | if (new DirectoryInfo(current).Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new IOException("diagnostic_path_invalid"); |
| 31 | } |
| 32 | using var identity = WindowsIdentity.GetCurrent(); |
| 33 | var acl = new DirectorySecurity(); |
| 34 | acl.SetAccessRuleProtection(true, false); |
| 35 | foreach (var sid in new[] { identity.User!, new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null) }) |
| 36 | acl.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.FullControl, |
| 37 | InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); |
| 38 | new DirectoryInfo(directory).SetAccessControl(acl); |
| 39 | return directory; |
| 40 | } |
| 41 | |
| 42 | private static void Clean(string directory) |
| 43 | { |
| 44 | foreach (var file in Files(directory)) |
| 45 | { |
| 46 | var info = new FileInfo(file); |
| 47 | if (info.Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new IOException("diagnostic_path_invalid"); |
| 48 | if (info.LastWriteTimeUtc < DateTime.UtcNow.AddDays(-14)) File.Delete(file); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | internal static void Record(string source, string reason) |
| 53 | { |
| 54 | if (!Code.IsMatch(source) || !Code.IsMatch(reason)) return; |
| 55 | try |
| 56 | { |
| 57 | lock (Sync) |
| 58 | { |
| 59 | var now = DateTime.UtcNow; |
| 60 | var key = source + "/" + reason; |
| 61 | if (key == last && now - lastAt < TimeSpan.FromSeconds(5)) return; |
| 62 | var directory = DirectoryPath(); |
| 63 | Clean(directory); |
| 64 | var file = Path.Combine(directory, "events.jsonl"); |
| 65 | var entry = JsonSerializer.Serialize(new { time = now, source, reason }) + "\n"; |
| 66 | if (File.Exists(file) && (new FileInfo(file).Length + Protocol.Utf8.GetByteCount(entry) > FileBytes || File.GetCreationTimeUtc(file).Date != now.Date)) |
| 67 | { |
| 68 | for (var index = 9; index >= 1; index--) |
| 69 | { |
| 70 | var old = Path.Combine(directory, index == 1 ? "events.jsonl" : $"events-{index - 1}.jsonl"); |
| 71 | var target = Path.Combine(directory, $"events-{index}.jsonl"); |
| 72 | if (File.Exists(old)) File.Move(old, target, true); |
| 73 | } |
| 74 | } |
| 75 | File.AppendAllText(file, entry, Protocol.Utf8); |
| 76 | last = key; |
| 77 | lastAt = now; |
| 78 | } |
| 79 | } |
| 80 | catch { } |
| 81 | } |
| 82 | |
| 83 | internal static void Failure(string source, Exception error) => Record(source, error.GetType().Name); |
| 84 | |
| 85 | private static async Task Read(Stream stream, CancellationToken token, Func<bool> available) |
| 86 | { |
| 87 | var request = await Protocol.Read(stream, 1024, token); |
| 88 | if (request?["action"]?.GetValue<string>() != "read") throw new InvalidDataException("diagnostic_request_invalid"); |
| 89 | var lines = new Queue<string>(); |
| 90 | var bytes = 0; |
| 91 | lock (Sync) |
| 92 | { |
| 93 | var directory = DirectoryPath(); |
| 94 | Clean(directory); |
| 95 | |
| 96 | foreach (var file in Files(directory).Reverse()) |
| 97 | { |
| 98 | if (new FileInfo(file).Length > FileBytes + 4096) continue; |
| 99 | foreach (var line in File.ReadLines(file, Protocol.Utf8)) |
| 100 | { |
| 101 | if (line.Length > 4096) continue; |
| 102 | try |
| 103 | { |
| 104 | using var item = JsonDocument.Parse(line); |
| 105 | var value = item.RootElement; |
| 106 | var source = value.GetProperty("source").GetString() ?? ""; |
| 107 | var reason = value.GetProperty("reason").GetString() ?? ""; |
| 108 | var time = value.GetProperty("time").GetDateTime(); |
| 109 | if (!Code.IsMatch(source) || !Code.IsMatch(reason) || time < DateTime.UtcNow.AddDays(-14)) continue; |
| 110 | var safe = JsonSerializer.Serialize(new { time, source, reason }) + "\n"; |
| 111 | lines.Enqueue(safe); |
| 112 | bytes += Protocol.Utf8.GetByteCount(safe); |
| 113 | while (lines.Count > 150 || bytes > 48 << 10) bytes -= Protocol.Utf8.GetByteCount(lines.Dequeue()); |
| 114 | } |
| 115 | catch (Exception error) when (error is JsonException or InvalidOperationException or KeyNotFoundException or FormatException) { } |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | await Protocol.Write(stream, new() { ["version"] = 1, ["lines"] = string.Concat(lines) }, token); |
| 120 | } |
| 121 | } |