1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
/*
* Copyright (c) 2020-2023, Stalwart Labs Ltd.
*
* This file is part of the Stalwart Sieve Interpreter.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* in the LICENSE file at the top-level directory of this distribution.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* You can be released from the requirements of the AGPLv3 license by
* purchasing a commercial license. Please contact licensing@stalw.art
* for more details.
*/
//! # sieve
//!
//! [![crates.io](https://img.shields.io/crates/v/sieve-rs)](https://crates.io/crates/sieve-rs)
//! [![build](https://github.com/stalwartlabs/sieve/actions/workflows/rust.yml/badge.svg)](https://github.com/stalwartlabs/sieve/actions/workflows/rust.yml)
//! [![docs.rs](https://img.shields.io/docsrs/sieve-rs)](https://docs.rs/sieve-rs)
//! [![License: AGPL v3](https://img.shields.io/badge/License-AGPL_v3-blue.svg)](https://www.gnu.org/licenses/agpl-3.0)
//!
//! _sieve_ is a fast and secure Sieve filter interpreter for Rust that supports all [registered Sieve extensions](https://www.iana.org/assignments/sieve-extensions/sieve-extensions.xhtml).
//!
//! ## Usage Example
//!
//! ```rust
//! use sieve::{runtime::RuntimeError, 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;
//! }
//! "#;
//! let raw_message = r#"From: Sales Mailing List <list-sales@example.org>
//! To: John Doe <jdoe@example.org>
//! List-ID: <sales@example.org>
//! 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!
//! "#;
//!
//! // 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(raw_message.as_bytes());
//! let mut input = Input::script("my-script", script);
//! let mut messages: Vec<String> = Vec::new();
//!
//! // 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 { .. } => {
//! // Set to true if the mailbox exists
//! input = false.into();
//! }
//! Event::ListContains { .. } => {
//! // Set to true if the list(s) contains an entry
//! input = false.into();
//! }
//! Event::DuplicateId { .. } => {
//! // Set to true if the ID is duplicate
//! input = false.into();
//! }
//! Event::SetEnvelope { envelope, value } => {
//! println!("Set envelope {envelope:?} to {value:?}");
//! input = true.into();
//! }
//!
//! Event::Keep { flags, message_id } => {
//! println!(
//! "Keep message '{}' with flags {:?}.",
//! if message_id > 0 {
//! messages[message_id - 1].as_str()
//! } else {
//! raw_message
//! },
//! flags
//! );
//! input = true.into();
//! }
//! Event::Discard => {
//! println!("Discard message.");
//! input = true.into();
//! }
//! Event::Reject { reason, .. } => {
//! println!("Reject message with reason {:?}.", reason);
//! input = true.into();
//! }
//! Event::FileInto {
//! folder,
//! flags,
//! message_id,
//! ..
//! } => {
//! println!(
//! "File message '{}' in folder {:?} with flags {:?}.",
//! if message_id > 0 {
//! messages[message_id - 1].as_str()
//! } else {
//! raw_message
//! },
//! folder,
//! flags
//! );
//! input = true.into();
//! }
//! Event::SendMessage {
//! recipient,
//! message_id,
//! ..
//! } => {
//! println!(
//! "Send message '{}' to {:?}.",
//! if message_id > 0 {
//! messages[message_id - 1].as_str()
//! } else {
//! raw_message
//! },
//! recipient
//! );
//! input = true.into();
//! }
//! Event::Notify {
//! message, method, ..
//! } => {
//! println!("Notify URI {:?} with message {:?}", method, message);
//! input = true.into();
//! }
//! Event::CreatedMessage { message, .. } => {
//! messages.push(String::from_utf8(message).unwrap());
//! input = true.into();
//! }
//! Event::Function { id, arguments } => {
//! println!(
//! "Script executed external function {id} with parameters {arguments:?}"
//! );
//! // Return variable result back to interpreter
//! input = Input::result("hello world".into());
//! }
//! },
//! Err(error) => {
//! match error {
//! 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::CPULimitReached => {
//! eprintln!("Script exceeded the configured CPU limit.");
//! }
//! }
//! input = true.into();
//! }
//! }
//! }
//! ```
//!
//! ## Testing and Fuzzing
//!
//! To run the testsuite:
//!
//! ```bash
//! $ cargo test --all-features
//! ```
//!
//! To fuzz the library with `cargo-fuzz`:
//!
//! ```bash
//! $ cargo +nightly fuzz run mail_parser
//! ```
//!
//! ## Conformed RFCs
//!
//! - [RFC 5228 - Sieve: An Email Filtering Language](https://datatracker.ietf.org/doc/html/rfc5228)
//! - [RFC 3894 - Copying Without Side Effects](https://datatracker.ietf.org/doc/html/rfc3894)
//! - [RFC 5173 - Body Extension](https://datatracker.ietf.org/doc/html/rfc5173)
//! - [RFC 5183 - Environment Extension](https://datatracker.ietf.org/doc/html/rfc5183)
//! - [RFC 5229 - Variables Extension](https://datatracker.ietf.org/doc/html/rfc5229)
//! - [RFC 5230 - Vacation Extension](https://datatracker.ietf.org/doc/html/rfc5230)
//! - [RFC 5231 - Relational Extension](https://datatracker.ietf.org/doc/html/rfc5231)
//! - [RFC 5232 - Imap4flags Extension](https://datatracker.ietf.org/doc/html/rfc5232)
//! - [RFC 5233 - Subaddress Extension](https://datatracker.ietf.org/doc/html/rfc5233)
//! - [RFC 5235 - Spamtest and Virustest Extensions](https://datatracker.ietf.org/doc/html/rfc5235)
//! - [RFC 5260 - Date and Index Extensions](https://datatracker.ietf.org/doc/html/rfc5260)
//! - [RFC 5293 - Editheader Extension](https://datatracker.ietf.org/doc/html/rfc5293)
//! - [RFC 5429 - Reject and Extended Reject Extensions](https://datatracker.ietf.org/doc/html/rfc5429)
//! - [RFC 5435 - Extension for Notifications](https://datatracker.ietf.org/doc/html/rfc5435)
//! - [RFC 5463 - Ihave Extension](https://datatracker.ietf.org/doc/html/rfc5463)
//! - [RFC 5490 - Extensions for Checking Mailbox Status and Accessing Mailbox Metadata](https://datatracker.ietf.org/doc/html/rfc5490)
//! - [RFC 5703 - MIME Part Tests, Iteration, Extraction, Replacement, and Enclosure](https://datatracker.ietf.org/doc/html/rfc5703)
//! - [RFC 6009 - Delivery Status Notifications and Deliver-By Extensions](https://datatracker.ietf.org/doc/html/rfc6009)
//! - [RFC 6131 - Sieve Vacation Extension: "Seconds" Parameter](https://datatracker.ietf.org/doc/html/rfc6131)
//! - [RFC 6134 - Externally Stored Lists](https://datatracker.ietf.org/doc/html/rfc6134)
//! - [RFC 6558 - Converting Messages before Delivery](https://datatracker.ietf.org/doc/html/rfc6558)
//! - [RFC 6609 - Include Extension](https://datatracker.ietf.org/doc/html/rfc6609)
//! - [RFC 7352 - Detecting Duplicate Deliveries](https://datatracker.ietf.org/doc/html/rfc7352)
//! - [RFC 8579 - Delivering to Special-Use Mailboxes](https://datatracker.ietf.org/doc/html/rfc8579)
//! - [RFC 8580 - File Carbon Copy (FCC)](https://datatracker.ietf.org/doc/html/rfc8580)
//! - [RFC 9042 - Delivery by MAILBOXID](https://datatracker.ietf.org/doc/html/rfc9042)
//! - [REGEX-01 - Regular Expression Extension (draft-ietf-sieve-regex-01)](https://www.ietf.org/archive/id/draft-ietf-sieve-regex-01.html)
//!
//! ## License
//!
//! Licensed under the terms of the [GNU Affero General Public License](https://www.gnu.org/licenses/agpl-3.0.en.html) as published by
//! the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//! See [LICENSE](LICENSE) for more details.
//!
//! You can be released from the requirements of the AGPLv3 license by purchasing
//! a commercial license. Please contact licensing@stalw.art for more details.
//!
//! ## Copyright
//!
//! Copyright (C) 2020-2023, Stalwart Labs Ltd.
//!
use std::{borrow::Cow, sync::Arc, vec::IntoIter};
use ahash::{AHashMap, AHashSet};
use compiler::grammar::{
actions::action_redirect::{ByTime, Notify, Ret},
instruction::Instruction,
Capability,
};
use mail_parser::{HeaderName, Message};
use runtime::{context::ScriptStack, Variable};
use serde::{Deserialize, Serialize};
pub mod compiler;
pub mod runtime;
pub(crate) const MAX_MATCH_VARIABLES: usize = 63;
pub(crate) const MAX_LOCAL_VARIABLES: usize = 256;
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct Sieve {
instructions: Vec<Instruction>,
num_vars: usize,
num_match_vars: usize,
}
#[derive(Clone)]
pub struct Compiler {
// Settings
pub(crate) max_script_size: usize,
pub(crate) max_string_size: usize,
pub(crate) max_variable_name_size: usize,
pub(crate) max_nested_blocks: usize,
pub(crate) max_nested_tests: usize,
pub(crate) max_nested_foreverypart: usize,
pub(crate) max_match_variables: usize,
pub(crate) max_local_variables: usize,
pub(crate) max_header_size: usize,
pub(crate) max_includes: usize,
pub(crate) no_capability_check: bool,
// Functions
pub(crate) functions: AHashMap<String, (u32, u32)>,
}
pub type Function = for<'x> fn(&'x Context<'x>, Vec<Variable>) -> Variable;
#[derive(Default, Clone)]
pub struct FunctionMap {
pub(crate) map: AHashMap<String, (u32, u32)>,
pub(crate) functions: Vec<Function>,
}
#[derive(Debug, Clone)]
pub struct Runtime {
pub(crate) allowed_capabilities: AHashSet<Capability>,
pub(crate) valid_notification_uris: AHashSet<Cow<'static, str>>,
pub(crate) valid_ext_lists: AHashSet<Cow<'static, str>>,
pub(crate) protected_headers: Vec<HeaderName<'static>>,
pub(crate) environment: AHashMap<Cow<'static, str>, Variable>,
pub(crate) metadata: Vec<(Metadata<String>, Cow<'static, str>)>,
pub(crate) include_scripts: AHashMap<String, Arc<Sieve>>,
pub(crate) local_hostname: Cow<'static, str>,
pub(crate) functions: Vec<Function>,
pub(crate) max_nested_includes: usize,
pub(crate) cpu_limit: usize,
pub(crate) max_variable_size: usize,
pub(crate) max_redirects: usize,
pub(crate) max_received_headers: usize,
pub(crate) max_header_size: usize,
pub(crate) max_out_messages: usize,
pub(crate) default_vacation_expiry: u64,
pub(crate) default_duplicate_expiry: u64,
pub(crate) vacation_use_orig_rcpt: bool,
pub(crate) vacation_default_subject: Cow<'static, str>,
pub(crate) vacation_subject_prefix: Cow<'static, str>,
}
#[derive(Clone, Debug)]
pub struct Context<'x> {
#[cfg(test)]
pub(crate) runtime: Runtime,
#[cfg(not(test))]
pub(crate) runtime: &'x Runtime,
pub(crate) user_address: Cow<'x, str>,
pub(crate) user_full_name: Cow<'x, str>,
pub(crate) current_time: i64,
pub(crate) message: Message<'x>,
pub(crate) message_size: usize,
pub(crate) envelope: Vec<(Envelope, Variable)>,
pub(crate) metadata: Vec<(Metadata<String>, Cow<'x, str>)>,
pub(crate) part: usize,
pub(crate) part_iter: IntoIter<usize>,
pub(crate) part_iter_stack: Vec<(usize, IntoIter<usize>)>,
pub(crate) spam_status: SpamStatus,
pub(crate) virus_status: VirusStatus,
pub(crate) pos: usize,
pub(crate) test_result: bool,
pub(crate) script_cache: AHashMap<Script, Arc<Sieve>>,
pub(crate) script_stack: Vec<ScriptStack>,
pub(crate) vars_global: AHashMap<Cow<'static, str>, Variable>,
pub(crate) vars_env: AHashMap<Cow<'static, str>, Variable>,
pub(crate) vars_local: Vec<Variable>,
pub(crate) vars_match: Vec<Variable>,
pub(crate) expr_stack: Vec<Variable>,
pub(crate) expr_pos: usize,
pub(crate) queued_events: IntoIter<Event>,
pub(crate) final_event: Option<Event>,
pub(crate) last_message_id: usize,
pub(crate) main_message_id: usize,
pub(crate) has_changes: bool,
pub(crate) num_redirects: usize,
pub(crate) num_instructions: usize,
pub(crate) num_out_messages: usize,
}
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum Script {
Personal(String),
Global(String),
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub enum Envelope {
From,
To,
ByTimeAbsolute,
ByTimeRelative,
ByMode,
ByTrace,
Notify,
Orcpt,
Ret,
Envid,
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub enum Metadata<T> {
Server { annotation: T },
Mailbox { name: T, annotation: T },
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Event {
IncludeScript {
name: Script,
optional: bool,
},
MailboxExists {
mailboxes: Vec<Mailbox>,
special_use: Vec<String>,
},
ListContains {
lists: Vec<String>,
values: Vec<String>,
match_as: MatchAs,
},
DuplicateId {
id: String,
expiry: u64,
last: bool,
},
SetEnvelope {
envelope: Envelope,
value: String,
},
Function {
id: ExternalId,
arguments: Vec<Variable>,
},
// Actions
Keep {
flags: Vec<String>,
message_id: usize,
},
Discard,
Reject {
extended: bool,
reason: String,
},
FileInto {
folder: String,
flags: Vec<String>,
mailbox_id: Option<String>,
special_use: Option<String>,
create: bool,
message_id: usize,
},
SendMessage {
recipient: Recipient,
notify: Notify,
return_of_content: Ret,
by_time: ByTime<i64>,
message_id: usize,
},
Notify {
from: Option<String>,
importance: Importance,
options: Vec<String>,
message: String,
method: String,
},
CreatedMessage {
message_id: usize,
message: Vec<u8>,
},
}
pub type ExternalId = u32;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub(crate) struct FileCarbonCopy<T> {
pub mailbox: T,
pub mailbox_id: Option<T>,
pub create: bool,
pub flags: Vec<T>,
pub special_use: Option<T>,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum Importance {
High,
Normal,
Low,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum MatchAs {
Octet,
Lowercase,
Number,
}
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum Recipient {
Address(String),
List(String),
Group(Vec<String>),
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Input {
True,
False,
FncResult(Variable),
Script { name: Script, script: Arc<Sieve> },
}
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum Mailbox {
Name(String),
Id(String),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SpamStatus {
Unknown,
Ham,
MaybeSpam(f64),
Spam,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum VirusStatus {
Unknown,
Clean,
Replaced,
Cured,
MaybeVirus,
Virus,
}
#[cfg(test)]
mod tests {
use std::{
fs,
path::{Path, PathBuf},
};
use ahash::{AHashMap, AHashSet};
use mail_parser::{
parsers::MessageStream, Encoding, HeaderValue, Message, MessageParser, MessagePart,
PartType,
};
use crate::{
compiler::grammar::Capability,
runtime::{actions::action_mime::reset_test_boundary, Variable},
Compiler, Context, Envelope, Event, FunctionMap, Input, Mailbox, Recipient, Runtime,
SpamStatus, VirusStatus,
};
impl Variable {
pub fn unwrap_string(self) -> String {
self.to_string().into_owned()
}
}
#[test]
fn test_suite() {
let mut tests = Vec::new();
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push("tests");
read_dir(path, &mut tests);
for test in tests {
/*if !test
.file_name()
.unwrap()
.to_str()
.unwrap()
.contains("expressions")
{
continue;
}*/
println!("===== {} =====", test.display());
run_test(&test);
}
}
fn read_dir(path: PathBuf, files: &mut Vec<PathBuf>) {
for entry in fs::read_dir(path).unwrap() {
let entry = entry.unwrap().path();
if entry.is_dir() {
read_dir(entry, files);
} else if entry
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.eq("svtest")
{
files.push(entry);
}
}
}
fn run_test(script_path: &Path) {
let mut fnc_map = FunctionMap::new()
.with_function("trim", |_, v| match v.into_iter().next().unwrap() {
crate::runtime::Variable::String(s) => s.trim().to_string().into(),
v => v.to_string().into(),
})
.with_function("len", |_, v| v[0].to_string().len().into())
.with_function("count", |_, v| {
v[0].as_array().map_or(0, |arr| arr.len()).into()
})
.with_function("to_lowercase", |_, v| {
v[0].to_string().to_lowercase().to_string().into()
})
.with_function("to_uppercase", |_, v| {
v[0].to_string().to_uppercase().to_string().into()
})
.with_function("is_uppercase", |_, v| {
v[0].to_string()
.as_ref()
.chars()
.filter(|c| c.is_alphabetic())
.all(|c| c.is_uppercase())
.into()
})
.with_function("is_ascii", |_, v| {
v[0].to_string()
.as_ref()
.chars()
.any(|c| !c.is_ascii())
.into()
})
.with_function("char_count", |_, v| {
v[0].to_string().as_ref().chars().count().into()
})
.with_function("lines", |_, v| {
v[0].to_string()
.lines()
.map(|line| Variable::from(line.to_string()))
.collect::<Vec<_>>()
.into()
})
.with_function_args(
"contains",
|_, v| v[0].to_string().contains(v[1].to_string().as_ref()).into(),
2,
)
.with_function_args(
"eq_lowercase",
|_, v| {
v[0].to_string()
.as_ref()
.eq_ignore_ascii_case(v[1].to_string().as_ref())
.into()
},
2,
)
.with_function_args(
"concat_three",
|_, v| format!("{}-{}-{}", v[0], v[1], v[2]).into(),
3,
)
.with_function_args(
"in_array",
|_, v| {
v[0].as_array()
.map_or(false, |arr| arr.contains(&v[1]))
.into()
},
2,
)
.with_external_function("ext_zero", 0, 0)
.with_external_function("ext_one", 1, 1)
.with_external_function("ext_two", 2, 2)
.with_external_function("ext_three", 3, 3)
.with_external_function("ext_true", 4, 0)
.with_external_function("ext_false", 5, 0);
let mut compiler = Compiler::new()
.with_max_string_size(10240)
.register_functions(&mut fnc_map);
let mut ancestors = script_path.ancestors();
ancestors.next();
let base_path = ancestors.next().unwrap();
let script = compiler
.compile(&add_crlf(&fs::read(script_path).unwrap()))
.unwrap();
let mut input = Input::script("", script);
let mut current_test = String::new();
let mut raw_message_: Option<Vec<u8>> = None;
let mut prev_state = None;
let mut mailboxes = Vec::new();
let mut lists: AHashMap<String, AHashSet<String>> = AHashMap::new();
let mut duplicated_ids = AHashSet::new();
let mut actions = Vec::new();
'outer: loop {
let runtime = Runtime::new()
.with_protected_header("Auto-Submitted")
.with_protected_header("Received")
.with_valid_notification_uri("mailto")
.with_max_out_messages(100)
.with_capability(Capability::While)
.with_capability(Capability::Expressions)
.with_functions(&mut fnc_map.clone());
let mut instance = Context::new(
&runtime,
Message {
parts: vec![MessagePart {
headers: vec![],
is_encoding_problem: false,
body: PartType::Text("".into()),
encoding: Encoding::None,
offset_header: 0,
offset_body: 0,
offset_end: 0,
}],
raw_message: b""[..].into(),
..Default::default()
},
);
let raw_message = raw_message_.take().unwrap_or_default();
instance.message =
MessageParser::new()
.parse(&raw_message)
.unwrap_or_else(|| Message {
html_body: vec![],
text_body: vec![],
attachments: vec![],
parts: vec![MessagePart {
headers: vec![],
is_encoding_problem: false,
body: PartType::Text("".into()),
encoding: Encoding::None,
offset_header: 0,
offset_body: 0,
offset_end: 0,
}],
raw_message: b""[..].into(),
});
instance.message_size = raw_message.len();
if let Some((pos, script_cache, script_stack, vars_global, vars_local, vars_match)) =
prev_state.take()
{
instance.pos = pos;
instance.script_cache = script_cache;
instance.script_stack = script_stack;
instance.vars_global = vars_global;
instance.vars_local = vars_local;
instance.vars_match = vars_match;
}
instance.set_env_variable("vnd.stalwart.default_mailbox", "INBOX");
instance.set_env_variable("vnd.stalwart.username", "john.doe");
instance.set_user_address("MAILER-DAEMON");
if let Some(addr) = instance
.message
.from()
.and_then(|a| a.first())
.and_then(|a| a.address.as_ref())
{
instance.set_envelope(Envelope::From, addr.to_string());
}
if let Some(addr) = instance
.message
.to()
.and_then(|a| a.first())
.and_then(|a| a.address.as_ref())
{
instance.set_envelope(Envelope::To, addr.to_string());
}
while let Some(event) = instance.run(input) {
match event.unwrap() {
Event::IncludeScript { name, optional } => {
let mut include_path = PathBuf::from(base_path);
include_path.push(if matches!(name, crate::Script::Personal(_)) {
"included"
} else {
"included-global"
});
include_path.push(format!("{name}.sieve"));
if let Ok(bytes) = fs::read(include_path.as_path()) {
let script = compiler.compile(&add_crlf(&bytes)).unwrap();
input = Input::script(name, script);
} else if optional {
input = Input::False;
} else {
panic!("Script {} not found.", include_path.display());
}
}
Event::MailboxExists {
mailboxes: mailboxes_,
special_use,
} => {
for action in &actions {
if let Event::FileInto { folder, create, .. } = action {
if *create && !mailboxes.contains(folder) {
mailboxes.push(folder.to_string());
}
}
}
input = (special_use.is_empty()
&& mailboxes_.iter().all(|n| {
if let Mailbox::Name(n) = n {
mailboxes.contains(n)
} else {
false
}
}))
.into();
}
Event::ListContains {
lists: lists_,
values,
..
} => {
let mut result = false;
'list: for list in &lists_ {
if let Some(list) = lists.get(list) {
for value in &values {
if list.contains(value) {
result = true;
break 'list;
}
}
}
}
input = result.into();
}
Event::DuplicateId { id, .. } => {
input = duplicated_ids.contains(&id).into();
}
Event::Function { id, arguments } => {
if id == u32::MAX {
// Test functions
input = Input::True;
let mut arguments = arguments.into_iter();
let command = arguments.next().unwrap().unwrap_string();
let mut params =
arguments.map(|arg| arg.unwrap_string()).collect::<Vec<_>>();
match command.as_str() {
"test" => {
current_test = params.pop().unwrap();
println!("Running test '{current_test}'...");
}
"test_set" => {
let mut params = params.into_iter();
let target = params.next().expect("test_set parameter");
if target == "message" {
let value = params.next().unwrap();
raw_message_ = if value.eq_ignore_ascii_case(":smtp") {
let mut message = None;
for action in actions.iter().rev() {
if let Event::SendMessage { message_id, .. } =
action
{
let message_ = actions
.iter()
.find_map(|item| {
if let Event::CreatedMessage {
message_id: message_id_,
message,
} = item
{
if message_id == message_id_ {
return Some(message);
}
}
None
})
.unwrap();
/*println!(
"<[{}]>",
std::str::from_utf8(message_).unwrap()
);*/
message = message_.into();
break;
}
}
message.expect("No SMTP message found").to_vec().into()
} else {
value.into_bytes().into()
};
prev_state = (
instance.pos,
instance.script_cache,
instance.script_stack,
instance.vars_global,
instance.vars_local,
instance.vars_match,
)
.into();
continue 'outer;
} else if let Some(envelope) = target.strip_prefix("envelope.")
{
let envelope =
Envelope::try_from(envelope.to_string()).unwrap();
instance.envelope.retain(|(e, _)| e != &envelope);
instance.set_envelope(envelope, params.next().unwrap());
} else if target == "currentdate" {
let bytes = params.next().unwrap().into_bytes();
if let HeaderValue::DateTime(dt) =
MessageStream::new(&bytes).parse_date()
{
instance.current_time = dt.to_timestamp();
} else {
panic!("Invalid currentdate");
}
} else {
panic!("test_set {target} not implemented.");
}
}
"test_message" => {
let mut params = params.into_iter();
input = match params.next().unwrap().as_str() {
":folder" => {
let folder_name = params.next().expect("test_message folder name");
matches!(&instance.final_event, Some(Event::Keep { .. })) ||
actions.iter().any(|a| if !folder_name.eq_ignore_ascii_case("INBOX") {
matches!(a, Event::FileInto { folder, .. } if folder == &folder_name )
} else {
matches!(a, Event::Keep { .. })
})
}
":smtp" => {
actions.iter().any(|a| matches!(a, Event::SendMessage { .. } ))
}
param => panic!("Invalid test_message param '{param}'" ),
}.into();
}
"test_assert_message" => {
let expected_message =
params.first().expect("test_set parameter");
let built_message = instance.build_message();
if expected_message.as_bytes() != built_message {
//fs::write("_deleteme.json", serde_json::to_string_pretty(&Message::parse(&built_message).unwrap()).unwrap()).unwrap();
print!("<[");
print!("{}", String::from_utf8(built_message).unwrap());
println!("]>");
panic!("Message built incorrectly at '{current_test}'");
}
}
"test_config_set" => {
let mut params = params.into_iter();
let name = params.next().unwrap();
let value = params.next().expect("test_config_set value");
match name.as_str() {
"sieve_editheader_protected"
| "sieve_editheader_forbid_add"
| "sieve_editheader_forbid_delete" => {
if !value.is_empty() {
for header_name in value.split(' ') {
instance.runtime.set_protected_header(
header_name.to_string(),
);
}
} else {
instance.runtime.protected_headers.clear();
}
}
"sieve_variables_max_variable_size" => {
instance
.runtime
.set_max_variable_size(value.parse().unwrap());
}
"sieve_valid_ext_list" => {
instance.runtime.set_valid_ext_list(value);
}
"sieve_ext_list_item" => {
lists
.entry(value)
.or_default()
.insert(params.next().expect("list item value"));
}
"sieve_duplicated_id" => {
duplicated_ids.insert(value);
}
"sieve_user_email" => {
instance.set_user_address(value);
}
"sieve_vacation_use_original_recipient" => {
instance.runtime.set_vacation_use_orig_rcpt(
value.eq_ignore_ascii_case("yes"),
);
}
"sieve_vacation_default_subject" => {
instance.runtime.set_vacation_default_subject(value);
}
"sieve_vacation_default_subject_template" => {
instance.runtime.set_vacation_subject_prefix(value);
}
"sieve_spam_status" => {
instance.set_spam_status(SpamStatus::from_number(
value.parse().unwrap(),
));
}
"sieve_spam_status_plus" => {
instance.set_spam_status(
match value.parse::<u32>().unwrap() {
0 => SpamStatus::Unknown,
100.. => SpamStatus::Spam,
n => SpamStatus::MaybeSpam((n as f64) / 100.0),
},
);
}
"sieve_virus_status" => {
instance.set_virus_status(VirusStatus::from_number(
value.parse().unwrap(),
));
}
"sieve_editheader_max_header_size" => {
let mhs = if !value.is_empty() {
value.parse::<usize>().unwrap()
} else {
1024
};
instance.runtime.set_max_header_size(mhs);
compiler.set_max_header_size(mhs);
}
"sieve_include_max_includes" => {
compiler.set_max_includes(if !value.is_empty() {
value.parse::<usize>().unwrap()
} else {
3
});
}
"sieve_include_max_nesting_depth" => {
compiler.set_max_nested_blocks(if !value.is_empty() {
value.parse::<usize>().unwrap()
} else {
3
});
}
param => panic!("Invalid test_config_set param '{param}'"),
}
}
"test_result_execute" => {
input =
(matches!(&instance.final_event, Some(Event::Keep { .. }))
|| actions.iter().any(|a| {
matches!(
a,
Event::Keep { .. }
| Event::FileInto { .. }
| Event::SendMessage { .. }
)
}))
.into();
}
"test_result_action" => {
let param =
params.first().expect("test_result_action parameter");
input = if param == "reject" {
(actions.iter().any(|a| matches!(a, Event::Reject { .. })))
.into()
} else if param == "redirect" {
let param = params
.last()
.expect("test_result_action redirect address");
(actions
.iter()
.any(|a| matches!(a, Event::SendMessage { recipient: Recipient::Address(address), .. } if address == param)))
.into()
} else if param == "keep" {
(matches!(&instance.final_event, Some(Event::Keep { .. }))
|| actions
.iter()
.any(|a| matches!(a, Event::Keep { .. })))
.into()
} else if param == "send_message" {
(actions
.iter()
.any(|a| matches!(a, Event::SendMessage { .. })))
.into()
} else {
panic!("test_result_action {param} not implemented");
};
}
"test_result_action_count" => {
input = (actions.len()
== params.first().unwrap().parse::<usize>().unwrap())
.into();
}
"test_imap_metadata_set" => {
let mut params = params.into_iter();
let first = params.next().expect("metadata parameter");
let (mailbox, annotation) = if first == ":mailbox" {
(
params.next().expect("metadata mailbox name").into(),
params.next().expect("metadata annotation name"),
)
} else {
(None, first)
};
let value = params.next().expect("metadata value");
if let Some(mailbox) = mailbox {
instance.set_medatata((mailbox, annotation), value);
} else {
instance.set_medatata(annotation, value);
}
}
"test_mailbox_create" => {
mailboxes.push(params.pop().expect("mailbox to create"));
}
"test_result_reset" => {
actions.clear();
instance.final_event = Event::Keep {
flags: vec![],
message_id: 0,
}
.into();
instance.metadata.clear();
instance.has_changes = false;
instance.num_redirects = 0;
instance.runtime.vacation_use_orig_rcpt = false;
mailboxes.clear();
lists.clear();
reset_test_boundary();
}
"test_script_compile" => {
let mut include_path = PathBuf::from(base_path);
include_path.push(params.first().unwrap());
if let Ok(bytes) = fs::read(include_path.as_path()) {
let result = compiler.compile(&add_crlf(&bytes));
/*if let Err(err) = &result {
println!("Error: {:?}", err);
}*/
input = result.is_ok().into();
} else {
panic!("Script {} not found.", include_path.display());
}
}
"test_config_reload" => (),
"test_fail" => {
panic!(
"Test '{}' failed: {}",
current_test,
params.pop().unwrap()
);
}
_ => panic!("Test command {command} not implemented."),
}
} else {
let result = match id {
0 => Variable::from("my_value"),
1 => Variable::from(arguments[0].to_string().to_uppercase()),
2 => Variable::from(format!(
"{}-{}",
arguments[0].to_string(),
arguments[1].to_string()
)),
3 => Variable::from(format!(
"{}-{}-{}",
arguments[0].to_string(),
arguments[1].to_string(),
arguments[2].to_string()
)),
4 => true.into(),
5 => false.into(),
_ => {
panic!("Unknown external function {id}");
}
};
input = result.into();
}
}
action => {
actions.push(action);
input = true.into();
}
}
}
return;
}
}
fn add_crlf(bytes: &[u8]) -> Vec<u8> {
let mut result = Vec::with_capacity(bytes.len());
let mut last_ch = 0;
for &ch in bytes {
if ch == b'\n' && last_ch != b'\r' {
result.push(b'\r');
}
result.push(ch);
last_ch = ch;
}
result
}
}