ssdp_server.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. """SSDP discovery responder for virtual printer.
  2. Responds to M-SEARCH requests from slicers and sends periodic NOTIFY
  3. announcements so the virtual printer appears as a discoverable Bambu printer.
  4. Also provides SSDP proxy functionality for proxy mode, where Bambuddy sits
  5. between two networks and re-broadcasts printer SSDP from LAN A to LAN B.
  6. """
  7. import asyncio
  8. import logging
  9. import re
  10. import socket
  11. import struct
  12. logger = logging.getLogger(__name__)
  13. # SSDP addresses - Bambu uses port 2021
  14. # Real Bambu printers broadcast to 255.255.255.255, not multicast to 239.255.255.250
  15. SSDP_MULTICAST_ADDR = "239.255.255.250"
  16. SSDP_BROADCAST_ADDR = "255.255.255.255"
  17. SSDP_PORT = 2021
  18. # Bambu service target
  19. BAMBU_SEARCH_TARGET = "urn:bambulab-com:device:3dprinter:1"
  20. class VirtualPrinterSSDPServer:
  21. """SSDP server that responds to discovery requests as a virtual Bambu printer."""
  22. def __init__(
  23. self,
  24. name: str = "Bambuddy",
  25. serial: str = "00M09A391800001", # X1C serial format for compatibility
  26. model: str = "BL-P001", # X1C model code for best compatibility
  27. advertise_ip: str = "",
  28. ):
  29. """Initialize the SSDP server.
  30. Args:
  31. name: Display name shown in slicer discovery
  32. serial: Unique serial number for this virtual printer (must match cert CN)
  33. model: Model code (BL-P001=X1C, C11=P1S, O1D=H2D)
  34. advertise_ip: Override IP to advertise instead of auto-detecting
  35. """
  36. self.name = name
  37. self.serial = serial
  38. self.model = model
  39. self._running = False
  40. self._socket: socket.socket | None = None
  41. self._local_ip: str | None = advertise_ip or None
  42. def _get_local_ip(self) -> str:
  43. """Get the local IP address to advertise."""
  44. if self._local_ip:
  45. return self._local_ip
  46. # Try to determine local IP by connecting to a public address
  47. try:
  48. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  49. s.connect(("8.8.8.8", 80))
  50. ip = s.getsockname()[0]
  51. s.close()
  52. self._local_ip = ip
  53. return ip
  54. except OSError:
  55. return "127.0.0.1"
  56. def _build_notify_message(self) -> bytes:
  57. """Build SSDP NOTIFY message for periodic announcements.
  58. Format matches real Bambu printer SSDP broadcasts observed on the network.
  59. Real printers use Host: 239.255.255.250:1990 (port 1990 in header).
  60. """
  61. ip = self._get_local_ip()
  62. # Match exact format of real Bambu printers (captured via tcpdump)
  63. # Key: DevBind.bambu.com: free - tells slicer printer is NOT cloud-bound
  64. message = (
  65. "NOTIFY * HTTP/1.1\r\n"
  66. f"Host: {SSDP_MULTICAST_ADDR}:1990\r\n"
  67. "Server: UPnP/1.0\r\n"
  68. f"Location: {ip}\r\n"
  69. f"NT: {BAMBU_SEARCH_TARGET}\r\n"
  70. "NTS: ssdp:alive\r\n"
  71. f"USN: {self.serial}\r\n"
  72. "Cache-Control: max-age=1800\r\n"
  73. f"DevModel.bambu.com: {self.model}\r\n"
  74. f"DevName.bambu.com: {self.name}\r\n"
  75. "DevSignal.bambu.com: -44\r\n"
  76. "DevConnect.bambu.com: lan\r\n"
  77. "DevBind.bambu.com: free\r\n"
  78. "Devseclink.bambu.com: secure\r\n"
  79. "DevInf.bambu.com: eth0\r\n"
  80. "DevVersion.bambu.com: 01.07.00.00\r\n"
  81. "DevCap.bambu.com: 1\r\n"
  82. "\r\n"
  83. )
  84. return message.encode()
  85. def _build_response_message(self) -> bytes:
  86. """Build SSDP response message for M-SEARCH requests.
  87. Format matches real Bambu printer SSDP responses.
  88. """
  89. ip = self._get_local_ip()
  90. # Match format of real Bambu printers
  91. # Key: DevBind.bambu.com: free - tells slicer printer is NOT cloud-bound
  92. message = (
  93. "HTTP/1.1 200 OK\r\n"
  94. "Server: UPnP/1.0\r\n"
  95. f"Location: {ip}\r\n"
  96. f"ST: {BAMBU_SEARCH_TARGET}\r\n"
  97. f"USN: {self.serial}\r\n"
  98. "Cache-Control: max-age=1800\r\n"
  99. f"DevModel.bambu.com: {self.model}\r\n"
  100. f"DevName.bambu.com: {self.name}\r\n"
  101. "DevSignal.bambu.com: -44\r\n"
  102. "DevConnect.bambu.com: lan\r\n"
  103. "DevBind.bambu.com: free\r\n"
  104. "Devseclink.bambu.com: secure\r\n"
  105. "DevInf.bambu.com: eth0\r\n"
  106. "DevVersion.bambu.com: 01.07.00.00\r\n"
  107. "DevCap.bambu.com: 1\r\n"
  108. "\r\n"
  109. )
  110. return message.encode()
  111. async def start(self) -> None:
  112. """Start the SSDP server."""
  113. if self._running:
  114. return
  115. logger.info("Starting virtual printer SSDP server: %s (%s)", self.name, self.serial)
  116. self._running = True
  117. try:
  118. # Create UDP socket
  119. self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  120. self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  121. # Try to set SO_REUSEPORT if available
  122. try:
  123. self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  124. except (AttributeError, OSError):
  125. pass # SO_REUSEPORT not available on all platforms; non-critical
  126. # Set non-blocking mode
  127. self._socket.setblocking(False)
  128. # Bind to SSDP port
  129. self._socket.bind(("", SSDP_PORT))
  130. # Join multicast group
  131. mreq = struct.pack("4sl", socket.inet_aton(SSDP_MULTICAST_ADDR), socket.INADDR_ANY)
  132. self._socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
  133. # Enable broadcast
  134. self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  135. # Set multicast TTL
  136. self._socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
  137. local_ip = self._get_local_ip()
  138. logger.info("SSDP server listening on port %s, advertising IP: %s", SSDP_PORT, local_ip)
  139. logger.info("Virtual printer: %s (%s) model=%s", self.name, self.serial, self.model)
  140. # Send initial NOTIFY
  141. await self._send_notify()
  142. logger.info("Sent initial SSDP NOTIFY announcement")
  143. # Run receive and announce loops
  144. last_notify = asyncio.get_event_loop().time()
  145. notify_interval = 30.0 # Send NOTIFY every 30 seconds
  146. while self._running:
  147. # Try to receive M-SEARCH requests
  148. try:
  149. data, addr = self._socket.recvfrom(4096)
  150. message = data.decode("utf-8", errors="ignore")
  151. await self._handle_message(message, addr)
  152. except BlockingIOError:
  153. pass # No data available on non-blocking socket; will retry
  154. except OSError as e:
  155. if self._running:
  156. logger.debug("SSDP receive error: %s", e)
  157. # Send periodic NOTIFY
  158. now = asyncio.get_event_loop().time()
  159. if now - last_notify >= notify_interval:
  160. await self._send_notify()
  161. last_notify = now
  162. await asyncio.sleep(0.1)
  163. except OSError as e:
  164. if e.errno == 98: # Address already in use
  165. logger.warning("SSDP port %s in use - real printers may be running", SSDP_PORT)
  166. else:
  167. logger.error("SSDP server error: %s", e)
  168. except asyncio.CancelledError:
  169. logger.debug("SSDP server cancelled")
  170. except Exception as e:
  171. logger.error("SSDP server error: %s", e)
  172. finally:
  173. await self._cleanup()
  174. async def stop(self) -> None:
  175. """Stop the SSDP server."""
  176. logger.info("Stopping SSDP server")
  177. self._running = False
  178. await self._cleanup()
  179. async def _cleanup(self) -> None:
  180. """Clean up resources."""
  181. if self._socket:
  182. try:
  183. # Send byebye message
  184. await self._send_byebye()
  185. except OSError:
  186. pass # Best-effort byebye broadcast; socket may already be closed
  187. try:
  188. self._socket.close()
  189. except OSError:
  190. pass # Best-effort socket close; may already be released
  191. self._socket = None
  192. async def _send_notify(self) -> None:
  193. """Send SSDP NOTIFY message via broadcast (like real Bambu printers)."""
  194. if not self._socket:
  195. return
  196. try:
  197. msg = self._build_notify_message()
  198. # Real Bambu printers broadcast to 255.255.255.255, not multicast
  199. self._socket.sendto(msg, (SSDP_BROADCAST_ADDR, SSDP_PORT))
  200. logger.debug("Sent SSDP NOTIFY for %s", self.name)
  201. except OSError as e:
  202. logger.debug("Failed to send NOTIFY: %s", e)
  203. async def _send_byebye(self) -> None:
  204. """Send SSDP byebye message when shutting down."""
  205. if not self._socket:
  206. return
  207. message = (
  208. "NOTIFY * HTTP/1.1\r\n"
  209. f"Host: {SSDP_MULTICAST_ADDR}:1990\r\n"
  210. f"NT: {BAMBU_SEARCH_TARGET}\r\n"
  211. "NTS: ssdp:byebye\r\n"
  212. f"USN: {self.serial}\r\n"
  213. "\r\n"
  214. )
  215. try:
  216. self._socket.sendto(message.encode(), (SSDP_BROADCAST_ADDR, SSDP_PORT))
  217. logger.debug("Sent SSDP byebye")
  218. except OSError:
  219. pass # Best-effort byebye send; network may be unavailable during shutdown
  220. async def _handle_message(self, message: str, addr: tuple[str, int]) -> None:
  221. """Handle incoming SSDP message.
  222. Args:
  223. message: The SSDP message content
  224. addr: Tuple of (ip_address, port) of sender
  225. """
  226. # Check if this is an M-SEARCH request for Bambu printers
  227. if "M-SEARCH" not in message:
  228. return
  229. # Check search target
  230. if BAMBU_SEARCH_TARGET not in message and "ssdp:all" not in message.lower():
  231. return
  232. logger.debug("Received M-SEARCH from %s", addr[0])
  233. # Send response
  234. if self._socket:
  235. try:
  236. response = self._build_response_message()
  237. self._socket.sendto(response, addr)
  238. logger.info("Sent SSDP response to %s for virtual printer '%s'", addr[0], self.name)
  239. except OSError as e:
  240. logger.debug("Failed to send SSDP response: %s", e)
  241. class SSDPProxy:
  242. """SSDP proxy that re-broadcasts printer discovery from one network to another.
  243. Listens for SSDP broadcasts from a real printer on the local interface (LAN A),
  244. then re-broadcasts them on the remote interface (LAN B) with the Location
  245. header changed to point to Bambuddy's IP on LAN B.
  246. This allows Bambu Studio on LAN B to discover the printer via Bambuddy.
  247. """
  248. def __init__(
  249. self,
  250. local_interface_ip: str,
  251. remote_interface_ip: str,
  252. target_printer_ip: str,
  253. ):
  254. """Initialize the SSDP proxy.
  255. Args:
  256. local_interface_ip: IP of interface on printer's network (LAN A)
  257. remote_interface_ip: IP of interface on slicer's network (LAN B)
  258. target_printer_ip: IP of the real printer to proxy SSDP for
  259. """
  260. self.local_interface_ip = local_interface_ip
  261. self.remote_interface_ip = remote_interface_ip
  262. self.target_printer_ip = target_printer_ip
  263. self._running = False
  264. self._local_socket: socket.socket | None = None
  265. self._remote_socket: socket.socket | None = None
  266. self._last_printer_ssdp: bytes | None = None
  267. self._printer_info: dict[str, str] = {}
  268. def _parse_ssdp_message(self, data: bytes) -> dict[str, str]:
  269. """Parse SSDP message into header dict."""
  270. headers = {}
  271. try:
  272. text = data.decode("utf-8", errors="ignore")
  273. for line in text.split("\r\n"):
  274. if ":" in line:
  275. key, value = line.split(":", 1)
  276. headers[key.strip().lower()] = value.strip()
  277. except Exception:
  278. pass # Return partial headers if parsing fails; malformed packets are common
  279. return headers
  280. def _rewrite_ssdp(self, data: bytes) -> bytes:
  281. """Rewrite SSDP message for proxy re-broadcast.
  282. - Location: changed to Bambuddy's remote interface IP
  283. - DevBind: forced to 'free' so the slicer treats the proxy as a
  284. LAN-only printer (avoids cloud auth requirement for sending prints)
  285. """
  286. try:
  287. text = data.decode("utf-8", errors="ignore")
  288. original = text
  289. # Replace Location header with our remote interface IP
  290. text = re.sub(
  291. r"(Location:\s*)[\d.]+",
  292. f"\\g<1>{self.remote_interface_ip}",
  293. text,
  294. flags=re.IGNORECASE,
  295. )
  296. # Force DevBind to 'free' - ensures slicer uses LAN mode for
  297. # both monitoring AND sending prints through the proxy
  298. text = re.sub(
  299. r"(DevBind\.bambu\.com:\s*)\S+",
  300. r"\g<1>free",
  301. text,
  302. flags=re.IGNORECASE,
  303. )
  304. # Append " - Proxy" to printer name so it's distinguishable
  305. text = re.sub(
  306. r"(DevName\.bambu\.com:\s*)(.+)",
  307. r"\g<1>\g<2> - Proxy",
  308. text,
  309. flags=re.IGNORECASE,
  310. )
  311. if text != original:
  312. logger.debug("Rewrote SSDP for proxy:\n%s", text)
  313. else:
  314. logger.warning("SSDP rewrite had no effect. Packet:\n%s", original)
  315. return text.encode("utf-8")
  316. except Exception as e:
  317. logger.error("Failed to rewrite SSDP: %s", e)
  318. return data
  319. async def start(self) -> None:
  320. """Start the SSDP proxy."""
  321. if self._running:
  322. return
  323. logger.info(
  324. f"Starting SSDP proxy: listening on {self.local_interface_ip} (LAN A), "
  325. f"broadcasting on {self.remote_interface_ip} (LAN B), "
  326. f"proxying printer {self.target_printer_ip}"
  327. )
  328. self._running = True
  329. try:
  330. # Create socket for listening on LAN A (printer network)
  331. # Bind to 0.0.0.0 to receive broadcast packets (255.255.255.255)
  332. # We filter by source IP in the handler
  333. self._local_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  334. self._local_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  335. try:
  336. self._local_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  337. except (AttributeError, OSError):
  338. pass # SO_REUSEPORT not available on all platforms; non-critical
  339. self._local_socket.setblocking(False)
  340. # Bind to all interfaces to receive broadcasts
  341. self._local_socket.bind(("", SSDP_PORT))
  342. # Join multicast group on local interface (for multicast SSDP if used)
  343. mreq = struct.pack(
  344. "4s4s",
  345. socket.inet_aton(SSDP_MULTICAST_ADDR),
  346. socket.inet_aton(self.local_interface_ip),
  347. )
  348. self._local_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
  349. self._local_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  350. # Create socket for broadcasting on LAN B (slicer network)
  351. self._remote_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  352. self._remote_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  353. try:
  354. self._remote_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  355. except (AttributeError, OSError):
  356. pass # SO_REUSEPORT not available on all platforms; non-critical
  357. self._remote_socket.setblocking(False)
  358. # Bind to remote interface
  359. self._remote_socket.bind((self.remote_interface_ip, 0))
  360. self._remote_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  361. logger.info(
  362. "SSDP proxy listening on 0.0.0.0:%s (filtering for printer %s)", SSDP_PORT, self.target_printer_ip
  363. )
  364. logger.info("SSDP proxy will broadcast on %s", self.remote_interface_ip)
  365. # Main loop
  366. last_broadcast = 0.0
  367. broadcast_interval = 30.0 # Re-broadcast every 30 seconds
  368. while self._running:
  369. # Listen for SSDP from printer on LAN A
  370. try:
  371. data, addr = self._local_socket.recvfrom(4096)
  372. await self._handle_local_packet(data, addr)
  373. except BlockingIOError:
  374. pass # No data available on non-blocking socket; will retry
  375. except OSError as e:
  376. if self._running:
  377. logger.debug("SSDP proxy receive error: %s", e)
  378. # Listen for M-SEARCH from slicer on LAN B (via remote socket would need separate bind)
  379. # For now, we periodically re-broadcast cached printer SSDP
  380. now = asyncio.get_event_loop().time()
  381. if self._last_printer_ssdp and now - last_broadcast >= broadcast_interval:
  382. await self._broadcast_to_remote()
  383. last_broadcast = now
  384. await asyncio.sleep(0.1)
  385. except OSError as e:
  386. logger.error("SSDP proxy error: %s", e)
  387. except asyncio.CancelledError:
  388. logger.debug("SSDP proxy cancelled")
  389. except Exception as e:
  390. logger.error("SSDP proxy error: %s", e)
  391. finally:
  392. await self._cleanup()
  393. async def stop(self) -> None:
  394. """Stop the SSDP proxy."""
  395. logger.info("Stopping SSDP proxy")
  396. self._running = False
  397. await self._cleanup()
  398. async def _cleanup(self) -> None:
  399. """Clean up resources."""
  400. for sock in [self._local_socket, self._remote_socket]:
  401. if sock:
  402. try:
  403. sock.close()
  404. except OSError:
  405. pass # Best-effort socket close; may already be released
  406. self._local_socket = None
  407. self._remote_socket = None
  408. async def _handle_local_packet(self, data: bytes, addr: tuple[str, int]) -> None:
  409. """Handle SSDP packet received on local interface (LAN A).
  410. Processes two types of traffic:
  411. - NOTIFY from the real printer → cache and re-broadcast on LAN B
  412. - M-SEARCH from slicers on LAN B → respond with cached printer info
  413. """
  414. sender_ip = addr[0]
  415. # Ignore packets from our own interfaces (prevent loops)
  416. if sender_ip in (self.local_interface_ip, self.remote_interface_ip):
  417. return
  418. # Handle M-SEARCH from slicers (any IP that's not the target printer)
  419. if sender_ip != self.target_printer_ip:
  420. if b"M-SEARCH" in data:
  421. await self._respond_to_msearch(data, addr)
  422. return
  423. # Below: NOTIFY handling from the real printer
  424. # Check if it's a NOTIFY message
  425. if b"NOTIFY" not in data and b"HTTP/1.1 200" not in data:
  426. return
  427. # Check if it's a Bambu printer SSDP
  428. if b"bambulab-com:device:3dprinter" not in data:
  429. return
  430. # Parse and store printer info
  431. headers = self._parse_ssdp_message(data)
  432. if headers:
  433. self._printer_info = headers
  434. logger.debug("Received SSDP from printer %s: %s", sender_ip, headers.get("devname.bambu.com", "unknown"))
  435. # Store and immediately broadcast
  436. self._last_printer_ssdp = data
  437. await self._broadcast_to_remote()
  438. async def _respond_to_msearch(self, data: bytes, addr: tuple[str, int]) -> None:
  439. """Respond to M-SEARCH from a slicer with cached, rewritten printer info.
  440. When Bambu Studio sends an M-SEARCH (e.g., before sending a print),
  441. we respond with the cached printer info, rewritten to point to the
  442. proxy's LAN B IP. Without this, the slicer thinks the printer is
  443. offline and shows a 'connect to printer' modal.
  444. """
  445. # Check if it's a relevant M-SEARCH
  446. if b"bambulab-com:device:3dprinter" not in data and b"ssdp:all" not in data.lower():
  447. return
  448. if not self._last_printer_ssdp:
  449. logger.debug("M-SEARCH from %s but no cached printer SSDP yet", addr[0])
  450. return
  451. logger.debug("Received M-SEARCH from slicer %s", addr[0])
  452. # Rewrite the cached printer SSDP (Location → proxy IP, DevBind → free)
  453. rewritten = self._rewrite_ssdp(self._last_printer_ssdp)
  454. text = rewritten.decode("utf-8", errors="ignore")
  455. # Convert NOTIFY format to M-SEARCH response format:
  456. # "NOTIFY * HTTP/1.1" → "HTTP/1.1 200 OK"
  457. # NT: → ST: (Notification Type → Search Target)
  458. # Remove NTS: header (only in NOTIFY)
  459. text = re.sub(r"^NOTIFY \* HTTP/1\.1", "HTTP/1.1 200 OK", text)
  460. text = re.sub(r"^NT:", "ST:", text, flags=re.MULTILINE)
  461. text = re.sub(r"^NTS:.*\r\n", "", text, flags=re.MULTILINE)
  462. # Send unicast response directly to the slicer via remote socket
  463. if self._remote_socket:
  464. try:
  465. self._remote_socket.sendto(text.encode("utf-8"), addr)
  466. logger.info("Sent SSDP M-SEARCH response to %s", addr[0])
  467. except OSError as e:
  468. logger.debug("Failed to send M-SEARCH response to %s: %s", addr[0], e)
  469. async def _broadcast_to_remote(self) -> None:
  470. """Broadcast cached printer SSDP on remote interface (LAN B)."""
  471. if not self._remote_socket or not self._last_printer_ssdp:
  472. return
  473. try:
  474. # Rewrite Location to point to Bambuddy's remote interface
  475. rewritten = self._rewrite_ssdp(self._last_printer_ssdp)
  476. # Calculate broadcast address for remote network
  477. # Use 255.255.255.255 for simplicity (works across subnets)
  478. self._remote_socket.sendto(rewritten, (SSDP_BROADCAST_ADDR, SSDP_PORT))
  479. printer_name = self._printer_info.get("devname.bambu.com", "unknown")
  480. logger.debug("Broadcast SSDP for '%s' on LAN B (%s)", printer_name, self.remote_interface_ip)
  481. except OSError as e:
  482. logger.debug("Failed to broadcast SSDP on remote: %s", e)