跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

WindowsDesktopDownloads.cs

362 行 · 19.0 KB历史下载
1using System.Security.AccessControl;
2using System.Security.Cryptography;
3using System.Security.Principal;
4using System.Runtime.InteropServices;
5using System.Text;
6using System.Text.Json;
7using System.Text.Json.Nodes;
8using Microsoft.Win32.SafeHandles;
9
10namespace Cage.GuestClipboard;
11
12// Only destinations reserved for a verified Claude Save dialog enter this
13// catalog. A wire request names an opaque receipt, never a filesystem path.
14internal static class WindowsDesktopDownloads
15{
16 private sealed class Download
17 {
18 public string ID { get; set; } = "";
19 public string Name { get; set; } = "";
20 public string State { get; set; } = "downloading";
21 public string Error { get; set; } = "";
22 public bool Acknowledged { get; set; }
23 public string? Identity { get; set; }
24 public long Size { get; set; }
25 public long Written { get; set; }
26 public DateTimeOffset Started { get; set; } = DateTimeOffset.UtcNow;
27 }
28 private sealed class Transfer(FileStream file, string id, string session, long epoch)
29 {
30 internal readonly FileStream File = file;
31 internal readonly string ID = id;
32 internal bool SessionValid => ClipboardAgent.Current is { SessionEventsRegistered: true } agent && agent.Session == session && agent.SessionEpoch == epoch;
33 internal int Sequence;
34 internal DateTimeOffset Used = DateTimeOffset.UtcNow;
35 }
36 private static readonly object Gate = new();
37 private static readonly Dictionary<string, Download> Downloads = new();
38 private static readonly Dictionary<string, Transfer> Transfers = new();
39 private static readonly HashSet<string> Watching = new();
40 private static readonly System.Threading.Timer TransferExpiry = new(_ =>
41 {
42 lock (Gate)
43 {
44 if (Transfers.Count == 0) return;
45 bool available;
46 try { available = SessionGuard.Available(); } catch { available = false; }
47 foreach (var pair in Transfers.ToArray())
48 if (!available || !pair.Value.SessionValid || DateTimeOffset.UtcNow - pair.Value.Used > TimeSpan.FromMinutes(2))
49 { pair.Value.File.Dispose(); Transfers.Remove(pair.Key); }
50 }
51 }, null, 2000, 2000);
52 private static string? directory;
53 [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
54 private static extern uint GetFinalPathNameByHandleW(SafeFileHandle handle, StringBuilder path, uint length, uint flags);
55 [StructLayout(LayoutKind.Sequential)]
56 private struct FileInformation
57 {
58 internal uint Attributes;
59 internal System.Runtime.InteropServices.ComTypes.FILETIME Creation, Access, Written;
60 internal uint Volume, SizeHigh, SizeLow, Links, IndexHigh, IndexLow;
61 }
62 [DllImport("kernel32.dll", SetLastError = true)]
63 [return: MarshalAs(UnmanagedType.Bool)]
64 private static extern bool GetFileInformationByHandle(SafeFileHandle handle, out FileInformation information);
65 [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
66 private static extern SafeFileHandle CreateFileW(string path, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);
67 [DllImport("kernel32.dll", SetLastError = true)]
68 [return: MarshalAs(UnmanagedType.Bool)]
69 private static extern bool SetFileInformationByHandle(SafeFileHandle handle, int kind, ref byte information, uint size);
70
71 private static string FileIdentity(SafeFileHandle handle)
72 {
73 if (!GetFileInformationByHandle(handle, out var info)) throw new IOException("desktop_download_file_invalid");
74 return $"{info.Volume:x8}:{info.IndexHigh:x8}{info.IndexLow:x8}";
75 }
76
77 private static bool MatchesPath(SafeFileHandle handle, string path)
78 {
79 var actual = new StringBuilder(32768);
80 var length = GetFinalPathNameByHandleW(handle, actual, (uint)actual.Capacity, 0);
81 return length > 0 && length < actual.Capacity && string.Equals(actual.ToString(), @"\\?\" + Path.GetFullPath(path), StringComparison.OrdinalIgnoreCase);
82 }
83
84 private static FileStream OpenSource(Download item)
85 {
86 var path = Source(item);
87 var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
88 try
89 {
90 var actual = new StringBuilder(32768);
91 var length = GetFinalPathNameByHandleW(stream.SafeFileHandle, actual, (uint)actual.Capacity, 0);
92 if (length == 0 || length >= actual.Capacity ||
93 !string.Equals(actual.ToString(), @"\\?\" + Path.GetFullPath(path), StringComparison.OrdinalIgnoreCase) ||
94 stream.Length > AttachmentsRpc.FileLimit)
95 throw new InvalidDataException("desktop_download_file_invalid");
96 return stream;
97 }
98 catch { stream.Dispose(); throw; }
99 }
100
101 private static string DirectoryPath()
102 {
103 if (directory is not null) return directory;
104 var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
105 var root = Path.Combine(home, "Cage", "DesktopDownloads");
106 using var user = WindowsIdentity.GetCurrent();
107 foreach (var path in new[] { Path.Combine(home, "Cage"), root })
108 {
109 Directory.CreateDirectory(path);
110 var info = new DirectoryInfo(path);
111 if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.GetAccessControl().GetOwner(typeof(SecurityIdentifier))?.Value != user.User?.Value)
112 throw new InvalidDataException("desktop_download_directory_invalid");
113 }
114 var manifest = Path.Combine(root, "downloads.json");
115 if (File.Exists(manifest))
116 {
117 var info = new FileInfo(manifest);
118 if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.Length > 1 << 20) throw new InvalidDataException("desktop_download_catalog_invalid");
119 var saved = JsonSerializer.Deserialize<Download[]>(File.ReadAllBytes(manifest)) ?? [];
120 if (saved.Length > 100) throw new InvalidDataException("desktop_download_catalog_invalid");
121 foreach (var item in saved)
122 {
123 if (!Guid.TryParseExact(item.ID, "D", out _) || !AttachmentsRpc.NameValid(item.Name)) continue;
124 if (item.State == "downloading") { item.State = "failed"; item.Error = "保存过程被中断,请从 Claude Desktop 重新下载。"; }
125 Downloads[item.ID] = item;
126 }
127 }
128 directory = root;
129 return root;
130 }
131 private static string Source(Download item) => Path.Combine(DirectoryPath(), item.ID, item.Name);
132 private static void Persist()
133 {
134 var file = Path.Combine(DirectoryPath(), "downloads.json");
135 var temporary = file + "." + Guid.NewGuid().ToString("N");
136 try
137 {
138 using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None))
139 {
140 JsonSerializer.Serialize(stream, Downloads.Values.ToArray());
141 stream.Flush(true);
142 }
143 File.Move(temporary, file, true);
144 }
145 finally { if (File.Exists(temporary)) File.Delete(temporary); }
146 }
147
148 private static void RemoveSource(Download item)
149 {
150 var path = Source(item);
151 var folder = Path.GetDirectoryName(path)!;
152 using var parent = CreateFileW(folder, 0x10000 | 0x80, 1 | 2, IntPtr.Zero, 3, 0x02000000 | 0x00200000, IntPtr.Zero);
153 if (parent.IsInvalid && Marshal.GetLastWin32Error() is 2 or 3) return;
154 if (parent.IsInvalid || !MatchesPath(parent, folder) || !GetFileInformationByHandle(parent, out var parentInfo) ||
155 (parentInfo.Attributes & 0x410) != 0x10) throw new IOException("desktop_download_directory_invalid");
156 using (var file = CreateFileW(path, 0x80000000 | 0x10000, 1, IntPtr.Zero, 3, 0x00200000, IntPtr.Zero))
157 {
158 if (file.IsInvalid)
159 {
160 if (Marshal.GetLastWin32Error() is not (2 or 3)) throw new IOException("desktop_download_cleanup_failed");
161 }
162 else
163 {
164 if (item.State != "saved" || !MatchesPath(file, path) || !GetFileInformationByHandle(file, out var info) || (info.Attributes & 0x410) != 0 ||
165 FileIdentity(file) != item.Identity || ((long)info.SizeHigh << 32 | info.SizeLow) != item.Size ||
166 DateTime.FromFileTimeUtc((long)(uint)info.Written.dwHighDateTime << 32 | (uint)info.Written.dwLowDateTime).Ticks != item.Written)
167 throw new IOException("desktop_download_changed");
168 byte delete = 1;
169 if (!SetFileInformationByHandle(file, 4, ref delete, 1)) throw new IOException("desktop_download_cleanup_failed");
170 }
171 }
172 // The kernel removes this exact open directory only when it is empty.
173 // Unrecorded sibling files keep their directory and contents.
174 byte removeDirectory = 1;
175 var removed = SetFileInformationByHandle(parent, 4, ref removeDirectory, 1);
176 if (item.State == "failed" && !removed) throw new IOException("desktop_download_cleanup_failed");
177 }
178
179 private static void MakeRoom()
180 {
181 if (Downloads.Count < 100) return;
182 foreach (var item in Downloads.Values.ToArray())
183 {
184 var eligible = (item.State == "saved" && item.Acknowledged) || (item.State == "failed" && !Watching.Contains(item.ID));
185 if (!eligible || Transfers.Values.Any(transfer => transfer.ID == item.ID)) continue;
186 try { RemoveSource(item); Downloads.Remove(item.ID); return; }
187 catch (IOException) { /* Retain changed, in-use, or unowned source receipts. */ }
188 catch (UnauthorizedAccessException) { }
189 }
190 throw new InvalidDataException("desktop_download_limit");
191 }
192
193 internal static string Reserve(string name, Action<string> submit)
194 {
195 if (!AttachmentsRpc.NameValid(name)) throw new InvalidDataException("desktop_download_name_invalid");
196 lock (Gate)
197 {
198 DirectoryPath();
199 if (Downloads.Values.Count(item => item.State == "downloading") >= 12) throw new InvalidDataException("desktop_download_limit");
200 MakeRoom();
201 var item = new Download { ID = Guid.NewGuid().ToString("D"), Name = name };
202 var folder = Path.GetDirectoryName(Source(item))!;
203 Directory.CreateDirectory(folder);
204 var watcher = new FileSystemWatcher(folder) { NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size };
205 var changed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
206 var renamed = 0;
207 watcher.Changed += (_, eventArgs) => { if (eventArgs.Name == name) changed.TrySetResult(); };
208 watcher.Renamed += (_, eventArgs) => { if (eventArgs.Name == name) { Interlocked.Exchange(ref renamed, 1); changed.TrySetResult(); } };
209 watcher.Error += (_, _) => changed.TrySetException(new InvalidDataException("desktop_download_watch_failed"));
210 watcher.EnableRaisingEvents = true;
211 Watching.Add(item.ID);
212 Downloads.Add(item.ID, item);
213 try { Persist(); submit(Source(item)); }
214 catch
215 {
216 watcher.Dispose(); Watching.Remove(item.ID); item.State = "failed"; item.Error = "客机保存窗口未接收文件位置,请重新下载。"; Persist(); throw;
217 }
218 _ = Task.Run(async () =>
219 {
220 using (watcher)
221 using (var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(30)))
222 {
223 try
224 {
225 await changed.Task.WaitAsync(timeout.Token);
226 while (true)
227 {
228 timeout.Token.ThrowIfCancellationRequested();
229 if (!File.Exists(Source(item) + ".crdownload"))
230 {
231 try
232 {
233 using var source = OpenSource(item);
234 if (source.Length == 0 && Volatile.Read(ref renamed) == 0) throw new IOException("empty reservation is waiting for completion");
235 lock (Gate)
236 {
237 item.Size = source.Length; item.Written = File.GetLastWriteTimeUtc(Source(item)).Ticks;
238 item.Identity = FileIdentity(source.SafeFileHandle);
239 item.State = "saved"; Persist();
240 }
241 return;
242 }
243 catch (IOException) { }
244 }
245 await Task.Delay(100, timeout.Token);
246 }
247 }
248 catch
249 {
250 lock (Gate) { item.State = "failed"; item.Error = "未能确认文件保存完成,请从 Claude Desktop 重新下载。"; Persist(); }
251 }
252 finally { watcher.Dispose(); lock (Gate) Watching.Remove(item.ID); }
253 }
254 });
255 return item.ID;
256 }
257 }
258
259 internal static JsonArray Snapshot()
260 {
261 lock (Gate)
262 {
263 DirectoryPath();
264 return new JsonArray(Downloads.Values.TakeLast(100).Reverse().Select(item => (JsonNode)new JsonObject
265 {
266 ["id"] = item.ID, ["name"] = item.Name, ["state"] = item.State, ["target"] = "desktop",
267 ["acknowledged"] = item.Acknowledged,
268 ["receivedBytes"] = item.Size, ["totalBytes"] = item.Size, ["retryable"] = false,
269 ["error"] = item.Error, ["startedAt"] = item.Started.ToString("O"),
270 }).ToArray());
271 }
272 }
273
274 internal static (string ID, bool Directory)? FindPath(string path)
275 {
276 lock (Gate)
277 {
278 DirectoryPath();
279 foreach (var item in Downloads.Values)
280 {
281 var source = Source(item);
282 if (string.Equals(path, source, StringComparison.OrdinalIgnoreCase)) return (item.ID, false);
283 if (string.Equals(path, Path.GetDirectoryName(source), StringComparison.OrdinalIgnoreCase)) return (item.ID, true);
284 }
285 return null;
286 }
287 }
288
289 internal static JsonObject Read(JsonObject input)
290 {
291 lock (Gate)
292 {
293 SessionGuard.Assert(); DirectoryPath();
294 foreach (var pair in Transfers.ToArray())
295 if (!pair.Value.SessionValid || DateTimeOffset.UtcNow - pair.Value.Used > TimeSpan.FromMinutes(2)) { pair.Value.File.Dispose(); Transfers.Remove(pair.Key); }
296 var action = input["action"]?.GetValue<string>();
297 if (action == "files-download-ack")
298 {
299 var ids = input["ids"] as JsonArray;
300 if (ids is null || ids.Count > 100 || ids.Any(value => value is not JsonValue scalar || !scalar.TryGetValue<string>(out var id) || !Guid.TryParseExact(id, "D", out _)))
301 throw new InvalidDataException("desktop_download_ack_invalid");
302 var changed = new List<Download>();
303 try
304 {
305 foreach (var value in ids)
306 {
307 if (!Downloads.TryGetValue(value!.GetValue<string>(), out var item) || item.State != "saved" || item.Acknowledged) continue;
308 if (item.Identity is null)
309 {
310 try
311 {
312 using var file = OpenSource(item);
313 if (file.Length == item.Size && File.GetLastWriteTimeUtc(Source(item)).Ticks == item.Written) item.Identity = FileIdentity(file.SafeFileHandle);
314 }
315 catch (IOException) { }
316 catch (UnauthorizedAccessException) { }
317 }
318 item.Acknowledged = true; changed.Add(item);
319 }
320 if (changed.Count > 0) Persist();
321 }
322 catch { foreach (var item in changed) item.Acknowledged = false; throw; }
323 return new JsonObject { ["ok"] = true };
324 }
325 if (action == "files-download-retry")
326 {
327 var id = input["id"]?.GetValue<string>() ?? "";
328 if (!Downloads.TryGetValue(id, out var item) || item.State != "saved") throw new InvalidDataException("desktop_download_incomplete");
329 using var file = OpenSource(item);
330 if (file.Length != item.Size || File.GetLastWriteTimeUtc(Source(item)).Ticks != item.Written) throw new InvalidDataException("desktop_download_changed");
331 return new JsonObject { ["ok"] = true };
332 }
333 if (action == "files-download-open")
334 {
335 var agent = ClipboardAgent.Current;
336 if (agent is null || !agent.SessionEventsRegistered) throw new InvalidDataException("desktop_download_session_unavailable");
337 var id = input["id"]?.GetValue<string>() ?? "";
338 if (!Downloads.TryGetValue(id, out var item) || item.State != "saved" || Transfers.Count >= 12) throw new InvalidDataException("desktop_download_unavailable");
339 var file = OpenSource(item);
340 if (file.Length != item.Size || File.GetLastWriteTimeUtc(Source(item)).Ticks != item.Written)
341 { file.Dispose(); throw new InvalidDataException("desktop_download_changed"); }
342 var key = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
343 Transfers.Add(key, new Transfer(file, item.ID, agent.Session, agent.SessionEpoch));
344 return new JsonObject { ["transfer"] = key, ["size"] = file.Length, ["name"] = item.Name };
345 }
346 var transfer = input["transfer"]?.GetValue<string>() ?? "";
347 if (action == "files-download-close")
348 {
349 if (Transfers.Remove(transfer, out var old)) old.File.Dispose();
350 return new JsonObject { ["ok"] = true };
351 }
352 if (action != "files-download-read" || !Transfers.TryGetValue(transfer, out var current) || current.Sequence != input["sequence"]?.GetValue<int>())
353 throw new InvalidDataException("desktop_download_transfer_invalid");
354 var data = new byte[64 << 10];
355 var count = current.File.Read(data);
356 current.Used = DateTimeOffset.UtcNow;
357 var result = new JsonObject { ["data"] = Convert.ToBase64String(data, 0, count), ["sequence"] = ++current.Sequence, ["eof"] = current.File.Position == current.File.Length };
358 if (current.File.Position == current.File.Length) { current.File.Dispose(); Transfers.Remove(transfer); }
359 return result;
360 }
361 }
362}