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
/*
* vSMTP mail transfer agent
* Copyright (C) 2022 viridIT SAS
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see https://www.gnu.org/licenses/.
*
*/
use crate::{
api::{
EngineResult, {Message, SharedObject},
},
get_global,
};
use rhai::plugin::{
mem, Dynamic, FnAccess, FnNamespace, ImmutableString, Module, NativeCallContext,
PluginFunction, RhaiResult, TypeId,
};
pub use message::*;
use vsmtp_common::Address;
/// Inspect incoming messages.
#[rhai::plugin::export_module]
mod message {
/// Generate the `.eml` representation of the message.
///
/// # rhai-autodocs:index:1
#[rhai_fn(global, pure)]
pub fn to_string(message: &mut Message) -> String {
message
.read()
.expect("msg not poisoned")
.inner()
.to_string()
}
/// Checks if the message contains a specific header.
///
/// # Args
///
/// * `header` - the name of the header to search.
///
/// # Effective smtp stage
///
/// All of them, although it is most useful in the `preq` stage because the
/// email is received at this point.
///
/// # Examples
///
/// ```
/// // Message example.
/// # let msg = vsmtp_mail_parser::MessageBody::try_from(concat!(
/// "X-My-Header: foo\r\n",
/// "Subject: Unit test are cool\r\n",
/// "\r\n",
/// "Hello world!\r\n",
/// # )).unwrap();
/// # let rules = r#"
/// #{
/// preq: [
/// rule "check if header exists" || {
/// if msg::has_header("X-My-Header") && msg::has_header(identifier("Subject")) {
/// state::accept();
/// } else {
/// state::deny();
/// }
/// }
/// ]
/// }
/// # "#;
/// # let states = vsmtp_test::vsl::run_with_msg(|builder| Ok(builder
/// # .add_root_filter_rules("#{}")?
/// # .add_domain_rules("testserver.com".parse().unwrap())
/// # .with_incoming(rules)?
/// # .with_outgoing(rules)?
/// # .with_internal(rules)?
/// # .build()
/// # .build()), Some(msg));
/// # use vsmtp_common::{status::Status};
/// # assert_eq!(states[&vsmtp_rule_engine::ExecutionStage::PreQ].2, Status::Accept("250 Ok".parse::<vsmtp_common::Reply>().unwrap()));
/// ```
///
/// # rhai-autodocs:index:2
#[rhai_fn(name = "has_header", return_raw)]
pub fn has_header(ncc: NativeCallContext, header: &str) -> EngineResult<bool> {
Ok(vsl_guard_ok!(get_global!(ncc, msg).read())
.get_header(header)
.is_some())
}
#[doc(hidden)]
#[rhai_fn(name = "has_header", return_raw)]
pub fn has_header_obj(ncc: NativeCallContext, header: SharedObject) -> EngineResult<bool> {
has_header(ncc, &header.to_string())
}
/// Count the number of headers with the given name.
///
/// # Args
///
/// * `header` - the name of the header to count.
///
/// # Return
///
/// * `number` - the number headers with the same name.
///
/// # Effective smtp stage
///
/// All of them, although it is most useful in the `preq` stage because this
/// is when the email body is received.
///
/// # Examples
///
/// ```
/// # let msg = vsmtp_mail_parser::MessageBody::try_from(concat!(
/// "X-My-Header: foo\r\n",
/// "X-My-Header: bar\r\n",
/// "X-My-Header: baz\r\n",
/// "Subject: Unit test are cool\r\n",
/// "\r\n",
/// "Hello world!\r\n",
/// # )).unwrap();
/// # let rules = r#"
/// #{
/// preq: [
/// rule "count_header" || {
/// state::accept(`250 count is ${msg::count_header("X-My-Header")} and ${msg::count_header(identifier("Subject"))}`);
/// }
/// ]
/// }
/// # "#;
/// # let states = vsmtp_test::vsl::run_with_msg(|builder| Ok(builder
/// # .add_root_filter_rules("#{}")?
/// # .add_domain_rules("testserver.com".parse().unwrap())
/// # .with_incoming(rules)?
/// # .with_outgoing(rules)?
/// # .with_internal(rules)?
/// # .build()
/// # .build()), Some(msg));
/// # use vsmtp_common::{status::Status, Reply, ReplyCode::Code};
/// # assert_eq!(states[&vsmtp_rule_engine::ExecutionStage::PreQ].2, Status::Accept(
/// # "250 count is 3 and 1\r\n".parse().unwrap()
/// # ));
/// ```
///
/// # rhai-autodocs:index:3
#[rhai_fn(name = "count_header", return_raw)]
pub fn count_header(ncc: NativeCallContext, header: &str) -> EngineResult<rhai::INT> {
super::Impl::count_header(&get_global!(ncc, msg), header)
}
#[doc(hidden)]
#[rhai_fn(name = "count_header", return_raw)]
pub fn count_header_obj(
ncc: NativeCallContext,
header: SharedObject,
) -> EngineResult<rhai::INT> {
super::Impl::count_header(&get_global!(ncc, msg), &header.to_string())
}
/// Get a specific header from the incoming message.
///
/// # Args
///
/// * `header` - the name of the header to get.
///
/// # Return
///
/// * `string` - the header value, or an empty string if the header was not found.
///
/// # Effective smtp stage
///
/// All of them, although it is most useful in the `preq` stage because this
/// is when the email body is received.
///
/// # Examples
///
/// ```
/// # let msg = r#"
/// X-My-Header: 250 foo
/// Subject: Unit test are cool
///
/// Hello world!
/// # "#
/// ; // .eml ends here
/// # let msg = vsmtp_mail_parser::MessageBody::try_from(msg[1..].replace("\n", "\r\n").as_str()).unwrap();
///
/// let rules = r#"
/// #{
/// preq: [
/// rule "get_header" || {
/// if msg::get_header("X-My-Header") != "250 foo"
/// || msg::get_header(identifier("Subject")) != "Unit test are cool" {
/// state::deny();
/// } else {
/// state::accept(`${msg::get_header("X-My-Header")} ${msg::get_header(identifier("Subject"))}`);
/// }
/// }
/// ]
/// }
/// # "#;
/// # let states = vsmtp_test::vsl::run_with_msg(|builder| Ok(builder
/// # .add_root_filter_rules("#{}")?
/// # .add_domain_rules("testserver.com".parse().unwrap())
/// # .with_incoming(rules)?
/// # .with_outgoing(rules)?
/// # .with_internal(rules)?
/// # .build()
/// # .build()), Some(msg));
/// # use vsmtp_common::{status::Status, Reply, ReplyCode::Code};
/// # assert_eq!(states[&vsmtp_rule_engine::ExecutionStage::PreQ].2, Status::Accept(
/// # "250 foo Unit test are cool\r\n".parse().unwrap()
/// # ));
/// ```
///
/// # rhai-autodocs:index:4
#[rhai_fn(name = "get_header", return_raw)]
pub fn get_header(ncc: NativeCallContext, header: &str) -> EngineResult<String> {
Ok(vsl_guard_ok!(get_global!(ncc, msg).read())
.get_header(header)
.unwrap_or_default())
}
#[doc(hidden)]
#[rhai_fn(name = "get_header", return_raw)]
pub fn get_header_obj(ncc: NativeCallContext, header: SharedObject) -> EngineResult<String> {
get_header(ncc, &header.to_string())
}
/// Get a list of all headers.
///
/// # Args
///
/// * `header` - the name of the header to search. (optional, if not set, returns every header)
///
/// # Return
///
/// * `array` - all of the headers found in the message.
///
/// # Effective smtp stage
///
/// All of them, although it is most useful in the `preq` stage because this
/// is when the email body is received.
///
/// # Examples
///
/// ```
/// # let msg = r#"
/// X-My-Header: 250 foo
/// Subject: Unit test are cool
///
/// Hello world!
/// # "#
/// ; // .eml ends here
/// # let msg = vsmtp_mail_parser::MessageBody::try_from(msg[1..].replace("\n", "\r\n").as_str()).unwrap();
///
/// # let states = vsmtp_test::vsl::run_with_msg(
/// # |builder| Ok(builder.add_root_filter_rules(r#"
/// #{
/// preq: [
/// rule "display headers" || {
/// log("info", `all headers: ${msg::get_all_headers()}`);
/// log("info", `all "Return-Path" headers: ${msg::get_all_headers("Return-Path")}`);
/// }
/// ]
/// }
/// # "#)?.build()), Some(msg));
/// ```
///
/// # rhai-autodocs:index:5
#[rhai_fn(name = "get_all_headers", return_raw)]
pub fn get_all_headers(ncc: NativeCallContext) -> EngineResult<rhai::Array> {
Ok(vsl_guard_ok!(get_global!(ncc, msg).read())
.inner()
.raw_headers()
.iter()
.map(|raw| rhai::Dynamic::from(raw.clone()))
.collect())
}
#[doc(hidden)]
#[rhai_fn(name = "get_all_headers", return_raw)]
pub fn get_all_headers_str(ncc: NativeCallContext, name: &str) -> EngineResult<rhai::Array> {
Ok(super::Impl::get_all_headers(&get_global!(ncc, msg), name))
}
#[doc(hidden)]
#[rhai_fn(name = "get_all_headers", return_raw)]
pub fn get_all_headers_obj(
ncc: NativeCallContext,
name: SharedObject,
) -> EngineResult<rhai::Array> {
Ok(super::Impl::get_all_headers(
&get_global!(ncc, msg),
&name.to_string(),
))
}
/// Get a list of all headers of a specific name with it's name and value
/// separated by a column.
///
/// # Args
///
/// * `header` - the name of the header to search.
///
/// # Return
///
/// * `array` - all header values, or an empty array if the header was not found.
///
/// # Effective smtp stage
///
/// All of them, although it is most useful in the `preq` stage because this
/// is when the email body is received.
///
/// # Examples
///
/// ```
/// # let msg = r#"
/// X-My-Header: 250 foo
/// Subject: Unit test are cool
///
/// Hello world!
/// # "#
/// ; // .eml ends here
/// # let msg = vsmtp_mail_parser::MessageBody::try_from(msg[1..].replace("\n", "\r\n").as_str()).unwrap();
///
/// # let states = vsmtp_test::vsl::run_with_msg(
/// # |builder| Ok(builder.add_root_filter_rules(r#"
/// #{
/// postq: [
/// action "display return path" || {
/// // Will display "Return-Path: value".
/// log("info", msg::get_header_untouched("Return-Path"));
/// }
/// ],
/// }
/// # "#)?.build()), Some(msg));
/// ```
///
/// # rhai-autodocs:index:6
#[rhai_fn(return_raw)]
pub fn get_header_untouched(ncc: NativeCallContext, name: &str) -> EngineResult<rhai::Array> {
Ok(super::Impl::get_header_untouched(
&get_global!(ncc, msg),
name,
))
}
/// Add a new header **at the end** of the header list in the message.
///
/// # Args
///
/// * `header` - the name of the header to append.
/// * `value` - the value of the header to append.
///
/// # Effective smtp stage
///
/// All of them. Even though the email is not received at the current stage,
/// vsmtp stores new headers and will add them on top of the ones received once
/// the `preq` stage is reached.
///
/// # Examples
///
/// ```
/// # let msg = vsmtp_mail_parser::MessageBody::try_from(concat!(
/// "X-My-Header: 250 foo\r\n",
/// "Subject: Unit test are cool\r\n",
/// "\r\n",
/// "Hello world!\r\n",
/// # )).unwrap();
/// # let rules = r#"
/// #{
/// preq: [
/// rule "append_header" || {
/// msg::append_header("X-My-Header-2", "bar");
/// msg::append_header("X-My-Header-3", identifier("baz"));
/// }
/// ]
/// }
/// # "#;
/// # let states = vsmtp_test::vsl::run_with_msg(|builder| Ok(builder
/// # .add_root_filter_rules("#{}")?
/// # .add_domain_rules("testserver.com".parse().unwrap())
/// # .with_incoming(rules)?
/// # .with_outgoing(rules)?
/// # .with_internal(rules)?
/// # .build()
/// # .build()), Some(msg));
/// # assert_eq!(*states[&vsmtp_rule_engine::ExecutionStage::PreQ].1.inner().raw_headers(), vec![
/// # "X-My-Header: 250 foo\r\n".to_string(),
/// # "Subject: Unit test are cool\r\n".to_string(),
/// # "X-My-Header-2: bar\r\n".to_string(),
/// # "X-My-Header-3: baz\r\n".to_string(),
/// # ]);
/// ```
///
/// # rhai-autodocs:index:7
#[rhai_fn(name = "append_header", return_raw)]
pub fn append_header(ncc: NativeCallContext, header: &str, value: &str) -> EngineResult<()> {
super::Impl::append_header(&get_global!(ncc, msg), &header, &value);
Ok(())
}
#[doc(hidden)]
#[rhai_fn(name = "append_header", return_raw)]
pub fn append_header_str_obj(
ncc: NativeCallContext,
header: &str,
value: SharedObject,
) -> EngineResult<()> {
super::Impl::append_header(&get_global!(ncc, msg), &header, &value.to_string());
Ok(())
}
/// Add a new header on top all other headers in the message.
///
/// # Args
///
/// * `header` - the name of the header to prepend.
/// * `value` - the value of the header to prepend.
///
/// # Effective smtp stage
///
/// All of them. Even though the email is not received at the current stage,
/// vsmtp stores new headers and will add them on top of the ones received once
/// the `preq` stage is reached.
///
/// # Examples
///
/// ```
/// # let msg = vsmtp_mail_parser::MessageBody::try_from(concat!(
/// "X-My-Header: 250 foo\r\n",
/// "Subject: Unit test are cool\r\n",
/// "\r\n",
/// "Hello world!\r\n",
/// # )).unwrap();
/// # let rules = r#"
/// #{
/// preq: [
/// rule "prepend_header" || {
/// msg::prepend_header("X-My-Header-2", "bar");
/// msg::prepend_header("X-My-Header-3", identifier("baz"));
/// }
/// ]
/// }
/// # "#;
/// # let states = vsmtp_test::vsl::run_with_msg(|builder| Ok(builder
/// # .add_root_filter_rules("#{}")?
/// # .add_domain_rules("testserver.com".parse().unwrap())
/// # .with_incoming(rules)?
/// # .with_outgoing(rules)?
/// # .with_internal(rules)?
/// # .build()
/// # .build()), Some(msg));
/// # assert_eq!(*states[&vsmtp_rule_engine::ExecutionStage::PreQ].1.inner().raw_headers(), vec![
/// # "X-My-Header-3: baz\r\n".to_string(),
/// # "X-My-Header-2: bar\r\n".to_string(),
/// # "X-My-Header: 250 foo\r\n".to_string(),
/// # "Subject: Unit test are cool\r\n".to_string(),
/// # ]);
/// ```
///
/// # rhai-autodocs:index:8
#[rhai_fn(name = "prepend_header", return_raw)]
pub fn prepend_header(ncc: NativeCallContext, header: &str, value: &str) -> EngineResult<()> {
super::Impl::prepend_header(&get_global!(ncc, msg), header, value);
Ok(())
}
#[doc(hidden)]
#[rhai_fn(name = "prepend_header", return_raw)]
pub fn prepend_header_str_obj(
ncc: NativeCallContext,
header: &str,
value: SharedObject,
) -> EngineResult<()> {
super::Impl::prepend_header(&get_global!(ncc, msg), header, &value.to_string());
Ok(())
}
/// Replace an existing header value by a new value, or append a new header
/// to the message.
///
/// # Args
///
/// * `header` - the name of the header to set or add.
/// * `value` - the value of the header to set or add.
///
/// # Effective smtp stage
///
/// All of them. Even though the email is not received at the current stage,
/// vsmtp stores new headers and will add them on top to the ones received once
/// the `preq` stage is reached.
///
/// Be aware that if you want to set a header value from the original message,
/// you must use `set_header` in the `preq` stage and onwards.
///
/// # Examples
///
/// ```
/// # let msg = vsmtp_mail_parser::MessageBody::try_from(concat!(
/// "Subject: The initial header value\r\n",
/// "\r\n",
/// "Hello world!\r\n",
/// # )).unwrap();
/// # let rules = r#"
/// #{
/// preq: [
/// rule "set_header" || {
/// msg::set_header("Subject", "The header value has been updated");
/// msg::set_header("Subject", identifier("The header value has been updated again"));
/// state::accept(`250 ${msg::get_header("Subject")}`);
/// }
/// ]
/// }
/// # "#;
/// # let states = vsmtp_test::vsl::run_with_msg(|builder| Ok(builder
/// # .add_root_filter_rules("#{}")?
/// # .add_domain_rules("testserver.com".parse().unwrap())
/// # .with_incoming(rules)?
/// # .with_outgoing(rules)?
/// # .with_internal(rules)?
/// # .build()
/// # .build()), Some(msg));
/// # use vsmtp_common::{status::Status, Reply, ReplyCode::Code};
/// # assert_eq!(states[&vsmtp_rule_engine::ExecutionStage::PreQ].2, Status::Accept(
/// # "250 The header value has been updated again\r\n".parse().unwrap()
/// # ));
/// ```
///
/// # rhai-autodocs:index:9
#[rhai_fn(name = "set_header", return_raw)]
pub fn set_header(ncc: NativeCallContext, header: &str, value: &str) -> EngineResult<()> {
super::Impl::set_header(&get_global!(ncc, msg), header, value);
Ok(())
}
#[doc(hidden)]
#[rhai_fn(name = "set_header", return_raw)]
pub fn set_header_str_obj(
ncc: NativeCallContext,
header: &str,
value: SharedObject,
) -> EngineResult<()> {
super::Impl::set_header(&get_global!(ncc, msg), header, &value.to_string());
Ok(())
}
/// Replace an existing header name by a new value.
///
/// # Args
///
/// * `old` - the name of the header to rename.
/// * `new` - the new new of the header.
///
/// # Effective smtp stage
///
/// All of them, although it is most useful in the `preq` stage because this
/// is when the email body is received.
///
/// # Examples
///
/// ```
/// # let msg = vsmtp_mail_parser::MessageBody::try_from(concat!(
/// "Subject: The initial header value\r\n",
/// "\r\n",
/// "Hello world!\r\n",
/// # )).unwrap();
///
/// # let rules = r#"
/// #{
/// preq: [
/// rule "rename_header" || {
/// msg::rename_header("Subject", "bob");
/// if msg::has_header("Subject") { return state::deny(); }
///
/// msg::rename_header("bob", identifier("Subject"));
/// if msg::has_header("bob") { return state::deny(); }
///
/// msg::rename_header(identifier("Subject"), "foo");
/// if msg::has_header("Subject") { return state::deny(); }
///
/// msg::rename_header(identifier("foo"), identifier("Subject"));
/// if msg::has_header("foo") { return state::deny(); }
///
/// state::accept(`250 ${msg::get_header("Subject")}`);
/// }
/// ]
/// }
/// # "#;
/// # let states = vsmtp_test::vsl::run_with_msg(|builder| Ok(builder
/// # .add_root_filter_rules("#{}")?
/// # .add_domain_rules("testserver.com".parse().unwrap())
/// # .with_incoming(rules)?
/// # .with_outgoing(rules)?
/// # .with_internal(rules)?
/// # .build()
/// # .build()), Some(msg));
/// # use vsmtp_common::{status::Status, Reply, ReplyCode::Code};
/// # assert_eq!(states[&vsmtp_rule_engine::ExecutionStage::PreQ].2, Status::Accept(
/// # "250 The initial header value\r\n".parse().unwrap()
/// # ));
/// ```
///
/// # rhai-autodocs:index:10
#[rhai_fn(name = "rename_header", return_raw)]
pub fn rename_header(ncc: NativeCallContext, old: &str, new: &str) -> EngineResult<()> {
super::Impl::rename_header(&get_global!(ncc, msg), old, new);
Ok(())
}
#[doc(hidden)]
#[rhai_fn(name = "rename_header", return_raw)]
pub fn rename_header_str_obj(
ncc: NativeCallContext,
old: &str,
new: SharedObject,
) -> EngineResult<()> {
super::Impl::rename_header(&get_global!(ncc, msg), old, &new.to_string());
Ok(())
}
#[doc(hidden)]
#[rhai_fn(name = "rename_header", return_raw)]
pub fn rename_header_obj_str(
ncc: NativeCallContext,
old: SharedObject,
new: &str,
) -> EngineResult<()> {
super::Impl::rename_header(&get_global!(ncc, msg), &old.to_string(), new);
Ok(())
}
#[doc(hidden)]
#[rhai_fn(name = "rename_header", return_raw)]
pub fn rename_header_obj_obj(
ncc: NativeCallContext,
old: SharedObject,
new: SharedObject,
) -> EngineResult<()> {
super::Impl::rename_header(&get_global!(ncc, msg), &old.to_string(), &new.to_string());
Ok(())
}
/// Get a copy of the whole email as a string.
///
/// # Effective smtp stage
///
/// `preq` and onwards.
///
/// # Example
///
/// ```
/// # vsmtp_test::vsl::run(
/// # |builder| Ok(builder.add_root_filter_rules(r#"
/// #{
/// postq: [
/// action "display email content" || log("trace", `email content: ${msg::mail()}`),
/// ]
/// }
/// # "#)?.build()));
/// ```
///
/// # rhai-autodocs:index:11
#[rhai_fn(name = "mail", return_raw)]
pub fn mail(ncc: NativeCallContext) -> EngineResult<String> {
Ok(vsl_guard_ok!(get_global!(ncc, msg).read())
.inner()
.to_string())
}
/// Remove an existing header from the message.
///
/// # Args
///
/// * `header` - the name of the header to remove.
///
/// # Return
///
/// * a boolean value, true if a header has been removed, false otherwise.
///
/// # Effective smtp stage
///
/// All of them, although it is most useful in the `preq` stage because this
/// is when the email body is received.
///
/// # Examples
///
/// ```
/// # let msg = vsmtp_mail_parser::MessageBody::try_from(concat!(
/// "Subject: The initial header value\r\n",
/// "\r\n",
/// "Hello world!\r\n",
/// # )).unwrap();
/// # let rules = r#"
/// #{
/// preq: [
/// rule "remove_header" || {
/// msg::rm_header("Subject");
/// if msg::has_header("Subject") { return state::deny(); }
///
/// msg::prepend_header("Subject-2", "Rust is good");
/// msg::rm_header(identifier("Subject-2"));
///
/// msg::prepend_header("Subject-3", "Rust is good !!!!!");
///
/// state::accept(`250 ${msg::get_header("Subject-3")}`);
/// }
/// ]
/// }
/// # "#;
/// # let states = vsmtp_test::vsl::run_with_msg(|builder| Ok(builder
/// # .add_root_filter_rules("#{}")?
/// # .add_domain_rules("testserver.com".parse().unwrap())
/// # .with_incoming(rules)?
/// # .with_outgoing(rules)?
/// # .with_internal(rules)?
/// # .build()
/// # .build()), Some(msg));
/// # use vsmtp_common::{status::Status, Reply, ReplyCode::Code};
/// # assert_eq!(states[&vsmtp_rule_engine::ExecutionStage::PreQ].2, Status::Accept(
/// # "250 Rust is good !!!!!\r\n".parse().unwrap()
/// # ));
/// ```
///
/// # rhai-autodocs:index:12
#[rhai_fn(name = "rm_header", return_raw)]
pub fn remove_header(ncc: NativeCallContext, header: &str) -> EngineResult<bool> {
Ok(super::Impl::remove_header(&get_global!(ncc, msg), header))
}
#[doc(hidden)]
#[rhai_fn(name = "rm_header", return_raw)]
pub fn remove_header_obj(ncc: NativeCallContext, header: SharedObject) -> EngineResult<bool> {
Ok(super::Impl::remove_header(
&get_global!(ncc, msg),
&header.to_string(),
))
}
/// Change the sender's address in the `From` header of the message.
///
/// # Args
///
/// * `new_addr` - the new sender address to set.
///
/// # Effective smtp stage
///
/// `preq` and onwards.
///
/// # Examples
///
///```
/// # vsmtp_test::vsl::run(
/// # |builder| Ok(builder.add_root_filter_rules(r#"
/// #{
/// preq: [
/// action "replace sender" || msg::rw_mail_from("john.server@example.com"),
/// ]
/// }
/// # "#)?.build()));
/// ```
///
/// # rhai-autodocs:index:13
#[rhai_fn(name = "rw_mail_from", return_raw)]
pub fn rewrite_mail_from_message_str(
ncc: NativeCallContext,
new_addr: &str,
) -> EngineResult<()> {
super::Impl::rewrite_mail_from_message(&get_global!(ncc, msg), new_addr)
}
#[doc(hidden)]
#[rhai_fn(name = "rw_mail_from", return_raw)]
pub fn rewrite_mail_from_message_obj(
ncc: NativeCallContext,
new_addr: SharedObject,
) -> EngineResult<()> {
super::Impl::rewrite_mail_from_message(&get_global!(ncc, msg), &new_addr.to_string())
}
/// Replace a recipient by an other in the `To` header of the message.
///
/// # Args
///
/// * `old_addr` - the recipient to replace.
/// * `new_addr` - the new address to use when replacing `old_addr`.
///
/// # Effective smtp stage
///
/// `preq` and onwards.
///
/// # Examples
///
/// ```
/// # vsmtp_test::vsl::run(
/// # |builder| Ok(builder.add_root_filter_rules(r#"
/// #{
/// preq: [
/// action "rewrite recipient" || msg::rw_rcpt("john.doe@example.com", "john-mta@example.com"),
/// ]
/// }
/// # "#)?.build()));
/// ```
///
/// # rhai-autodocs:index:14
#[rhai_fn(name = "rw_rcpt", return_raw)]
pub fn rewrite_rcpt_message_str_str(
ncc: NativeCallContext,
old_addr: &str,
new_addr: &str,
) -> EngineResult<()> {
super::Impl::rewrite_rcpt_message(&get_global!(ncc, msg), old_addr, new_addr)
}
#[doc(hidden)]
#[rhai_fn(name = "rw_rcpt", return_raw)]
pub fn rewrite_rcpt_message_obj_str(
ncc: NativeCallContext,
old_addr: SharedObject,
new_addr: &str,
) -> EngineResult<()> {
super::Impl::rewrite_rcpt_message(&get_global!(ncc, msg), &old_addr.to_string(), new_addr)
}
#[doc(hidden)]
#[rhai_fn(name = "rw_rcpt", return_raw)]
pub fn rewrite_rcpt_message_str_obj(
ncc: NativeCallContext,
old_addr: &str,
new_addr: SharedObject,
) -> EngineResult<()> {
super::Impl::rewrite_rcpt_message(&get_global!(ncc, msg), old_addr, &new_addr.to_string())
}
#[doc(hidden)]
#[rhai_fn(name = "rw_rcpt", return_raw)]
pub fn rewrite_rcpt_message_obj_obj(
ncc: NativeCallContext,
old_addr: SharedObject,
new_addr: SharedObject,
) -> EngineResult<()> {
super::Impl::rewrite_rcpt_message(
&get_global!(ncc, msg),
&old_addr.to_string(),
&new_addr.to_string(),
)
}
/// Add a recipient to the `To` header of the message.
///
/// # Args
///
/// * `addr` - the recipient address to add to the `To` header.
///
/// # Effective smtp stage
///
/// `preq` and onwards.
///
/// # Examples
///
/// ```
/// # vsmtp_test::vsl::run(
/// # |builder| Ok(builder.add_root_filter_rules(r#"
/// #{
/// preq: [
/// action "update recipients" || msg::add_rcpt("john.doe@example.com"),
/// ]
/// }
/// # "#)?.build()));
/// ```
///
/// # rhai-autodocs:index:15
#[rhai_fn(name = "add_rcpt", return_raw)]
pub fn add_rcpt_message_str(ncc: NativeCallContext, new_addr: &str) -> EngineResult<()> {
super::Impl::add_rcpt_message(&get_global!(ncc, msg), new_addr)
}
#[doc(hidden)]
#[rhai_fn(name = "add_rcpt", return_raw)]
pub fn add_rcpt_message_obj(
ncc: NativeCallContext,
new_addr: SharedObject,
) -> EngineResult<()> {
super::Impl::add_rcpt_message(&get_global!(ncc, msg), &new_addr.to_string())
}
/// Remove a recipient from the `To` header of the message.
///
/// # Args
///
/// * `addr` - the recipient to remove to the `To` header.
///
/// # Effective smtp stage
///
/// `preq` and onwards.
///
/// # Examples
///
/// ```
/// # vsmtp_test::vsl::run(
/// # |builder| Ok(builder.add_root_filter_rules(r#"
/// #{
/// preq: [
/// action "update recipients" || msg::rm_rcpt("john.doe@example.com"),
/// ]
/// }
/// # "#)?.build()));
/// ```
///
/// # rhai-autodocs:index:16
#[rhai_fn(name = "rm_rcpt", return_raw)]
pub fn remove_rcpt_message_str(ncc: NativeCallContext, addr: &str) -> EngineResult<()> {
super::Impl::remove_rcpt_message(&get_global!(ncc, msg), addr)
}
#[doc(hidden)]
#[rhai_fn(name = "rm_rcpt", return_raw)]
pub fn remove_rcpt_message_obj(ncc: NativeCallContext, addr: SharedObject) -> EngineResult<()> {
super::Impl::remove_rcpt_message(&get_global!(ncc, msg), &addr.to_string())
}
}
pub(super) struct Impl;
impl Impl {
pub fn get_all_headers(message: &Message, name: &str) -> rhai::Array {
vsl_guard_ok!(message.read())
.inner()
.headers()
.into_iter()
.filter(|(key, _)| key.eq_ignore_ascii_case(name))
.map(|(_, value)| rhai::Dynamic::from(value))
.collect()
}
pub fn get_header_untouched(msg: &Message, name: &str) -> rhai::Array {
vsl_guard_ok!(msg.read())
.inner()
.headers()
.iter()
.filter(|(key, _)| key.eq_ignore_ascii_case(name))
.map(|(key, value)| rhai::Dynamic::from(format!("{key}:{value}")))
.collect::<Vec<_>>()
}
pub fn count_header<T>(message: &Message, header: &T) -> EngineResult<rhai::INT>
where
T: AsRef<str> + ?Sized,
{
vsl_guard_ok!(message.read())
.count_header(header.as_ref())
.try_into()
.map_err::<Box<rhai::EvalAltResult>, _>(|_| "header count overflowed".into())
}
pub fn append_header<T, U>(message: &Message, header: &T, value: &U)
where
T: AsRef<str> + ?Sized,
U: AsRef<str> + ?Sized,
{
vsl_guard_ok!(message.write()).append_header(header.as_ref(), value.as_ref());
}
pub fn prepend_header<T, U>(message: &Message, header: &T, value: &U)
where
T: AsRef<str> + ?Sized,
U: AsRef<str> + ?Sized,
{
vsl_guard_ok!(message.write()).prepend_header(header.as_ref(), value.as_ref());
}
pub fn set_header<T, U>(message: &Message, header: &T, value: &U)
where
T: AsRef<str> + ?Sized,
U: AsRef<str> + ?Sized,
{
vsl_guard_ok!(message.write()).set_header(header.as_ref(), value.as_ref());
}
pub fn rename_header<T, U>(message: &Message, old: &T, new: &U)
where
T: AsRef<str> + ?Sized,
U: AsRef<str> + ?Sized,
{
vsl_guard_ok!(message.write()).rename_header(old.as_ref(), new.as_ref());
}
pub fn remove_header<T>(message: &Message, header: &T) -> bool
where
T: AsRef<str> + ?Sized,
{
vsl_guard_ok!(message.write()).remove_header(header.as_ref())
}
fn rewrite_mail_from_message(message: &Message, new_addr: &str) -> EngineResult<()> {
let new_addr = vsl_conversion_ok!(
"address",
<Address as std::str::FromStr>::from_str(new_addr)
);
let mut writer = vsl_guard_ok!(message.write());
vsl_parse_ok!(writer).rewrite_mail_from(new_addr.full());
Ok(())
}
fn rewrite_rcpt_message(message: &Message, old_addr: &str, new_addr: &str) -> EngineResult<()> {
let new_addr = vsl_conversion_ok!(
"address",
<Address as std::str::FromStr>::from_str(new_addr)
);
let old_addr = vsl_conversion_ok!(
"address",
<Address as std::str::FromStr>::from_str(old_addr)
);
let mut writer = vsl_guard_ok!(message.write());
vsl_parse_ok!(writer).rewrite_rcpt(old_addr.full(), new_addr.full());
Ok(())
}
fn add_rcpt_message(message: &Message, new_addr: &str) -> EngineResult<()> {
let new_addr = vsl_conversion_ok!(
"address",
<Address as std::str::FromStr>::from_str(new_addr)
);
let mut writer = vsl_guard_ok!(message.write());
vsl_parse_ok!(writer).add_rcpt(new_addr.full());
Ok(())
}
fn remove_rcpt_message(message: &Message, addr: &str) -> EngineResult<()> {
let addr = vsl_conversion_ok!("address", <Address as std::str::FromStr>::from_str(addr));
let mut writer = vsl_guard_ok!(message.write());
vsl_parse_ok!(writer).remove_rcpt(addr.full());
Ok(())
}
}