ftp

    FTP/FTPS client library for MoonBit with passive EPSV/PASV data connections, MLSD/LIST parsing, resume, directory tree walking, and explicit/implicit TLS.

    ftp
    network
    client
    protocol
    async
    Download zip
    Author
    Version
    0.2.7
    License
    Apache-2.0
    Last updated
    10 days ago
    Downloads
    258

    #PaiGack/ftp

    纯 MoonBit 实现的 FTP / FTPS 客户端库,移植自 jlaffaye/ftp。

    支持被动模式(EPSV 优先、PASV 回退)、MLSD / LIST 四种列表格式解析、断点续传、 目录树遍历,以及显式与隐式 TLS。

    #环境要求

    • MoonBit 工具链(moon)
    • C 编译器:gcc + libc6-dev。FTP 需要真实 TCP + TLS,模块声明了 preferred_target = "native",native 后端的编译与链接依赖 C 工具链。

    安装:

    curl -fsSL https://cli.moonbitlang.cn/install/unix.sh | bash export PATH="$HOME/.moon/bin:$PATH" # native 后端所需的 C 工具链(Debian / Ubuntu) sudo apt-get install -y gcc libc6-dev

    完整依赖表(openssl / python3 / docker 分别服务哪些步骤)见 开发 → 依赖安装。

    #快速开始

    所有公开函数都是 async 函数,调用方需处在 @async 运行时中(CLI / 测试里写 async fn main 即可,无需手写 await)。下面这段最小可运行例子同时是文档自身的 回归测试:它用 moonbit check 标注,会被 moon check 真的类型检查。

    ///|
    test {
    ///|
    async fn demo() -> Unit {
    // 1. 建连并登录
    let client = @ftp.dial("127.0.0.1:21", timeout_ms=15000)
    @ftp.login(client, "user", "pass")

    // 2. 列目录:优先 MLSD,否则自动回退到 LIST 四种格式解析
    for entry in @ftp.list(client, "/") {
    println("\{entry.type_.to_string()} size=\{entry.size} \{entry.name}")
    }

    // 3. 下载文件
    // `read_all` / `read_to` 边读边持锁、读完自动 `close`;手动 `read` 时
    // 在 `close` 之前不要调用其它客户端操作。
    let resp = @ftp.retr(client, "/hello.txt")
    // 读到的内容要接住:`let bytes` 不消费会触发 unused warning
    let payload = resp.read_all() catch { _ => Bytes::new(0) }
    println("downloaded \{payload.length()} bytes")

    // 4. 上传文件(任意 &@io.Reader 均可)
    // `MemoryReader` 的后台生产者由调用方负责关:绑到变量再 defer close,
    // 否则传输失败时它残留的任务会让事件循环以死锁收场。
    let source = @io.MemoryReader(w => w.write("demo upload"))
    defer source.close()
    let upload = "/upload.txt"
    @ftp.stor(client, upload, source)

    // 5. 重命名,顺手做一次建目录 / 删目录的往返
    let renamed = "/upload_renamed.txt"
    @ftp.rename(client, upload, renamed)
    @ftp.make_dir(client, "/newdir")
    @ftp.remove_dir(client, "/newdir")

    // 6. 递归删除非空目录:`remove_dir` 只删空目录,`remove_dir_recur` 先删光
    // 内容再删目录本身(对应上游的 RemoveDirRecur)
    @ftp.make_dir(client, "/tree")
    @ftp.make_dir(client, "/tree/sub")
    let nested = @io.MemoryReader(w => w.write("nested"))
    defer nested.close()
    @ftp.stor(client, "/tree/sub/f.txt", nested)
    @ftp.remove_dir_recur(client, "/tree")

    // 7. 递归遍历目录树
    let w = @ftp.walk(client, "/")
    while w.next() {
    println(w.path())
    }

    // 8. 遍历结束再删:上传的文件活到走完目录树才收拾,重复运行才安全(幂等)
    @ftp.delete(client, renamed)

    // 9. 退出:发 QUIT 并标记为已关闭(底层 socket 的处理见下方说明)
    @ftp.quit(client)
    }
    ignore(demo)
    }

    这个代码块用 moonbit check 标注,因此它真的会被 moon check 类型检查, 不是只做语法高亮:把它单独跑一遍 moon check --target native --deny-warn 也是绿的。 写法上按 --deny-warn 的标准收紧了尾巴:

    • 例子里是 async fn demo() -> Unit 而不是 async fn main:main 只允许出现在 可执行包里(pkgtype(kind: "executable")),写进 README 这种普通包会报 Unexpected main function in the non-main package,所以用 test { ... } 包一层、 换个名字,语义不变。
    • main / demo 的返回类型必须是 Unit,标注成别的反而报错。
    • 读到的内容要被 println 接住,let bytes 不消费会触发 unused warning。
    • 上传的 @io.MemoryReader 绑到变量再 defer close():它的后台生产者只能这样停, 传输失败时没人关它,事件循环会以死锁 panic 收场。

    要真的跑起来,把代码放进 cmd/example/main.mbt 那种可执行包里 (moon.pkg 声明 pkgtype(kind: "executable") + supported_targets = "+native"), 用 async fn main 去掉外层 test { } 即可 moon run --target native。

    但不是"同样的一行":上面最小例子建连用的是 @ftp.dial("127.0.0.1:21"), 没带 trust_pasv_ip;cmd/example 带了 trust_pasv_ip=true。对着 scripts/start-ftp.sh 起的容器两者都能过,因为它的 PASV 回包 IP 与控制连接 IP 相同(不算可疑 IP,默认的 SSRF 防护本来就放行);换一台回包 IP 与对端不符的服务器, 不带这个开关的那一行会被当可疑 IP 挡掉。例子里省掉它是为了短, cmd/example 留着它是因为它要对着多种真实服务器跑。

    #常用函数

    下面这些函数都是 async,调用方需处在 @async 运行时中(async fn main 或 test { } 块内);walk 本身是普通函数,但它的 Walker::next 是 async。

    函数作用
    dial(addr, ..)建连,可选 explicit_tls / tls / timeout_ms / trust_pasv_ip 等参数
    login(client, user, pass)USER/PASS 登录,随后按上游顺序协商:FEAT → TYPE I → OPTS UTF8 ON(能力与开关都满足时)→ PBSZ 0/PROT P(TLS 时)
    list(client, path)列目录,返回 Array[@core.Entry](MLSD / LIST 自动回退)
    name_list(client, path)NLST,只拿名字,返回 Array[String]
    get_entry(client, path)MLST 取单个条目的 facts
    retr / retr_from(client, path, offset)下载 / 断点续传下载,返回 DataResponse;用 read_to / read_all 一次读完后自动 close,手动 read 则必须 close
    stor / append(client, path, reader)上传 / 追加,reader 由调用方负责 close
    file_size(client, path)SIZE
    get_time(client, path) / set_file_time(client, path, time)MDTM 读 / 写时间戳
    make_dir / remove_dir / remove_dir_recur / delete / rename / change_dir / change_dir_to_parent / current_dir目录与文件管理(remove_dir_recur 递归删除非空目录)
    walk(client, root)普通函数,拿到 Walker;while w.next() { ... } 深度优先遍历,next() 是 async 且失败时不抛错而是返回 false(原因读 w.err())
    no_op / logout / quit(client)NOOP / REIN / QUIT(quit 发 QUIT 并标记为已关闭,之后其余操作都被拒绝;socket 不做显式 close,见下方"连接与关闭语义")

    dial(..., debug_sink=w) 打开流量日志时,命令方向以 PASS 开头的那一行会被记成 PASS ***—— 日志常被贴进 issue 和 CI 输出,密码是唯一一行不能出现在里面的东西。线上发的仍是真实字节; @debug.DebugLog::new(sink, redact_pass=false) 可关掉脱敏(给需要逐字节比对日志的测试用)。

    错误以 @core.FtpError 抛出(Entry / FtpError 在 PaiGack/ftp/core 包里, 自己的包要 moon add 之外再 import 它才能写类型标注),可用 catch / try! 统一处理;多次失败会被聚合成 FtpErrors::MultipleErrors 一起报,而不是遇到第一个就吞掉。list / walk 解析不出的行会被跳过而非中断。

    #连接与关闭语义

    quit 发 QUIT,然后把客户端标记为已关闭(之后再调 quit 是空操作,is_closed() 返回 true)。 关闭之后其余操作一律被拒绝:no_op / list / retr / change_dir 等每一个公开操作在拿锁时 都会先看到这个标志,直接抛 FtpError::ParseError(消息里写明客户端已经 quit),一个字节都不会 再写进控制通道。没有这一步时,QUIT 之后的命令会写进一条服务端已经挂断的会话,报出来的是 ReaderClosed 或读超时,读不出"这个客户端已经关了"。

    它不关闭底层 socket:Control 没有 close 方法,也没有任何路径调用 @socket.Tcp::close。 关闭由两端各自完成——服务端收到 QUIT 后回包并关闭它那一侧,进程退出时本地的句柄随之释放。

    这与上游 Go 版不同:上游 Quit 会显式 c.conn.Close(),再把这条关闭错误与命令错误一起 errors.Join。本仓库删掉了那一步,所以 quit 的错误列表里最多只有 QUIT 命令本身的一个错误, "聚合"是上游 errors.Join 的形状,不是当下的必要性。因此也不要指望 quit 之后 socket 立刻 读到一个 EOF——那要靠服务端关闭它那一侧。

    与之互补的是 logout(REIN):它丢弃登录态但保留控制连接,可以继续在这条连接上 USER/PASS。

    #开发

    #依赖安装

    除 MoonBit 工具链外,本仓库的 moon 命令与自测脚本还有这些外部依赖,装不齐会在 完全无关的步骤上报错,所以先装好:

    依赖谁需要它安装(Debian / Ubuntu)
    gcc + libc6-dev所有 --target native 的编译与链接。native 后端没有 C 工具链连不出可执行文件,moon.pkg 因此声明 preferred_target = "native"sudo apt-get install -y gcc libc6-dev
    opensslFTPS:scripts/ftps/gen-cert.sh 每次签发自签名 CA + 叶证书,scripts/ftps/probe-ftps.sh 用 s_client 做就绪握手sudo apt-get install -y openssl
    python3scripts/ 下所有 *-selftest.py 无 Docker 自测sudo apt-get install -y python3
    docker仅"本地端到端"那一层需要(拉 jmoyer/vsftpd / bfren/ftps 镜像)。不需要跑真实服务器测试时可以完全不装见 Docker 官方安装

    MoonBit 工具链本身:

    curl -fsSL https://cli.moonbitlang.cn/install/unix.sh | bash export PATH="$HOME/.moon/bin:$PATH"

    moon test --target native 还有一个仓库内的前置条件:testdata/ftp/tls 里的 证书必须先由 scripts/ftps/gen-cert.sh testdata/ftp/tls 生成。有一条零字节 TLS 上传的 白测要讲服务端 TLS,只能从磁盘上的证书构造。没生成的话失败信息是 transfer_wbtest.mbt:386 FAILED: stor_from: Cancelled——一个任务组的取消,读起来像库 的 bug,而真正原因只是没人签发过证书。scripts/ci.sh 因此在任何测试之前先跑 gen-cert.sh,并用 tls-fixture-selftest.py 断言这一步真的发生过。

    #常用命令

    所有 moon 命令都带上 --target native:模块声明了 preferred_target = "native", wasm / wasm-gc 后端没有真实网络栈。

    moon update # 首次 / 依赖变动后:拉取 registry 索引 moon fmt --check # 格式检查 moon check --target native --deny-warn # 类型检查,要求 0 warning moon test --target native --deny-warn # 单元测试(含 --enable-coverage 与覆盖率报告) moon build --target native # 构建 moon build --target native --release # release 构建 moon info # 更新生成接口(.mbti),放在最后

    moon info 会重写 pkg.generated.mbti,里面 Int / Int32 的写法跟着工具链走 (core 里 Int 就是 #alias(Int32))。所以顺序是:先看 git diff 干净,再跑 moon info;scripts/ci.sh 同样是先 git diff --exit-code、后 moon info。

    提交前请确认下面三条均通过(与 scripts/ci.sh 用的是同一条命令,不是近似版):

    moon fmt --check moon check --target native --deny-warn moon test --target native --deny-warn

    moon test 前面记得先 scripts/ftps/gen-cert.sh testdata/ftp/tls(见上文"依赖安装")。 想省事可以直接 bash scripts/ci.sh,它按同样顺序跑完 check / test / build / 真实服务器 演示,并在失败时导出容器日志。

    #测试分层

    层命令覆盖
    纯逻辑单测moon test --target native --deny-warn四种列表解析、状态码、路径 join、控制通道帧解析
    明文端到端scripts/start-ftp.sh + cmd/example/run.sh真实 vsftpd 上的 dial / login / list / retr / stor / rename / mkdir / walk
    能力画像端到端cmd/profiles/run.sh <画像>同一个 vsftpd 上四个客户端画像(full / no-mlst / no-time / no-epsv):FEAT、MLSD/LIST、EPSV/PASV、STOR/RETR/NLST、MDTM 读+写、MKD/RMD/RemoveDirRecur。CI 逐个画像各调一次(每次前面插一次 scripts/ensure-ftp.sh 复检容器)
    FTPS 端到端scripts/ftps/start-ftps.sh + cmd/ftps/run.sh真实 vsftpd 上的显式 AUTH TLS:dial / login / LIST / RETR / STOR / APPE×2 / DELE(APPE 断言追加后的内容与 SIZE,不是状态码)
    明文回归cmd/ftps/run.sh plain同一个 cmd/ftps 二进制走明文链路,确保数据通道时序改动没有破坏无 TLS 路径
    无 Docker 自测scripts/ 下的 *-selftest.py拉镜像之前就跑:TLS fixture 已签发、FTPS 就绪探测、cmd/ftps(含 STOR 被拒回归与 APPE 确实追加到服务端)、cmd/profiles 的协议选择断言、两个容器不共用 fixture、cmd/ftp/run.sh 不拼 flag、start-ftp.sh 传给镜像的 10 个环境变量非空、ensure-ftp.sh 的复检三分支、明文探测 probe-ftp.py(含每次会话以 QUIT 收尾),以及 ensure-ftp.sh 在 ci.sh 中的位置

    #本地端到端(需要 docker)

    scripts/start-ftp.sh # 明文 vsftpd,127.0.0.1:21 cmd/example/run.sh # 明文演示:dial / login / list / retr / stor / rename / mkdir / walk cmd/profiles/run.sh # 四个能力画像,都打这个容器(也可 cmd/profiles/run.sh no-epsv 只跑一个) scripts/ftps/start-ftps.sh # FTPS vsftpd,127.0.0.1:2121 cmd/ftps/run.sh # 显式 AUTH TLS cmd/ftps/run.sh plain # 明文回归 scripts/ftps/stop-ftps.sh scripts/stop-ftp.sh

    这一层还有一条硬性约定:scripts/ftps/gen-cert.sh 每次重新签发证书并写进 testdata/ftp/tls(gitignored),客户端用 trust=@tls.TrustedRoot::CustomPemFile(...) 注入它,证书校验始终开启——不要为了跑通把它关掉。

    不需要 Docker 也能跑其中一层:scripts/profiles/ftp_profile_mock.py 是一个带真实文件系统的 FTP mock,scripts/profiles/cmd-profiles-selftest.py 用它驱动真的 cmd/profiles,并逐条核对 每个画像实际发出的命令(LIST 还是 MLSD、PASV 还是 EPSV、有没有写时间戳)—— 这些在真实服务器上看不出来,因为它两种被动命令都支持、两种列表都出结果。

    mock 还必须按容器的形状回答 NLST:vsftpd 对 NLST <dir> 返回完整路径而不是裸文件名 (RFC 3659 §4.1 两者都允许),而这个差别在只跑 mock 时是隐形的——所以自测会直接向 mock 探测它的 NLST 形状,两边一旦不一致就立刻报错。

    FTPS 用自签名 CA,客户端始终校验证书;两种传输方式共用同一个 cmd/ftps 二进制。

    #目录结构

    源码分成四个包,根目录是公开 API 包 PaiGack/ftp,另外三个是子目录里的实现层。 对自己包里的符号直接写名字,对子包写 @core. / @connection. / @debug. 前缀:

    包内容你会拿到的类型
    PaiGack/ftp(根目录)FTPClient / Session / DialOptions 与全部操作函数@ftp.dial、@ftp.list、@ftp.FTPClient
    PaiGack/ftp/coreEntry / FtpError / 状态码 / 列表解析@core.Entry、@core.FtpError
    PaiGack/ftp/connection控制通道与数据通道@connection.Control、@connection.DataConn
    PaiGack/ftp/debug流量日志@debug.DebugLog

    . ├── client.mbt FTPClient + Session / Options + DialOptions + 时间/大小 ├── dial.mbt 拨号 + 登录 + FEAT 能力协商 ├── commands.mbt CWD / PWD / MKD / RMD / DELE / RNFR+RNTO / QUIT 等 ├── list.mbt NLST / LIST / MLST + set_transfer_type ├── transfer.mbt DataResponse:RETR / STOR / APPE ├── transport.mbt Session 到 @connection.ConnOptions 的薄适配 ├── walker.mbt 目录树遍历 ├── core/ 协议值类型与解析(无 IO) │ ├── entry.mbt Entry / EntryType / TransferType │ ├── status.mbt RFC 959 状态码与常量 + status_text() │ ├── error.mbt FtpError / FtpErrors │ ├── parse.mbt RFC 3659 / UNIX ls / DOS DIR / hostedftp 解析器 │ ├── pathutil.mbt 远端路径 join │ └── reply.mbt Response / parse_code / is_continuation ├── connection/ 控制通道与数据通道 │ ├── control.mbt 命令编码、多行响应、FEAT 解析 │ └── transport.mbt EPSV / PASV / PRET / REST / 数据连接 / TLS 建立 ├── debug/ 流量日志(DebugLog) ├── cmd/ftp/ CLI 示例:ls / get / put / walk / mkdir / rm │ ├── main.mbt │ └── run.sh 只转发 argv:连接参数由 cmd/ftp/main.mbt 从环境读默认值 ├── cmd/example/ 真实 vsftpd 端到端演示(明文) │ ├── main.mbt │ └── run.sh 跑 cmd/example(无参数) ├── cmd/ftps/ FTPS / 明文端到端冒烟:参数选择传输方式 │ ├── main.mbt │ └── run.sh 读 .ftp-tls.env 跑 cmd/ftps(可传 plain) ├── cmd/profiles/ 四个客户端能力画像的端到端测试(同一个容器) │ ├── main.mbt full / no-mlst / no-time / no-epsv,各自的开关与断言 │ └── run.sh 设置 FTP_TEST_* 环境默认值后跑 cmd/profiles ├── scripts/ │ ├── ci.sh CI 入口脚本(check / test / build / 演示的唯一入口) │ ├── start-ftp.sh 启动明文 vsftpd 容器(127.0.0.1:21) │ ├── probe-ftp.py 明文容器就绪探测(登录 + 一次被动 LIST) │ ├── probe-ftp-selftest.py 用 mock vsftpd 自测上面的探测(含每次会话都以 QUIT 收尾,无需 Docker) │ ├── ensure-ftp.sh 客户端之间复检明文容器,挂了就用 start-ftp.sh 重启 │ ├── ensure-ftp-selftest.py 用桩 docker 自测上面的复检(无需 Docker) │ ├── ftp-wrapper-selftest.py 断言 cmd/ftp/run.sh 一个连接 flag 都不拼(无需 Docker) │ ├── vsftpd-env-selftest.py 断言 start-ftp.sh 传齐镜像入口要的 10 个变量(无需 Docker) │ ├── stop-ftp.sh 导出明文容器日志并清理 │ ├── ftps/ FTPS(显式 AUTH TLS)容器 │ │ ├── gen-cert.sh 自签名 CA + 叶证书(每次重新签发,写进 testdata/ftp/tls) │ │ ├── probe-ftps.sh 就绪探测:AUTH TLS 握手 + 证书校验 │ │ ├── probe-ftps-selftest.py 用 mock 服务器自测上面的探测(无需 Docker,用法见下) │ │ ├── ftp_mock.py 明文 FTP mock,供 cmd-ftps-selftest.py 驱动真实二进制 │ │ ├── cmd-ftps-selftest.py 无 Docker 跑 cmd/ftps plain(含 STOR 被拒的回归用例) │ │ ├── fixture-isolation-selftest.py 断言两个容器不共用可写 fixture │ │ ├── tls-fixture-selftest.py 断言 moon test 要的证书在跑之前已被签发(无需 Docker) │ │ ├── start-ftps.sh 启动 FTPS 容器(127.0.0.1:2121)并写 .ftp-tls.env │ │ └── stop-ftps.sh 导出容器日志并清理 │ └── profiles/ cmd/profiles 的无 Docker 自测 │ ├── ftp_profile_mock.py 带真实文件系统的 FTP mock │ └── cmd-profiles-selftest.py 驱动真程序并核对每个画像发出的命令 ├── testdata/ftp/ 测试与演示使用的 fixture │ ├── fixture/ 明文演示的 hello.txt + sub/(两个容器各拷一份, │ │ 互不共用,见 scripts/ftps/fixture-isolation-selftest.py) │ └── tls/ gen-cert.sh 每次现签的 CA + 叶证书(gitignored, │ `moon test` 的前置条件,见"开发 → 依赖安装") ├── docs/ 移植方案(porting.md)与设计文档(proposal.md) ├── moon.pkg 根包清单 └── moon.mod 模块定义

    分层由包边界本身保证,不再靠注释约定:core/ 不 import 任何 async 包, connection/ 不认识 FTPClient,根包引用三者的先后顺序即依赖方向。 每个文件头部的 // Package: 注释只说明它属于哪个包。

    probe-ftps-selftest.py 的用法:python3 scripts/ftps/probe-ftps-selftest.py PROBE [CA_FILE]。 PROBE 是被测的探测脚本(scripts/ftps/probe-ftps.sh),CA_FILE 可选,默认用自测现场 现签的那张 CA(正是 mock 出示的证书的签发者)。 第一个参数是脚本路径,不是仓库根目录——把 $PWD 之类的路径传进去,它会被当成 PROBE, 于是报出 bash /gen-cert.sh: exit 127 这种与真实原因无关的错。scripts/ci.sh 只传 PROBE。

    #致谢与来源

    本项目为 jlaffaye/ftp(ISC License)的 MoonBit 移植, 参考其协议实现与测试用例。原项目版权归 Julien Laffaye 所有。

    上游 ISC 许可证原文、版权署名与来源说明见 LICENSE-THIRD-PARTY。 包含移植代码的源文件头部均标注 Ported from jlaffaye/ftp (ISC License), see LICENSE-THIRD-PARTY.。

    #许可证

    本项目自身代码采用 Apache-2.0,见 LICENSE。 移植自 jlaffaye/ftp 的部分同时受其 ISC 许可约束, 原文见 LICENSE-THIRD-PARTY。

    DataResponse

    pub struct DataResponse {
    reader : &
    Reader

    closed : Bool
    session : Session
    client : FTPClient
    shut_timeout_ms : Int
    }

    A data transfer in progress, returned by retr / retr_from.

    DataResponse::read is this type's own method, not an @io.Reader impl: the reader half of the @io.Reader trait needs a ReaderBuffer that only moonbitlang/async/io can mint, so the method reads through the wrapped reader rather than claiming the trait. Callers that need the trait (a read_all, a copy helper, a function taking &@io.Reader) should take retr's underlying reader instead of assuming DataResponse is one -- it is not, and a doc comment is not an impl.

    close() is idempotent and performs the mandatory 226 wrap-up read.

    DataResponse::close

    async fn DataResponse::close(self : DataResponse) -> Unit

    Release the data connection and read the closing 226.

    This is upstream's checkDataShut plus Close: dropping it would leave the trailing 226 in the control channel and desynchronise the next command. Errors from the two phases are aggregated.

    A failed wrap-up is raised, not swallowed. The server reports the transfer's real outcome on this reply (426 Connection closed, transferaborted, 451 local error, 550), so hiding it made every such failure look like a clean transfer: read_all handed back the bytes it had already collected and the caller verified a file that was silently truncated. The swallow existed because a raising close() left the lock held -- that is not true any more (with_lock releases in a defer), so the reply now reaches the caller like every other error in this file.

    The single exception is still swallowed: shut_timeout_ms expiring on the read. There is no reply on the wire at that point and the session is still usable, so failing a transfer the caller already has the data for would turn a slow server into a lost download; the timeout is what bounds that wait, and a genuinely dead server surfaces on the next command.

    DataResponse::read

    async fn DataResponse::read(self : DataResponse, dst : FixedArray[Byte], offset? : Int, max_len? : Int) -> Int

    Read up to max_len bytes of the transfer.

    Does not take the session lock: it reads through a handle that can be held across a long transfer, and taking the lock here would let a second operation in between two reads and mix the two transfers' replies. The calls that run the transfer to completion (read_all, read_to) take the lock for their own duration, and close takes it for the wrap-up 226; a caller that reads with read must not issue other operations until it closes.

    DataResponse::read_all

    async fn DataResponse::read_all(self : DataResponse) -> Bytes

    Consume the transfer into memory and close it.

    DataResponse::read_to

    async fn DataResponse::read_to(self : DataResponse, sink : &
    Writer
    ) -> Unit

    Stream the whole transfer into sink and close it -- one call, so the response (and the session lock it holds) cannot be left behind.

    A read or write failure is still followed by close, which drains the data socket and reads the 226; the original failure is what raises.

    DialOptions

    pub struct DialOptions {
    timeout_ms : Int
    shut_timeout_ms : Int
    tls : Bool
    explicit_tls : Bool
    trust :
    TrustedRoot

    disable_epsv : Bool
    trust_pasv_ip : Bool
    disable_utf8 : Bool
    disable_mlsd : Bool
    writing_mdtm : Bool
    force_list_hidden : Bool
    location :
    Zone

    debug_sink : &
    Writer
    ?
    now_ms : () -> UInt64
    }

    The connection options, the MoonBit counterpart of upstream's 16 DialWith* functions. Every field has a documented default so that dial(addr) alone is a valid call.

    DialOptions::debug_sink

    The traffic log sink, if one was installed.

    DialOptions::default

    fn DialOptions::default() -> DialOptions

    The documented defaults: 30s connect timeout, no TLS, EPSV enabled, PASV IP untrusted, UTF8 and MLSD enabled, UTC timestamps.

    DialOptions::set_debug_sink

    fn DialOptions::set_debug_sink(self : DialOptions, sink : &
    Writer
    ?) -> Unit

    Route a log of every control channel line -- commands out, replies back -- into sink, the MoonBit counterpart of upstream DialWithDebugOutput.

    Off by default: with no sink installed dial installs no logging layer at all, so the hot path is a None check and the bytes on the wire are unchanged. sink = None turns it back off.

    DialOptions::set_disable_epsv

    fn DialOptions::set_disable_epsv(self : DialOptions, value : Bool) -> Unit

    Turn EPSV off, forcing PASV.

    DialOptions::set_disable_mlsd

    fn DialOptions::set_disable_mlsd(self : DialOptions, value : Bool) -> Unit

    Turn MLSD off, forcing LIST.

    DialOptions::set_disable_utf8

    fn DialOptions::set_disable_utf8(self : DialOptions, value : Bool) -> Unit

    Turn OPTS UTF8 ON off.

    DialOptions::set_explicit_tls

    fn DialOptions::set_explicit_tls(self : DialOptions, value : Bool) -> Unit

    Turn explicit AUTH TLS on or off.

    DialOptions::set_force_list_hidden

    fn DialOptions::set_force_list_hidden(self : DialOptions, value : Bool) -> Unit

    Force LIST -a.

    DialOptions::set_location

    fn DialOptions::set_location(self : DialOptions, value :
    Zone
    ) -> Unit

    Replace the timezone used to interpret LIST timestamps.

    DialOptions::set_now_ms

    fn DialOptions::set_now_ms(self : DialOptions, value : () -> UInt64) -> Unit

    Replace the clock backing FTPClient::now.

    The default reads the system time on every list(); a test injects a fixed clock to pin the half-year rule's reference instant. Go's @core.epoch fallback is deliberately not an option here — see FTPClient::now.

    DialOptions::set_shut_timeout_ms

    fn DialOptions::set_shut_timeout_ms(self : DialOptions, value : Int) -> Unit

    Replace the 226 wrap-up timeout in milliseconds.

    DialOptions::set_timeout_ms

    fn DialOptions::set_timeout_ms(self : DialOptions, value : Int) -> Unit

    Replace the connect timeout in milliseconds.

    DialOptions::set_tls

    fn DialOptions::set_tls(self : DialOptions, value : Bool) -> Unit

    Turn implicit TLS on or off.

    DialOptions::set_trust

    Replace the certificate trust policy.

    DialOptions::set_trust_pasv_ip

    fn DialOptions::set_trust_pasv_ip(self : DialOptions, value : Bool) -> Unit

    Trust or distrust the IP returned by PASV.

    DialOptions::set_writing_mdtm

    fn DialOptions::set_writing_mdtm(self : DialOptions, value : Bool) -> Unit

    Use MDTM <time> <path> to write timestamps (VsFtpd quirk).

    DialOptions::to_state_options

    fn DialOptions::to_state_options(self : DialOptions) -> Options

    Project a DialOptions onto the subset of parameters the data channel layer needs.

    FTPClient

    pub struct FTPClient {
    options : DialOptions
    state_options : Options
    session : Session
    closed : Bool
    host : String
    mutex :
    Mutex

    mlst_supported : Bool
    mfmt_supported : Bool
    mdtm_supported : Bool
    mdtm_can_write : Bool
    location :
    Zone

    features : Map[String, Bool]
    }

    The FTP client, the equivalent of upstream ftp.ServerConn.

    Upstream documents this type as not safe for concurrent use. We keep the same constraint but enforce it with a Mutex so that a misuse shows up as serialized commands instead of a corrupted session — a deliberate improvement over the Go implementation, with unchanged semantics.

    FTPClient::has_feature

    fn FTPClient::has_feature(self : FTPClient, name : String) -> Bool

    Whether the server advertised name in its FEAT list.

    FTPClient::is_closed

    fn FTPClient::is_closed(self : FTPClient) -> Bool

    Whether the client already sent QUIT.

    FTPClient::is_get_time_supported

    fn FTPClient::is_get_time_supported(self : FTPClient) -> Bool

    Whether the server accepts MDTM to read modification times.

    FTPClient::is_mfmt_supported

    fn FTPClient::is_mfmt_supported(self : FTPClient) -> Bool

    Whether the server accepts MFMT to set modification times.

    FTPClient::is_mlst_supported

    fn FTPClient::is_mlst_supported(self : FTPClient) -> Bool

    Whether the server advertised MLST (and MLSD was not disabled explicitly).

    FTPClient::is_set_time_supported

    fn FTPClient::is_set_time_supported(self : FTPClient) -> Bool

    Whether the modification time can be written, either via MFMT or via the VsFtpd style MDTM <time> <path>.

    writing_mdtm is part of the answer, not a detail on top of it: a server that only advertises MDTM reads timestamps through it and writes them only when the caller turned the VsFtpd quirk on, so without this flag the query would report a capability set_file_time then refuses with 502. Upstream computes the same expression (MFMT || (MDTM && writing_mdtm)).

    FTPClient::is_time_precise_in_list

    fn FTPClient::is_time_precise_in_list(self : FTPClient) -> Bool

    Whether LIST output carries second level precision. Servers without MDTM only give minute precision through LIST.

    FTPClient::location

    The timezone used to interpret LIST timestamps.

    FTPClient::lock

    async fn FTPClient::lock(self : FTPClient) -> Unit

    Acquire the internal lock, making every public operation serialized.

    Upstream documents ServerConn as not concurrency safe; enforcing it at runtime is a deliberate improvement that does not change the semantics.

    This is also the guard that refuses to work on a client that already sent QUIT. Every public operation takes this lock before touching the control channel, so checking here covers all of them at once instead of leaving the check to each one (where it was missing: is_closed existed but only quit itself read it). Without it, a command after quit was written into a session the server had already hung up on, and the failure surfaced as whichever IO error the dead socket produced -- ReaderClosed, a read timeout -- rather than as "this client is closed".

    FTPClient::options

    fn FTPClient::options(self : FTPClient) -> DialOptions

    The connection options this client was dialed with.

    FTPClient::session

    fn FTPClient::session(self : FTPClient) -> Session

    The negotiated session state shared with the data channel layer.

    FTPClient::state_options

    fn FTPClient::state_options(self : FTPClient) -> Options

    The data channel view of the connection options.

    FTPClient::unlock

    fn FTPClient::unlock(self : FTPClient) -> Unit

    Release the internal lock.

    FTPClient::with_lock

    async fn FTPClient::with_lock(self : FTPClient, op : async () -> Unit) -> Unit

    Run op while holding the client lock, which every public operation takes to serialize the session.

    The lock is not re-entrant: calling it from inside a public operation that already holds it -- retr, stor, list, retr_from, stor_from, ... -- deadlocks the single task that owns the session. Private helpers that run under an operation's lock (stream, check_data_shut, this function) must therefore not call back into the public API, and this one is the way a helper outside client.mbt can take the lock without racing the operations that already do. transfer.mbt uses it to wait for DataResponse::close.

    Holds only "ownership of the session" tokens: the reply reads inside use the control channel's own deadline, and the data channel's I/O has no deadline at all (see docs/porting.md section on SetDeadline), so there is nothing with a timer inside for defer to complain about.

    Options

    pub struct Options {
    disable_epsv : Bool
    trust_pasv_ip : Bool
    tls : Bool
    timeout_ms : Int
    shut_timeout_ms : Int
    trust :
    TrustedRoot

    }

    The connection parameters that affect the data channel, mirroring the subset of upstream DialOptions that transport cares about.

    Options::default

    fn Options::default() -> Options

    Default options, matching the documented defaults in docs/porting.md section 2.4 (API mapping).

    Options::disable_epsv

    fn Options::disable_epsv(self : Options) -> Bool

    Whether EPSV is disabled by configuration.

    Options::new

    fn Options::new(disable_epsv : Bool, trust_pasv_ip : Bool, tls : Bool, timeout_ms : Int, shut_timeout_ms : Int, trust :
    TrustedRoot
    ) -> Options

    Build the data channel options explicitly.

    Options::shut_timeout_ms

    fn Options::shut_timeout_ms(self : Options) -> Int

    Timeout pushing the control connection before the 226 read, milliseconds.

    Options::timeout_ms

    fn Options::timeout_ms(self : Options) -> Int

    Connect timeout for the data connection, milliseconds.

    Options::tls

    fn Options::tls(self : Options) -> Bool

    Whether the data connection is wrapped in TLS.

    Options::trust

    The certificate trust policy for TLS data connections.

    Options::trust_pasv_ip

    fn Options::trust_pasv_ip(self : Options) -> Bool

    Whether the PASV reply IP may be trusted.

    Session

    pub struct Session {
    options : Options
    control :
    Control

    skip_epsv : Bool
    use_pret : Bool
    }

    Everything transport needs from a dialed FTP session.

    This type exists to break the otherwise circular dependency between the client package (which owns FTPClient) and the transport package (which needs the control connection and the capability flags). client embeds a Session and fills it in during dial / feat, transport only reads it.

    Session::conn_options

    fn Session::conn_options(self : Session, use_pret? : Bool) ->
    ConnOptions

    Project a Session onto the settings the data channel needs.

    This is the one place that knows both types: @connection takes a plain ConnOptions so it never has to import the client, and the client hands it over here rather than at every call site.

    server_name is handed over as Control stores it (None for a plaintext session); ConnOptions resolves a missing name when it has to run a handshake, so this projection carries no policy of its own.

    Session::control

    The control connection of this session.

    Session::new

    Build a session around an already established control connection.

    Session::options

    fn Session::options(self : Session) -> Options

    The connection parameters of this session.

    Session::record_data_port

    fn Session::record_data_port(self : Session, latched : Bool) -> Unit

    Remember the data-channel decision the last transfer made.

    true means the transfer took PASV (either because disable_epsv is set or because EPSV failed), so later transfers go straight there instead of re-sending a command the server already refused. That latch is upstream behaviour (see @connection.get_data_port); it used to be computed and then dropped, which made every transfer cost one extra refused EPSV.

    The one case that must not repin the session is a caller that asked for EPSV explicitly (disable_epsv off) while the session is still unpinned: false leaves everything as it is.

    Session::skip_epsv

    fn Session::skip_epsv(self : Session) -> Bool

    Whether EPSV has already failed and must not be retried.

    Session::use_pret

    fn Session::use_pret(self : Session) -> Bool

    Whether the server supports PRET.

    Walker

    pub struct Walker {
    client : FTPClient
    cur :
    Entry
    ?
    cur_path : String
    stack : Array[(
    Entry
    , String)]
    descend : Bool
    root : String
    walker_err : Error?
    }

    A depth-first directory tree walker, a faithful port of upstream ftp.Walker.

    The API contract matters here: next() returns false on a listing error instead of raising, and the error is readable through err().

    Walker::entries

    fn Walker::entries(self : Walker) -> Array[(
    Entry
    , String)]

    The entries currently waiting on the stack, oldest first.

    Walker::err

    fn Walker::err(self : Walker) -> Error?

    The error that stopped the walk, if any.

    Walker::next

    async fn Walker::next(self : Walker) -> Bool

    Advance to the next entry, returning false when the walk is finished or when a listing failed.

    The steps are exactly upstream's:
    1. initialise cur to a synthetic folder entry for the root,
    2. list cur only when descend is set and cur is a folder, recording (not raising) failures,
    3. push every child except . and ..,
    4. stop when the stack is empty,
    5. pop the stack top, reset descend, return true.

    The cur is a folder guard is upstream's (Next tests w.cur.entry.Type == EntryTypeFolder), and it is what makes a walk of a real tree terminate cleanly: without it the walker would try to LIST every file it pops, and a server that refuses to list a file would turn an ordinary tree into an error at the end.

    Walker::path

    fn Walker::path(self : Walker) -> String

    The path of the current entry.

    Walker::pending

    fn Walker::pending(self : Walker) -> Int

    The number of entries still to visit.

    Walker::pop

    fn Walker::pop(self : Walker) -> (
    Entry
    , String)?

    Drop and return the most recently pushed entry, if any.

    Walker::push

    fn Walker::push(self : Walker, entry :
    Entry
    , path : String) -> Unit

    Push a child entry onto the walk stack.

    Walker::set_stack

    fn Walker::set_stack(self : Walker, stack : Array[(
    Entry
    , String)]) -> Unit

    Replace the pending entry stack.

    Walker::skip_dir

    fn Walker::skip_dir(self : Walker) -> Unit

    Do not descend into the directory returned by the last next().

    Walker::stat

    The entry currently being visited.

    append

    async fn append(client : FTPClient, path : String, source : &
    Reader
    ) -> Unit

    APPE <path>, appending a file.

    change_dir

    async fn change_dir(client : FTPClient, dir : String) -> Unit

    CWD <path>, expecting 250.

    change_dir_to_parent

    async fn change_dir_to_parent(client : FTPClient) -> Unit

    CDUP, expecting 250.

    check_data_shut

    async fn check_data_shut(session : Session) -> Unit

    Read the 226 (or 250) that terminates a transfer. Must always run before the next command is sent.

    current_dir

    async fn current_dir(client : FTPClient) -> String

    PWD, returning the path inside the quoted part of the 257 reply.

    delete

    async fn delete(client : FTPClient, path : String) -> Unit

    DELE <path>, expecting 250.

    dial

    async fn dial(addr : String, timeout_ms? : Int, shut_timeout_ms? : Int, tls? : Bool, explicit_tls? : Bool, trust? :
    TrustedRoot
    , disable_epsv? : Bool, trust_pasv_ip? : Bool, disable_utf8? : Bool, disable_mlsd? : Bool, writing_mdtm? : Bool, force_list_hidden? : Bool, location? :
    Zone
    , debug_sink? : &
    Writer
    ?, now_ms? : () -> UInt64) -> FTPClient

    Connect to addr (host or host:port) and return a ready client.

    The options mirror the Go DialWith* family; they are labels rather than a function-options variadic, which is the MoonBit idiom recorded in docs/porting.md section 2.4 (API mapping).

    Once connected the client reads the greeting (expecting 220). When explicit_tls is set it then sends AUTH TLS, expects 234 and upgrades the control connection.

    extract_quoted

    fn extract_quoted(message : String) -> String?

    Extract the substring between the first pair of double quotes, which is how 257 "/incoming" created. encodes the path.

    feat

    async fn feat(client : FTPClient) -> Unit

    Ask the server for its feature list and cache the capabilities the client cares about.

    A server that answers FEAT with anything other than 211 simply has no feature list; that is not an error, upstream treats it the same way.

    The lock is taken here because this is a public function: a caller that re-runs feat after changing server-side configuration would otherwise race every other operation on the control channel. login calls it outside its own lock for exactly that reason (the lock is not re-entrant).

    file_size

    async fn file_size(client : FTPClient, path : String) -> UInt64

    SIZE <path>, expecting 213.

    format_mdtm

    fn format_mdtm(timestamp :
    ZonedDateTime
    ) -> String

    Render a timestamp as yyyyMMddHHmmss in UTC.

    get_entry

    async fn get_entry(client : FTPClient, path : String) ->
    Entry

    MLST <path>: the facts of a single entry.

    The body carries the framing lines too, so this follows upstream exactly: the message must split into at least three lines, the first and the last are dropped, and the remaining lines are merged into one entry (RFC 3659 allows the facts of a single file to be spread over several lines).

    get_time

    async fn get_time(client : FTPClient, path : String) ->
    ZonedDateTime

    MDTM <path>, expecting 213 and a yyyyMMddHHmmss UTC timestamp.

    list

    async fn list(client : FTPClient, path : String) -> Array[
    Entry
    ]

    List a directory.

    MLSD is preferred when the server supports it; otherwise LIST (with -a when force_list_hidden is set) is parsed with the four parser fallback. Lines that no parser recognises are skipped, not fatal: real servers emit total 1 headers and other noise.

    login

    async fn login(client : FTPClient, user : String, password : String) -> Unit

    Authenticate with USER / PASS, then negotiate capabilities.

    The sequence matches upstream Login command for command: USER -> 331 -> PASS -> 230, then FEAT, then TYPE I, then optionally OPTS UTF8 ON, then PBSZ 0 / PROT P for either TLS flavour.

    The FEAT / TYPE / OPTS steps are taken outside the client lock: they are public API and take the lock themselves, and the lock is deliberately not re-entrant (see FTPClient::lock). Holding it across these calls would deadlock every login against a real server.

    logout

    async fn logout(client : FTPClient) -> Unit

    REIN, expecting 220: drops the authentication state but keeps the control connection.

    make_dir

    async fn make_dir(client : FTPClient, dir : String) -> Unit

    MKD <path>, expecting 257.

    name_list

    async fn name_list(client : FTPClient, path : String) -> Array[String]

    NLST <path>: a bare list of names, one per line.

    no_op

    async fn no_op(client : FTPClient) -> Unit

    NOOP, expecting 200.

    parse_decimal

    fn parse_decimal(text : String) -> Int?

    Parse a decimal string into an Int, returning None on any non-digit.

    parse_mdtm

    Parse a yyyyMMddHHmmss timestamp as UTC.

    quit

    async fn quit(client : FTPClient) -> Unit

    QUIT and mark the connection as closed.

    The socket is not closed here: @connection.Control has no close, and no path in this module calls @socket.Tcp::close (see the "connection and shutdown semantics" note in README.mbt.md). Upstream's Quit closes c.conn explicitly and joins that error with the command's, which is why the shape below -- collect into errors, then finish_quit -- survives even though only the command can fail. Sending QUIT therefore does not make the next read observe EOF; the server closing its side and this process releasing the handle do.

    A second call is a no-op, visible through is_closed. The closed check comes before the lock on purpose: FTPClient::lock refuses every operation on a closed client (that is how the rest of the API refuses to run after quit), and quit has to stay the exception so that making it idempotent does not turn a double quit into an error.

    The flag is also set before QUIT goes out, under the lock, so that a concurrent operation either got in first or is refused -- never both.

    The pre-lock check is only a fast path; the decision is taken again under the lock. Two tasks calling quit at the same time both pass the fast path (the flag is still false), then queue on the mutex: the first sets the flag and releases, and without the second check below the second sends a second QUIT into a session whose 221 has already been read -- a reply nobody is waiting for, i.e. a session desynchronised by one line for whoever reuses the handle. FTPClient::lock cannot cover it: it refuses closed clients by raising, and quit must stay the one idempotent call.

    remove_dir

    async fn remove_dir(client : FTPClient, dir : String) -> Unit

    RMD <path>, expecting 250.

    remove_dir_recur

    async fn remove_dir_recur(client : FTPClient, path : String) -> Unit

    Delete a non-empty directory recursively, the port of upstream RemoveDirRecur.

    The sequence is upstream's, and it is a cd-in / cd ..-out dance rather than a walk of the tree, because a plain FTP server has no way to name a child relative to a directory the client is not currently in: every LIST / RMD argument is resolved against the session's working directory.

    1. CWD path, then PWD to learn the absolute name the server assigned — not the caller's string, which may be relative or a symlink.
    2. LIST that absolute path and recurse into every folder child, DELE every file child. . and .. are skipped.
    3. CDUP out, then RMD the directory itself — bottom up, so a directory is only removed once it is empty.

    The client lock is deliberately not held across the recursion: list / delete / remove_dir each take it themselves and the lock is not reentrant, so wrapping the body would deadlock on the first child.

    rename

    async fn rename(client : FTPClient, from : String, to : String) -> Unit

    Rename in two steps, RNFR -> 350 then RNTO -> 250.

    retr

    async fn retr(client : FTPClient, path : String) -> DataResponse

    RETR <path>, returning a readable DataResponse.

    retr_from

    async fn retr_from(client : FTPClient, path : String, offset? : Int64) -> DataResponse

    RETR <path> after REST <offset>, i.e. a resumed download.

    set_file_time

    async fn set_file_time(client : FTPClient, path : String, timestamp :
    ZonedDateTime
    ) -> Unit

    Set the modification time of path.

    MFMT is tried first; when the server only advertises MDTM and writing_mdtm is set, the VsFtpd quirk MDTM <time> <path> is used instead. When neither is available the call raises ServerError with code 502, matching upstream's "not implemented" behaviour.

    set_transfer_type

    async fn set_transfer_type(client : FTPClient, transfer_type :
    TransferType
    ) -> Unit

    TYPE I / TYPE A.

    split_addr

    fn split_addr(addr : String, default_port : Int) -> (String, Int)

    Split host / host:port into its two components, applying default_port when the caller did not specify one.

    stor

    async fn stor(client : FTPClient, path : String, source : &
    Reader
    ) -> Unit

    STOR <path>, uploading from source.

    stor_from

    async fn stor_from(client : FTPClient, path : String, source : &
    Reader
    , offset? : Int64) -> Unit

    STOR <path> after REST <offset>, i.e. a resumed upload.

    The zero-byte TLS case is handled explicitly: ProFTPD answers Unable to build data connection when the data connection was never written to, because the TLS handshake never happened. Uploading nothing while triggering the handshake explicitly keeps the server happy.

    See @connection.DataConn::start_tls for why the trigger is a real call here rather than a poke at a session that already exists: Go's tls.Conn handshakes lazily, @tls.Tls::client handshakes while it is being built.

    walk

    fn walk(client : FTPClient, root : String) -> Walker

    Walk the directory tree rooted at root.