compose_bridge.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. """Private Compose desktop transport. No network port or Docker socket."""
  2. import base64
  3. import http.server
  4. import json
  5. import os
  6. from pathlib import Path
  7. import secrets
  8. import signal
  9. import socketserver
  10. import subprocess
  11. import threading
  12. import time
  13. DESKTOP_ID = os.environ.get('YAOYAO_COMPOSE_DESKTOP_ID')
  14. if not DESKTOP_ID:
  15. raise SystemExit(0)
  16. ROOT = Path('/run/yaoyao-private')
  17. ROOT.mkdir(exist_ok=True)
  18. ROOT.chmod(0o700)
  19. BRIDGE = ROOT / 'bridge'
  20. BRIDGE.mkdir(exist_ok=True)
  21. BRIDGE.chmod(0o755)
  22. SOCKET = BRIDGE / 'desktop.sock'
  23. INSTANCE = secrets.token_hex(24)
  24. PID1 = Path('/proc/1/stat').read_text().split()[21]
  25. RESET = BRIDGE / 'reset.json'
  26. if RESET.exists() and json.loads(RESET.read_text()).get('pid1') == PID1:
  27. raise SystemExit(1) # A new bridge process alone cannot fence old programs.
  28. RESET.unlink(missing_ok=True)
  29. SOCKET.unlink(missing_ok=True)
  30. LOCK = threading.RLock()
  31. LEASE = None
  32. RESTARTING = False
  33. DRIVER = '/usr/local/libexec/openmausbot/cua-driver'
  34. CUA_SOCKET = '/run/user/1000/openmausbot-cua.sock'
  35. ENV = {'PATH': '/opt/venv/bin:/usr/local/bin:/usr/bin:/bin', 'HOME': '/home/cua', 'USER': 'cua', 'DISPLAY': ':1'}
  36. def reset_desktop():
  37. global RESTARTING, LEASE
  38. with LOCK:
  39. if RESTARTING:
  40. return
  41. RESTARTING = True
  42. LEASE = None
  43. RESET.write_text(json.dumps({'pid1': PID1}))
  44. # Compose restarts the same service and retains its workspace volume.
  45. threading.Timer(0.1, lambda: os.kill(1, signal.SIGTERM)).start()
  46. def current(body):
  47. if RESTARTING or not LEASE or body.get('token') != LEASE['token'] or body.get('instance') != INSTANCE or LEASE['expires'] <= time.monotonic():
  48. raise ValueError('桌面控制授权已失效')
  49. return LEASE
  50. def start(argv, cwd):
  51. # Change directory after dropping privileges: the persistent workspace is
  52. # owned by cua and the bridge does not need DAC_OVERRIDE.
  53. wrapper = 'import os,sys;os.chdir(sys.argv[1]);os.execvpe(sys.argv[2],sys.argv[2:],os.environ)'
  54. return subprocess.Popen(['python3','-c',wrapper,cwd,*argv], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=ENV, user=1000, group=1000, extra_groups=[], start_new_session=True)
  55. def run(argv, cwd='/home/cua/workspace', data=None, timeout=30):
  56. process = start(argv, cwd)
  57. try:
  58. stdout, stderr = process.communicate(data, timeout=timeout)
  59. except subprocess.TimeoutExpired:
  60. os.killpg(process.pid, signal.SIGKILL)
  61. process.communicate()
  62. raise ValueError('桌面画面服务尚未就绪')
  63. if len(stdout) + len(stderr) > 8 * 1024 * 1024:
  64. raise ValueError('桌面命令输出超过限制')
  65. return {'stdout': stdout.decode('utf-8', 'replace'), 'stderr': stderr.decode('utf-8', 'replace'), 'exitCode': process.returncode}
  66. class Handler(http.server.BaseHTTPRequestHandler):
  67. def log_message(self, *args):
  68. pass
  69. def do_POST(self):
  70. global LEASE
  71. try:
  72. length = int(self.headers.get('Content-Length', '0'))
  73. if length > 36 * 1024 * 1024:
  74. raise ValueError('请求过大')
  75. body = json.loads(self.rfile.read(length) or b'{}')
  76. if body.get('desktopId') != DESKTOP_ID:
  77. raise ValueError('桌面身份不匹配')
  78. op = self.path
  79. if op == '/health':
  80. ready = False
  81. if not RESTARTING:
  82. try:
  83. result = run([DRIVER, 'call', 'health_report', '{}', '--socket', CUA_SOCKET], timeout=5)
  84. ready = result['exitCode'] == 0
  85. except Exception:
  86. pass
  87. result = {'id': DESKTOP_ID, 'protocol': 1, 'instance': INSTANCE, 'ready': ready}
  88. elif op == '/acquire':
  89. with LOCK:
  90. if RESTARTING:
  91. raise ValueError('桌面正在重置')
  92. if LEASE:
  93. if body.get('requestId') != LEASE['requestId'] or body.get('owner') != LEASE['owner']:
  94. raise ValueError('共享桌面正在使用')
  95. current({'token': LEASE['token'], 'instance': INSTANCE})
  96. else:
  97. if not isinstance(body.get('requestId'), str) or not isinstance(body.get('owner'), str):
  98. raise ValueError('缺少桌面授权身份')
  99. LEASE = {'requestId': body['requestId'], 'owner': body['owner'], 'token': secrets.token_hex(32), 'expires': time.monotonic() + 90, 'active': 0}
  100. result = {'token': LEASE['token'], 'instance': INSTANCE}
  101. elif op == '/renew':
  102. with LOCK:
  103. current(body)['expires'] = time.monotonic() + 90
  104. result = {'ok': True}
  105. elif op == '/release':
  106. with LOCK:
  107. current(body)
  108. if LEASE['active'] and not body.get('cancel'):
  109. raise ValueError('共享桌面仍有未结束操作')
  110. LEASE = None
  111. result = {'ok': True}
  112. if body.get('cancel'):
  113. reset_desktop()
  114. elif op == '/frame':
  115. path = '/tmp/yaoyao-compose-' + secrets.token_hex(12) + '.png'
  116. try:
  117. frame = run([DRIVER, 'call', 'get_desktop_state', '{}', '--socket', CUA_SOCKET, '--screenshot-out-file', path], timeout=10)
  118. if frame['exitCode'] != 0:
  119. raise ValueError('桌面画面尚未就绪')
  120. data = Path(path).read_bytes()
  121. if data[1:4] != b'PNG':
  122. raise ValueError('桌面画面无效')
  123. result = {'data': base64.b64encode(data).decode(), 'width': int.from_bytes(data[16:20], 'big'), 'height': int.from_bytes(data[20:24], 'big'), 'capturedAt': int(time.time()*1000)}
  124. finally:
  125. Path(path).unlink(missing_ok=True)
  126. elif op == '/execute':
  127. argv = body.get('argv')
  128. if not isinstance(argv, list) or not argv or len(argv) > 64 or any(not isinstance(x, str) or '\0' in x for x in argv) or sum(map(len, argv)) > 65536:
  129. raise ValueError('桌面命令无效')
  130. cwd = body.get('cwd', '/home/cua/workspace')
  131. if not isinstance(cwd, str) or (cwd != '/home/cua/workspace' and not cwd.startswith('/home/cua/workspace/')) or '..' in Path(cwd).parts:
  132. raise ValueError('Compose 桌面工作目录必须位于 /home/cua/workspace')
  133. with LOCK:
  134. lease = current(body)
  135. # Spawn while holding the lease lock, then release the lock
  136. # before waiting so revocation can stop the container.
  137. process = start(argv, cwd)
  138. lease['active'] += 1
  139. try:
  140. data = base64.b64decode(body['input']) if body.get('input') else None
  141. stdout, stderr = process.communicate(data, timeout=min(60, max(1, body.get('timeout', 30000)/1000)))
  142. if len(stdout) + len(stderr) > 8*1024*1024:
  143. raise ValueError('桌面命令输出超过限制')
  144. with LOCK:
  145. current(body)
  146. result = {'stdout': stdout.decode('utf-8','replace'), 'stderr': stderr.decode('utf-8','replace'), 'exitCode': process.returncode}
  147. except Exception:
  148. reset_desktop()
  149. raise
  150. finally:
  151. with LOCK:
  152. if LEASE is lease:
  153. lease['active'] -= 1
  154. else:
  155. raise ValueError('桌面数量和创建删除由 Compose 管理')
  156. payload = json.dumps(result).encode()
  157. self.send_response(200)
  158. except Exception as exc:
  159. code = 'computer_busy' if str(exc) in ('共享桌面正在使用','共享桌面仍有未结束操作') else 'compose_desktop_error'
  160. payload = json.dumps({'error': str(exc), 'code': code}, ensure_ascii=False).encode()
  161. self.send_response(409)
  162. self.send_header('Content-Type','application/json')
  163. self.send_header('X-Yaoyao-Desktop-Id',DESKTOP_ID)
  164. self.send_header('Content-Length',str(len(payload)))
  165. self.end_headers()
  166. try:
  167. self.wfile.write(payload)
  168. except BrokenPipeError:
  169. pass
  170. class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
  171. daemon_threads = True
  172. def expire():
  173. while True:
  174. time.sleep(5)
  175. with LOCK:
  176. expired = LEASE and LEASE['expires'] <= time.monotonic()
  177. if expired:
  178. reset_desktop()
  179. server = Server(str(SOCKET), Handler)
  180. SOCKET.chmod(0o600)
  181. os.chown(SOCKET,1000,1000)
  182. threading.Thread(target=expire,daemon=True).start()
  183. server.serve_forever()