Skip to main content

3 posts tagged with "sieve"

View All Tags

· 2 min read
Mauro D.

Today we are announcing the latest release of Stalwart Mail Server: version 0.3.6. This update includes multiple enhancements to the Sieve filtering language, including the ability to evaluate arithmetical and logical expressions, and fetch data from SQL or LDAP databases to Sieve variables.

Arithmetical and Logical Expressions

Stalwart Mail Server now incorporates the ability to evaluate arithmetical and logical operations within Sieve scripts. For instance, the following Sieve script rejects a mail if it satisfies a particular condition:

if test eval "score + ((awl_score / awl_count) - score) * awl_factor > 2.25" {
reject "Your message is SPAM.";
stop;
}

Whether you're aiming to refine your filtering mechanisms or just add some mathematical magic to your scripts, this feature is sure to come in handy.

To learn more about expressions in Sieve scripts, check out the Arithmetical and Logical Expressions section in the documentation.

Fetching Data from Databases

Using Sieve scripts, you can now query SQL or LDAP databases and store the results as Sieve variables. This is done using the query command with the optional :set argument.

Consider this example:

query :use "sql" :set ["awl_score", "awl_count"] "SELECT score, count FROM awl WHERE sender = ? AND ip = ?" ["${env.from}", "%{env.remote_ip}"];

The above Sieve script fetches the score and count columns from the awl table in an SQL database and stores them as the Sieve variables awl_score and awl_count respectively.

To learn more about fetching data from SQL or LDAP queries, check out the query extension documentation.

Conclusion

These features allow for more advanced filtering mechanisms and more powerful Sieve scripts. We hope you enjoy them!

· 2 min read
Mauro D.

Sieve (RFC5228) is a scripting language for filtering email messages at or around the time of final delivery. It is suitable for running on a mail server where users may not be allowed to execute arbitrary programs as it has no user-controlled loops or the ability to run external programs. Sieve is a data-driven programming language, similar to earlier email filtering languages such as procmail and maildrop, and earlier line-oriented languages such as sed and AWK: it specifies conditions to match and actions to take on matching.

Today Stalwart JMAP v0.2 was released including support for the for JMAP for Sieve Scripts draft. Additionally, ManageSieve support was added to Stalwart IMAP v0.2.

Stalwart JMAP safely runs Sieve scripts in a controlled sandbox that ensures that programs do not exceed or abuse their allocated system resources.

Unlike other mail servers that offer limited support for Sieve extensions, Stalwart JMAP supports all existing Sieve extensions including:

· 4 min read
Mauro D.

Sieve is a language that can be used to create filters for electronic mail. It is not tied to any particular operating system or mail architecture. It requires the use of RFC 822-compliant messages, but otherwise should generalize to other systems that meet these criteria.

Today, the sieve-rs crate was released which is an interpreter for Sieve scripts written in Rust. The interpreter includes support for all existing Sieve extensions.

Currently the interpreter is available as a standalone library but it will be soon added to Stalwart JMAP (including JMAP Sieve support) and Stalwart IMAP (including ManageSieve support).

Compiling and running a Sieve script is straightforward:

    use sieve::{runtime::RuntimeError, Action, Compiler, Event, Input, Runtime};

let text_script = br#"
require ["fileinto", "body", "imap4flags"];

if body :contains "tps" {
setflag "$tps_reports";
}

if header :matches "List-ID" "*<*@*" {
fileinto "INBOX.lists.${2}"; stop;
}
"#;

// Compile
let compiler = Compiler::new();
let script = compiler.compile(text_script).unwrap();

// Build runtime
let runtime = Runtime::new();

// Create filter instance
let mut instance = runtime.filter(
br#"From: Sales Mailing List <[email protected]>
To: John Doe <[email protected]>
List-ID: <[email protected]>
Subject: TPS Reports

We're putting new coversheets on all the TPS reports before they go out now.
So if you could go ahead and try to remember to do that from now on, that'd be great. All right!
"#,
);
let mut input = Input::script("my-script", script);

// Start event loop
while let Some(result) = instance.run(input) {
match result {
Ok(event) => match event {
Event::IncludeScript { name, optional } => {
// NOTE: Just for demonstration purposes, script name needs to be validated first.
if let Ok(bytes) = std::fs::read(name.as_str()) {
let script = compiler.compile(&bytes).unwrap();
input = Input::script(name, script);
} else if optional {
input = Input::False;
} else {
panic!("Script {} not found.", name);
}
}
Event::MailboxExists { .. } => {
// Return true if the mailbox exists
input = false.into();
}
Event::ListContains { .. } => {
// Return true if the list(s) contains an entry
input = false.into();
}
Event::DuplicateId { .. } => {
// Return true if the ID is duplicate
input = false.into();
}
Event::Execute { command, arguments } => {
println!(
"Script executed command {:?} with parameters {:?}",
command, arguments
);
input = false.into(); // Report whether the script succeeded
}
#[cfg(test)]
_ => unreachable!(),
},
Err(error) => {
match error {
RuntimeError::IllegalAction => {
eprintln!("Script tried allocating more variables than allowed.");
}
RuntimeError::TooManyIncludes => {
eprintln!("Too many included scripts.");
}
RuntimeError::InvalidInstruction(instruction) => {
eprintln!(
"Invalid instruction {:?} found at {}:{}.",
instruction.name(),
instruction.line_num(),
instruction.line_pos()
);
}
RuntimeError::ScriptErrorMessage(message) => {
eprintln!("Script called the 'error' function with {:?}", message);
}
RuntimeError::CapabilityNotAllowed(capability) => {
eprintln!(
"Capability {:?} has been disabled by the administrator.",
capability
);
}
RuntimeError::CapabilityNotSupported(capability) => {
eprintln!("Capability {:?} not supported.", capability);
}
RuntimeError::OutOfMemory => {
eprintln!("Script exceeded the configured memory limit.");
}
RuntimeError::CPULimitReached => {
eprintln!("Script exceeded the configured CPU limit.");
}
}
break;
}
}
}

// Process actions
for action in instance.get_actions() {
match action {
Action::Keep { flags, message_id } => {
println!(
"Keep message '{}' with flags {:?}.",
std::str::from_utf8(instance.get_message(*message_id).unwrap()).unwrap(),
flags
);
}
Action::Discard => {
println!("Discard message.")
}
Action::Reject { reason } => {
println!("Reject message with reason {:?}.", reason);
}
Action::Ereject { reason } => {
println!("Ereject message with reason {:?}.", reason);
}
Action::FileInto {
folder,
flags,
message_id,
..
} => {
println!(
"File message '{}' in folder {:?} with flags {:?}.",
std::str::from_utf8(instance.get_message(*message_id).unwrap()).unwrap(),
folder,
flags
);
}
Action::SendMessage {
recipient,
message_id,
..
} => {
println!(
"Send message '{}' to {:?}.",
std::str::from_utf8(instance.get_message(*message_id).unwrap()).unwrap(),
recipient
);
}
Action::Notify {
message, method, ..
} => {
println!("Notify URI {:?} with message {:?}", method, message);
}
}
}

Additional examples are available on the repository.