diff options
author | Quentin <quentin@dufour.io> | 2024-01-02 22:44:29 +0000 |
---|---|---|
committer | Quentin <quentin@dufour.io> | 2024-01-02 22:44:29 +0000 |
commit | b9a0c1e6eced036eb71e8221a4f236f72832fec2 (patch) | |
tree | c498a7a2a5833f2c6f27d4ba97894747f9d454c0 /src/imap/command | |
parent | 6ff3c6f71efd802da422a371e6168ae528fb2ddc (diff) | |
parent | c9a33c080d39d4a2b269e3c8f166a708b6606da5 (diff) | |
download | aerogramme-b9a0c1e6eced036eb71e8221a4f236f72832fec2.tar.gz aerogramme-b9a0c1e6eced036eb71e8221a4f236f72832fec2.zip |
Merge pull request 'Implement imap-flow' (#34) from refactor/imap-flow into main
Reviewed-on: https://git.deuxfleurs.fr/Deuxfleurs/aerogramme/pulls/34
Diffstat (limited to 'src/imap/command')
-rw-r--r-- | src/imap/command/anonymous.rs | 91 | ||||
-rw-r--r-- | src/imap/command/anystate.rs | 52 | ||||
-rw-r--r-- | src/imap/command/authenticated.rs | 400 | ||||
-rw-r--r-- | src/imap/command/examined.rs | 142 | ||||
-rw-r--r-- | src/imap/command/mod.rs | 17 | ||||
-rw-r--r-- | src/imap/command/selected.rs | 161 |
6 files changed, 573 insertions, 290 deletions
diff --git a/src/imap/command/anonymous.rs b/src/imap/command/anonymous.rs index d258bd3..fbd10e9 100644 --- a/src/imap/command/anonymous.rs +++ b/src/imap/command/anonymous.rs @@ -1,92 +1,77 @@ -use anyhow::{Error, Result}; -use boitalettres::proto::{res::body::Data as Body, Request, Response}; -use imap_codec::types::command::CommandBody; -use imap_codec::types::core::AString; -use imap_codec::types::response::{Capability, Data, Status}; +use anyhow::Result; +use imap_codec::imap_types::command::{Command, CommandBody}; +use imap_codec::imap_types::core::AString; +use imap_codec::imap_types::secret::Secret; +use crate::imap::command::anystate; use crate::imap::flow; +use crate::imap::response::Response; use crate::login::ArcLoginProvider; use crate::mail::user::User; //--- dispatching pub struct AnonymousContext<'a> { - pub req: &'a Request, - pub login_provider: Option<&'a ArcLoginProvider>, + pub req: &'a Command<'static>, + pub login_provider: &'a ArcLoginProvider, } -pub async fn dispatch(ctx: AnonymousContext<'_>) -> Result<(Response, flow::Transition)> { - match &ctx.req.command.body { - CommandBody::Noop => Ok((Response::ok("Noop completed.")?, flow::Transition::None)), - CommandBody::Capability => ctx.capability().await, - CommandBody::Logout => ctx.logout().await, +pub async fn dispatch(ctx: AnonymousContext<'_>) -> Result<(Response<'static>, flow::Transition)> { + match &ctx.req.body { + // Any State + CommandBody::Noop => anystate::noop_nothing(ctx.req.tag.clone()), + CommandBody::Capability => anystate::capability(ctx.req.tag.clone()), + CommandBody::Logout => anystate::logout(), + + // Specific to anonymous context (3 commands) CommandBody::Login { username, password } => ctx.login(username, password).await, - _ => Ok((Response::no("Command unavailable")?, flow::Transition::None)), + CommandBody::Authenticate { .. } => { + anystate::not_implemented(ctx.req.tag.clone(), "authenticate") + } + //StartTLS is not implemented for now, we will probably go full TLS. + + // Collect other commands + _ => anystate::wrong_state(ctx.req.tag.clone()), } } //--- Command controllers, private impl<'a> AnonymousContext<'a> { - async fn capability(self) -> Result<(Response, flow::Transition)> { - let capabilities = vec![Capability::Imap4Rev1, Capability::Idle]; - let res = Response::ok("Server capabilities")?.with_body(Data::Capability(capabilities)); - Ok((res, flow::Transition::None)) - } - async fn login( self, - username: &AString, - password: &AString, - ) -> Result<(Response, flow::Transition)> { + username: &AString<'a>, + password: &Secret<AString<'a>>, + ) -> Result<(Response<'static>, flow::Transition)> { let (u, p) = ( - String::try_from(username.clone())?, - String::try_from(password.clone())?, + std::str::from_utf8(username.as_ref())?, + std::str::from_utf8(password.declassify().as_ref())?, ); tracing::info!(user = %u, "command.login"); - let login_provider = match &self.login_provider { - 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 { + let creds = match self.login_provider.login(&u, &p).await { Err(e) => { tracing::debug!(error=%e, "authentication failed"); return Ok(( - Response::no("Authentication failed")?, + Response::build() + .to_req(self.req) + .message("Authentication failed") + .no()?, flow::Transition::None, )); } 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"); Ok(( - Response::ok("Completed")?, + Response::build() + .to_req(self.req) + .message("Completed") + .ok()?, flow::Transition::Authenticate(user), )) } - - // C: 10 logout - // S: * BYE Logging out - // S: 10 OK Logout completed. - async fn logout(self) -> Result<(Response, flow::Transition)> { - // @FIXME we should implement From<Vec<Status>> and From<Vec<ImapStatus>> in - // boitalettres/src/proto/res/body.rs - Ok(( - 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, - )) - } } diff --git a/src/imap/command/anystate.rs b/src/imap/command/anystate.rs new file mode 100644 index 0000000..42fe645 --- /dev/null +++ b/src/imap/command/anystate.rs @@ -0,0 +1,52 @@ +use anyhow::Result; +use imap_codec::imap_types::core::{NonEmptyVec, Tag}; +use imap_codec::imap_types::response::{Capability, Data}; + +use crate::imap::flow; +use crate::imap::response::Response; + +pub(crate) fn capability(tag: Tag<'static>) -> Result<(Response<'static>, flow::Transition)> { + let capabilities: NonEmptyVec<Capability> = + (vec![Capability::Imap4Rev1, Capability::Idle]).try_into()?; + let res = Response::build() + .tag(tag) + .message("Server capabilities") + .data(Data::Capability(capabilities)) + .ok()?; + + Ok((res, flow::Transition::None)) +} + +pub(crate) fn noop_nothing(tag: Tag<'static>) -> Result<(Response<'static>, flow::Transition)> { + Ok(( + Response::build().tag(tag).message("Noop completed.").ok()?, + flow::Transition::None, + )) +} + +pub(crate) fn logout() -> Result<(Response<'static>, flow::Transition)> { + Ok((Response::bye()?, flow::Transition::Logout)) +} + +pub(crate) fn not_implemented<'a>( + tag: Tag<'a>, + what: &str, +) -> Result<(Response<'a>, flow::Transition)> { + Ok(( + Response::build() + .tag(tag) + .message(format!("Command not implemented {}", what)) + .bad()?, + flow::Transition::None, + )) +} + +pub(crate) fn wrong_state(tag: Tag<'static>) -> Result<(Response<'static>, flow::Transition)> { + Ok(( + Response::build() + .tag(tag) + .message("Command not authorized in this state") + .bad()?, + flow::Transition::None, + )) +} diff --git a/src/imap/command/authenticated.rs b/src/imap/command/authenticated.rs index 2deb723..1bb4c6d 100644 --- a/src/imap/command/authenticated.rs +++ b/src/imap/command/authenticated.rs @@ -2,37 +2,42 @@ use std::collections::BTreeMap; use std::sync::Arc; use anyhow::{anyhow, bail, Result}; -use boitalettres::proto::res::body::Data as Body; -use boitalettres::proto::{Request, Response}; -use imap_codec::types::command::{CommandBody, StatusAttribute}; -use imap_codec::types::core::NonZeroBytes; -use imap_codec::types::datetime::MyDateTime; -use imap_codec::types::flag::{Flag, FlagNameAttribute}; -use imap_codec::types::mailbox::{ListMailbox, Mailbox as MailboxCodec}; -use imap_codec::types::response::{Code, Data, StatusAttributeValue}; - -use crate::imap::command::anonymous; +use imap_codec::imap_types::command::{Command, CommandBody}; +use imap_codec::imap_types::core::{Atom, Literal, QuotedChar}; +use imap_codec::imap_types::datetime::DateTime; +use imap_codec::imap_types::flag::{Flag, FlagNameAttribute}; +use imap_codec::imap_types::mailbox::{ListMailbox, Mailbox as MailboxCodec}; +use imap_codec::imap_types::response::{Code, CodeOther, Data}; +use imap_codec::imap_types::status::{StatusDataItem, StatusDataItemName}; + +use crate::imap::command::{anystate, MailboxName}; use crate::imap::flow; use crate::imap::mailbox_view::MailboxView; +use crate::imap::response::Response; use crate::mail::mailbox::Mailbox; use crate::mail::uidindex::*; -use crate::mail::user::{User, INBOX, MAILBOX_HIERARCHY_DELIMITER}; +use crate::mail::user::{User, MAILBOX_HIERARCHY_DELIMITER as MBX_HIER_DELIM_RAW}; use crate::mail::IMF; pub struct AuthenticatedContext<'a> { - pub req: &'a Request, + pub req: &'a Command<'static>, pub user: &'a Arc<User>, } -pub async fn dispatch(ctx: AuthenticatedContext<'_>) -> Result<(Response, flow::Transition)> { - match &ctx.req.command.body { +pub async fn dispatch<'a>( + ctx: AuthenticatedContext<'a>, +) -> Result<(Response<'static>, flow::Transition)> { + match &ctx.req.body { + // Any state + CommandBody::Noop => anystate::noop_nothing(ctx.req.tag.clone()), + CommandBody::Capability => anystate::capability(ctx.req.tag.clone()), + CommandBody::Logout => anystate::logout(), + + // Specific to this state (11 commands) CommandBody::Create { mailbox } => ctx.create(mailbox).await, CommandBody::Delete { mailbox } => ctx.delete(mailbox).await, - CommandBody::Rename { - mailbox, - new_mailbox, - } => ctx.rename(mailbox, new_mailbox).await, + CommandBody::Rename { from, to } => ctx.rename(from, to).await, CommandBody::Lsub { reference, mailbox_wildcard, @@ -43,8 +48,8 @@ pub async fn dispatch(ctx: AuthenticatedContext<'_>) -> Result<(Response, flow:: } => ctx.list(reference, mailbox_wildcard, false).await, CommandBody::Status { mailbox, - attributes, - } => ctx.status(mailbox, attributes).await, + item_names, + } => ctx.status(mailbox, item_names).await, CommandBody::Subscribe { mailbox } => ctx.subscribe(mailbox).await, CommandBody::Unsubscribe { mailbox } => ctx.unsubscribe(mailbox).await, CommandBody::Select { mailbox } => ctx.select(mailbox).await, @@ -55,90 +60,148 @@ pub async fn dispatch(ctx: AuthenticatedContext<'_>) -> Result<(Response, flow:: date, message, } => ctx.append(mailbox, flags, date, message).await, - _ => { - let ctx = anonymous::AnonymousContext { - req: ctx.req, - login_provider: None, - }; - anonymous::dispatch(ctx).await - } + + // Collect other commands + _ => anystate::wrong_state(ctx.req.tag.clone()), } } // --- PRIVATE --- - impl<'a> AuthenticatedContext<'a> { - async fn create(self, mailbox: &MailboxCodec) -> Result<(Response, flow::Transition)> { - let name = String::try_from(mailbox.clone())?; - - if name == INBOX { - return Ok(( - Response::bad("Cannot create INBOX")?, - flow::Transition::None, - )); - } + async fn create( + self, + mailbox: &MailboxCodec<'a>, + ) -> Result<(Response<'static>, flow::Transition)> { + let name = match mailbox { + MailboxCodec::Inbox => { + return Ok(( + Response::build() + .to_req(self.req) + .message("Cannot create INBOX") + .bad()?, + flow::Transition::None, + )); + } + MailboxCodec::Other(aname) => std::str::from_utf8(aname.as_ref())?, + }; match self.user.create_mailbox(&name).await { - Ok(()) => Ok((Response::ok("CREATE complete")?, flow::Transition::None)), - Err(e) => Ok((Response::no(&e.to_string())?, flow::Transition::None)), + Ok(()) => Ok(( + Response::build() + .to_req(self.req) + .message("CREATE complete") + .ok()?, + flow::Transition::None, + )), + Err(e) => Ok(( + Response::build() + .to_req(self.req) + .message(&e.to_string()) + .no()?, + flow::Transition::None, + )), } } - async fn delete(self, mailbox: &MailboxCodec) -> Result<(Response, flow::Transition)> { - let name = String::try_from(mailbox.clone())?; + async fn delete( + self, + mailbox: &MailboxCodec<'a>, + ) -> Result<(Response<'static>, flow::Transition)> { + let name: &str = MailboxName(mailbox).try_into()?; match self.user.delete_mailbox(&name).await { - Ok(()) => Ok((Response::ok("DELETE complete")?, flow::Transition::None)), - Err(e) => Ok((Response::no(&e.to_string())?, flow::Transition::None)), + Ok(()) => Ok(( + Response::build() + .to_req(self.req) + .message("DELETE complete") + .ok()?, + flow::Transition::None, + )), + Err(e) => Ok(( + Response::build() + .to_req(self.req) + .message(e.to_string()) + .no()?, + flow::Transition::None, + )), } } async fn rename( self, - mailbox: &MailboxCodec, - new_mailbox: &MailboxCodec, - ) -> Result<(Response, flow::Transition)> { - let name = String::try_from(mailbox.clone())?; - let new_name = String::try_from(new_mailbox.clone())?; + from: &MailboxCodec<'a>, + to: &MailboxCodec<'a>, + ) -> Result<(Response<'static>, flow::Transition)> { + let name: &str = MailboxName(from).try_into()?; + let new_name: &str = MailboxName(to).try_into()?; match self.user.rename_mailbox(&name, &new_name).await { - Ok(()) => Ok((Response::ok("RENAME complete")?, flow::Transition::None)), - Err(e) => Ok((Response::no(&e.to_string())?, flow::Transition::None)), + Ok(()) => Ok(( + Response::build() + .to_req(self.req) + .message("RENAME complete") + .ok()?, + flow::Transition::None, + )), + Err(e) => Ok(( + Response::build() + .to_req(self.req) + .message(e.to_string()) + .no()?, + flow::Transition::None, + )), } } async fn list( self, - reference: &MailboxCodec, - mailbox_wildcard: &ListMailbox, + reference: &MailboxCodec<'a>, + mailbox_wildcard: &ListMailbox<'a>, is_lsub: bool, - ) -> Result<(Response, flow::Transition)> { - let reference = String::try_from(reference.clone())?; + ) -> Result<(Response<'static>, flow::Transition)> { + let mbx_hier_delim: QuotedChar = QuotedChar::unvalidated(MBX_HIER_DELIM_RAW); + + let reference: &str = MailboxName(reference).try_into()?; if !reference.is_empty() { return Ok(( - Response::bad("References not supported")?, + Response::build() + .to_req(self.req) + .message("References not supported") + .bad()?, 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 is_lsub { return Ok(( - Response::ok("LSUB complete")?.with_body(vec![Data::Lsub { - items: vec![], - delimiter: Some(MAILBOX_HIERARCHY_DELIMITER), - mailbox: "".try_into().unwrap(), - }]), + Response::build() + .to_req(self.req) + .message("LSUB complete") + .data(Data::Lsub { + items: vec![], + delimiter: Some(mbx_hier_delim), + mailbox: "".try_into().unwrap(), + }) + .ok()?, flow::Transition::None, )); } else { return Ok(( - Response::ok("LIST complete")?.with_body(vec![Data::List { - items: vec![], - delimiter: Some(MAILBOX_HIERARCHY_DELIMITER), - mailbox: "".try_into().unwrap(), - }]), + Response::build() + .to_req(self.req) + .message("LIST complete") + .data(Data::List { + items: vec![], + delimiter: Some(mbx_hier_delim), + mailbox: "".try_into().unwrap(), + }) + .ok()?, flow::Transition::None, )); } @@ -147,7 +210,7 @@ impl<'a> AuthenticatedContext<'a> { let mailboxes = self.user.list_mailboxes().await?; let mut vmailboxes = BTreeMap::new(); 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 { let smb = &mb[..i]; vmailboxes.entry(smb).or_insert(false); @@ -163,22 +226,22 @@ impl<'a> AuthenticatedContext<'a> { .to_string() .try_into() .map_err(|_| anyhow!("invalid mailbox name"))?; - let mut items = vec![FlagNameAttribute::Extension( - "Subscribed".try_into().unwrap(), - )]; + let mut items = vec![FlagNameAttribute::try_from(Atom::unvalidated( + "Subscribed", + ))?]; if !*is_real { items.push(FlagNameAttribute::Noselect); } if is_lsub { ret.push(Data::Lsub { items, - delimiter: Some(MAILBOX_HIERARCHY_DELIMITER), + delimiter: Some(mbx_hier_delim), mailbox, }); } else { ret.push(Data::List { items, - delimiter: Some(MAILBOX_HIERARCHY_DELIMITER), + delimiter: Some(mbx_hier_delim), mailbox, }); } @@ -190,79 +253,120 @@ impl<'a> AuthenticatedContext<'a> { } else { "LIST completed" }; - Ok((Response::ok(msg)?.with_body(ret), flow::Transition::None)) + Ok(( + Response::build() + .to_req(self.req) + .message(msg) + .many_data(ret) + .ok()?, + flow::Transition::None, + )) } async fn status( self, - mailbox: &MailboxCodec, - attributes: &[StatusAttribute], - ) -> Result<(Response, flow::Transition)> { - let name = String::try_from(mailbox.clone())?; - let mb_opt = self.user.open_mailbox(&name).await?; + mailbox: &MailboxCodec<'static>, + attributes: &[StatusDataItemName], + ) -> Result<(Response<'static>, flow::Transition)> { + let name: &str = MailboxName(mailbox).try_into()?; + let mb_opt = self.user.open_mailbox(name).await?; let mb = match mb_opt { Some(mb) => mb, None => { return Ok(( - Response::no("Mailbox does not exist")?, + Response::build() + .to_req(self.req) + .message("Mailbox does not exist") + .no()?, flow::Transition::None, )) } }; - let (view, _data) = MailboxView::new(mb).await?; + let view = MailboxView::new(mb).await; let mut ret_attrs = vec![]; for attr in attributes.iter() { ret_attrs.push(match attr { - StatusAttribute::Messages => StatusAttributeValue::Messages(view.exists()?), - StatusAttribute::Unseen => StatusAttributeValue::Unseen(view.unseen_count() as u32), - StatusAttribute::Recent => StatusAttributeValue::Recent(view.recent()?), - StatusAttribute::UidNext => StatusAttributeValue::UidNext(view.uidnext()), - StatusAttribute::UidValidity => { - StatusAttributeValue::UidValidity(view.uidvalidity()) + StatusDataItemName::Messages => StatusDataItem::Messages(view.exists()?), + StatusDataItemName::Unseen => StatusDataItem::Unseen(view.unseen_count() as u32), + StatusDataItemName::Recent => StatusDataItem::Recent(view.recent()?), + StatusDataItemName::UidNext => StatusDataItem::UidNext(view.uidnext()), + StatusDataItemName::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(), - attributes: ret_attrs, - })]; + items: ret_attrs.into(), + }; Ok(( - Response::ok("STATUS completed")?.with_body(data), + Response::build() + .to_req(self.req) + .message("STATUS completed") + .data(data) + .ok()?, flow::Transition::None, )) } - async fn subscribe(self, mailbox: &MailboxCodec) -> Result<(Response, flow::Transition)> { - let name = String::try_from(mailbox.clone())?; + async fn subscribe( + self, + mailbox: &MailboxCodec<'a>, + ) -> Result<(Response<'static>, flow::Transition)> { + let name: &str = MailboxName(mailbox).try_into()?; if self.user.has_mailbox(&name).await? { - Ok((Response::ok("SUBSCRIBE complete")?, flow::Transition::None)) + Ok(( + Response::build() + .to_req(self.req) + .message("SUBSCRIBE complete") + .ok()?, + flow::Transition::None, + )) } else { Ok(( - Response::bad(&format!("Mailbox {} does not exist", name))?, + Response::build() + .to_req(self.req) + .message(format!("Mailbox {} does not exist", name)) + .bad()?, flow::Transition::None, )) } } - async fn unsubscribe(self, mailbox: &MailboxCodec) -> Result<(Response, flow::Transition)> { - let name = String::try_from(mailbox.clone())?; + async fn unsubscribe( + self, + mailbox: &MailboxCodec<'a>, + ) -> Result<(Response<'static>, flow::Transition)> { + let name: &str = MailboxName(mailbox).try_into()?; if self.user.has_mailbox(&name).await? { Ok(( - Response::bad(&format!( - "Cannot unsubscribe from mailbox {}: not supported by Aerogramme", - name - ))?, + Response::build() + .to_req(self.req) + .message(format!( + "Cannot unsubscribe from mailbox {}: not supported by Aerogramme", + name + )) + .bad()?, flow::Transition::None, )) } else { Ok(( - Response::bad(&format!("Mailbox {} does not exist", name))?, + Response::build() + .to_req(self.req) + .message(format!("Mailbox {} does not exist", name)) + .no()?, flow::Transition::None, )) } @@ -301,83 +405,113 @@ impl<'a> AuthenticatedContext<'a> { * TRACE END --- */ - async fn select(self, mailbox: &MailboxCodec) -> Result<(Response, flow::Transition)> { - let name = String::try_from(mailbox.clone())?; + async fn select( + self, + mailbox: &MailboxCodec<'a>, + ) -> Result<(Response<'static>, flow::Transition)> { + let name: &str = MailboxName(mailbox).try_into()?; let mb_opt = self.user.open_mailbox(&name).await?; let mb = match mb_opt { Some(mb) => mb, None => { return Ok(( - Response::no("Mailbox does not exist")?, + Response::build() + .to_req(self.req) + .message("Mailbox does not exist") + .no()?, flow::Transition::None, )) } }; tracing::info!(username=%self.user.username, mailbox=%name, "mailbox.selected"); - let (mb, data) = MailboxView::new(mb).await?; + let mb = MailboxView::new(mb).await; + let data = mb.summary()?; Ok(( - Response::ok("Select completed")? - .with_extra_code(Code::ReadWrite) - .with_body(data), + Response::build() + .message("Select completed") + .to_req(self.req) + .code(Code::ReadWrite) + .set_body(data) + .ok()?, flow::Transition::Select(mb), )) } - async fn examine(self, mailbox: &MailboxCodec) -> Result<(Response, flow::Transition)> { - let name = String::try_from(mailbox.clone())?; + async fn examine( + self, + mailbox: &MailboxCodec<'a>, + ) -> Result<(Response<'static>, flow::Transition)> { + let name: &str = MailboxName(mailbox).try_into()?; let mb_opt = self.user.open_mailbox(&name).await?; let mb = match mb_opt { Some(mb) => mb, None => { return Ok(( - Response::no("Mailbox does not exist")?, + Response::build() + .to_req(self.req) + .message("Mailbox does not exist") + .no()?, flow::Transition::None, )) } }; tracing::info!(username=%self.user.username, mailbox=%name, "mailbox.examined"); - let (mb, data) = MailboxView::new(mb).await?; + let mb = MailboxView::new(mb).await; + let data = mb.summary()?; Ok(( - Response::ok("Examine completed")? - .with_extra_code(Code::ReadOnly) - .with_body(data), + Response::build() + .to_req(self.req) + .message("Examine completed") + .code(Code::ReadOnly) + .set_body(data) + .ok()?, flow::Transition::Examine(mb), )) } async fn append( self, - mailbox: &MailboxCodec, - flags: &[Flag], - date: &Option<MyDateTime>, - message: &NonZeroBytes, - ) -> Result<(Response, flow::Transition)> { + mailbox: &MailboxCodec<'a>, + flags: &[Flag<'a>], + date: &Option<DateTime>, + message: &Literal<'a>, + ) -> Result<(Response<'static>, flow::Transition)> { + let append_tag = self.req.tag.clone(); match self.append_internal(mailbox, flags, date, message).await { Ok((_mb, uidvalidity, uid)) => Ok(( - Response::ok("APPEND completed")?.with_extra_code(Code::Other( - "APPENDUID".try_into().unwrap(), - Some(format!("{} {}", uidvalidity, uid)), - )), + Response::build() + .tag(append_tag) + .message("APPEND completed") + .code(Code::Other(CodeOther::unvalidated( + format!("APPENDUID {} {}", uidvalidity, uid).into_bytes(), + ))) + .ok()?, + flow::Transition::None, + )), + Err(e) => Ok(( + Response::build() + .tag(append_tag) + .message(e.to_string()) + .no()?, flow::Transition::None, )), - Err(e) => Ok((Response::no(&e.to_string())?, flow::Transition::None)), } } pub(crate) async fn append_internal( self, - mailbox: &MailboxCodec, - flags: &[Flag], - date: &Option<MyDateTime>, - message: &NonZeroBytes, + mailbox: &MailboxCodec<'a>, + flags: &[Flag<'a>], + date: &Option<DateTime>, + message: &Literal<'a>, ) -> 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 = match mb_opt { @@ -389,8 +523,8 @@ impl<'a> AuthenticatedContext<'a> { bail!("Cannot set date when appending message"); } - let msg = IMF::try_from(message.as_slice()) - .map_err(|_| anyhow!("Could not parse e-mail message"))?; + let msg = + 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<_>>(); // TODO: filter allowed flags? ping @Quentin @@ -422,7 +556,7 @@ fn matches_wildcard(wildcard: &str, name: &str) -> bool { && j > 0 && matches[i - 1][j] && (wildcard[j - 1] == '*' - || (wildcard[j - 1] == '%' && name[i - 1] != MAILBOX_HIERARCHY_DELIMITER))); + || (wildcard[j - 1] == '%' && name[i - 1] != MBX_HIER_DELIM_RAW))); } } diff --git a/src/imap/command/examined.rs b/src/imap/command/examined.rs index 1740b39..7de94f4 100644 --- a/src/imap/command/examined.rs +++ b/src/imap/command/examined.rs @@ -1,56 +1,60 @@ use std::sync::Arc; use anyhow::Result; -use boitalettres::proto::Request; -use boitalettres::proto::Response; -use imap_codec::types::command::{CommandBody, SearchKey}; -use imap_codec::types::core::{Charset, NonZeroBytes}; -use imap_codec::types::datetime::MyDateTime; -use imap_codec::types::fetch_attributes::MacroOrFetchAttributes; -use imap_codec::types::flag::Flag; -use imap_codec::types::mailbox::Mailbox as MailboxCodec; -use imap_codec::types::response::Code; -use imap_codec::types::sequence::SequenceSet; +use imap_codec::imap_types::command::{Command, CommandBody}; +use imap_codec::imap_types::core::Charset; +use imap_codec::imap_types::fetch::MacroOrMessageDataItemNames; +use imap_codec::imap_types::search::SearchKey; +use imap_codec::imap_types::sequence::SequenceSet; -use crate::imap::command::authenticated; +use crate::imap::command::{anystate, authenticated}; use crate::imap::flow; use crate::imap::mailbox_view::MailboxView; +use crate::imap::response::Response; use crate::mail::user::User; pub struct ExaminedContext<'a> { - pub req: &'a Request, + pub req: &'a Command<'static>, pub user: &'a Arc<User>, pub mailbox: &'a mut MailboxView, } -pub async fn dispatch(ctx: ExaminedContext<'_>) -> Result<(Response, flow::Transition)> { - match &ctx.req.command.body { - // CLOSE in examined state is not the same as in selected state - // (in selected state it also does an EXPUNGE, here it doesn't) +pub async fn dispatch(ctx: ExaminedContext<'_>) -> Result<(Response<'static>, flow::Transition)> { + match &ctx.req.body { + // Any State + // noop is specific to this state + CommandBody::Capability => anystate::capability(ctx.req.tag.clone()), + CommandBody::Logout => anystate::logout(), + + // Specific to the EXAMINE state (specialization of the SELECTED state) + // ~3 commands -> close, fetch, search + NOOP CommandBody::Close => ctx.close().await, CommandBody::Fetch { sequence_set, - attributes, + macro_or_item_names, uid, - } => ctx.fetch(sequence_set, attributes, uid).await, + } => ctx.fetch(sequence_set, macro_or_item_names, uid).await, CommandBody::Search { charset, criteria, uid, } => ctx.search(charset, criteria, uid).await, - CommandBody::Noop => ctx.noop().await, - CommandBody::Append { - mailbox, - flags, - date, - message, - } => ctx.append(mailbox, flags, date, message).await, + CommandBody::Noop | CommandBody::Check => ctx.noop().await, + CommandBody::Expunge { .. } | CommandBody::Store { .. } => Ok(( + Response::build() + .to_req(ctx.req) + .message("Forbidden command: can't write in read-only mode (EXAMINE)") + .bad()?, + flow::Transition::None, + )), + + // In examined mode, we fallback to authenticated when needed _ => { - let ctx = authenticated::AuthenticatedContext { + authenticated::dispatch(authenticated::AuthenticatedContext { req: ctx.req, user: ctx.user, - }; - authenticated::dispatch(ctx).await + }) + .await } } } @@ -58,71 +62,69 @@ pub async fn dispatch(ctx: ExaminedContext<'_>) -> Result<(Response, flow::Trans // --- PRIVATE --- impl<'a> ExaminedContext<'a> { - async fn close(self) -> Result<(Response, flow::Transition)> { - Ok((Response::ok("CLOSE completed")?, flow::Transition::Unselect)) + /// CLOSE in examined state is not the same as in selected state + /// (in selected state it also does an EXPUNGE, here it doesn't) + async fn close(self) -> Result<(Response<'static>, flow::Transition)> { + Ok(( + Response::build() + .to_req(self.req) + .message("CLOSE completed") + .ok()?, + flow::Transition::Unselect, + )) } pub async fn fetch( self, sequence_set: &SequenceSet, - attributes: &MacroOrFetchAttributes, + attributes: &'a MacroOrMessageDataItemNames<'static>, uid: &bool, - ) -> Result<(Response, flow::Transition)> { + ) -> Result<(Response<'static>, flow::Transition)> { match self.mailbox.fetch(sequence_set, attributes, uid).await { Ok(resp) => Ok(( - Response::ok("FETCH completed")?.with_body(resp), + Response::build() + .to_req(self.req) + .message("FETCH completed") + .set_body(resp) + .ok()?, + flow::Transition::None, + )), + Err(e) => Ok(( + Response::build() + .to_req(self.req) + .message(e.to_string()) + .no()?, flow::Transition::None, )), - Err(e) => Ok((Response::no(&e.to_string())?, flow::Transition::None)), } } pub async fn search( self, - _charset: &Option<Charset>, - _criteria: &SearchKey, + _charset: &Option<Charset<'a>>, + _criteria: &SearchKey<'a>, _uid: &bool, - ) -> Result<(Response, flow::Transition)> { - Ok((Response::bad("Not implemented")?, flow::Transition::None)) + ) -> Result<(Response<'static>, flow::Transition)> { + Ok(( + Response::build() + .to_req(self.req) + .message("Not implemented") + .bad()?, + flow::Transition::None, + )) } - pub async fn noop(self) -> Result<(Response, flow::Transition)> { + pub async fn noop(self) -> Result<(Response<'static>, flow::Transition)> { self.mailbox.mailbox.force_sync().await?; let updates = self.mailbox.update().await?; Ok(( - Response::ok("NOOP completed.")?.with_body(updates), + Response::build() + .to_req(self.req) + .message("NOOP completed.") + .set_body(updates) + .ok()?, flow::Transition::None, )) } - - async fn append( - self, - mailbox: &MailboxCodec, - flags: &[Flag], - date: &Option<MyDateTime>, - message: &NonZeroBytes, - ) -> Result<(Response, flow::Transition)> { - let ctx2 = authenticated::AuthenticatedContext { - req: self.req, - user: self.user, - }; - - match ctx2.append_internal(mailbox, flags, date, message).await { - Ok((mb, uidvalidity, uid)) => { - let resp = Response::ok("APPEND completed")?.with_extra_code(Code::Other( - "APPENDUID".try_into().unwrap(), - Some(format!("{} {}", uidvalidity, uid)), - )); - - if Arc::ptr_eq(&mb, &self.mailbox.mailbox) { - let data = self.mailbox.update().await?; - Ok((resp.with_body(data), flow::Transition::None)) - } else { - Ok((resp, flow::Transition::None)) - } - } - Err(e) => Ok((Response::no(&e.to_string())?, flow::Transition::None)), - } - } } diff --git a/src/imap/command/mod.rs b/src/imap/command/mod.rs index 0b7e576..dc95746 100644 --- a/src/imap/command/mod.rs +++ b/src/imap/command/mod.rs @@ -1,4 +1,21 @@ pub mod anonymous; +pub mod anystate; pub mod authenticated; pub mod examined; pub mod selected; + +use crate::mail::user::INBOX; +use imap_codec::imap_types::mailbox::Mailbox as MailboxCodec; + +/// Convert an IMAP mailbox name/identifier representation +/// to an utf-8 string that is used internally in Aerogramme +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())?), + } + } +} diff --git a/src/imap/command/selected.rs b/src/imap/command/selected.rs index 90a00ee..220a952 100644 --- a/src/imap/command/selected.rs +++ b/src/imap/command/selected.rs @@ -1,31 +1,50 @@ use std::sync::Arc; use anyhow::Result; -use boitalettres::proto::Request; -use boitalettres::proto::Response; -use imap_codec::types::command::CommandBody; -use imap_codec::types::flag::{Flag, StoreResponse, StoreType}; -use imap_codec::types::mailbox::Mailbox as MailboxCodec; -use imap_codec::types::response::Code; -use imap_codec::types::sequence::SequenceSet; - -use crate::imap::command::examined; +use imap_codec::imap_types::command::{Command, CommandBody}; +use imap_codec::imap_types::core::Charset; +use imap_codec::imap_types::fetch::MacroOrMessageDataItemNames; +use imap_codec::imap_types::flag::{Flag, StoreResponse, StoreType}; +use imap_codec::imap_types::mailbox::Mailbox as MailboxCodec; +use imap_codec::imap_types::response::{Code, CodeOther}; +use imap_codec::imap_types::search::SearchKey; +use imap_codec::imap_types::sequence::SequenceSet; + +use crate::imap::command::{anystate, authenticated, MailboxName}; use crate::imap::flow; use crate::imap::mailbox_view::MailboxView; +use crate::imap::response::Response; use crate::mail::user::User; pub struct SelectedContext<'a> { - pub req: &'a Request, + pub req: &'a Command<'static>, pub user: &'a Arc<User>, pub mailbox: &'a mut MailboxView, } -pub async fn dispatch(ctx: SelectedContext<'_>) -> Result<(Response, flow::Transition)> { - match &ctx.req.command.body { - // Only write commands here, read commands are handled in - // `examined.rs` +pub async fn dispatch<'a>( + ctx: SelectedContext<'a>, +) -> Result<(Response<'static>, flow::Transition)> { + match &ctx.req.body { + // Any State + // noop is specific to this state + CommandBody::Capability => anystate::capability(ctx.req.tag.clone()), + CommandBody::Logout => anystate::logout(), + + // Specific to this state (7 commands + NOOP) CommandBody::Close => ctx.close().await, + CommandBody::Noop | CommandBody::Check => ctx.noop().await, + CommandBody::Fetch { + sequence_set, + macro_or_item_names, + uid, + } => ctx.fetch(sequence_set, macro_or_item_names, uid).await, + CommandBody::Search { + charset, + criteria, + uid, + } => ctx.search(charset, criteria, uid).await, CommandBody::Expunge => ctx.expunge().await, CommandBody::Store { sequence_set, @@ -39,13 +58,14 @@ pub async fn dispatch(ctx: SelectedContext<'_>) -> Result<(Response, flow::Trans mailbox, uid, } => ctx.copy(sequence_set, mailbox, uid).await, + + // In selected mode, we fallback to authenticated when needed _ => { - let ctx = examined::ExaminedContext { + authenticated::dispatch(authenticated::AuthenticatedContext { req: ctx.req, user: ctx.user, - mailbox: ctx.mailbox, - }; - examined::dispatch(ctx).await + }) + .await } } } @@ -53,18 +73,81 @@ pub async fn dispatch(ctx: SelectedContext<'_>) -> Result<(Response, flow::Trans // --- PRIVATE --- impl<'a> SelectedContext<'a> { - async fn close(self) -> Result<(Response, flow::Transition)> { + async fn close(self) -> Result<(Response<'static>, flow::Transition)> { // We expunge messages, // but we don't send the untagged EXPUNGE responses + let tag = self.req.tag.clone(); self.expunge().await?; - Ok((Response::ok("CLOSE completed")?, flow::Transition::Unselect)) + Ok(( + Response::build().tag(tag).message("CLOSE completed").ok()?, + flow::Transition::Unselect, + )) + } + + pub async fn fetch( + self, + sequence_set: &SequenceSet, + attributes: &'a MacroOrMessageDataItemNames<'static>, + uid: &bool, + ) -> Result<(Response<'static>, flow::Transition)> { + match self.mailbox.fetch(sequence_set, attributes, uid).await { + Ok(resp) => Ok(( + Response::build() + .to_req(self.req) + .message("FETCH completed") + .set_body(resp) + .ok()?, + flow::Transition::None, + )), + Err(e) => Ok(( + Response::build() + .to_req(self.req) + .message(e.to_string()) + .no()?, + flow::Transition::None, + )), + } + } + + pub async fn search( + self, + _charset: &Option<Charset<'a>>, + _criteria: &SearchKey<'a>, + _uid: &bool, + ) -> Result<(Response<'static>, flow::Transition)> { + Ok(( + Response::build() + .to_req(self.req) + .message("Not implemented") + .bad()?, + flow::Transition::None, + )) } - async fn expunge(self) -> Result<(Response, flow::Transition)> { + pub async fn noop(self) -> Result<(Response<'static>, flow::Transition)> { + self.mailbox.mailbox.force_sync().await?; + + let updates = self.mailbox.update().await?; + Ok(( + Response::build() + .to_req(self.req) + .message("NOOP completed.") + .set_body(updates) + .ok()?, + flow::Transition::None, + )) + } + + async fn expunge(self) -> Result<(Response<'static>, flow::Transition)> { + let tag = self.req.tag.clone(); let data = self.mailbox.expunge().await?; Ok(( - Response::ok("EXPUNGE completed")?.with_body(data), + Response::build() + .tag(tag) + .message("EXPUNGE completed") + .set_body(data) + .ok()?, flow::Transition::None, )) } @@ -74,16 +157,20 @@ impl<'a> SelectedContext<'a> { sequence_set: &SequenceSet, kind: &StoreType, response: &StoreResponse, - flags: &[Flag], + flags: &[Flag<'a>], uid: &bool, - ) -> Result<(Response, flow::Transition)> { + ) -> Result<(Response<'static>, flow::Transition)> { let data = self .mailbox .store(sequence_set, kind, response, flags, uid) .await?; Ok(( - Response::ok("STORE completed")?.with_body(data), + Response::build() + .to_req(self.req) + .message("STORE completed") + .set_body(data) + .ok()?, flow::Transition::None, )) } @@ -91,18 +178,21 @@ impl<'a> SelectedContext<'a> { async fn copy( self, sequence_set: &SequenceSet, - mailbox: &MailboxCodec, + mailbox: &MailboxCodec<'a>, uid: &bool, - ) -> Result<(Response, flow::Transition)> { - let name = String::try_from(mailbox.clone())?; + ) -> Result<(Response<'static>, flow::Transition)> { + let name: &str = MailboxName(mailbox).try_into()?; let mb_opt = self.user.open_mailbox(&name).await?; let mb = match mb_opt { Some(mb) => mb, None => { return Ok(( - Response::no("Destination mailbox does not exist")? - .with_extra_code(Code::TryCreate), + Response::build() + .to_req(self.req) + .message("Destination mailbox does not exist") + .code(Code::TryCreate) + .no()?, flow::Transition::None, )) } @@ -126,10 +216,13 @@ impl<'a> SelectedContext<'a> { ); Ok(( - Response::ok("COPY completed")?.with_extra_code(Code::Other( - "COPYUID".try_into().unwrap(), - Some(copyuid_str), - )), + Response::build() + .to_req(self.req) + .message("COPY completed") + .code(Code::Other(CodeOther::unvalidated( + format!("COPYUID {}", copyuid_str).into_bytes(), + ))) + .ok()?, flow::Transition::None, )) } |