| 1 | |
| 2 | """Receive a validated PNG on stdin; never read host paths or use the network.""" |
| 3 | import ctypes as C |
| 4 | import fcntl |
| 5 | import json |
| 6 | import os |
| 7 | from pathlib import Path |
| 8 | import select |
| 9 | import signal |
| 10 | import subprocess |
| 11 | import sys |
| 12 | import tempfile |
| 13 | |
| 14 | |
| 15 | def save_image(data): |
| 16 | directory = Path.home() / '.local/share/cage/attachments' |
| 17 | directory.mkdir(parents=True, exist_ok=True, mode=0o700) |
| 18 | fd, path = tempfile.mkstemp(prefix='image-', suffix='.png', dir=directory) |
| 19 | try: |
| 20 | with os.fdopen(fd, 'wb') as stream: |
| 21 | stream.write(data) |
| 22 | except BaseException: |
| 23 | os.unlink(path) |
| 24 | raise |
| 25 | return {'path': path} |
| 26 | |
| 27 | |
| 28 | def clipboard_owner(data, ack): |
| 29 | |
| 30 | |
| 31 | gtk = C.CDLL('libgtk-3.so.0') |
| 32 | gdk = C.CDLL('libgdk-3.so.0') |
| 33 | glib = C.CDLL('libglib-2.0.so.0') |
| 34 | pointer = C.c_void_p |
| 35 | def bind(lib, name, result, *args): |
| 36 | fn = getattr(lib, name) |
| 37 | fn.restype, fn.argtypes = result, list(args) |
| 38 | return fn |
| 39 | init = bind(gtk, 'gtk_init_check', C.c_int, pointer, pointer) |
| 40 | atom = bind(gdk, 'gdk_atom_intern_static_string', pointer, C.c_char_p) |
| 41 | get = bind(gtk, 'gtk_clipboard_get', pointer, pointer) |
| 42 | set_data = bind(gtk, 'gtk_selection_data_set', None, pointer, pointer, C.c_int, pointer, C.c_int) |
| 43 | flush = bind(gdk, 'gdk_flush', None) |
| 44 | main = bind(gtk, 'gtk_main', None) |
| 45 | quit_main = bind(gtk, 'gtk_main_quit', None) |
| 46 | callback = C.CFUNCTYPE(C.c_int, pointer) |
| 47 | timeout = bind(glib, 'g_timeout_add', C.c_uint, C.c_uint, callback, pointer) |
| 48 | class Target(C.Structure): |
| 49 | _fields_ = [('target', C.c_char_p), ('flags', C.c_uint), ('info', C.c_uint)] |
| 50 | provide_type = C.CFUNCTYPE(None, pointer, pointer, C.c_uint, pointer) |
| 51 | clear_type = C.CFUNCTYPE(None, pointer, pointer) |
| 52 | own = bind(gtk, 'gtk_clipboard_set_with_data', C.c_int, pointer, C.POINTER(Target), C.c_uint, provide_type, clear_type, pointer) |
| 53 | if not init(None, None): |
| 54 | raise RuntimeError('display unavailable') |
| 55 | png = atom(b'image/png') |
| 56 | buffer = C.create_string_buffer(data) |
| 57 | acknowledged = False |
| 58 | @callback |
| 59 | def stop(_): |
| 60 | quit_main() |
| 61 | return 0 |
| 62 | @provide_type |
| 63 | def provide(_clipboard, selection, _info, _user): |
| 64 | nonlocal acknowledged |
| 65 | set_data(selection, png, 8, buffer, len(data)) |
| 66 | flush() |
| 67 | if not acknowledged: |
| 68 | os.write(ack, b'ok') |
| 69 | os.close(ack) |
| 70 | acknowledged = True |
| 71 | @clear_type |
| 72 | def clear(_clipboard, _user): |
| 73 | |
| 74 | timeout(10000, stop, None) |
| 75 | targets = (Target * 1)(Target(b'image/png', 0, 0)) |
| 76 | if not own(get(atom(b'CLIPBOARD')), targets, 1, provide, clear, None): |
| 77 | raise RuntimeError('clipboard unavailable') |
| 78 | flush() |
| 79 | subprocess.run(['xdotool', 'key', '--clearmodifiers', 'ctrl+v'], check=True, |
| 80 | stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=3) |
| 81 | timeout(120000, stop, None) |
| 82 | main() |
| 83 | |
| 84 | |
| 85 | def paste_image(data): |
| 86 | lock_dir = Path.home() / '.cache/cage' |
| 87 | lock_dir.mkdir(parents=True, exist_ok=True, mode=0o700) |
| 88 | with open(lock_dir / 'image-input.lock', 'a') as lock: |
| 89 | fcntl.flock(lock, fcntl.LOCK_EX) |
| 90 | read_fd, write_fd = os.pipe() |
| 91 | pid = os.fork() |
| 92 | if pid == 0: |
| 93 | os.close(read_fd) |
| 94 | lock.close() |
| 95 | os.setsid() |
| 96 | with open(os.devnull, 'r+b') as null: |
| 97 | for fd in (0, 1, 2): |
| 98 | os.dup2(null.fileno(), fd) |
| 99 | try: |
| 100 | clipboard_owner(data, write_fd) |
| 101 | finally: |
| 102 | os._exit(0) |
| 103 | os.close(write_fd) |
| 104 | try: |
| 105 | ready, _, _ = select.select([read_fd], [], [], 10) |
| 106 | if not ready or os.read(read_fd, 2) != b'ok': |
| 107 | os.kill(pid, signal.SIGTERM) |
| 108 | os.waitpid(pid, 0) |
| 109 | raise RuntimeError('目标没有接收图片,请点击支持图片的输入框后重试;若环境组件过旧,请先更新环境') |
| 110 | finally: |
| 111 | os.close(read_fd) |
| 112 | return {'ok': True} |
| 113 | |
| 114 | |
| 115 | if __name__ == '__main__': |
| 116 | try: |
| 117 | data = sys.stdin.buffer.read(20 * 1024 * 1024 + 1) |
| 118 | if not data.startswith(b'\x89PNG\r\n\x1a\n') or len(data) > 20 * 1024 * 1024: |
| 119 | raise ValueError('PNG input invalid') |
| 120 | if sys.argv[1:] == ['save']: |
| 121 | result = save_image(data) |
| 122 | elif sys.argv[1:] == ['paste']: |
| 123 | result = paste_image(data) |
| 124 | else: |
| 125 | raise ValueError('unknown action') |
| 126 | print(json.dumps(result)) |
| 127 | except Exception as error: |
| 128 | print(str(error), file=sys.stderr) |
| 129 | sys.exit(1) |