ftp_server.py 37 KB

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