bridge_ownership.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. """Non-destructive bridge allocation for multiplexed secondary profiles."""
  2. import os
  3. import socket
  4. from contextlib import suppress
  5. from pathlib import Path
  6. # 3000 stays the default profile's historical port; secondaries allocate above it. 999 ports
  7. # covers any realistic number of paired phones on one host.
  8. SECONDARY_PORT_FIRST = 3001
  9. SECONDARY_PORT_LAST = 3999
  10. def port_is_free(port: int) -> bool:
  11. """Whether the WhatsApp Node bridge could bind ``port`` on 127.0.0.1 right now.
  12. Contract: this answers for the bridge's own bind semantics, not for an arbitrary binder. On
  13. POSIX the bridge (Express/libuv) sets SO_REUSEADDR, so a port holding only TIME-WAIT entries
  14. reads as free here even though a binder without SO_REUSEADDR would get EADDRINUSE; a live
  15. listener still reads as busy. Its callers are this module's bridge-port allocation and
  16. ownership checks and the adapter's pre-spawn wait for the old bridge to release its port.
  17. Do not reuse it to gate a process that binds without SO_REUSEADDR.
  18. """
  19. with socket.socket() as sock:
  20. # A just-stopped bridge can leave its accepted TCP connections in TIME-WAIT. The Node
  21. # bridge enables this option too, so match its bind semantics while still rejecting a listener.
  22. # POSIX only, like libuv: on Windows SO_REUSEADDR lets a bind share a live listener's port,
  23. # which would read a foreign bridge as free (Windows binds past TIME-WAIT without it).
  24. if os.name != "nt":
  25. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  26. try:
  27. sock.bind(("127.0.0.1", port))
  28. except OSError:
  29. return False
  30. return True
  31. def _read_port_record(record: Path) -> int:
  32. try:
  33. return int(record.read_text(encoding="utf-8-sig").strip())
  34. except ValueError:
  35. raise ValueError(f"Bridge port record {record} is not a port number; delete it to allocate a new port") from None
  36. def _sibling_claims(home: Path) -> set:
  37. """Ports other profiles' records claim. A sibling whose bridge is down leaves its port unbound, so a
  38. bind probe alone would hand it to this profile and the sibling would hit a conflict on its next start."""
  39. claims = set()
  40. for record in home.parent.glob("*/platforms/whatsapp/bridge_port"):
  41. if record.parents[2] != home:
  42. with suppress(OSError, ValueError):
  43. claims.add(_read_port_record(record))
  44. return claims
  45. def secondary_bridge_port(home: Path, explicit) -> int:
  46. record = home / "platforms/whatsapp/bridge_port"
  47. if explicit is not None:
  48. port = int(explicit)
  49. elif record.exists():
  50. port = _read_port_record(record)
  51. else:
  52. claimed = _sibling_claims(home)
  53. port = next((p for p in range(SECONDARY_PORT_FIRST, SECONDARY_PORT_LAST + 1)
  54. if p not in claimed and port_is_free(p)), None)
  55. if port is None:
  56. raise ValueError(f"No free bridge port in {SECONDARY_PORT_FIRST}..{SECONDARY_PORT_LAST}")
  57. record.parent.mkdir(parents=True, exist_ok=True)
  58. record.write_text(str(port), encoding="utf-8")
  59. if not 1 <= port <= 65535:
  60. raise ValueError(f"Invalid bridge port {port}")
  61. return port
  62. def standalone_bridge_port(home: Path, explicit) -> int:
  63. """Port for the launch profile's startup and for out-of-process sends; never allocates.
  64. Explicit config wins, then the profile's persisted record (written when it served as a
  65. secondary), then the historical default 3000. Startup and delivery share this one
  66. resolution so they always target the same bridge.
  67. """
  68. if explicit is not None:
  69. port = int(explicit)
  70. else:
  71. record = home / "platforms/whatsapp/bridge_port"
  72. if not record.exists():
  73. return 3000
  74. port = _read_port_record(record)
  75. if not 1 <= port <= 65535:
  76. raise ValueError(f"Invalid bridge port {port}")
  77. return port
  78. def check_secondary_ownership(session: Path, port: int) -> str:
  79. """``"free"`` when the port is unbound, ``"ours"`` when it is bound and this profile's own
  80. ``bridge.pid`` names a live process (pid plus kernel start time, the same fingerprint the default
  81. path trusts) that was spawned on this same port, so a bridge orphaned by a gateway crash can be
  82. adopted or reaped by identity. A live recorded bridge on a different port proves nothing about
  83. who holds this one. Anything else bound on the port belongs to someone else and is a fatal for
  84. this profile: no HTTP probe is safe before ownership is known, a healthy listener can still be
  85. another phone, and a secondary never signals a process it cannot prove is its own."""
  86. if port_is_free(port):
  87. return "free"
  88. from .adapter import _bridge_pid_is_ours, _read_bridge_pidfile
  89. pid, recorded_start, recorded_port = _read_bridge_pidfile(session)
  90. if pid is not None and recorded_port == port and _bridge_pid_is_ours(pid, recorded_start):
  91. return "ours"
  92. raise ValueError(f"Bridge port {port} is bound by a process this profile does not own")