Implement imap-flow #34

Merged
quentin merged 18 commits from refactor/imap-flow into main 2024-01-02 22:44:29 +00:00
5 changed files with 390 additions and 158 deletions
Showing only changes of commit e2d77defc8 - Show all commits

View file

@ -1,9 +1,11 @@
use anyhow::{Error, Result}; use anyhow::Result;
use imap_codec::imap_types::command::{Command, CommandBody}; use imap_codec::imap_types::command::{Command, CommandBody};
use imap_codec::imap_types::core::AString; use imap_codec::imap_types::core::{AString, NonEmptyVec};
use imap_codec::imap_types::response::{Capability, Data, Status, CommandContinuationRequest}; use imap_codec::imap_types::response::{Capability, Data};
use imap_codec::imap_types::secret::Secret;
use crate::imap::flow; use crate::imap::flow;
use crate::imap::response::Response;
use crate::login::ArcLoginProvider; use crate::login::ArcLoginProvider;
use crate::mail::user::User; use crate::mail::user::User;
@ -11,18 +13,30 @@ use crate::mail::user::User;
pub struct AnonymousContext<'a> { pub struct AnonymousContext<'a> {
pub req: &'a Command<'static>, pub req: &'a Command<'static>,
pub login_provider: Option<&'a ArcLoginProvider>, pub login_provider: &'a ArcLoginProvider,
} }
pub async fn dispatch(ctx: AnonymousContext<'_>) -> Result<(Status, flow::Transition)> { pub async fn dispatch(ctx: AnonymousContext<'_>) -> Result<(Response, flow::Transition)> {
match &ctx.req.body { match &ctx.req.body {
CommandBody::Noop => Ok((Response::ok("Noop completed.")?, flow::Transition::None)), CommandBody::Noop => Ok((
Response::ok()
.to_req(ctx.req)
.message("Noop completed.")
.build()?,
flow::Transition::None,
)),
CommandBody::Capability => ctx.capability().await, CommandBody::Capability => ctx.capability().await,
CommandBody::Logout => ctx.logout().await, CommandBody::Logout => ctx.logout().await,
CommandBody::Login { username, password } => ctx.login(username, password).await, CommandBody::Login { username, password } => ctx.login(username, password).await,
cmd => { cmd => {
tracing::warn!("Unknown command {:?}", cmd); tracing::warn!("Unknown command for the anonymous state {:?}", cmd);
Ok((Response::no("Command unavailable")?, flow::Transition::None)) Ok((
Response::bad()
.to_req(ctx.req)
.message("Command unavailable")
.build()?,
flow::Transition::None,
))
} }
} }
} }
@ -30,49 +44,50 @@ pub async fn dispatch(ctx: AnonymousContext<'_>) -> Result<(Status, flow::Transi
//--- Command controllers, private //--- Command controllers, private
impl<'a> AnonymousContext<'a> { impl<'a> AnonymousContext<'a> {
async fn capability(self) -> Result<(Status, flow::Transition)> { async fn capability(self) -> Result<(Response, flow::Transition)> {
let capabilities = vec![Capability::Imap4Rev1, Capability::Idle]; let capabilities: NonEmptyVec<Capability> =
let res = Response::ok("Server capabilities")?.with_body(Data::Capability(capabilities)); (vec![Capability::Imap4Rev1, Capability::Idle]).try_into()?;
let res = Response::ok()
.to_req(self.req)
.message("Server capabilities")
.data(Data::Capability(capabilities))
.build()?;
Ok((res, flow::Transition::None)) Ok((res, flow::Transition::None))
} }
async fn login( async fn login(
self, self,
username: &AString, username: &AString<'a>,
password: &AString, password: &Secret<AString<'a>>,
) -> Result<(Status, flow::Transition)> { ) -> Result<(Response, flow::Transition)> {
let (u, p) = ( let (u, p) = (
String::try_from(username.clone())?, std::str::from_utf8(username.as_ref())?,
String::try_from(password.clone())?, std::str::from_utf8(password.declassify().as_ref())?,
); );
tracing::info!(user = %u, "command.login"); tracing::info!(user = %u, "command.login");
let login_provider = match &self.login_provider { let creds = match self.login_provider.login(&u, &p).await {
Some(lp) => lp,
None => {
return Ok((
Response::no("Login command not available (already logged in)")?,
flow::Transition::None,
))
}
};
let creds = match login_provider.login(&u, &p).await {
Err(e) => { Err(e) => {
tracing::debug!(error=%e, "authentication failed"); tracing::debug!(error=%e, "authentication failed");
return Ok(( return Ok((
Response::no("Authentication failed")?, Response::no()
.to_req(self.req)
.message("Authentication failed")
.build()?,
flow::Transition::None, flow::Transition::None,
)); ));
} }
Ok(c) => c, Ok(c) => c,
}; };
let user = User::new(u.clone(), creds).await?; let user = User::new(u.to_string(), creds).await?;
tracing::info!(username=%u, "connected"); tracing::info!(username=%u, "connected");
Ok(( Ok((
Response::ok("Completed")?, Response::ok()
.to_req(self.req)
.message("Completed")
.build()?,
flow::Transition::Authenticate(user), flow::Transition::Authenticate(user),
)) ))
} }
@ -80,15 +95,9 @@ impl<'a> AnonymousContext<'a> {
// C: 10 logout // C: 10 logout
// S: * BYE Logging out // S: * BYE Logging out
// S: 10 OK Logout completed. // S: 10 OK Logout completed.
async fn logout(self) -> Result<(Status, flow::Transition)> { async fn logout(self) -> Result<(Response, flow::Transition)> {
// @FIXME we should implement From<Vec<Status>> and From<Vec<ImapStatus>> in // @FIXME we should implement From<Vec<Status>> and From<Vec<ImapStatus>> in
// boitalettres/src/proto/res/body.rs // boitalettres/src/proto/res/body.rs
Ok(( Ok((Response::bye()?, flow::Transition::Logout))
Response::ok("Logout completed")?.with_body(vec![Body::Status(
Status::bye(None, "Logging out")
.map_err(|e| Error::msg(e).context("Unable to generate IMAP status"))?,
)]),
flow::Transition::Logout,
))
} }
} }

View file

@ -2,37 +2,35 @@ use std::collections::BTreeMap;
use std::sync::Arc; use std::sync::Arc;
use anyhow::{anyhow, bail, Result}; use anyhow::{anyhow, bail, Result};
use boitalettres::proto::res::body::Data as Body; use imap_codec::imap_types::command::{Command, CommandBody};
use boitalettres::proto::{Request, Response}; use imap_codec::imap_types::core::{Atom, Literal, QuotedChar};
use imap_codec::imap_types::command::{CommandBody, StatusAttribute}; use imap_codec::imap_types::datetime::DateTime;
use imap_codec::imap_types::core::NonZeroBytes;
use imap_codec::imap_types::datetime::MyDateTime;
use imap_codec::imap_types::flag::{Flag, FlagNameAttribute}; use imap_codec::imap_types::flag::{Flag, FlagNameAttribute};
use imap_codec::imap_types::mailbox::{ListMailbox, Mailbox as MailboxCodec}; use imap_codec::imap_types::mailbox::{ListMailbox, Mailbox as MailboxCodec};
use imap_codec::imap_types::response::{Code, Data, StatusAttributeValue}; use imap_codec::imap_types::response::{Code, CodeOther, Data};
use imap_codec::imap_types::status::{StatusDataItem, StatusDataItemName};
use crate::imap::command::anonymous;
use crate::imap::flow; use crate::imap::flow;
use crate::imap::mailbox_view::MailboxView; use crate::imap::mailbox_view::MailboxView;
use crate::imap::response::Response;
use crate::mail::mailbox::Mailbox; use crate::mail::mailbox::Mailbox;
use crate::mail::uidindex::*; use crate::mail::uidindex::*;
use crate::mail::user::{User, INBOX, MAILBOX_HIERARCHY_DELIMITER}; use crate::mail::user::{User, INBOX, MAILBOX_HIERARCHY_DELIMITER as MBX_HIER_DELIM_RAW};
use crate::mail::IMF; use crate::mail::IMF;
static MAILBOX_HIERARCHY_DELIMITER: QuotedChar = QuotedChar::unvalidated(MBX_HIER_DELIM_RAW);
pub struct AuthenticatedContext<'a> { pub struct AuthenticatedContext<'a> {
pub req: &'a Request, pub req: &'a Command<'static>,
pub user: &'a Arc<User>, pub user: &'a Arc<User>,
} }
pub async fn dispatch(ctx: AuthenticatedContext<'_>) -> Result<(Response, flow::Transition)> { pub async fn dispatch(ctx: AuthenticatedContext<'_>) -> Result<(Response, flow::Transition)> {
match &ctx.req.command.body { match &ctx.req.body {
CommandBody::Create { mailbox } => ctx.create(mailbox).await, CommandBody::Create { mailbox } => ctx.create(mailbox).await,
CommandBody::Delete { mailbox } => ctx.delete(mailbox).await, CommandBody::Delete { mailbox } => ctx.delete(mailbox).await,
CommandBody::Rename { CommandBody::Rename { from, to } => ctx.rename(from, to).await,
mailbox,
new_mailbox,
} => ctx.rename(mailbox, new_mailbox).await,
CommandBody::Lsub { CommandBody::Lsub {
reference, reference,
mailbox_wildcard, mailbox_wildcard,
@ -43,8 +41,8 @@ pub async fn dispatch(ctx: AuthenticatedContext<'_>) -> Result<(Response, flow::
} => ctx.list(reference, mailbox_wildcard, false).await, } => ctx.list(reference, mailbox_wildcard, false).await,
CommandBody::Status { CommandBody::Status {
mailbox, mailbox,
attributes, item_names,
} => ctx.status(mailbox, attributes).await, } => ctx.status(mailbox, item_names).await,
CommandBody::Subscribe { mailbox } => ctx.subscribe(mailbox).await, CommandBody::Subscribe { mailbox } => ctx.subscribe(mailbox).await,
CommandBody::Unsubscribe { mailbox } => ctx.unsubscribe(mailbox).await, CommandBody::Unsubscribe { mailbox } => ctx.unsubscribe(mailbox).await,
CommandBody::Select { mailbox } => ctx.select(mailbox).await, CommandBody::Select { mailbox } => ctx.select(mailbox).await,
@ -55,90 +53,161 @@ pub async fn dispatch(ctx: AuthenticatedContext<'_>) -> Result<(Response, flow::
date, date,
message, message,
} => ctx.append(mailbox, flags, date, message).await, } => ctx.append(mailbox, flags, date, message).await,
_ => { cmd => {
let ctx = anonymous::AnonymousContext { tracing::warn!("Unknown command for the authenticated state {:?}", cmd);
req: ctx.req, Ok((
login_provider: None, Response::bad()
}; .to_req(ctx.req)
anonymous::dispatch(ctx).await .message("Command unavailable")
.build()?,
flow::Transition::None,
))
} }
} }
} }
// --- PRIVATE --- // --- PRIVATE ---
impl<'a> AuthenticatedContext<'a> { /// Convert an IMAP mailbox name/identifier representation
async fn create(self, mailbox: &MailboxCodec) -> Result<(Response, flow::Transition)> { /// to an utf-8 string that is used internally in Aerogramme
let name = String::try_from(mailbox.clone())?; struct MailboxName<'a>(&'a MailboxCodec<'a>);
impl<'a> TryInto<&'a str> for MailboxName<'a> {
type Error = std::str::Utf8Error;
fn try_into(self) -> Result<&'a str, Self::Error> {
match self.0 {
MailboxCodec::Inbox => Ok(INBOX),
MailboxCodec::Other(aname) => Ok(std::str::from_utf8(aname.as_ref())?),
}
}
}
if name == INBOX { impl<'a> AuthenticatedContext<'a> {
async fn create(self, mailbox: &MailboxCodec<'a>) -> Result<(Response, flow::Transition)> {
let name = match mailbox {
MailboxCodec::Inbox => {
return Ok(( return Ok((
Response::bad("Cannot create INBOX")?, Response::bad()
.to_req(self.req)
.message("Cannot create INBOX")
.build()?,
flow::Transition::None, flow::Transition::None,
)); ));
} }
MailboxCodec::Other(aname) => std::str::from_utf8(aname.as_ref())?,
};
match self.user.create_mailbox(&name).await { match self.user.create_mailbox(&name).await {
Ok(()) => Ok((Response::ok("CREATE complete")?, flow::Transition::None)), Ok(()) => Ok((
Err(e) => Ok((Response::no(&e.to_string())?, flow::Transition::None)), Response::ok()
.to_req(self.req)
.message("CREATE complete")
.build()?,
flow::Transition::None,
)),
Err(e) => Ok((
Response::no()
.to_req(self.req)
.message(&e.to_string())
.build()?,
flow::Transition::None,
)),
} }
} }
async fn delete(self, mailbox: &MailboxCodec) -> Result<(Response, flow::Transition)> { async fn delete(self, mailbox: &MailboxCodec<'a>) -> Result<(Response, flow::Transition)> {
let name = String::try_from(mailbox.clone())?; let name: &str = MailboxName(mailbox).try_into()?;
match self.user.delete_mailbox(&name).await { match self.user.delete_mailbox(&name).await {
Ok(()) => Ok((Response::ok("DELETE complete")?, flow::Transition::None)), Ok(()) => Ok((
Err(e) => Ok((Response::no(&e.to_string())?, flow::Transition::None)), Response::ok()
.to_req(self.req)
.message("DELETE complete")
.build()?,
flow::Transition::None,
)),
Err(e) => Ok((
Response::no()
.to_req(self.req)
.message(e.to_string())
.build()?,
flow::Transition::None,
)),
} }
} }
async fn rename( async fn rename(
self, self,
mailbox: &MailboxCodec, from: &MailboxCodec<'a>,
new_mailbox: &MailboxCodec, to: &MailboxCodec<'a>,
) -> Result<(Response, flow::Transition)> { ) -> Result<(Response, flow::Transition)> {
let name = String::try_from(mailbox.clone())?; let name: &str = MailboxName(from).try_into()?;
let new_name = String::try_from(new_mailbox.clone())?; let new_name: &str = MailboxName(to).try_into()?;
match self.user.rename_mailbox(&name, &new_name).await { match self.user.rename_mailbox(&name, &new_name).await {
Ok(()) => Ok((Response::ok("RENAME complete")?, flow::Transition::None)), Ok(()) => Ok((
Err(e) => Ok((Response::no(&e.to_string())?, flow::Transition::None)), Response::ok()
.to_req(self.req)
.message("RENAME complete")
.build()?,
flow::Transition::None,
)),
Err(e) => Ok((
Response::no()
.to_req(self.req)
.message(e.to_string())
.build()?,
flow::Transition::None,
)),
} }
} }
async fn list( async fn list(
self, self,
reference: &MailboxCodec, reference: &MailboxCodec<'a>,
mailbox_wildcard: &ListMailbox, mailbox_wildcard: &ListMailbox<'a>,
is_lsub: bool, is_lsub: bool,
) -> Result<(Response, flow::Transition)> { ) -> Result<(Response, flow::Transition)> {
let reference = String::try_from(reference.clone())?; let reference: &str = MailboxName(reference).try_into()?;
if !reference.is_empty() { if !reference.is_empty() {
return Ok(( return Ok((
Response::bad("References not supported")?, Response::bad()
.to_req(self.req)
.message("References not supported")
.build()?,
flow::Transition::None, flow::Transition::None,
)); ));
} }
let wildcard = String::try_from(mailbox_wildcard.clone())?; // @FIXME would probably need a rewrite to better use the imap_codec library
let wildcard = match mailbox_wildcard {
ListMailbox::Token(v) => std::str::from_utf8(v.as_ref())?,
ListMailbox::String(v) => std::str::from_utf8(v.as_ref())?,
};
if wildcard.is_empty() { if wildcard.is_empty() {
if is_lsub { if is_lsub {
return Ok(( return Ok((
Response::ok("LSUB complete")?.with_body(vec![Data::Lsub { Response::ok()
.to_req(self.req)
.message("LSUB complete")
.data(Data::Lsub {
items: vec![], items: vec![],
delimiter: Some(MAILBOX_HIERARCHY_DELIMITER), delimiter: Some(MAILBOX_HIERARCHY_DELIMITER),
mailbox: "".try_into().unwrap(), mailbox: "".try_into().unwrap(),
}]), })
.build()?,
flow::Transition::None, flow::Transition::None,
)); ));
} else { } else {
return Ok(( return Ok((
Response::ok("LIST complete")?.with_body(vec![Data::List { Response::ok()
.to_req(self.req)
.message("LIST complete")
.data(Data::List {
items: vec![], items: vec![],
delimiter: Some(MAILBOX_HIERARCHY_DELIMITER), delimiter: Some(MAILBOX_HIERARCHY_DELIMITER),
mailbox: "".try_into().unwrap(), mailbox: "".try_into().unwrap(),
}]), })
.build()?,
flow::Transition::None, flow::Transition::None,
)); ));
} }
@ -147,7 +216,7 @@ impl<'a> AuthenticatedContext<'a> {
let mailboxes = self.user.list_mailboxes().await?; let mailboxes = self.user.list_mailboxes().await?;
let mut vmailboxes = BTreeMap::new(); let mut vmailboxes = BTreeMap::new();
for mb in mailboxes.iter() { for mb in mailboxes.iter() {
for (i, _) in mb.match_indices(MAILBOX_HIERARCHY_DELIMITER) { for (i, _) in mb.match_indices(MBX_HIER_DELIM_RAW) {
if i > 0 { if i > 0 {
let smb = &mb[..i]; let smb = &mb[..i];
vmailboxes.entry(smb).or_insert(false); vmailboxes.entry(smb).or_insert(false);
@ -163,9 +232,9 @@ impl<'a> AuthenticatedContext<'a> {
.to_string() .to_string()
.try_into() .try_into()
.map_err(|_| anyhow!("invalid mailbox name"))?; .map_err(|_| anyhow!("invalid mailbox name"))?;
let mut items = vec![FlagNameAttribute::Extension( let mut items = vec![FlagNameAttribute::try_from(Atom::unvalidated(
"Subscribed".try_into().unwrap(), "Subscribed",
)]; ))?];
if !*is_real { if !*is_real {
items.push(FlagNameAttribute::Noselect); items.push(FlagNameAttribute::Noselect);
} }
@ -190,21 +259,31 @@ impl<'a> AuthenticatedContext<'a> {
} else { } else {
"LIST completed" "LIST completed"
}; };
Ok((Response::ok(msg)?.with_body(ret), flow::Transition::None)) Ok((
Response::ok()
.to_req(self.req)
.message(msg)
.set_data(ret)
.build()?,
flow::Transition::None,
))
} }
async fn status( async fn status(
self, self,
mailbox: &MailboxCodec, mailbox: &MailboxCodec<'a>,
attributes: &[StatusAttribute], attributes: &[StatusDataItemName],
) -> Result<(Response, flow::Transition)> { ) -> Result<(Response, flow::Transition)> {
let name = String::try_from(mailbox.clone())?; let name: &str = MailboxName(mailbox).try_into()?;
let mb_opt = self.user.open_mailbox(&name).await?; let mb_opt = self.user.open_mailbox(name).await?;
let mb = match mb_opt { let mb = match mb_opt {
Some(mb) => mb, Some(mb) => mb,
None => { None => {
return Ok(( return Ok((
Response::no("Mailbox does not exist")?, Response::no()
.to_req(self.req)
.message("Mailbox does not exist")
.build()?,
flow::Transition::None, flow::Transition::None,
)) ))
} }
@ -215,54 +294,79 @@ impl<'a> AuthenticatedContext<'a> {
let mut ret_attrs = vec![]; let mut ret_attrs = vec![];
for attr in attributes.iter() { for attr in attributes.iter() {
ret_attrs.push(match attr { ret_attrs.push(match attr {
StatusAttribute::Messages => StatusAttributeValue::Messages(view.exists()?), StatusDataItemName::Messages => StatusDataItem::Messages(view.exists()?),
StatusAttribute::Unseen => StatusAttributeValue::Unseen(view.unseen_count() as u32), StatusDataItemName::Unseen => StatusDataItem::Unseen(view.unseen_count() as u32),
StatusAttribute::Recent => StatusAttributeValue::Recent(view.recent()?), StatusDataItemName::Recent => StatusDataItem::Recent(view.recent()?),
StatusAttribute::UidNext => StatusAttributeValue::UidNext(view.uidnext()), StatusDataItemName::UidNext => StatusDataItem::UidNext(view.uidnext()),
StatusAttribute::UidValidity => { StatusDataItemName::UidValidity => {
StatusAttributeValue::UidValidity(view.uidvalidity()) StatusDataItem::UidValidity(view.uidvalidity())
} }
StatusDataItemName::Deleted => {
bail!("quota not implemented, can't return deleted elements waiting for EXPUNGE");
},
StatusDataItemName::DeletedStorage => {
bail!("quota not implemented, can't return freed storage after EXPUNGE will be run");
},
}); });
} }
let data = vec![Body::Data(Data::Status { let data = Data::Status {
mailbox: mailbox.clone(), mailbox: mailbox.clone(),
attributes: ret_attrs, items: ret_attrs.into(),
})]; };
Ok(( Ok((
Response::ok("STATUS completed")?.with_body(data), Response::ok()
.to_req(self.req)
.message("STATUS completed")
.data(data)
.build()?,
flow::Transition::None, flow::Transition::None,
)) ))
} }
async fn subscribe(self, mailbox: &MailboxCodec) -> Result<(Response, flow::Transition)> { async fn subscribe(self, mailbox: &MailboxCodec<'a>) -> Result<(Response, flow::Transition)> {
let name = String::try_from(mailbox.clone())?; let name: &str = MailboxName(mailbox).try_into()?;
if self.user.has_mailbox(&name).await? { if self.user.has_mailbox(&name).await? {
Ok((Response::ok("SUBSCRIBE complete")?, flow::Transition::None)) Ok((
Response::ok()
.to_req(self.req)
.message("SUBSCRIBE complete")
.build()?,
flow::Transition::None,
))
} else { } else {
Ok(( Ok((
Response::bad(&format!("Mailbox {} does not exist", name))?, Response::bad()
.to_req(self.req)
.message(format!("Mailbox {} does not exist", name))
.build()?,
flow::Transition::None, flow::Transition::None,
)) ))
} }
} }
async fn unsubscribe(self, mailbox: &MailboxCodec) -> Result<(Response, flow::Transition)> { async fn unsubscribe(self, mailbox: &MailboxCodec<'a>) -> Result<(Response, flow::Transition)> {
let name = String::try_from(mailbox.clone())?; let name: &str = MailboxName(mailbox).try_into()?;
if self.user.has_mailbox(&name).await? { if self.user.has_mailbox(&name).await? {
Ok(( Ok((
Response::bad(&format!( Response::bad()
.to_req(self.req)
.message(format!(
"Cannot unsubscribe from mailbox {}: not supported by Aerogramme", "Cannot unsubscribe from mailbox {}: not supported by Aerogramme",
name name
))?, ))
.build()?,
flow::Transition::None, flow::Transition::None,
)) ))
} else { } else {
Ok(( Ok((
Response::bad(&format!("Mailbox {} does not exist", name))?, Response::no()
.to_req(self.req)
.message(format!("Mailbox {} does not exist", name))
.build()?,
flow::Transition::None, flow::Transition::None,
)) ))
} }
@ -301,15 +405,18 @@ impl<'a> AuthenticatedContext<'a> {
* TRACE END --- * TRACE END ---
*/ */
async fn select(self, mailbox: &MailboxCodec) -> Result<(Response, flow::Transition)> { async fn select(self, mailbox: &MailboxCodec<'a>) -> Result<(Response, flow::Transition)> {
let name = String::try_from(mailbox.clone())?; let name: &str = MailboxName(mailbox).try_into()?;
let mb_opt = self.user.open_mailbox(&name).await?; let mb_opt = self.user.open_mailbox(&name).await?;
let mb = match mb_opt { let mb = match mb_opt {
Some(mb) => mb, Some(mb) => mb,
None => { None => {
return Ok(( return Ok((
Response::no("Mailbox does not exist")?, Response::no()
.to_req(self.req)
.message("Mailbox does not exist")
.build()?,
flow::Transition::None, flow::Transition::None,
)) ))
} }
@ -319,22 +426,27 @@ impl<'a> AuthenticatedContext<'a> {
let (mb, data) = MailboxView::new(mb).await?; let (mb, data) = MailboxView::new(mb).await?;
Ok(( Ok((
Response::ok("Select completed")? Response::ok()
.with_extra_code(Code::ReadWrite) .message("Select completed")
.with_body(data), .code(Code::ReadWrite)
.data(data)
.build()?,
flow::Transition::Select(mb), flow::Transition::Select(mb),
)) ))
} }
async fn examine(self, mailbox: &MailboxCodec) -> Result<(Response, flow::Transition)> { async fn examine(self, mailbox: &MailboxCodec<'a>) -> Result<(Response, flow::Transition)> {
let name = String::try_from(mailbox.clone())?; let name: &str = MailboxName(mailbox).try_into()?;
let mb_opt = self.user.open_mailbox(&name).await?; let mb_opt = self.user.open_mailbox(&name).await?;
let mb = match mb_opt { let mb = match mb_opt {
Some(mb) => mb, Some(mb) => mb,
None => { None => {
return Ok(( return Ok((
Response::no("Mailbox does not exist")?, Response::no()
.to_req(self.req)
.message("Mailbox does not exist")
.build()?,
flow::Transition::None, flow::Transition::None,
)) ))
} }
@ -344,40 +456,53 @@ impl<'a> AuthenticatedContext<'a> {
let (mb, data) = MailboxView::new(mb).await?; let (mb, data) = MailboxView::new(mb).await?;
Ok(( Ok((
Response::ok("Examine completed")? Response::ok()
.with_extra_code(Code::ReadOnly) .to_req(self.req)
.with_body(data), .message("Examine completed")
.code(Code::ReadOnly)
.data(data)
.build()?,
flow::Transition::Examine(mb), flow::Transition::Examine(mb),
)) ))
} }
async fn append( async fn append(
self, self,
mailbox: &MailboxCodec, mailbox: &MailboxCodec<'a>,
flags: &[Flag], flags: &[Flag<'a>],
date: &Option<MyDateTime>, date: &Option<DateTime>,
message: &NonZeroBytes, message: &Literal<'a>,
) -> Result<(Response, flow::Transition)> { ) -> Result<(Response, flow::Transition)> {
let append_tag = self.req.tag.clone();
match self.append_internal(mailbox, flags, date, message).await { match self.append_internal(mailbox, flags, date, message).await {
Ok((_mb, uidvalidity, uid)) => Ok(( Ok((_mb, uidvalidity, uid)) => Ok((
Response::ok("APPEND completed")?.with_extra_code(Code::Other( Response::ok()
"APPENDUID".try_into().unwrap(), .tag(append_tag)
Some(format!("{} {}", uidvalidity, uid)), .message("APPEND completed")
)), .code(Code::Other(CodeOther::unvalidated(
format!("APPENDUID {} {}", uidvalidity, uid).into_bytes(),
)))
.build()?,
flow::Transition::None,
)),
Err(e) => Ok((
Response::no()
.tag(append_tag)
.message(e.to_string())
.build()?,
flow::Transition::None, flow::Transition::None,
)), )),
Err(e) => Ok((Response::no(&e.to_string())?, flow::Transition::None)),
} }
} }
pub(crate) async fn append_internal( pub(crate) async fn append_internal(
self, self,
mailbox: &MailboxCodec, mailbox: &MailboxCodec<'a>,
flags: &[Flag], flags: &[Flag<'a>],
date: &Option<MyDateTime>, date: &Option<DateTime>,
message: &NonZeroBytes, message: &Literal<'a>,
) -> Result<(Arc<Mailbox>, ImapUidvalidity, ImapUidvalidity)> { ) -> Result<(Arc<Mailbox>, ImapUidvalidity, ImapUidvalidity)> {
let name = String::try_from(mailbox.clone())?; let name: &str = MailboxName(mailbox).try_into()?;
let mb_opt = self.user.open_mailbox(&name).await?; let mb_opt = self.user.open_mailbox(&name).await?;
let mb = match mb_opt { let mb = match mb_opt {
@ -389,8 +514,8 @@ impl<'a> AuthenticatedContext<'a> {
bail!("Cannot set date when appending message"); bail!("Cannot set date when appending message");
} }
let msg = IMF::try_from(message.as_slice()) let msg =
.map_err(|_| anyhow!("Could not parse e-mail message"))?; IMF::try_from(message.data()).map_err(|_| anyhow!("Could not parse e-mail message"))?;
let flags = flags.iter().map(|x| x.to_string()).collect::<Vec<_>>(); let flags = flags.iter().map(|x| x.to_string()).collect::<Vec<_>>();
// TODO: filter allowed flags? ping @Quentin // TODO: filter allowed flags? ping @Quentin
@ -422,7 +547,7 @@ fn matches_wildcard(wildcard: &str, name: &str) -> bool {
&& j > 0 && j > 0
&& matches[i - 1][j] && matches[i - 1][j]
&& (wildcard[j - 1] == '*' && (wildcard[j - 1] == '*'
|| (wildcard[j - 1] == '%' && name[i - 1] != MAILBOX_HIERARCHY_DELIMITER))); || (wildcard[j - 1] == '%' && name[i - 1] != MBX_HIER_DELIM_RAW)));
} }
} }

View file

@ -1,6 +1,7 @@
mod command; mod command;
mod flow; mod flow;
mod mailbox_view; mod mailbox_view;
mod response;
mod session; mod session;
use std::task::{Context, Poll}; use std::task::{Context, Poll};

97
src/imap/response.rs Normal file
View file

@ -0,0 +1,97 @@
use anyhow::Result;
use imap_codec::imap_types::command::Command;
use imap_codec::imap_types::core::Tag;
use imap_codec::imap_types::response::{Code, Data, Status, StatusKind};
pub struct ResponseBuilder {
status: StatusKind,
tag: Option<Tag<'static>>,
code: Option<Code<'static>>,
text: String,
data: Vec<Data<'static>>,
}
impl<'a> Default for ResponseBuilder {
fn default() -> ResponseBuilder {
ResponseBuilder {
status: StatusKind::Bad,
tag: None,
code: None,
text: "".to_string(),
data: vec![],
}
}
}
impl ResponseBuilder {
pub fn to_req(mut self, cmd: &Command) -> Self {
self.tag = Some(cmd.tag);
self
}
pub fn tag(mut self, tag: Tag) -> Self {
self.tag = Some(tag);
self
}
pub fn message(mut self, txt: impl Into<String>) -> Self {
self.text = txt.into();
self
}
pub fn code(mut self, code: Code) -> Self {
self.code = Some(code);
self
}
pub fn data(mut self, data: Data) -> Self {
self.data.push(data);
self
}
pub fn set_data(mut self, data: Vec<Data>) -> Self {
self.data = data;
self
}
pub fn build(self) -> Result<Response> {
Ok(Response {
status: Status::new(self.tag, self.status, self.code, self.text)?,
data: self.data,
})
}
}
pub struct Response {
data: Vec<Data<'static>>,
status: Status<'static>,
}
impl Response {
pub fn ok() -> ResponseBuilder {
ResponseBuilder {
status: StatusKind::Ok,
..ResponseBuilder::default()
}
}
pub fn no() -> ResponseBuilder {
ResponseBuilder {
status: StatusKind::No,
..ResponseBuilder::default()
}
}
pub fn bad() -> ResponseBuilder {
ResponseBuilder {
status: StatusKind::Bad,
..ResponseBuilder::default()
}
}
pub fn bye() -> Result<Response> {
Ok(Response {
status: Status::bye(None, "bye")?,
data: vec![],
})
}
}