ftp_server.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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 logging
  9. import os
  10. import random
  11. import ssl
  12. from collections.abc import Callable
  13. from pathlib import Path
  14. logger = logging.getLogger(__name__)
  15. # Default FTP port for Bambu printers (implicit FTPS)
  16. FTP_PORT = 9990
  17. class FTPSession:
  18. """Handles a single FTP client session."""
  19. def __init__(
  20. self,
  21. reader: asyncio.StreamReader,
  22. writer: asyncio.StreamWriter,
  23. upload_dir: Path,
  24. access_code: str,
  25. ssl_context: ssl.SSLContext,
  26. on_file_received: Callable[[Path, str], None] | None,
  27. passive_port_range: tuple[int, int] = (50000, 50100),
  28. pasv_address: str = "",
  29. bind_address: str = "0.0.0.0", # nosec B104
  30. ):
  31. self.reader = reader
  32. self.writer = writer
  33. self.upload_dir = upload_dir
  34. self.access_code = access_code
  35. self.ssl_context = ssl_context
  36. self.on_file_received = on_file_received
  37. self.passive_port_range = passive_port_range
  38. self.pasv_address = pasv_address
  39. self.bind_address = bind_address
  40. self.authenticated = False
  41. self.username: str | None = None
  42. self.current_dir = upload_dir
  43. self.transfer_type = "A" # ASCII by default
  44. self.data_server: asyncio.Server | None = None
  45. self.data_port: int | None = None
  46. # For data transfer coordination
  47. self._data_reader: asyncio.StreamReader | None = None
  48. self._data_writer: asyncio.StreamWriter | None = None
  49. self._data_connected = asyncio.Event()
  50. self._transfer_done = asyncio.Event()
  51. peername = writer.get_extra_info("peername")
  52. self.remote_ip = peername[0] if peername else "unknown"
  53. async def send(self, code: int, message: str) -> None:
  54. """Send an FTP response."""
  55. response = f"{code} {message}\r\n"
  56. logger.info("FTP -> %s: %s", self.remote_ip, response.strip())
  57. self.writer.write(response.encode("utf-8"))
  58. await self.writer.drain()
  59. async def handle(self) -> None:
  60. """Handle the FTP session."""
  61. try:
  62. # Send welcome banner
  63. await self.send(220, "Bambuddy Virtual Printer FTP ready")
  64. while True:
  65. try:
  66. line = await asyncio.wait_for(
  67. self.reader.readline(),
  68. timeout=300, # 5 minute timeout
  69. )
  70. except TimeoutError:
  71. logger.debug("FTP session timeout from %s", self.remote_ip)
  72. break
  73. if not line:
  74. break
  75. try:
  76. command_line = line.decode("utf-8").strip()
  77. except UnicodeDecodeError:
  78. command_line = line.decode("latin-1").strip()
  79. if not command_line:
  80. continue
  81. logger.info("FTP <- %s: %s", self.remote_ip, command_line)
  82. # Parse command and argument
  83. parts = command_line.split(" ", 1)
  84. cmd = parts[0].upper()
  85. arg = parts[1] if len(parts) > 1 else ""
  86. # Dispatch command
  87. handler = getattr(self, f"cmd_{cmd}", None)
  88. if handler:
  89. await handler(arg)
  90. else:
  91. logger.warning("FTP command not implemented: %s", cmd)
  92. await self.send(502, f"Command {cmd} not implemented")
  93. except asyncio.CancelledError:
  94. logger.info("FTP session cancelled from %s", self.remote_ip)
  95. except Exception as e:
  96. logger.error("FTP session error from %s: %s", self.remote_ip, e)
  97. finally:
  98. logger.info("FTP session ended from %s", self.remote_ip)
  99. await self._cleanup()
  100. async def _cleanup(self) -> None:
  101. """Clean up session resources."""
  102. # Release any waiting data connection callback
  103. self._transfer_done.set()
  104. if self.data_server:
  105. self.data_server.close()
  106. try:
  107. await self.data_server.wait_closed()
  108. except OSError:
  109. pass # Best-effort data server cleanup; may already be closed
  110. self.data_server = None
  111. try:
  112. self.writer.close()
  113. await self.writer.wait_closed()
  114. except OSError:
  115. pass # Best-effort control connection cleanup; client may have disconnected
  116. # FTP Commands
  117. async def cmd_USER(self, arg: str) -> None:
  118. """Handle USER command."""
  119. self.username = arg
  120. if arg.lower() == "bblp":
  121. await self.send(331, "Password required")
  122. else:
  123. await self.send(530, "Invalid user")
  124. async def cmd_PASS(self, arg: str) -> None:
  125. """Handle PASS command."""
  126. if self.username and self.username.lower() == "bblp":
  127. if arg == self.access_code:
  128. self.authenticated = True
  129. await self.send(230, "Login successful")
  130. logger.info("FTP login from %s", self.remote_ip)
  131. else:
  132. await self.send(530, "Login incorrect")
  133. logger.warning("FTP failed login from %s", self.remote_ip)
  134. else:
  135. await self.send(503, "Login with USER first")
  136. async def cmd_SYST(self, arg: str) -> None:
  137. """Handle SYST command."""
  138. await self.send(215, "UNIX Type: L8")
  139. async def cmd_FEAT(self, arg: str) -> None:
  140. """Handle FEAT command."""
  141. features = [
  142. "211-Features:",
  143. " PASV",
  144. " EPSV",
  145. " UTF8",
  146. " SIZE",
  147. "211 End",
  148. ]
  149. for line in features[:-1]:
  150. self.writer.write(f"{line}\r\n".encode())
  151. await self.writer.drain()
  152. self.writer.write(f"{features[-1]}\r\n".encode())
  153. await self.writer.drain()
  154. async def cmd_PWD(self, arg: str) -> None:
  155. """Handle PWD command."""
  156. if not self.authenticated:
  157. await self.send(530, "Not logged in")
  158. return
  159. await self.send(257, '"/" is current directory')
  160. async def cmd_CWD(self, arg: str) -> None:
  161. """Handle CWD command."""
  162. if not self.authenticated:
  163. await self.send(530, "Not logged in")
  164. return
  165. # Accept any directory change (we use a flat structure)
  166. await self.send(250, "Directory changed")
  167. async def cmd_TYPE(self, arg: str) -> None:
  168. """Handle TYPE command."""
  169. if not self.authenticated:
  170. await self.send(530, "Not logged in")
  171. return
  172. if arg.upper() in ("A", "I"):
  173. self.transfer_type = arg.upper()
  174. type_name = "ASCII" if arg.upper() == "A" else "Binary"
  175. await self.send(200, f"Type set to {type_name}")
  176. else:
  177. await self.send(504, "Type not supported")
  178. async def _bind_passive_port(self) -> bool:
  179. """Try to bind a passive data port with retries.
  180. Returns True if a port was successfully bound, False otherwise.
  181. Sets self.data_server and self.data_port on success.
  182. """
  183. port_min, port_max = self.passive_port_range
  184. for attempt in range(10):
  185. port = random.randint(port_min, port_max)
  186. try:
  187. self.data_server = await asyncio.start_server(
  188. self._handle_data_connection,
  189. self.bind_address,
  190. port,
  191. ssl=self.ssl_context,
  192. )
  193. self.data_port = port
  194. return True
  195. except OSError:
  196. logger.debug("FTP passive port %s in use, retrying (%s/10)", port, attempt + 1)
  197. return False
  198. async def cmd_EPSV(self, arg: str) -> None:
  199. """Handle EPSV command - Extended Passive Mode (IPv6 compatible)."""
  200. if not self.authenticated:
  201. await self.send(530, "Not logged in")
  202. return
  203. # Close any existing data connection/server
  204. await self._close_data_connection()
  205. # Reset connection state for the new transfer
  206. self._data_connected.clear()
  207. self._data_reader = None
  208. self._data_writer = None
  209. self._transfer_done = asyncio.Event()
  210. if await self._bind_passive_port():
  211. # EPSV response format: 229 Entering Extended Passive Mode (|||port|)
  212. await self.send(229, f"Entering Extended Passive Mode (|||{self.data_port}|)")
  213. logger.info("FTP EPSV listening on port %s", self.data_port)
  214. else:
  215. logger.error("Failed to bind any passive port for EPSV")
  216. await self.send(425, "Cannot open data connection")
  217. async def cmd_PASV(self, arg: str) -> None:
  218. """Handle PASV command - set up passive data connection."""
  219. if not self.authenticated:
  220. await self.send(530, "Not logged in")
  221. return
  222. # Close any existing data connection/server
  223. await self._close_data_connection()
  224. # Reset connection state for the new transfer
  225. self._data_connected.clear()
  226. self._data_reader = None
  227. self._data_writer = None
  228. self._transfer_done = asyncio.Event()
  229. if await self._bind_passive_port():
  230. # Determine the IP to advertise in PASV response
  231. if self.pasv_address:
  232. # Explicit override (e.g., for Docker bridge mode behind NAT)
  233. ip = self.pasv_address
  234. else:
  235. # Use the local IP of the control connection
  236. sockname = self.writer.get_extra_info("sockname")
  237. ip = sockname[0] if sockname else "127.0.0.1"
  238. # 0.0.0.0 is not routable — fall back to control connection IP
  239. if ip == "0.0.0.0": # nosec B104
  240. ip = "127.0.0.1"
  241. # Format IP and port for PASV response
  242. ip_parts = ip.split(".")
  243. port_hi = self.data_port // 256
  244. port_lo = self.data_port % 256
  245. await self.send(
  246. 227,
  247. f"Entering Passive Mode ({ip_parts[0]},{ip_parts[1]},{ip_parts[2]},{ip_parts[3]},{port_hi},{port_lo})",
  248. )
  249. logger.info("FTP PASV listening on %s:%s", ip, self.data_port)
  250. else:
  251. logger.error("Failed to bind any passive port for PASV")
  252. await self.send(425, "Cannot open data connection")
  253. async def _handle_data_connection(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
  254. """Handle incoming data connection (used by PASV/EPSV).
  255. This callback stays alive until the transfer completes to ensure the
  256. asyncio task holds strong references to the reader/writer throughout
  257. the data transfer. If the callback returned immediately, the task
  258. would complete and the StreamReaderProtocol could release its strong
  259. reader reference, potentially destabilising the connection.
  260. """
  261. # Reject duplicate connections — only one data connection per transfer
  262. if self._data_reader is not None:
  263. logger.warning("FTP rejecting duplicate data connection from %s", self.remote_ip)
  264. try:
  265. writer.close()
  266. await writer.wait_closed()
  267. except OSError:
  268. pass
  269. return
  270. # Log TLS details for debugging
  271. ssl_obj = writer.get_extra_info("ssl_object")
  272. if ssl_obj:
  273. logger.info(
  274. f"FTP data TLS from {self.remote_ip}: cipher={ssl_obj.cipher()}, "
  275. f"version={ssl_obj.version()}, session_reused={ssl_obj.session_reused}"
  276. )
  277. else:
  278. logger.warning("FTP data connection from %s has no SSL!", self.remote_ip)
  279. logger.info("FTP data connection established from %s", self.remote_ip)
  280. self._data_reader = reader
  281. self._data_writer = writer
  282. # Stop accepting further connections on the passive port
  283. if self.data_server:
  284. self.data_server.close()
  285. self._data_connected.set()
  286. # Keep this callback alive until the transfer command (STOR/RETR)
  287. # finishes. This ensures the asyncio server-handler task holds strong
  288. # references to reader/writer for the entire transfer lifetime.
  289. await self._transfer_done.wait()
  290. async def _close_data_connection(self) -> None:
  291. """Close the data connection and server."""
  292. had_connection = self._data_writer is not None or self.data_server is not None
  293. # Signal the _handle_data_connection callback to return, allowing
  294. # its asyncio task to complete cleanly.
  295. self._transfer_done.set()
  296. if self._data_writer:
  297. try:
  298. self._data_writer.close()
  299. await self._data_writer.wait_closed()
  300. except OSError:
  301. pass # Best-effort data writer cleanup; peer may have closed already
  302. self._data_writer = None
  303. self._data_reader = None
  304. if self.data_server:
  305. try:
  306. self.data_server.close()
  307. await self.data_server.wait_closed()
  308. except OSError:
  309. pass # Best-effort data server shutdown; port may already be released
  310. self.data_server = None
  311. # Only delay if we actually closed something
  312. if had_connection:
  313. await asyncio.sleep(0.1)
  314. async def cmd_STOR(self, arg: str) -> None:
  315. """Handle STOR command - receive file upload."""
  316. if not self.authenticated:
  317. await self.send(530, "Not logged in")
  318. return
  319. if not self.data_server and not self._data_connected.is_set():
  320. await self.send(425, "Use PASV first")
  321. return
  322. filename = Path(arg).name # Sanitize filename
  323. file_path = self.upload_dir / filename
  324. logger.info("FTP receiving file: %s from %s", filename, self.remote_ip)
  325. await self.send(150, f"Opening data connection for {filename}")
  326. # Wait for data connection to be established (client connects after 150)
  327. try:
  328. await asyncio.wait_for(self._data_connected.wait(), timeout=30)
  329. except TimeoutError:
  330. logger.error("FTP data connection timeout - client didn't connect")
  331. await self.send(425, "Data connection timeout")
  332. await self._close_data_connection()
  333. return
  334. if not self._data_reader:
  335. await self.send(425, "Data connection failed")
  336. await self._close_data_connection()
  337. return
  338. # Receive data
  339. data_content: list[bytes] = []
  340. total_received = 0
  341. try:
  342. while True:
  343. chunk = await asyncio.wait_for(self._data_reader.read(65536), timeout=60)
  344. if not chunk:
  345. break
  346. data_content.append(chunk)
  347. total_received += len(chunk)
  348. logger.debug("FTP received chunk: %s bytes (total: %s)", len(chunk), total_received)
  349. except TimeoutError:
  350. logger.error("FTP data transfer timeout after %s bytes for %s", total_received, filename)
  351. await self.send(426, "Transfer timeout")
  352. await self._close_data_connection()
  353. return
  354. except Exception as e:
  355. logger.error(
  356. "FTP data transfer error after %s bytes for %s: %s(%s)",
  357. total_received,
  358. filename,
  359. type(e).__name__,
  360. e,
  361. )
  362. await self.send(426, f"Transfer failed: {e}")
  363. await self._close_data_connection()
  364. return
  365. # Close data connection
  366. await self._close_data_connection()
  367. # Write file
  368. try:
  369. total_size = sum(len(c) for c in data_content)
  370. file_path.write_bytes(b"".join(data_content))
  371. logger.info("FTP saved file: %s (%s bytes)", file_path, total_size)
  372. await self.send(226, "Transfer complete")
  373. # Notify callback
  374. if self.on_file_received:
  375. try:
  376. result = self.on_file_received(file_path, self.remote_ip)
  377. if asyncio.iscoroutine(result):
  378. await result
  379. except Exception as e:
  380. logger.error("File received callback error: %s", e)
  381. except Exception as e:
  382. logger.error("Failed to save file %s: %s", file_path, e)
  383. await self.send(550, "Failed to save file")
  384. async def cmd_SIZE(self, arg: str) -> None:
  385. """Handle SIZE command."""
  386. if not self.authenticated:
  387. await self.send(530, "Not logged in")
  388. return
  389. # We don't store files for SIZE queries
  390. await self.send(550, "File not found")
  391. async def cmd_QUIT(self, arg: str) -> None:
  392. """Handle QUIT command."""
  393. await self.send(221, "Goodbye")
  394. raise asyncio.CancelledError()
  395. async def cmd_NOOP(self, arg: str) -> None:
  396. """Handle NOOP command."""
  397. await self.send(200, "OK")
  398. async def cmd_OPTS(self, arg: str) -> None:
  399. """Handle OPTS command."""
  400. if arg.upper().startswith("UTF8"):
  401. await self.send(200, "UTF8 mode enabled")
  402. else:
  403. await self.send(501, "Option not supported")
  404. async def cmd_PBSZ(self, arg: str) -> None:
  405. """Handle PBSZ (Protection Buffer Size) command.
  406. Required for FTP security extensions. With TLS, buffer size is 0.
  407. """
  408. await self.send(200, "PBSZ=0")
  409. async def cmd_PROT(self, arg: str) -> None:
  410. """Handle PROT (Data Channel Protection Level) command.
  411. P = Private (encrypted), which we always use with implicit FTPS.
  412. """
  413. if arg.upper() == "P":
  414. await self.send(200, "Protection level set to Private")
  415. elif arg.upper() == "C":
  416. # Clear (unprotected) - we don't support this
  417. await self.send(536, "Protection level C not supported")
  418. else:
  419. await self.send(504, f"Protection level {arg} not supported")
  420. async def cmd_MKD(self, arg: str) -> None:
  421. """Handle MKD (Make Directory) command."""
  422. if not self.authenticated:
  423. await self.send(530, "Not logged in")
  424. return
  425. # We don't really create directories, just pretend it works
  426. await self.send(257, f'"{arg}" directory created')
  427. async def cmd_LIST(self, arg: str) -> None:
  428. """Handle LIST command - list directory contents."""
  429. if not self.authenticated:
  430. await self.send(530, "Not logged in")
  431. return
  432. # We don't support listing, return empty
  433. await self.send(150, "Opening data connection")
  434. await self.send(226, "Transfer complete")
  435. class VirtualPrinterFTPServer:
  436. """Implicit FTPS server that accepts uploads from slicers."""
  437. PASSIVE_PORT_MIN = 50000
  438. PASSIVE_PORT_MAX = 50100
  439. def __init__(
  440. self,
  441. upload_dir: Path,
  442. access_code: str,
  443. cert_path: Path,
  444. key_path: Path,
  445. port: int = FTP_PORT,
  446. on_file_received: Callable[[Path, str], None] | None = None,
  447. bind_address: str = "0.0.0.0", # nosec B104
  448. ):
  449. """Initialize the FTPS server.
  450. Args:
  451. upload_dir: Directory to store uploaded files
  452. access_code: Password for authentication (bblp user)
  453. cert_path: Path to TLS certificate file
  454. key_path: Path to TLS private key file
  455. port: Port to listen on (default 990)
  456. on_file_received: Callback when file upload completes (path, source_ip)
  457. bind_address: IP address to bind to (default 0.0.0.0)
  458. """
  459. self.upload_dir = upload_dir
  460. self.access_code = access_code
  461. self.cert_path = cert_path
  462. self.key_path = key_path
  463. self.port = port
  464. self.on_file_received = on_file_received
  465. self.bind_address = bind_address
  466. self._server: asyncio.Server | None = None
  467. self._running = False
  468. self._ssl_context: ssl.SSLContext | None = None
  469. self._active_sessions: list[asyncio.Task] = []
  470. # Override PASV response IP for Docker bridge mode / NAT environments
  471. self._pasv_address = os.environ.get("VIRTUAL_PRINTER_PASV_ADDRESS", "")
  472. async def start(self) -> None:
  473. """Start the implicit FTPS server."""
  474. if self._running:
  475. return
  476. logger.info("Starting virtual printer implicit FTPS on port %s", self.port)
  477. # Ensure upload directory exists
  478. self.upload_dir.mkdir(parents=True, exist_ok=True)
  479. cache_dir = self.upload_dir / "cache"
  480. cache_dir.mkdir(exist_ok=True)
  481. # Create SSL context for implicit FTPS (TLS from byte 0)
  482. self._ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
  483. self._ssl_context.load_cert_chain(str(self.cert_path), str(self.key_path))
  484. self._ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  485. self._ssl_context.maximum_version = ssl.TLSVersion.TLSv1_2
  486. # Use standard TLS settings for compatibility
  487. self._ssl_context.set_ciphers("HIGH:!aNULL:!MD5:!RC4")
  488. logger.info("FTP SSL context created with standard settings")
  489. try:
  490. # Create server with SSL - TLS handshake happens before any FTP data
  491. self._server = await asyncio.start_server(
  492. self._handle_client,
  493. self.bind_address,
  494. self.port,
  495. ssl=self._ssl_context, # This makes it implicit FTPS!
  496. )
  497. self._running = True
  498. logger.info("Implicit FTPS server started on port %s", self.port)
  499. logger.info(
  500. "FTP passive data port range: %s-%s",
  501. self.PASSIVE_PORT_MIN,
  502. self.PASSIVE_PORT_MAX,
  503. )
  504. if self._pasv_address:
  505. logger.info("FTP PASV address override: %s", self._pasv_address)
  506. async with self._server:
  507. await self._server.serve_forever()
  508. except OSError as e:
  509. if e.errno == 98: # Address already in use
  510. logger.error("FTP port %s is already in use", self.port)
  511. else:
  512. logger.error("FTP server error: %s", e)
  513. except asyncio.CancelledError:
  514. logger.debug("FTP server task cancelled")
  515. except Exception as e:
  516. logger.error("FTP server error: %s", e)
  517. finally:
  518. await self.stop()
  519. async def _handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
  520. """Handle a new FTP client connection."""
  521. peername = writer.get_extra_info("peername")
  522. logger.info("FTP connection from %s", peername)
  523. session = FTPSession(
  524. reader=reader,
  525. writer=writer,
  526. upload_dir=self.upload_dir,
  527. access_code=self.access_code,
  528. ssl_context=self._ssl_context,
  529. on_file_received=self.on_file_received,
  530. passive_port_range=(self.PASSIVE_PORT_MIN, self.PASSIVE_PORT_MAX),
  531. pasv_address=self._pasv_address,
  532. bind_address=self.bind_address,
  533. )
  534. # Track the session task so we can cancel it on stop
  535. task = asyncio.current_task()
  536. if task:
  537. self._active_sessions.append(task)
  538. try:
  539. await session.handle()
  540. finally:
  541. if task and task in self._active_sessions:
  542. self._active_sessions.remove(task)
  543. async def stop(self) -> None:
  544. """Stop the FTPS server."""
  545. logger.info("Stopping FTP server")
  546. self._running = False
  547. # Cancel all active sessions first
  548. for task in self._active_sessions[:]: # Copy list to avoid modification during iteration
  549. task.cancel()
  550. # Wait briefly for sessions to clean up
  551. if self._active_sessions:
  552. await asyncio.sleep(0.1)
  553. self._active_sessions.clear()
  554. if self._server:
  555. try:
  556. self._server.close()
  557. await self._server.wait_closed()
  558. except OSError as e:
  559. logger.debug("Error closing FTP server: %s", e)
  560. self._server = None