| 1 | |
| 2 | """Share CLIPBOARD selections over a private stdin/stdout channel. |
| 3 | |
| 4 | No clipboard payload is logged. File bytes use a separate streaming archive. |
| 5 | """ |
| 6 | import base64 |
| 7 | from contextlib import contextmanager |
| 8 | import fcntl |
| 9 | import json |
| 10 | import os |
| 11 | from pathlib import Path |
| 12 | import queue |
| 13 | import shutil |
| 14 | import stat |
| 15 | import sys |
| 16 | import tarfile |
| 17 | import tempfile |
| 18 | import threading |
| 19 | import time |
| 20 | import uuid |
| 21 | from urllib.parse import unquote, urlsplit |
| 22 | |
| 23 | TEXT_LIMIT = 2 * 1024 * 1024 |
| 24 | IMAGE_LIMIT = 20 * 1024 * 1024 |
| 25 | FILE_LIMIT = 2 * 1024 * 1024 * 1024 |
| 26 | WIRE_LIMIT = 30 * 1024 * 1024 |
| 27 | |
| 28 | |
| 29 | class CacheRegistry: |
| 30 | def __init__(self, directory=None): |
| 31 | self.directory = Path(directory or Path(tempfile.gettempdir()) / ('cage-clipboard-ownership-' + str(os.getuid()))) |
| 32 | |
| 33 | def ensure_directory(self): |
| 34 | self.directory.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 35 | info = self.directory.lstat() |
| 36 | if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o077: |
| 37 | raise ValueError('Clipboard ownership directory is not private') |
| 38 | |
| 39 | def session_path(self, session): |
| 40 | if not isinstance(session, str) or not 1 <= len(session) <= 256 or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-' for c in session): |
| 41 | raise ValueError('Invalid clipboard session') |
| 42 | return self.directory / ('session-' + session) |
| 43 | |
| 44 | def begin_session(self, session): |
| 45 | self.ensure_directory() |
| 46 | path = self.session_path(session) |
| 47 | with path.open('x') as output: |
| 48 | os.chmod(path, 0o600) |
| 49 | json.dump({'owner': os.getpid()}, output) |
| 50 | |
| 51 | def require_session(self, session): |
| 52 | try: |
| 53 | value = json.loads(self.session_path(session).read_text()) |
| 54 | owner = value['owner'] |
| 55 | if not isinstance(owner, int) or owner < 1: |
| 56 | raise ValueError('Invalid clipboard session owner') |
| 57 | os.kill(owner, 0) |
| 58 | except (OSError, ValueError, KeyError, TypeError) as error: |
| 59 | raise ValueError('Clipboard session changed') from error |
| 60 | |
| 61 | def end_session(self, session): |
| 62 | self.session_path(session).unlink(missing_ok=True) |
| 63 | |
| 64 | def records(self): |
| 65 | if not self.directory.exists(): |
| 66 | return [] |
| 67 | self.ensure_directory() |
| 68 | records = [] |
| 69 | for path in self.directory.iterdir(): |
| 70 | if path.suffix != '.json' or not path.is_file(): |
| 71 | continue |
| 72 | record = json.loads(path.read_text()) |
| 73 | identity = record.get('id') if isinstance(record, dict) else None |
| 74 | directory = record.get('directory') if isinstance(record, dict) else None |
| 75 | paths = record.get('paths') if isinstance(record, dict) else None |
| 76 | marker = record.get('marker') if isinstance(record, dict) else None |
| 77 | if (not isinstance(identity, str) or len(identity) != 32 or any(c not in '0123456789abcdef' for c in identity) |
| 78 | or identity + '.json' != path.name or not isinstance(directory, str) |
| 79 | or not Path(directory).is_absolute() or os.path.normpath(directory) != directory |
| 80 | or not isinstance(paths, list) or not 1 <= len(paths) <= 100 |
| 81 | or any(not isinstance(item, str) or Path(item).parent != Path(directory) or os.path.normpath(item) != item for item in paths) |
| 82 | or not isinstance(marker, str) or marker in ('', '.', '..') or Path(marker).name != marker |
| 83 | or not isinstance(record.get('session'), str) or not isinstance(record.get('retired'), bool) |
| 84 | or not isinstance(record.get('pending', False), bool) |
| 85 | or record.get('pending') and (not isinstance(record.get('producer'), int) or record['producer'] < 1)): |
| 86 | raise ValueError('Invalid clipboard ownership record') |
| 87 | records.append(record) |
| 88 | return records |
| 89 | |
| 90 | def save(self, record): |
| 91 | self.ensure_directory() |
| 92 | fd, temporary = tempfile.mkstemp(dir=self.directory, prefix='.record-') |
| 93 | try: |
| 94 | with os.fdopen(fd, 'w') as output: |
| 95 | json.dump(record, output) |
| 96 | os.replace(temporary, self.directory / (record['id'] + '.json')) |
| 97 | finally: |
| 98 | Path(temporary).unlink(missing_ok=True) |
| 99 | |
| 100 | def register(self, paths, session, pending=False): |
| 101 | root = Path(paths[0]).parent |
| 102 | identity = uuid.uuid4().hex |
| 103 | fd, marker = tempfile.mkstemp(dir=root, prefix='.cage-clipboard-owner-') |
| 104 | with os.fdopen(fd, 'w') as output: |
| 105 | output.write(identity) |
| 106 | self.ensure_directory() |
| 107 | lock = self.directory / (identity + '.lock') |
| 108 | lock.touch(mode=0o600, exist_ok=False) |
| 109 | try: |
| 110 | record = {'id': identity, 'directory': str(root), 'marker': Path(marker).name, |
| 111 | 'paths': paths, 'session': session, 'retired': False, 'pending': pending, 'producer': os.getpid()} |
| 112 | self.save(record) |
| 113 | return record |
| 114 | except BaseException: |
| 115 | lock.unlink(missing_ok=True) |
| 116 | raise |
| 117 | |
| 118 | def retire(self, paths): |
| 119 | selected = set(paths) |
| 120 | for record in self.records(): |
| 121 | if selected.intersection(record['paths']): |
| 122 | record['retired'] = True |
| 123 | self.save(record) |
| 124 | |
| 125 | def adopt(self, paths, session): |
| 126 | selected = set(paths) |
| 127 | for record in self.records(): |
| 128 | if selected.intersection(record['paths']): |
| 129 | record['session'] = session |
| 130 | self.save(record) |
| 131 | |
| 132 | @contextmanager |
| 133 | def reading(self, paths): |
| 134 | leases = [] |
| 135 | try: |
| 136 | for record in self.records(): |
| 137 | root = Path(record['directory']) |
| 138 | if any(Path(path).is_relative_to(root) for path in paths): |
| 139 | lock = (self.directory / (record['id'] + '.lock')).open('rb') |
| 140 | fcntl.flock(lock, fcntl.LOCK_SH) |
| 141 | leases.append(lock) |
| 142 | yield |
| 143 | finally: |
| 144 | for lease in leases: |
| 145 | lease.close() |
| 146 | |
| 147 | def collect(self, selected, session): |
| 148 | for record in self.records(): |
| 149 | root = Path(record['directory']) |
| 150 | if root.exists() and record.get('pending') and not record['retired']: |
| 151 | try: |
| 152 | os.kill(record['producer'], 0) |
| 153 | continue |
| 154 | except ProcessLookupError: |
| 155 | pass |
| 156 | if root.exists() and not record.get('pending') and not record['retired'] and (not record['session'] or record['session'] == session): |
| 157 | continue |
| 158 | if any(Path(path).is_relative_to(root) or root.is_relative_to(Path(path)) for path in selected): |
| 159 | continue |
| 160 | lock_path = self.directory / (record['id'] + '.lock') |
| 161 | with lock_path.open('rb') as lease: |
| 162 | try: |
| 163 | fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB) |
| 164 | except BlockingIOError: |
| 165 | continue |
| 166 | if root.exists(): |
| 167 | marker = root / record['marker'] |
| 168 | if root.is_symlink() or marker.is_symlink() or marker.read_text() != record['id']: |
| 169 | raise ValueError('Clipboard ownership changed') |
| 170 | for item in root.iterdir(): |
| 171 | if item == marker: |
| 172 | continue |
| 173 | if item.is_dir() and not item.is_symlink(): |
| 174 | shutil.rmtree(item) |
| 175 | else: |
| 176 | item.unlink() |
| 177 | marker.unlink() |
| 178 | try: |
| 179 | root.rmdir() |
| 180 | except OSError: |
| 181 | marker.write_text(record['id']) |
| 182 | marker.chmod(0o600) |
| 183 | raise |
| 184 | (self.directory / (record['id'] + '.json')).unlink() |
| 185 | lock_path.unlink(missing_ok=True) |
| 186 | |
| 187 | |
| 188 | def file_paths(uris): |
| 189 | paths = [] |
| 190 | for uri in uris: |
| 191 | parsed = urlsplit(uri) |
| 192 | if parsed.scheme != 'file' or parsed.netloc not in ('', 'localhost'): |
| 193 | raise ValueError('Only local clipboard files can be shared') |
| 194 | path = Path(unquote(parsed.path)) |
| 195 | if not path.is_absolute() or path.is_symlink() or not path.exists(): |
| 196 | raise ValueError('Clipboard file unavailable') |
| 197 | paths.append(str(path)) |
| 198 | if not 1 <= len(paths) <= 100: |
| 199 | raise ValueError('Clipboard supports 1 to 100 selected files or folders') |
| 200 | return paths |
| 201 | |
| 202 | |
| 203 | def export_files(paths, output): |
| 204 | paths = file_paths([Path(path).as_uri() for path in paths]) |
| 205 | names = set() |
| 206 | with tarfile.open(fileobj=output, mode='w|') as archive: |
| 207 | def check(info): |
| 208 | if not (info.isfile() or info.isdir()) or info.size > FILE_LIMIT: |
| 209 | raise ValueError('Clipboard supports ordinary files up to 2 GB') |
| 210 | return info |
| 211 | for path in paths: |
| 212 | name = Path(path).name |
| 213 | if not name or name in names: |
| 214 | raise ValueError('Clipboard file names must be distinct') |
| 215 | names.add(name) |
| 216 | archive.add(path, arcname=name, filter=check) |
| 217 | |
| 218 | |
| 219 | def import_files(source, session=''): |
| 220 | registry = CacheRegistry() |
| 221 | if session: |
| 222 | registry.require_session(session) |
| 223 | root = Path(tempfile.mkdtemp(prefix='cage-clipboard-')) |
| 224 | record = None |
| 225 | try: |
| 226 | record = registry.register([str(root / '.pending')], session, pending=True) |
| 227 | paths = extract_files(source, root) |
| 228 | record['paths'] = paths |
| 229 | record['pending'] = False |
| 230 | registry.save(record) |
| 231 | if session: |
| 232 | registry.require_session(session) |
| 233 | return paths |
| 234 | except BaseException: |
| 235 | shutil.rmtree(root) |
| 236 | if record: |
| 237 | (registry.directory / (record['id'] + '.json')).unlink(missing_ok=True) |
| 238 | (registry.directory / (record['id'] + '.lock')).unlink(missing_ok=True) |
| 239 | raise |
| 240 | |
| 241 | |
| 242 | def extract_files(source, root): |
| 243 | root.chmod(0o755) |
| 244 | names = [] |
| 245 | with tarfile.open(fileobj=source, mode='r|') as archive: |
| 246 | for item in archive: |
| 247 | parts = item.name.split('/') |
| 248 | if (not parts or any(part in ('', '.', '..') or '\\' in part for part in parts) |
| 249 | or not (item.isfile() or item.isdir()) or item.size > FILE_LIMIT): |
| 250 | raise ValueError('Invalid clipboard archive') |
| 251 | if parts[0] not in names: |
| 252 | names.append(parts[0]) |
| 253 | if len(names) > 100: |
| 254 | raise ValueError('Too many clipboard files') |
| 255 | destination = root.joinpath(*parts) |
| 256 | destination.parent.mkdir(parents=True, exist_ok=True, mode=0o755) |
| 257 | if item.isdir(): |
| 258 | destination.mkdir(exist_ok=True, mode=0o755) |
| 259 | else: |
| 260 | with archive.extractfile(item) as source_file, destination.open('xb') as target: |
| 261 | while chunk := source_file.read(1024 * 1024): |
| 262 | target.write(chunk) |
| 263 | destination.chmod(0o644) |
| 264 | if not names: |
| 265 | raise ValueError('Empty clipboard archive') |
| 266 | return [str(root / name) for name in names] |
| 267 | |
| 268 | |
| 269 | def materialize_guest_files(paths, user, session=''): |
| 270 | |
| 271 | |
| 272 | import multiprocessing |
| 273 | import pwd |
| 274 | account = pwd.getpwnam(user) |
| 275 | read_fd, write_fd = os.pipe() |
| 276 | def export(): |
| 277 | os.close(read_fd) |
| 278 | os.initgroups(account.pw_name, account.pw_gid) |
| 279 | os.setgid(account.pw_gid) |
| 280 | os.setuid(account.pw_uid) |
| 281 | try: |
| 282 | with os.fdopen(write_fd, 'wb') as output: |
| 283 | export_files(paths, output) |
| 284 | except BaseException: |
| 285 | os._exit(1) |
| 286 | process = multiprocessing.get_context('fork').Process(target=export) |
| 287 | process.start() |
| 288 | os.close(write_fd) |
| 289 | copied = None |
| 290 | try: |
| 291 | with os.fdopen(read_fd, 'rb') as source: |
| 292 | copied = import_files(source, session) |
| 293 | process.join(timeout=3) |
| 294 | if process.exitcode != 0: |
| 295 | raise ValueError('Clipboard source files cannot be read') |
| 296 | return copied |
| 297 | except BaseException: |
| 298 | if copied: |
| 299 | shutil.rmtree(Path(copied[0]).parent) |
| 300 | raise |
| 301 | finally: |
| 302 | if process.is_alive(): |
| 303 | process.terminate(); process.join(timeout=2) |
| 304 | |
| 305 | |
| 306 | def clipboard_worker(name, connection): |
| 307 | os.environ['NO_AT_BRIDGE'] = '1' |
| 308 | os.environ['DISPLAY'] = name |
| 309 | if name == ':78': |
| 310 | os.environ['XAUTHORITY'] = '/run/cage-desktop/Xauthority' |
| 311 | else: |
| 312 | os.environ.pop('XAUTHORITY', None) |
| 313 | import gi |
| 314 | gi.require_version('Gtk', '3.0') |
| 315 | gi.require_version('Gdk', '3.0') |
| 316 | from gi.repository import Gdk, GdkPixbuf, GLib, Gtk |
| 317 | |
| 318 | Gtk.init_check([]) |
| 319 | display = Gdk.Display.get_default() |
| 320 | if not display: |
| 321 | return |
| 322 | clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) |
| 323 | displays = {name: (display, clipboard)} |
| 324 | last = None |
| 325 | initialized = False |
| 326 | commands = queue.Queue() |
| 327 | changes = {} |
| 328 | |
| 329 | def write(clipboard, payload): |
| 330 | if 'text' in payload: |
| 331 | clipboard.set_text(payload['text'], -1) |
| 332 | elif 'png' in payload: |
| 333 | loader = GdkPixbuf.PixbufLoader.new_with_type('png') |
| 334 | loader.write(base64.b64decode(payload['png'], validate=True)) |
| 335 | loader.close() |
| 336 | image = loader.get_pixbuf() |
| 337 | if image.get_width() * image.get_height() > 40_000_000: |
| 338 | raise ValueError('Clipboard image too large') |
| 339 | clipboard.set_image(image) |
| 340 | else: |
| 341 | uris = [Path(path).as_uri() for path in payload['files']] |
| 342 | |
| 343 | |
| 344 | set_files(clipboard, uris) |
| 345 | |
| 346 | import ctypes as C |
| 347 | gtk = C.CDLL('libgtk-3.so.0') |
| 348 | gdk = C.CDLL('libgdk-3.so.0') |
| 349 | p = C.c_void_p |
| 350 | def bind(lib, name, result, *args): |
| 351 | function = getattr(lib, name) |
| 352 | function.restype, function.argtypes = result, list(args) |
| 353 | return function |
| 354 | atom = bind(gdk, 'gdk_atom_intern_static_string', p, C.c_char_p) |
| 355 | set_data = bind(gtk, 'gtk_selection_data_set', None, p, p, C.c_int, p, C.c_int) |
| 356 | get_clipboard = bind(gtk, 'gtk_clipboard_get_for_display', p, p, p) |
| 357 | class Target(C.Structure): |
| 358 | _fields_ = [('target', C.c_char_p), ('flags', C.c_uint), ('info', C.c_uint)] |
| 359 | provide_type = C.CFUNCTYPE(None, p, p, C.c_uint, p) |
| 360 | clear_type = C.CFUNCTYPE(None, p, p) |
| 361 | own = bind(gtk, 'gtk_clipboard_set_with_data', C.c_int, p, C.POINTER(Target), C.c_uint, provide_type, clear_type, p) |
| 362 | owners = {} |
| 363 | def set_files(clipboard, uris): |
| 364 | names = [b'text/uri-list', b'x-special/gnome-copied-files'] |
| 365 | data = [('\r\n'.join(uris) + '\r\n').encode(), ('copy\n' + '\n'.join(uris)).encode()] |
| 366 | buffers = [C.create_string_buffer(value) for value in data] |
| 367 | @provide_type |
| 368 | def provide(_clipboard, selection, index, _user): |
| 369 | set_data(selection, atom(names[index]), 8, buffers[index], len(data[index])) |
| 370 | @clear_type |
| 371 | def clear(_clipboard, _user): |
| 372 | pass |
| 373 | display = clipboard.get_display() |
| 374 | native_clipboard = get_clipboard(hash(display), atom(b'CLIPBOARD')) |
| 375 | targets = (Target * 2)(*(Target(name, 0, index) for index, name in enumerate(names))) |
| 376 | |
| 377 | previous = owners.get(hash(display)) |
| 378 | if previous: |
| 379 | GLib.timeout_add_seconds(10, lambda retained=previous: False) |
| 380 | owners[hash(display)] = (provide, clear, buffers, targets) |
| 381 | if not own(native_clipboard, targets, 2, provide, clear, None): |
| 382 | raise ValueError('Cannot own clipboard files') |
| 383 | |
| 384 | def publish(payload, source): |
| 385 | nonlocal last |
| 386 | if not initialized or payload == last: |
| 387 | return |
| 388 | last = payload |
| 389 | for name, (_, clipboard) in displays.items(): |
| 390 | if name != source: |
| 391 | write(clipboard, payload) |
| 392 | message = dict(payload) |
| 393 | if 'files' in payload: |
| 394 | message['source'] = 'cage-browser' if source == ':77' else 'cage' |
| 395 | connection.send(message) |
| 396 | |
| 397 | def changed(clipboard, _event, name): |
| 398 | |
| 399 | |
| 400 | |
| 401 | changes[name] = changes.get(name, 0) + 1 |
| 402 | sequence = changes[name] |
| 403 | def valid(): |
| 404 | return sequence == changes.get(name) |
| 405 | def failure(): |
| 406 | connection.send({'error': '剪贴板内容无法共享,请检查文件是否仍存在及大小限制。'}) |
| 407 | def text_ready(_clipboard, text, _data): |
| 408 | if not valid() or text is None: |
| 409 | return |
| 410 | if len(text.encode()) > TEXT_LIMIT: |
| 411 | failure() |
| 412 | else: |
| 413 | publish({'text': text}, name) |
| 414 | def image_ready(_clipboard, image, _data): |
| 415 | if not valid(): |
| 416 | return |
| 417 | if not image: |
| 418 | clipboard.request_text(text_ready, None) |
| 419 | return |
| 420 | try: |
| 421 | if image.get_width() * image.get_height() > 40_000_000: |
| 422 | raise ValueError('Clipboard image too large') |
| 423 | ok, data = image.save_to_bufferv('png', [], []) |
| 424 | if not ok or len(data) > IMAGE_LIMIT: |
| 425 | raise ValueError('Clipboard image too large') |
| 426 | publish({'png': base64.b64encode(data).decode()}, name) |
| 427 | except (ValueError, OSError, GLib.Error): |
| 428 | failure() |
| 429 | def selected_files(uris): |
| 430 | if not valid(): |
| 431 | return |
| 432 | if uris: |
| 433 | try: |
| 434 | paths = file_paths(uris) |
| 435 | connection.send({'clipboard_files': paths}) |
| 436 | publish({'files': paths}, name) |
| 437 | except (ValueError, OSError): |
| 438 | failure() |
| 439 | else: |
| 440 | connection.send({'clipboard_files': []}) |
| 441 | clipboard.request_image(image_ready, None) |
| 442 | def gnome_ready(_clipboard, selection, _data): |
| 443 | data = selection.get_data() or b'' |
| 444 | if len(data) > TEXT_LIMIT: |
| 445 | failure() |
| 446 | return |
| 447 | try: |
| 448 | lines = data.decode('utf-8', errors='strict').splitlines() |
| 449 | except UnicodeError: |
| 450 | failure() |
| 451 | return |
| 452 | selected_files(lines[1:] if lines and lines[0] in ('copy', 'cut') else []) |
| 453 | def uris_ready(_clipboard, uris, _data): |
| 454 | if uris: |
| 455 | selected_files(uris) |
| 456 | else: |
| 457 | clipboard.request_contents(Gdk.Atom.intern('x-special/gnome-copied-files', False), gnome_ready, None) |
| 458 | clipboard.request_uris(uris_ready, None) |
| 459 | |
| 460 | def tick(): |
| 461 | nonlocal last, initialized |
| 462 | while not commands.empty(): |
| 463 | payload = commands.get() |
| 464 | if payload is None: |
| 465 | Gtk.main_quit() |
| 466 | return False |
| 467 | try: |
| 468 | serial = payload.pop('serial', 0) |
| 469 | if 'text' in payload and isinstance(payload['text'], str) and len(payload['text'].encode()) <= TEXT_LIMIT: |
| 470 | pass |
| 471 | elif 'png' in payload and len(base64.b64decode(payload['png'], validate=True)) <= IMAGE_LIMIT: |
| 472 | pass |
| 473 | elif 'files' in payload: |
| 474 | payload = {'files': file_paths([Path(path).as_uri() for path in payload['files']])} |
| 475 | else: |
| 476 | raise ValueError('Invalid clipboard payload') |
| 477 | last = payload |
| 478 | initialized = True |
| 479 | for _, clipboard in displays.values(): |
| 480 | write(clipboard, payload) |
| 481 | connection.send({'ack': serial}) |
| 482 | except (TypeError, ValueError, KeyError, OSError, GLib.Error): |
| 483 | connection.send({'error': '剪贴板内容无法共享。'}) |
| 484 | return True |
| 485 | |
| 486 | def read(): |
| 487 | try: |
| 488 | while True: |
| 489 | commands.put(connection.recv()) |
| 490 | except EOFError: |
| 491 | pass |
| 492 | commands.put(None) |
| 493 | threading.Thread(target=read, daemon=True).start() |
| 494 | clipboard.connect('owner-change', changed, name) |
| 495 | changed(clipboard, None, name) |
| 496 | GLib.timeout_add(100, tick) |
| 497 | Gtk.main() |
| 498 | |
| 499 | |
| 500 | def bridge(): |
| 501 | |
| 502 | |
| 503 | import multiprocessing |
| 504 | import pwd |
| 505 | import selectors |
| 506 | import uuid |
| 507 | workers = {} |
| 508 | commands = queue.Queue() |
| 509 | pending = {} |
| 510 | last = None |
| 511 | initialized = False |
| 512 | internal_serial = 0 |
| 513 | session = str(uuid.uuid4()) |
| 514 | announced = None |
| 515 | registry = CacheRegistry() |
| 516 | registry.begin_session(session) |
| 517 | current_files = {} |
| 518 | next_cache_check = 0 |
| 519 | cleanup_needed = True |
| 520 | def referenced_files(): |
| 521 | selected = [path for paths in current_files.values() for path in paths] |
| 522 | if last: |
| 523 | selected.extend(last.get('files', [])) |
| 524 | for value in pending.values(): |
| 525 | selected.extend(value.get('files', [])) |
| 526 | return selected |
| 527 | def run_worker(name, connection, uid, gid, home): |
| 528 | os.initgroups(pwd.getpwuid(uid).pw_name, gid) |
| 529 | os.setgid(gid) |
| 530 | os.setuid(uid) |
| 531 | os.environ['HOME'] = home |
| 532 | clipboard_worker(name, connection) |
| 533 | selector = selectors.DefaultSelector() |
| 534 | selector.register(sys.stdin.fileno(), selectors.EVENT_READ) |
| 535 | incoming = b'' |
| 536 | context = multiprocessing.get_context('fork') |
| 537 | try: |
| 538 | running = True |
| 539 | while running: |
| 540 | if selector.select(timeout=.05): |
| 541 | chunk = os.read(sys.stdin.fileno(), 65536) |
| 542 | if not chunk: |
| 543 | break |
| 544 | incoming += chunk |
| 545 | if len(incoming) > WIRE_LIMIT: |
| 546 | break |
| 547 | while b'\n' in incoming: |
| 548 | line, incoming = incoming.split(b'\n', 1) |
| 549 | try: |
| 550 | commands.put(json.loads(line)) |
| 551 | except ValueError: |
| 552 | running = False |
| 553 | break |
| 554 | for name, user in ((':77', 'cage-browser'), (':78', 'cage')): |
| 555 | previous = workers.get(name) |
| 556 | if previous and not previous[0].is_alive(): |
| 557 | previous[0].join(); previous[1].close(); del workers[name] |
| 558 | current_files.pop(name, None) |
| 559 | if name not in workers and Path('/tmp/.X11-unix/X' + name[1:]).exists(): |
| 560 | account = pwd.getpwnam(user) |
| 561 | parent, child = context.Pipe() |
| 562 | process = context.Process(target=run_worker, args=(name, child, account.pw_uid, account.pw_gid, account.pw_dir)) |
| 563 | process.start(); child.close() |
| 564 | workers[name] = (process, parent) |
| 565 | if initialized: |
| 566 | parent.send(last) |
| 567 | available = bool(workers) |
| 568 | if available != announced: |
| 569 | print(json.dumps({'hello': {'version': 1, 'os': 'linux', 'session': session, |
| 570 | 'formats': ['text', 'png', 'files'], 'available': available, 'file_release': True}}), flush=True) |
| 571 | announced = available |
| 572 | while not commands.empty(): |
| 573 | message = commands.get() |
| 574 | if message is None: |
| 575 | running = False |
| 576 | break |
| 577 | if 'release' in message: |
| 578 | registry.retire(message['release']) |
| 579 | cleanup_needed = True |
| 580 | continue |
| 581 | serial = message.get('serial', 0) |
| 582 | last = {key: value for key, value in message.items() if key in ('text', 'png', 'files')} |
| 583 | initialized = True |
| 584 | registry.adopt(last.get('files', []), session) |
| 585 | pending[serial] = {'targets': set(workers), 'message': None, 'files': last.get('files', [])} |
| 586 | for _, connection in workers.values(): |
| 587 | connection.send({**last, 'serial': serial}) |
| 588 | if not pending[serial]['targets']: |
| 589 | print(json.dumps({'ack': serial}), flush=True) |
| 590 | del pending[serial] |
| 591 | for name, (process, connection) in list(workers.items()): |
| 592 | while process.is_alive() and connection.poll(): |
| 593 | try: |
| 594 | message = connection.recv() |
| 595 | except EOFError: |
| 596 | break |
| 597 | if 'clipboard_files' in message: |
| 598 | current_files[name] = message['clipboard_files'] |
| 599 | cleanup_needed = True |
| 600 | continue |
| 601 | if 'ack' in message: |
| 602 | serial = message['ack'] |
| 603 | if serial in pending: |
| 604 | pending[serial]['targets'].discard(name) |
| 605 | if not pending[serial]['targets']: |
| 606 | outgoing = pending[serial]['message'] |
| 607 | if outgoing is None: |
| 608 | print(json.dumps({'ack': serial}), flush=True) |
| 609 | elif {key: value for key, value in outgoing.items() if key in ('text','png','files')} == last: |
| 610 | print(json.dumps(outgoing), flush=True) |
| 611 | else: |
| 612 | registry.retire(outgoing.get('files', [])) |
| 613 | cleanup_needed = True |
| 614 | del pending[serial] |
| 615 | continue |
| 616 | if message.get('error'): |
| 617 | print(json.dumps(message), flush=True) |
| 618 | continue |
| 619 | payload = {key: value for key, value in message.items() if key in ('text', 'png', 'files')} |
| 620 | if not initialized or payload == last: |
| 621 | continue |
| 622 | if 'files' in payload: |
| 623 | try: |
| 624 | with registry.reading(payload['files']): |
| 625 | payload = {'files': materialize_guest_files(payload['files'], 'cage-browser' if name == ':77' else 'cage', session)} |
| 626 | message = {**payload, 'source': 'cage'} |
| 627 | except (ValueError, OSError, tarfile.TarError): |
| 628 | print('{"error":"剪贴板文件无法共享,请检查文件是否仍存在及读取权限。"}', flush=True) |
| 629 | continue |
| 630 | last = payload |
| 631 | internal_serial -= 1 |
| 632 | targets = set(workers) if 'files' in payload else set(workers) - {name} |
| 633 | pending[internal_serial] = {'targets': targets, 'message': message, 'files': payload.get('files', [])} |
| 634 | for other, (_, sibling) in workers.items(): |
| 635 | if other in targets: |
| 636 | sibling.send({**payload, 'serial': internal_serial}) |
| 637 | if not targets: |
| 638 | print(json.dumps(message), flush=True) |
| 639 | del pending[internal_serial] |
| 640 | if workers and all(name in current_files for name in workers) and (cleanup_needed or time.monotonic() >= next_cache_check): |
| 641 | try: |
| 642 | registry.collect(referenced_files(), session) |
| 643 | except (ValueError, OSError): |
| 644 | print('Clipboard cache cleanup failed; creation records retained.', file=sys.stderr) |
| 645 | cleanup_needed = False |
| 646 | next_cache_check = time.monotonic() + 1 |
| 647 | finally: |
| 648 | try: |
| 649 | registry.end_session(session) |
| 650 | for record in registry.records(): |
| 651 | if record['session'] == session: |
| 652 | registry.retire(record['paths']) |
| 653 | if workers and all(name in current_files for name in workers): |
| 654 | registry.collect(referenced_files(), session) |
| 655 | except (ValueError, OSError): |
| 656 | print('Clipboard cache cleanup failed; creation records retained.', file=sys.stderr) |
| 657 | selector.close() |
| 658 | for process, connection in workers.values(): |
| 659 | connection.close() |
| 660 | process.terminate(); process.join(timeout=2) |
| 661 | if process.is_alive(): |
| 662 | process.kill(); process.join() |
| 663 | |
| 664 | |
| 665 | if __name__ == '__main__': |
| 666 | if sys.argv[1:] == ['--import'] or len(sys.argv) == 4 and sys.argv[1:3] == ['--import', '--session']: |
| 667 | print(json.dumps({'paths': import_files(sys.stdin.buffer, sys.argv[3] if len(sys.argv) == 4 else '')})) |
| 668 | elif len(sys.argv) == 4 and sys.argv[1] == '--export-user' and sys.argv[2] in ('cage', 'cage-browser') and sys.argv[3] == '--paths-stdin': |
| 669 | import pwd |
| 670 | selection = sys.stdin.buffer.read((1 << 20) + 1) |
| 671 | if len(selection) > 1 << 20: |
| 672 | raise ValueError('file selection exceeded its limit') |
| 673 | paths = json.loads(selection) |
| 674 | with CacheRegistry().reading(paths): |
| 675 | account = pwd.getpwnam(sys.argv[2]) |
| 676 | os.initgroups(account.pw_name, account.pw_gid) |
| 677 | os.setgid(account.pw_gid) |
| 678 | os.setuid(account.pw_uid) |
| 679 | export_files(paths, sys.stdout.buffer) |
| 680 | elif len(sys.argv) == 3 and sys.argv[1] == '--export': |
| 681 | selection = sys.stdin.buffer.read((1 << 20) + 1) if sys.argv[2] == '--paths-stdin' else sys.argv[2] |
| 682 | if len(selection) > 1 << 20: |
| 683 | raise ValueError('file selection exceeded its limit') |
| 684 | export_files(json.loads(selection), sys.stdout.buffer) |
| 685 | else: |
| 686 | bridge() |