use std::sync::Arc;
use std::time::Duration;
use serde::{Deserialize, Serialize};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::time::timeout;
use super::tcp::insecure_client_config;
use crate::error::{NoctisError, Result};
const READ_IDLE_MS: u64 = 500;
const MAX_REPLY_BYTES: usize = 64 * 1024;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DialogueResult {
pub connected: bool,
pub banner: Option<String>,
pub responses: Vec<String>,
pub transcript: String,
pub response_hex: Option<String>,
pub duration_ms: u64,
}
fn to_text(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).trim_end().to_string()
}
async fn read_reply<S: AsyncReadExt + Unpin>(
stream: &mut S,
first_wait: Duration,
) -> Option<Vec<u8>> {
let mut acc = Vec::new();
let mut chunk = [0u8; 4096];
loop {
let wait = if acc.is_empty() {
first_wait
} else {
Duration::from_millis(READ_IDLE_MS)
};
match timeout(wait, stream.read(&mut chunk)).await {
Ok(Ok(0)) => break, Ok(Ok(n)) => {
acc.extend_from_slice(&chunk[..n]);
if acc.len() >= MAX_REPLY_BYTES {
break;
}
}
Ok(Err(_)) => break, Err(_) => break, }
}
if acc.is_empty() {
None
} else {
Some(acc)
}
}
struct Exchange {
banner: Option<Vec<u8>>,
replies: Vec<Vec<u8>>,
}
async fn converse<S: AsyncReadExt + AsyncWriteExt + Unpin>(
stream: &mut S,
read_banner: bool,
commands: &[String],
line_ending: &str,
send_hex: Option<&[u8]>,
first_wait: Duration,
) -> Exchange {
let banner = if read_banner {
read_reply(stream, first_wait).await
} else {
None
};
let mut replies = Vec::new();
if let Some(frame) = send_hex {
if stream.write_all(frame).await.is_ok() {
replies.push(read_reply(stream, first_wait).await.unwrap_or_default());
}
} else {
for cmd in commands {
let line = format!("{cmd}{line_ending}");
if stream.write_all(line.as_bytes()).await.is_err() {
break;
}
replies.push(read_reply(stream, first_wait).await.unwrap_or_default());
}
}
Exchange { banner, replies }
}
#[allow(clippy::too_many_arguments)]
pub async fn run(
host: &str,
port: u16,
use_tls: bool,
read_banner: bool,
commands: Vec<String>,
line_ending: String,
send_hex: Option<Vec<u8>>,
timeout_secs: u64,
) -> Result<DialogueResult> {
let addr = format!("{host}:{port}");
let start = std::time::Instant::now();
let tcp = match timeout(Duration::from_secs(timeout_secs), TcpStream::connect(&addr)).await {
Ok(Ok(s)) => s,
Ok(Err(e)) => return Err(NoctisError::Tcp(format!("connect {addr}: {e}"))),
Err(_) => {
return Ok(DialogueResult {
connected: false,
banner: None,
responses: Vec::new(),
transcript: String::new(),
response_hex: None,
duration_ms: start.elapsed().as_millis() as u64,
})
}
};
let send_hex = send_hex.as_deref();
let first_wait = super::raw_socket::first_byte_wait(timeout_secs);
let ex = if use_tls {
let limit = Duration::from_secs(timeout_secs);
let reconnect = || async {
timeout(limit, TcpStream::connect(&addr))
.await
.map_err(|_| NoctisError::Tcp(format!("connect timeout: {addr}")))?
.map_err(|e| NoctisError::Tcp(format!("connect {addr}: {e}")))
};
let config = Arc::new(insecure_client_config()?);
let mut stream = super::legacy_tls::connect(tcp, host, config, Some(limit), reconnect)
.await
.map_err(|e| NoctisError::Tcp(format!("TLS handshake {addr}: {e}")))?;
converse(
&mut stream,
read_banner,
&commands,
&line_ending,
send_hex,
first_wait,
)
.await
} else {
let mut stream = tcp;
converse(
&mut stream,
read_banner,
&commands,
&line_ending,
send_hex,
first_wait,
)
.await
};
let banner = ex.banner.as_deref().map(to_text);
let responses: Vec<String> = ex.replies.iter().map(|b| to_text(b)).collect();
let mut transcript_parts: Vec<&str> = Vec::new();
if let Some(b) = &banner {
transcript_parts.push(b);
}
for r in &responses {
transcript_parts.push(r);
}
let transcript = transcript_parts.join("\n");
let mut raw: Vec<u8> = Vec::new();
if let Some(b) = &ex.banner {
raw.extend_from_slice(b);
}
for r in &ex.replies {
raw.extend_from_slice(r);
}
let response_hex = if raw.is_empty() {
None
} else {
Some(raw.iter().map(|b| format!("{b:02x}")).collect())
};
Ok(DialogueResult {
connected: true,
banner,
responses,
transcript,
response_hex,
duration_ms: start.elapsed().as_millis() as u64,
})
}
#[cfg(test)]
mod tests {
#[tokio::test]
async fn tls_dialogue_falls_back_to_legacy_stack() {
use crate::checks::legacy_tls::test_server::{spawn, Mode};
let port = spawn(Mode::Tls10).await;
let r = run(
"127.0.0.1",
port,
true,
false,
vec!["PING".to_string()],
"\n".to_string(),
None,
5,
)
.await
.unwrap();
assert!(r.connected);
assert_eq!(r.responses, vec!["PONG-LEGACY".to_string()]);
}
use super::*;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpListener;
async fn scripted_server() -> std::net::SocketAddr {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
if let Ok((mut sock, _)) = listener.accept().await {
let _ = sock.write_all(b"220 ready\r\n").await;
let mut buf = [0u8; 1024];
let mut n = 0u32;
loop {
match sock.read(&mut buf).await {
Ok(0) | Err(_) => break,
Ok(len) => {
n += 1;
let line = String::from_utf8_lossy(&buf[..len]);
let reply = format!("{n}: {}\r\n", line.trim());
if sock.write_all(reply.as_bytes()).await.is_err() {
break;
}
}
}
}
}
});
addr
}
#[tokio::test]
async fn banner_and_command_replies() {
let addr = scripted_server().await;
let r = run(
&addr.ip().to_string(),
addr.port(),
false,
true,
vec!["EHLO x".into(), "QUIT".into()],
"\r\n".into(),
None,
5,
)
.await
.unwrap();
assert!(r.connected);
assert_eq!(r.banner.as_deref(), Some("220 ready"));
assert_eq!(r.responses.len(), 2);
assert_eq!(r.responses[0], "1: EHLO x");
assert_eq!(r.responses[1], "2: QUIT");
assert!(r.transcript.contains("220 ready"));
assert!(r.transcript.contains("1: EHLO x"));
}
#[tokio::test]
async fn skip_banner() {
let addr = scripted_server().await;
let r = run(
&addr.ip().to_string(),
addr.port(),
false,
false,
vec!["NOOP".into()],
"\r\n".into(),
None,
5,
)
.await
.unwrap();
assert!(r.banner.is_none());
assert_eq!(r.responses.len(), 1);
assert!(r.responses[0].contains("220 ready"));
}
async fn binary_server() -> std::net::SocketAddr {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
if let Ok((mut sock, _)) = listener.accept().await {
let mut buf = [0u8; 1024];
if let Ok(n) = sock.read(&mut buf).await {
if n > 0 {
let _ = sock.write_all(&[0x00, 0xff]).await;
let _ = sock.write_all(b"databases").await;
}
}
}
});
addr
}
#[tokio::test]
async fn binary_frame_sends_and_captures_hex() {
let addr = binary_server().await;
let r = run(
&addr.ip().to_string(),
addr.port(),
false,
false,
Vec::new(),
"\r\n".into(),
Some(vec![0xde, 0xad, 0xbe, 0xef]),
5,
)
.await
.unwrap();
assert!(r.connected);
let hex = r.response_hex.expect("response_hex present");
assert!(hex.starts_with("00ff"));
assert!(hex.contains("646174616261736573"));
assert!(r.transcript.contains("databases"));
}
async fn slow_reply_server(delay_ms: u64) -> std::net::SocketAddr {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
while let Ok((mut sock, _)) = listener.accept().await {
let _ = sock.write_all(b"220 ready\r\n").await;
let mut buf = [0u8; 1024];
while let Ok(n) = sock.read(&mut buf).await {
if n == 0 {
break;
}
tokio::time::sleep(Duration::from_millis(delay_ms)).await;
if sock.write_all(b"250 slow ok\r\n").await.is_err() {
break;
}
}
}
});
addr
}
#[tokio::test]
async fn slow_first_reply_byte_is_awaited() {
let addr = slow_reply_server(1200).await;
for send_hex in [None, Some(vec![0x01, 0x02])] {
let r = run(
&addr.ip().to_string(),
addr.port(),
false,
true,
vec!["NOOP".into()],
"\r\n".into(),
send_hex,
3,
)
.await
.unwrap();
assert!(r.transcript.contains("250 slow ok"), "{r:?}");
}
}
}