patch_runtime.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. """Small fail-closed fixes applied to the exported, immutable baseline sources."""
  2. import ast
  3. DELIVERY_MARKER = '# FMODE_ROOM_SCOPED_REUSE_V1'
  4. OLD_HUB = ''' if (chk.get("count") or 0) > 0 and (chk.get("files") or []):
  5. first = chk["files"][0]'''
  6. NEW_HUB = ''' # FMODE_ROOM_SCOPED_REUSE_V1: a URL in another room is not this room's registration.
  7. matches = [item for item in (chk.get("files") or [])
  8. if isinstance(item, dict) and item.get("roomId") == room_id
  9. and (not item.get("agentId") or item.get("agentId") == _resolve_agent_id())]
  10. if matches:
  11. first = matches[0]'''
  12. OLD_REUSE = ''' log("REUSE %s url=%s did=%s" % (owner, cached_url, old.get("id")))
  13. res.append({"path": owner, "ok": True, "url": cached_url,
  14. "did": old.get("id"), "detail": "reused-existing"})'''
  15. NEW_REUSE = ''' if any(item.get("path") == owner and item.get("url") for item in res):
  16. continue
  17. hub = _hub_register(owner, cached_url, thread_root, room_id, old.get("id"))
  18. digest = hashlib.sha256()
  19. with open(owner, "rb") as stream:
  20. for chunk in iter(lambda: stream.read(1 << 20), b""):
  21. digest.update(chunk)
  22. log("REUSE %s url=%s did=%s registered=%s" % (owner, cached_url, old.get("id"), hub.get("ok")))
  23. res.append({"path": owner, "ok": hub.get("ok") is True, "url": cached_url,
  24. "did": old.get("id"), "hub": hub, "sha256": digest.hexdigest(),
  25. "detail": "reused-existing" if hub.get("ok") is True else "reuse-register-failed"})'''
  26. OLD_NOTICE = ''' subprocess.Popen(
  27. ["python3", str(NOTICE_SCRIPT)],
  28. stdin=subprocess.PIPE,
  29. stdout=subprocess.DEVNULL,
  30. stderr=subprocess.DEVNULL,
  31. env=env,
  32. start_new_session=True,
  33. ).communicate(input=json.dumps(payload, ensure_ascii=False).encode("utf-8"))'''
  34. NEW_NOTICE = ''' # FMODE_NOTICE_NONBLOCKING_V1: file-backed stdin cannot wait on child network I/O.
  35. import tempfile
  36. import threading
  37. with tempfile.TemporaryFile(mode="w+b") as input_stream:
  38. input_stream.write(json.dumps(payload, ensure_ascii=False).encode("utf-8"))
  39. input_stream.seek(0)
  40. worker = subprocess.Popen(
  41. ["python3", str(NOTICE_SCRIPT)], stdin=input_stream,
  42. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
  43. env=env, start_new_session=True,
  44. )
  45. threading.Thread(target=worker.wait, daemon=True).start()'''
  46. def once(source, old, new):
  47. if source.count(old) != 1:
  48. raise ValueError('Runtime differs from verified baseline; refusing partial patch')
  49. return source.replace(old, new, 1)
  50. def patch_delivery(source):
  51. ast.parse(source)
  52. if DELIVERY_MARKER in source:
  53. if not all(item in source for item in [NEW_HUB, NEW_REUSE, NEW_NOTICE]):
  54. raise ValueError('Incomplete room-reuse or nonblocking-notice patch')
  55. return source
  56. updated = once(source, OLD_HUB, NEW_HUB)
  57. updated = once(updated, OLD_REUSE, NEW_REUSE)
  58. updated = once(updated, 'reused = {r["path"] for r in res if r.get("ok")}',
  59. 'reused = {r["path"] for r in res if r.get("ok") or r.get("detail") == "reuse-register-failed"}')
  60. updated = once(updated, OLD_NOTICE, NEW_NOTICE)
  61. ast.parse(updated)
  62. return updated
  63. OLD_ALREADY = ''' if "_is_allowed_media_url" in s or "async def _fetch_http_media" in s:
  64. rep.append("已存在补丁标记 → 视为已打过(跳过)")
  65. return s, rep, True'''
  66. NEW_ALREADY = ''' ast.parse(s)
  67. if "_is_allowed_media_url" in s or "async def _fetch_http_media" in s:
  68. # FMODE_ATOMIC_MEDIA_PATCH_V1: syntax and the complete transformation are required.
  69. if not all(part in s for part in (B1, B2, B3, "def _is_allowed_media_url(", "async def _fetch_http_media(")):
  70. raise ValueError("残缺的媒体补丁,保留原文件并停止启动;请检查已验证备份")
  71. rep.append("已验证完整媒体补丁与语法,跳过")
  72. return s, rep, True'''
  73. OLD_WRITE = '''def write(p, s):
  74. io.open(p, "w", encoding="utf-8").write(s)'''
  75. NEW_WRITE = '''def write(p, s):
  76. compile(s, p, "exec")
  77. directory = os.path.dirname(p) or "."
  78. fd, temporary = tempfile.mkstemp(prefix=".fmode-media-", suffix=".tmp", dir=directory)
  79. try:
  80. with os.fdopen(fd, "w", encoding="utf-8") as stream:
  81. stream.write(s)
  82. stream.flush()
  83. os.fsync(stream.fileno())
  84. if os.path.exists(p):
  85. os.chmod(temporary, os.stat(p).st_mode & 0o7777)
  86. os.replace(temporary, p)
  87. finally:
  88. if os.path.exists(temporary):
  89. os.unlink(temporary)'''
  90. def patch_media(source):
  91. ast.parse(source)
  92. if 'FMODE_ATOMIC_MEDIA_PATCH_V1' in source:
  93. if NEW_ALREADY not in source or NEW_WRITE not in source:
  94. raise ValueError('Incomplete atomic media patch')
  95. return source
  96. updated = once(source, 'import argparse\n', 'import argparse\nimport ast\nimport tempfile\n')
  97. updated = once(updated, OLD_ALREADY, NEW_ALREADY)
  98. updated = once(updated, OLD_WRITE, NEW_WRITE)
  99. updated = once(updated, 'shutil.copy2(baks[-1], TARGET)', 'write(TARGET, read(baks[-1]))')
  100. updated = once(updated, 'shutil.copy2(bak, TARGET)', 'write(TARGET, read(bak))')
  101. ast.parse(updated)
  102. return updated