v1.2.1
Some checks failed
Scorecard supply-chain security / Scorecard analysis (push) Has been cancelled
trivy / Check (push) Has been cancelled

This commit is contained in:
Stalwart Git Sync 2026-11-25 22:52:06 +01:00
parent b2d3df9a9b
commit 0b1342eda2
No known key found for this signature in database
117 changed files with 1777 additions and 688 deletions

View file

@ -41,7 +41,7 @@ jobs:
contents: read
attestations: write
packages: write
needs: [linux, windows, macos, freebsd]
needs: [linux, windows, freebsd]
if: github.event_name == 'push' || inputs.Docker
steps:
- name: Install Cosign
@ -375,7 +375,7 @@ jobs:
matrix:
include:
- target: aarch64-apple-darwin
- target: x86_64-apple-darwin
# - target: x86_64-apple-darwin
steps:
- name: Checkout
uses: actions/checkout@v7
@ -395,7 +395,7 @@ jobs:
- name: Upload Artifacts
uses: actions/upload-artifact@v7.0.1
with:
name: artifact-${{matrix.target}}
name: macos-artifact-${{matrix.target}}
path: artifacts
freebsd:
@ -461,7 +461,7 @@ jobs:
contents: write
attestations: write
if: github.event_name == 'push' || inputs.Release
needs: [linux, windows, macos, freebsd]
needs: [linux, windows, freebsd]
runs-on: ubuntu-latest
steps:
# Must run before artifacts are downloaded — checkout cleans the workspace.
@ -545,9 +545,50 @@ jobs:
draft: ${{ startsWith(github.ref, 'refs/tags/') || null }}
body_path: release_body.md
release-macos:
name: Release / macOS
permissions:
id-token: write
contents: write
attestations: write
if: github.event_name == 'push' || inputs.Release
needs: [macos, release]
runs-on: ubuntu-latest
steps:
- name: Download Artifacts
uses: actions/download-artifact@v8
with:
path: archive
pattern: macos-artifact-*
- name: Compress
run: |
set -eux
cd archive
for dir in macos-artifact-*; do
target="${dir#macos-artifact-}"
tar -C "$dir" -czf "stalwart-${target}.tar.gz" stalwart
done
- name: Attest binary
uses: actions/attest-build-provenance@v4
with:
subject-path: archive/*.tar.gz
- name: Use cosign to sign existing artifacts
uses: sigstore/gh-action-sigstore-python@v3.5.0
with:
inputs: archive/*.tar.gz
- name: Upload to release
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ startsWith(github.ref, 'refs/tags/') && github.ref_name || 'nightly' }}
run: gh release upload "$TAG" archive/*.tar.gz archive/*.sigstore.json --clobber --repo "${{ github.repository }}"
publish:
name: Publish release
needs: [linux, windows, macos, freebsd, multiarch, release]
needs: [linux, windows, freebsd, multiarch, release]
if: startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
permissions:
@ -560,7 +601,7 @@ jobs:
cleanup:
name: Cleanup failed release
needs: [linux, windows, macos, freebsd, multiarch, release]
needs: [linux, windows, freebsd, multiarch, release]
if: failure() && startsWith(github.ref, 'refs/tags/') && github.run_attempt >= 3
runs-on: ubuntu-latest
permissions:

View file

@ -2,6 +2,36 @@
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
## [1.2.1] - 2026-11-25
## Fixed
- MTA: in a cluster, an in-memory store error while locking a queued message now retries within seconds instead of parking the message for ten minutes.
- IMAP:
- IDLE no longer sends unsolicited `FETCH` responses for newly arrived messages, which made Thunderbird and Evolution skip messages announced by `EXISTS` while another command was running.
- Mailbox names and other strings containing CR or LF are sent as literals, so a shared mailbox name can no longer inject response lines into another user's session.
- JMAP:
- `/get` methods list an id requested more than once only once in `list` or `notFound`.
- `Mailbox/set` refuses two sibling mailboxes with the same name created or renamed in the same request.
- `Email/set` rejects with `invalidPatch` a keyword or mailbox pointer deeper than one level, and an update that both replaces and patches `keywords` or `mailboxIds`.
- Sieve:
- JMAP reports invalid scripts as `invalidSieve`, a `require` of an unsupported extension is refused, invalid header names in tests no longer fail compilation, and imap4flags variable names require `variables`.
- `redirect` keeps an empty envelope sender (`MAIL FROM:<>`), and `reject` sends a failure MDN instead of a DSN; `ereject` still produces a DSN. Mail rules now reject with `ereject` (protocol-level refusal) instead of `reject`.
- Calendar: iMIP invitation and update emails now label UTC and fixed-offset times that have no `TZID` with their time zone.
- Exchange:
- MAPI: Outlook in cached mode no longer shows an empty body for messages whose HTML part is larger than 32 KiB; properties over 32 KiB are now included in cached-mode downloads and FastTransfer copies.
- EWS: folders now return the `PR_ENTRYID` and `PR_ATTR_HIDDEN` extended properties when requested, which Apple Mail needs to sync the folder list without crashing.
- ActiveSync: Find reads its search text as KQL, so iOS Mail server searches such as `from:"name" OR subject:"name"` find messages again.
- ActiveSync: SendMail, SmartReply and SmartForward accept a raw `message/rfc822` body at every protocol version, so Outlook for iOS and Android can send mail.
- ActiveSync: refused SendMail, SmartReply and SmartForward requests, and requests refused for their body type or invalid WBXML, are logged as `http.error` (debug) with the command, the ActiveSync status and the reason.
- ActiveSync: a calendar Add with an empty `Recurrence` element is stored as a single event instead of failing with status 6, so iOS Calendar can create events again.
- Auth: password logins on a domain served by an OpenID Connect directory now fail as invalid credentials (`535 5.7.8` over SMTP) and count toward the authentication auto-ban.
- Security:
- `x:AppPassword/set` and `x:ApiKey/set` only update or delete credentials of their own type, so an app password or API key can no longer change the account password or remove its TOTP.
- S/MIME key harvesting limits the nesting of the signed content, so a crafted signed message can no longer crash the server with a stack overflow.
- `Mailbox/set` requires the share right for pointer patches into `shareWith`, so a sharee without `mayShare` can no longer change a mailbox's permissions.
- Store maintenance: a trace retention longer than the time since 2021-09-22 no longer fails the task with "Invalid id cutoff for global unindex".
- In-memory store: when the configured store is not available (for example Stalwart Keep was unreachable at startup), operations now fail with "not configured" and point to the startup log instead of "Operation not supported by store".
## [1.2.0] - 2026-11-23
Upgrade instructions:

397
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,15 +1,15 @@
[package]
name = "calcard"
description = "iCalendar/JSCalendar and vCard/JSContact parsing, building and conversion library"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
license = "AGPL-3.0-only OR LicenseRef-SEL"
publish = false
[dependencies]
jmap-tools = { path = "../jmap-tools", optional = true }
ahash = "0.8.12"
jiff = "0.2.38"
ahash = "0.8.14"
jiff = "1.0.3"
hashify = "0.3"
memchr = "2.8"
encodify = "1.0"
@ -23,7 +23,7 @@ serde = { version = "1.0", features = ["derive"], optional = true }
serde_json = { version = "1.0", optional = true }
[target.'cfg(all(target_family = "wasm", target_os = "unknown"))'.dependencies]
jiff = { version = "0.2.38", features = ["js"] }
jiff = { version = "1.0.3", features = ["js"] }
[features]
default = ["jmap", "tzdb-bundle"]

View file

@ -1,6 +1,6 @@
[package]
name = "common"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
build = "build.rs"
@ -24,10 +24,10 @@ smtp-report = { path = "../smtp-report" }
smtp-proto = { path = "../smtp-proto", features = ["rkyv"] }
dns-update = { version = "0.6.3" }
calcard = { path = "../calcard", features = ["rkyv"] }
ahash = { version = "0.8.12", features = ["serde"] }
ahash = { version = "0.8.14", features = ["serde"] }
parking_lot = "0.13.0"
proxy-header = { version = "0.1.3", features = ["tokio"] }
arc-swap = "1.9.3"
arc-swap = "1.9.5"
rustls = { version = "0.23.46", default-features = false, features = ["std", "aws_lc_rs", "tls12"] }
rustls-pemfile = "2.2"
rustls-pki-types = { version = "1" }
@ -43,8 +43,8 @@ serde_json = { version = "1.0", features = ["raw_value"] }
encodify = "1.0"
x509-parser = "0.18"
pem = "4.0"
jiff = "0.2.38"
hyper = { version = "1.12.0", features = ["server", "http1", "http2"] }
jiff = "1.0.3"
hyper = { version = "1.13.0", features = ["server", "http1", "http2"] }
imagesize = "0.15"
sha1 = "0.11"
sha2 = "0.11"
@ -53,15 +53,15 @@ md5 = "0.8.1"
whatlang = "0.18"
idna = "1.1"
decancer = "4.0.0"
unicode-security = "0.1.2"
unicode-security = "0.1.3"
infer = "0.22"
bincode = { version = "2.0.1", features = ["serde"] }
zip = "9.1"
xxhash-rust = { version = "0.8.19", features = ["xxh3"] }
zip = "9.8"
xxhash-rust = { version = "0.8.21", features = ["xxh3"] }
psl = "2"
aes-gcm-siv = "0.12.1"
jsonwebtoken = { version = "11.1.0", features = ["aws_lc_rs"] }
rsa = "0.9.10"
jsonwebtoken = { version = "12.0.0", features = ["aws_lc_rs"] }
rsa = "0.10.0"
p256 = { version = "0.14", features = ["ecdh", "ecdsa", "pkcs8", "pem"] }
p384 = { version = "0.14", features = ["ecdh"] }
hashify = "0.3"
@ -78,10 +78,10 @@ zxcvbn = "3.1.1"
pkcs8 = { version = "0.11.0", features = ["alloc", "std"] }
quick-xml = "0.42"
percent-encoding = "2.3.2"
bumpalo = { version = "3.20.3", features = ["collections"] }
regex-automata = { version = "0.4.18", default-features = false, features = ["std", "syntax", "meta", "nfa-pikevm", "nfa-backtrack", "hybrid", "dfa-onepass", "perf-inline", "perf-literal", "unicode"] }
bumpalo = { version = "3.20.4", features = ["collections"] }
regex-automata = { version = "0.4.19", default-features = false, features = ["std", "syntax", "meta", "nfa-pikevm", "nfa-backtrack", "hybrid", "dfa-onepass", "perf-inline", "perf-literal", "unicode"] }
memchr = "2.8.3"
itoa = "1.0.18"
itoa = "1.0.19"
zmij = "1.0.23"
[target.'cfg(unix)'.dependencies]
@ -104,7 +104,7 @@ keep = ["store/keep"]
[dev-dependencies]
tokio = { version = "1.54", features = ["full"] }
regex = "1.13.1"
regex = "1.13.2"
[lints]
workspace = true

View file

@ -48,7 +48,7 @@ pub struct OAuthConfig {
pub client_metadata_documents: OAuthClientMetadataPolicy,
pub oidc_expiry_id_token: u64,
pub oidc_signing_secret: EncodingKey,
pub oidc_signing_secret: Option<EncodingKey>,
pub oidc_verifying_key: Option<DecodingKey>,
pub oidc_signature_algorithm: Algorithm,
pub oidc_signature_algorithm_name: &'static str,
@ -113,8 +113,11 @@ impl OAuthConfig {
};
let (oidc_signing_secret, algorithm) = match asymmetric_key {
None => (EncodingKey::from_secret(signature_key.as_bytes()), None),
Some(Ok((secret, params))) => (secret, Some(params)),
None => (
EncodingKey::from_secret(signature_key.as_bytes()).ok(),
None,
),
Some(Ok((secret, params))) => (Some(secret), Some(params)),
Some(Err(err)) => match ephemeral_ecdsa_key() {
Ok((secret, params)) => {
bp.build_error(
@ -123,7 +126,7 @@ impl OAuthConfig {
);
oidc_signature_algorithm = Algorithm::ES256;
oidc_signature_algorithm_name = "ES256";
(secret, Some(params))
(Some(secret), Some(params))
}
Err(ephemeral_err) => {
bp.build_error(
@ -135,7 +138,10 @@ impl OAuthConfig {
oidc_signature_algorithm = Algorithm::HS256;
oidc_signature_algorithm_name = "HS256";
signature_key = Cow::Owned(random_secret());
(EncodingKey::from_secret(signature_key.as_bytes()), None)
(
EncodingKey::from_secret(signature_key.as_bytes()).ok(),
None,
)
}
},
};
@ -146,7 +152,7 @@ impl OAuthConfig {
algorithm: params.clone(),
})
.ok(),
None => Some(DecodingKey::from_secret(signature_key.as_bytes())),
None => DecodingKey::from_secret(signature_key.as_bytes()).ok(),
};
let oidc_jwks = Resource {

View file

@ -141,6 +141,16 @@ impl Server {
audience: impl Into<String>,
claims: StandardClaims,
) -> trc::Result<String> {
let signing_key = self
.core
.oauth
.oidc_signing_secret
.as_ref()
.ok_or_else(|| {
trc::AuthEvent::Error
.into_err()
.details("No OIDC signing key available")
})?;
let now = now() as i64;
jsonwebtoken::encode(
@ -157,7 +167,7 @@ impl Server {
exp: now + self.core.oauth.oidc_expiry_id_token as i64,
private: claims,
},
&self.core.oauth.oidc_signing_secret,
signing_key,
)
.map_err(|err| {
trc::AuthEvent::Error

View file

@ -72,6 +72,7 @@ impl Scripting {
.map(|cap| cap.as_str()),
)
.without_capability(Capability::ImapSieve)
.without_unknown_capabilities()
.register_functions(&mut fnc_map_untrusted);
// Parse untrusted runtime

View file

@ -25,7 +25,7 @@ use hyper::HeaderMap;
use p256::elliptic_curve::sec1::ToSec1Point;
use pkcs8::EncodePrivateKey;
use rsa::{
RsaPrivateKey,
PrivateKey,
pkcs1::{DecodeRsaPrivateKey, EncodeRsaPrivateKey},
pkcs8::DecodePrivateKey as _,
traits::PublicKeyParts,
@ -147,8 +147,8 @@ impl Core {
}
}
const RSA_MIN_MODULUS_BITS: usize = 2048;
const RSA_MAX_MODULUS_BITS: usize = 8192;
const RSA_MIN_MODULUS_BITS: u32 = 2048;
const RSA_MAX_MODULUS_BITS: u32 = 8192;
fn no_key_found(pem: &str, expected: &str) -> String {
if pem.contains("ENCRYPTED PRIVATE KEY") || pem.contains("Proc-Type: 4,ENCRYPTED") {
@ -171,17 +171,17 @@ pub fn build_rsa_keypair(pem: &str) -> Result<RsaSigningKey, String> {
for item in rustls_pemfile::read_all(&mut Cursor::new(pem)) {
let key = match item.map_err(|err| format!("Failed to read private key PEM: {err}"))? {
rustls_pemfile::Item::Pkcs1Key(key) => {
RsaPrivateKey::from_pkcs1_der(key.secret_pkcs1_der())
PrivateKey::from_pkcs1_der(key.secret_pkcs1_der())
.map_err(|err| format!("Failed to parse PKCS1 RSA key: {err}"))?
}
rustls_pemfile::Item::Pkcs8Key(key) => {
RsaPrivateKey::from_pkcs8_der(key.secret_pkcs8_der())
PrivateKey::from_pkcs8_der(key.secret_pkcs8_der())
.map_err(|err| format!("Failed to parse PKCS8 RSA key: {err}"))?
}
_ => continue,
};
let bits = key.n().bits();
let bits = key.n().bit_width();
if !(RSA_MIN_MODULUS_BITS..=RSA_MAX_MODULUS_BITS).contains(&bits) {
return Err(format!(
"RSA key modulus is {bits} bits, expected between {RSA_MIN_MODULUS_BITS} and {RSA_MAX_MODULUS_BITS}"
@ -194,8 +194,8 @@ pub fn build_rsa_keypair(pem: &str) -> Result<RsaSigningKey, String> {
return Ok(RsaSigningKey {
pkcs1_der: pkcs1_der.as_bytes().to_vec(),
modulus: key.n().to_bytes_be(),
exponent: key.e().to_bytes_be(),
modulus: key.n_bytes().into_vec(),
exponent: key.e_bytes().into_vec(),
});
}

View file

@ -249,6 +249,7 @@ pub enum QueueEventStatus {
Completed,
Locked,
Deferred,
Failed,
}
#[derive(Debug)]

View file

@ -12,7 +12,7 @@ use mail_auth::crypto::{Ed25519Key, MlDsa44Key};
use mail_auth::dkim::generate::DkimKeyPair;
use registry::schema::enums::DkimSignatureType;
use registry::schema::structs::DkimSignature;
use rsa::pkcs1::{DecodeRsaPublicKey, der::Document};
use rsa::{PublicKey as RsaPublicKey, pkcs1::DecodeRsaPublicKey, pkcs8::EncodePublicKey};
use store::rand::distr::Alphanumeric;
use store::rand::{self, RngExt};
@ -53,11 +53,14 @@ pub async fn generate_dkim_public_key(key: &DkimSignature) -> trc::Result<String
DkimSignature::Dkim1RsaSha256(_) | DkimSignature::Dkim2RsaSha256(_) => {
rsa_key_parse(pem.as_bytes())
.and_then(|pk| {
Document::from_pkcs1_der(&pk.public_key()).map_err(|err| {
trc::EventType::Dkim(trc::DkimEvent::BuildError)
.into_err()
.reason(err)
})
RsaPublicKey::from_pkcs1_der(&pk.public_key())
.map_err(|err| err.to_string())
.and_then(|key| key.to_public_key_der().map_err(|err| err.to_string()))
.map_err(|err| {
trc::EventType::Dkim(trc::DkimEvent::BuildError)
.into_err()
.reason(err)
})
})
.map(|pk| STANDARD.encode(pk.as_bytes()))
}
@ -142,7 +145,7 @@ pub fn generate_dkim_selector(
template: &str,
sig_type: DkimSignatureType,
) -> Result<String, String> {
let now = Timestamp::now().to_zoned(TimeZone::UTC);
let now = Timestamp::now().to_zoned_datetime(TimeZone::UTC);
let mut result = Vec::with_capacity(template.len());
let mut chars = template.as_bytes();

View file

@ -1,6 +1,6 @@
[package]
name = "coordinator"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]
@ -10,9 +10,9 @@ utils = { path = "../utils", optional = true }
trc = { path = "../trc" }
futures = { version = "0.3", optional = true }
tokio = { version = "1.54", features = ["sync", "fs", "io-util"] }
async-nats = { version = "0.50", default-features = false, features = ["server_2_10", "server_2_11", "aws-lc-rs"], optional = true }
zenoh = { version = "1.10.1", default-features = false, features = ["auth_pubkey", "transport_multilink", "transport_compression", "transport_quic", "transport_tcp", "transport_tls", "transport_udp"], optional = true }
rdkafka = { version = "0.39", features = ["cmake-build", "ssl"], optional = true }
async-nats = { version = "0.53", default-features = false, features = ["server_2_10", "server_2_11", "aws-lc-rs"], optional = true }
zenoh = { version = "1.10.2", default-features = false, features = ["auth_pubkey", "transport_multilink", "transport_compression", "transport_quic", "transport_tcp", "transport_tls", "transport_udp"], optional = true }
rdkafka = { version = "0.40", features = ["cmake-build", "ssl"], optional = true }
redis = { version = "1.8", features = [ "tokio-comp", "tokio-rustls-comp", "tls-rustls-insecure", "tls-rustls", "cluster-async", "sentinel"], optional = true }
deadpool = { version = "0.13", default-features = false, features = ["managed"], optional = true }
hashify = { version = "0.3", optional = true }

View file

@ -1,14 +1,14 @@
[package]
name = "crypto"
description = "OpenPGP and S/MIME encryption, key validation and signature verification"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
license = "AGPL-3.0-only OR LicenseRef-SEL"
publish = false
[dependencies]
aes = "0.9.3"
aws-lc-rs = "1.18.2"
aes = "0.9.4"
aws-lc-rs = "1.19.0"
ed448-goldilocks = "0.9"
encodify = "1.0"
hashify = "0.3"

View file

@ -10,7 +10,7 @@ use crate::{
backend::{hash::HashAlgorithm, verify::SignatureScheme},
der::{
DerError, oid,
reader::{Encoding, Reader, Tlv},
reader::{Encoding, MAX_DEPTH, Reader, Tlv},
tag,
},
error::VerifyError,
@ -95,18 +95,19 @@ struct SignerInfo<'x> {
signature: &'x [u8],
}
fn hash_econtent(econtent: Tlv<'_>, hasher: &mut impl Sink) -> Result<(), DerError> {
fn hash_econtent(econtent: Tlv<'_>, hasher: &mut impl Sink, depth: usize) -> Result<(), DerError> {
match econtent.tag {
tag::OCTET_STRING => {
hasher.put(econtent.content);
Ok(())
}
CONSTRUCTED_OCTET_STRING => {
CONSTRUCTED_OCTET_STRING if depth < MAX_DEPTH => {
for chunk in econtent.reader() {
hash_econtent(chunk?, hasher)?;
hash_econtent(chunk?, hasher, depth + 1)?;
}
Ok(())
}
CONSTRUCTED_OCTET_STRING => Err(DerError::TooDeep),
_ => Err(DerError::UnexpectedTag),
}
}
@ -287,7 +288,7 @@ pub(crate) fn verify<'x>(
let mut hasher = hash.hasher();
match (&content, econtent) {
(Content::Detached(data), None) => Canonical::new(&mut hasher).put(data),
(Content::Encapsulated, Some(econtent)) => hash_econtent(econtent, &mut hasher)?,
(Content::Encapsulated, Some(econtent)) => hash_econtent(econtent, &mut hasher, 0)?,
_ => return Err(DerError::UnexpectedTag),
}
Ok(hasher.finish())

View file

@ -6,7 +6,7 @@
use super::{DerError, tag};
const MAX_DEPTH: usize = 32;
pub(crate) const MAX_DEPTH: usize = 32;
const HIGH_TAG_NUMBER: u8 = 0x1F;
const INDEFINITE_LENGTH: u8 = 0x80;

View file

@ -1,6 +1,6 @@
[package]
name = "dav-proto"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]
@ -10,7 +10,7 @@ hashify = "0.3"
quick-xml = "0.42"
calcard = { path = "../calcard", features = ["rkyv"] }
mail-parser = { version = "1.0", features = ["full_encoding"] }
hyper = "1.12.0"
hyper = "1.13.0"
compact_str = "0.10.0"
memchr = "2.8.3"

View file

@ -1,6 +1,6 @@
[package]
name = "dav"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]
@ -17,7 +17,7 @@ types = { path = "../types" }
trc = { path = "../trc" }
calcard = { path = "../calcard", features = ["rkyv"] }
hashify = { version = "0.3" }
hyper = { version = "1.12.0", features = ["server", "http1", "http2"] }
hyper = { version = "1.13.0", features = ["server", "http1", "http2"] }
percent-encoding = "2.3.2"
rkyv.workspace = true
compact_str = "0.10.0"

View file

@ -1,6 +1,6 @@
[package]
name = "directory"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]
@ -25,10 +25,10 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls", "h
serde_json = "1.0"
encodify = "1.0"
nohash-hasher = "0.2.0"
jsonwebtoken = { version = "11.1.0", features = ["aws_lc_rs"] }
jsonwebtoken = { version = "12.0.0", features = ["aws_lc_rs"] }
compact_str = "0.10.0"
hashify = "0.3"
form_urlencoded = "1.2.2"
form_urlencoded = "1.2.3"
parking_lot = "0.13.0"
[dev-dependencies]

View file

@ -40,7 +40,7 @@ const NON_ACCESS_MARKERS: [(&str, &str); 12] = [
impl OpenIdDirectory {
pub async fn authenticate(&self, _credentials: &Credentials) -> trc::Result<Account> {
Err(AuthEvent::Error
Err(AuthEvent::Failed
.into_err()
.reason("Unsupported credentials type for OIDC backend"))
}

View file

@ -1,6 +1,6 @@
[package]
name = "email"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]
@ -20,7 +20,7 @@ mail-parser = { version = "1.0", features = ["full_encoding"] }
mail-builder = { version = "2.0" }
sieve-rs = { path = "../sieve" }
tokio = { version = "1.54", features = ["net", "macros"] }
rand = "0.8"
rand = "0.10"
hashify = "0.3"
rkyv.workspace = true
compact_str = "0.10.0"

View file

@ -552,7 +552,7 @@ fn default_text(disposition_type: DispositionType, subject: Option<&str>) -> Str
}
}
fn is_valid_field_value(value: &str) -> bool {
pub(crate) fn is_valid_field_value(value: &str) -> bool {
!value.is_empty()
&& value.len() <= MAX_FIELD_LEN
&& !value.chars().any(|ch| ch.is_control() && ch != '\t')

View file

@ -18,6 +18,7 @@ use crate::{
SenderAuthentication,
},
ingest::{EmailIngest, IngestEmail, IngestSource, IngestedEmail},
mdn::{MdnMessage, OriginalMessage, is_valid_field_value},
},
};
use common::{
@ -27,6 +28,7 @@ use common::{
scripts::plugins::PluginContext,
};
use compact_str::{CompactString, ToCompactString};
use jmap_proto::object::mdn::{ActionMode, Disposition, DispositionType, Mdn, SendingMode};
use mail_builder::headers::date::Date;
use mail_parser::{HeaderName, MessageParser};
use sieve::{
@ -68,6 +70,7 @@ struct SieveHandler<'x, 'r> {
resolved: Vec<(MailboxQuery, Option<u32>)>,
has_mailboxes: bool,
mail_from: &'x str,
envelope_from: &'x str,
return_path_status: ReturnPathStatus,
spam_percentage: Option<u8>,
server_name: &'x str,
@ -80,7 +83,7 @@ struct SieveHandler<'x, 'r> {
seen_ids: Vec<SeenId>,
vacation_id: Option<SeenIdHash>,
last_duplicate_id: Option<SeenIdHash>,
reject_reason: Option<String>,
rejection: Option<Rejection>,
reply_message_id: Option<usize>,
did_reject: bool,
do_discard: bool,
@ -90,6 +93,11 @@ struct SieveHandler<'x, 'r> {
pending: Option<PendingWork<'x>>,
}
enum Rejection {
Mdn(String),
Protocol(String),
}
enum PendingWork<'x> {
Include {
name: String,
@ -283,12 +291,16 @@ impl SieveHandler<'_, '_> {
notify: Notify,
message_id: usize,
) {
let (sender_address, return_path) = if source == MessageSource::Vacation {
self.reply_message_id = Some(message_id);
self.vacation_id = self.last_duplicate_id;
("", AutogeneratedReturnPath::Null)
} else {
(self.mail_from, AutogeneratedReturnPath::Account)
let (sender_address, return_path) = match source {
MessageSource::Vacation => {
self.reply_message_id = Some(message_id);
self.vacation_id = self.last_duplicate_id;
("", AutogeneratedReturnPath::Null)
}
MessageSource::Redirect if self.envelope_from.is_empty() => {
("", AutogeneratedReturnPath::Null)
}
_ => (self.mail_from, AutogeneratedReturnPath::Account),
};
let Some(message) = self.messages.get(message_id) else {
trc::event!(
@ -513,9 +525,16 @@ impl<'x> Handler<'x> for SieveHandler<'x, '_> {
SieveAction::Discard => {
self.do_discard = true;
}
SieveAction::Reject { reason, .. } => {
if self.return_path_status == ReturnPathStatus::Verified {
self.reject_reason = reason.to_string().into();
SieveAction::Reject { extended, reason } => {
if self.return_path_status == ReturnPathStatus::Verified
&& !self.envelope_from.is_empty()
{
let reason = reason.to_string();
self.rejection = Some(if extended {
Rejection::Protocol(reason)
} else {
Rejection::Mdn(reason)
});
}
self.did_reject = true;
self.do_discard = true;
@ -699,6 +718,7 @@ impl SieveScriptIngest for Server {
resolved: Vec::new(),
has_mailboxes: false,
mail_from,
envelope_from,
return_path_status,
spam_percentage: envelope_to.spam_percentage,
server_name: self.core.network.server_name.as_str(),
@ -716,7 +736,7 @@ impl SieveScriptIngest for Server {
seen_ids: Vec::new(),
vacation_id: None,
last_duplicate_id: None,
reject_reason: None,
rejection: None,
reply_message_id: None,
did_reject: false,
do_discard: false,
@ -878,7 +898,7 @@ impl SieveScriptIngest for Server {
autogenerated: mut generated,
mut seen_ids,
vacation_id,
reject_reason,
rejection,
reply_message_id,
did_reject,
do_discard,
@ -898,6 +918,35 @@ impl SieveScriptIngest for Server {
);
}
drop(ctx);
let reject_mdn = match &rejection {
Some(Rejection::Mdn(reason))
if !message.root_part().is_content_type("multipart", "report") =>
{
let mdn = Mdn {
subject: Some(match message.subject() {
Some(subject) => format!("Rejected: {subject}"),
None => "Rejected".to_string(),
}),
text_body: Some(format!(
"Your message was refused by the recipient's mail filtering program.\r\nThe reason given was as follows:\r\n\r\n{reason}\r\n"
)),
reporting_ua: Some(format!("{}; Stalwart", self.core.network.server_name)),
original_recipient: envelope_to
.orcpt_parameter()
.filter(|orcpt| is_valid_field_value(orcpt)),
final_recipient: Some(format!("rfc822;{}", envelope_to.address)),
original_message_id: message
.message_id()
.filter(|id| is_valid_field_value(id))
.map(|id| format!("<{id}>")),
..Default::default()
};
Some((mdn, !message.root_part().raw_headers().is_ascii()))
}
_ => None,
};
let mut message = Some(message);
if did_reject && let Some(reply_id) = reply_message_id {
@ -976,7 +1025,10 @@ impl SieveScriptIngest for Server {
}
}
if reject_reason.is_some() || has_delivered || last_temp_error.is_none() {
if matches!(rejection, Some(Rejection::Protocol(_)))
|| has_delivered
|| last_temp_error.is_none()
{
if !seen_ids.is_empty() {
let mut batch = BatchBuilder::new();
SeenId::write_all(&seen_ids, account_id, &mut batch);
@ -1000,18 +1052,61 @@ impl SieveScriptIngest for Server {
autogenerated.append(&mut generated);
}
if let Some(reject_reason) = reject_reason {
Err(
trc::EventType::MessageIngest(trc::MessageIngestEvent::Error)
.ctx(trc::Key::Code, 571)
.ctx(trc::Key::Reason, reject_reason),
match rejection {
Some(Rejection::Protocol(reason)) => Err(trc::EventType::MessageIngest(
trc::MessageIngestEvent::Error,
)
} else if has_delivered || last_temp_error.is_none() {
Ok(ingested_message)
} else {
// There were problems during delivery
#[allow(clippy::unnecessary_unwrap)]
Err(last_temp_error.unwrap())
.ctx(trc::Key::Code, 571)
.ctx(trc::Key::Reason, reason)),
Some(Rejection::Mdn(_)) => match last_temp_error {
Some(err) if !has_delivered => Err(err),
_ => {
if let Some((mdn, utf8_headers)) = reject_mdn {
let max_size = self.core.email.mail_max_size;
let to = [envelope_from.to_string()];
let mut mdn_message = MdnMessage {
mdn: &mdn,
disposition: Disposition {
action_mode: ActionMode::Automatic,
sending_mode: SendingMode::Automatic,
disposition_type: DispositionType::Deleted,
},
from_name: account_info.description(),
from_address: mail_from,
to: &to,
original_message: (raw_message.len() < max_size).then_some(
OriginalMessage {
raw: raw_message,
utf8_headers,
},
),
};
let raw = match mdn_message.build() {
Some(raw) if raw.len() > max_size => {
mdn_message.original_message = None;
mdn_message.build()
}
raw => raw,
};
if let Some(raw) = raw {
let [recipient] = to;
autogenerated.push(AutogeneratedMessage {
account_address: mail_from.to_string(),
return_path: AutogeneratedReturnPath::Null,
recipients: vec![recipient],
message: raw,
notify: Notify::Never,
source: MessageSource::Notification,
spam_percentage: None,
exploded: false,
});
}
}
Ok(ingested_message)
}
},
None if has_delivered => Ok(ingested_message),
None => last_temp_error.map_or(Ok(ingested_message), Err),
}
}

View file

@ -472,10 +472,7 @@ impl<'s> Decoder<'s> {
actions.discard = true;
ActionSlot::Discard
}
Op::Reject {
ereject: false,
reason,
} => {
Op::Reject { reason, .. } => {
actions.reject = Some(MailRuleReject {
reason: self.string(reason)?,
});

View file

@ -39,11 +39,11 @@ const CAPABILITY_NAMES: [&str; 20] = [
"editheader",
"envelope",
"environment",
"ereject",
"fileinto",
"imap4flags",
"mailboxid",
"mime",
"reject",
"relational",
"spamtest",
"spamtestplus",
@ -130,11 +130,11 @@ impl Capabilities {
const EDITHEADER: u32 = 1 << 4;
const ENVELOPE: u32 = 1 << 5;
const ENVIRONMENT: u32 = 1 << 6;
const FILEINTO: u32 = 1 << 7;
const IMAP4FLAGS: u32 = 1 << 8;
const MAILBOXID: u32 = 1 << 9;
const MIME: u32 = 1 << 10;
const REJECT: u32 = 1 << 11;
const EREJECT: u32 = 1 << 7;
const FILEINTO: u32 = 1 << 8;
const IMAP4FLAGS: u32 = 1 << 9;
const MAILBOXID: u32 = 1 << 10;
const MIME: u32 = 1 << 11;
const RELATIONAL: u32 = 1 << 12;
const SPAMTEST: u32 = 1 << 13;
const SPAMTESTPLUS: u32 = 1 << 14;
@ -251,7 +251,7 @@ impl Capabilities {
};
}
if actions.reject.is_some() {
caps |= Self::REJECT;
caps |= Self::EREJECT;
}
caps
}
@ -860,7 +860,7 @@ fn write_actions(
out.push_str("discard;\r\n");
}
if let Some(reject) = &actions.reject {
out.push_str("reject ");
out.push_str("ereject ");
write_quoted(out, &reject.reason);
out.push_str(";\r\n");
}

View file

@ -1,29 +1,29 @@
[package]
name = "exchange-proto"
description = "EWS, Autodiscover, Exchange ActiveSync and MAPI over HTTP protocol codecs"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
license = "AGPL-3.0-only OR LicenseRef-SEL"
publish = false
[dependencies]
ahash = "0.8.12"
ammonia = "4.2.4"
ahash = "0.8.14"
ammonia = "4.2.5"
arrayvec = "0.7"
bytes = "1"
calcard = { path = "../calcard", optional = true }
compact_str = "0.10.0"
crc32fast = "1.5"
encodify = "1.0"
hashbrown = "0.17.1"
hashbrown = "0.17.2"
hashify = "0.3"
html5ever = "0.40"
jiff = { version = "0.2.38", optional = true }
jiff = { version = "1.0.3", optional = true }
mail-builder = { version = "2.0", optional = true }
mail-parser = { version = "1.0", features = ["full_encoding"], optional = true }
memchr = "2.8.3"
quick-xml = "0.42"
roaring = "0.11"
roaring = "0.12"
simdutf8 = "0.1.5"
smallvec = { version = "1.16", features = ["union"] }

View file

@ -757,7 +757,7 @@ fn compact(instant: Timestamp) -> Compact {
fn local_as_utc(zoned: ZonedDateTime) -> EasDateTime {
let local = zoned.naive_local();
let seconds = local
.to_zoned(TimeZone::UTC)
.to_zoned_datetime(TimeZone::UTC)
.map_or(0, |zoned| zoned.timestamp().as_second());
EasDateTime(UtcSeconds(seconds), 0)
}

View file

@ -86,13 +86,17 @@ pub fn event_from_eas(ical: &mut ICalendar, update: &EventUpdate<'_>) -> Result<
.position(|component| component.component_type == ICalendarComponentType::VEvent)
.ok_or(ConvertError::Unsupported)?;
let all_day = calendar.all_day_event == Some(ALL_DAY);
let recurrence = calendar
.recurrence
.as_ref()
.filter(|recurrence| recurrence.recurrence_type.is_some());
let (start, end) = event_times(calendar, all_day, update.now)?;
let zone = if all_day && update.version >= ProtocolVersion::V160 {
Zone::Named(TimeTarget {
tz: Tz::UTC,
tzid: None,
})
} else if calendar.recurrence.is_some() {
} else if recurrence.is_some() {
Zone::decode(calendar.timezone.as_ref()).resolved(start)
} else {
Zone::decode(calendar.timezone.as_ref())
@ -116,7 +120,7 @@ pub fn event_from_eas(ical: &mut ICalendar, update: &EventUpdate<'_>) -> Result<
};
let mut dtstart = zone.time_entry(ICalendarProperty::Dtstart, start, all_day)?;
let form = time_form(&dtstart);
let (start, end, rule) = match &calendar.recurrence {
let (start, end, rule) = match recurrence {
Some(recurrence) => {
check_occurrences(recurrence)?;
let rule = recurrence_rule(recurrence, utc(start), &zone, form)?;
@ -185,7 +189,7 @@ pub fn event_from_eas(ical: &mut ICalendar, update: &EventUpdate<'_>) -> Result<
if let Some(OrEmpty(Some(minutes))) = calendar.reminder {
add_alarm(ical, main, minutes)?;
}
if calendar.recurrence.is_some() {
if recurrence.is_some() {
let exceptions = calendar
.exceptions
.as_ref()

View file

@ -390,7 +390,7 @@ impl Moment {
(_, Some(local), _) => {
let wall = Timestamp::from_second(local)
.ok()?
.to_zoned(TimeZone::UTC)
.to_zoned_datetime(TimeZone::UTC)
.datetime();
target.tz.from_local(wall).map(|zoned| zoned.to_timestamp())
}

View file

@ -110,13 +110,13 @@ pub(super) fn instance_start(props: &PropBag) -> Result<Option<Timestamp>, Conve
let Some(OwnedPropValue::Time(start)) = props.get_any(START_WHOLE.prop()) else {
return Err(ConvertError::Unsupported);
};
let time = timestamp(*start).to_zoned(TimeZone::UTC).time();
let time = timestamp(*start).to_zoned_datetime(TimeZone::UTC).time();
i16::try_from(year)
.ok()
.zip(i8::try_from(month).ok())
.zip(i8::try_from(day).ok())
.and_then(|((year, month), day)| Date::new(year, month, day).ok())
.and_then(|date| date.to_datetime(time).to_zoned(TimeZone::UTC).ok())
.and_then(|date| date.to_datetime(time).to_zoned_datetime(TimeZone::UTC).ok())
.map(|zoned| Some(zoned.timestamp()))
.ok_or(ConvertError::Unsupported)
}

View file

@ -597,7 +597,7 @@ fn set_date(
}
if let Some(midnight) = partner_date
.filter(|_| has_time(component, &partner))
.and_then(|date| date.to_zoned(TimeZone::UTC).ok())
.and_then(|date| date.to_zoned_datetime(TimeZone::UTC).ok())
{
remove_all(component, &partner);
component
@ -713,7 +713,7 @@ fn materialize_due(component: &mut ICalendarComponent, pending: ImpliedDue) {
entry
}
_ => {
let Ok(midnight) = due.to_zoned(TimeZone::UTC) else {
let Ok(midnight) = due.to_zoned_datetime(TimeZone::UTC) else {
return;
};
utc_target().entry(ICalendarProperty::Due, midnight.timestamp(), true)

View file

@ -185,7 +185,7 @@ fn local_midnight(value: ZonedDateTime) -> Option<Timestamp> {
value
.naive_local()
.date()
.to_zoned(TimeZone::UTC)
.to_zoned_datetime(TimeZone::UTC)
.ok()
.map(|zoned| zoned.timestamp())
}

View file

@ -412,7 +412,7 @@ impl<'c> Writer<'_, 'c> {
if let Some(time) = other_text(main, SEQUENCE_TIME_NAME).and_then(|value| {
DateTime::strptime(SEQUENCE_TIME_FORMAT, value.trim())
.ok()?
.to_zoned(TimeZone::UTC)
.to_zoned_datetime(TimeZone::UTC)
.ok()
}) {
set_time(bag, SEQUENCE_TIME.key(), time.timestamp());

View file

@ -749,7 +749,7 @@ pub(super) fn impp_handle(uri: &str) -> &str {
fn utc_date(time: FileTime) -> Option<PartialDateTime> {
let date = Timestamp::from_second(time.to_utc().0.0)
.ok()?
.to_zoned(jiff::tz::TimeZone::UTC)
.to_zoned_datetime(jiff::tz::TimeZone::UTC)
.date();
Some(PartialDateTime {
year: u16::try_from(date.year()).ok(),

View file

@ -1075,7 +1075,7 @@ fn text_date(text: &str) -> Option<Date> {
fn file_time(date: Date, hour: i8, minute: i8) -> Option<FileTime> {
let seconds = date
.to_datetime(Time::new(hour, minute, 0, 0).ok()?)
.to_zoned(TimeZone::UTC)
.to_zoned_datetime(TimeZone::UTC)
.ok()?
.timestamp()
.as_second();
@ -1101,7 +1101,7 @@ fn utc_time(value: &PartialDateTime) -> Option<FileTime> {
.ok()?;
let local = date
.to_datetime(time)
.to_zoned(TimeZone::UTC)
.to_zoned_datetime(TimeZone::UTC)
.ok()?
.timestamp()
.as_second();

View file

@ -219,8 +219,11 @@ pub(crate) fn read_id<'a>(
tag: Tag,
max: usize,
) -> Result<Cow<'a, str>, CommandError> {
let value = read_str(dec, tag)?;
if value.len() <= max {
read_str(dec, tag).and_then(|value| bounded(value, tag, max))
}
pub(crate) fn bounded<T: AsRef<str>>(value: T, tag: Tag, max: usize) -> Result<T, CommandError> {
if value.as_ref().len() <= max {
Ok(value)
} else {
Err(CommandError::InvalidValue { tag })

View file

@ -9,9 +9,10 @@ use std::borrow::Cow;
use super::appdata::email::{Forwardee, Forwardees};
use super::appdata::{Body, Value};
use super::{
Children, CommandError, MAX_ID_LEN, MAX_LONG_ID_LEN, read_bytes, read_date, read_id, read_str,
required,
Children, CommandError, MAX_ID_LEN, MAX_LONG_ID_LEN, bounded, read_bytes, read_date, read_id,
read_str, required,
};
use crate::eas::http::RequestParams;
use crate::eas::status::Status;
use crate::eas::tokens::tag::{airsyncbase as asb, compose_mail as cm, rights_management as rm};
use crate::eas::tokens::{ProtocolVersion, Tag};
@ -116,9 +117,57 @@ impl<'a> ComposeRequest<'a> {
}
Ok(request)
}
pub fn from_mime(
params: &'a RequestParams<'_>,
mime: &'a [u8],
command: ComposeCommand,
) -> Result<Self, CommandError> {
let source = match command {
ComposeCommand::SendMail => None,
ComposeCommand::SmartReply | ComposeCommand::SmartForward => {
Some(Source::from_params(params)?)
}
};
Ok(ComposeRequest {
command,
client_id: Cow::Borrowed(""),
source,
account_id: None,
save_in_sent: params.save_in_sent,
replace_mime: false,
mime: Cow::Borrowed(mime),
template_id: None,
body: None,
forwardees: Vec::new(),
})
}
}
impl<'a> Source<'a> {
fn from_params(params: &'a RequestParams<'_>) -> Result<Self, CommandError> {
let id = |value: &'a Option<Cow<'_, str>>, tag: Tag, max: usize| {
value
.as_deref()
.map(|value| bounded(value, tag, max).map(Cow::Borrowed))
.transpose()
};
Ok(Source {
folder_id: id(&params.collection_id, cm::FOLDER_ID, MAX_ID_LEN)?,
item_id: id(&params.item_id, cm::ITEM_ID, MAX_ID_LEN)?,
long_id: id(&params.long_id, cm::LONG_ID, MAX_LONG_ID_LEN)?,
instance_id: params
.occurrence
.as_deref()
.map(|occurrence| {
EasDateTime::parse(occurrence.as_bytes()).ok_or(CommandError::InvalidDate {
tag: cm::INSTANCE_ID,
})
})
.transpose()?,
})
}
fn parse(dec: &mut Decoder<'a>) -> Result<Self, CommandError> {
let mut source = Source::default();
let mut children = Children::of(dec);

View file

@ -181,6 +181,7 @@ impl From<Truncated> for HttpError {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BodyKind {
Wbxml,
Mime,
Empty,
Other,
}
@ -197,15 +198,15 @@ pub fn classify_body(content_type: Option<&[u8]>, len: usize) -> BodyKind {
.next()
.unwrap_or_default()
.trim_ascii();
if hashify::set_ignore_case!(
hashify::map_ignore_case!(
media,
"application/vnd.ms-sync.wbxml",
"application/vnd.ms-sync"
) {
BodyKind::Wbxml
} else {
BodyKind::Other
}
BodyKind,
"application/vnd.ms-sync.wbxml" => BodyKind::Wbxml,
"application/vnd.ms-sync" => BodyKind::Wbxml,
"message/rfc822" => BodyKind::Mime,
)
.copied()
.unwrap_or(BodyKind::Other)
}
pub fn parse_request_line<'a>(

View file

@ -0,0 +1,289 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
pub const MAX_KQL_DEPTH: usize = 8;
pub const MAX_KQL_TERMS: usize = 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KqlProperty {
From,
To,
Cc,
Bcc,
Participants,
Recipients,
Subject,
Body,
Attachment,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KqlNode<'a> {
And,
Or,
Not,
End,
Term {
property: Option<KqlProperty>,
value: &'a str,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FreeText<'a> {
Keywords(&'a str),
Query(Vec<KqlNode<'a>>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Lexeme<'a> {
Open,
Close,
And,
Or,
Not,
Property(Option<KqlProperty>),
Value(&'a str),
}
struct Lexer<'a> {
rest: &'a str,
}
struct TooDeep;
struct Parser<'a, F> {
lexer: Lexer<'a>,
peeked: Option<Lexeme<'a>>,
nodes: Vec<KqlNode<'a>>,
terms: usize,
structured: bool,
accept: F,
}
impl<'a> FreeText<'a> {
pub fn parse(text: &'a str, accept: impl Fn(&str) -> bool) -> Self {
let mut parser = Parser {
lexer: Lexer { rest: text },
peeked: None,
nodes: Vec::new(),
terms: 0,
structured: false,
accept,
};
match parser.or_expr(0) {
Ok(_) if parser.structured => FreeText::Query(parser.nodes),
Ok(_) | Err(TooDeep) => FreeText::Keywords(text),
}
}
}
impl<'a> Iterator for Lexer<'a> {
type Item = Lexeme<'a>;
fn next(&mut self) -> Option<Lexeme<'a>> {
let text = self.rest.trim_start();
if let Some(rest) = text.strip_prefix('(') {
self.rest = rest;
return Some(Lexeme::Open);
}
if let Some(rest) = text.strip_prefix(')') {
self.rest = rest;
return Some(Lexeme::Close);
}
if let Some(body) = text.strip_prefix('"') {
let (phrase, rest) = body
.split_once('"')
.and_then(|(inner, _)| text.split_at_checked(inner.len() + 2))
.unwrap_or((body, ""));
self.rest = rest;
return Some(Lexeme::Value(phrase));
}
let (run, rest) = text
.find(|c: char| c.is_whitespace() || matches!(c, '(' | ')' | '"'))
.and_then(|end| text.split_at_checked(end))
.unwrap_or((text, ""));
if run.is_empty() {
return None;
}
self.rest = rest;
if let Some(keyword) = hashify::map!(
run.as_bytes(),
Lexeme<'static>,
"AND" => Lexeme::And,
"OR" => Lexeme::Or,
"NOT" => Lexeme::Not,
) {
return Some(*keyword);
}
if let Some((name, _)) = run.split_once(':')
&& let Some(property) = hashify::map_ignore_case!(
name.as_bytes(),
Option<KqlProperty>,
"from" => Some(KqlProperty::From),
"to" => Some(KqlProperty::To),
"cc" => Some(KqlProperty::Cc),
"bcc" => Some(KqlProperty::Bcc),
"participants" => Some(KqlProperty::Participants),
"recipients" => Some(KqlProperty::Recipients),
"subject" => Some(KqlProperty::Subject),
"body" => Some(KqlProperty::Body),
"attachment" => Some(KqlProperty::Attachment),
"attachmentnames" => Some(KqlProperty::Attachment),
"category" => None,
"folderid" => None,
"hasattachment" => None,
"importance" => None,
"isread" => None,
"itemclass" => None,
"kind" => None,
"received" => None,
"sent" => None,
"size" => None,
)
{
self.rest = text.get(name.len() + 1..).unwrap_or(rest);
return Some(Lexeme::Property(*property));
}
Some(Lexeme::Value(run))
}
}
impl<'a, F: Fn(&str) -> bool> Parser<'a, F> {
fn lex(&mut self) -> Option<Lexeme<'a>> {
if self.terms < MAX_KQL_TERMS {
self.lexer.next()
} else {
None
}
}
fn peek(&mut self) -> Option<Lexeme<'a>> {
if self.peeked.is_none() {
self.peeked = self.lex();
}
self.peeked
}
fn advance(&mut self) -> Option<Lexeme<'a>> {
self.peeked.take().or_else(|| self.lex())
}
fn group(&mut self, start: usize, operands: usize, op: KqlNode<'a>) {
if operands > 1 {
self.nodes.insert(start, op);
self.nodes.push(KqlNode::End);
}
}
fn or_expr(&mut self, depth: usize) -> Result<bool, TooDeep> {
let start = self.nodes.len();
let mut operands = 0;
loop {
if self.and_expr(depth)? {
operands += 1;
}
if self.peek() != Some(Lexeme::Or) {
break;
}
self.advance();
self.structured = true;
}
self.group(start, operands, KqlNode::Or);
Ok(operands > 0)
}
fn and_expr(&mut self, depth: usize) -> Result<bool, TooDeep> {
let start = self.nodes.len();
let mut operands = 0;
loop {
match self.peek() {
None | Some(Lexeme::Or) => break,
Some(Lexeme::Close) if depth > 0 => break,
Some(Lexeme::Close) => {
self.advance();
}
Some(Lexeme::And) => {
self.advance();
self.structured = true;
}
Some(_) => {
if self.unary(depth)? {
operands += 1;
}
}
}
}
self.group(start, operands, KqlNode::And);
Ok(operands > 0)
}
fn unary(&mut self, depth: usize) -> Result<bool, TooDeep> {
if matches!(
self.peek(),
None | Some(Lexeme::And | Lexeme::Or | Lexeme::Close)
) {
return Ok(false);
}
match self.advance() {
Some(Lexeme::Not) => {
self.structured = true;
let depth = nested(depth)?;
self.nodes.push(KqlNode::Not);
if self.unary(depth)? {
self.nodes.push(KqlNode::End);
Ok(true)
} else {
self.nodes.pop();
Ok(false)
}
}
Some(Lexeme::Open) => {
self.structured = true;
let emitted = self.or_expr(nested(depth)?)?;
if self.peek() == Some(Lexeme::Close) {
self.advance();
}
Ok(emitted)
}
Some(Lexeme::Property(property)) => {
self.structured = true;
match self.peek() {
Some(Lexeme::Value(value)) => {
self.advance();
Ok(property.is_some_and(|property| self.term(Some(property), value)))
}
_ => Ok(false),
}
}
Some(Lexeme::Value(value)) => Ok(self.term(None, value)),
Some(Lexeme::And | Lexeme::Or | Lexeme::Close) | None => Ok(false),
}
}
fn term(&mut self, property: Option<KqlProperty>, value: &'a str) -> bool {
if !(self.accept)(value) {
return false;
}
self.terms += 1;
self.nodes.push(KqlNode::Term { property, value });
true
}
}
fn nested(depth: usize) -> Result<usize, TooDeep> {
let depth = depth + 1;
if depth > MAX_KQL_DEPTH {
Err(TooDeep)
} else {
Ok(depth)
}
}
#[cfg(all(test, stalwart_tests))]
#[rustfmt::skip]
#[path = "../../../../../stalwart-tests/unit/exchange-proto/src/eas/kql/tests.rs"]
mod tests;

View file

@ -6,6 +6,7 @@
pub mod commands;
pub mod http;
pub mod kql;
pub mod multipart;
pub mod status;
pub mod tokens;

View file

@ -413,7 +413,7 @@ impl CalendarEdit {
};
start
.unwrap_or_else(Timestamp::now)
.to_zoned(TimeZone::UTC)
.to_zoned_datetime(TimeZone::UTC)
.year()
}

View file

@ -1,6 +1,6 @@
[package]
name = "exchange"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]
@ -16,10 +16,10 @@ http_proto = { path = "../http-proto" }
types = { path = "../types" }
registry = { path = "../registry" }
trc = { path = "../trc" }
ahash = { version = "0.8.12" }
ahash = { version = "0.8.14" }
hashify = "0.3"
hyper = { version = "1.12.0", features = ["server", "http1", "http2"] }
jiff = "0.2.38"
hyper = { version = "1.13.0", features = ["server", "http1", "http2"] }
jiff = "1.0.3"
rkyv.workspace = true
smallvec = { version = "1.16", features = ["union"] }
mail-builder = { version = "2.0" }

View file

@ -50,7 +50,8 @@ use exchange_proto::{
};
use groupware::cache::GroupwareCache;
use jiff::Timestamp;
use store::{ValueKey, rand, write::now};
use std::fmt::Debug;
use store::{ValueKey, blake3, rand, write::now};
use trc::{AddContext, EventType, LimitEvent};
use types::{
collection::{Collection, SyncCollection},
@ -62,11 +63,17 @@ const MERGE_MEMORY_FACTOR: usize = 4;
const TRANSIENT_REPLY: char = '4';
const TOO_MANY_RECIPIENTS: &str = ".5.3";
pub enum ComposeBody<'a, 'b> {
Wbxml(&'b mut Decoder<'a>),
Mime(&'a [u8]),
Missing,
}
pub trait EasCompose: Sync + Send {
fn eas_compose(
&self,
ctx: &EasContext<'_>,
decoder: Option<&mut Decoder<'_>>,
body: ComposeBody<'_, '_>,
command: ComposeCommand,
) -> impl Future<Output = trc::Result<EasResponse>> + Send;
}
@ -75,7 +82,7 @@ impl EasCompose for Server {
async fn eas_compose(
&self,
ctx: &EasContext<'_>,
decoder: Option<&mut Decoder<'_>>,
body: ComposeBody<'_, '_>,
command: ComposeCommand,
) -> trc::Result<EasResponse> {
let http_command = match command {
@ -83,16 +90,40 @@ impl EasCompose for Server {
ComposeCommand::SmartReply => Command::SmartReply,
ComposeCommand::SmartForward => Command::SmartForward,
};
let failed = |status: Status| Ok(EasResponse::status(http_command, status));
let Some(decoder) = decoder else {
return failed(CommonStatus::INVALID_XML.into());
let failed = |status: Status, reason: &dyn Debug| {
Ok(EasResponse::refused(
ctx.session.session_id,
ctx.account_id,
http_command,
status,
reason,
))
};
let request = match ComposeRequest::parse(decoder, ctx.version, command) {
Ok(request) => request,
Err(err) => return failed(err.status(http_command)),
let (request, once) = match body {
ComposeBody::Wbxml(decoder) => {
match ComposeRequest::parse(decoder, ctx.version, command) {
Ok(request) => {
let once = SubmitOnce::eas(ctx.device.slot, request.client_id.as_bytes());
(request, once)
}
Err(err) => return failed(err.status(http_command), &err),
}
}
ComposeBody::Mime(mime) => {
match ComposeRequest::from_mime(&ctx.params, mime, command) {
Ok(request) => (
request,
SubmitOnce::eas(ctx.device.slot, blake3::hash(mime).as_bytes()),
),
Err(err) => return failed(err.status(http_command), &err),
}
}
ComposeBody::Missing => {
return failed(CommonStatus::INVALID_XML.into(), &Refusal::MissingBody);
}
};
if !ctx.allows(EasDataKind::Mail) {
return failed(CommonStatus::ACCESS_DENIED.into());
return failed(CommonStatus::ACCESS_DENIED.into(), &Refusal::MailNotAllowed);
}
if let Some(account_id) = request.account_id.as_deref()
&& !self
@ -102,10 +133,10 @@ impl EasCompose for Server {
.iter()
.any(|address| address.eq_ignore_ascii_case(account_id))
{
return failed(CommonStatus::INVALID_ACCOUNT_ID.into());
return failed(CommonStatus::INVALID_ACCOUNT_ID.into(), &Refusal::AccountId);
}
if request.template_id.is_some() {
return failed(CommonStatus::IRM_FEATURE_DISABLED.into());
return failed(CommonStatus::IRM_FEATURE_DISABLED.into(), &Refusal::Irm);
}
let cache = self.get_cached_messages(ctx.account_id).await?;
@ -165,8 +196,10 @@ impl EasCompose for Server {
let raw = match outcome {
Ok(SmartOutcome::Merged(raw)) => raw,
Ok(SmartOutcome::Unmerged) => request.mime.into_owned(),
Ok(SmartOutcome::InvalidClient) => return failed(CommonStatus::INVALID_MIME.into()),
Err(status) => return failed(status),
Ok(SmartOutcome::InvalidClient) => {
return failed(CommonStatus::INVALID_MIME.into(), &Refusal::ClientMime);
}
Err(status) => return failed(status, &Refusal::Source),
};
let raw = match (source, &source_row) {
(
@ -202,7 +235,7 @@ impl EasCompose for Server {
message: Outgoing::Composed { raw, save_copy },
recipients: Recipients::Headers,
options: SubmitOptions {
once: SubmitOnce::eas(ctx.device.slot, &request.client_id),
once,
delivery_report: DeliveryReport::FromMessage,
..Default::default()
},
@ -215,7 +248,7 @@ impl EasCompose for Server {
}
Ok(EasResponse::Empty)
}
Err(err) => failed(submit_status(&err, ctx.version)),
Err(err) => failed(submit_status(&err, ctx.version), &err),
}
}
}
@ -303,6 +336,16 @@ async fn mark_source_once(
.await
}
#[derive(Debug)]
enum Refusal {
MissingBody,
MailNotAllowed,
AccountId,
Irm,
Source,
ClientMime,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SourceItem {
Mail {

View file

@ -192,7 +192,7 @@ async fn find_mail(
}
let cache = server.get_cached_messages(ctx.account_id).await?;
let mut search = MailSearch::default();
search.push_text(free_text, server.core.email.default_language);
search.push_free_text(free_text, server.core.email.default_language);
if class.is_some_and(|class| class != Class::Email) {
search.empty = true;
}

View file

@ -8,6 +8,7 @@ use super::{context::EasContext, sync::estimate::mail_folder};
use crate::folders::FolderNode;
use ::email::cache::{email::MessageCacheAccess, mailbox::MailboxCacheAccess};
use common::{MessageStoreCache, Server, cache::email::MessageRef};
use exchange_proto::eas::kql::{FreeText, KqlNode, KqlProperty};
use nlp::language::Language;
use smallvec::SmallVec;
use std::mem;
@ -45,6 +46,12 @@ pub enum TextFields {
Contacts,
}
#[derive(Debug, Clone, Copy)]
enum TextTarget {
Fields,
Email(&'static [EmailSearchField]),
}
#[derive(Debug, Clone, Copy)]
pub struct MailHit {
pub document_id: u32,
@ -173,26 +180,86 @@ impl MailSearch {
}
}
pub fn push_free_text(&mut self, text: &str, language: Language) {
let nodes = match FreeText::parse(text, |value| {
TextToken::parse(value).is_some_and(|token| token.term(TokenPosition::Inner).is_some())
}) {
FreeText::Keywords(text) => {
self.push_text(text, language);
return;
}
FreeText::Query(nodes) => nodes,
};
let last = nodes
.iter()
.rposition(|node| matches!(node, KqlNode::Term { .. }));
for (index, node) in nodes.iter().enumerate() {
match *node {
KqlNode::And => self.text.push(SearchFilter::And),
KqlNode::Or => self.text.push(SearchFilter::Or),
KqlNode::Not => self.text.push(SearchFilter::Not),
KqlNode::End => self.text.push(SearchFilter::End),
KqlNode::Term { property, value } => {
let position = if last == Some(index) {
TokenPosition::Last
} else {
TokenPosition::Inner
};
let target = property.map_or(TextTarget::Fields, |property| {
TextTarget::Email(property_fields(property))
});
if let Some(term) =
TextToken::parse(value).and_then(|token| token.term(position))
{
self.push_term_in(term, target, language);
}
}
}
}
}
fn push_term(&mut self, term: TextTerm<'_>, language: Language) {
self.push_term_in(term, TextTarget::Fields, language);
}
fn push_term_in(&mut self, term: TextTerm<'_>, target: TextTarget, language: Language) {
match term {
TextTerm::Prefix { word, prefix } => {
self.text.push(SearchFilter::Or);
self.fields.push(&mut self.text, word, language);
self.fields
.push(&mut self.text, &format!("{prefix}*"), language);
self.push_target(target, word, language);
self.push_target(target, &format!("{prefix}*"), language);
self.text.push(SearchFilter::End);
}
TextTerm::Split { word, head, tail } => {
self.text.push(SearchFilter::Or);
self.fields.push(&mut self.text, word, language);
self.push_target(target, word, language);
self.text.push(SearchFilter::And);
self.fields.push(&mut self.text, head, language);
self.fields
.push(&mut self.text, &format!("{tail}*"), language);
self.push_target(target, head, language);
self.push_target(target, &format!("{tail}*"), language);
self.text.push(SearchFilter::End);
self.text.push(SearchFilter::End);
}
TextTerm::Word(word) => self.fields.push(&mut self.text, word, language),
TextTerm::Word(word) => self.push_target(target, word, language),
}
}
fn push_target(&mut self, target: TextTarget, text: &str, language: Language) {
match target {
TextTarget::Fields => self.fields.push(&mut self.text, text, language),
TextTarget::Email(fields) => {
self.text.push(SearchFilter::Or);
self.text.extend(fields.iter().map(|field| {
let language = match field {
EmailSearchField::From
| EmailSearchField::To
| EmailSearchField::Cc
| EmailSearchField::Bcc => Language::None,
_ => language,
};
SearchFilter::has_text(field.clone(), text, language)
}));
self.text.push(SearchFilter::End);
}
}
}
@ -286,6 +353,29 @@ impl MailSearch {
}
}
fn property_fields(property: KqlProperty) -> &'static [EmailSearchField] {
match property {
KqlProperty::From => &[EmailSearchField::From],
KqlProperty::To => &[EmailSearchField::To],
KqlProperty::Cc => &[EmailSearchField::Cc],
KqlProperty::Bcc => &[EmailSearchField::Bcc],
KqlProperty::Participants => &[
EmailSearchField::From,
EmailSearchField::To,
EmailSearchField::Cc,
EmailSearchField::Bcc,
],
KqlProperty::Recipients => &[
EmailSearchField::To,
EmailSearchField::Cc,
EmailSearchField::Bcc,
],
KqlProperty::Subject => &[EmailSearchField::Subject],
KqlProperty::Body => &[EmailSearchField::Body],
KqlProperty::Attachment => &[EmailSearchField::Attachment],
}
}
pub fn mailbox_tree(cache: &MessageStoreCache, root: u32) -> RoaringBitmap {
let mut subtree = RoaringBitmap::from_iter([root]);
loop {

View file

@ -30,7 +30,7 @@ pub mod sync;
pub mod wait;
use crate::eas::{
compose::EasCompose,
compose::{ComposeBody, EasCompose},
context::EasContext,
device::{DeviceGate, EasDeviceAccess},
find::EasFind,
@ -136,11 +136,23 @@ impl EasHandler for Server {
let command = line.command;
let body_kind = classify_body(content_type, body.len());
if body_kind == BodyKind::Other {
return Ok(
EasResponse::status(command, CommonStatus::INVALID_CONTENT.into())
.into_http(Some(version)),
);
let accepted = match body_kind {
BodyKind::Wbxml | BodyKind::Empty => true,
BodyKind::Mime => matches!(
command,
Command::SendMail | Command::SmartReply | Command::SmartForward
),
BodyKind::Other => false,
};
if !accepted {
return Ok(EasResponse::refused(
session.session_id,
access_token.account_id(),
command,
CommonStatus::INVALID_CONTENT.into(),
&eas_headers.content_type,
)
.into_http(Some(version)));
}
let Some(device_id) = line.device_id.as_str() else {
@ -176,11 +188,15 @@ impl EasHandler for Server {
let mut decoder = match body_kind {
BodyKind::Wbxml => match Decoder::new(&body, &WbxmlLimits::DEFAULT) {
Ok(decoder) => Some(decoder),
Err(_) => {
return Ok(
EasResponse::status(command, CommonStatus::INVALID_WBXML.into())
.into_http(Some(version)),
);
Err(err) => {
return Ok(EasResponse::refused(
ctx.session.session_id,
ctx.account_id,
command,
CommonStatus::INVALID_WBXML.into(),
&err,
)
.into_http(Some(version)));
}
},
_ => None,
@ -222,16 +238,28 @@ impl EasHandler for Server {
},
),
Command::SendMail => {
self.eas_compose(&ctx, decoder.as_mut(), ComposeCommand::SendMail)
.await?
self.eas_compose(
&ctx,
compose_body(decoder.as_mut(), body_kind, &body),
ComposeCommand::SendMail,
)
.await?
}
Command::SmartReply => {
self.eas_compose(&ctx, decoder.as_mut(), ComposeCommand::SmartReply)
.await?
self.eas_compose(
&ctx,
compose_body(decoder.as_mut(), body_kind, &body),
ComposeCommand::SmartReply,
)
.await?
}
Command::SmartForward => {
self.eas_compose(&ctx, decoder.as_mut(), ComposeCommand::SmartForward)
.await?
self.eas_compose(
&ctx,
compose_body(decoder.as_mut(), body_kind, &body),
ComposeCommand::SmartForward,
)
.await?
}
};
@ -239,6 +267,18 @@ impl EasHandler for Server {
}
}
fn compose_body<'a, 'b>(
decoder: Option<&'b mut Decoder<'a>>,
kind: BodyKind,
body: &'a [u8],
) -> ComposeBody<'a, 'b> {
match (decoder, kind) {
(Some(decoder), _) => ComposeBody::Wbxml(decoder),
(None, BodyKind::Mime) => ComposeBody::Mime(body),
(None, _) => ComposeBody::Missing,
}
}
pub(crate) const SUPPORTED_VERSIONS: &str = "14.1,16.1";
pub(crate) const IMPLEMENTED_COMMANDS: [Command; 19] = [
Command::Sync,

View file

@ -28,6 +28,7 @@ use hyper::{
header::{CONTENT_ENCODING, HeaderValue as HttpHeaderValue, VARY},
};
use std::{
fmt::Debug,
io::Write,
pin::Pin,
task::{Context, Poll},
@ -70,6 +71,26 @@ impl EasResponse {
EasResponse::Status { command, status }
}
#[cold]
#[inline(never)]
pub fn refused(
session_id: u64,
account_id: u32,
command: Command,
status: Status,
reason: &dyn Debug,
) -> Self {
trc::event!(
Http(trc::HttpEvent::Error),
SpanId = session_id,
AccountId = account_id,
Details = command.name(),
Code = status.0,
Reason = format!("{reason:?}"),
);
EasResponse::Status { command, status }
}
pub fn encode(version: ProtocolVersion, write: impl FnOnce(&mut Encoder)) -> Self {
let mut encoder = Encoder::new(version);
write(&mut encoder);

View file

@ -5,8 +5,8 @@
*/
use super::{
FolderCounts, FolderFieldSet, FolderRenderer, FolderSelector, props::FolderProp,
removed_folder_status, resolve_folder,
FolderCounts, FolderEntryIds, FolderFieldSet, FolderRenderer, FolderSelector,
props::FolderProp, removed_folder_status, resolve_folder,
};
use crate::{
ews::{
@ -58,6 +58,7 @@ pub(crate) async fn get_folder(
.filter_map(|entry| entry.as_ref().ok().copied()),
)
.await?,
entry_ids: FolderEntryIds::load(server, ctx, fields).await?,
};
let mut out = Vec::with_capacity(RESPONSE_CAPACITY);
@ -128,6 +129,7 @@ pub(crate) async fn find_folder(
} else {
FolderCounts::default()
},
entry_ids: FolderEntryIds::load(server, ctx, fields).await?,
};
let matches = parents
.iter()

View file

@ -14,16 +14,19 @@ use self::props::{EXTENDED_PROPS, FolderProp, change_time};
use super::context::{EwsContext, MailboxOwner};
use super::filter::PropValue;
use crate::{
cache::ExchangeCacheFetch,
folders::{
ContainerClass, FolderEntry, FolderNode, FolderTree, SpecialFolder, access::ViewRights,
rights::FolderRights,
},
mapi::{emsmdb::store::StoreGuids, ids::MapiId},
store::{FolderKind, FolderRef},
};
use ahash::AHashMap;
use common::{GroupwareResources, Server};
use common::{GroupwareResources, Server, cache::exchange::ExchangeAccountCache};
use email::cache::MessageCacheFetch;
use exchange_proto::{
common::base64::{base64_encode_into, base64_encoded_len},
ews::{
MessageXml, Status,
schema::{BaseShape, DistinguishedFolderName, ResponseCode, UnindexedField},
@ -53,6 +56,7 @@ const MAILBOX_ITEM_NOT_FOUND: &str = "The specified object was not found in the
const NON_EXISTENT_MAILBOX: &str = "The SMTP address has no mailbox associated with it.";
const SMTP_ADDRESS: &str = "SmtpAddress";
const SEEN_BIT: u32 = 1 << SEEN;
const ENTRY_ID_CAPACITY: usize = 46;
#[derive(Clone, Copy)]
pub(crate) enum FolderSelector<'r, 'a> {
@ -337,6 +341,17 @@ impl FolderFieldSet {
}
mask
};
const EXTENDED_ENTRY_ID: u32 = {
let mut mask = 0;
let mut index = 0;
while index < EXTENDED_PROPS.len() {
if EXTENDED_PROPS[index].2.is_entry_id() {
mask |= 1 << (Self::EXTENDED_SHIFT + index);
}
index += 1;
}
mask
};
const DEFAULT: u32 = Self::ID | Self::NAME | Self::TOTAL | Self::CHILDREN | Self::UNREAD;
const ALL: u32 = Self::DEFAULT | Self::PARENT | Self::CLASS | Self::RIGHTS;
@ -387,6 +402,10 @@ impl FolderFieldSet {
FolderFieldSet(self.0 | Self::TOTAL | Self::EXTENDED_TIMES)
}
fn needs_entry_ids(self) -> bool {
self.has(Self::EXTENDED_ENTRY_ID)
}
fn needs_change_times(self) -> bool {
self.has(Self::EXTENDED_TIMES)
}
@ -549,12 +568,45 @@ fn children_count(resources: Option<&GroupwareResources>, id: u32) -> usize {
resources.map_or(0, |resources| resources.children_ids(id).count())
}
pub(crate) struct FolderEntryIds {
exchange: Arc<ExchangeAccountCache>,
guids: StoreGuids,
}
impl FolderEntryIds {
pub async fn load(
server: &Server,
ctx: &EwsContext,
fields: FolderFieldSet,
) -> trc::Result<Option<Self>> {
if !fields.needs_entry_ids() {
return Ok(None);
}
let account_id = ctx.account.account_id;
let exchange = server.get_cached_exchange(account_id).await?;
let guids = StoreGuids::new(exchange.store_instance, account_id);
Ok(Some(FolderEntryIds { exchange, guids }))
}
fn base64(&self, node: FolderNode) -> Option<String> {
let mut entry_id = Vec::with_capacity(ENTRY_ID_CAPACITY);
self.guids
.folder_entry_id(MapiId::from_folder(&self.exchange, node))
.encode(&mut entry_id)
.ok()?;
let mut out = Vec::with_capacity(base64_encoded_len(entry_id.len()));
base64_encode_into(&entry_id, &mut out);
String::from_utf8(out).ok()
}
}
pub(crate) struct FolderRenderer<'t> {
pub tree: &'t FolderTree,
pub access: &'t ViewRights,
pub account_id: u32,
pub fields: FolderFieldSet,
pub counts: FolderCounts,
pub entry_ids: Option<FolderEntryIds>,
}
impl<'t> FolderRenderer<'t> {
@ -614,7 +666,7 @@ impl<'t> FolderRenderer<'t> {
target: XPropTarget::Tag(*tag),
ptype: *ptype,
},
value: XPropValue::Single(self.value(entry, *prop)?.to_text()),
value: XPropValue::Single(self.extended_text(entry, *prop)?),
})
})
.collect(),
@ -624,8 +676,17 @@ impl<'t> FolderRenderer<'t> {
kind.wrap(out)
}
fn extended_text(&self, entry: &'t FolderEntry, prop: FolderProp) -> Option<Cow<'t, str>> {
match prop {
FolderProp::EntryId => self.entry_ids.as_ref()?.base64(entry.node).map(Cow::Owned),
prop => self.value(entry, prop).map(PropValue::to_text),
}
}
pub fn value(&self, entry: &'t FolderEntry, prop: FolderProp) -> Option<PropValue<'t>> {
Some(match prop {
FolderProp::EntryId => return None,
FolderProp::AttrHidden => PropValue::Bool(false),
FolderProp::DisplayName => PropValue::Text(&entry.name),
FolderProp::Class => {
let class = entry.class.as_str();

View file

@ -26,9 +26,11 @@ pub(crate) enum FolderProp {
UnreadCount,
CommitTimeMax,
LastModified,
EntryId,
AttrHidden,
}
pub(crate) const EXTENDED_PROPS: [(u16, MapiPropertyTypeName, FolderProp); 8] = [
pub(crate) const EXTENDED_PROPS: [(u16, MapiPropertyTypeName, FolderProp); 10] = [
(
0x3001,
MapiPropertyTypeName::String,
@ -65,13 +67,21 @@ pub(crate) const EXTENDED_PROPS: [(u16, MapiPropertyTypeName, FolderProp); 8] =
MapiPropertyTypeName::SystemTime,
FolderProp::LastModified,
),
(0x0FFF, MapiPropertyTypeName::Binary, FolderProp::EntryId),
(
0x10F4,
MapiPropertyTypeName::Boolean,
FolderProp::AttrHidden,
),
];
impl FilterProp for FolderProp {
fn of_path(path: &Path<'_>) -> Option<Self> {
match path {
Path::Field(field) => Self::of_field(*field),
Path::Extended(uri) => Self::of_extended(uri).map(|(_, prop)| prop),
Path::Extended(uri) => Self::of_extended(uri)
.map(|(_, prop)| prop)
.filter(|prop| *prop != FolderProp::EntryId),
Path::Indexed { .. } => None,
}
}
@ -104,6 +114,10 @@ impl FolderProp {
matches!(self, FolderProp::CommitTimeMax | FolderProp::LastModified)
}
pub const fn is_entry_id(self) -> bool {
matches!(self, FolderProp::EntryId)
}
pub const fn needs_counts(self) -> bool {
matches!(
self,

View file

@ -4,7 +4,9 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
use super::{FolderCounts, FolderFieldSet, FolderRenderer, FolderSelector, resolve_folder};
use super::{
FolderCounts, FolderEntryIds, FolderFieldSet, FolderRenderer, FolderSelector, resolve_folder,
};
use crate::{
ews::{
context::EwsContext,
@ -99,6 +101,7 @@ pub(crate) async fn sync_folder_hierarchy(
}),
)
.await?,
entry_ids: FolderEntryIds::load(server, ctx, fields).await?,
};
let account_id = ctx.account.account_id;
messages.message(&MessageResult {

View file

@ -60,7 +60,9 @@ use exchange_proto::{
ids::{Globcnt, ReplGuid},
mapi::{
ErrorCode,
prop::{NamedPropMap, PropId, PropKeyRef, PropTag, PropType, PropValue, tags},
prop::{
NamedPropMap, OwnedPropValue, PropId, PropKeyRef, PropTag, PropType, PropValue, tags,
},
},
};
use groupware::cache::GroupwareCache;
@ -725,7 +727,7 @@ fn write_message(
.contains(SynchronizationFlags::BEST_BODY)
.then(|| native_body_id(bag))
.flatten();
write_message_props(encoder, bag, filter, native, names)?;
write_message_props(encoder, bag, &content.props, filter, native, names)?;
write_children(encoder, content, filter, names, 0)
}
@ -749,6 +751,7 @@ fn carries_value(bag: &PropBag, tag: PropTag) -> bool {
pub(super) fn write_message_props(
encoder: &mut FxEncoder,
bag: &PropBag,
content: &ContentBag,
filter: Option<&TagFilter>,
native: Option<PropId>,
names: &dyn NamedPropMap,
@ -762,6 +765,12 @@ pub(super) fn write_message_props(
continue;
}
match value {
PropOut::Value(PropValue::Error(ErrorCode::NOT_ENOUGH_MEMORY)) => {
let Some((key, value)) = oversized_value(content, tag, names) else {
continue;
};
encoder.prop_owned(key, value, names)
}
PropOut::Value(value) => encoder.prop(tag, &value, names),
PropOut::Text(text) => encoder.prop_text(tag, text, names),
}
@ -770,6 +779,20 @@ pub(super) fn write_message_props(
Ok(())
}
fn oversized_value<'x>(
content: &'x ContentBag,
tag: PropTag,
names: &'x dyn NamedPropMap,
) -> Option<(PropKeyRef<'x>, &'x OwnedPropValue)> {
let id = tag.id();
let key = if id.is_named() {
names.key(id)?
} else {
PropKeyRef::Tag(id)
};
content.get(key, tag.ptype()).map(|value| (key, value))
}
pub(super) fn write_children(
encoder: &mut FxEncoder,
content: &MessageContent,

View file

@ -274,7 +274,7 @@ impl CopySource {
write_identity(encoder, id, bag, versions, guids, names)?;
}
}
write_message_props(encoder, bag, filter, None, names)?;
write_message_props(encoder, bag, &content.props, filter, None, names)?;
if self.subobjects == Subobjects::Copy {
write_children(encoder, content, filter, names, 0)?;
}

View file

@ -277,8 +277,7 @@ impl ExchangeSubmit for Server {
}
impl SubmitOnce {
pub fn eas(device_slot: u16, client_id: &str) -> Option<Self> {
let bytes = client_id.as_bytes();
pub fn eas(device_slot: u16, bytes: &[u8]) -> Option<Self> {
let len = u8::try_from(bytes.len()).ok().filter(|len| *len > 0)?;
let mut once = SubmitOnce {
device_slot,

View file

@ -1,7 +1,7 @@
[package]
name = "fdb"
description = "Native async FoundationDB client"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
license = "AGPL-3.0-only OR LicenseRef-SEL"
publish = false

View file

@ -1,6 +1,6 @@
[package]
name = "groupware"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]
@ -21,13 +21,14 @@ percent-encoding = "2.3.2"
compact_str = "0.10.0"
ahash = { version = "0.8" }
indexmap = "2.14.2"
jiff = "0.2.38"
jiff = "1.0.3"
icu_locale_core = "2"
icu_provider = { version = "2", features = ["sync"] }
icu_plurals = "2"
serde = { version = "1.0", features = ["derive"]}
serde_json = "1.0"
icu_datetime = { version = "~2.4", features = ["unstable_jiff_0_2"] }
icu_datetime = "~2.4"
icu_calendar = "~2.4"
[features]
enterprise = ["utils/enterprise", "store/enterprise", "common/enterprise", "trc/enterprise", "registry/enterprise"]

View file

@ -116,7 +116,7 @@ pub fn generate_vavailability(
Some(name) => match ICalendar::parse(&ical) {
Ok(mut parsed) => {
let from = reference_date(0)
.and_then(|date| date.to_zoned(CivilTimeZone::UTC).ok())
.and_then(|date| date.to_zoned_datetime(CivilTimeZone::UTC).ok())
.map_or(now, |zoned| zoned.timestamp().as_second());
parsed.add_timezone(name, from, now.saturating_add(TZ_RANGE_SECONDS));
Some(parsed.to_string())
@ -141,7 +141,12 @@ pub fn always_available_vavailability(account_id: u32) -> String {
pub fn parse_vavailability(ical: &ICalendar, now: i64) -> Result<WorkingHours, VAvailabilityError> {
let latest_start = Timestamp::from_second(now)
.ok()
.and_then(|now| now.to_zoned(CivilTimeZone::UTC).date().tomorrow().ok())
.and_then(|now| {
now.to_zoned_datetime(CivilTimeZone::UTC)
.date()
.tomorrow()
.ok()
})
.unwrap_or(Date::MAX);
let mut availability = None;
for component in &ical.components {

View file

@ -11,12 +11,16 @@ use calcard::{
};
use common::i18n::{self, Locale, PluralForms};
use compact_str::ToCompactString;
use icu_datetime::{DateTimeFormatter, fieldsets};
use icu_calendar::{Date as IcuDate, Gregorian};
use icu_datetime::{
DateTimeFormatter, fieldsets,
input::{DateTime as IcuDateTime, Time as IcuTime},
};
use icu_locale_core::{Locale as IcuLocale, locale};
use icu_plurals::{PluralCategory, PluralRuleType, PluralRules, PluralRulesOptions};
use jiff::{
Timestamp,
civil::{Date, ISOWeekDate, Weekday},
civil::{Date, DateTime, ISOWeekDate, Weekday},
};
use std::fmt::Write;
@ -105,7 +109,10 @@ impl TextFormatter {
let local = tz
.from_timestamp(Timestamp::from_second(time.start).unwrap_or_default())
.naive_local();
let local_date = local.date();
let Some(local) = icu_datetime(local) else {
return;
};
let local_date = local.date;
let _ = write!(out, "{}, ", weekday.format(&local_date));
match time.kind {
ItipTimeKind::DateTime => {
@ -334,13 +341,19 @@ impl TextFormatter {
ICalendarWeekday::Sunday => Weekday::Sunday,
};
if let Ok(date) = ISOWeekDate::new(2024, 1, weekday).map(ISOWeekDate::date) {
if let Some(date) = ISOWeekDate::new(2024, 1, weekday)
.ok()
.and_then(|date| icu_date(date.date()))
{
let _ = write!(out, "{}", self.weekday.format(&date));
}
}
fn write_month(&self, out: &mut String, month: u8) {
if let Ok(date) = Date::new(2024, month.clamp(1, 12) as i8, 1) {
if let Some(date) = Date::new(2024, month.clamp(1, 12) as i8, 1)
.ok()
.and_then(icu_date)
{
let _ = write!(out, "{}", self.month.format(&date));
}
}
@ -428,6 +441,23 @@ pub fn hyperlink(value: &str) -> Option<&str> {
.then_some(value)
}
fn icu_date(date: Date) -> Option<IcuDate<Gregorian>> {
IcuDate::try_new_gregorian(i32::from(date.year()), date.month() as u8, date.day() as u8).ok()
}
fn icu_datetime(datetime: DateTime) -> Option<IcuDateTime<Gregorian>> {
Some(IcuDateTime {
date: icu_date(datetime.date())?,
time: IcuTime::try_new(
datetime.hour() as u8,
datetime.minute() as u8,
datetime.second() as u8,
datetime.subsec_nanosecond() as u32,
)
.ok()?,
})
}
#[cfg(all(test, stalwart_tests))]
#[rustfmt::skip]
#[path = "../../../../../stalwart-tests/unit/groupware/src/scheduling/format/tests.rs"]

View file

@ -11,6 +11,7 @@ use crate::scheduling::{
RecurrenceId,
};
use ahash::AHashMap;
use calcard::common::DateTimeResult;
use calcard::icalendar::{
ICalendar, ICalendarDuration, ICalendarParameterName, ICalendarParameterValue,
ICalendarParticipationStatus, ICalendarProperty, ICalendarScheduleAgentValue, ICalendarValue,
@ -322,15 +323,19 @@ pub fn itip_snapshot<'x, 'y>(
ItipEntryValue::Text(v.as_str())
}
ICalendarValue::PartialDateTime(date) => {
let tz = tz_resolver
.get_or_insert_with(|| ical.build_tz_resolver())
.resolve_or_default(tz_id);
let resolved = date.to_date_time();
let tz = match resolved.as_ref().and_then(DateTimeResult::tz) {
Some(tz) => tz,
None => tz_resolver
.get_or_insert_with(|| ical.build_tz_resolver())
.resolve_or_default(tz_id),
};
ItipEntryValue::DateTime(ItipDateTime {
date,
tz_id,
tz_code: tz.as_id(),
timestamp: date
.to_date_time_with_tz(tz)
timestamp: resolved
.and_then(|dt| dt.to_date_time_with_tz(tz))
.map(|dt| dt.timestamp())
.unwrap_or_else(|| {
date.to_timestamp().unwrap_or_default()

View file

@ -1,6 +1,6 @@
[package]
name = "http_proto"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]
@ -9,9 +9,9 @@ trc = { path = "../trc" }
registry = { path = "../registry" }
serde = { version = "1.0", features = ["derive"]}
serde_json = "1.0"
hyper = { version = "1.12.0", features = ["server", "http1", "http2"] }
hyper = { version = "1.13.0", features = ["server", "http1", "http2"] }
http-body-util = "0.1.5"
form_urlencoded = "1.2.2"
form_urlencoded = "1.2.3"
percent-encoding = "2.3.2"
compact_str = "0.10.0"
tokio = { version = "1.54", features = ["time"] }

View file

@ -1,6 +1,6 @@
[package]
name = "http"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]
@ -26,7 +26,7 @@ mail-parser = { version = "1.0", features = ["full_encoding"] }
mail-builder = { version = "2.0" }
mail-auth = { version = "0.16.0", features = ["generate", "arc"] }
tokio = { version = "1.54", features = ["rt", "time"] }
hyper = { version = "1.12.0", features = ["server", "http1", "http2"] }
hyper = { version = "1.13.0", features = ["server", "http1", "http2"] }
hyper-util = { version = "0.1.21", features = ["tokio"] }
http-body-util = "0.1.5"
async-stream = "0.3.6"
@ -36,7 +36,7 @@ encodify = "1.0"
sha2 = "0.11"
rkyv.workspace = true
form-data = { version = "0.6.0", features = ["sync"], default-features = false }
mime = "0.3.17"
mime = "0.3.18"
percent-encoding = "2.3.2"
hashify = { version = "0.3" }
compact_str = "0.10.0"

View file

@ -1,6 +1,6 @@
[package]
name = "imap_proto"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]
@ -9,7 +9,7 @@ utils = { path = "../utils" }
mail-parser = { version = "1.0", features = ["full_encoding"] }
ahash = { version = "0.8" }
encodify = "1.0"
jiff = "0.2.38"
jiff = "1.0.3"
trc = { path = "../trc" }
hashify = { version = "0.3" }
compact_str = "0.10.0"

View file

@ -205,8 +205,7 @@ const fn byte_class_table(needles: &[u8]) -> [bool; 256] {
table
}
static NEEDS_ESCAPE: [bool; 256] = byte_class_table(b"\\\"\0");
static NEEDS_LITERAL: [bool; 256] = byte_class_table(b"\\\"\r\n\0");
static NEEDS_ESCAPE: [bool; 256] = byte_class_table(b"\\\"\r\n\0");
#[inline(always)]
fn find_escape(text: &[u8]) -> Option<usize> {
@ -220,15 +219,24 @@ fn without_nul(text: &str) -> String {
}
pub fn quoted_string(buf: &mut Vec<u8>, text: &str) {
let start = buf.len();
let mut rest = text.as_bytes();
buf.push(b'"');
while let Some(pos) = find_escape(rest) {
let (head, tail) = rest.split_at(pos);
buf.extend_from_slice(head);
let mut tail = tail.iter();
if let Some(&ch) = tail.next().filter(|&&ch| ch != 0) {
buf.push(b'\\');
buf.push(ch);
match tail.next() {
Some(b'\r' | b'\n') => {
buf.truncate(start);
quoted_or_literal_string(buf, text);
return;
}
Some(&ch) if ch != 0 => {
buf.push(b'\\');
buf.push(ch);
}
_ => {}
}
rest = tail.as_slice();
}
@ -250,7 +258,7 @@ pub(crate) fn quoted_mailbox_name(buf: &mut Vec<u8>, name: &str, is_utf8: bool)
pub fn quoted_or_literal_string(buf: &mut Vec<u8>, text: &str) {
let bytes = text.as_bytes();
if !bytes.iter().any(|&ch| NEEDS_LITERAL[ch as usize]) {
if find_escape(bytes).is_none() {
buf.push(b'"');
buf.extend_from_slice(bytes);
buf.push(b'"');

View file

@ -1,6 +1,6 @@
[package]
name = "imap"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]
@ -20,7 +20,7 @@ tokio = { version = "1.54", features = ["full"] }
tokio-rustls = { version = "0.26", default-features = false, features = ["aws_lc_rs", "tls12"] }
parking_lot = "0.13"
ahash = { version = "0.8" }
rand = "0.10.3"
rand = "0.10.4"
compact_str = "0.10.0"
[features]

View file

@ -709,8 +709,7 @@ impl MailboxView {
uid,
id: document_id,
});
}
if let Some(changed) = changed.as_deref_mut() {
} else if let Some(changed) = changed.as_deref_mut() {
changed.push(uid);
}
}

View file

@ -1,6 +1,6 @@
[package]
name = "jmap_proto"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]
@ -12,10 +12,10 @@ jmap-tools = { path = "../jmap-tools" }
calcard = { path = "../calcard" }
mail-parser = { version = "1.0", features = ["full_encoding"] }
serde = { version = "1.0", features = ["derive"]}
ahash = { version = "0.8.12", features = ["serde"] }
ahash = { version = "0.8.14", features = ["serde"] }
serde_json = { version = "1.0", features = ["raw_value"] }
simdutf8 = "0.1.5"
sonic-rs = "0.5.10"
sonic-rs = "0.5.12"
hashify = "0.3"
rkyv.workspace = true
compact_str = { version = "0.10.0", features = ["rkyv", "serde"] }

View file

@ -106,8 +106,8 @@ pub enum SetErrorType {
CannotUnsend,
#[serde(rename = "alreadyExists")]
AlreadyExists,
#[serde(rename = "invalidScript")]
InvalidScript,
#[serde(rename = "invalidSieve")]
InvalidSieve,
#[serde(rename = "sieveIsActive")]
SieveIsActive,
#[serde(rename = "addressBookHasContents")]
@ -157,7 +157,7 @@ impl SetErrorType {
SetErrorType::ForbiddenToSend => "forbiddenToSend",
SetErrorType::CannotUnsend => "cannotUnsend",
SetErrorType::AlreadyExists => "alreadyExists",
SetErrorType::InvalidScript => "invalidScript",
SetErrorType::InvalidSieve => "invalidSieve",
SetErrorType::SieveIsActive => "sieveIsActive",
SetErrorType::AddressBookHasContents => "addressBookHasContents",
SetErrorType::NodeHasChildren => "nodeHasChildren",

View file

@ -13,8 +13,10 @@ use crate::{
},
types::state::State,
};
use ahash::AHashSet;
use jmap_tools::Value;
use serde::{Deserialize, Deserializer};
use std::hash::Hash;
use types::id::Id;
const LINEAR_DEDUP_LIMIT: usize = 16;
@ -148,17 +150,33 @@ impl<T: JmapObject> GetRequest<T> {
pub fn unwrap_ids(
&mut self,
max_objects_in_get: usize,
) -> trc::Result<(Option<Vec<T::Id>>, Vec<MaybeInvalid<T::Id>>)> {
) -> trc::Result<(Option<Vec<T::Id>>, Vec<MaybeInvalid<T::Id>>)>
where
T::Id: Clone + Eq + Hash,
{
if let Some(ids) = self.ids.take() {
let ids = ids.unwrap();
if ids.len() <= max_objects_in_get {
let mut valid = Vec::with_capacity(ids.len());
let mut invalid = Vec::new();
let mut seen =
(ids.len() > LINEAR_DEDUP_LIMIT).then(|| AHashSet::with_capacity(ids.len()));
for id in ids {
match id {
MaybeIdReference::Id(id) => valid.push(id),
MaybeIdReference::Id(id) => {
let is_new = match &mut seen {
Some(seen) => seen.insert(id.clone()),
None => !valid.contains(&id),
};
if is_new {
valid.push(id);
}
}
MaybeIdReference::Invalid(s) | MaybeIdReference::Reference(s) => {
invalid.push(MaybeInvalid::Invalid(s))
let id = MaybeInvalid::Invalid(s);
if !invalid.contains(&id) {
invalid.push(id);
}
}
}
}

View file

@ -1,7 +1,7 @@
[package]
name = "jmap-tools"
description = "JMAP object parser with JSON Pointer querying and patching support"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
license = "AGPL-3.0-only OR LicenseRef-SEL"
publish = false

View file

@ -1,6 +1,6 @@
[package]
name = "jmap"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]
@ -30,7 +30,7 @@ sieve-rs = { path = "../sieve" }
jmap-tools = { path = "../jmap-tools", features = ["rkyv"] }
serde = { version = "1.0", features = ["derive"]}
serde_json = "1.0"
hyper = { version = "1.12.0", features = ["server", "http1", "http2"] }
hyper = { version = "1.13.0", features = ["server", "http1", "http2"] }
hyper-util = { version = "0.1.21", features = ["tokio"] }
http-body-util = "0.1.5"
tokio = { version = "1.54", features = ["rt"] }
@ -44,8 +44,8 @@ sha2 = "0.11"
reqwest = { version = "0.13", default-features = false, features = ["rustls", "http2"]}
tokio-tungstenite = "0.30"
tungstenite = "0.30"
jiff = "0.2.38"
rand = "0.10.3"
jiff = "1.0.3"
rand = "0.10.4"
rkyv.workspace = true
hashify = "0.3"
compact_str = "0.10.0"

View file

@ -10,7 +10,9 @@ use crate::{
NewMetadata, ObjectMetadata,
},
changes::state::JmapCacheState,
email::{PatchResult, handle_email_patch, ingested_into_object, parse_keywords},
email::{
PatchResult, handle_email_patch, ingested_into_object, invalid_pointer, parse_keywords,
},
};
use common::{
MAX_RECEIVED_AT, Server, auth::AccessToken, ipc::PushNotification, sharing::EffectiveAcl,
@ -210,8 +212,11 @@ impl JmapEmailCopy for Server {
PatchResult::RemoveMailbox(id) => {
mailboxes.retain(|mid| mid != &id);
}
PatchResult::Invalid(set_error) => {
response.not_created.append(id.clone(), set_error);
PatchResult::Invalid | PatchResult::InvalidValue => {
response.not_created.append(
id.clone(),
invalid_pointer(SetError::invalid_properties(), pointer),
);
continue 'create;
}
}

View file

@ -16,6 +16,10 @@ use types::{id::Id, keyword::Keyword};
#[rustfmt::skip]
#[path = "../../../../../stalwart-tests/unit/jmap/src/email/contention.rs"]
mod contention;
#[cfg(all(test, stalwart_tests))]
#[rustfmt::skip]
#[path = "../../../../../stalwart-tests/unit/jmap/src/email/patch.rs"]
mod patch;
pub mod copy;
pub mod get;
mod grouped;
@ -41,7 +45,8 @@ pub(crate) enum PatchResult<'x> {
RemoveKeyword(&'x Keyword),
AddMailbox(u32),
RemoveMailbox(u32),
Invalid(SetError<EmailProperty>),
Invalid,
InvalidValue,
}
pub(crate) fn parse_keywords<'x>(
@ -66,31 +71,58 @@ pub(crate) fn handle_email_patch<'x>(
) -> PatchResult<'x> {
let mut pointer_iter = pointer.iter();
match (pointer_iter.next(), pointer_iter.next()) {
(
Some(JsonPointerItem::Key(Key::Property(EmailProperty::Keywords))),
Some(JsonPointerItem::Key(Key::Property(EmailProperty::Keyword(keyword)))),
) => match value {
Value::Bool(true) => return PatchResult::SetKeyword(keyword),
Value::Bool(false) | Value::Null => return PatchResult::RemoveKeyword(keyword),
_ => (),
},
match (
pointer_iter.next(),
pointer_iter.next(),
pointer_iter.next(),
) {
(Some(JsonPointerItem::Key(Key::Property(EmailProperty::Keywords))), Some(item), None) => {
match (item, value) {
(JsonPointerItem::Invalid(_), _) => PatchResult::Invalid,
(
JsonPointerItem::Key(Key::Property(EmailProperty::Keyword(keyword))),
Value::Bool(true),
) => PatchResult::SetKeyword(keyword),
(
JsonPointerItem::Key(Key::Property(EmailProperty::Keyword(keyword))),
Value::Bool(false) | Value::Null,
) => PatchResult::RemoveKeyword(keyword),
_ => PatchResult::InvalidValue,
}
}
(
Some(JsonPointerItem::Key(Key::Property(EmailProperty::MailboxIds))),
Some(JsonPointerItem::Key(Key::Property(EmailProperty::IdValue(id)))),
) => match value {
Value::Bool(true) => return PatchResult::AddMailbox(id.document_id()),
Value::Bool(false) | Value::Null => {
return PatchResult::RemoveMailbox(id.document_id());
}
_ => (),
Some(item),
None,
) => match (item, value) {
(JsonPointerItem::Invalid(_), _) => PatchResult::Invalid,
(
JsonPointerItem::Key(Key::Property(EmailProperty::IdValue(id))),
Value::Bool(true),
) => PatchResult::AddMailbox(id.document_id()),
(
JsonPointerItem::Key(Key::Property(EmailProperty::IdValue(id))),
Value::Bool(false) | Value::Null,
) => PatchResult::RemoveMailbox(id.document_id()),
_ => PatchResult::InvalidValue,
},
_ => (),
_ => PatchResult::Invalid,
}
PatchResult::Invalid(
SetError::invalid_properties()
.with_property(EmailProperty::Pointer(pointer.clone()))
.with_description("Invalid patch value".to_string()),
)
}
#[cold]
pub(crate) fn invalid_pointer(
error: SetError<EmailProperty>,
pointer: JsonPointer<EmailProperty>,
) -> SetError<EmailProperty> {
error
.with_property(EmailProperty::Pointer(pointer))
.with_description("Invalid patch value")
}
#[cold]
pub(crate) fn conflicting_patch(property: EmailProperty) -> SetError<EmailProperty> {
SetError::invalid_patch()
.with_property(property)
.with_description("A property cannot be replaced and patched in the same update.")
}

View file

@ -12,9 +12,9 @@ use crate::{
blob::download::{BlobAccess, BlobDownload},
changes::state::JmapCacheState,
email::{
PatchResult,
PatchResult, conflicting_patch,
grouped::{GroupedIngest, QueuedEmail},
handle_email_patch, ingested_into_object, parse_keywords,
handle_email_patch, ingested_into_object, invalid_pointer, parse_keywords,
},
};
use common::{
@ -299,8 +299,11 @@ impl EmailSet for Server {
PatchResult::RemoveMailbox(id) => {
mailboxes.retain(|mid| mid != &id);
}
PatchResult::Invalid(set_error) => {
response.not_created.append(id, set_error);
PatchResult::Invalid | PatchResult::InvalidValue => {
response.not_created.append(
id,
invalid_pointer(SetError::invalid_properties(), pointer),
);
continue 'create;
}
}
@ -1219,6 +1222,9 @@ impl EmailSet for Server {
};
let mut new_data = data.clone();
let mut has_keyword_replace = false;
let mut has_keyword_patch = false;
let mut has_mailbox_replace = false;
let mut has_mailbox_patch = false;
for (property, mut value) in object.into_expanded_object() {
if let Err(err) = response.resolve_self_references(&mut value, 0, false) {
@ -1228,6 +1234,13 @@ impl EmailSet for Server {
match (property, value) {
(Key::Property(EmailProperty::MailboxIds), Value::Object(ids)) => {
if has_mailbox_patch {
response
.not_updated
.append(id, conflicting_patch(EmailProperty::MailboxIds));
continue 'update;
}
has_mailbox_replace = true;
new_data.set_mailboxes(
ids.into_expanded_boolean_set()
.filter_map(|id| {
@ -1243,6 +1256,12 @@ impl EmailSet for Server {
);
}
(Key::Property(EmailProperty::Keywords), keywords @ Value::Object(_)) => {
if has_keyword_patch {
response
.not_updated
.append(id, conflicting_patch(EmailProperty::Keywords));
continue 'update;
}
has_keyword_replace = true;
match parse_keywords(keywords) {
Ok(keywords) => new_data.set_keywords(keywords),
@ -1254,20 +1273,50 @@ impl EmailSet for Server {
}
(Key::Property(EmailProperty::Pointer(pointer)), value) => {
match handle_email_patch(&pointer, value) {
PatchResult::SetKeyword(_) | PatchResult::RemoveKeyword(_)
if has_keyword_replace =>
{
response
.not_updated
.append(id, conflicting_patch(EmailProperty::Keywords));
continue 'update;
}
PatchResult::AddMailbox(_) | PatchResult::RemoveMailbox(_)
if has_mailbox_replace =>
{
response
.not_updated
.append(id, conflicting_patch(EmailProperty::MailboxIds));
continue 'update;
}
PatchResult::SetKeyword(keyword) => {
has_keyword_patch = true;
new_data.add_keyword(keyword.clone());
}
PatchResult::RemoveKeyword(keyword) => {
has_keyword_patch = true;
new_data.remove_keyword(keyword);
}
PatchResult::AddMailbox(id) => {
has_mailbox_patch = true;
new_data.add_mailbox(MessageUid::new_unassigned(id));
}
PatchResult::RemoveMailbox(id) => {
has_mailbox_patch = true;
new_data.remove_mailbox(id);
}
PatchResult::Invalid(set_error) => {
response.not_updated.append(id, set_error);
PatchResult::Invalid => {
response.not_updated.append(
id,
invalid_pointer(SetError::invalid_patch(), pointer),
);
continue 'update;
}
PatchResult::InvalidValue => {
response.not_updated.append(
id,
invalid_pointer(SetError::invalid_properties(), pointer),
);
continue 'update;
}
}

View file

@ -77,6 +77,15 @@ pub struct SetContext<'x> {
mailbox_ids: RoaringBitmap,
will_destroy: Vec<Id>,
counters: AHashMap<u32, MailboxCounters>,
claimed_names: AHashMap<NameClaim, Option<u32>>,
}
type NameClaim = (ParentRef, String);
pub struct PreparedMailbox {
builder: ObjectIndexBuilder<Archive<Mailbox>, Mailbox>,
parent: ParentRef,
name_claim: Option<NameClaim>,
}
#[derive(Clone, Copy)]
@ -158,21 +167,13 @@ pub trait MailboxSet: Sync + Send {
lock: Option<&CreateLock>,
) -> impl Future<Output = trc::Result<SetResponse<mailbox::Mailbox>>> + Send;
#[allow(clippy::type_complexity)]
fn mailbox_set_item(
&self,
changes_: Map<'_, MailboxProperty, MailboxValue>,
update: Option<(u32, Archive<Mailbox>)>,
ctx: &SetContext,
resolver: Option<&CreateResolver<'_>>,
) -> impl Future<
Output = trc::Result<
Result<
(ObjectIndexBuilder<Archive<Mailbox>, Mailbox>, ParentRef),
SetError<MailboxProperty>,
>,
>,
> + Send;
) -> impl Future<Output = trc::Result<Result<PreparedMailbox, SetError<MailboxProperty>>>> + Send;
}
impl ResolveCreatedReference<MailboxProperty, MailboxValue> for CreateResolver<'_> {
@ -289,6 +290,7 @@ impl MailboxSet for Server {
mailbox_ids: RoaringBitmap::from_iter(cache.mailboxes.index.keys()),
will_destroy,
counters,
claimed_names: AHashMap::new(),
};
let mut change_id = None;
@ -334,7 +336,11 @@ impl MailboxSet for Server {
)
.await?
{
Ok((mut builder, parent)) => {
Ok(PreparedMailbox {
mut builder,
parent,
name_claim,
}) => {
let my_rights = if ctx.is_shared {
JmapRights::rights::<mailbox::Mailbox>(
builder
@ -400,6 +406,9 @@ impl MailboxSet for Server {
batch.commit_point();
pending_creates.insert(id.clone(), slot);
if let Some(name_claim) = name_claim {
ctx.claimed_names.insert(name_claim, None);
}
created.push((id, slot, omitted, my_rights));
}
Err(err) => {
@ -429,6 +438,8 @@ impl MailboxSet for Server {
}
}
ctx.claimed_names.clear();
// Process updates
let mut will_update = Vec::with_capacity(request.update.as_ref().map_or(0, |u| u.len()));
let mut batch = BatchBuilder::new();
@ -514,8 +525,17 @@ impl MailboxSet for Server {
.with_description("You are not allowed to modify this mailbox."),
);
continue 'update;
} else if object.contains_key(&Key::Property(MailboxProperty::ShareWith))
&& !acl.contains(Acl::Share)
} else if !acl.contains(Acl::Share)
&& object.keys().any(|key| match key {
Key::Property(MailboxProperty::ShareWith) => true,
Key::Property(MailboxProperty::Pointer(pointer)) => matches!(
pointer.first(),
Some(JsonPointerItem::Key(Key::Property(
MailboxProperty::ShareWith
)))
),
_ => false,
})
{
ctx.response.not_updated.append(
id,
@ -583,7 +603,11 @@ impl MailboxSet for Server {
.mailbox_set_item(object, (document_id, mailbox).into(), &ctx, None)
.await?
{
Ok((mut builder, parent)) => {
Ok(PreparedMailbox {
mut builder,
parent,
name_claim,
}) => {
batch
.with_account_id(account_id)
.with_collection(Collection::Mailbox);
@ -649,6 +673,9 @@ impl MailboxSet for Server {
}
batch.commit_point();
}
if let Some(name_claim) = name_claim {
ctx.claimed_names.insert(name_claim, Some(document_id));
}
will_update.push(id);
}
Err(err) => {
@ -770,12 +797,7 @@ impl MailboxSet for Server {
update: Option<(u32, Archive<Mailbox>)>,
ctx: &SetContext<'_>,
resolver: Option<&CreateResolver<'_>>,
) -> trc::Result<
Result<
(ObjectIndexBuilder<Archive<Mailbox>, Mailbox>, ParentRef),
SetError<MailboxProperty>,
>,
> {
) -> trc::Result<Result<PreparedMailbox, SetError<MailboxProperty>>> {
// Parse properties
let mut changes = update
.as_ref()
@ -1042,25 +1064,48 @@ impl MailboxSet for Server {
}
// Verify that the mailbox name is unique.
let mut name_claim = None;
if !changes.name.is_empty() {
// Obtain parent mailbox id
let lower_name = changes.name.to_lowercase();
let current_id = update.as_ref().map(|(document_id, _)| *document_id);
if update.as_ref().is_none_or(|(_, m)| {
m.inner.name != changes.name || m.inner.parent_id != changes.parent_id
}) && let Some(parent_cache_id) = parent.cache_id()
&& let Some(existing) = cached_mailboxes.mailboxes.items.iter().find(|m| {
Some(m.document_id) != current_id
&& m.parent_id() == parent_cache_id
&& m.name.to_lowercase() == lower_name
})
{
return Ok(Err(SetError::already_exists()
.with_existing_id(Id::from(existing.document_id))
.with_description(format!(
}) {
let lower_name = changes
.name
.chars()
.flat_map(char::to_lowercase)
.collect::<String>();
let current_id = update.as_ref().map(|(document_id, _)| *document_id);
if let Some(parent_cache_id) = parent.cache_id()
&& let Some(existing) = cached_mailboxes.mailboxes.items.iter().find(|m| {
Some(m.document_id) != current_id
&& m.parent_id() == parent_cache_id
&& m.name
.chars()
.flat_map(char::to_lowercase)
.eq(lower_name.chars())
})
{
return Ok(Err(SetError::already_exists()
.with_existing_id(Id::from(existing.document_id))
.with_description(format!(
"A mailbox with name '{}' already exists.",
changes.name
))));
}
let claim = (parent, lower_name);
if let Some(holder) = ctx.claimed_names.get(&claim) {
let err = match holder {
Some(document_id) => {
SetError::already_exists().with_existing_id(Id::from(*document_id))
}
None => SetError::invalid_properties().with_property(MailboxProperty::Name),
};
return Ok(Err(err.with_description(format!(
"A mailbox with name '{}' already exists.",
changes.name
))));
}
name_claim = Some(claim);
}
} else {
return Ok(Err(SetError::invalid_properties()
@ -1087,11 +1132,12 @@ impl MailboxSet for Server {
}
// Validate
Ok(Ok((
ObjectIndexBuilder::new()
Ok(Ok(PreparedMailbox {
builder: ObjectIndexBuilder::new()
.with_changes(changes)
.with_current_opt(current),
parent,
)))
name_claim,
}))
}
}

View file

@ -530,11 +530,10 @@ pub(crate) async fn account_set(
// Process updates
'outer: for (id, value) in set.update.drain(..) {
if let Some(mut old_credential) =
account.credentials.values_mut().find(|credential| {
credential.credential_id() == id
&& !matches!(credential, Credential::Passkey(_))
})
if let Some(mut old_credential) = account
.credentials
.values_mut()
.find(|credential| is_secondary_credential(credential, set.object_type, id))
{
let mut credential = old_credential.clone();
let mut unpatched_properties = VecMap::new();
@ -619,24 +618,11 @@ pub(crate) async fn account_set(
.credentials
.0
.inner
.iter_mut()
.position(|c| c.value.credential_id() == id)
.iter()
.position(|c| is_secondary_credential(&c.value, set.object_type, id))
{
let credentials = &mut account.credentials.inner_mut().inner;
if !matches!(
credentials[idx].value,
Credential::Password(_) | Credential::Passkey(_)
) {
credentials.remove(idx);
set.response.destroyed.push(id);
} else {
set.response.not_destroyed.append(
id,
SetError::forbidden().with_description(
"Users are not allowed to destroy their own credentials.",
),
);
}
account.credentials.inner_mut().inner.remove(idx);
set.response.destroyed.push(id);
} else {
set.response.not_destroyed.append(id, SetError::not_found());
}
@ -945,6 +931,14 @@ pub(crate) async fn credential_query(
Ok(response)
}
fn is_secondary_credential(credential: &Credential, object_type: ObjectType, id: Id) -> bool {
match (credential, object_type) {
(Credential::AppPassword(credential), ObjectType::AppPassword)
| (Credential::ApiKey(credential), ObjectType::ApiKey) => credential.credential_id == id,
_ => false,
}
}
pub(crate) fn validate_credential_permissions(
access_token: &AccessToken,
credential: &SecondaryCredential,

View file

@ -753,7 +753,7 @@ impl SieveScriptSet for Server {
if let ErrorType::ScriptTooLong = &err.error_type() {
SetErrorType::TooLarge
} else {
SetErrorType::InvalidScript
SetErrorType::InvalidSieve
},
)
.with_description(err.to_string())));

View file

@ -37,7 +37,7 @@ impl SieveScriptValidate for Server {
.map(|bytes| self.core.sieve.untrusted_compiler.compile(&bytes))
{
Some(Ok(_)) => None,
Some(Err(err)) => SetError::new(SetErrorType::InvalidScript)
Some(Err(err)) => SetError::new(SetErrorType::InvalidSieve)
.with_description(err.to_string())
.into(),
None => SetError::new(SetErrorType::BlobNotFound).into(),

View file

@ -7,7 +7,7 @@ homepage = "https://stalw.art"
keywords = ["imap", "jmap", "smtp", "email", "mail", "webdav", "server"]
categories = ["email"]
license = "AGPL-3.0-only OR LicenseRef-SEL"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[[bin]]

View file

@ -1,6 +1,6 @@
[package]
name = "managesieve"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]

View file

@ -1,19 +1,19 @@
[package]
name = "nlp"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]
xxhash-rust = { version = "0.8.19", features = ["xxh3"] }
xxhash-rust = { version = "0.8.21", features = ["xxh3"] }
serde = { version = "1.0", features = ["derive"]}
ahash = { version = "0.8.12", features = ["serde"] }
ahash = { version = "0.8.14", features = ["serde"] }
whatlang = "0.18" # Language detection
rust-stemmers = "1.2" # Stemmers
jieba-rs = "0.11" # Chinese stemmer
psl = "2"
memchr = "2.8"
hashify = "0.3"
rand = "0.10.3"
rand = "0.10.4"
rkyv.workspace = true
[features]

View file

@ -1,6 +1,6 @@
[package]
name = "pop3"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]

View file

@ -1,6 +1,6 @@
[package]
name = "registry"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]

View file

@ -1,6 +1,6 @@
[package]
name = "s3"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
license = "AGPL-3.0-only OR LicenseRef-SEL"
publish = false
@ -14,7 +14,7 @@ md5 = "0.8"
quick-xml = "0.42"
crc-fast = { version = "1.10", default-features = false, features = ["std"] }
tokio = { version = "1.54", features = ["time"] }
rand = "0.10.3"
rand = "0.10.4"
hashify = "0.3"
memchr = "2.8"
@ -22,5 +22,5 @@ memchr = "2.8"
workspace = true
[dev-dependencies]
jiff = "0.2.38"
jiff = "1.0.3"
tokio = { version = "1.54", features = ["macros", "rt", "net", "io-util", "time"] }

View file

@ -1,6 +1,6 @@
[package]
name = "scim-proto"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]

View file

@ -1,6 +1,6 @@
[package]
name = "scim"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]
@ -17,10 +17,10 @@ types = { path = "../types" }
utils = { path = "../utils" }
trc = { path = "../trc" }
compact_str = "0.10.0"
hyper = { version = "1.12.0", features = ["server", "http1", "http2"] }
hyper = { version = "1.13.0", features = ["server", "http1", "http2"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
xxhash-rust = { version = "0.8.19", features = ["xxh3"] }
xxhash-rust = { version = "0.8.21", features = ["xxh3"] }
icu_locale = "2.4.0"
[dev-dependencies]

View file

@ -1,6 +1,6 @@
[package]
name = "services"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
[dependencies]

View file

@ -1,7 +1,7 @@
[package]
name = "sieve-rs"
description = "Sieve filter interpreter"
version = "1.2.0"
version = "1.2.1"
edition = "2024"
license = "AGPL-3.0-only OR LicenseRef-SEL"
publish = false
@ -12,23 +12,23 @@ doctest = false
[dependencies]
mail-parser = { version = "1.0", features = ["full_encoding"] }
fancy-regex = "0.20.0"
fancy-regex = "0.20.2"
bumpalo = { version = "3.20", features = ["collections"] }
memchr = "2.8"
encodify = "1.0"
smallvec = "1.16"
hashbrown = "0.17.1"
hashbrown = "0.17.2"
hashify = "0.3"
serde = { version = "1.0", features = ["derive", "rc"], optional = true }
mail-builder = { version = "2.0" }
ahash = { version = "0.8.12" }
ahash = { version = "0.8.14" }
calcard = { path = "../calcard", default-features = false, features = ["tzdb-bundle"] }
[dev-dependencies]
mail-parser = { version = "1.0", features = ["full_encoding", "serde"] }
serde = { version = "1.0", features = ["derive", "rc"] }
serde_json = "1.0"
evalexpr = "13.1.0"
evalexpr = "14.0.0"
[features]
default = []

View file

@ -53,11 +53,14 @@ impl CompilerState<'_> {
Some(Ok(
Token::StringConstant(_) | Token::StringVariable(_) | Token::BracketOpen,
)),
) => EditFlags {
name: self.parse_variable_name(token_info, false)?.into(),
flags: self.parse_strings(false)?.into(),
action,
},
) => {
self.validate_flag_variable_name(token_info.line_num, token_info.line_pos)?;
EditFlags {
name: self.parse_variable_name(token_info, false)?.into(),
flags: self.parse_strings(false)?.into(),
action,
}
}
(Token::BracketOpen, _)
| (
Token::StringConstant(_) | Token::StringVariable(_),

View file

@ -20,7 +20,9 @@ impl CompilerState<'_> {
capability: Capability,
token_info: &TokenInfo,
) -> Result<(), CompileError> {
if self.compiler.disabled_capabilities.contains(&capability) {
if self.compiler.disabled_capabilities.contains(&capability)
|| (self.compiler.unknown_capabilities_disabled && capability.is_unknown())
{
return Err(CompileError {
line_num: token_info.line_num,
line_pos: token_info.line_pos,

View file

@ -436,6 +436,14 @@ impl CompilerState<'_> {
|| (capability != &Capability::Ihave && self.compiler.no_capability_check)
}
pub(crate) fn validate_flag_variable_name(
&mut self,
line_num: usize,
line_pos: usize,
) -> Result<(), CompileError> {
self.validate_argument(0, Capability::Variables.into(), line_num, line_pos)
}
#[inline(always)]
pub(crate) fn reset_param_check(&mut self) {
self.param_check.fill(false);
@ -500,21 +508,17 @@ impl CompilerState<'_> {
self.header_name(header).ok()
}
pub(crate) fn resolve_header_names(&mut self, headers: Vec<RawValue>) -> (Vec<Value>, bool) {
let mut all_valid = true;
let mut values = Vec::with_capacity(headers.len());
for header in headers {
match self.header_name(header) {
Ok(value) => values.push(value),
Err(value) => {
all_valid = false;
values.push(value);
}
}
pub(crate) fn resolve_test_header_name(&mut self, header: RawValue) -> Value {
match self.header_name(header) {
Ok(value) | Err(value) => value,
}
}
(values, all_valid)
pub(crate) fn resolve_header_names(&mut self, headers: Vec<RawValue>) -> Vec<Value> {
headers
.into_iter()
.map(|header| self.resolve_test_header_name(header))
.collect()
}
pub(crate) fn validate_match(
@ -585,6 +589,13 @@ impl AddressPart {
}
impl Capability {
pub(crate) fn is_unknown(&self) -> bool {
matches!(
self,
Capability::Other(_) | Capability::Comparator(Comparator::Other(_))
)
}
pub(crate) fn id(&self) -> u8 {
match self {
Capability::Envelope => 0,

View file

@ -130,7 +130,7 @@ impl CompilerState<'_> {
_ => {
if header_list.is_none() {
let headers = self.parse_raw_strings_token(token_info)?;
header_list = self.resolve_header_names(headers).0.into();
header_list = self.resolve_header_names(headers).into();
} else {
key_list = self.parse_raw_strings_token(token_info)?;
break;

View file

@ -5,7 +5,7 @@
*/
use crate::compiler::{
CompileError, ErrorType, Number, Value,
CompileError, Number, Value,
grammar::{Capability, Comparator, instruction::CompilerState},
lexer::{StringConstant, Token, tokenizer::TokenInfo, word::Word},
};
@ -170,15 +170,7 @@ impl CompilerState<'_> {
_ => {
if header_name.is_none() {
let header = self.parse_raw_string_token(token_info)?;
header_name = match self.resolve_header_name(header) {
Some(header) => header.into(),
None => {
return Err(self
.tokens
.unwrap_next()?
.custom(ErrorType::InvalidHeaderName));
}
};
header_name = self.resolve_test_header_name(header).into();
} else if date_part.is_none() {
if let Token::StringConstant(string) = &token_info.token
&& let Some(date_part_) =

View file

@ -5,7 +5,7 @@
*/
use crate::compiler::{
CompileError, ErrorType, Value,
CompileError, Value,
grammar::instruction::{CompilerState, MapLocalVars},
lexer::{Token, word::Word},
};
@ -59,15 +59,7 @@ impl CompilerState<'_> {
self.validate_argument(2, None, line_num, line_pos)?;
self.tokens.next();
let header = self.parse_raw_string()?;
dup_match = match self.resolve_header_name(header) {
Some(header) => DupMatch::Header(header),
None => {
return Err(self
.tokens
.unwrap_next()?
.custom(ErrorType::InvalidHeaderName));
}
};
dup_match = DupMatch::Header(self.resolve_test_header_name(header));
}
Token::Tag(Word::UniqueId) => {
self.validate_argument(2, None, line_num, line_pos)?;

View file

@ -5,7 +5,7 @@
*/
use crate::compiler::{
CompileError, ErrorType, Value,
CompileError, Value,
grammar::{Capability, instruction::CompilerState},
lexer::{Token, word::Word},
};
@ -53,14 +53,7 @@ impl CompilerState<'_> {
}
_ => {
let headers = self.parse_raw_strings_token(token_info)?;
let (headers, all_valid) = self.resolve_header_names(headers);
if !all_valid {
return Err(self
.tokens
.unwrap_next()?
.custom(ErrorType::InvalidHeaderName));
}
header_names = headers.into();
header_names = self.resolve_header_names(headers).into();
}
}
}

View file

@ -38,6 +38,8 @@ impl CompilerState<'_> {
let mut is_local = false;
let maybe_variables;
let variables_line_num;
let variables_line_pos;
loop {
let token_info = self.tokens.unwrap_next()?;
@ -72,6 +74,8 @@ impl CompilerState<'_> {
is_local = true;
}
_ => {
variables_line_num = token_info.line_num;
variables_line_pos = token_info.line_pos;
maybe_variables = self.parse_raw_strings_token(token_info)?;
break;
}
@ -87,6 +91,7 @@ impl CompilerState<'_> {
if !maybe_variables.is_empty() {
let line_num = *line_num;
let line_pos = *line_pos;
self.validate_flag_variable_name(variables_line_num, variables_line_pos)?;
let mut variable_list = Vec::with_capacity(maybe_variables.len());
for variable in maybe_variables {

View file

@ -5,7 +5,7 @@
*/
use crate::compiler::{
CompileError, ErrorType, Value,
CompileError, Value,
grammar::{
Capability, Comparator,
actions::action_mime::MimeOpts,
@ -129,14 +129,7 @@ impl CompilerState<'_> {
_ => {
if header_list.is_none() {
let headers = self.parse_raw_strings_token(token_info)?;
let (headers, all_valid) = self.resolve_header_names(headers);
if !all_valid {
return Err(self
.tokens
.unwrap_next()?
.custom(ErrorType::InvalidHeaderName));
}
header_list = headers.into();
header_list = self.resolve_header_names(headers).into();
} else {
key_list = self.parse_raw_strings_token(token_info)?;
break;

View file

@ -383,6 +383,7 @@ impl Compiler {
functions: AHashMap::new(),
no_capability_check: false,
disabled_capabilities: AHashSet::new(),
unknown_capabilities_disabled: false,
}
}
@ -508,6 +509,11 @@ impl Compiler {
}
self
}
pub fn without_unknown_capabilities(mut self) -> Self {
self.unknown_capabilities_disabled = true;
self
}
}
impl CompileError {

View file

@ -46,6 +46,7 @@ pub struct Compiler {
pub(crate) max_includes: usize,
pub(crate) no_capability_check: bool,
pub(crate) disabled_capabilities: AHashSet<Capability>,
pub(crate) unknown_capabilities_disabled: bool,
pub(crate) functions: AHashMap<String, (u32, u32)>,
}

View file

@ -13,7 +13,7 @@ use crate::{
Number,
grammar::{AddressPart, Comparator, MatchType},
},
runtime::{RuntimeError, handler::Handler},
runtime::{RuntimeError, handler::Handler, tests::test_header::InvalidHeaderNames},
};
use ahash::AHashSet;
use mail_parser::{
@ -30,7 +30,9 @@ impl<'x> Context<'x> {
handler: &mut H,
) -> Result<TestResult, RuntimeError> {
let key_list = self.eval_keys(script, test.key_list)?;
let header_list = self.parse_header_names(script, test.header_list)?;
let header_list = self
.parse_header_names(script, test.header_list, InvalidHeaderNames::Skip)?
.unwrap_or_default();
let address_part = AddressPart::from_code(test.address_part);
let comparator = Comparator::from_code(test.comparator);
let match_type = test.match_type.match_type();

View file

@ -11,7 +11,7 @@ use crate::{
runtime::{
RuntimeError,
message::parts::{PartCursor, Scope},
tests::test_header::HeaderKeys,
tests::test_header::{HeaderKeys, InvalidHeaderNames},
},
};
use mail_parser::HeaderName;
@ -23,7 +23,11 @@ impl<'x> Context<'x> {
script: &'x Sieve<'x>,
test: &ops::TestExists,
) -> Result<TestResult, RuntimeError> {
let header_names = self.parse_header_names(script, test.header_names)?;
let Some(header_names) =
self.parse_header_names(script, test.header_names, InvalidHeaderNames::Fail)?
else {
return Ok(TestResult::Bool(test.is_not));
};
let Some(part) = self.current_part() else {
return Ok(TestResult::Bool(test.is_not));
};

View file

@ -32,6 +32,12 @@ use smallvec::SmallVec;
pub(crate) type HeaderNames<'x> = SmallVec<[HeaderName<'x>; 4]>;
pub(crate) type HeaderKeys<'x> = SmallVec<[HeaderKey<'x>; 4]>;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum InvalidHeaderNames {
Skip,
Fail,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum MimeOptsRef<'x> {
None,
@ -49,7 +55,9 @@ impl<'x> Context<'x> {
handler: &mut H,
) -> Result<TestResult, RuntimeError> {
let key_list = self.eval_keys(script, test.key_list)?;
let header_list = self.parse_header_names(script, test.header_list)?;
let header_list = self
.parse_header_names(script, test.header_list, InvalidHeaderNames::Skip)?
.unwrap_or_default();
let mime_opts = self.mime_opts(script, &test.mime_opts)?;
let comparator = Comparator::from_code(test.comparator);
let match_type = test.match_type.match_type();
@ -235,7 +243,8 @@ impl<'x> Context<'x> {
&self,
script: &'x Sieve<'x>,
header_names: Range,
) -> Result<HeaderNames<'x>, RuntimeError> {
invalid: InvalidHeaderNames,
) -> Result<Option<HeaderNames<'x>>, RuntimeError> {
let mut result = HeaderNames::with_capacity(header_names.len as usize);
let mut iter = script.recs(header_names)?;
while let Some(rec) = iter.next() {
@ -248,10 +257,12 @@ impl<'x> Context<'x> {
self.parse_header_name_str(self.intern_cow(value.into_string()))
{
result.push(header_name);
} else if invalid == InvalidHeaderNames::Fail {
return Ok(None);
}
}
}
Ok(result)
Ok(Some(result))
}
#[inline(always)]

Some files were not shown because too many files have changed in this diff Show more