use std::string::String;
use std::error::FromError;
use std::io::net::ip::SocketAddr;
use std::io::net::ip::ToSocketAddr;
use tools::{get_first_word, unquote_email_address};
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;
pub mod server_info;
pub mod connecter;
pub mod stream;
pub struct Client<S> {
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::<S>();
return Err(FromError::from_error($err))
})
)
macro_rules! check_command_sequence (
($command: ident $client: ident) => ({
if !$client.state.is_command_allowed(&$command) {
fail_with_err!(
Response{code: 503, message: Some("Bad sequence of commands".to_string())} $client
);
}
})
)
impl<S> 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(),
}
}
}
impl<S: Connecter + ClientStream + Clone> Client<S> {
fn close_on_error<S>(&mut self) {
if self.is_connected::<S>() {
let _ = self.quit::<S>();
}
self.close();
}
pub fn send_mail<S>(&mut self, from_address: &str,
to_addresses: &[&str], message: &str) -> SmtpResult {
try!(self.connect());
match self.ehlo::<S>() {
Err(error) => match error.kind {
ErrorKind::PermanentError(Response{code: 550, message: _}) => {
try_smtp!(self.helo::<S>() self);
},
_ => {
try_smtp!(Err(error) self)
},
},
_ => {},
}
debug!("server {}", self.server_info.as_ref().unwrap());
try_smtp!(self.mail::<S>(from_address) self);
info!("from=<{}>, size={}, nrcpt={}", from_address, message.len(), to_addresses.len());
for to_address in to_addresses.iter() {
try_smtp!(self.rcpt::<S>(*to_address) self);
}
try_smtp!(self.data::<S>() self);
let sent = try_smtp!(self.message::<S>(message) self);
info!("to=<{}>, status=sent ({})",
to_addresses.connect(">, to=<"), sent);
try_smtp!(self.quit::<S>() 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<S>(&mut self) -> bool {
self.noop::<S>().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<S>(&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<S>(&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<S>(&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(unquote_email_address(from_address).to_string(), options)
)
}
pub fn rcpt<S>(&mut self, to_address: &str) -> SmtpResult {
self.send_command(
Command::Recipient(unquote_email_address(to_address).to_string(), None)
)
}
pub fn data<S>(&mut self) -> SmtpResult {
self.send_command(Command::Data)
}
pub fn message<S>(&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);
}
}
match server_info.supports_feature(Extension::Size(0)) {
Some(Extension::Size(max)) 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<S>(&mut self) -> SmtpResult {
self.send_command(Command::Quit)
}
pub fn rset<S>(&mut self) -> SmtpResult {
self.send_command(Command::Reset)
}
pub fn noop<S>(&mut self) -> SmtpResult {
self.send_command(Command::Noop)
}
pub fn vrfy<S>(&mut self, to_address: &str) -> SmtpResult {
self.send_command(Command::Verify(to_address.to_string()))
}
pub fn expn<S>(&mut self, list: &str) -> SmtpResult {
self.send_command(Command::Expand(list.to_string()))
}
}