PaiGack/ftp/connection does not have a README file

    ConnOptions

    pub struct ConnOptions {
    use_pret : Bool
    skip_epsv : Bool
    disable_epsv : Bool
    trust_pasv_ip : Bool
    timeout_ms : Int
    shut_timeout_ms : Int
    tls : Bool
    server_name : String?
    trust :
    TrustedRoot

    }

    The connection settings cmd_data_conn_from and open_data_conn need.

    A plain value rather than the client's Session, so this package never depends on the root package: the caller (which owns the session) fills in the fields once per transfer.

    ConnOptions::new

    fn ConnOptions::new(use_pret? : Bool, skip_epsv? : Bool, disable_epsv? : Bool, trust_pasv_ip? : Bool, timeout_ms? : Int, shut_timeout_ms? : Int, tls? : Bool, server_name? : String?, trust? :
    TrustedRoot
    ) -> ConnOptions

    Build connection options; every field has an explicit caller.

    ConnOptions::shut_bound

    fn ConnOptions::shut_bound(self : ConnOptions) -> Int

    The deadline DataConn::close should bound its close_notify with, from the options of the transfer that opened this connection.

    Control

    pub struct Control {
    reader : &
    Reader

    writer : &
    Writer

    host : String
    server_name : String?
    timeout_ms : Int
    debug :
    DebugLog
    ?
    }

    An FTP control connection: a line buffered reader/writer pair over the underlying socket.

    The reader and the writer are kept as trait objects so the same code drives a plain Tcp socket and a Tls connection after AUTH TLS.

    Control::debug_enabled

    fn Control::debug_enabled(self : Control) -> Bool

    Whether the traffic log is on.

    Control::host

    fn Control::host(self : Control) -> String

    The peer address of the control connection.

    Control::new

    fn Control::new(reader : &
    Reader
    , writer : &
    Writer
    , host : String, server_name? : String?, timeout_ms? : Int, debug? :
    DebugLog
    ?) -> Control raise
    FtpError

    Wrap an already connected reader/writer pair.

    Raises ParseError for a blank server_name; see the body.

    Control::read_line

    async fn Control::read_line(self : Control) -> String

    Read one line, without its trailing CRLF. Raises ReaderClosed when the connection was closed before a complete line arrived, and RequestTimeout when the server stayed silent for timeout_ms.

    The deadline is on the reply, not on the transfer: only the idle part of a wait is bounded, so a long listing still completes as long as the server keeps the lines coming.

    Control::send_line

    async fn Control::send_line(self : Control, line : String) -> Unit

    Write line followed by CRLF.

    Control::server_name

    fn Control::server_name(self : Control) -> String?

    The hostname the TLS certificate is verified against, None when none was set (which is also "this connection was never upgraded to TLS").

    Control::set_debug

    fn Control::set_debug(self : Control, debug :
    DebugLog
    ?) -> Unit

    Install (or clear) the traffic log on an already built connection.

    Separate from Control::new so dial can attach the sink the caller asked for without every other call site growing the label.

    Control::timeout_ms

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

    The deadline applied to every reply read, in milliseconds. Never zero.

    Control::upgrade

    Replace the underlying reader/writer, used when the connection is upgraded to TLS after AUTH TLS.

    DataConn

    The data connection used for one transfer.

    The socket is always a raw Tcp at first, even for FTPS: the TLS handshake is deferred until start_tls runs, which happens only after the server answered the transfer command with 150. reader / writer are the trait objects the transfer code actually uses; before start_tls they point at the socket, after it they point at the Tls session.

    DataConn::close

    async fn DataConn::close(self : DataConn, timeout_ms? : Int) -> Unit

    Close the data connection without touching the control channel.

    For a TLS data connection the close_notify is sent first. This is not politeness: a server that reads the upload until EOF waits for the record layer to say "no more data", and a bare socket close (which is all Tls::close does -- it frees the OpenSSL handle, the graceful half is the async Tls::shutdown) leaves the server without its EOF, so it never writes the 226 and the very next control read blocks forever. In the clear the socket close is the EOF, so nothing extra is needed there.

    The bound on that shutdown is the caller's shut_timeout_ms, or the connection timeout when it is unset. It used to be a hard-coded 5s: an upload loop against a half-dead server then paid 5 seconds per file that no configuration could shorten, which is also a slow-rejection amplifier.

    DataConn::from_parts

    Build a data connection over an already connected socket with a caller chosen reader/writer pair.

    Only for tests: the production paths build the struct from open_data_conn so the reader and the writer are always the socket (or its TLS session).

    DataConn::reader

    The readable end of the data connection.

    DataConn::start_tls

    async fn DataConn::start_tls(self : DataConn, server_name : String?, trust :
    TrustedRoot
    , timeout_ms : Int, tls : Bool) -> Unit

    Start the TLS handshake on an already connected data socket.

    The timing is the whole point of this function, and it is why the handshake is not done in open_data_conn:

    RFC 4217 starts the data-channel TLS session after the server accepted the transfer command. The server does not read the data socket until it has answered 150 on the control channel, so a client that connects and handshakes earlier writes a ClientHello into a socket nobody is reading yet -- and the server, when it later accepts the connection, sees the bytes of a handshake it never invited. vsftpd and proftpd answer 425 Unable to build data connection (or simply drop it) and the transfer dies; a lenient server may let it slide, which is exactly the "green but wrong" state a stub server used to hide.

    Doing it here also keeps the plain path untouched: start_tls is a no-op when Options::tls is off, so a plaintext transfer connects no differently than before.

    The call is idempotent (self.tls is None is the guard), because stor_from calls it again for a zero-byte upload -- the one case where nothing else would have driven the handshake. See that call site.

    server_name is the name from the control connection, and None there is the normal case for a plaintext session. On a TLS session there is no safe default to fall back to -- verifying against the peer address when the caller meant a name is how a certificate check gets silently weakened -- so a missing name raises instead of handshaking.

    DataConn::writer

    The writable end of the data connection.

    accept_any_status

    fn accept_any_status() -> Array[Int]

    The explicit "any status code is acceptable" status list.

    Upstream spells this cmd(command, ..., -1); an empty list is refused (see cmd_expect), so "any code" has to be asked for by name. No server can send -1, which is what cmd_expect looks for; every real code is three digits and compares against expected.

    check_for_command_injection

    fn check_for_command_injection(arg : String) -> Unit raise
    FtpError

    Refuse command arguments that contain CR or LF.

    Upstream calls this checkForCommandInjection; the check must happen before a single byte is written to the socket, otherwise a crafted path could smuggle extra FTP commands into the session.

    cmd

    async fn cmd(control : Control, command : String) ->
    Response

    Send cmd (already encoded) and return the reply.

    cmd_data_conn_from

    async fn cmd_data_conn_from(control : Control, offset : Int64, cmd : String, args : Array[String], options~ : ConnOptions) -> DataConn

    cmd_data_conn_from_ex

    async fn cmd_data_conn_from_ex(control : Control, offset : Int64, cmd : String, args : Array[String], options~ : ConnOptions) -> (DataConn, Bool)

    Open the data connection for one transfer, and report whether EPSV has just been given up on.

    The Bool is get_data_port's "latched" flag: true when this call took the PASV path because EPSV failed (or was configured off), which is what the caller stores in Session::set_skip_epsv. It used to be dropped on the floor inside cmd_data_conn_from, so the "EPSV failed once, never try again" latch never engaged and every transfer re-sent EPSV to a server already known to refuse it.

    cmd_expect

    async fn cmd_expect(control : Control, command : String, expected : Array[Int]) ->
    Response

    Send cmd and require one of the expected status codes.

    An empty expected list accepts any code, which is how upstream spells cmd(..., -1) for the expected == -1 case -- but it is also what a caller gets from a forgotten status list, and then the check is silently off. The list is therefore required to be non-empty: a call site that really means "any code" passes accept_any_status, so the intent is written down rather than implied by an empty array. A mismatch raises @core.FtpError::ServerError carrying the original message.

    cmd_format

    async fn cmd_format(control : Control, format : String, args : Array[String], expected : Array[Int]) ->
    Response

    Send \format` with args applied through {} substitution and requireone of the expected codes. Convenience wrapper mirroring upstreamcmd(format, args, expected...)`.

    epsv

    async fn epsv(control : Control) -> Int

    Send EPSV (RFC 2428) and return the data port the server opened.

    229 Entering Extended Passive Mode (|||6446|)

    get_data_port

    async fn get_data_port(control : Control, skip_epsv~ : Bool, disable_epsv~ : Bool, trust_pasv_ip~ : Bool) -> (String, Int, Bool)

    Get the port to connect to, preferring EPSV and permanently falling back to PASV after the first failure.

    The "EPSV failed once, never try again" behaviour is a deliberate upstream design choice: some servers answer EPSV with an error but also with a malformed PASV reply, and retrying EPSV on every transfer turns a fast failure into a timeout per file.

    is_all_digits

    fn is_all_digits(src : String) -> Bool

    Whether every byte of src is an ASCII digit.

    is_bogus_data_ip

    fn is_bogus_data_ip(cmd_ip : String, data_ip : String) -> Bool

    Decide whether the IP returned by PASV may be used as the data destination.

    Upstream's rule, kept verbatim: the address is bogus when it is multicast, or when its "privateness" differs from the control connection, or when its loopback-ness differs. This is what makes a server that answers PASV ... (10,0,0,1,...) from a public IP unusable unless the caller opts in with trust_pasv_ip.

    is_loopback

    fn is_loopback(ip : String) -> Bool

    Whether ip is a loopback address (127.0.0.0/8 or ::1).

    is_multicast

    fn is_multicast(ip : String) -> Bool

    Whether ip is a multicast address (224.0.0.0/4 or ff00::/8).

    is_private

    fn is_private(ip : String) -> Bool

    Whether ip is a private (RFC 1918 / link local / ULA) address.

    open_data_conn

    async fn open_data_conn(control : Control, skip_epsv~ : Bool, disable_epsv~ : Bool, trust_pasv_ip~ : Bool, timeout_ms~ : Int) -> (DataConn, Bool)

    Open the passive data connection: EPSV / PASV, then a TCP connect.

    No TLS handshake happens here on purpose -- see DataConn::start_tls for why it belongs after the transfer command was accepted. The socket is left raw so the handshake can be triggered at the right moment.

    parse_epsv

    fn parse_epsv(line : String) -> Int raise
    FtpError

    Extract the port from an EPSV reply body.

    The body is expected to contain ||| followed by the port and a closing |. A malformed reply raises ParseError instead of silently using port 0, which would otherwise hang the connect.

    parse_features

    fn parse_features(body : String) -> Map[String, Bool]

    Parse a FEAT body into a set of command names.

    Feature lines have the shape COMMAND [description]; only the first token is kept, uppercased.

    The leading space test is not cosmetic: the body carries the text of the 211-Features: and 211 End framing lines too (see @connection.read_response), and once trimmed they would otherwise register as features named FEATURES: and END. Upstream filters with exactly this test.

    A feature name may carry a parameter list after a ;: RFC 2228 registers the security extensions as AUTH <mechanism> and lets a server list the mechanisms it supports on the same line, so vsftpd configured with ssl_enable=YES may answer AUTH TLS;TLS-C. The name is cut at the ; as well as at the first space: a caller asking has_feature("AUTH TLS") means "does this server speak TLS", and AUTH TLS;TLS-C is a yes. Without the cut the entry was keyed AUTH TLS;TLS-C, the plaintext-login warning in login never fired, and a server that advertises TLS most explicitly was the one that stayed silent.

    parse_octet

    fn parse_octet(text : String) -> Int?

    Parse a decimal byte value (0..255), returning None otherwise.

    parse_pasv

    fn parse_pasv(line : String) -> (String, Int) raise
    FtpError

    Parse the six comma separated numbers of a PASV reply into an IP and a port (port = p1 * 256 + p2). Fewer than six numbers is an error.

    parse_port

    fn parse_port(digits : String) -> Int?

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

    pasv

    async fn pasv(control : Control) -> (String, Int)

    Send PASV and return the (ip, port) pair the server advertises.

    227 Entering Passive Mode (127,0,0,1,196,6)

    read_response

    async fn read_response(control : Control) ->
    Response

    Read a complete reply from the control connection, handling both the single line and the multi line (RFC 959 211-...211 End) shapes.

    The result reproduces Go's net/textproto.ReadResponse byte for byte, because the rest of the port (starting with FEAT and MLST) is written against that shape. Two consequences are load bearing:

    • the message includes the text of the first and of the terminating status line, joined by \n. Go's feat() filters those back out with a leading space test, and its GetEntry relies on lines[1:lc-1]; a body that dropped the boundary lines would break MLST outright.
    • a line that is exactly three digits, with no separator, is a short response error, not an empty message.

    The multi line terminator is the line that repeats the code without a dash. Getting that wrong makes FEAT swallow the next reply, so it has a dedicated test.

    render_command

    fn render_command(format : String, args : Array[String]) -> String raise
    FtpError

    Apply {} substitution to format without sending anything, validating every argument first.

    Split out of cmd_format because the PRET handshake needs the rendered command before it is sent: it announces the line that follows, so the two must be built by the same code or they drift.