ftp_server.py 25 KB

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