ftp_server.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. """Implicit FTPS server for receiving 3MF uploads from slicers.
  2. Implements an implicit FTPS server (TLS from byte 0) that accepts file uploads
  3. from Bambu Studio and OrcaSlicer, matching the real Bambu printer behavior.
  4. Unlike explicit FTPS (AUTH TLS), implicit FTPS wraps the connection in TLS
  5. immediately upon connection, before any FTP commands are exchanged.
  6. """
  7. import asyncio
  8. import hmac
  9. import logging
  10. import os
  11. import random
  12. import ssl
  13. import zipfile
  14. from collections.abc import Callable
  15. from pathlib import Path
  16. logger = logging.getLogger(__name__)
  17. # Default FTP port for Bambu printers (implicit FTPS).
  18. # Must be 990 (same as real printers) to avoid iptables REDIRECT,
  19. # which rewrites the destination IP to the incoming interface's primary
  20. # address — breaking multi-VP setups with different bind IPs.
  21. # Requires CAP_NET_BIND_SERVICE or root.
  22. FTP_PORT = 990
  23. # Hard cap on a single upload. 4 GiB covers the largest realistic
  24. # multi-plate .gcode.3mf and rejects runaway / malicious clients before
  25. # they can exhaust the disk or OOM the host. STOR still buffers the
  26. # whole file in memory before write_bytes — peak RSS ~2x file size during
  27. # the b''.join — so the cap also caps that peak. If real users hit it
  28. # with a legitimate file, raise here.
  29. MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024 # 4 GiB
  30. class FTPSession:
  31. """Handles a single FTP client session."""
  32. def __init__(
  33. self,
  34. reader: asyncio.StreamReader,
  35. writer: asyncio.StreamWriter,
  36. upload_dir: Path,
  37. access_code: str,
  38. ssl_context: ssl.SSLContext,
  39. on_file_received: Callable[[Path, str], None] | None,
  40. passive_port_range: tuple[int, int] = (50000, 50100),
  41. pasv_address: str = "",
  42. bind_address: str = "0.0.0.0", # nosec B104
  43. vp_name: str = "",
  44. ):
  45. self.reader = reader
  46. self.writer = writer
  47. self.upload_dir = upload_dir
  48. self.access_code = access_code
  49. self.ssl_context = ssl_context
  50. self.on_file_received = on_file_received
  51. self.passive_port_range = passive_port_range
  52. self.pasv_address = pasv_address
  53. self.bind_address = bind_address
  54. self.vp_name = vp_name
  55. self._log_prefix = f"[{vp_name}] " if vp_name else ""
  56. self.authenticated = False
  57. self.username: str | None = None
  58. self.current_dir = upload_dir
  59. self.transfer_type = "A" # ASCII by default
  60. self.data_server: asyncio.Server | None = None
  61. self.data_port: int | None = None
  62. # For data transfer coordination
  63. self._data_reader: asyncio.StreamReader | None = None
  64. self._data_writer: asyncio.StreamWriter | None = None
  65. self._data_connected = asyncio.Event()
  66. self._transfer_done = asyncio.Event()
  67. peername = writer.get_extra_info("peername")
  68. self.remote_ip = peername[0] if peername else "unknown"
  69. async def send(self, code: int, message: str) -> None:
  70. """Send an FTP response."""
  71. response = f"{code} {message}\r\n"
  72. logger.debug("%sFTP -> %s: %s", self._log_prefix, self.remote_ip, response.strip())
  73. self.writer.write(response.encode("utf-8"))
  74. await self.writer.drain()
  75. async def handle(self) -> None:
  76. """Handle the FTP session."""
  77. try:
  78. # Send welcome banner
  79. await self.send(220, "Bambuddy Virtual Printer FTP ready")
  80. while True:
  81. try:
  82. line = await asyncio.wait_for(
  83. self.reader.readline(),
  84. timeout=300, # 5 minute timeout
  85. )
  86. except TimeoutError:
  87. logger.debug("%sFTP session timeout from %s", self._log_prefix, self.remote_ip)
  88. break
  89. if not line:
  90. break
  91. try:
  92. command_line = line.decode("utf-8").strip()
  93. except UnicodeDecodeError:
  94. command_line = line.decode("latin-1").strip()
  95. if not command_line:
  96. continue
  97. # Never log passwords
  98. if command_line.upper().startswith("PASS"):
  99. logger.debug("%sFTP <- %s: PASS ********", self._log_prefix, self.remote_ip)
  100. else:
  101. logger.debug("%sFTP <- %s: %s", self._log_prefix, self.remote_ip, command_line)
  102. # Parse command and argument
  103. parts = command_line.split(" ", 1)
  104. cmd = parts[0].upper()
  105. arg = parts[1] if len(parts) > 1 else ""
  106. # Dispatch command
  107. handler = getattr(self, f"cmd_{cmd}", None)
  108. if handler:
  109. await handler(arg)
  110. else:
  111. logger.debug("%sFTP command not implemented: %s", self._log_prefix, cmd)
  112. await self.send(502, f"Command {cmd} not implemented")
  113. except asyncio.CancelledError:
  114. logger.info("%sFTP session cancelled from %s", self._log_prefix, self.remote_ip)
  115. except Exception as e:
  116. logger.error("%sFTP session error from %s: %s", self._log_prefix, self.remote_ip, e)
  117. finally:
  118. logger.info("%sFTP session ended from %s", self._log_prefix, self.remote_ip)
  119. await self._cleanup()
  120. async def _cleanup(self) -> None:
  121. """Clean up session resources."""
  122. # Release any waiting data connection callback
  123. self._transfer_done.set()
  124. if self.data_server:
  125. self.data_server.close()
  126. try:
  127. await self.data_server.wait_closed()
  128. except OSError:
  129. pass # Best-effort data server cleanup; may already be closed
  130. self.data_server = None
  131. try:
  132. self.writer.close()
  133. await self.writer.wait_closed()
  134. except OSError:
  135. pass # Best-effort control connection cleanup; client may have disconnected
  136. # FTP Commands
  137. async def cmd_USER(self, arg: str) -> None:
  138. """Handle USER command."""
  139. self.username = arg
  140. if arg.lower() == "bblp":
  141. await self.send(331, "Password required")
  142. else:
  143. await self.send(530, "Invalid user")
  144. async def cmd_PASS(self, arg: str) -> None:
  145. """Handle PASS command."""
  146. if self.username and self.username.lower() == "bblp":
  147. # ``hmac.compare_digest`` is constant-time — keeps the auth check
  148. # from leaking the access code via response timing under network
  149. # jitter. LAN-only threat is marginal; this is the standard fix.
  150. if hmac.compare_digest(arg, self.access_code):
  151. self.authenticated = True
  152. await self.send(230, "Login successful")
  153. logger.info("%sFTP login from %s", self._log_prefix, self.remote_ip)
  154. else:
  155. await self.send(530, "Login incorrect")
  156. logger.warning("%sFTP failed login from %s (access code mismatch)", self._log_prefix, self.remote_ip)
  157. else:
  158. await self.send(503, "Login with USER first")
  159. async def cmd_SYST(self, arg: str) -> None:
  160. """Handle SYST command."""
  161. await self.send(215, "UNIX Type: L8")
  162. async def cmd_FEAT(self, arg: str) -> None:
  163. """Handle FEAT command."""
  164. features = [
  165. "211-Features:",
  166. " PASV",
  167. " EPSV",
  168. " UTF8",
  169. " SIZE",
  170. "211 End",
  171. ]
  172. for line in features[:-1]:
  173. self.writer.write(f"{line}\r\n".encode())
  174. await self.writer.drain()
  175. self.writer.write(f"{features[-1]}\r\n".encode())
  176. await self.writer.drain()
  177. async def cmd_PWD(self, arg: str) -> None:
  178. """Handle PWD command."""
  179. if not self.authenticated:
  180. await self.send(530, "Not logged in")
  181. return
  182. await self.send(257, '"/" is current directory')
  183. async def cmd_CWD(self, arg: str) -> None:
  184. """Handle CWD command."""
  185. if not self.authenticated:
  186. await self.send(530, "Not logged in")
  187. return
  188. # Accept any directory change (we use a flat structure)
  189. await self.send(250, "Directory changed")
  190. async def cmd_TYPE(self, arg: str) -> None:
  191. """Handle TYPE command."""
  192. if not self.authenticated:
  193. await self.send(530, "Not logged in")
  194. return
  195. if arg.upper() in ("A", "I"):
  196. self.transfer_type = arg.upper()
  197. type_name = "ASCII" if arg.upper() == "A" else "Binary"
  198. await self.send(200, f"Type set to {type_name}")
  199. else:
  200. await self.send(504, "Type not supported")
  201. async def _bind_passive_port(self) -> bool:
  202. """Try to bind a passive data port with retries.
  203. Returns True if a port was successfully bound, False otherwise.
  204. Sets self.data_server and self.data_port on success.
  205. """
  206. port_min, port_max = self.passive_port_range
  207. for attempt in range(10):
  208. port = random.randint(port_min, port_max)
  209. try:
  210. self.data_server = await asyncio.start_server(
  211. self._handle_data_connection,
  212. self.bind_address,
  213. port,
  214. ssl=self.ssl_context,
  215. )
  216. self.data_port = port
  217. return True
  218. except OSError:
  219. logger.debug("FTP passive port %s in use, retrying (%s/10)", port, attempt + 1)
  220. return False
  221. async def cmd_EPSV(self, arg: str) -> None:
  222. """Handle EPSV command - Extended Passive Mode (IPv6 compatible)."""
  223. if not self.authenticated:
  224. await self.send(530, "Not logged in")
  225. return
  226. # Close any existing data connection/server
  227. await self._close_data_connection()
  228. # Reset connection state for the new transfer
  229. self._data_connected.clear()
  230. self._data_reader = None
  231. self._data_writer = None
  232. self._transfer_done = asyncio.Event()
  233. if await self._bind_passive_port():
  234. # EPSV response format: 229 Entering Extended Passive Mode (|||port|)
  235. await self.send(229, f"Entering Extended Passive Mode (|||{self.data_port}|)")
  236. logger.info("FTP EPSV listening on port %s", self.data_port)
  237. else:
  238. logger.error("Failed to bind any passive port for EPSV")
  239. await self.send(425, "Cannot open data connection")
  240. async def cmd_PASV(self, arg: str) -> None:
  241. """Handle PASV command - set up passive data connection."""
  242. if not self.authenticated:
  243. await self.send(530, "Not logged in")
  244. return
  245. # Close any existing data connection/server
  246. await self._close_data_connection()
  247. # Reset connection state for the new transfer
  248. self._data_connected.clear()
  249. self._data_reader = None
  250. self._data_writer = None
  251. self._transfer_done = asyncio.Event()
  252. if await self._bind_passive_port():
  253. # Determine the IP to advertise in PASV response
  254. if self.pasv_address:
  255. # Explicit override (e.g., for Docker bridge mode behind NAT)
  256. ip = self.pasv_address
  257. else:
  258. # Use the local IP of the control connection
  259. sockname = self.writer.get_extra_info("sockname")
  260. ip = sockname[0] if sockname else "127.0.0.1"
  261. # 0.0.0.0 is not routable — fall back to control connection IP
  262. if ip == "0.0.0.0": # nosec B104
  263. ip = "127.0.0.1"
  264. # Format IP and port for PASV response
  265. ip_parts = ip.split(".")
  266. port_hi = self.data_port // 256
  267. port_lo = self.data_port % 256
  268. await self.send(
  269. 227,
  270. f"Entering Passive Mode ({ip_parts[0]},{ip_parts[1]},{ip_parts[2]},{ip_parts[3]},{port_hi},{port_lo})",
  271. )
  272. logger.info("FTP PASV listening on %s:%s", ip, self.data_port)
  273. else:
  274. logger.error("Failed to bind any passive port for PASV")
  275. await self.send(425, "Cannot open data connection")
  276. async def _handle_data_connection(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
  277. """Handle incoming data connection (used by PASV/EPSV).
  278. This callback stays alive until the transfer completes to ensure the
  279. asyncio task holds strong references to the reader/writer throughout
  280. the data transfer. If the callback returned immediately, the task
  281. would complete and the StreamReaderProtocol could release its strong
  282. reader reference, potentially destabilising the connection.
  283. """
  284. # Reject duplicate connections — only one data connection per transfer
  285. if self._data_reader is not None:
  286. logger.warning("FTP rejecting duplicate data connection from %s", self.remote_ip)
  287. try:
  288. writer.close()
  289. await writer.wait_closed()
  290. except OSError:
  291. pass
  292. return
  293. # Log TLS details for debugging
  294. ssl_obj = writer.get_extra_info("ssl_object")
  295. if ssl_obj:
  296. logger.info(
  297. f"FTP data TLS from {self.remote_ip}: cipher={ssl_obj.cipher()}, "
  298. f"version={ssl_obj.version()}, session_reused={ssl_obj.session_reused}"
  299. )
  300. else:
  301. logger.warning("FTP data connection from %s has no SSL!", self.remote_ip)
  302. logger.info("FTP data connection established from %s", self.remote_ip)
  303. self._data_reader = reader
  304. self._data_writer = writer
  305. # Stop accepting further connections on the passive port
  306. if self.data_server:
  307. self.data_server.close()
  308. self._data_connected.set()
  309. # Keep this callback alive until the transfer command (STOR/RETR)
  310. # finishes. This ensures the asyncio server-handler task holds strong
  311. # references to reader/writer for the entire transfer lifetime.
  312. await self._transfer_done.wait()
  313. async def _close_data_connection(self) -> None:
  314. """Close the data connection and server."""
  315. had_connection = self._data_writer is not None or self.data_server is not None
  316. # Signal the _handle_data_connection callback to return, allowing
  317. # its asyncio task to complete cleanly.
  318. self._transfer_done.set()
  319. if self._data_writer:
  320. try:
  321. self._data_writer.close()
  322. await self._data_writer.wait_closed()
  323. except OSError:
  324. pass # Best-effort data writer cleanup; peer may have closed already
  325. self._data_writer = None
  326. self._data_reader = None
  327. if self.data_server:
  328. try:
  329. self.data_server.close()
  330. await self.data_server.wait_closed()
  331. except OSError:
  332. pass # Best-effort data server shutdown; port may already be released
  333. self.data_server = None
  334. # Only delay if we actually closed something
  335. if had_connection:
  336. await asyncio.sleep(0.1)
  337. async def cmd_STOR(self, arg: str) -> None:
  338. """Handle STOR command - receive file upload.
  339. Streams each chunk directly to disk inside the receive loop instead
  340. of buffering the whole file in a ``list[bytes]`` and joining at the
  341. end. Wire protocol unchanged — same 150/226/426 sequence, same
  342. single-write target path (no ``.part`` or atomic rename), no new
  343. verbs, no concurrency guard. The visible behaviour difference is
  344. that the destination file grows progressively during upload rather
  345. than appearing all-at-once on completion; slicers don't LIST during
  346. STOR, so this isn't observable. Peak RSS for a multi-GB upload
  347. drops from ~2× file size to one chunk (64 KiB).
  348. ``MAX_UPLOAD_BYTES`` cap kept — purely server-internal DoS guard.
  349. """
  350. if not self.authenticated:
  351. await self.send(530, "Not logged in")
  352. return
  353. if not self.data_server and not self._data_connected.is_set():
  354. await self.send(425, "Use PASV first")
  355. return
  356. filename = Path(arg).name # Sanitize filename
  357. file_path = (
  358. self.upload_dir / filename
  359. ) # SEC-PATH-OK: filename = Path(arg).name strips every path component above
  360. logger.info("FTP receiving file: %s from %s", filename, self.remote_ip)
  361. await self.send(150, f"Opening data connection for {filename}")
  362. # Wait for data connection to be established (client connects after 150)
  363. try:
  364. await asyncio.wait_for(self._data_connected.wait(), timeout=30)
  365. except TimeoutError:
  366. logger.error("FTP data connection timeout - client didn't connect")
  367. await self.send(425, "Data connection timeout")
  368. await self._close_data_connection()
  369. return
  370. if not self._data_reader:
  371. await self.send(425, "Data connection failed")
  372. await self._close_data_connection()
  373. return
  374. # Receive + stream to disk
  375. total_received = 0
  376. write_failed: Exception | None = None
  377. try:
  378. with file_path.open("wb") as f:
  379. while True:
  380. chunk = await asyncio.wait_for(self._data_reader.read(65536), timeout=60)
  381. if not chunk:
  382. break
  383. total_received += len(chunk)
  384. if total_received > MAX_UPLOAD_BYTES:
  385. raise OSError(f"upload exceeded size cap ({total_received} > {MAX_UPLOAD_BYTES} bytes)")
  386. f.write(chunk)
  387. logger.debug("FTP received chunk: %s bytes (total: %s)", len(chunk), total_received)
  388. except TimeoutError:
  389. logger.error("FTP data transfer timeout after %s bytes for %s", total_received, filename)
  390. write_failed = TimeoutError("Transfer timeout")
  391. except Exception as e:
  392. logger.error(
  393. "FTP data transfer error after %s bytes for %s: %s(%s)",
  394. total_received,
  395. filename,
  396. type(e).__name__,
  397. e,
  398. )
  399. write_failed = e
  400. # Close data connection
  401. await self._close_data_connection()
  402. if write_failed is not None:
  403. # Drop the partial file so it doesn't masquerade as a complete
  404. # upload — buffer-then-write never had a partial-file footprint.
  405. try:
  406. file_path.unlink(missing_ok=True)
  407. except OSError:
  408. pass
  409. await self.send(426, f"Transfer failed: {write_failed}")
  410. return
  411. # Defense in depth (#1896): a clean read-loop EOF does NOT prove the
  412. # upload arrived intact. Under uvloop, the SSL layer can silently drop
  413. # already-received but still-buffered data when the client closes the
  414. # data connection without a TLS close_notify (a "ragged EOF") while the
  415. # transport is flow-control-paused on slow storage — read() then returns
  416. # b"" and we would otherwise reply 226 for a tail-truncated file, archive
  417. # it, queue it, and forward the corrupt job to the real printer.
  418. #
  419. # Bambu 3MF uploads are ZIP containers whose End-Of-Central-Directory
  420. # record sits at the very end of the file, so any lost tail makes the
  421. # archive impossible to open. Verify that before acknowledging success:
  422. # a truncated file is treated exactly like a failed transfer (426 +
  423. # drop) so the slicer surfaces an actionable send error instead of the
  424. # printer choking on a half-written job later. Only ZIP-based (.3mf)
  425. # uploads are validated — other filetypes keep the prior pass-through
  426. # behaviour. Reading the central directory is O(dir), not O(file): no
  427. # decompression, negligible next to the write loop above.
  428. if filename.lower().endswith(".3mf"):
  429. try:
  430. with zipfile.ZipFile(file_path) as zf:
  431. zf.namelist()
  432. except Exception as e:
  433. logger.error(
  434. "FTP upload of %s is a corrupt/truncated 3MF (%s bytes): %s(%s) — "
  435. "rejecting with 426 instead of archiving a broken file",
  436. filename,
  437. total_received,
  438. type(e).__name__,
  439. e,
  440. )
  441. try:
  442. file_path.unlink(missing_ok=True)
  443. except OSError:
  444. pass
  445. await self.send(426, "Transfer failed: uploaded 3MF is incomplete or corrupt")
  446. return
  447. # Confirm + notify
  448. logger.info("FTP saved file: %s (%s bytes)", file_path, total_received)
  449. await self.send(226, "Transfer complete")
  450. if self.on_file_received:
  451. try:
  452. result = self.on_file_received(file_path, self.remote_ip)
  453. if asyncio.iscoroutine(result):
  454. await result
  455. except Exception as e:
  456. logger.error("File received callback error: %s", e)
  457. async def cmd_SIZE(self, arg: str) -> None:
  458. """Handle SIZE command."""
  459. if not self.authenticated:
  460. await self.send(530, "Not logged in")
  461. return
  462. # We don't store files for SIZE queries
  463. await self.send(550, "File not found")
  464. async def cmd_QUIT(self, arg: str) -> None:
  465. """Handle QUIT command."""
  466. await self.send(221, "Goodbye")
  467. raise asyncio.CancelledError()
  468. async def cmd_NOOP(self, arg: str) -> None:
  469. """Handle NOOP command."""
  470. await self.send(200, "OK")
  471. async def cmd_OPTS(self, arg: str) -> None:
  472. """Handle OPTS command."""
  473. if arg.upper().startswith("UTF8"):
  474. await self.send(200, "UTF8 mode enabled")
  475. else:
  476. await self.send(501, "Option not supported")
  477. async def cmd_PBSZ(self, arg: str) -> None:
  478. """Handle PBSZ (Protection Buffer Size) command.
  479. Required for FTP security extensions. With TLS, buffer size is 0.
  480. """
  481. await self.send(200, "PBSZ=0")
  482. async def cmd_PROT(self, arg: str) -> None:
  483. """Handle PROT (Data Channel Protection Level) command.
  484. P = Private (encrypted), which we always use with implicit FTPS.
  485. """
  486. if arg.upper() == "P":
  487. await self.send(200, "Protection level set to Private")
  488. elif arg.upper() == "C":
  489. # Clear (unprotected) - we don't support this
  490. await self.send(536, "Protection level C not supported")
  491. else:
  492. await self.send(504, f"Protection level {arg} not supported")
  493. async def cmd_MKD(self, arg: str) -> None:
  494. """Handle MKD (Make Directory) command."""
  495. if not self.authenticated:
  496. await self.send(530, "Not logged in")
  497. return
  498. # We don't really create directories, just pretend it works
  499. await self.send(257, f'"{arg}" directory created')
  500. async def cmd_LIST(self, arg: str) -> None:
  501. """Handle LIST command - list directory contents.
  502. Intentionally answers 150 + 226 without opening the passive data
  503. channel. Bambuddy is an upload-only VP — no slicer in capture logs
  504. actually issues LIST during the project_file flow, so the
  505. no-data-conn ack is what every observed slicer accepts. A previous
  506. audit recommended opening + closing the data conn for protocol
  507. purity; reverted because (a) the bug was theoretical, (b) slicer
  508. compatibility matters more than RFC purity here, and (c) adding
  509. NLST/MLSD alongside changes the "supported verbs" surface in a way
  510. we cannot regression-test without every supported slicer build.
  511. """
  512. if not self.authenticated:
  513. await self.send(530, "Not logged in")
  514. return
  515. # We don't support listing, return empty
  516. await self.send(150, "Opening data connection")
  517. await self.send(226, "Transfer complete")
  518. PASSIVE_PORT_BASE = 50000
  519. PASSIVE_SLICE_SIZE = 10
  520. PASSIVE_MAX_SLOTS = 100
  521. def compute_passive_port_slice(vp_id: int) -> tuple[int, int]:
  522. """Return the (min, max) passive-mode data port range for VP `vp_id`.
  523. Each VP gets a unique non-overlapping slice so bridge-mode Docker users
  524. only need to expose `PASSIVE_SLICE_SIZE * <vp count>` ports instead of
  525. the full historical 1001-port pool (#1646 — wide pool × Docker's
  526. userland-proxy spawned ~2000 host processes at ~3.5 GB RAM). vp_id is
  527. taken modulo PASSIVE_MAX_SLOTS so installs that have churned through
  528. many VPs over time still produce a valid in-range slice; a same-slot
  529. collision falls back to the existing per-session 10-attempt random
  530. retry, which is the pre-#1646 behaviour and recovers gracefully.
  531. """
  532. slot = (max(vp_id, 1) - 1) % PASSIVE_MAX_SLOTS
  533. port_min = PASSIVE_PORT_BASE + slot * PASSIVE_SLICE_SIZE
  534. port_max = port_min + PASSIVE_SLICE_SIZE - 1
  535. return port_min, port_max
  536. class VirtualPrinterFTPServer:
  537. """Implicit FTPS server that accepts uploads from slicers.
  538. Each VP is given a small non-overlapping passive-mode data-port slice
  539. via `passive_port_min/passive_port_max` (typically computed by
  540. `compute_passive_port_slice(vp_id)` at the call site). The slice is
  541. intentionally narrow — 10 ports per VP fits Bambu-style one-passive-
  542. socket-per-upload sessions with safe headroom, and bridge-mode docker
  543. setups only have to expose `N_vps * 10` ports instead of the historical
  544. 1001-port pool (#1646).
  545. """
  546. def __init__(
  547. self,
  548. upload_dir: Path,
  549. access_code: str,
  550. cert_path: Path,
  551. key_path: Path,
  552. port: int = FTP_PORT,
  553. on_file_received: Callable[[Path, str], None] | None = None,
  554. bind_address: str = "0.0.0.0", # nosec B104
  555. vp_name: str = "",
  556. passive_port_min: int = PASSIVE_PORT_BASE,
  557. passive_port_max: int = PASSIVE_PORT_BASE + PASSIVE_SLICE_SIZE - 1,
  558. ):
  559. """Initialize the FTPS server.
  560. Args:
  561. upload_dir: Directory to store uploaded files
  562. access_code: Password for authentication (bblp user)
  563. cert_path: Path to TLS certificate file
  564. key_path: Path to TLS private key file
  565. port: Port to listen on (default 990)
  566. on_file_received: Callback when file upload completes (path, source_ip)
  567. bind_address: IP address to bind to (default 0.0.0.0)
  568. vp_name: Virtual printer name for log identification
  569. passive_port_min: Low end of this VP's passive-mode data port slice
  570. (inclusive). Per-VP slicing eliminates cross-VP collisions on
  571. shared 0.0.0.0 binds without paying for a 1001-port pool (#1646).
  572. passive_port_max: High end of the slice (inclusive). Defaults
  573. produce a 10-port window starting at PASSIVE_PORT_BASE.
  574. """
  575. self.upload_dir = upload_dir
  576. self.access_code = access_code
  577. self.cert_path = cert_path
  578. self.key_path = key_path
  579. self.port = port
  580. self.on_file_received = on_file_received
  581. self.bind_address = bind_address
  582. self.vp_name = vp_name
  583. self.passive_port_min = passive_port_min
  584. self.passive_port_max = passive_port_max
  585. self._server: asyncio.Server | None = None
  586. self._running = False
  587. # Set after the socket is bound and the server is accepting connections,
  588. # so VirtualPrinterInstance.start_server can wait for readiness before
  589. # reporting is_running=True. Without this, a caller racing the start
  590. # could probe the port and see "connection refused" while is_running
  591. # already says yes.
  592. self.ready = asyncio.Event()
  593. self._ssl_context: ssl.SSLContext | None = None
  594. self._active_sessions: list[asyncio.Task] = []
  595. # Override PASV response IP for Docker bridge mode / NAT environments
  596. self._pasv_address = os.environ.get("VIRTUAL_PRINTER_PASV_ADDRESS", "")
  597. async def start(self) -> None:
  598. """Start the implicit FTPS server."""
  599. if self._running:
  600. return
  601. logger.info("[%s] Starting virtual printer implicit FTPS on %s:%s", self.vp_name, self.bind_address, self.port)
  602. # Ensure upload directory exists
  603. self.upload_dir.mkdir(parents=True, exist_ok=True)
  604. cache_dir = self.upload_dir / "cache"
  605. cache_dir.mkdir(exist_ok=True)
  606. # Create SSL context for implicit FTPS (TLS from byte 0).
  607. # Pinned to TLS 1.2 only. Allowing 1.3 broke BambuStudio mid-upload
  608. # in the field (session_reused=True on data channel via PSK + libcurl
  609. # CURLE_PARTIAL_FILE / RST after ~80 KiB; "server did not report OK,
  610. # got 426"). Real Bambu printers also serve their FTPS at 1.2 only,
  611. # and the slicer expects to match that. A future slicer drop of 1.2
  612. # is a problem to solve when it actually happens; until then 1.2 is
  613. # mandatory for compat.
  614. self._ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
  615. self._ssl_context.load_cert_chain(str(self.cert_path), str(self.key_path))
  616. self._ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  617. self._ssl_context.maximum_version = ssl.TLSVersion.TLSv1_2
  618. # Keep the historical `HIGH:!aNULL:!MD5:!RC4` baseline so the cipher
  619. # set stays a strict superset of what shipped before (the previous
  620. # set offered ~58 extra suites — CCM, ARIA, CAMELLIA, DSS variants —
  621. # that no Bambu slicer is known to pick, but the
  622. # [[feedback_dont_remove_compat_pinning]] HARD RULE says don't
  623. # narrow a compat surface without proof). The two explicit additions
  624. # cover the #1610 case on hardened distros (Fedora / RHEL with
  625. # `update-crypto-policies`, hardened Alpine builds) where the system
  626. # policy strips the plain-RSA `AES256-GCM-SHA384` / `AES128-GCM-SHA256`
  627. # suites from `HIGH` — without them present the slicer's FTPS
  628. # ClientHello (which mimics the cipher set real Bambu printers offer)
  629. # finds no overlap and the handshake aborts. Listing them explicitly
  630. # survives any system policy that strips them from `HIGH`.
  631. self._ssl_context.set_ciphers("HIGH:AES256-GCM-SHA384:AES128-GCM-SHA256:!aNULL:!MD5:!RC4")
  632. logger.info("FTP SSL context created with standard settings")
  633. try:
  634. # Create server with SSL - TLS handshake happens before any FTP data
  635. self._server = await asyncio.start_server(
  636. self._handle_client,
  637. self.bind_address,
  638. self.port,
  639. ssl=self._ssl_context, # This makes it implicit FTPS!
  640. )
  641. self._running = True
  642. self.ready.set()
  643. logger.info("Implicit FTPS server started on port %s", self.port)
  644. logger.info(
  645. "FTP passive data port range: %s-%s",
  646. self.passive_port_min,
  647. self.passive_port_max,
  648. )
  649. if self._pasv_address:
  650. logger.info("FTP PASV address override: %s", self._pasv_address)
  651. async with self._server:
  652. await self._server.serve_forever()
  653. except OSError as e:
  654. if e.errno == 98: # Address already in use
  655. logger.error("FTP port %s is already in use", self.port)
  656. else:
  657. logger.error("FTP server error: %s", e)
  658. except asyncio.CancelledError:
  659. logger.debug("FTP server task cancelled")
  660. except Exception as e:
  661. logger.error("FTP server error: %s", e)
  662. finally:
  663. await self.stop()
  664. async def _handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
  665. """Handle a new FTP client connection."""
  666. peername = writer.get_extra_info("peername")
  667. log_prefix = f"[{self.vp_name}] " if self.vp_name else ""
  668. logger.info("%sFTP connection from %s", log_prefix, peername)
  669. session = FTPSession(
  670. reader=reader,
  671. writer=writer,
  672. upload_dir=self.upload_dir,
  673. access_code=self.access_code,
  674. ssl_context=self._ssl_context,
  675. on_file_received=self.on_file_received,
  676. passive_port_range=(self.passive_port_min, self.passive_port_max),
  677. pasv_address=self._pasv_address,
  678. bind_address=self.bind_address,
  679. vp_name=self.vp_name,
  680. )
  681. # Track the session task so we can cancel it on stop
  682. task = asyncio.current_task()
  683. if task:
  684. self._active_sessions.append(task)
  685. try:
  686. await session.handle()
  687. finally:
  688. if task and task in self._active_sessions:
  689. self._active_sessions.remove(task)
  690. async def stop(self) -> None:
  691. """Stop the FTPS server."""
  692. logger.info("Stopping FTP server")
  693. self._running = False
  694. self.ready.clear()
  695. # Cancel all active sessions and AWAIT cancellation. Previously
  696. # this slept 0.1 s and called it good — a session mid-write,
  697. # mid-TLS handshake, or holding a 60 s data-read could easily
  698. # outlive that and then ``_server.close()`` would run while the
  699. # underlying sockets were still in use.
  700. for task in self._active_sessions[:]:
  701. task.cancel()
  702. if self._active_sessions:
  703. await asyncio.gather(*self._active_sessions, return_exceptions=True)
  704. self._active_sessions.clear()
  705. if self._server:
  706. try:
  707. self._server.close()
  708. await self._server.wait_closed()
  709. except OSError as e:
  710. logger.debug("Error closing FTP server: %s", e)
  711. self._server = None