Skip to main content

mailrs_clamav/
lib.rs

1#![doc = include_str!("../README.md")]
2#![deny(missing_docs)]
3#![deny(rustdoc::broken_intra_doc_links)]
4
5use std::time::Duration;
6
7use tokio::io::{AsyncReadExt, AsyncWriteExt};
8use tokio::net::TcpStream;
9
10/// Max chunk size per ClamAV INSTREAM frame.
11///
12/// ClamAV's `StreamMaxLength` default is 25 MB; INSTREAM splits the
13/// payload into length-prefixed chunks. 2 MiB per chunk balances syscall
14/// overhead against memory use.
15pub const CHUNK_SIZE: usize = 2 * 1024 * 1024;
16
17/// Default per-call timeout. Applied to connect + write + read together.
18/// ClamAV scans of typical 100 KB mails finish in <100 ms; large
19/// attachments (5-10 MB) can take seconds. Pick something that won't
20/// stall your inbound pipeline.
21pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
22
23/// Outcome of a ClamAV scan.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub enum ClamavResult {
26    /// The payload was scanned and no signature matched.
27    Clean,
28    /// A signature matched. The string is the virus name as reported by
29    /// `clamd` (e.g. `"Eicar-Test-Signature"`).
30    Virus(String),
31    /// The scan didn't complete. The string is a human-readable
32    /// description (TCP connect failure, protocol error, unparseable
33    /// reply, etc).
34    Error(String),
35}
36
37/// Scan `data` against a `clamd` daemon listening at `addr` (e.g.
38/// `"127.0.0.1:3310"`) using the **zINSTREAM** protocol variant.
39///
40/// `zINSTREAM` is the null-terminated form of INSTREAM (the `z` prefix
41/// means "command terminator is `\0`"). It's the most widely supported
42/// form across `clamd` versions.
43///
44/// The default timeout (see [`DEFAULT_TIMEOUT`]) applies. Use
45/// [`scan_with_timeout`] to override.
46///
47/// Returns:
48/// - [`ClamavResult::Clean`] if the payload was scanned and is clean
49/// - [`ClamavResult::Virus`] with the virus name on detection
50/// - [`ClamavResult::Error`] on any I/O / protocol / timeout failure
51///   (never panics)
52pub async fn scan(addr: &str, data: &[u8]) -> ClamavResult {
53    scan_with_timeout(addr, data, DEFAULT_TIMEOUT).await
54}
55
56/// Like [`scan`] but with a caller-supplied timeout.
57pub async fn scan_with_timeout(addr: &str, data: &[u8], timeout: Duration) -> ClamavResult {
58    match tokio::time::timeout(timeout, scan_inner(addr, data)).await {
59        Ok(r) => r,
60        Err(_) => ClamavResult::Error(format!("timeout after {timeout:?}")),
61    }
62}
63
64async fn scan_inner(addr: &str, data: &[u8]) -> ClamavResult {
65    let mut stream = match TcpStream::connect(addr).await {
66        Ok(s) => s,
67        Err(e) => return ClamavResult::Error(format!("connect failed: {e}")),
68    };
69
70    // zINSTREAM = INSTREAM with NUL terminator instead of newline.
71    if stream.write_all(b"zINSTREAM\0").await.is_err() {
72        return ClamavResult::Error("write command failed".into());
73    }
74
75    // Length-prefixed chunks. ClamAV refuses chunks above StreamMaxLength
76    // (typically 25 MB), so we cap each frame at CHUNK_SIZE.
77    for chunk in data.chunks(CHUNK_SIZE) {
78        let len = (chunk.len() as u32).to_be_bytes();
79        if stream.write_all(&len).await.is_err() || stream.write_all(chunk).await.is_err() {
80            return ClamavResult::Error("write data failed".into());
81        }
82    }
83
84    // Zero-length chunk terminates the INSTREAM frame.
85    if stream.write_all(&0u32.to_be_bytes()).await.is_err() {
86        return ClamavResult::Error("write terminator failed".into());
87    }
88
89    // Replies fit in 1 KB easily — `stream: Eicar-Test-Signature FOUND\n`
90    // is ~40 bytes; even verbose error strings are well under 200.
91    let mut response = vec![0u8; 1024];
92    match stream.read(&mut response).await {
93        Ok(n) => parse_response(&response[..n]),
94        Err(e) => ClamavResult::Error(format!("read failed: {e}")),
95    }
96}
97
98/// Parse a `clamd` INSTREAM reply.
99///
100/// Expected wire shapes:
101/// - `"stream: OK"` → Clean
102/// - `"stream: Eicar-Test-Signature FOUND"` → Virus("Eicar-Test-Signature")
103/// - anything else → Error (includes `clamd` error strings like
104///   `"INSTREAM size limit exceeded. ERROR"`)
105pub fn parse_response(response: &[u8]) -> ClamavResult {
106    let s = String::from_utf8_lossy(response);
107    let s = s.trim_end_matches('\0').trim();
108
109    if s.ends_with("OK") {
110        ClamavResult::Clean
111    } else if let Some(found_pos) = s.find("FOUND") {
112        // Wire form: "stream: VirusName FOUND" — virus name lives
113        // between the last ':' and the trailing " FOUND".
114        let virus = s[..found_pos]
115            .trim()
116            .rsplit(':')
117            .next()
118            .unwrap_or("")
119            .trim();
120        ClamavResult::Virus(virus.to_string())
121    } else {
122        ClamavResult::Error(s.to_string())
123    }
124}
125
126/// PING the daemon. Returns `true` if `clamd` is up and replies `PONG`
127/// within the timeout.
128pub async fn ping(addr: &str, timeout: Duration) -> bool {
129    let Ok(Ok(mut stream)) = tokio::time::timeout(timeout, TcpStream::connect(addr)).await else {
130        return false;
131    };
132    if tokio::time::timeout(timeout, stream.write_all(b"zPING\0"))
133        .await
134        .is_err()
135        || stream.flush().await.is_err()
136    {
137        return false;
138    }
139    let mut buf = [0u8; 16];
140    let Ok(Ok(n)) = tokio::time::timeout(timeout, stream.read(&mut buf)).await else {
141        return false;
142    };
143    let reply = String::from_utf8_lossy(&buf[..n]);
144    reply.trim_end_matches('\0').trim() == "PONG"
145}
146
147/// Ask `clamd` for its version string. Useful for ops dashboards.
148///
149/// Returns `None` if the daemon doesn't respond within `timeout` or
150/// reports a malformed reply.
151pub async fn version(addr: &str, timeout: Duration) -> Option<String> {
152    let Ok(Ok(mut stream)) = tokio::time::timeout(timeout, TcpStream::connect(addr)).await else {
153        return None;
154    };
155    if tokio::time::timeout(timeout, stream.write_all(b"zVERSION\0"))
156        .await
157        .is_err()
158    {
159        return None;
160    }
161    let mut buf = [0u8; 256];
162    let Ok(Ok(n)) = tokio::time::timeout(timeout, stream.read(&mut buf)).await else {
163        return None;
164    };
165    let v = String::from_utf8_lossy(&buf[..n]);
166    let v = v.trim_end_matches('\0').trim();
167    if v.is_empty() {
168        None
169    } else {
170        Some(v.to_string())
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    #[test]
179    fn parse_clean_reply() {
180        assert_eq!(parse_response(b"stream: OK\n"), ClamavResult::Clean);
181        assert_eq!(parse_response(b"stream: OK"), ClamavResult::Clean);
182        // Trailing NUL (zINSTREAM)
183        assert_eq!(parse_response(b"stream: OK\0"), ClamavResult::Clean);
184    }
185
186    #[test]
187    fn parse_virus_reply_eicar() {
188        assert_eq!(
189            parse_response(b"stream: Eicar-Test-Signature FOUND\n"),
190            ClamavResult::Virus("Eicar-Test-Signature".into())
191        );
192    }
193
194    #[test]
195    fn parse_virus_reply_with_extended_name() {
196        // ClamAV signatures can have dots, dashes, slashes
197        assert_eq!(
198            parse_response(b"stream: Trojan.Win32.Generic-7654321 FOUND\n"),
199            ClamavResult::Virus("Trojan.Win32.Generic-7654321".into())
200        );
201    }
202
203    #[test]
204    fn parse_virus_reply_no_stream_prefix() {
205        // Some daemons / proxies strip the prefix.
206        assert_eq!(
207            parse_response(b"Eicar FOUND"),
208            ClamavResult::Virus("Eicar".into())
209        );
210    }
211
212    #[test]
213    fn parse_error_reply_size_limit() {
214        // Real clamd reply when payload exceeds StreamMaxLength
215        let r = parse_response(b"INSTREAM size limit exceeded. ERROR");
216        assert!(matches!(r, ClamavResult::Error(_)));
217        if let ClamavResult::Error(e) = r {
218            assert!(e.contains("size limit"));
219        }
220    }
221
222    #[test]
223    fn parse_empty_reply_is_error() {
224        let r = parse_response(b"");
225        assert!(matches!(r, ClamavResult::Error(_)));
226    }
227
228    #[test]
229    fn parse_whitespace_only_reply_is_error() {
230        // Empty after trim — still parsed as error (no OK / FOUND)
231        let r = parse_response(b"   \n\t  ");
232        assert!(matches!(r, ClamavResult::Error(_)));
233    }
234
235    #[test]
236    fn parse_strips_trailing_nuls() {
237        // zINSTREAM wire form has NUL terminator
238        let r = parse_response(b"stream: OK\0\0\0");
239        assert_eq!(r, ClamavResult::Clean);
240    }
241
242    #[test]
243    fn parse_invalid_utf8_lossy_still_works() {
244        let bad: &[u8] = &[
245            0xFF, 0xFE, b's', b't', b'r', b'e', b'a', b'm', b':', b' ', b'O', b'K',
246        ];
247        let r = parse_response(bad);
248        // From-utf8-lossy replaces invalid bytes; "OK" still matches.
249        assert_eq!(r, ClamavResult::Clean);
250    }
251
252    #[test]
253    fn clamav_result_equality_for_same_virus_name() {
254        let a = ClamavResult::Virus("X".into());
255        let b = ClamavResult::Virus("X".into());
256        assert_eq!(a, b);
257    }
258
259    #[test]
260    fn clamav_result_inequality_for_different_virus_names() {
261        assert_ne!(
262            ClamavResult::Virus("A".into()),
263            ClamavResult::Virus("B".into())
264        );
265    }
266
267    #[test]
268    fn scan_unreachable_addr_returns_error_not_panic() {
269        // Use a port that's almost certainly not bound.
270        let rt = tokio::runtime::Runtime::new().unwrap();
271        let r = rt.block_on(scan_with_timeout(
272            "127.0.0.1:1",
273            b"payload",
274            Duration::from_millis(200),
275        ));
276        assert!(matches!(r, ClamavResult::Error(_)));
277    }
278
279    #[test]
280    fn scan_with_zero_timeout_returns_timeout_error() {
281        let rt = tokio::runtime::Runtime::new().unwrap();
282        let r = rt.block_on(scan_with_timeout(
283            "127.0.0.1:1",
284            b"payload",
285            Duration::from_micros(1),
286        ));
287        assert!(matches!(r, ClamavResult::Error(_)));
288        if let ClamavResult::Error(e) = r {
289            // Either timeout or connect-failure depending on race
290            assert!(e.contains("timeout") || e.contains("connect"));
291        }
292    }
293
294    #[test]
295    fn ping_returns_false_when_unreachable() {
296        let rt = tokio::runtime::Runtime::new().unwrap();
297        let r = rt.block_on(ping("127.0.0.1:1", Duration::from_millis(200)));
298        assert!(!r);
299    }
300
301    #[test]
302    fn version_returns_none_when_unreachable() {
303        let rt = tokio::runtime::Runtime::new().unwrap();
304        let r = rt.block_on(version("127.0.0.1:1", Duration::from_millis(200)));
305        assert!(r.is_none());
306    }
307}