Skip to main content

rfc5321/
client.rs

1#![allow(clippy::result_large_err)]
2use crate::client_types::*;
3use crate::parser::{Command, Domain, EsmtpParameter, ForwardPath, ReversePath};
4use crate::{AsyncReadAndWrite, BoxedAsyncReadAndWrite};
5use bstr::ByteSlice;
6use hickory_proto::rr::rdata::TLSA;
7use hickory_proto::rr::Name;
8use kumo_chrono_helper::Instant;
9use memchr::memmem::Finder;
10use nom_utils::DomainString;
11use openssl::x509::{X509Ref, X509};
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::net::IpAddr;
15use std::str::FromStr;
16use std::sync::{Arc, LazyLock};
17use std::time::Duration;
18use thiserror::Error;
19use tokio::io::{AsyncReadExt, AsyncWriteExt};
20use tokio::net::{TcpStream, ToSocketAddrs};
21use tokio::time::{timeout, timeout_at};
22use tokio_rustls::rustls::pki_types::ServerName;
23use tracing::Level;
24
25pub use kumo_tls_helper::TlsOptions;
26pub use openssl;
27pub use tokio_rustls;
28
29const MAX_LINE_LEN: usize = 4096;
30
31#[derive(Error, Debug, Clone)]
32pub enum ClientError {
33    #[error("response is not UTF8")]
34    Utf8(#[from] std::string::FromUtf8Error),
35    #[error("Malformed Response: {0}")]
36    MalformedResponseLine(String),
37    #[error("Response line is too long")]
38    ResponseTooLong,
39    #[error("Not connected")]
40    NotConnected,
41    #[error("Command rejected {0:?}")]
42    Rejected(Response),
43    #[error("Commands rejected {0:?}")]
44    RejectedBatch(Vec<Response>),
45    #[error("STARTTLS: {0} is not a valid DNS name")]
46    InvalidDnsName(String),
47    #[error("Invalid client certificate configured: {error:?}")]
48    FailedToBuildConnector { error: String },
49    #[error("Timed Out waiting {duration:?} for response to cmd={}", self.command_for_err())]
50    TimeOutResponse {
51        command: Option<Command>,
52        duration: Duration,
53    },
54    #[error("Timed Out after {duration:?} writing cmd={}", self.command_for_err())]
55    TimeOutRequest {
56        commands: Vec<Command>,
57        duration: Duration,
58    },
59    #[error("Error {error} reading response to cmd={}", self.command_for_err())]
60    ReadError {
61        command: Option<Command>,
62        error: String,
63        partial: String,
64    },
65    #[error("Error {error} flushing send buffer")]
66    FlushError { error: String },
67    #[error("Error {error} writing {}", self.command_for_err())]
68    WriteError {
69        commands: Vec<Command>,
70        error: String,
71    },
72    #[error("Timed Out sending message payload data")]
73    TimeOutData,
74    #[error("SSL Error: {0}")]
75    SslErrorStack(#[from] openssl::error::ErrorStack),
76    #[error("No usable DANE TLSA records for {hostname}: {tlsa:?}")]
77    NoUsableDaneTlsa { hostname: String, tlsa: Vec<TLSA> },
78}
79
80impl ClientError {
81    /// Returns the command(s) string suitable for passing into a Response,
82    /// with any AUTH credential masked (see [`Command::encode_for_logging`]).
83    pub fn command(&self) -> Option<String> {
84        match self {
85            Self::TimeOutResponse {
86                command: Some(command),
87                ..
88            }
89            | Self::ReadError {
90                command: Some(command),
91                ..
92            } => Some(command.encode_for_logging().to_string()),
93            Self::TimeOutRequest { commands, .. } | Self::WriteError { commands, .. }
94                if !commands.is_empty() =>
95            {
96                let s: String = commands
97                    .iter()
98                    .map(|cmd| cmd.encode_for_logging().to_string())
99                    .collect();
100                Some(s)
101            }
102            _ => None,
103        }
104    }
105
106    /// Returns the command(s) string suitable for embedding in the
107    /// overall error message
108    fn command_for_err(&self) -> String {
109        self.command()
110            .map(|cmd| cmd.replace("\r\n", ""))
111            .unwrap_or_else(|| "NONE".to_string())
112    }
113
114    /// If the error contents were likely caused by something
115    /// about the mostly recently attempted message, rather than
116    /// a transport issue, or a carry-over from a prior message
117    /// (eg: previous message was rejected and destination chose
118    /// to drop the connection, which we detect later in RSET
119    /// on the next message), then we return true.
120    /// The expectation is that the caller will transiently
121    /// fail the message for later retry.
122    /// If we return false then the caller might decide to
123    /// try that same message again more immediately on
124    /// a separate connection
125    pub fn was_due_to_message(&self) -> bool {
126        match self {
127            Self::Utf8(_)
128            | Self::MalformedResponseLine(_)
129            | Self::ResponseTooLong
130            | Self::NotConnected
131            | Self::InvalidDnsName(_)
132            | Self::FailedToBuildConnector { .. }
133            | Self::TimeOutResponse { .. }
134            | Self::TimeOutRequest { .. }
135            | Self::ReadError { .. }
136            | Self::FlushError { .. }
137            | Self::WriteError { .. }
138            | Self::TimeOutData
139            | Self::SslErrorStack(_)
140            | Self::NoUsableDaneTlsa { .. } => false,
141            Self::Rejected(response) => response.was_due_to_message(),
142            Self::RejectedBatch(responses) => match responses.len() {
143                1 => responses[0].was_due_to_message(),
144                _ => false,
145            },
146        }
147    }
148}
149
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct EsmtpCapability {
152    pub name: String,
153    pub param: Option<String>,
154}
155
156#[derive(Clone, Debug)]
157pub enum SmtpClientTraceEvent {
158    Closed,
159    Read(Vec<u8>),
160    Write(String),
161    Diagnostic {
162        level: tracing::Level,
163        message: String,
164    },
165}
166
167pub trait DeferredTracer {
168    fn trace(&self) -> SmtpClientTraceEvent;
169}
170
171pub trait SmtpClientTracer: std::fmt::Debug {
172    fn trace_event(&self, event: SmtpClientTraceEvent);
173    fn lazy_trace(&self, deferred: &dyn DeferredTracer);
174}
175
176// helper to avoid making a second copy of every write buffer
177struct WriteTracer<'a> {
178    data: &'a str,
179}
180impl DeferredTracer for WriteTracer<'_> {
181    fn trace(&self) -> SmtpClientTraceEvent {
182        SmtpClientTraceEvent::Write(self.data.to_string())
183    }
184}
185impl<'a> WriteTracer<'a> {
186    fn trace(tracer: &Arc<dyn SmtpClientTracer + Send + Sync>, data: &'a str) {
187        tracer.lazy_trace(&Self { data });
188    }
189}
190
191struct BinWriteTracer<'a> {
192    data: &'a [u8],
193}
194impl DeferredTracer for BinWriteTracer<'_> {
195    fn trace(&self) -> SmtpClientTraceEvent {
196        let data = String::from_utf8_lossy(self.data).to_string();
197        SmtpClientTraceEvent::Write(data)
198    }
199}
200impl<'a> BinWriteTracer<'a> {
201    fn trace(tracer: &Arc<dyn SmtpClientTracer + Send + Sync>, data: &'a [u8]) {
202        tracer.lazy_trace(&Self { data });
203    }
204}
205
206// A little bit of gymnastics to avoid making a second
207// copy of every read buffer
208struct ReadTracer<'a> {
209    data: &'a [u8],
210}
211impl DeferredTracer for ReadTracer<'_> {
212    fn trace(&self) -> SmtpClientTraceEvent {
213        SmtpClientTraceEvent::Read(self.data.to_vec())
214    }
215}
216
217#[derive(Debug)]
218pub struct SmtpClient {
219    socket: Option<BoxedAsyncReadAndWrite>,
220    hostname: String,
221    capabilities: HashMap<String, EsmtpCapability>,
222    read_buffer: Vec<u8>,
223    timeouts: SmtpClientTimeouts,
224    tracer: Option<Arc<dyn SmtpClientTracer + Send + Sync>>,
225    use_rset: bool,
226    enable_rset: bool,
227    enable_pipelining: bool,
228    ignore_8bit_checks: bool,
229}
230
231fn extract_hostname(hostname: &str) -> &str {
232    // Just the hostname, without any :port
233    let fields: Vec<&str> = hostname.rsplitn(2, ':').collect();
234    let hostname = if fields.len() == 2 {
235        fields[1]
236    } else {
237        hostname
238    };
239
240    let hostname = if hostname.starts_with('[') && hostname.ends_with(']') {
241        &hostname[1..hostname.len() - 1]
242    } else {
243        hostname
244    };
245
246    // Remove any trailing FQDN dot
247    hostname.strip_suffix(".").unwrap_or(hostname)
248}
249
250impl SmtpClient {
251    pub async fn new<A: ToSocketAddrs + ToString + Clone>(
252        addr: A,
253        timeouts: SmtpClientTimeouts,
254    ) -> std::io::Result<Self> {
255        let stream = TcpStream::connect(addr.clone()).await?;
256        // No need for Nagle with SMTP request/response
257        stream.set_nodelay(true)?;
258        Ok(Self::with_stream(stream, addr.to_string(), timeouts))
259    }
260
261    pub fn with_stream<S: AsyncReadAndWrite + 'static, H: AsRef<str>>(
262        stream: S,
263        peer_hostname: H,
264        timeouts: SmtpClientTimeouts,
265    ) -> Self {
266        let hostname = extract_hostname(peer_hostname.as_ref()).to_string();
267
268        Self {
269            socket: Some(Box::new(stream)),
270            hostname,
271            capabilities: HashMap::new(),
272            read_buffer: Vec::with_capacity(1024),
273            timeouts,
274            tracer: None,
275            use_rset: false,
276            enable_rset: false,
277            enable_pipelining: false,
278            ignore_8bit_checks: false,
279        }
280    }
281
282    /// Setting this to true causes 8BITMIME and SMTPUTF8 checks to be ignored
283    pub fn set_ignore_8bit_checks(&mut self, enable: bool) {
284        self.ignore_8bit_checks = enable;
285    }
286
287    pub fn is_connected(&self) -> bool {
288        self.socket.is_some()
289    }
290
291    pub fn set_enable_rset(&mut self, enable: bool) {
292        self.enable_rset = enable;
293    }
294
295    pub fn set_enable_pipelining(&mut self, enable: bool) {
296        self.enable_pipelining = enable;
297    }
298
299    pub fn set_tracer(&mut self, tracer: Arc<dyn SmtpClientTracer + Send + Sync>) {
300        self.tracer.replace(tracer);
301    }
302
303    pub fn timeouts(&self) -> &SmtpClientTimeouts {
304        &self.timeouts
305    }
306
307    async fn read_line(
308        &mut self,
309        timeout_duration: Duration,
310        cmd: Option<&Command>,
311    ) -> Result<String, ClientError> {
312        let mut too_long = false;
313        loop {
314            let mut iter = self.read_buffer.iter().enumerate();
315            while let Some((i, &b)) = iter.next() {
316                if b != b'\r' {
317                    continue;
318                }
319                if let Some((_, b'\n')) = iter.next() {
320                    if too_long {
321                        self.read_buffer.drain(0..i + 2);
322
323                        if let Some(tracer) = &self.tracer {
324                            tracer.trace_event(SmtpClientTraceEvent::Diagnostic {
325                                level: Level::ERROR,
326                                message: "Response too long".to_string(),
327                            });
328                        }
329
330                        return Err(ClientError::ResponseTooLong);
331                    }
332
333                    let line = String::from_utf8(self.read_buffer[0..i].to_vec());
334                    self.read_buffer.drain(0..i + 2);
335                    return Ok(line?);
336                }
337            }
338            if self.read_buffer.len() > MAX_LINE_LEN {
339                self.read_buffer.clear();
340                too_long = true;
341            }
342
343            // Didn't find a complete line, fill up the rest of the buffer
344            let mut data = [0u8; MAX_LINE_LEN];
345            let size = match self.socket.as_mut() {
346                Some(s) => match timeout(timeout_duration, s.read(&mut data)).await {
347                    Ok(Ok(size)) => size,
348                    Ok(Err(err)) => {
349                        self.socket.take();
350                        if let Some(tracer) = &self.tracer {
351                            tracer.trace_event(SmtpClientTraceEvent::Diagnostic {
352                                level: Level::ERROR,
353                                message: format!("Error during read: {err:#}"),
354                            });
355                            tracer.trace_event(SmtpClientTraceEvent::Closed);
356                        }
357                        return Err(ClientError::ReadError {
358                            command: cmd.cloned(),
359                            error: format!("{err:#}"),
360                            partial: String::from_utf8_lossy(&self.read_buffer).to_string(),
361                        });
362                    }
363                    Err(_) => {
364                        // If we're using a zero timeout we're probing
365                        // for liveness, so we don't want to treat this
366                        // timeout as a fatal error that closes the
367                        // connection
368                        if timeout_duration != Duration::ZERO {
369                            self.socket.take();
370                        }
371                        if let Some(tracer) = &self.tracer {
372                            tracer.trace_event(SmtpClientTraceEvent::Diagnostic {
373                                level: Level::ERROR,
374                                message: format!("Read Timeout after {timeout_duration:?}"),
375                            });
376                            if self.socket.is_none() {
377                                tracer.trace_event(SmtpClientTraceEvent::Closed);
378                            }
379                        }
380                        return Err(ClientError::TimeOutResponse {
381                            command: cmd.cloned(),
382                            duration: timeout_duration,
383                        });
384                    }
385                },
386                None => {
387                    return Err(ClientError::ReadError {
388                        command: cmd.cloned(),
389                        error: "the socket was closed in response to an earlier issue".to_string(),
390                        partial: String::from_utf8_lossy(&self.read_buffer).to_string(),
391                    });
392                }
393            };
394            if size == 0 {
395                self.socket.take();
396                if let Some(tracer) = &self.tracer {
397                    tracer.trace_event(SmtpClientTraceEvent::Closed);
398                }
399                return Err(ClientError::ReadError {
400                    command: cmd.cloned(),
401                    error: "Connection closed by peer".to_string(),
402                    partial: String::from_utf8_lossy(&self.read_buffer).to_string(),
403                });
404            }
405            if let Some(tracer) = &self.tracer {
406                tracer.lazy_trace(&ReadTracer {
407                    data: &data[0..size],
408                });
409            }
410            self.read_buffer.extend_from_slice(&data[0..size]);
411        }
412    }
413
414    /// Check to see if there is either a unilateral response
415    /// or an error condition immediately available on the socket.
416    ///
417    /// Intended to be used after the connection has idled to see if
418    /// the peer has opted to close the connection, either gracefully
419    /// by sending what should be a 421, or abruptly by simply snipping
420    /// the connection.
421    pub async fn check_unilateral_response(&mut self) -> Result<Option<Response>, ClientError> {
422        match self.read_response(None, Duration::ZERO).await {
423            // Unilateral response was received
424            Ok(response) => Ok(Some(response)),
425            // Nothing immediately available: this should hopefully be the common case
426            Err(ClientError::TimeOutResponse { .. }) => Ok(None),
427            // An actual error
428            Err(err) => Err(err),
429        }
430    }
431
432    pub async fn read_response(
433        &mut self,
434        command: Option<&Command>,
435        timeout_duration: Duration,
436    ) -> Result<Response, ClientError> {
437        let deadline = Instant::now().saturating_add(timeout_duration);
438
439        if let Some(sock) = self.socket.as_mut() {
440            match timeout_at(deadline.into(), sock.flush()).await {
441                Ok(Ok(())) => {}
442                Ok(Err(err)) => {
443                    self.socket.take();
444                    if let Some(tracer) = &self.tracer {
445                        tracer.trace_event(SmtpClientTraceEvent::Diagnostic {
446                            level: Level::ERROR,
447                            message: format!("Error during flush: {err:#}"),
448                        });
449                        tracer.trace_event(SmtpClientTraceEvent::Closed);
450                    }
451                    return Err(ClientError::FlushError {
452                        error: format!("{err:#}"),
453                    });
454                }
455                Err(_elapsed) => {
456                    self.socket.take();
457                    if let Some(tracer) = &self.tracer {
458                        tracer.trace_event(SmtpClientTraceEvent::Diagnostic {
459                            level: Level::ERROR,
460                            message: format!("Flush timed out after {timeout_duration:?}"),
461                        });
462                        tracer.trace_event(SmtpClientTraceEvent::Closed);
463                    }
464                    return Err(ClientError::TimeOutResponse {
465                        command: command.cloned(),
466                        duration: timeout_duration,
467                    });
468                }
469            }
470        }
471
472        let mut line = self
473            .read_line(deadline.saturating_duration_since(Instant::now()), command)
474            .await?;
475        tracing::trace!("recv<-{}: {line}", self.hostname);
476        let mut parsed = parse_response_line(&line)?;
477        let mut response_builder = ResponseBuilder::new(&parsed);
478
479        while !parsed.is_final {
480            let per_line =
481                Duration::from_secs(60).min(deadline.saturating_duration_since(Instant::now()));
482            line = self.read_line(per_line, command).await?;
483            parsed = parse_response_line(&line)?;
484            response_builder
485                .add_line(&parsed)
486                .map_err(ClientError::MalformedResponseLine)?;
487        }
488
489        let response =
490            response_builder.build(command.map(|cmd| cmd.encode_for_logging().to_string()));
491
492        tracing::trace!("{}: {response:?}", self.hostname);
493
494        Ok(response)
495    }
496
497    pub async fn send_command(&mut self, command: &Command) -> Result<Response, ClientError> {
498        self.write_command_request(command).await?;
499        self.read_response(Some(command), command.client_timeout(&self.timeouts))
500            .await
501    }
502
503    /// Wrapper around socket.write_all() that will emit trace diagnostics and synthesize
504    /// a Close event to the tracer if a timeout or IO error occurs.
505    /// If an error or timeout, occurs ensures that the socket will not be reused.
506    async fn write_all_with_timeout<F, G>(
507        &mut self,
508        timeout_duration: Duration,
509        bytes: &[u8],
510        make_timeout_err: F,
511        make_write_err: G,
512    ) -> Result<(), ClientError>
513    where
514        F: FnOnce() -> ClientError,
515        G: FnOnce(String) -> ClientError,
516    {
517        match self.socket.as_mut() {
518            Some(socket) => match timeout(timeout_duration, socket.write_all(bytes)).await {
519                Ok(Ok(response)) => Ok(response),
520                Ok(Err(err)) => {
521                    self.socket.take();
522                    if let Some(tracer) = &self.tracer {
523                        tracer.trace_event(SmtpClientTraceEvent::Diagnostic {
524                            level: Level::ERROR,
525                            message: format!("Error during write: {err:#}"),
526                        });
527                        tracer.trace_event(SmtpClientTraceEvent::Closed);
528                    }
529                    Err(make_write_err(format!("{err:#}")))
530                }
531                Err(_) => {
532                    self.socket.take();
533                    if let Some(tracer) = &self.tracer {
534                        tracer.trace_event(SmtpClientTraceEvent::Diagnostic {
535                            level: Level::ERROR,
536                            message: format!("Write Timeout after {timeout_duration:?}"),
537                        });
538                        tracer.trace_event(SmtpClientTraceEvent::Closed);
539                    }
540                    Err(make_timeout_err())
541                }
542            },
543            None => Err(make_write_err(
544                "the socket was closed in response to an earlier issue".to_string(),
545            )),
546        }
547    }
548
549    async fn write_pipeline_request(&mut self, commands: &[Command]) -> Result<(), ClientError> {
550        let total_timeout: Duration = commands
551            .iter()
552            .map(|cmd| cmd.client_timeout_request(&self.timeouts))
553            .sum();
554
555        let mut lines: Vec<String> = vec![];
556        let mut all: Vec<u8> = vec![];
557        for cmd in commands {
558            let line = cmd.encode();
559            all.extend_from_slice(&line);
560            lines.push(line.to_string());
561        }
562        tracing::trace!(
563            "send->{}: (PIPELINE) {}",
564            self.hostname,
565            all.as_bstr().escape_bytes()
566        );
567        if self.socket.is_some() {
568            if let Some(tracer) = &self.tracer {
569                // Send the lines individually to the tracer, so that we
570                // don't break --terse mode
571                for line in &lines {
572                    WriteTracer::trace(tracer, line);
573                }
574            }
575        }
576        self.write_all_with_timeout(
577            total_timeout,
578            &all,
579            || ClientError::TimeOutRequest {
580                duration: total_timeout,
581                commands: commands.to_vec(),
582            },
583            |error| ClientError::WriteError {
584                error,
585                commands: commands.to_vec(),
586            },
587        )
588        .await
589    }
590
591    async fn write_command_request(&mut self, command: &Command) -> Result<(), ClientError> {
592        let line = command.encode();
593        tracing::trace!("send->{}: {line}", self.hostname);
594        if self.socket.is_some() {
595            if let Some(tracer) = &self.tracer {
596                WriteTracer::trace(tracer, &line.to_string());
597            }
598        }
599
600        let timeout_duration = command.client_timeout_request(&self.timeouts);
601        self.write_all_with_timeout(
602            timeout_duration,
603            &line,
604            || ClientError::TimeOutRequest {
605                duration: timeout_duration,
606                commands: vec![command.clone()],
607            },
608            |error| ClientError::WriteError {
609                error,
610                commands: vec![command.clone()],
611            },
612        )
613        .await
614    }
615
616    async fn write_data_with_timeout(&mut self, data: &[u8]) -> Result<(), ClientError> {
617        if self.socket.is_some() {
618            if let Some(tracer) = &self.tracer {
619                BinWriteTracer::trace(tracer, data);
620            }
621        }
622        let timeout_duration = Command::Data.client_timeout_request(&self.timeouts);
623        self.write_all_with_timeout(
624            timeout_duration,
625            data,
626            || ClientError::TimeOutData,
627            |error| ClientError::WriteError {
628                error,
629                commands: vec![],
630            },
631        )
632        .await
633    }
634
635    /// Issue a series of commands, and return the responses to
636    /// those commands.
637    ///
638    /// If the server advertised the RFC 2920 PIPELINING extension,
639    /// the commands are written one after the other before waiting
640    /// to read any data, resulting in lower overall latency due
641    /// to round-trip-times.
642    ///
643    /// If PIPELINING is not available, each command is written
644    /// and the response read before attempting to write the next
645    /// command.
646    ///
647    /// The number of returned responses may be smaller than the
648    /// number of requested commands if there is an issue with
649    /// the network connection.
650    pub async fn pipeline_commands(
651        &mut self,
652        commands: Vec<Command>,
653    ) -> Vec<Result<Response, ClientError>> {
654        let mut results: Vec<Result<Response, ClientError>> = vec![];
655
656        let pipeline = self.enable_pipelining && self.capabilities.contains_key("PIPELINING");
657        if pipeline {
658            if let Err(err) = self.write_pipeline_request(&commands).await {
659                let err: ClientError = err;
660                results.push(Err(err.clone()));
661                while results.len() < commands.len() {
662                    // Synthesize failures for the remaining commands
663                    results.push(Err(err.clone()));
664                }
665                return results;
666            }
667
668            // Now read the responses effectively in a batch
669            for cmd in &commands {
670                results.push(
671                    self.read_response(Some(cmd), cmd.client_timeout(&self.timeouts))
672                        .await,
673                );
674            }
675            return results;
676        }
677
678        for cmd in &commands {
679            if let Err(err) = self.write_command_request(cmd).await {
680                let err: ClientError = err;
681                results.push(Err(err.clone()));
682                while results.len() < commands.len() {
683                    // Synthesize failures for the remaining commands
684                    results.push(Err(err.clone()));
685                }
686                return results;
687            }
688            // Immediately request the response if the server
689            // doesn't support pipelining
690            results.push(
691                self.read_response(Some(cmd), cmd.client_timeout(&self.timeouts))
692                    .await,
693            );
694        }
695        results
696    }
697
698    pub async fn ehlo_lhlo(
699        &mut self,
700        ehlo_name: &str,
701        use_lmtp: bool,
702    ) -> Result<&HashMap<String, EsmtpCapability>, ClientError> {
703        if use_lmtp {
704            self.lhlo(ehlo_name).await
705        } else {
706            self.ehlo(ehlo_name).await
707        }
708    }
709
710    pub async fn lhlo(
711        &mut self,
712        ehlo_name: &str,
713    ) -> Result<&HashMap<String, EsmtpCapability>, ClientError> {
714        let response = self
715            .send_command(&Command::Lhlo(Domain::DomainName(
716                ehlo_name
717                    .parse::<DomainString>()
718                    .map_err(|_| ClientError::InvalidDnsName(ehlo_name.to_string()))?,
719            )))
720            .await?;
721        self.ehlo_common(response)
722    }
723
724    pub async fn ehlo(
725        &mut self,
726        ehlo_name: &str,
727    ) -> Result<&HashMap<String, EsmtpCapability>, ClientError> {
728        let response = self
729            .send_command(&Command::Ehlo(Domain::DomainName(
730                ehlo_name
731                    .parse::<DomainString>()
732                    .map_err(|_| ClientError::InvalidDnsName(ehlo_name.to_string()))?,
733            )))
734            .await?;
735        self.ehlo_common(response)
736    }
737
738    fn ehlo_common(
739        &mut self,
740        response: Response,
741    ) -> Result<&HashMap<String, EsmtpCapability>, ClientError> {
742        if response.code != 250 {
743            return Err(ClientError::Rejected(response));
744        }
745
746        let mut capabilities = HashMap::new();
747
748        for line in response.content.lines().skip(1) {
749            let mut fields = line.splitn(2, ' ');
750            if let Some(name) = fields.next() {
751                let param = fields.next().map(|s| s.to_string());
752                let cap = EsmtpCapability {
753                    name: name.to_string(),
754                    param,
755                };
756                capabilities.insert(name.to_ascii_uppercase(), cap);
757            }
758        }
759
760        self.capabilities = capabilities;
761        Ok(&self.capabilities)
762    }
763
764    pub async fn auth_plain(
765        &mut self,
766        username: &str,
767        password: Option<&str>,
768    ) -> Result<(), ClientError> {
769        // RFC 4616 says that the format is:
770        // [authzid] NUL authcid NUL passwd
771        let password = password.unwrap_or("");
772        let payload = format!("\x00{username}\x00{password}");
773        let payload = data_encoding::BASE64.encode(payload.as_bytes());
774
775        let response = self
776            .send_command(&Command::Auth {
777                sasl_mech: "PLAIN".to_string(),
778                initial_response: Some(payload),
779            })
780            .await?;
781
782        if response.code != 235 {
783            return Err(ClientError::Rejected(response));
784        }
785
786        Ok(())
787    }
788
789    /// Send the STARTTLS command and, if the server accepts it, perform the TLS
790    /// handshake to upgrade the connection.
791    ///
792    /// Returns Err if the server rejects STARTTLS or a transport error occurs.
793    /// A failed handshake is instead reported as
794    /// `Ok(TlsStatus::FailedHandshake(_))` rather than Err. On success the
795    /// socket is upgraded to TLS and the client remains usable. On a failed
796    /// handshake the client is unusable. A new connection is required to send
797    /// further commands.
798    pub async fn starttls(&mut self, options: TlsOptions) -> Result<TlsStatus, ClientError> {
799        let resp = self.send_command(&Command::StartTls).await?;
800        if resp.code != 220 {
801            return Err(ClientError::Rejected(resp));
802        }
803
804        self.tls_handshake(options).await
805    }
806
807    /// Perform the TLS handshake directly on the current socket, without a
808    /// preceding STARTTLS negotiation. Used for implicit TLS (SMTPS), where
809    /// the session is encrypted from the first byte.
810    pub async fn tls_connect(&mut self, options: TlsOptions) -> Result<TlsStatus, ClientError> {
811        self.tls_handshake(options).await
812    }
813
814    async fn tls_handshake(&mut self, options: TlsOptions) -> Result<TlsStatus, ClientError> {
815        let mut handshake_error = None;
816        let mut tls_info = TlsInformation::default();
817
818        let stream: Option<BoxedAsyncReadAndWrite> = if options.prefer_openssl
819            || !options.dane_tlsa.is_empty()
820        {
821            let connector = options
822                .build_openssl_connector(&self.hostname)
823                .map_err(|error| ClientError::FailedToBuildConnector {
824                    error: error.to_string(),
825                })?;
826            let ssl = connector.into_ssl(self.hostname.as_str())?;
827
828            let stream = match self.socket.take() {
829                Some(s) => s,
830                None => return Err(ClientError::NotConnected),
831            };
832
833            let mut ssl_stream = tokio_openssl::SslStream::new(ssl, stream)?;
834
835            match timeout(
836                self.timeouts.starttls_timeout,
837                std::pin::Pin::new(&mut ssl_stream).connect(),
838            )
839            .await
840            {
841                Ok(Ok(())) => {}
842                Ok(Err(err)) => {
843                    handshake_error.replace(format!("{err:#}"));
844                }
845                Err(_elapsed) => {
846                    if let Some(tracer) = &self.tracer {
847                        tracer.trace_event(SmtpClientTraceEvent::Diagnostic {
848                            level: Level::ERROR,
849                            message: format!(
850                                "openssl handshake timed out after {:?}",
851                                self.timeouts.starttls_timeout
852                            ),
853                        });
854                        tracer.trace_event(SmtpClientTraceEvent::Closed);
855                    }
856                    return Err(ClientError::TimeOutResponse {
857                        command: Some(Command::StartTls),
858                        duration: self.timeouts.starttls_timeout,
859                    });
860                }
861            }
862
863            tls_info.provider_name = "openssl".to_string();
864            tls_info.cipher = match ssl_stream.ssl().current_cipher() {
865                Some(cipher) => cipher.standard_name().unwrap_or(cipher.name()).to_string(),
866                None => String::new(),
867            };
868            tls_info.protocol_version = ssl_stream.ssl().version_str().to_string();
869
870            if let Some(cert) = ssl_stream.ssl().peer_certificate() {
871                tls_info.subject_name = subject_name(&cert);
872            }
873            if let Ok(authority) = ssl_stream.ssl().dane_authority() {
874                if let Some(cert) = &authority.cert {
875                    tls_info.subject_name = subject_name(cert);
876                }
877            }
878
879            if handshake_error.is_some() {
880                None
881            } else {
882                Some(Box::new(ssl_stream) as BoxedAsyncReadAndWrite)
883            }
884        } else {
885            tls_info.provider_name = "rustls".to_string();
886            let connector = options.build_tls_connector().await.map_err(|error| {
887                ClientError::FailedToBuildConnector {
888                    error: error.to_string(),
889                }
890            })?;
891            let server_name = parse_server_name(self.hostname.as_str())?;
892
893            let socket = match self.socket.take() {
894                Some(s) => s,
895                None => return Err(ClientError::NotConnected),
896            };
897
898            let connect_future = connector.connect(server_name, socket);
899            match timeout(self.timeouts.starttls_timeout, connect_future).await {
900                Ok(Ok(stream)) => {
901                    let (_, conn) = stream.get_ref();
902                    tls_info.cipher = match conn.negotiated_cipher_suite() {
903                        Some(suite) => suite.suite().as_str().unwrap_or("UNKNOWN").to_string(),
904                        None => String::new(),
905                    };
906                    tls_info.protocol_version = match conn.protocol_version() {
907                        Some(version) => version.as_str().unwrap_or("UNKNOWN").to_string(),
908                        None => String::new(),
909                    };
910
911                    if let Some(certs) = conn.peer_certificates() {
912                        let peer_cert = &certs[0];
913                        if let Ok(cert) = X509::from_der(peer_cert.as_ref()) {
914                            tls_info.subject_name = subject_name(&cert);
915                        }
916                    }
917
918                    Some(Box::new(stream) as BoxedAsyncReadAndWrite)
919                }
920                Ok(Err(err)) => {
921                    handshake_error.replace(format!("{err:#}"));
922                    None
923                }
924                Err(_elapsed) => {
925                    if let Some(tracer) = &self.tracer {
926                        tracer.trace_event(SmtpClientTraceEvent::Diagnostic {
927                            level: Level::ERROR,
928                            message: format!(
929                                "rustls handshake timed out after {:?}",
930                                self.timeouts.starttls_timeout
931                            ),
932                        });
933                        tracer.trace_event(SmtpClientTraceEvent::Closed);
934                    }
935                    return Err(ClientError::TimeOutResponse {
936                        command: Some(Command::StartTls),
937                        duration: self.timeouts.starttls_timeout,
938                    });
939                }
940            }
941        };
942
943        // On a successful handshake the peer was authenticated iff verification
944        // was required: when `insecure` is set we accept the peer's certificate
945        // without validating it, so the session is encrypted but unauthenticated.
946        tls_info.authenticated = !options.insecure;
947
948        if let Some(tracer) = &self.tracer {
949            tracer.trace_event(SmtpClientTraceEvent::Diagnostic {
950                level: Level::INFO,
951                message: match &handshake_error {
952                    Some(error) => format!("TLS handshake failed: {error:?}"),
953                    None => format!("TLS handshake -> {tls_info:?}"),
954                },
955            });
956        }
957
958        if let Some(stream) = stream {
959            self.socket.replace(stream);
960        }
961        Ok(match handshake_error {
962            Some(error) => TlsStatus::FailedHandshake(error),
963            None => TlsStatus::Info(tls_info),
964        })
965    }
966
967    pub async fn send_mail<B: AsRef<[u8]>, SENDER: Into<ReversePath>, RECIP: Into<ForwardPath>>(
968        &mut self,
969        sender: SENDER,
970        recipient: RECIP,
971        data: B,
972    ) -> Result<Response, ClientError> {
973        let recipient: ForwardPath = recipient.into();
974        let status = self
975            .send_mail_multi_recip(sender, vec![recipient], data)
976            .await?;
977        Ok(status.response)
978    }
979
980    pub async fn send_mail_multi_recip<B: AsRef<[u8]>, SENDER: Into<ReversePath>>(
981        &mut self,
982        sender: SENDER,
983        recipient_list: Vec<ForwardPath>,
984        data: B,
985    ) -> Result<BatchSendSuccess, ClientError> {
986        let sender = sender.into();
987
988        let data: &[u8] = data.as_ref();
989        let stuffed;
990
991        let data = match apply_dot_stuffing(data) {
992            Some(d) => {
993                stuffed = d;
994                &stuffed
995            }
996            None => data,
997        };
998
999        let data_is_8bit = data.iter().any(|&b| b >= 0x80);
1000        let envelope_is_8bit =
1001            !sender.is_ascii() || recipient_list.iter().any(|recipient| !recipient.is_ascii());
1002
1003        let mut mail_from_params = vec![];
1004        if data_is_8bit {
1005            if self.capabilities.contains_key("8BITMIME") {
1006                mail_from_params.push(EsmtpParameter {
1007                    name: "BODY".to_string(),
1008                    value: Some("8BITMIME".to_string()),
1009                });
1010            } else if !self.ignore_8bit_checks {
1011                return Err(ClientError::Rejected(Response {
1012                    code: 554,
1013                    command: None,
1014                    enhanced_code: Some(EnhancedStatusCode {
1015                        class: 5,
1016                        subject: 6,
1017                        detail: 3,
1018                    }),
1019                    content: "KumoMTA internal: DATA is 8bit, destination does \
1020                        not support 8BITMIME. Conversion via msg:check_fix_conformance \
1021                        during reception is required"
1022                        .to_string(),
1023                }));
1024            }
1025        }
1026
1027        if envelope_is_8bit {
1028            if self.capabilities.contains_key("SMTPUTF8") {
1029                mail_from_params.push(EsmtpParameter {
1030                    name: "SMTPUTF8".to_string(),
1031                    value: None,
1032                });
1033            } else if !self.ignore_8bit_checks {
1034                return Err(ClientError::Rejected(Response {
1035                    code: 554,
1036                    command: None,
1037                    enhanced_code: Some(EnhancedStatusCode {
1038                        class: 5,
1039                        subject: 6,
1040                        detail: 7,
1041                    }),
1042                    content: "KumoMTA internal: envelope is 8bit, destination does \
1043                        not support SMTPUTF8."
1044                        .to_string(),
1045                }));
1046            }
1047        }
1048
1049        let mut commands = vec![];
1050
1051        // We want to avoid using RSET for the first message we send on
1052        // a given connection, because postfix can run in a mode where
1053        // it will not tolerate RSET because it considers it to be a "junk"
1054        // command, and rejecting junk commands will cut down on its load
1055        // when it is under stress; it is used as a load shedding approach.
1056        // If we always RSET then we will never deliver to a site that is
1057        // configured that way. If we take care to RSET only for subsequent
1058        // sends, then we should get one message per connection through
1059        // without being unfairly penalized for defensively RSETing.
1060        let used_rset = self.use_rset;
1061        if self.use_rset {
1062            commands.push(Command::Rset);
1063        }
1064        commands.push(Command::MailFrom {
1065            address: sender,
1066            parameters: mail_from_params,
1067        });
1068
1069        for recipient in &recipient_list {
1070            commands.push(Command::RcptTo {
1071                address: recipient.clone(),
1072                parameters: vec![],
1073            });
1074        }
1075        commands.push(Command::Data);
1076
1077        // Assume that something might break below: if it does, we want
1078        // to ensure that we RSET the connection on the next go around.
1079        self.use_rset = true;
1080
1081        let mut responses = self.pipeline_commands(commands).await;
1082
1083        // This is a little awkward. We want to handle the RFC 2090 3.1 case
1084        // below, which requires deferring checking the actual response codes
1085        // until later, but we must also handle the case where we had a hard
1086        // transport error partway through pipelining.
1087        // So we set a flag for that case and will then "eagerly", wrt. the
1088        // RFC 2090 3.1 logic, evaluate the SMTP response codes, so that we
1089        // can propagate the correct error disposition up to the caller.
1090        let is_err = responses.iter().any(|r| r.is_err());
1091
1092        if used_rset {
1093            let rset_resp = responses.remove(0)?;
1094            if rset_resp.code != 250 {
1095                return Err(ClientError::Rejected(rset_resp));
1096            }
1097        }
1098
1099        let mail_resp = responses.remove(0)?;
1100        if is_err && mail_resp.code != 250 {
1101            return Err(ClientError::Rejected(mail_resp));
1102        }
1103
1104        let mut rcpt_responses = vec![];
1105        for _ in &recipient_list {
1106            rcpt_responses.push(responses.remove(0)?);
1107        }
1108
1109        if is_err && rcpt_responses.iter().all(|resp| resp.code != 250) {
1110            return Err(ClientError::RejectedBatch(rcpt_responses));
1111        }
1112
1113        let data_resp = responses.remove(0)?;
1114        if is_err && data_resp.code != 354 {
1115            return Err(ClientError::Rejected(data_resp));
1116        }
1117
1118        if data_resp.code == 354
1119            && (mail_resp.code != 250 || rcpt_responses.iter().all(|resp| resp.code != 250))
1120        {
1121            // RFC 2920 3.1:
1122            // the client cannot assume that the DATA command will be rejected
1123            // just because none of the RCPT TO commands worked.  If the DATA
1124            // command was properly rejected the client SMTP can just issue
1125            // RSET, but if the DATA command was accepted the client SMTP
1126            // should send a single dot.
1127
1128            // Send dummy data
1129            self.write_data_with_timeout(b".\r\n").await?;
1130            let data_dot = Command::DataDot;
1131            // wait for its response
1132            let _ = self
1133                .read_response(Some(&data_dot), data_dot.client_timeout(&self.timeouts))
1134                .await?;
1135
1136            // Continue below: we will match one of the failure cases and
1137            // return a ClientError::Rejected from one of the earlier
1138            // commands
1139        }
1140
1141        if mail_resp.code != 250 {
1142            return Err(ClientError::Rejected(mail_resp));
1143        }
1144        if rcpt_responses.iter().all(|resp| resp.code != 250) {
1145            if rcpt_responses.len() == 1 {
1146                return Err(ClientError::Rejected(
1147                    rcpt_responses.pop().expect("have at least one"),
1148                ));
1149            }
1150            return Err(ClientError::RejectedBatch(rcpt_responses));
1151        }
1152        if data_resp.code != 354 {
1153            return Err(ClientError::Rejected(data_resp));
1154        }
1155
1156        let needs_newline = data.last().map(|&b| b != b'\n').unwrap_or(true);
1157
1158        tracing::trace!("message data is {} bytes", data.len());
1159
1160        self.write_data_with_timeout(data).await?;
1161
1162        let marker = if needs_newline { "\r\n.\r\n" } else { ".\r\n" };
1163
1164        tracing::trace!("send->{}: {}", self.hostname, marker.escape_debug());
1165
1166        self.write_data_with_timeout(marker.as_bytes()).await?;
1167
1168        let data_dot = Command::DataDot;
1169        let resp = self
1170            .read_response(Some(&data_dot), data_dot.client_timeout(&self.timeouts))
1171            .await?;
1172        if resp.code != 250 {
1173            return Err(ClientError::Rejected(resp));
1174        }
1175
1176        // If everything went well, respect the user preference for speculatively
1177        // issuing an RSET next time around
1178        self.use_rset = self.enable_rset;
1179
1180        Ok(BatchSendSuccess {
1181            response: resp,
1182            rcpt_responses,
1183        })
1184    }
1185}
1186
1187#[derive(Debug)]
1188pub struct BatchSendSuccess {
1189    pub response: Response,
1190    pub rcpt_responses: Vec<Response>,
1191}
1192
1193#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone)]
1194pub enum TlsStatus {
1195    FailedHandshake(String),
1196    Info(TlsInformation),
1197}
1198
1199#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize, Clone)]
1200pub struct TlsInformation {
1201    pub cipher: String,
1202    pub protocol_version: String,
1203    pub subject_name: Vec<String>,
1204    pub provider_name: String,
1205    /// Whether the peer certificate was authenticated (validated) as part of
1206    /// the handshake. False when the session is encrypted but the peer was not
1207    /// verified (e.g. opportunistic-insecure, or DANE with no usable TLSA
1208    /// records).
1209    pub authenticated: bool,
1210}
1211
1212impl Drop for SmtpClient {
1213    fn drop(&mut self) {
1214        if let Some(tracer) = &self.tracer {
1215            if self.socket.is_some() {
1216                tracer.trace_event(SmtpClientTraceEvent::Closed);
1217            }
1218        }
1219    }
1220}
1221fn parse_response_line(line: &'_ str) -> Result<ResponseLine<'_>, ClientError> {
1222    if line.len() < 4 {
1223        return Err(ClientError::MalformedResponseLine(line.to_string()));
1224    }
1225
1226    match line.as_bytes()[3] {
1227        b' ' | b'-' => match line[0..3].parse::<u16>() {
1228            Ok(code) => Ok(ResponseLine {
1229                code,
1230                is_final: line.as_bytes()[3] == b' ',
1231                content: &line[4..],
1232            }),
1233            Err(_) => Err(ClientError::MalformedResponseLine(line.to_string())),
1234        },
1235        _ => Err(ClientError::MalformedResponseLine(line.to_string())),
1236    }
1237}
1238
1239fn apply_dot_stuffing(data: &[u8]) -> Option<Vec<u8>> {
1240    static LFDOT: LazyLock<Finder> = LazyLock::new(|| memchr::memmem::Finder::new("\n."));
1241
1242    if !data.starts_with(b".") && LFDOT.find(data).is_none() {
1243        return None;
1244    }
1245
1246    let mut stuffed = vec![];
1247    if data.starts_with(b".") {
1248        stuffed.push(b'.');
1249    }
1250    let mut last_idx = 0;
1251    for i in LFDOT.find_iter(data) {
1252        stuffed.extend_from_slice(&data[last_idx..=i]);
1253        stuffed.push(b'.');
1254        last_idx = i + 1;
1255    }
1256    stuffed.extend_from_slice(&data[last_idx..]);
1257    Some(stuffed)
1258}
1259
1260/// Extracts the object=name pairs of the subject name from a cert.
1261/// eg:
1262/// ```text
1263/// ["C=US", "ST=CA", "L=SanFrancisco", "O=Fort-Funston", "OU=MyOrganizationalUnit",
1264/// "CN=do.havedane.net", "name=EasyRSA", "emailAddress=me@myhost.mydomain"]
1265/// ```
1266pub fn subject_name(cert: &X509Ref) -> Vec<String> {
1267    let mut subject_name = vec![];
1268    for entry in cert.subject_name().entries() {
1269        if let Ok(obj) = entry.object().nid().short_name() {
1270            if let Ok(name) = entry.data().as_utf8() {
1271                subject_name.push(format!("{obj}={name}"));
1272            }
1273        }
1274    }
1275    subject_name
1276}
1277
1278fn parse_server_name(input: &str) -> Result<ServerName<'static>, ClientError> {
1279    match IpAddr::from_str(input) {
1280        Ok(ip) => Ok(ServerName::IpAddress(ip.into())),
1281        Err(_) => {
1282            let name = Name::from_str_relaxed(input)
1283                .map_err(|_| ClientError::InvalidDnsName(input.to_string()))?;
1284            ServerName::try_from(name.to_ascii())
1285                .map_err(|_| ClientError::InvalidDnsName(name.to_ascii()))
1286        }
1287    }
1288}
1289
1290#[cfg(test)]
1291mod test {
1292    use super::*;
1293    use crate::parser::{EnvelopeAddress, ReversePath};
1294
1295    #[test]
1296    fn test_stuffing() {
1297        assert_eq!(apply_dot_stuffing(b"foo"), None);
1298        assert_eq!(apply_dot_stuffing(b".foo").unwrap(), b"..foo");
1299        assert_eq!(apply_dot_stuffing(b"foo\n.bar").unwrap(), b"foo\n..bar");
1300        assert_eq!(
1301            apply_dot_stuffing(b"foo\n.bar\n..baz\n").unwrap(),
1302            b"foo\n..bar\n...baz\n"
1303        );
1304    }
1305
1306    /*
1307    #[tokio::test]
1308    async fn test_against_sink() {
1309        use tokio::net::TcpStream;
1310        let stream = TcpStream::connect("127.0.0.1:2025").await.unwrap();
1311        let mut client =
1312            SmtpClient::with_stream(stream, "localhost", SmtpClientTimeouts::default());
1313        dbg!(client.read_response(None).await).unwrap();
1314        dbg!(client.ehlo("localhost").await).unwrap();
1315        let insecure = true;
1316        dbg!(client.starttls(insecure).await).unwrap();
1317        let resp = client
1318            .send_mail(
1319                ReversePath::try_from("wez@mail.example.com").unwrap(),
1320                ForwardPath::try_from("wez@mail.example.com").unwrap(),
1321                "Subject: hello\r\n\r\nwoot\r\n",
1322            )
1323            .await
1324            .unwrap();
1325        panic!("{resp:#?}");
1326    }
1327    */
1328
1329    #[test]
1330    fn response_line_parsing() {
1331        assert_eq!(
1332            parse_response_line("220 woot").unwrap(),
1333            ResponseLine {
1334                code: 220,
1335                is_final: true,
1336                content: "woot"
1337            }
1338        );
1339        assert_eq!(
1340            parse_response_line("220-woot").unwrap(),
1341            ResponseLine {
1342                code: 220,
1343                is_final: false,
1344                content: "woot"
1345            }
1346        );
1347
1348        assert!(matches!(
1349            parse_response_line("220_woot"),
1350            Err(ClientError::MalformedResponseLine(_))
1351        ));
1352        assert!(matches!(
1353            parse_response_line("not really"),
1354            Err(ClientError::MalformedResponseLine(_))
1355        ));
1356    }
1357
1358    fn parse_multi_line(lines: &[&str]) -> Result<Response, ClientError> {
1359        let mut parsed = parse_response_line(lines[0])?;
1360        let mut b = ResponseBuilder::new(&parsed);
1361        for line in &lines[1..] {
1362            parsed = parse_response_line(line)?;
1363            b.add_line(&parsed)
1364                .map_err(ClientError::MalformedResponseLine)?;
1365        }
1366        assert!(parsed.is_final);
1367        Ok(b.build(None))
1368    }
1369
1370    #[test]
1371    fn multi_line_response() {
1372        assert_eq!(
1373            parse_multi_line(&["220-woot", "220-more", "220 done",]).unwrap(),
1374            Response {
1375                code: 220,
1376                enhanced_code: None,
1377                content: "woot\nmore\ndone".to_string(),
1378                command: None
1379            }
1380        );
1381
1382        let res = parse_multi_line(&["220-woot", "221-more", "220 done"]).unwrap_err();
1383        assert!(
1384            matches!(
1385                    res,
1386                ClientError::MalformedResponseLine(ref err) if err == "221-more"
1387            ),
1388            "got error {res:?}"
1389        );
1390
1391        let res = parse_multi_line(&["220-woot", "220-more", "221 done"]).unwrap_err();
1392        assert!(
1393            matches!(
1394                    res,
1395                ClientError::MalformedResponseLine(ref err) if err == "221 done"
1396            ),
1397            "got error {res:?}"
1398        );
1399
1400        assert_eq!(
1401            parse_multi_line(&["220-4.1.0 woot", "220-more", "220 done",]).unwrap(),
1402            Response {
1403                code: 220,
1404                enhanced_code: Some(EnhancedStatusCode {
1405                    class: 4,
1406                    subject: 1,
1407                    detail: 0
1408                }),
1409                content: "woot\nmore\ndone".to_string(),
1410                command: None
1411            }
1412        );
1413
1414        // Confirm that we strip the enhanced status code from each line
1415        assert_eq!(
1416            parse_multi_line(&["220-4.1.0 woot", "220-4.1.0 more", "220 done",]).unwrap(),
1417            Response {
1418                code: 220,
1419                enhanced_code: Some(EnhancedStatusCode {
1420                    class: 4,
1421                    subject: 1,
1422                    detail: 0
1423                }),
1424                content: "woot\nmore\ndone".to_string(),
1425                command: None
1426            }
1427        );
1428
1429        // ... but only if the code matches that of the first line
1430        assert_eq!(
1431            parse_multi_line(&["220-4.1.0 woot", "220-4.1.0 more", "220 5.5.5 done",]).unwrap(),
1432            Response {
1433                code: 220,
1434                enhanced_code: Some(EnhancedStatusCode {
1435                    class: 4,
1436                    subject: 1,
1437                    detail: 0
1438                }),
1439                content: "woot\nmore\n5.5.5 done".to_string(),
1440                command: None
1441            }
1442        );
1443    }
1444
1445    #[test]
1446    fn test_extract_hostname() {
1447        assert_eq!(extract_hostname("foo"), "foo");
1448        assert_eq!(extract_hostname("foo."), "foo");
1449        assert_eq!(extract_hostname("foo:25"), "foo");
1450        assert_eq!(extract_hostname("foo.:25"), "foo");
1451        assert_eq!(extract_hostname("[foo]:25"), "foo");
1452        assert_eq!(extract_hostname("[foo.]:25"), "foo");
1453        assert_eq!(extract_hostname("[::1]:25"), "::1");
1454        assert_eq!(extract_hostname("::1:25"), "::1");
1455    }
1456
1457    #[test]
1458    fn test_format_error_command() {
1459        assert_eq!(
1460            format!(
1461                "{:#}",
1462                ClientError::TimeOutRequest {
1463                    commands: vec![Command::DataDot],
1464                    duration: Duration::from_secs(10),
1465                }
1466            ),
1467            "Timed Out after 10s writing cmd=."
1468        );
1469        assert_eq!(
1470            format!(
1471                "{:#}",
1472                ClientError::TimeOutResponse {
1473                    command: Some(Command::MailFrom {
1474                        address: {
1475                            let EnvelopeAddress::Path(p) =
1476                                EnvelopeAddress::parse("user@host").unwrap()
1477                            else {
1478                                panic!("expected Path")
1479                            };
1480                            ReversePath::Path(p)
1481                        },
1482                        parameters: vec![],
1483                    }),
1484                    duration: Duration::from_secs(10),
1485                }
1486            ),
1487            r#"Timed Out waiting 10s for response to cmd=MAIL FROM:<user@host>"#
1488        );
1489    }
1490
1491    #[test]
1492    fn test_issue_533() {
1493        let _name = parse_server_name("münchen.de").unwrap();
1494    }
1495}