Import upstream v0.16.22, stripped

Upstream commit: 474dd0229cb20cf513036619781ed97bd8073c3f
Enterprise-only files removed or emptied: 63
Enterprise-only snippets removed: 117 in 50 files
Dangling module declarations removed: 5
Cargo edits turning enterprise off: 14
Verification: clean
Enterprise feature gates left for rebuilt features: 19 in 18 files

Produced by tools/fork/strip.py. The full report is in docs/fork/strip-reports/ on main.
This commit is contained in:
2026-09-18 10:21:56 -07:00
commit 7dae9b29fd
1650 changed files with 485521 additions and 0 deletions
+288
View File
@@ -0,0 +1,288 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
use super::{Command, ResponseCode, SerializeResponse, Session, State};
use common::{
KV_RATE_LIMIT_IMAP,
network::{SessionResult, SessionStream},
};
use imap_proto::receiver::{self, Request};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use trc::{AddContext, SecurityEvent};
use types::{collection::Collection, field::SieveField};
impl<T: SessionStream> Session<T> {
pub async fn ingest(&mut self, bytes: &[u8]) -> SessionResult {
let mut bytes = bytes.iter();
let mut requests = Vec::with_capacity(2);
let mut needs_literal = None;
loop {
match self.receiver.parse(&mut bytes) {
Ok(request) => match self.validate_request(request).await {
Ok(request) => {
requests.push(request);
}
Err(err) => {
let mut disconnect = err.must_disconnect();
if let Err(err) = self.write_error(err).await {
trc::error!(err.span_id(self.session_id));
disconnect = true;
}
if disconnect {
return SessionResult::Close;
}
}
},
Err(receiver::Error::NeedsMoreData) => {
break;
}
Err(receiver::Error::NeedsLiteral { size }) => {
needs_literal = size.into();
break;
}
Err(receiver::Error::Error { response }) => {
// Check for port scanners
if matches!(
(&self.state, response.key(trc::Key::Code)),
(
State::NotAuthenticated { .. },
Some(trc::Value::String(v))
) if v == "PARSE"
) {
match self.server.is_scanner_fail2banned(self.remote_addr).await {
Ok(true) => {
trc::event!(
Security(SecurityEvent::ScanBan),
SpanId = self.session_id,
RemoteIp = self.remote_addr,
Reason = "Invalid ManageSieve command",
);
return SessionResult::Close;
}
Ok(false) => {}
Err(err) => {
trc::error!(
err.span_id(self.session_id)
.details("Failed to check for fail2ban")
);
}
}
}
if let Err(err) = self.write_error(response).await {
trc::error!(err.span_id(self.session_id));
return SessionResult::Close;
}
break;
}
}
}
for request in requests {
let command = request.command;
match match command {
Command::ListScripts => self.handle_listscripts().await,
Command::PutScript => self.handle_putscript(request).await,
Command::SetActive => self.handle_setactive(request).await,
Command::GetScript => self.handle_getscript(request).await,
Command::DeleteScript => self.handle_deletescript(request).await,
Command::RenameScript => self.handle_renamescript(request).await,
Command::CheckScript => self.handle_checkscript(request).await,
Command::HaveSpace => self.handle_havespace(request).await,
Command::Capability => self.handle_capability("").await,
Command::Authenticate => Box::pin(self.handle_authenticate(request)).await,
Command::StartTls => self.handle_start_tls().await,
Command::Logout => self.handle_logout().await,
Command::Noop => self.handle_noop(request).await,
Command::Unauthenticate => self.handle_unauthenticate().await,
} {
Ok(response) => {
if let Err(err) = self.write(&response).await {
trc::error!(err.span_id(self.session_id));
return SessionResult::Close;
}
match command {
Command::Logout => return SessionResult::Close,
Command::StartTls => return SessionResult::UpgradeTls,
_ => (),
}
}
Err(err) => {
let mut disconnect = err.must_disconnect();
if let Err(err) = self.write_error(err).await {
trc::error!(err.span_id(self.session_id));
disconnect = true;
}
if disconnect {
return SessionResult::Close;
}
}
}
}
if let Some(needs_literal) = needs_literal
&& let Err(err) = self
.write(format!("OK Ready for {} bytes.\r\n", needs_literal).as_bytes())
.await
{
trc::error!(err.span_id(self.session_id));
return SessionResult::Close;
}
SessionResult::Continue
}
async fn validate_request(&self, command: Request<Command>) -> trc::Result<Request<Command>> {
match &command.command {
Command::Capability | Command::Logout | Command::Noop => Ok(command),
Command::Authenticate => {
if let State::NotAuthenticated { .. } = &self.state {
if self.stream.is_tls() || self.server.core.imap.allow_plain_auth {
Ok(command)
} else {
Err(trc::ManageSieveEvent::Error
.into_err()
.code(ResponseCode::EncryptNeeded)
.details("Cannot authenticate over plain-text."))
}
} else {
Err(trc::ManageSieveEvent::Error
.into_err()
.details("Already authenticated."))
}
}
Command::StartTls => {
if !self.stream.is_tls() {
Ok(command)
} else {
Err(trc::ManageSieveEvent::Error
.into_err()
.details("Already in TLS mode."))
}
}
Command::HaveSpace
| Command::PutScript
| Command::ListScripts
| Command::SetActive
| Command::GetScript
| Command::DeleteScript
| Command::RenameScript
| Command::CheckScript
| Command::Unauthenticate => {
if let State::Authenticated { access_token, .. } = &self.state {
if let Some(rate) = &self.server.core.imap.rate_requests {
if self
.server
.in_memory_store()
.is_rate_allowed(
KV_RATE_LIMIT_IMAP,
&access_token.account_id().to_be_bytes(),
rate,
true,
)
.await
.caused_by(trc::location!())?
.is_none()
{
Ok(command)
} else {
Err(trc::LimitEvent::TooManyRequests
.into_err()
.code(ResponseCode::TryLater))
}
} else {
Ok(command)
}
} else {
Err(trc::ManageSieveEvent::Error
.into_err()
.details("Not authenticated."))
}
}
}
}
}
impl<T: AsyncWrite + AsyncRead + Unpin> Session<T> {
#[inline(always)]
pub async fn write(&mut self, bytes: &[u8]) -> trc::Result<()> {
trc::event!(
ManageSieve(trc::ManageSieveEvent::RawOutput),
SpanId = self.session_id,
Size = bytes.len(),
Contents = trc::Value::from_maybe_string(bytes),
);
self.stream.write_all(bytes).await.map_err(|err| {
trc::NetworkEvent::WriteError
.into_err()
.reason(err)
.caused_by(trc::location!())
})?;
self.stream.flush().await.map_err(|err| {
trc::NetworkEvent::FlushError
.into_err()
.reason(err)
.caused_by(trc::location!())
})?;
Ok(())
}
pub async fn write_error(&mut self, error: trc::Error) -> trc::Result<()> {
let bytes = error.serialize();
trc::error!(error.span_id(self.session_id));
self.write(&bytes).await
}
#[inline(always)]
pub async fn read(&mut self, bytes: &mut [u8]) -> trc::Result<usize> {
let len = self.stream.read(bytes).await.map_err(|err| {
trc::NetworkEvent::ReadError
.into_err()
.reason(err)
.caused_by(trc::location!())
})?;
trc::event!(
ManageSieve(trc::ManageSieveEvent::RawInput),
SpanId = self.session_id,
Size = len,
Contents = trc::Value::from_maybe_string(bytes.get(0..len).unwrap_or_default()),
);
Ok(len)
}
}
impl<T: AsyncWrite + AsyncRead> Session<T> {
pub async fn get_script_id(&self, account_id: u32, name: &str) -> trc::Result<u32> {
self.server
.document_ids_matching(
account_id,
Collection::SieveScript,
SieveField::Name,
name.to_lowercase().as_bytes(),
)
.await
.caused_by(trc::location!())
.and_then(|results| {
results.min().ok_or_else(|| {
trc::ManageSieveEvent::Error
.into_err()
.code(ResponseCode::NonExistent)
.reason("There is no script by that name")
})
})
}
}
+314
View File
@@ -0,0 +1,314 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
pub mod client;
pub mod session;
use std::{borrow::Cow, net::IpAddr, sync::Arc};
use common::{
Inner, Server,
auth::AccessToken,
network::{ServerInstance, limiter::InFlight},
};
use compact_str::CompactString;
use imap_proto::receiver::{CommandParser, Receiver};
use tokio::io::{AsyncRead, AsyncWrite};
pub struct Session<T: AsyncRead + AsyncWrite> {
pub server: Server,
pub instance: Arc<ServerInstance>,
pub receiver: Receiver<Command>,
pub state: State,
pub remote_addr: IpAddr,
pub stream: T,
pub session_id: u64,
pub in_flight: InFlight,
}
pub enum State {
NotAuthenticated {
auth_failures: u32,
},
Authenticated {
access_token: AccessToken,
in_flight: Option<InFlight>,
},
}
impl State {
pub fn access_token(&self) -> &AccessToken {
match self {
State::Authenticated { access_token, .. } => access_token,
State::NotAuthenticated { .. } => unreachable!("Not authenticated"),
}
}
}
#[derive(Clone)]
pub struct ManageSieveSessionManager {
pub inner: Arc<Inner>,
}
impl ManageSieveSessionManager {
pub fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Command {
Authenticate,
StartTls,
Logout,
Capability,
HaveSpace,
PutScript,
ListScripts,
SetActive,
GetScript,
DeleteScript,
RenameScript,
CheckScript,
#[default]
Noop,
Unauthenticate,
}
impl CommandParser for Command {
fn parse(value: &[u8], _is_uid: bool) -> Option<Self> {
match value {
b"AUTHENTICATE" => Some(Command::Authenticate),
b"STARTTLS" => Some(Command::StartTls),
b"LOGOUT" => Some(Command::Logout),
b"CAPABILITY" => Some(Command::Capability),
b"HAVESPACE" => Some(Command::HaveSpace),
b"PUTSCRIPT" => Some(Command::PutScript),
b"LISTSCRIPTS" => Some(Command::ListScripts),
b"SETACTIVE" => Some(Command::SetActive),
b"GETSCRIPT" => Some(Command::GetScript),
b"DELETESCRIPT" => Some(Command::DeleteScript),
b"RENAMESCRIPT" => Some(Command::RenameScript),
b"CHECKSCRIPT" => Some(Command::CheckScript),
b"NOOP" => Some(Command::Noop),
b"UNAUTHENTICATE" => Some(Command::Unauthenticate),
_ => None,
}
}
fn tokenize_brackets(&self) -> bool {
false
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatusResponse {
pub code: Option<ResponseCode>,
pub message: Cow<'static, str>,
pub rtype: ResponseType,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResponseType {
Ok,
No,
Bye,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResponseCode {
AuthTooWeak,
EncryptNeeded,
Quota,
QuotaMaxScripts,
QuotaMaxSize,
Referral,
Sasl,
TransitionNeeded,
TryLater,
Active,
NonExistent,
AlreadyExists,
Tag(String),
Warnings,
}
impl ResponseCode {
pub fn serialize(&self, buf: &mut Vec<u8>) {
buf.extend_from_slice(match self {
ResponseCode::AuthTooWeak => b"AUTH-TOO-WEAK",
ResponseCode::EncryptNeeded => b"ENCRYPT-NEEDED",
ResponseCode::Quota => b"QUOTA",
ResponseCode::QuotaMaxScripts => b"QUOTA/MAXSCRIPTS",
ResponseCode::QuotaMaxSize => b"QUOTA/MAXSIZE",
ResponseCode::Referral => b"REFERRAL",
ResponseCode::Sasl => b"SASL",
ResponseCode::TransitionNeeded => b"TRANSITION-NEEDED",
ResponseCode::TryLater => b"TRYLATER",
ResponseCode::Active => b"ACTIVE",
ResponseCode::NonExistent => b"NONEXISTENT",
ResponseCode::AlreadyExists => b"ALREADYEXISTS",
ResponseCode::Tag(tag) => {
buf.extend_from_slice(b"TAG {");
buf.extend_from_slice(tag.len().to_string().as_bytes());
buf.extend_from_slice(b"}\r\n");
buf.extend_from_slice(tag.as_bytes());
return;
}
ResponseCode::Warnings => b"WARNINGS",
});
}
pub fn as_str(&self) -> &'static str {
match self {
ResponseCode::AuthTooWeak => "AUTH-TOO-WEAK",
ResponseCode::EncryptNeeded => "ENCRYPT-NEEDED",
ResponseCode::Quota => "QUOTA",
ResponseCode::QuotaMaxScripts => "QUOTA/MAXSCRIPTS",
ResponseCode::QuotaMaxSize => "QUOTA/MAXSIZE",
ResponseCode::Referral => "REFERRAL",
ResponseCode::Sasl => "SASL",
ResponseCode::TransitionNeeded => "TRANSITION-NEEDED",
ResponseCode::TryLater => "TRYLATER",
ResponseCode::Active => "ACTIVE",
ResponseCode::NonExistent => "NONEXISTENT",
ResponseCode::AlreadyExists => "ALREADYEXISTS",
ResponseCode::Tag(_) => "TAG",
ResponseCode::Warnings => "WARNINGS",
}
}
}
impl ResponseType {
pub fn serialize(&self, buf: &mut Vec<u8>) {
buf.extend_from_slice(self.as_str().as_bytes());
}
pub fn as_str(&self) -> &'static str {
match self {
ResponseType::Ok => "OK",
ResponseType::No => "NO",
ResponseType::Bye => "BYE",
}
}
}
impl StatusResponse {
pub fn serialize(self, mut buf: Vec<u8>) -> Vec<u8> {
self.rtype.serialize(&mut buf);
if let Some(code) = &self.code {
buf.extend_from_slice(b" (");
code.serialize(&mut buf);
buf.push(b')');
}
if !self.message.is_empty() {
buf.extend_from_slice(b" \"");
for ch in self.message.as_bytes() {
if b"\"\\".contains(ch) {
buf.push(b'\\');
}
buf.push(*ch);
}
buf.push(b'\"');
}
buf.extend_from_slice(b"\r\n");
buf
}
pub fn into_bytes(self) -> Vec<u8> {
self.serialize(Vec::with_capacity(16))
}
pub fn with_code(mut self, code: ResponseCode) -> Self {
self.code = Some(code);
self
}
pub fn no(message: impl Into<Cow<'static, str>>) -> Self {
StatusResponse {
code: None,
message: message.into(),
rtype: ResponseType::No,
}
}
pub fn ok(message: impl Into<Cow<'static, str>>) -> Self {
StatusResponse {
code: None,
message: message.into(),
rtype: ResponseType::Ok,
}
}
pub fn bye(message: impl Into<Cow<'static, str>>) -> Self {
StatusResponse {
code: None,
message: message.into(),
rtype: ResponseType::Bye,
}
}
pub fn database_failure() -> Self {
StatusResponse {
code: Some(ResponseCode::TryLater),
message: Cow::Borrowed("Database failure"),
rtype: ResponseType::No,
}
}
}
pub trait SerializeResponse {
fn serialize(&self) -> Vec<u8>;
}
impl SerializeResponse for trc::Error {
fn serialize(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(64);
buf.extend_from_slice(self.value_as_str(trc::Key::Type).unwrap_or("NO").as_bytes());
if let Some(code) = self
.value_as_str(trc::Key::Code)
.or_else(|| match self.as_ref() {
trc::EventType::Store(trc::StoreEvent::NotFound) => {
Some(ResponseCode::NonExistent.as_str())
}
trc::EventType::Store(_) => Some(ResponseCode::TryLater.as_str()),
trc::EventType::Limit(trc::LimitEvent::Quota) => Some(ResponseCode::Quota.as_str()),
trc::EventType::Limit(_) => Some(ResponseCode::TryLater.as_str()),
_ => None,
})
{
buf.extend_from_slice(b" (");
buf.extend_from_slice(code.as_bytes());
buf.push(b')');
}
let message = self
.value_as_str(trc::Key::Details)
.unwrap_or_else(|| self.as_ref().message());
buf.extend_from_slice(b" \"");
for ch in message.as_bytes() {
if b"\"\\".contains(ch) {
buf.push(b'\\');
}
buf.push(*ch);
}
buf.push(b'\"');
buf.extend_from_slice(b"\r\n");
buf
}
}
impl From<ResponseCode> for trc::Value {
fn from(value: ResponseCode) -> Self {
trc::Value::String(CompactString::const_new(value.as_str()))
}
}
impl From<ResponseType> for trc::Value {
fn from(value: ResponseType) -> Self {
trc::Value::String(CompactString::const_new(value.as_str()))
}
}
+151
View File
@@ -0,0 +1,151 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
use super::{ManageSieveSessionManager, Session, State};
use crate::SERVER_GREETING;
use common::{
BuildServer,
network::{SessionData, SessionManager, SessionResult, SessionStream},
};
use imap_proto::receiver::{self, Receiver};
use tokio_rustls::server::TlsStream;
impl SessionManager for ManageSieveSessionManager {
#[allow(clippy::manual_async_fn)]
fn handle<T: SessionStream>(
self,
session: SessionData<T>,
) -> impl std::future::Future<Output = ()> + Send {
async move {
// Create session
let server = self.inner.build_server();
let mut session = Session {
receiver: Receiver::with_max_request_size(server.core.imap.max_request_size)
.with_start_state(receiver::State::Command { is_uid: false }),
server,
instance: session.instance,
state: State::NotAuthenticated { auth_failures: 0 },
session_id: session.session_id,
stream: session.stream,
in_flight: session.in_flight,
remote_addr: session.remote_ip,
};
if session
.write(&session.handle_capability(SERVER_GREETING).await.unwrap())
.await
.is_ok()
&& session.handle_conn().await
&& session.instance.acceptor.is_tls()
&& let Ok(mut session) = session.into_tls().await
{
let _ = session
.write(&session.handle_capability(SERVER_GREETING).await.unwrap())
.await;
session.handle_conn().await;
}
}
}
#[allow(clippy::manual_async_fn)]
fn shutdown(&self) -> impl std::future::Future<Output = ()> + Send {
async {}
}
}
impl<T: SessionStream> Session<T> {
pub async fn handle_conn(&mut self) -> bool {
let mut buf = vec![0; 8192];
let mut shutdown_rx = self.instance.shutdown_rx.clone();
loop {
tokio::select! {
result = tokio::time::timeout(
if !matches!(self.state, State::NotAuthenticated {..}) {
self.server.core.imap.timeout_auth
} else {
self.server.core.imap.timeout_unauth
},
self.read(&mut buf)) => {
match result {
Ok(Ok(bytes_read)) => {
if bytes_read > 0 {
match self.ingest(&buf[..bytes_read]).await {
SessionResult::Continue => (),
SessionResult::UpgradeTls => {
return true;
}
SessionResult::Close => {
break;
}
}
} else {
trc::event!(
Network(trc::NetworkEvent::Closed),
SpanId = self.session_id,
CausedBy = trc::location!()
);
break;
}
}
Ok(Err(err)) => {
trc::event!(
Network(trc::NetworkEvent::ReadError),
SpanId = self.session_id,
Reason = err,
CausedBy = trc::location!()
);
break;
}
Err(_) => {
trc::event!(
Network(trc::NetworkEvent::Timeout),
SpanId = self.session_id,
CausedBy = trc::location!()
);
self
.write(b"BYE \"Connection timed out.\"\r\n")
.await
.ok();
break;
}
}
},
_ = shutdown_rx.changed() => {
trc::event!(
Network(trc::NetworkEvent::Closed),
SpanId = self.session_id,
Reason = "Server shutting down",
CausedBy = trc::location!()
);
self.write(b"BYE \"Server shutting down.\"\r\n").await.ok();
break;
}
};
}
false
}
pub async fn into_tls(self) -> Result<Session<TlsStream<T>>, ()> {
let receiver = Receiver::with_max_request_size(self.server.core.imap.max_request_size)
.with_start_state(receiver::State::Command { is_uid: false });
Ok(Session {
stream: self
.instance
.tls_accept(self.stream, self.session_id)
.await?,
state: self.state,
instance: self.instance,
in_flight: self.in_flight,
session_id: self.session_id,
server: self.server,
receiver,
remote_addr: self.remote_addr,
})
}
}
+144
View File
@@ -0,0 +1,144 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
#![warn(clippy::large_futures)]
pub mod core;
pub mod op;
static SERVER_GREETING: &str = "Stalwart ManageSieve at your service.";
#[cfg(test)]
mod tests {
use imap_proto::receiver::{Error, Receiver, Request, State, Token};
use crate::core::Command;
#[test]
fn receiver_parse_managesieve() {
let mut receiver = Receiver::new().with_start_state(State::Command { is_uid: false });
for (frames, expected_requests) in [
(
vec!["Authenticate \"DIGEST-MD5\"\r\n"],
vec![Request {
tag: "".into(),
command: Command::Authenticate,
tokens: vec![Token::Argument(b"DIGEST-MD5".to_vec())],
}],
),
(
vec![
" AUTHENTICATE \"GSSAPI\" {56+}\r\n",
"cnNwYXV0aD1lYTQwZjYwMzM1YzQyN2I1NTI3Yjg0ZGJhYmNkZmZmZA==\r\n",
],
vec![Request {
tag: "".into(),
command: Command::Authenticate,
tokens: vec![
Token::Argument(b"GSSAPI".to_vec()),
Token::Argument(
b"cnNwYXV0aD1lYTQwZjYwMzM1YzQyN2I1NTI3Yjg0ZGJhYmNkZmZmZA==".to_vec(),
),
],
}],
),
(
vec!["Authenticate \"PLAIN\" \"QJIrweAPyo6Q1T9xu\"\r\n"],
vec![Request {
tag: "".into(),
command: Command::Authenticate,
tokens: vec![
Token::Argument(b"PLAIN".to_vec()),
Token::Argument(b"QJIrweAPyo6Q1T9xu".to_vec()),
],
}],
),
(
vec!["StartTls\r\n"],
vec![Request {
tag: "".into(),
command: Command::StartTls,
tokens: vec![],
}],
),
(
vec!["HAVESPACE \"myscript\" 999999\r\n"],
vec![Request {
tag: "".into(),
command: Command::HaveSpace,
tokens: vec![
Token::Argument(b"myscript".to_vec()),
Token::Argument(b"999999".to_vec()),
],
}],
),
(
vec![
"Putscript \"foo\" {31+}\r\n",
"#comment\r\n",
"InvalidSieveCommand\r\n\r\n",
],
vec![Request {
tag: "".into(),
command: Command::PutScript,
tokens: vec![
Token::Argument(b"foo".to_vec()),
Token::Argument(b"#comment\r\nInvalidSieveCommand\r\n".to_vec()),
],
}],
),
(
vec!["Listscripts\r\n"],
vec![Request {
tag: "".into(),
command: Command::ListScripts,
tokens: vec![],
}],
),
(
vec!["Setactive \"baz\"\r\n"],
vec![Request {
tag: "".into(),
command: Command::SetActive,
tokens: vec![Token::Argument(b"baz".to_vec())],
}],
),
(
vec!["Renamescript \"foo\" \"bar\"\r\n"],
vec![Request {
tag: "".into(),
command: Command::RenameScript,
tokens: vec![
Token::Argument(b"foo".to_vec()),
Token::Argument(b"bar".to_vec()),
],
}],
),
(
vec!["NOOP \"STARTTLS-SYNC-42\"\r\n"],
vec![Request {
tag: "".into(),
command: Command::Noop,
tokens: vec![Token::Argument(b"STARTTLS-SYNC-42".to_vec())],
}],
),
] {
let mut requests = Vec::new();
for frame in &frames {
let mut bytes = frame.as_bytes().iter();
loop {
match receiver.parse(&mut bytes) {
Ok(request) => requests.push(request),
Err(Error::NeedsMoreData | Error::NeedsLiteral { .. }) => break,
Err(err) => panic!("{:?} for frames {:#?}", err, frames),
}
}
}
assert_eq!(requests, expected_requests, "{:#?}", frames);
}
}
}
+126
View File
@@ -0,0 +1,126 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
use crate::core::{Command, Session, State, StatusResponse};
use common::{
auth::AuthRequest,
network::{SessionStream, limiter::LimiterResult},
};
use directory::Credentials;
use imap_proto::{
protocol::authenticate::Mechanism,
receiver::{self, Request},
};
use mail_parser::decoders::base64::base64_decode;
use registry::schema::enums::Permission;
impl<T: SessionStream> Session<T> {
pub async fn handle_authenticate(&mut self, request: Request<Command>) -> trc::Result<Vec<u8>> {
if request.tokens.is_empty() {
return Err(trc::AuthEvent::Error
.into_err()
.details("Authentication mechanism missing."));
}
let mut tokens = request.tokens.into_iter();
let mechanism = Mechanism::parse(&tokens.next().unwrap().unwrap_bytes())
.map_err(|err| trc::AuthEvent::Error.into_err().details(err))?;
let mut params: Vec<String> = tokens
.filter_map(|token| token.unwrap_string().ok())
.collect();
let credentials = match mechanism {
Mechanism::Plain | Mechanism::OAuthBearer | Mechanism::XOauth2 => {
if !params.is_empty() {
base64_decode(params.pop().unwrap().as_bytes())
.and_then(|challenge| {
if mechanism == Mechanism::Plain {
Credentials::decode_sasl_challenge_plain(&challenge)
} else {
Credentials::decode_sasl_challenge_oauth(&challenge)
}
})
.ok_or_else(|| {
trc::AuthEvent::Error
.into_err()
.details("Failed to decode challenge.")
})?
} else {
self.receiver.request = receiver::Request {
tag: "".into(),
command: Command::Authenticate,
tokens: vec![receiver::Token::Argument(mechanism.into_bytes())],
};
self.receiver.state = receiver::State::Argument { last_ch: b' ' };
return Ok(b"{0}\r\n".to_vec());
}
}
_ => {
return Err(trc::AuthEvent::Error
.into_err()
.details("Authentication mechanism not supported."));
}
};
// Authenticate
let access_token = self
.server
.authenticate(&AuthRequest::from_credentials(
credentials,
self.session_id,
self.remote_addr,
))
.await
.map_err(|err| {
if err.matches(trc::EventType::Auth(trc::AuthEvent::Failed)) {
match &self.state {
State::NotAuthenticated { auth_failures }
if *auth_failures < self.server.core.imap.max_auth_failures =>
{
self.state = State::NotAuthenticated {
auth_failures: auth_failures + 1,
};
}
_ => {
return trc::AuthEvent::TooManyAttempts.into_err().caused_by(err);
}
}
}
err
})
.and_then(|token| token.assert_has_permission(Permission::SieveAuthenticate))?;
// Enforce concurrency limits
let in_flight = match access_token.is_imap_request_allowed() {
LimiterResult::Allowed(in_flight) => Some(in_flight),
LimiterResult::Forbidden => {
return Err(trc::LimitEvent::ConcurrentRequest.into_err());
}
LimiterResult::Disabled => None,
};
// Create session
self.state = State::Authenticated {
access_token,
in_flight,
};
Ok(StatusResponse::ok("Authentication successful").into_bytes())
}
pub async fn handle_unauthenticate(&mut self) -> trc::Result<Vec<u8>> {
self.state = State::NotAuthenticated { auth_failures: 0 };
trc::event!(
ManageSieve(trc::ManageSieveEvent::Unauthenticate),
SpanId = self.session_id,
Elapsed = trc::Value::Duration(0)
);
Ok(StatusResponse::ok("Unauthenticate successful.").into_bytes())
}
}
+69
View File
@@ -0,0 +1,69 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
use crate::core::{Session, StatusResponse};
use common::network::SessionStream;
use jmap_proto::request::capability::Capabilities;
use std::time::Instant;
impl<T: SessionStream> Session<T> {
pub async fn handle_capability(&self, message: &'static str) -> trc::Result<Vec<u8>> {
let op_start = Instant::now();
let mut response = Vec::with_capacity(128);
response.extend_from_slice(b"\"IMPLEMENTATION\" \"Stalwart ManageSieve\"\r\n");
response.extend_from_slice(b"\"VERSION\" \"1.0\"\r\n");
if !self.stream.is_tls() {
response.extend_from_slice(b"\"STARTTLS\"\r\n");
}
if self.stream.is_tls() || self.server.core.imap.allow_plain_auth {
response.extend_from_slice(b"\"SASL\" \"PLAIN OAUTHBEARER XOAUTH2\"\r\n");
} else {
response.extend_from_slice(b"\"SASL\" \"OAUTHBEARER XOAUTH2\"\r\n");
};
if let Some(sieve) =
self.server
.core
.jmap
.capabilities
.account
.iter()
.find_map(|(_, item)| {
if let Capabilities::SieveAccount(sieve) = item {
Some(sieve)
} else {
None
}
})
{
response.extend_from_slice(b"\"SIEVE\" \"");
response.extend_from_slice(sieve.extensions.join(" ").as_bytes());
response.extend_from_slice(b"\"\r\n");
if let Some(notification_methods) = &sieve.notification_methods {
response.extend_from_slice(b"\"NOTIFY\" \"");
response.extend_from_slice(notification_methods.join(" ").as_bytes());
response.extend_from_slice(b"\"\r\n");
}
if sieve.max_redirects > 0 {
response.extend_from_slice(b"\"MAXREDIRECTS\" \"");
response.extend_from_slice(sieve.max_redirects.to_string().as_bytes());
response.extend_from_slice(b"\"\r\n");
}
} else {
response.extend_from_slice(b"\"SIEVE\" \"\"\r\n");
}
trc::event!(
ManageSieve(trc::ManageSieveEvent::Capabilities),
SpanId = self.session_id,
Tls = self.stream.is_tls(),
Strict = !self.server.core.imap.allow_plain_auth,
Elapsed = op_start.elapsed()
);
Ok(StatusResponse::ok(message).serialize(response))
}
}
+50
View File
@@ -0,0 +1,50 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
use std::time::Instant;
use common::network::SessionStream;
use imap_proto::receiver::Request;
use registry::schema::enums::Permission;
use crate::core::{Command, Session, StatusResponse};
impl<T: SessionStream> Session<T> {
pub async fn handle_checkscript(&mut self, request: Request<Command>) -> trc::Result<Vec<u8>> {
// Validate access
self.assert_has_permission(Permission::SieveCheckScript)?;
let op_start = Instant::now();
if request.tokens.is_empty() {
return Err(trc::ManageSieveEvent::Error
.into_err()
.details("Expected script as a parameter."));
}
let script = request.tokens.into_iter().next().unwrap().unwrap_bytes();
self.server
.core
.sieve
.untrusted_compiler
.compile(&script)
.map(|_| {
trc::event!(
ManageSieve(trc::ManageSieveEvent::CheckScript),
SpanId = self.session_id,
Size = script.len(),
Elapsed = op_start.elapsed()
);
StatusResponse::ok("Script is valid.").into_bytes()
})
.map_err(|err| {
trc::ManageSieveEvent::Error
.into_err()
.details(err.to_string())
})
}
}
+75
View File
@@ -0,0 +1,75 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
use crate::core::{Command, ResponseCode, Session, StatusResponse};
use common::network::SessionStream;
use email::sieve::{delete::SieveScriptDelete, ingest::SieveScriptIngest};
use imap_proto::receiver::Request;
use registry::schema::enums::Permission;
use std::time::Instant;
use store::write::BatchBuilder;
use trc::AddContext;
impl<T: SessionStream> Session<T> {
pub async fn handle_deletescript(&mut self, request: Request<Command>) -> trc::Result<Vec<u8>> {
// Validate access
self.assert_has_permission(Permission::SieveDeleteScript)?;
let op_start = Instant::now();
let name = request
.tokens
.into_iter()
.next()
.and_then(|s| s.unwrap_string().ok())
.ok_or_else(|| {
trc::ManageSieveEvent::Error
.into_err()
.details("Expected script name as a parameter.")
})?;
let access_token = self.state.access_token();
let account_id = access_token.account_id();
let document_id = self.get_script_id(account_id, &name).await?;
let mut batch = BatchBuilder::new();
let active_script_id = self.server.sieve_script_get_active_id(account_id).await?;
if active_script_id != Some(document_id) {
if self
.server
.sieve_script_delete(account_id, document_id, access_token, &mut batch)
.await
.caused_by(trc::location!())?
{
if !batch.is_empty() {
self.server
.commit_batch(batch)
.await
.caused_by(trc::location!())?;
}
trc::event!(
ManageSieve(trc::ManageSieveEvent::DeleteScript),
SpanId = self.session_id,
Id = name,
DocumentId = document_id,
Elapsed = op_start.elapsed()
);
Ok(StatusResponse::ok("Deleted.").into_bytes())
} else {
Err(trc::ManageSieveEvent::Error
.into_err()
.details("Script not found"))
}
} else {
Err(trc::ManageSieveEvent::Error
.into_err()
.details("You may not delete an active script")
.code(ResponseCode::Active))
}
}
}
+94
View File
@@ -0,0 +1,94 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
use crate::core::{Command, ResponseCode, Session, StatusResponse};
use common::network::SessionStream;
use email::sieve::SieveScript;
use imap_proto::receiver::Request;
use registry::schema::enums::Permission;
use std::time::Instant;
use store::{
ValueKey,
write::{AlignedBytes, Archive},
};
use trc::AddContext;
use types::{blob::BlobSection, blob_hash::BlobHash, collection::Collection};
impl<T: SessionStream> Session<T> {
pub async fn handle_getscript(&mut self, request: Request<Command>) -> trc::Result<Vec<u8>> {
// Validate access
self.assert_has_permission(Permission::SieveGetScript)?;
let op_start = Instant::now();
let name = request
.tokens
.into_iter()
.next()
.and_then(|s| s.unwrap_string().ok())
.ok_or_else(|| {
trc::ManageSieveEvent::Error
.into_err()
.details("Expected script name as a parameter.")
})?;
let account_id = self.state.access_token().account_id();
let document_id = self.get_script_id(account_id, &name).await?;
let sieve_ = self
.server
.store()
.get_value::<Archive<AlignedBytes>>(ValueKey::archive(
account_id,
Collection::SieveScript,
document_id,
))
.await
.caused_by(trc::location!())?
.ok_or_else(|| {
trc::ManageSieveEvent::Error
.into_err()
.details("Script not found")
.code(ResponseCode::NonExistent)
})?;
let sieve = sieve_
.unarchive::<SieveScript>()
.caused_by(trc::location!())?;
let blob_size = u32::from(sieve.size) as usize;
let script = self
.server
.get_blob_section(
&BlobHash::from(&sieve.blob_hash),
&BlobSection {
size: blob_size,
..Default::default()
},
)
.await
.caused_by(trc::location!())?
.ok_or_else(|| {
trc::ManageSieveEvent::Error
.into_err()
.details("Script blob not found")
.code(ResponseCode::NonExistent)
})?;
debug_assert_eq!(script.len(), blob_size);
let mut response = Vec::with_capacity(script.len() + 32);
response.push(b'{');
response.extend_from_slice(blob_size.to_string().as_bytes());
response.extend_from_slice(b"}\r\n");
response.extend(script);
response.extend_from_slice(b"\r\n");
trc::event!(
ManageSieve(trc::ManageSieveEvent::GetScript),
SpanId = self.session_id,
Id = name,
DocumentId = document_id,
Elapsed = op_start.elapsed()
);
Ok(StatusResponse::ok("").serialize(response))
}
}
+76
View File
@@ -0,0 +1,76 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
use std::time::Instant;
use common::network::SessionStream;
use imap_proto::receiver::Request;
use registry::schema::enums::Permission;
use trc::AddContext;
use crate::core::{Command, ResponseCode, Session, StatusResponse};
impl<T: SessionStream> Session<T> {
pub async fn handle_havespace(&mut self, request: Request<Command>) -> trc::Result<Vec<u8>> {
// Validate access
self.assert_has_permission(Permission::SieveHaveSpace)?;
let op_start = Instant::now();
let mut tokens = request.tokens.into_iter();
let name = tokens
.next()
.and_then(|s| s.unwrap_string().ok())
.ok_or_else(|| {
trc::ManageSieveEvent::Error
.into_err()
.details("Expected script name as a parameter.")
})?;
let size: usize = tokens
.next()
.and_then(|s| s.unwrap_string().ok())
.ok_or_else(|| {
trc::ManageSieveEvent::Error
.into_err()
.details("Expected script size as a parameter.")
})?
.parse::<usize>()
.map_err(|_| {
trc::ManageSieveEvent::Error
.into_err()
.details("Invalid size parameter.")
})?;
// Validate name
let account_id = self.state.access_token().account_id();
let account = self.server.account(account_id).await?;
self.validate_name(account_id, &name).await?;
// Validate quota
if account.disk_quota() == 0
|| size as i64
+ self
.server
.get_used_quota_account(account_id)
.await
.caused_by(trc::location!())?
<= account.disk_quota() as i64
{
trc::event!(
ManageSieve(trc::ManageSieveEvent::HaveSpace),
SpanId = self.session_id,
Size = size,
Elapsed = op_start.elapsed()
);
Ok(StatusResponse::ok("").into_bytes())
} else {
Err(trc::ManageSieveEvent::Error
.into_err()
.details("Quota exceeded.")
.code(ResponseCode::QuotaMaxSize))
}
}
}
+79
View File
@@ -0,0 +1,79 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
use crate::core::{Session, StatusResponse};
use common::network::SessionStream;
use email::sieve::{SieveScript, ingest::SieveScriptIngest};
use registry::schema::enums::Permission;
use std::time::Instant;
use store::{
ValueKey,
write::{AlignedBytes, Archive},
};
use trc::AddContext;
use types::{collection::Collection, field::SieveField};
impl<T: SessionStream> Session<T> {
pub async fn handle_listscripts(&mut self) -> trc::Result<Vec<u8>> {
// Validate access
self.assert_has_permission(Permission::SieveListScripts)?;
let op_start = Instant::now();
let account_id = self.state.access_token().account_id();
let document_ids = self
.server
.document_ids(account_id, Collection::SieveScript, SieveField::Name)
.await
.caused_by(trc::location!())?;
if document_ids.is_empty() {
return Ok(StatusResponse::ok("").into_bytes());
}
let mut response = Vec::with_capacity(128);
let count = document_ids.len();
let active_script_id = self.server.sieve_script_get_active_id(account_id).await?;
for document_id in document_ids {
if let Some(script_) = self
.server
.store()
.get_value::<Archive<AlignedBytes>>(ValueKey::archive(
account_id,
Collection::SieveScript,
document_id,
))
.await
.caused_by(trc::location!())?
{
let script = script_
.unarchive::<SieveScript>()
.caused_by(trc::location!())?;
response.push(b'\"');
for ch in script.name.as_bytes() {
if b"\\\"".contains(ch) {
response.push(b'\\');
}
response.push(*ch);
}
if active_script_id == Some(document_id) {
response.extend_from_slice(b"\" ACTIVE\r\n");
} else {
response.extend_from_slice(b"\"\r\n");
}
}
}
trc::event!(
ManageSieve(trc::ManageSieveEvent::ListScripts),
SpanId = self.session_id,
Total = count,
Elapsed = op_start.elapsed()
);
Ok(StatusResponse::ok("").serialize(response))
}
}
+21
View File
@@ -0,0 +1,21 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
use tokio::io::{AsyncRead, AsyncWrite};
use crate::core::{Session, StatusResponse};
impl<T: AsyncRead + AsyncWrite> Session<T> {
pub async fn handle_logout(&mut self) -> trc::Result<Vec<u8>> {
trc::event!(
ManageSieve(trc::ManageSieveEvent::Logout),
SpanId = self.session_id,
Elapsed = trc::Value::Duration(0)
);
Ok(StatusResponse::ok("Stalwart ManageSieve bids you farewell.").into_bytes())
}
}
+43
View File
@@ -0,0 +1,43 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
use crate::core::{Session, State, StatusResponse};
use common::network::SessionStream;
use registry::schema::enums::Permission;
pub mod authenticate;
pub mod capability;
pub mod checkscript;
pub mod deletescript;
pub mod getscript;
pub mod havespace;
pub mod listscripts;
pub mod logout;
pub mod noop;
pub mod putscript;
pub mod renamescript;
pub mod setactive;
impl<T: SessionStream> Session<T> {
pub async fn handle_start_tls(&self) -> trc::Result<Vec<u8>> {
trc::event!(
ManageSieve(trc::ManageSieveEvent::StartTls),
SpanId = self.session_id,
Elapsed = trc::Value::Duration(0)
);
Ok(StatusResponse::ok("Begin TLS negotiation now").into_bytes())
}
pub fn assert_has_permission(&self, permission: Permission) -> trc::Result<bool> {
match &self.state {
State::Authenticated { access_token, .. } => {
access_token.enforce_permission(permission).map(|_| true)
}
State::NotAuthenticated { .. } => Ok(false),
}
}
}
+32
View File
@@ -0,0 +1,32 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
use imap_proto::receiver::Request;
use tokio::io::{AsyncRead, AsyncWrite};
use crate::core::{Command, ResponseCode, Session, StatusResponse};
impl<T: AsyncRead + AsyncWrite> Session<T> {
pub async fn handle_noop(&mut self, request: Request<Command>) -> trc::Result<Vec<u8>> {
trc::event!(
ManageSieve(trc::ManageSieveEvent::Noop),
SpanId = self.session_id,
Elapsed = trc::Value::Duration(0)
);
Ok(if let Some(tag) = request
.tokens
.into_iter()
.next()
.and_then(|t| t.unwrap_string().ok())
{
StatusResponse::ok("Done").with_code(ResponseCode::Tag(tag))
} else {
StatusResponse::ok("Done")
}
.into_bytes())
}
}
+241
View File
@@ -0,0 +1,241 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
use crate::core::{Command, ResponseCode, Session, StatusResponse};
use common::{network::SessionStream, storage::index::ObjectIndexBuilder};
use email::sieve::SieveScript;
use imap_proto::receiver::Request;
use registry::schema::enums::{Permission, StorageQuota};
use sieve::compiler::ErrorType;
use std::time::Instant;
use store::{
Serialize, ValueKey,
write::{AlignedBytes, Archive, Archiver, BatchBuilder},
};
use trc::AddContext;
use types::{collection::Collection, field::SieveField};
impl<T: SessionStream> Session<T> {
pub async fn handle_putscript(&mut self, request: Request<Command>) -> trc::Result<Vec<u8>> {
// Validate access
self.assert_has_permission(Permission::SievePutScript)?;
let op_start = Instant::now();
let mut tokens = request.tokens.into_iter();
let name = tokens
.next()
.and_then(|s| s.unwrap_string().ok())
.ok_or_else(|| {
trc::ManageSieveEvent::Error
.into_err()
.details("Expected script name as a parameter.")
})?
.trim()
.to_string();
let mut script_bytes = tokens
.next()
.ok_or_else(|| {
trc::ManageSieveEvent::Error
.into_err()
.details("Expected script as a parameter.")
})?
.unwrap_bytes();
let script_size = script_bytes.len() as i64;
// Check quota
let access_token = self.state.access_token();
let account_id = access_token.account_id();
let account = self.server.account(account_id).await?;
self.server
.has_available_quota(&account, script_bytes.len() as u64)
.await
.caused_by(trc::location!())?;
if self
.server
.document_ids(account_id, Collection::SieveScript, SieveField::Name)
.await
.caused_by(trc::location!())?
.len()
>= self
.server
.object_quota(account.object_quotas(), StorageQuota::MaxSieveScripts)
as u64
{
return Err(trc::ManageSieveEvent::Error
.into_err()
.details("Too many scripts.")
.code(ResponseCode::QuotaMaxScripts));
}
// Compile script
match self
.server
.core
.sieve
.untrusted_compiler
.compile(&script_bytes)
{
Ok(compiled_script) => {
script_bytes.extend(
Archiver::new(compiled_script)
.untrusted()
.serialize()
.caused_by(trc::location!())?,
);
}
Err(err) => {
return Err(if let ErrorType::ScriptTooLong = &err.error_type() {
trc::ManageSieveEvent::Error
.into_err()
.details(err.to_string())
.code(ResponseCode::QuotaMaxSize)
} else {
trc::ManageSieveEvent::Error
.into_err()
.details(err.to_string())
});
}
}
// Validate name
if let Some(document_id) = self.validate_name(account_id, &name).await? {
// Obtain script values
let script_ = self
.server
.store()
.get_value::<Archive<AlignedBytes>>(ValueKey::archive(
account_id,
Collection::SieveScript,
document_id,
))
.await
.caused_by(trc::location!())?
.ok_or_else(|| {
trc::ManageSieveEvent::Error
.into_err()
.details("Script not found")
.code(ResponseCode::NonExistent)
})?;
let script = script_
.to_unarchived::<SieveScript>()
.caused_by(trc::location!())?;
// Write script blob
let (blob_hash, blob_hold) = self
.server
.put_temporary_blob(account_id, &script_bytes, 60)
.await?;
// Write record
let mut batch = BatchBuilder::new();
batch
.with_account_id(account_id)
.with_collection(Collection::SieveScript)
.with_document(document_id)
.custom(
ObjectIndexBuilder::new()
.with_changes(
script
.deserialize()
.caused_by(trc::location!())?
.with_size(script_size as u32)
.with_blob_hash(blob_hash.clone()),
)
.with_current(script)
.with_changed_by(account.account_tenant_ids()),
)
.caused_by(trc::location!())?
.clear(blob_hold);
self.server
.commit_batch(batch)
.await
.caused_by(trc::location!())?;
trc::event!(
ManageSieve(trc::ManageSieveEvent::UpdateScript),
SpanId = self.session_id,
Id = name.to_string(),
DocumentId = document_id,
Size = script_size,
Elapsed = op_start.elapsed(),
);
} else {
// Write script blob
let (blob_hash, blob_hold) = self
.server
.put_temporary_blob(account_id, &script_bytes, 60)
.await?;
// Write record
let mut batch = BatchBuilder::new();
let document_id = self
.server
.store()
.assign_document_ids(account_id, Collection::SieveScript, 1)
.await
.caused_by(trc::location!())?;
batch
.with_account_id(account_id)
.with_collection(Collection::SieveScript)
.with_document(document_id)
.custom(
ObjectIndexBuilder::<(), _>::new()
.with_changes(
SieveScript::new(name.clone(), blob_hash.clone())
.with_size(script_size as u32),
)
.with_changed_by(account.account_tenant_ids()),
)
.caused_by(trc::location!())?
.clear(blob_hold);
self.server
.commit_batch(batch)
.await
.caused_by(trc::location!())?;
trc::event!(
ManageSieve(trc::ManageSieveEvent::CreateScript),
SpanId = self.session_id,
Id = name,
DocumentId = document_id,
Elapsed = op_start.elapsed()
);
}
Ok(StatusResponse::ok("Success.").into_bytes())
}
pub async fn validate_name(&self, account_id: u32, name: &str) -> trc::Result<Option<u32>> {
if name.is_empty() {
Err(trc::ManageSieveEvent::Error
.into_err()
.details("Script name cannot be empty."))
} else if name.len() > self.server.core.email.sieve_max_script_name {
Err(trc::ManageSieveEvent::Error
.into_err()
.details("Script name is too long."))
} else if name.eq_ignore_ascii_case("vacation") {
Err(trc::ManageSieveEvent::Error
.into_err()
.details("The 'vacation' name is reserved, please use a different name."))
} else {
Ok(self
.server
.document_ids_matching(
account_id,
Collection::SieveScript,
SieveField::Name,
name.to_lowercase().as_bytes(),
)
.await
.caused_by(trc::location!())?
.min())
}
}
}
+110
View File
@@ -0,0 +1,110 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
use crate::core::{Command, ResponseCode, Session, StatusResponse};
use common::{network::SessionStream, storage::index::ObjectIndexBuilder};
use email::sieve::SieveScript;
use imap_proto::receiver::Request;
use registry::schema::enums::Permission;
use std::time::Instant;
use store::{
ValueKey,
write::{AlignedBytes, Archive, BatchBuilder},
};
use trc::AddContext;
use types::collection::Collection;
impl<T: SessionStream> Session<T> {
pub async fn handle_renamescript(&mut self, request: Request<Command>) -> trc::Result<Vec<u8>> {
// Validate access
self.assert_has_permission(Permission::SieveRenameScript)?;
let op_start = Instant::now();
let mut tokens = request.tokens.into_iter();
let name = tokens
.next()
.and_then(|s| s.unwrap_string().ok())
.ok_or_else(|| {
trc::ManageSieveEvent::Error
.into_err()
.details("Expected old script name as a parameter.")
})?
.trim()
.to_string();
let new_name = tokens
.next()
.and_then(|s| s.unwrap_string().ok())
.ok_or_else(|| {
trc::ManageSieveEvent::Error
.into_err()
.details("Expected new script name as a parameter.")
})?
.trim()
.to_string();
// Validate name
if name == new_name {
return Ok(StatusResponse::ok("Old and new script names are the same.").into_bytes());
}
let account_id = self.state.access_token().account_id();
let document_id = self.get_script_id(account_id, &name).await?;
if self.validate_name(account_id, &new_name).await?.is_some() {
return Err(trc::ManageSieveEvent::Error
.into_err()
.details(format!("A sieve script with name '{name}' already exists.",))
.code(ResponseCode::AlreadyExists));
}
// Obtain script values
let script = self
.server
.store()
.get_value::<Archive<AlignedBytes>>(ValueKey::archive(
account_id,
Collection::SieveScript,
document_id,
))
.await
.caused_by(trc::location!())?
.ok_or_else(|| {
trc::ManageSieveEvent::Error
.into_err()
.details("Script not found")
.code(ResponseCode::NonExistent)
})?
.into_deserialized::<SieveScript>()
.caused_by(trc::location!())?;
// Write record
let mut batch = BatchBuilder::new();
batch
.with_account_id(account_id)
.with_collection(Collection::SieveScript)
.with_document(document_id)
.custom(
ObjectIndexBuilder::new()
.with_changes(script.inner.clone().with_name(new_name.clone()))
.with_current(script),
)
.caused_by(trc::location!())?;
if !batch.is_empty() {
self.server
.commit_batch(batch)
.await
.caused_by(trc::location!())?;
}
trc::event!(
ManageSieve(trc::ManageSieveEvent::RenameScript),
SpanId = self.session_id,
Id = new_name,
DocumentId = document_id,
Elapsed = op_start.elapsed()
);
Ok(StatusResponse::ok("Success.").into_bytes())
}
}
+66
View File
@@ -0,0 +1,66 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
use std::time::Instant;
use common::network::SessionStream;
use imap_proto::receiver::Request;
use registry::schema::enums::Permission;
use store::{SerializeInfallible, write::BatchBuilder};
use trc::AddContext;
use types::{collection::Collection, field::PrincipalField};
use crate::core::{Command, Session, StatusResponse};
impl<T: SessionStream> Session<T> {
pub async fn handle_setactive(&mut self, request: Request<Command>) -> trc::Result<Vec<u8>> {
// Validate access
self.assert_has_permission(Permission::SieveSetActive)?;
let op_start = Instant::now();
let name = request
.tokens
.into_iter()
.next()
.and_then(|s| s.unwrap_string().ok())
.ok_or_else(|| {
trc::ManageSieveEvent::Error
.into_err()
.details("Expected script name as a parameter.")
})?;
// De/activate script
let account_id = self.state.access_token().account_id();
let mut batch = BatchBuilder::new();
if !name.is_empty() {
let document_id = self.get_script_id(account_id, &name).await?;
batch
.with_account_id(account_id)
.with_collection(Collection::Principal)
.with_document(0)
.set(PrincipalField::ActiveScriptId, document_id.serialize());
} else {
batch
.with_account_id(account_id)
.with_collection(Collection::Principal)
.with_document(0)
.clear(PrincipalField::ActiveScriptId);
}
self.server
.commit_batch(batch)
.await
.caused_by(trc::location!())?;
trc::event!(
ManageSieve(trc::ManageSieveEvent::SetActive),
SpanId = self.session_id,
Id = name,
Elapsed = op_start.elapsed()
);
Ok(StatusResponse::ok("Success").into_bytes())
}
}