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:
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user