use crate::network::types::{FtpInfo, FtpMessageType};
const MAX_SNIFF_BYTES: usize = 1024;
const FTP_COMMANDS: &[&str] = &[
"USER", "PASS", "ACCT", "CWD", "CDUP", "SMNT", "QUIT", "REIN",
"PORT", "PASV", "TYPE", "STRU", "MODE", "RETR", "STOR", "STOU", "APPE", "ALLO", "REST", "RNFR", "RNTO", "ABOR", "DELE", "RMD", "MKD",
"PWD", "LIST", "NLST", "SITE", "SYST", "STAT", "HELP", "NOOP",
"FEAT", "OPTS", "EPSV", "EPRT", "AUTH", "PBSZ", "PROT", "CCC", "SIZE", "MDTM", "MLSD", "MLST",
];
const FTP_DISTINCTIVE_COMMANDS: &[&str] = &[
"ACCT", "CWD", "CDUP", "SMNT", "REIN", "PORT", "PASV", "TYPE", "STRU", "STOR", "STOU", "APPE",
"ALLO", "REST", "RNFR", "RNTO", "ABOR", "RMD", "MKD", "PWD", "NLST", "SITE", "SYST", "FEAT",
"OPTS", "EPSV", "EPRT", "PBSZ", "PROT", "CCC", "SIZE", "MDTM", "MLSD", "MLST",
];
pub(super) fn is_ftp(payload: &[u8]) -> bool {
let line = first_line(payload);
if line.is_empty() {
return false;
}
let upper = first_token_upper(line);
if upper.is_empty() {
return false;
}
FTP_DISTINCTIVE_COMMANDS
.iter()
.any(|cmd| cmd.as_bytes() == upper)
}
pub(super) fn analyze_ftp(payload: &[u8]) -> Option<FtpInfo> {
let line = first_line(payload);
if line.is_empty() {
return None;
}
if line.len() >= 4
&& line[0].is_ascii_digit()
&& line[1].is_ascii_digit()
&& line[2].is_ascii_digit()
&& (line[3] == b' ' || line[3] == b'-')
{
let code = std::str::from_utf8(&line[0..3]).ok()?.parse::<u16>().ok()?;
if !(1..=5).contains(&(code / 100)) || (code / 10) % 10 > 5 {
return None;
}
let is_continuation = line[3] == b'-';
let message = std::str::from_utf8(&line[4..])
.ok()
.map(|s| s.trim().to_string());
let server_software = if code == 220 && !is_continuation {
message.as_deref().map(extract_software_token)
} else {
None
};
let system_type = if code == 215 && !is_continuation {
message.as_deref().map(extract_software_token)
} else {
None
};
return Some(FtpInfo {
message_type: FtpMessageType::Response,
command: None,
args: None,
response_code: Some(code),
response_message: message,
username: None,
server_software,
system_type,
});
}
let upper = first_token_upper(line);
if upper.is_empty() {
return None;
}
let is_command = FTP_COMMANDS.iter().any(|cmd| cmd.as_bytes() == upper);
if !is_command {
return None;
}
let command = String::from_utf8(upper).ok()?;
let args = std::str::from_utf8(line)
.ok()
.map(|s| s.trim())
.and_then(|s| {
s.split_once(char::is_whitespace)
.map(|(_, rest)| rest.trim())
})
.filter(|s| !s.is_empty())
.map(|s| s.to_string());
let username = if command == "USER" {
args.clone()
} else {
None
};
Some(FtpInfo {
message_type: FtpMessageType::Request,
command: Some(command),
args,
response_code: None,
response_message: None,
username,
server_software: None,
system_type: None,
})
}
fn first_line(payload: &[u8]) -> &[u8] {
let sniff = &payload[..payload.len().min(MAX_SNIFF_BYTES)];
match sniff.iter().position(|&b| b == b'\n') {
Some(end) => {
if end > 0 && sniff[end - 1] == b'\r' {
&sniff[..end - 1]
} else {
&sniff[..end]
}
}
None => sniff,
}
}
fn first_token_upper(line: &[u8]) -> Vec<u8> {
let token_end = line
.iter()
.position(|&b| b == b' ' || b == b'\t' || b == b'\r')
.unwrap_or(line.len());
let token = &line[..token_end];
if token.is_empty() || token.len() > 6 {
return Vec::new();
}
if !token.iter().all(|b| b.is_ascii_alphabetic()) {
return Vec::new();
}
token.iter().map(|b| b.to_ascii_uppercase()).collect()
}
fn extract_software_token(message: &str) -> String {
for token in message.split_whitespace() {
let trimmed = token.trim_matches(|c: char| !c.is_ascii_alphanumeric());
if trimmed.chars().any(|c| c.is_ascii_alphabetic()) {
return trimmed.to_string();
}
}
message.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detects_server_greeting() {
let payload = b"220 ProFTPD 1.3.7 Server (Example) [::ffff:10.0.0.1]\r\n";
assert!(!is_ftp(payload));
let info = analyze_ftp(payload).expect("should parse");
assert!(matches!(info.message_type, FtpMessageType::Response));
assert_eq!(info.response_code, Some(220));
assert_eq!(info.server_software.as_deref(), Some("ProFTPD"));
}
#[test]
fn detects_continuation_response() {
let payload = b"220-Welcome to the FTP service.\r\n220 Ready.\r\n";
assert!(!is_ftp(payload));
let info = analyze_ftp(payload).expect("should parse");
assert_eq!(info.response_code, Some(220));
}
#[test]
fn signature_ignores_verbs_shared_with_mail_protocols() {
assert!(!is_ftp(b"220 smtp.gmail.com ESMTP x1234\r\n"));
assert!(!is_ftp(b"EHLO mail.example.com\r\n"));
assert!(!is_ftp(b"AUTH LOGIN\r\n"));
assert!(!is_ftp(b"USER alice\r\n"));
assert!(!is_ftp(b"RETR 1\r\n"));
assert!(is_ftp(b"PASV\r\n"));
assert!(is_ftp(b"TYPE I\r\n"));
assert!(is_ftp(b"cwd /pub\r\n"));
}
#[test]
fn rejects_out_of_range_reply_codes() {
assert!(analyze_ftp(b"999 hello\r\n").is_none());
assert!(analyze_ftp(b"090 hello\r\n").is_none());
assert!(analyze_ftp(b"260-x\r\n").is_none());
}
#[test]
fn skips_software_extraction_on_220_continuation() {
let payload = b"220-Welcome to the FTP service.\r\n220 ProFTPD 1.3.7\r\n";
let info = analyze_ftp(payload).expect("should parse");
assert_eq!(info.response_code, Some(220));
assert!(
info.server_software.is_none(),
"continuation lines must not populate server_software, got {:?}",
info.server_software
);
}
#[test]
fn parses_user_request() {
let payload = b"USER alice\r\n";
let info = analyze_ftp(payload).expect("should parse");
assert!(matches!(info.message_type, FtpMessageType::Request));
assert_eq!(info.command.as_deref(), Some("USER"));
assert_eq!(info.username.as_deref(), Some("alice"));
assert_eq!(info.args.as_deref(), Some("alice"));
}
#[test]
fn parses_retr_request() {
let payload = b"RETR /pub/file.iso\r\n";
let info = analyze_ftp(payload).expect("should parse");
assert_eq!(info.command.as_deref(), Some("RETR"));
assert_eq!(info.args.as_deref(), Some("/pub/file.iso"));
assert!(info.username.is_none());
}
#[test]
fn parses_noop_without_args() {
let payload = b"NOOP\r\n";
let info = analyze_ftp(payload).expect("should parse");
assert_eq!(info.command.as_deref(), Some("NOOP"));
assert!(info.args.is_none());
}
#[test]
fn parses_lowercase_command() {
let payload = b"quit\r\n";
let info = analyze_ftp(payload).expect("should parse");
assert_eq!(info.command.as_deref(), Some("QUIT"));
}
#[test]
fn parses_system_type_response() {
let payload = b"215 UNIX Type: L8\r\n";
let info = analyze_ftp(payload).expect("should parse");
assert_eq!(info.response_code, Some(215));
assert!(
info.server_software.is_none(),
"215 must not populate server_software"
);
assert_eq!(info.system_type.as_deref(), Some("UNIX"));
}
#[test]
fn rejects_unknown_request() {
assert!(!is_ftp(b"FOOBAR baz\r\n"));
assert!(analyze_ftp(b"FOOBAR baz\r\n").is_none());
}
#[test]
fn rejects_http_payload() {
let payload = b"GET /index.html HTTP/1.1\r\nHost: example.com\r\n\r\n";
assert!(!is_ftp(payload));
assert!(analyze_ftp(payload).is_none());
}
#[test]
fn rejects_short_response() {
assert!(!is_ftp(b"220"));
assert!(analyze_ftp(b"220").is_none());
}
#[test]
fn rejects_non_digit_prefix() {
assert!(!is_ftp(b"2X0 hello\r\n"));
}
#[test]
fn parses_epsv_extended_passive() {
let payload = b"EPSV\r\n";
let info = analyze_ftp(payload).expect("should parse");
assert_eq!(info.command.as_deref(), Some("EPSV"));
}
}