aboutsummaryrefslogtreecommitdiff
path: root/src/imap/command/authenticated.rs
diff options
context:
space:
mode:
authorQuentin <quentin@dufour.io>2024-01-02 22:44:29 +0000
committerQuentin <quentin@dufour.io>2024-01-02 22:44:29 +0000
commitb9a0c1e6eced036eb71e8221a4f236f72832fec2 (patch)
treec498a7a2a5833f2c6f27d4ba97894747f9d454c0 /src/imap/command/authenticated.rs
parent6ff3c6f71efd802da422a371e6168ae528fb2ddc (diff)
parentc9a33c080d39d4a2b269e3c8f166a708b6606da5 (diff)
downloadaerogramme-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/authenticated.rs')
-rw-r--r--src/imap/command/authenticated.rs400
1 files changed, 267 insertions, 133 deletions
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)));
}
}