suppaftp 10.0.2

A super FTP/FTPS client library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! # Command
//!
//! The set of FTP commands

pub mod feat;

use std::fmt;
use std::net::SocketAddr;
use std::string::ToString;

use crate::types::FileType;
use crate::{FtpError, FtpResult};

/// Rejects a rendered command line carrying CR or LF before its terminator.
///
/// The FTP control channel is line-oriented: a CR or LF embedded in a command
/// argument would end the intended command and smuggle a second one to the
/// server. Every command line must be checked before it is written to the wire.
///
/// # Errors
///
/// Returns [`FtpError::ConnectionError`] with [`std::io::ErrorKind::InvalidInput`]
/// if `line` contains CR or LF anywhere but in the trailing `\r\n` terminator.
pub(crate) fn validate_command_line(line: &str) -> FtpResult<()> {
    let body = line.strip_suffix("\r\n").unwrap_or(line);
    if body.contains(['\r', '\n']) {
        return Err(FtpError::ConnectionError(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "FTP command must not contain CR or LF",
        )));
    }

    Ok(())
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Ftp commands with their arguments
pub enum Command {
    /// Abort an active file transfer
    Abor,
    /// Append to file
    Appe(String),
    /// Set auth to TLS
    #[cfg(any(feature = "secure", feature = "async-secure"))]
    #[cfg_attr(docsrs, doc(cfg(any(feature = "secure", feature = "async-secure"))))]
    Auth,
    /// Ask server not to encrypt command channel
    #[cfg(any(feature = "secure", feature = "async-secure"))]
    #[cfg_attr(docsrs, doc(cfg(any(feature = "secure", feature = "async-secure"))))]
    ClearCommandChannel,
    /// Change directory to parent directory
    Cdup,
    /// Change working directory
    Cwd(String),
    /// Remove file at specified path
    Dele(String),
    /// Allows specification for protocol and address for data connections
    Eprt(SocketAddr),
    /// Extended passive mode <https://www.rfc-editor.org/rfc/rfc2428#section-3>
    Epsv,
    /// RFC 2389 <https://www.rfc-editor.org/rfc/rfc2389>, list supported options on the server
    Feat,
    /// List entries at specified path. If path is not provided list entries at current working directory
    List(Option<String>),
    /// Get modification time for file at specified path
    Mdtm(String),
    /// Get the list of directories at specified path. If path is not provided list directories at current working directory
    Mlsd(Option<String>),
    /// Get details of an individual file or directory at specified path
    Mlst(Option<String>),
    /// Make directory
    Mkd(String),
    /// Get the list of file names at specified path. If path is not provided list entries at current working directory
    Nlst(Option<String>),
    /// Ping server
    Noop,
    /// RFC 2389 <https://www.rfc-editor.org/rfc/rfc2389>, Set option to server, syntax is (command-name, command-options)
    Opts(String, Option<String>),
    /// Provide login password
    Pass(String),
    /// Passive mode
    Pasv,
    /// Protection buffer size
    #[cfg(any(feature = "secure", feature = "async-secure"))]
    #[cfg_attr(docsrs, doc(cfg(any(feature = "secure", feature = "async-secure"))))]
    Pbsz(usize),
    /// Specifies an address and port to which the server should connect (active mode)
    Port(String),
    /// Set protection level for protocol
    #[cfg(any(feature = "secure", feature = "async-secure"))]
    #[cfg_attr(docsrs, doc(cfg(any(feature = "secure", feature = "async-secure"))))]
    Prot(ProtectionLevel),
    /// Print working directory
    Pwd,
    /// Quit
    Quit,
    /// Select file to rename
    RenameFrom(String),
    /// Rename selected file to
    RenameTo(String),
    /// Resume transfer from offset
    Rest(usize),
    /// Retrieve file
    Retr(String),
    /// Remove directory
    Rmd(String),
    /// Site command
    Site(String),
    /// Get file size of specified path
    Size(String),
    /// Put file at specified path
    Store(String),
    /// Set transfer type
    Type(FileType),
    /// Provide user to login as
    User(String),
    /// Custom command
    Custom(String),
}

#[cfg(any(feature = "secure", feature = "async-secure"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "secure", feature = "async-secure"))))]
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(unused)]
/// Protection level; argument for `Prot` command
pub enum ProtectionLevel {
    Clear,
    Private,
}

impl Command {
    fn encode_eprt(addr: &SocketAddr) -> String {
        let (protocol, network_addr, tcp_port) = match addr {
            SocketAddr::V4(addr) => (1, addr.ip().to_string(), addr.port()),
            SocketAddr::V6(addr) => (2, addr.ip().to_string(), addr.port()),
        };
        format!("EPRT |{protocol}|{network_addr}|{tcp_port}|")
    }
}

// -- stringify

impl fmt::Display for Command {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::Abor => "ABOR".to_string(),
            Self::Appe(f) => format!("APPE {f}"),
            #[cfg(any(feature = "secure", feature = "async-secure"))]
            Self::Auth => "AUTH TLS".to_string(),
            Self::Cdup => "CDUP".to_string(),
            #[cfg(any(feature = "secure", feature = "async-secure"))]
            Self::ClearCommandChannel => "CCC".to_string(),
            Self::Cwd(d) => format!("CWD {d}"),
            Self::Dele(f) => format!("DELE {f}"),
            Self::Eprt(addr) => Self::encode_eprt(addr),
            Self::Epsv => "EPSV".to_string(),
            Self::Feat => "FEAT".to_string(),
            Self::List(p) => p
                .as_deref()
                .map(|x| format!("LIST {x}"))
                .unwrap_or_else(|| "LIST".to_string()),
            Self::Mdtm(p) => format!("MDTM {p}"),
            Self::Mkd(p) => format!("MKD {p}"),
            Self::Mlsd(p) => p
                .as_deref()
                .map(|x| format!("MLSD {x}"))
                .unwrap_or_else(|| "MLSD".to_string()),
            Self::Mlst(p) => p
                .as_deref()
                .map(|x| format!("MLST {x}"))
                .unwrap_or_else(|| "MLST".to_string()),
            Self::Nlst(p) => p
                .as_deref()
                .map(|x| format!("NLST {x}"))
                .unwrap_or_else(|| "NLST".to_string()),
            Self::Opts(command_name, command_opts) => {
                if let Some(command_opts) = command_opts {
                    format!("OPTS {command_name} {command_opts}")
                } else {
                    format!("OPTS {command_name}")
                }
            }
            Self::Noop => "NOOP".to_string(),
            Self::Pass(p) => format!("PASS {p}"),
            Self::Pasv => "PASV".to_string(),
            #[cfg(any(feature = "secure", feature = "async-secure"))]
            Self::Pbsz(sz) => format!("PBSZ {sz}"),
            Self::Port(p) => format!("PORT {p}"),
            #[cfg(any(feature = "secure", feature = "async-secure"))]
            Self::Prot(l) => format!("PROT {l}"),
            Self::Pwd => "PWD".to_string(),
            Self::Quit => "QUIT".to_string(),
            Self::RenameFrom(p) => format!("RNFR {p}"),
            Self::RenameTo(p) => format!("RNTO {p}"),
            Self::Rest(offset) => format!("REST {offset}"),
            Self::Retr(p) => format!("RETR {p}"),
            Self::Rmd(p) => format!("RMD {p}"),
            Self::Site(p) => format!("SITE {p}"),
            Self::Size(p) => format!("SIZE {p}"),
            Self::Store(p) => format!("STOR {p}"),
            Self::Type(t) => format!("TYPE {t}"),
            Self::User(u) => format!("USER {u}"),
            Self::Custom(c) => c.clone(),
        };
        write!(f, "{s}\r\n")
    }
}

#[cfg(any(feature = "secure", feature = "async-secure"))]
impl fmt::Display for ProtectionLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Clear => "C",
                Self::Private => "P",
            }
        )
    }
}

#[cfg(test)]
mod test {

    use pretty_assertions::assert_eq;

    use super::*;

    #[test]
    fn should_accept_command_line_without_embedded_line_breaks() {
        assert!(validate_command_line("USER omar\r\n").is_ok());
        assert!(validate_command_line(&Command::User(String::from("omar")).to_string()).is_ok());
        assert!(
            validate_command_line(&Command::Custom(String::from("SITE HELP")).to_string()).is_ok()
        );
    }

    #[test]
    fn should_reject_command_line_with_embedded_line_breaks() {
        assert!(validate_command_line("USER omar\r\nDELE a.txt\r\n").is_err());
        assert!(validate_command_line("USER omar\nDELE a.txt\r\n").is_err());
        assert!(validate_command_line("USER omar\rDELE a.txt\r\n").is_err());
        assert!(
            validate_command_line(&Command::User(String::from("omar\r\nDELE a.txt")).to_string())
                .is_err()
        );
        assert!(
            validate_command_line(&Command::Pass(String::from("pw\r\nDELE a.txt")).to_string())
                .is_err()
        );
        assert!(
            validate_command_line(&Command::Cwd(String::from("dir\nDELE a.txt")).to_string())
                .is_err()
        );
        assert!(
            validate_command_line(&Command::Custom(String::from("NOOP\r\nDELE a.txt")).to_string())
                .is_err()
        );
    }

    #[test]
    fn should_stringify_command() {
        assert_eq!(Command::Abor.to_string().as_str(), "ABOR\r\n");
        assert_eq!(
            Command::Appe(String::from("foobar.txt"))
                .to_string()
                .as_str(),
            "APPE foobar.txt\r\n"
        );
        #[cfg(any(feature = "secure", feature = "async-secure"))]
        assert_eq!(Command::Auth.to_string().as_str(), "AUTH TLS\r\n");
        #[cfg(any(feature = "secure", feature = "async-secure"))]
        assert_eq!(Command::ClearCommandChannel.to_string().as_str(), "CCC\r\n");
        assert_eq!(Command::Cdup.to_string().as_str(), "CDUP\r\n");
        assert_eq!(
            Command::Cwd(String::from("/tmp")).to_string().as_str(),
            "CWD /tmp\r\n"
        );
        assert_eq!(
            Command::Dele(String::from("a.txt")).to_string().as_str(),
            "DELE a.txt\r\n"
        );
        assert_eq!(
            Command::Eprt(SocketAddr::V4(std::net::SocketAddrV4::new(
                std::net::Ipv4Addr::new(127, 0, 0, 1),
                8080
            )))
            .to_string()
            .as_str(),
            "EPRT |1|127.0.0.1|8080|\r\n"
        );
        assert_eq!(
            Command::Eprt(SocketAddr::V6(std::net::SocketAddrV6::new(
                std::net::Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1),
                8080,
                0,
                0
            )))
            .to_string()
            .as_str(),
            "EPRT |2|2001:db8::1|8080|\r\n"
        );
        assert_eq!(Command::Epsv.to_string().as_str(), "EPSV\r\n");
        assert_eq!(Command::Feat.to_string(), "FEAT\r\n");
        assert_eq!(
            Command::List(Some(String::from("/tmp")))
                .to_string()
                .as_str(),
            "LIST /tmp\r\n"
        );
        assert_eq!(Command::List(None).to_string().as_str(), "LIST\r\n");
        assert_eq!(
            Command::Mdtm(String::from("a.txt")).to_string().as_str(),
            "MDTM a.txt\r\n"
        );
        assert_eq!(
            Command::Mkd(String::from("/tmp")).to_string().as_str(),
            "MKD /tmp\r\n"
        );
        assert_eq!(
            Command::Mlsd(Some(String::from("/tmp")))
                .to_string()
                .as_str(),
            "MLSD /tmp\r\n"
        );
        assert_eq!(Command::Mlsd(None).to_string().as_str(), "MLSD\r\n");
        assert_eq!(
            Command::Mlst(Some(String::from("/tmp")))
                .to_string()
                .as_str(),
            "MLST /tmp\r\n"
        );
        assert_eq!(Command::Mlst(None).to_string().as_str(), "MLST\r\n");
        assert_eq!(
            Command::Nlst(Some(String::from("/tmp")))
                .to_string()
                .as_str(),
            "NLST /tmp\r\n"
        );
        assert_eq!(Command::Nlst(None).to_string().as_str(), "NLST\r\n");
        assert_eq!(Command::Noop.to_string().as_str(), "NOOP\r\n");
        assert_eq!(
            Command::Opts(String::from("UTF8"), Some("ON".to_string()))
                .to_string()
                .as_str(),
            "OPTS UTF8 ON\r\n"
        );
        assert_eq!(
            Command::Opts(String::from("UTF8"), None)
                .to_string()
                .as_str(),
            "OPTS UTF8\r\n"
        );
        assert_eq!(
            Command::Pass(String::from("qwerty123"))
                .to_string()
                .as_str(),
            "PASS qwerty123\r\n"
        );
        assert_eq!(Command::Pasv.to_string().as_str(), "PASV\r\n");
        #[cfg(any(feature = "secure", feature = "async-secure"))]
        assert_eq!(Command::Pbsz(0).to_string().as_str(), "PBSZ 0\r\n");
        assert_eq!(
            Command::Port(String::from("0.0.0.0:21"))
                .to_string()
                .as_str(),
            "PORT 0.0.0.0:21\r\n"
        );
        #[cfg(any(feature = "secure", feature = "async-secure"))]
        assert_eq!(
            Command::Prot(ProtectionLevel::Clear).to_string().as_str(),
            "PROT C\r\n"
        );
        assert_eq!(Command::Pwd.to_string().as_str(), "PWD\r\n");
        assert_eq!(Command::Quit.to_string().as_str(), "QUIT\r\n");
        assert_eq!(
            Command::RenameFrom(String::from("a.txt"))
                .to_string()
                .as_str(),
            "RNFR a.txt\r\n"
        );
        assert_eq!(
            Command::RenameTo(String::from("b.txt"))
                .to_string()
                .as_str(),
            "RNTO b.txt\r\n"
        );
        assert_eq!(Command::Rest(123).to_string().as_str(), "REST 123\r\n");
        assert_eq!(
            Command::Retr(String::from("a.txt")).to_string().as_str(),
            "RETR a.txt\r\n"
        );
        assert_eq!(
            Command::Rmd(String::from("/tmp")).to_string().as_str(),
            "RMD /tmp\r\n"
        );
        assert_eq!(
            Command::Site(String::from("chmod 755 a.txt"))
                .to_string()
                .as_str(),
            "SITE chmod 755 a.txt\r\n"
        );
        assert_eq!(
            Command::Size(String::from("a.txt")).to_string().as_str(),
            "SIZE a.txt\r\n"
        );
        assert_eq!(
            Command::Store(String::from("a.txt")).to_string().as_str(),
            "STOR a.txt\r\n"
        );
        assert_eq!(
            Command::Type(FileType::Binary).to_string().as_str(),
            "TYPE I\r\n"
        );
        assert_eq!(
            Command::User(String::from("omar")).to_string().as_str(),
            "USER omar\r\n"
        );
        assert_eq!(
            Command::Custom(String::from("TEST TEST ABC"))
                .to_string()
                .as_str(),
            "TEST TEST ABC\r\n"
        );
    }

    #[cfg(any(feature = "secure", feature = "async-secure"))]
    #[test]
    fn should_stringify_protection_level() {
        assert_eq!(ProtectionLevel::Clear.to_string().as_str(), "C");
        assert_eq!(ProtectionLevel::Private.to_string().as_str(), "P");
    }
}