use std::string::String;
use std::error::FromError;
use std::io::net::tcp::TcpStream;
use std::io::net::ip::{SocketAddr, ToSocketAddr};
use tools::get_first_word;
use common::{CRLF, MESSAGE_ENDING};
use response::Response;
use extension::Extension;
use command::Command;
use transaction::TransactionState;
use error::{SmtpResult, ErrorKind};
use client::connecter::Connecter;
use client::server_info::ServerInfo;
use client::stream::ClientStream;
use email::Email;
pub mod server_info;
pub mod connecter;
pub mod stream;
pub struct Client<S = TcpStream> {
stream: Option<S>,
server_addr: SocketAddr,
my_hostname: String,
server_info: Option<ServerInfo>,
state: TransactionState,
}
macro_rules! try_smtp (
($err: expr $client: ident) => ({
match $err {
Ok(val) => val,
Err(err) => fail_with_err!(err $client),
}
})
)
macro_rules! fail_with_err (
($err: expr $client: ident) => ({
$client.close_on_error();
return Err(FromError::from_error($err))
})
)
macro_rules! check_command_sequence (
($command: ident $client: ident) => ({
if !$client.state.is_allowed(&$command) {
fail_with_err!(
Response{code: 503, message: Some("Bad sequence of commands".to_string())} $client
);
}
})
)
impl<S = TcpStream> Client<S> {
pub fn new<A: ToSocketAddr>(addr: A, my_hostname: Option<&str>) -> Client<S> {
Client{
stream: None,
server_addr: addr.to_socket_addr().unwrap(),
my_hostname: my_hostname.unwrap_or("localhost").to_string(),
server_info: None,
state: TransactionState::new(),
}
}
pub fn localhost() -> Client<S> {
Client::new("localhost", Some("localhost"))
}
}
impl<S: Connecter + ClientStream + Clone = TcpStream> Client<S> {
pub fn send_email(&mut self, email: Email) -> SmtpResult {
self.send_mail(
email.get_from(),
email.get_to(),
email.to_string().as_slice(),
)
}
fn close_on_error(&mut self) {
if self.is_connected() {
let _ = self.quit();
}
self.close();
}
pub fn send_mail(&mut self, from_address: String,
to_addresses: Vec<String>, message: &str) -> SmtpResult {
try!(self.connect());
if let Err(error) = self.ehlo() {
match error.kind {
ErrorKind::PermanentError(Response{code: 550, message: _}) => {
try_smtp!(self.helo() self);
},
_ => {
try_smtp!(Err(error) self)
},
};
}
debug!("server {}", self.server_info.as_ref().unwrap());
try_smtp!(self.mail(from_address.as_slice()) self);
info!("from=<{}>, size={}, nrcpt={}", from_address, message.len(), to_addresses.len());
for to_address in to_addresses.iter() {
try_smtp!(self.rcpt(to_address.as_slice()) self);
}
try_smtp!(self.data() self);
let sent = try_smtp!(self.message(message) self);
info!("to=<{}>, status=sent ({})",
to_addresses.connect(">, to=<"), sent);
try_smtp!(self.quit() self);
return Ok(sent);
}
pub fn connect(&mut self) -> SmtpResult {
let command = Command::Connect;
check_command_sequence!(command self);
if !self.stream.is_none() {
fail_with_err!("The connection is already established" self);
}
self.stream = Some(try!(Connecter::connect(self.server_addr)));
info!("connection established to {}",
self.stream.as_mut().unwrap().peer_name().unwrap());
let result = try!(self.stream.as_mut().unwrap().get_reply());
let checked_result = try!(command.test_success(result));
self.state = self.state.next_state(&command).unwrap();
Ok(checked_result)
}
pub fn send_command(&mut self, command: Command) -> SmtpResult {
if !command.is_ascii() {
fail_with_err!("Non-ASCII string" self);
}
self.send_server(command, None)
}
fn send_message(&mut self, message: &str) -> SmtpResult {
self.send_server(Command::Message, Some(message))
}
fn send_server(&mut self, command: Command, message: Option<&str>) -> SmtpResult {
check_command_sequence!(command self);
let result = try!(match message {
Some(message) => self.stream.as_mut().unwrap().send_and_get_response(
message, MESSAGE_ENDING
),
None => self.stream.as_mut().unwrap().send_and_get_response(
command.to_string().as_slice(), CRLF
),
});
let checked_result = try!(command.test_success(result));
self.state = self.state.next_state(&command).unwrap();
Ok(checked_result)
}
pub fn is_connected(&mut self) -> bool {
self.noop().is_ok()
}
pub fn close(&mut self) {
drop(self.stream.as_mut().unwrap());
self.stream = None;
self.state = TransactionState::new();
self.server_info = None;
}
pub fn helo(&mut self) -> SmtpResult {
let hostname = self.my_hostname.clone();
let result = try!(self.send_command(Command::Hello(hostname)));
self.server_info = Some(
ServerInfo{
name: get_first_word(result.message.as_ref().unwrap().as_slice()).to_string(),
esmtp_features: None,
}
);
Ok(result)
}
pub fn ehlo(&mut self) -> SmtpResult {
let hostname = self.my_hostname.clone();
let result = try!(self.send_command(Command::ExtendedHello(hostname)));
self.server_info = Some(
ServerInfo{
name: get_first_word(result.message.as_ref().unwrap().as_slice()).to_string(),
esmtp_features: Extension::parse_esmtp_response(
result.message.as_ref().unwrap().as_slice()
),
}
);
Ok(result)
}
pub fn mail(&mut self, from_address: &str) -> SmtpResult {
let server_info = match self.server_info.clone() {
Some(info) => info,
None => fail_with_err!(Response{
code: 503,
message: Some("Bad sequence of commands".to_string()),
} self),
};
let options = match server_info.supports_feature(Extension::EightBitMime) {
Some(extension) => Some(vec![extension.client_mail_option().unwrap().to_string()]),
None => None,
};
self.send_command(
Command::Mail(from_address.to_string(), options)
)
}
pub fn rcpt(&mut self, to_address: &str) -> SmtpResult {
self.send_command(
Command::Recipient(to_address.to_string(), None)
)
}
pub fn data(&mut self) -> SmtpResult {
self.send_command(Command::Data)
}
pub fn message(&mut self, message_content: &str) -> SmtpResult {
let server_info = match self.server_info.clone() {
Some(info) => info,
None => fail_with_err!(Response{
code: 503,
message: Some("Bad sequence of commands".to_string()),
} self)
};
if !server_info.supports_feature(Extension::EightBitMime).is_some() {
if !message_content.is_ascii() {
fail_with_err!("Server does not accepts UTF-8 strings" self);
}
}
if let Some(Extension::Size(max)) = server_info.supports_feature(Extension::Size(0)) {
if message_content.len() > max {
fail_with_err!(Response{
code: 552,
message: Some("Message exceeds fixed maximum message size".to_string()),
} self);
}
}
self.send_message(message_content)
}
pub fn quit(&mut self) -> SmtpResult {
self.send_command(Command::Quit)
}
pub fn rset(&mut self) -> SmtpResult {
self.send_command(Command::Reset)
}
pub fn noop(&mut self) -> SmtpResult {
self.send_command(Command::Noop)
}
pub fn vrfy(&mut self, to_address: &str) -> SmtpResult {
self.send_command(Command::Verify(to_address.to_string()))
}
pub fn expn(&mut self, list: &str) -> SmtpResult {
self.send_command(Command::Expand(list.to_string()))
}
}