跳到主要内容

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

浏览文件

save-download.py

158 行 · 6.8 KB历史下载
1#!/usr/bin/python3
2"""Publish one completed browser download into the fixed shared workspace."""
3import errno
4import json
5import os
6import pwd
7import re
8import secrets
9import stat
10import sys
11
12
13def checked_download(source_name, name):
14 if not re.fullmatch(r'[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}', source_name):
15 raise ValueError('下载标识无效')
16 if not name or name != os.path.basename(name) or name in ('.', '..') or '\0' in name:
17 raise ValueError('下载文件名无效')
18
19
20def copy_to_workspace(source, size, workspace, name):
21 """Run as the coding user; final names only become visible after fsync."""
22 parent = os.open(workspace, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
23 destination = None
24 published = None
25 temporary = '.cage-download-' + secrets.token_hex(12) + '.part'
26 try:
27 try:
28 os.mkdir('Downloads', mode=0o755, dir_fd=parent)
29 except FileExistsError:
30 pass
31 destination = os.open('Downloads', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent)
32 output = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=destination)
33 with os.fdopen(output, 'wb') as dst:
34 remaining = size
35 while remaining:
36 chunk = os.read(source, min(remaining, 1024 * 1024))
37 if not chunk:
38 raise OSError(errno.EIO, '下载源文件在保存过程中发生变化')
39 dst.write(chunk)
40 remaining -= len(chunk)
41 dst.flush()
42 os.fchmod(dst.fileno(), 0o644)
43 os.fsync(dst.fileno())
44 root, extension = os.path.splitext(name)
45 for number in range(1000):
46 candidate = name if number == 0 else f'{root} ({number}){extension}'
47 try:
48 # The complete file is published without replacing any entry.
49 os.link(temporary, candidate, src_dir_fd=destination, dst_dir_fd=destination, follow_symlinks=False)
50 published = {'ok': True, 'path': os.path.join(workspace, 'Downloads', candidate), 'name': candidate, 'bytes': size}
51 return published
52 except FileExistsError:
53 continue
54 raise OSError(errno.EEXIST, '同名文件过多,请整理 Downloads 后重试')
55 finally:
56 if destination is not None:
57 try:
58 os.unlink(temporary, dir_fd=destination)
59 except FileNotFoundError:
60 pass
61 except OSError:
62 if published is None:
63 raise
64 published['warning'] = '文件已保存到本机;共享目录中的临时文件暂时无法清理。'
65 finally:
66 os.close(destination)
67 os.close(parent)
68
69
70def remove_source_if_unchanged(directory, name, expected):
71 """Do not remove a replacement created after the source was opened."""
72 try:
73 current = os.stat(name, dir_fd=directory, follow_symlinks=False)
74 except FileNotFoundError:
75 return True
76 identity = lambda st: (st.st_dev, st.st_ino, st.st_uid, st.st_size, st.st_mtime_ns)
77 if not stat.S_ISREG(current.st_mode) or identity(current) != identity(expected):
78 return False
79 os.unlink(name, dir_fd=directory)
80 return True
81
82
83def error_message(error):
84 if isinstance(error, ValueError):
85 return str(error)
86 if isinstance(error, OSError):
87 if error.errno == errno.ENOSPC:
88 return '空间不足,文件尚未保存到本机。清理空间后可重试。'
89 if error.errno in (errno.EACCES, errno.EPERM, errno.EROFS):
90 return '无法写入共享下载目录。检查目录权限和共享连接后可重试。'
91 if error.errno in (errno.ELOOP, errno.ENOTDIR):
92 return '下载目录包含符号链接或已不再是目录,请修复后重试。'
93 if error.errno == errno.ENOENT:
94 return '下载源文件或共享目录不可用,请检查后重试。'
95 return '文件尚未保存到本机。检查共享连接和可用空间后可重试。'
96
97
98def main():
99 source_name, name = sys.argv[1:] if len(sys.argv) == 3 else ('', '')
100 checked_download(source_name, name)
101 with open('/etc/claude-cage/browser-control.json') as config:
102 workspace = json.load(config)['workspace']
103 directory = os.open('/home/cage-browser/Downloads', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
104 source = None
105 try:
106 browser_uid = pwd.getpwnam('cage-browser').pw_uid
107 if os.fstat(directory).st_uid != browser_uid:
108 raise ValueError('下载目录所有者无效')
109 source = os.open(source_name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory)
110 source_stat = os.fstat(source)
111 if not stat.S_ISREG(source_stat.st_mode) or source_stat.st_uid != browser_uid:
112 raise ValueError('下载源文件不是普通文件')
113 user = pwd.getpwnam('cage')
114 receive, send = os.pipe()
115 child = os.fork()
116 if child == 0:
117 os.close(receive)
118 try:
119 # Only the parent retains permission to clean up browser files.
120 os.setgroups([user.pw_gid])
121 os.setgid(user.pw_gid)
122 os.setuid(user.pw_uid)
123 result = copy_to_workspace(source, source_stat.st_size, workspace, name)
124 except Exception as error:
125 result = {'ok': False, 'error': error_message(error)}
126 with os.fdopen(send, 'wb') as pipe:
127 pipe.write(json.dumps(result, ensure_ascii=False).encode())
128 os._exit(0 if result['ok'] else 1)
129 os.close(send)
130 with os.fdopen(receive, 'rb') as pipe:
131 data = pipe.read(16385)
132 _, status = os.waitpid(child, 0)
133 if len(data) > 16384:
134 raise ValueError('下载保存结果无效')
135 result = json.loads(data)
136 if os.waitstatus_to_exitcode(status) != 0 or not result.get('ok'):
137 print(json.dumps({'ok': False, 'error': result.get('error', '下载保存未完成')}, ensure_ascii=False))
138 return 1
139 try:
140 cleaned = remove_source_if_unchanged(directory, source_name, source_stat)
141 except OSError:
142 cleaned = False
143 if not cleaned:
144 result['warning'] = '文件已保存到本机;客机中的下载源文件发生变化或暂时无法清理。'
145 print(json.dumps(result, ensure_ascii=False))
146 return 0
147 finally:
148 if source is not None:
149 os.close(source)
150 os.close(directory)
151
152
153if __name__ == '__main__':
154 try:
155 sys.exit(main())
156 except Exception as error:
157 print(json.dumps({'ok': False, 'error': error_message(error)}, ensure_ascii=False))
158 sys.exit(1)