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
use crate::smtp::error::Error;
use crate::smtp::extension::{ClientId, Extension, MailBodyParameter, MailParameter, ServerInfo};
use crate::smtp::net::{ConnectionConfiguration, Connector};
use crate::smtp::smtp_client::ClientSecurity;
use crate::smtp::stream::SmtpDataStream;
use crate::smtp::util::SmtpProto;
use crate::{smtp::commands::*, SyncFuture};
use crate::{Envelope, Transport};
use async_std::io::{Read, Write};
use pin_project::pin_project;
use potential::{Lease, Potential};
use samotop_core::io::tls::MayBeTls;
use std::time::Duration;
use std::{fmt, pin::Pin};

/// Structure that implements the high level SMTP client
#[pin_project]
pub struct SmtpTransport<Conf, Conn: Connector> {
    connector: Conn,
    configuration: Conf,
    /// inner state leased to produced futures
    inner: Potential<SmtpConnection<Conn::Stream>>,
}

impl<Conf, Conn: Connector> SmtpTransport<Conf, Conn>
where
    Conf: ConnectionConfiguration,
{
    pub fn new(configuration: Conf, connector: Conn) -> Self {
        SmtpTransport {
            inner: Potential::empty(),
            connector,
            configuration,
        }
    }

    async fn connect(
        configuration: &Conf,
        connector: &Conn,
    ) -> Result<SmtpConnection<Conn::Stream>, Error> {
        let mut stream = connector.connect(configuration).await?;
        let server_info = Self::setup(&configuration, &mut stream).await?;
        let reuse = configuration.max_reuse_count().saturating_add(1);
        Ok(SmtpConnection {
            stream,
            reuse,
            server_info,
        })
    }
    async fn setup(configuration: &Conf, stream: &mut Conn::Stream) -> Result<ServerInfo, Error> {
        let timeout = configuration.timeout();
        let address = configuration.address();
        let my_id = configuration.hello_name();
        let security = configuration.security();
        let lmtp = configuration.lmtp();

        let mut client = SmtpProto::new(Pin::new(stream));
        let banner = client.read_banner(timeout).await?;

        // Log the connection
        debug!(
            "connection established to {}. Saying: {}",
            address, banner.code
        );

        async fn say_helo<S: Read + Write>(
            lmtp: bool,
            c: &mut SmtpProto<'_, S>,
            me: ClientId,
            timeout: Duration,
        ) -> Result<ServerInfo, Error> {
            let res = match lmtp {
                false => c.execute_ehlo_or_helo(me, timeout).await?,
                true => c.execute_lhlo(me, timeout).await?,
            };
            Ok(res.1)
        }

        let mut server_info = say_helo(lmtp, &mut client, my_id.clone(), timeout).await?;

        if !client.stream().is_encrypted() {
            let can_encrypt =
                server_info.supports_feature(Extension::StartTls) && client.stream().can_encrypt();

            let encrypt = match security {
                ClientSecurity::Required => true,
                ClientSecurity::Opportunistic => can_encrypt,
                ClientSecurity::Wrapper | ClientSecurity::None => false,
            };
            if encrypt {
                client.execute_starttls(timeout).await?;
                client.stream_mut().encrypt();
                server_info = say_helo(lmtp, &mut client, my_id, timeout).await?;
            }
        }

        Self::try_login(configuration, stream, &server_info, timeout).await?;

        Ok(server_info)
    }
    async fn try_login(
        configuration: &Conf,
        stream: &mut Conn::Stream,
        server_info: &ServerInfo,
        timeout: Duration,
    ) -> Result<(), Error> {
        if let Some(auth) = configuration.get_authentication(&server_info, stream.is_encrypted()) {
            let mut client = SmtpProto::new(Pin::new(stream));
            client.authenticate(auth, timeout).await?;
        } else {
            info!("No authentication mechanisms are available");
        }

        Ok(())
    }
    async fn prepare_mail(
        _configuration: &Conf,
        lease: &mut Lease<SmtpConnection<Conn::Stream>>,
        envelope: Envelope,
        timeout: Duration,
    ) -> Result<(), Error> {
        // Mail
        let mut mail_options = vec![];

        if lease.server_info.supports_feature(Extension::EightBitMime) {
            // FIXME: this needs to be gracefully degraded to 7bit if not available
            mail_options.push(MailParameter::Body(MailBodyParameter::EightBitMime));
        }

        if lease.server_info.supports_feature(Extension::SmtpUtfEight) {
            // FIXME: this needs to be gracefully degraded to 7bit if not available
            mail_options.push(MailParameter::SmtpUtfEight);
        }

        let mut client = SmtpProto::new(Pin::new(&mut lease.stream));

        // MAIL FROM:<reverse-path>
        client
            .execute_command(
                MailCommand::new(envelope.from().cloned(), mail_options),
                [250],
                timeout,
            )
            .await?;

        // RCPT TO:<forward-path>
        for to_address in envelope.to() {
            client
                .execute_command(RcptCommand::new(to_address.clone(), vec![]), [2], timeout)
                .await?;
            // Log the rcpt command
            debug!("{}: to=<{}>", envelope.message_id(), to_address);
        }

        // DATA
        client.execute_command(DataCommand, [354], timeout).await?;

        // Ready to stream data - responsibility of the outer
        Ok(())
    }
}

impl<Conf: ConnectionConfiguration, Conn: Connector> Transport for SmtpTransport<Conf, Conn> {
    type DataStream = SmtpDataStream<Conn::Stream>;

    fn send_stream<'s, 'a>(
        &'s self,
        envelope: Envelope,
    ) -> SyncFuture<'a, Result<Self::DataStream, Error>>
    where
        's: 'a,
    {
        Box::pin(async move {
            let mut lease = match self.inner.lease().await {
                Ok(lease) => lease,
                Err(gone) => gone.set(Self::connect(&self.configuration, &self.connector).await?),
            };
            let timeout = self.configuration.timeout();

            lease.reuse = lease.reuse.saturating_sub(1);
            let message_id = envelope.message_id().to_owned();
            let rcpts = envelope.to().len().min(u16::MAX as usize) as u16;
            // prepare a mail
            if let Err(e) =
                Self::prepare_mail(&self.configuration, &mut lease, envelope, timeout).await
            {
                // the connection is broken. Fail now, next call shall establish a new one.
                lease.steal();
                return Err(e);
            }
            // Return a data stream carying the lease away
            Ok(SmtpDataStream::new(
                lease,
                message_id,
                timeout,
                self.configuration.lmtp(),
                rcpts,
            ))
        })
    }
}
#[derive(Debug)]
pub(crate) struct SmtpConnection<S> {
    pub stream: S,
    /// How many times can the stream be used
    pub reuse: u16,
    /// Information about the server
    /// Value is None before HELO/EHLO
    pub server_info: ServerInfo,
}

impl<Conf: ConnectionConfiguration, Conn: Connector> fmt::Debug for SmtpTransport<Conf, Conn> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        //TODO: better debug
        f.debug_struct("SmtpTransport").finish()
    }
}