-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathScenario.pm
1968 lines (1651 loc) · 58.4 KB
/
Scenario.pm
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
# -*- indent-tabs-mode: nil; -*-
# vim:ft=perl:et:sw=4
# Sympa - SYsteme de Multi-Postage Automatique
#
# Copyright (c) 1997, 1998, 1999 Institut Pasteur & Christophe Wolfhugel
# Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
# 2006, 2007, 2008, 2009, 2010, 2011 Comite Reseau des Universites
# Copyright (c) 2011, 2012, 2013, 2014, 2015, 2016, 2017 GIP RENATER
# Copyright 2017, 2018, 2019, 2020, 2021, 2022 The Sympa Community. See the
# AUTHORS.md file at the top-level directory of this distribution and at
# <https://github.com/sympa-community/sympa.git>.
#
# 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 2 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 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 <http://www.gnu.org/licenses/>.
package Sympa::Scenario;
use strict;
use warnings;
use English qw(-no_match_vars);
use Mail::Address;
use Net::CIDR;
use Sympa;
use Conf;
use Sympa::ConfDef;
use Sympa::Constants;
use Sympa::Database;
use Sympa::Language;
use Sympa::List;
use Sympa::Log;
use Sympa::Regexps;
use Sympa::Tools::Data;
use Sympa::Tools::File;
use Sympa::Tools::Time;
use Sympa::User;
my $log = Sympa::Log->instance;
our %all_scenarios;
my %persistent_cache;
my $picache = {};
my $picache_refresh = 10;
#FIXME: should be taken from Sympa::ListDef.
my %list_ppath_maps = (
visibility => 'visibility',
send => 'send',
info => 'info',
subscribe => 'subscribe',
add => 'add',
unsubscribe => 'unsubscribe',
del => 'del',
invite => 'invite',
remind => 'remind',
review => 'review',
d_read => 'shared_doc.d_read',
d_edit => 'shared_doc.d_edit',
archive_web_access => 'archive.web_access',
archive_mail_access => 'archive.mail_access',
tracking => 'tracking.tracking',
);
#FIXME: should be taken from Sympa::ConfDef.
my %domain_ppath_maps = (
create_list => 'create_list',
family_signoff => 'family_signoff',
global_remind => 'global_remind',
move_user => 'move_user',
automatic_list_creation => 'automatic_list_creation',
spam_status => 'spam_status',
);
# For compatibility to obsoleted use of parameter name instead of function.
my %compat_function_maps = (
'shared_doc.d_read' => 'd_read',
'shared_doc.d_edit' => 'd_edit',
'archive.access' => 'archive_mail_access', # obsoleted
'web_archive.access' => 'archive_web_access', # obsoleted
'mail_access' => 'archive_mail_access', # mislead
'web_access' => 'archive_web_access', # mislead
'archive.mail_access' => 'archive_mail_access',
'archive.web_access' => 'archive_web_access',
'tracking.tracking' => 'tracking',
);
## Creates a new object
## Supported parameters : function, robot, name, directory, file_path, options
## Output object has the following entries : name, file_path, rules, date,
## title, struct, data
sub new {
$log->syslog('debug2', '(%s, %s, %s, ...)', @_);
my $class = shift;
my $that = shift || $Conf::Conf{'domain'}; # List or domain
my $function = shift;
my %options = @_;
my $scenario_name_re = Sympa::Regexps::scenario_name();
# Compatibility for obsoleted use of parameter names.
$function = $compat_function_maps{$function} || $function;
die 'bug in logic. Ask developer'
unless defined $function and $function =~ /\A$scenario_name_re\z/;
# Determine parameter to get the name of scenario.
# 'include' and 'topics_visibility' functions are special: They don't
# have corresponding list/domain parameters.
my $ppath =
(ref $that eq 'Sympa::List')
? $list_ppath_maps{$function}
: $domain_ppath_maps{$function};
unless ($function eq 'include'
or (ref $that ne 'Sympa::List' and $function eq 'topics_visibility')
or $ppath) {
$log->syslog('err', 'Unknown scenario function "%s"', $function);
return undef;
}
my $name;
if ($options{name}) {
$name = $options{name};
} elsif ($function eq 'include') {
# {name} option is mandatory.
die 'bug in logic. Ask developer';
} elsif (ref $that eq 'Sympa::List') {
#FIXME: Use Sympa::List::Config.
if ($ppath =~ /[.]/) {
my ($pname, $key) = split /[.]/, $ppath, 2;
$name = ($that->{'admin'}{$pname}{$key} || {})->{name}
if $that->{'admin'}{$pname};
} else {
$name = ($that->{'admin'}{$ppath} || {})->{name};
}
} elsif ($function eq 'topics_visibility') {
# {name} option is mandatory.
die 'bug in logic. Ask developer';
} else {
$name = Conf::get_robot_conf($that, $ppath);
}
unless (
defined $name
and ( $function eq 'include' and $name =~ m{\A[^/]+\z}
or $name =~ /\A$scenario_name_re\z/)
) {
$log->syslog(
'err',
'Unknown or undefined scenario function "%s", scenario name "%s"',
$function,
$name
);
return undef;
}
my $data;
my $file_path = Sympa::search_fullpath(
$that,
$function . '.' . $name,
subdir => 'scenari'
);
if ($file_path) {
# Load the scenario if previously loaded in memory.
if ($all_scenarios{$file_path}
and ($options{dont_reload_scenario}
or Sympa::Tools::File::get_mtime($file_path) <=
$all_scenarios{$file_path}->{date})
) {
return bless {
context => $that,
function => $function,
name => $name,
file_path => $file_path,
_scenario => $all_scenarios{$file_path}
} => $class;
}
# Get the data from file.
if (open my $ifh, '<', $file_path) {
$data = do { local $RS; <$ifh> };
close $ifh;
} else {
$log->syslog('err', 'Failed to open scenario file "%s": %m',
$file_path);
return undef;
}
} elsif ($function eq 'include') {
# include.xx not found will not raise an error message.
return undef;
} else {
if ($all_scenarios{"ERROR/$function.$name"}) {
return bless {
context => $that,
function => $function,
name => $name,
file_path => 'ERROR',
_scenario => $all_scenarios{"ERROR/$function.$name"}
} => $class;
}
$log->syslog('err', 'Unable to find scenario file "%s.%s"',
$function, $name);
# Default rule is rejecting always.
$data = 'true() smtp -> reject';
}
my $parsed = Sympa::Scenario::compile(
$that, $data,
function => $function,
file_path => $file_path
);
# Keep the scenario in memory.
$all_scenarios{$file_path || "ERROR/$function.$name"} = $parsed;
return bless {
context => $that,
function => $function,
name => $name,
file_path => ($file_path || 'ERROR'),
_scenario => $parsed,
} => $class;
}
sub compile {
my $that = shift;
my $data = shift;
my %options = @_;
my $function = $options{function};
my $file_path = $options{file_path};
my $parsed = _parse_scenario($data, $file_path);
if ($parsed and not($function and $function eq 'include')) {
$parsed->{compiled} = _compile_scenario($that, $function, $parsed);
if ($parsed->{compiled}) {
$parsed->{sub} = eval $parsed->{compiled};
# Bad syntax in compiled Perl code.
$log->syslog('err', '%s: %s\n', ($file_path || '(data)'),
$EVAL_ERROR)
unless ref $parsed->{sub} eq 'CODE';
}
}
return $parsed;
}
# Parse scenario rules. On failure, returns hash with empty rules.
sub _parse_scenario {
$log->syslog('debug3', '(%s, %s)', @_);
my $data = shift;
my $file_path = shift;
my (%title, @rules);
my @lines = split /\r\n|\r|\n/, $data;
my $lineno = 0;
foreach my $line (@lines) {
$lineno++;
next if $line =~ /^\s*\w+\s*$/; # skip paragraph name
$line =~ s/\#.*$//; # remove comments
next if $line =~ /^\s*$/; # skip empty lines
if ($line =~ /^\s*title\.gettext\s+(.*)\s*$/i) {
$title{gettext} = $1;
next;
} elsif ($line =~ /^\s*title\.(\S+)\s+(.*)\s*$/i) {
my ($lang, $title) = ($1, $2);
# canonicalize lang if possible.
$lang = Sympa::Language::canonic_lang($lang) || $lang;
$title{$lang} = $title;
next;
} elsif ($line =~ /^\s*title\s+(.*)\s*$/i) {
$title{default} = $1;
next;
}
if ($line =~ /\s*(include\s*\(?\'?(.*)\'?\)?)\s*$/i) {
push @rules, {condition => $1, lineno => $lineno};
} elsif ($line =~
/^\s*(.*?)\s+((\s*(md5|pgp|smtp|smime|dkim)\s*,?)*)\s*->\s*(.*)\s*$/gi
) {
my ($condition, $auth_methods, $action) = ($1, $2 || 'smtp', $5);
# 'dkim' became a synonym of 'smtp' on Sympa 6.2.71b.
my @auth_methods = sort keys %{
{ map { ($_ eq 'dkim') ? (smtp => 1) : $_ ? ($_ => 1) : () }
split(/[\s,]+/, $auth_methods)
}
};
push @rules,
{
condition => $condition,
auth_method => [@auth_methods],
action => $action,
lineno => $lineno,
};
} else {
$log->syslog(
'err',
'Error parsing %s line %s: "%s"',
$file_path || '(file)',
$lineno, $line
);
@rules = ();
last;
}
}
my $purely_closed =
not
grep { not($_->{condition} eq 'true' and $_->{action} =~ /reject/) }
@rules;
return {
data => $data,
title => {%title},
rules => [@rules],
purely_closed => $purely_closed,
# Keep track of the current time ; used later to reload scenario files
# when they changed on disk
date => ($file_path ? time : 0),
};
}
sub to_string {
shift->{_scenario}{data};
}
sub request_action {
my $that = shift;
my $function = shift;
my $auth_method = shift;
my $context = shift;
my %options = @_;
my $self = Sympa::Scenario->new($that, $function, %options);
unless ($self) {
$log->syslog('err', 'Failed to load scenario for "%s"', $function);
return undef;
}
return $self->authz($auth_method, $context, %options);
}
# Old name: Sympa::Scenario::request_action().
sub authz {
$log->syslog('debug2', '(%s, %s, %s, ...)', @_);
my $self = shift;
my $auth_method = shift;
my $context = shift;
my %options = @_;
my $that = $self->{context};
my $function = $self->{function};
# Pending/closed lists => send/visibility are closed.
if ( ref $that eq 'Sympa::List'
and not($that->{'admin'}{'status'} eq 'open')
and grep { $function eq $_ } qw(send visibility)) {
$log->syslog('debug3', '%s rejected reason list not open', $function);
return {
action => 'reject',
reason => 'list-no-open',
auth_method => '',
condition => '',
};
}
# Check that authorization method is one of those known by Sympa.
unless ($auth_method =~ /^(smtp|md5|pgp|smime|dkim)/) { #FIXME: regex '$'
$log->syslog('info', 'Unknown auth method %s', $auth_method);
return {
action => 'reject',
reason => 'unknown-auth-method',
auth_method => $auth_method,
condition => '',
};
}
# 'dkim' auth method was deprecated on Sympa 6.2.71b.
# Now it is a synonym of 'smtp'.
$auth_method = 'smtp' if $auth_method eq 'dkim';
# Defining default values for parameters.
$context->{'sender'} ||= 'nobody';
$context->{'email'} ||= $context->{'sender'};
$context->{'remote_host'} ||= 'unknown_host';
$context->{'execution_date'} //= time;
if (ref $that eq 'Sympa::List') {
foreach my $var (@{$that->{'admin'}{'custom_vars'} || []}) {
$context->{'custom_vars'}{$var->{'name'}} = $var->{'value'};
}
$context->{listname} = $that->{'name'};
$context->{domain} = $that->{'domain'};
# Compat.<6.2.32
$context->{host} = $that->{'domain'};
} else {
$context->{domain} = Conf::get_robot_conf($that || '*', 'domain');
}
my $sub = ($self->{_scenario} || {})->{sub};
my $result = eval { $sub->($that, $context, $auth_method) }
if ref $sub eq 'CODE';
# Cope with errors.
unless ($result) {
unless ($sub) {
$result = {reason => 'not-compiled'};
} elsif (ref $EVAL_ERROR eq 'HASH') {
$result = $EVAL_ERROR;
} else {
# Fatal error will be logged but not be exposed.
$log->syslog('err', 'Error in scenario %s, context %s: (%s)',
$self, $that, $EVAL_ERROR || 'unknown');
$result = {};
}
$result->{action} ||= 'reject';
$result->{reason} ||= 'error-performing-condition';
$result->{auth_method} ||= $auth_method;
$result->{condition} ||= 'default';
if ($result->{reason} eq 'not-compiled') {
$log->syslog('info', '%s: Not compiled, reject', $self);
} elsif ($result->{reason} eq 'no-rule-match') {
$log->syslog('info', '%s: No rule match, reject', $self);
} else {
$log->syslog('info', 'Error in scenario %s, context %s: (%s)',
$self, $that, $result->{reason});
Sympa::send_notify_to_listmaster($that,
'error_performing_condition', {error => $result->{reason}})
unless $options{debug};
}
return $result;
}
my %action = %$result;
# Check syntax of returned action
if ( $options{debug}
or $action{action} =~
/^(do_it|reject|request_auth|owner|editor|editorkey|listmaster|ham|spam|unsure)/
) {
return {%action, auth_method => $auth_method,};
} else {
$log->syslog('err', 'Matched unknown action "%s" in scenario',
$action{action});
return {
action => 'reject',
reason => 'unknown-action',
auth_method => $auth_method,
};
}
}
# Old name: Sympa::Scenario::_parse_action().
sub _compile_action {
my $action = shift;
my $condition = shift;
my %action;
$action{condition} = $condition if $condition;
## reject : get parameters
if ($action =~ /^(ham|spam|unsure)/) {
$action = $1;
}
if ($action =~ /^reject(\((.+)\))?(\s?,\s?(quiet))?/) {
if ($4) {
$action = 'reject,quiet';
} else {
$action = 'reject';
}
my @param = split /,/, $2 if defined $2;
foreach my $p (@param) {
if ($p =~ /^reason=\'?(\w+)\'?/) {
$action{reason} = $1;
next;
} elsif ($p =~ /^tt2=\'?(\w+)\'?/) {
$action{tt2} = $1;
next;
}
if ($p =~ /^\'?([^'=]+)\'?/) {
$action{tt2} = $1;
# keeping existing only, not merging with reject
# parameters in scenarios
last;
}
}
}
$action{action} = $action;
return _compile_hashref({%action});
}
## check if email respect some condition
# Old name: Sympa::Scenario::verify().
# Deprecated: No longer used.
#sub _verify;
# Old names: (part of) Sympa::Scenario::authz().
sub _compile_scenario {
$log->syslog('debug2', '(%s, %s, ...)', @_);
my $that = shift;
my $function = shift;
my $parsed = shift;
my @rules = @{$parsed->{rules} || []};
# Include include.<function>.header if found.
my $include_scenario =
Sympa::Scenario->new($that, 'include', name => $function . '.header')
if $function;
if ($include_scenario) {
# Add rules at the beginning.
unshift @rules, @{$include_scenario->{_scenario}{rules}};
}
# Look for 'include' directives amongst rules first.
foreach my $index (0 .. $#rules) {
if ($rules[$index]{'condition'} =~
/^\s*include\s*\(?\'?([\w\.]+)\'?\)?\s*$/i) {
my $include_file = $1;
my $include_scenario =
Sympa::Scenario->new($that, 'include', name => $include_file);
if ($include_scenario) {
# Replace the include directive with included rules.
splice @rules, $index, 1,
@{$include_scenario->{_scenario}{rules}};
}
}
}
## Include a Blocklist rules if configured for this action
if ($function and $Conf::Conf{'blocklist'}{$function}) {
## Add rules at the beginning of the array
unshift @rules,
{
'condition' => "search('blocklist.txt',[sender])",
'action' => 'reject,quiet',
'auth_method' => ['smtp', 'dkim', 'md5', 'pgp', 'smime'],
};
}
my @codes;
my %required;
foreach my $rule (@rules) {
$log->syslog(
'debug3',
'Verify rule %s, auth %s, action %s',
$rule->{'condition'},
join(',', @{$rule->{'auth_method'} || []}),
$rule->{'action'}
);
my ($code, @required) = _compile_rule($rule);
return undef unless defined $code; # Bad syntax.
push @codes, $code;
%required = (%required, map { ($_ => 1) } @required);
}
my $required = join "\n", map {
my $req;
if ($_ eq 'list_object') {
$req =
'die "No list context" unless ref $that eq \'Sympa::List\';';
} elsif ($_ eq 'message') {
$req = '$context->{message} ||= Sympa::Message->new("\n");';
} else {
$req = sprintf '$context->{\'%s\'} //= \'\';', $_;
}
" $req";
} sort keys %required;
return sprintf(<<'EOF', $required, join '', @codes);
sub {
my $that = shift;
my $context = shift;
my $auth_method = shift;
%s
%s
die {reason => 'no-rule-match'};
}
EOF
}
sub _compile_rule {
my $rule = shift;
my ($cond, @required) = _compile_condition($rule);
return unless defined $cond and length $cond;
my $auth_methods = join ' ', sort @{$rule->{'auth_method'} || []};
my $result = _compile_action($rule->{action}, $rule->{condition});
if (1 == scalar @{$rule->{'auth_method'} || []}) {
return (sprintf(<<'EOF', $auth_methods, $result, $cond), @required);
if ($auth_method eq '%s') {
return %s if %s;
}
EOF
} elsif ($auth_methods eq join(' ', sort qw(smtp md5 smime))) {
return (sprintf(<<'EOF', $result, $cond), @required);
return %s if %s;
EOF
} else {
return (sprintf(<<'EOF', $auth_methods, $result, $cond), @required);
if (grep {$auth_method eq $_} qw(%s)) {
return %s if %s;
}
EOF
}
}
sub _compile_condition {
my $rule = shift;
my $condition = $rule->{condition};
unless ($condition =~
/(\!)?\s*(true|is_listmaster|verify_netmask|is_editor|is_owner|is_subscriber|less_than|match|equal|message|older|newer|all|search|customcondition\:\:\w+)\s*\(\s*(.*)\s*\)\s*/i
) {
$log->syslog('err', 'Error rule syntaxe: unknown condition %s',
$condition);
return undef;
}
my $negation = ($1 and $1 eq '!') ? '!' : '';
my $condition_key = lc $2;
my $arguments = $3;
## The expression for regexp is tricky because we don't allow the '/'
## character (that indicates the end of the regexp
## but we allow any number of \/ escape sequence)
my @args;
my %required_keys;
pos $arguments = 0;
while (
$arguments =~ m{
\G\s*(
(\[\w+(\-\>[\w\-]+)?\](\[[-+]?\d+\])?)
|
([\w\-\.]+)
|
'[^,)]*'
|
"[^,)]*"
|
/([^/]*((\\/)*[^/]+))*/
|
(\w+)\.ldap
|
(\w+)\.sql
)\s*,?
}cgx
) {
my $value = $1;
if ($value =~ m{\A/(.+)/\z}) {
my $re = $1;
# Fix orphan "'" and "\".
$re =~ s{(\\.|.)}{($1 eq "'" or $1 eq "\\")? "\\$1" : $1}eg;
# regexp w/o interpolates
unless (
defined
do { local $SIG{__DIE__}; eval sprintf "qr'%s'i", $re }
) {
$log->syslog('err', 'Bad regexp /%s/: %s', $re, $EVAL_ERROR);
return undef;
}
$value = sprintf 'Sympa::Scenario::safe_qr(\'%s\', $context)',
$re;
} elsif ($value =~ /\[custom_vars\-\>([\w\-]+)\]/i) {
# Custom vars
$value = sprintf '$context->{custom_vars}{\'%s\'}', $1;
} elsif ($value =~ /\[family\-\>([\w\-]+)\]/i) {
# Family vars
$value = sprintf '$context->{family}{\'%s\'}', $1;
} elsif ($value =~ /\[conf\-\>([\w\-]+)\]/i) {
# Config param
my $conf_key = $1;
# Compat. < 6.2.32
$conf_key = 'domain' if $conf_key and $conf_key eq 'host';
if (grep { $_->{'name'} and $_->{'name'} eq $conf_key }
@Sympa::ConfDef::params) {
#FIXME: Old or obsoleted names of parameters
$value =
sprintf
'Conf::get_robot_conf(((ref $that eq \'Sympa::List\') ? $that->{domain} : $that), \'%s\')',
$conf_key;
} else {
# a condition related to a undefined context variable is
# always false
$log->syslog('err', '%s: Unknown key for [conf->%s]',
$conf_key);
$value = 'undef()';
}
} elsif ($value =~ /\[list\-\>([\w\-]+)\]/i) {
# List param
my $param = $1;
$required_keys{list_object} = 1;
if ($param eq 'name') {
$value = '$that->{name}';
} elsif ($param eq 'total') {
$value = '$that->get_total';
} elsif ($param eq 'address') {
$value = 'Sympa::get_address($that)';
} else {
my $pinfo = {%Sympa::ListDef::pinfo}; #FIXME
my $canon_param = $param;
if (exists $pinfo->{$param}) {
my $alias = $pinfo->{$param}{'obsolete'};
if ($alias and exists $pinfo->{$alias}) {
$canon_param = $alias;
}
}
if ( exists $pinfo->{$canon_param}
and ref $pinfo->{$canon_param}{format} ne 'HASH'
and $pinfo->{$canon_param}{occurrence} !~ /n$/) {
$value = sprintf '$that->{admin}{\'%s\'}', $canon_param;
} else {
$log->syslog('err',
'Unknown list parameter %s in rule %s',
$value, $condition);
return undef;
}
}
} elsif ($value =~ /\[env\-\>([\w\-]+)\]/i) {
my $env = $1;
$value = sprintf '$ENV{\'%s\'}', $env;
} elsif ($value =~ /\[user\-\>([\w\-]+)\]/i) {
# Sender's user/subscriber attributes (if subscriber)
my $key = $1;
$value =
sprintf
'($context->{user} || Sympa::User->new($context->{sender}))->{\'%s\'}',
$key;
} elsif ($value =~ /\[user_attributes\-\>([\w\-]+)\]/i) {
my $key = $1;
$value =
sprintf
'($context->{user} || Sympa::User->new($context->{sender}))->{attributes}{\'%s\'}',
$key;
} elsif ($value =~ /\[subscriber\-\>([\w\-]+)\]/i) {
my $key = $1;
$value =
sprintf
'($context->{subscriber} || $that->get_list_memner($context->{sender}) || {})->{\'%s\'}',
$key;
} elsif ($value =~
/\[(msg_header|header)\-\>([\w\-]+)\](?:\[([-+]?\d+)\])?/i) {
## SMTP header field.
## "[msg_header->field]" returns arrayref of field values,
## preserving order. "[msg_header->field][index]" returns one
## field value.
my $field_name = $2;
my $index = (defined $3) ? $3 + 0 : undef;
## Defaulting empty or missing fields to '', so that we can
## test their value in Scenario, considering that, for an
## incoming message, a missing field is equivalent to an empty
## field : the information it is supposed to contain isn't
## available.
if (defined $index) {
$value =
sprintf
'do { my @h = $context->{message}->get_header(\'%s\'); $h[%s] // \'\' }',
$field_name, $index;
} else {
$value =
sprintf
'do { my @h = $context->{message}->get_header(\'%s\'); @h ? [@h] : [\'\'] }',
$field_name;
}
$required_keys{message} = 1;
} elsif ($value =~ /\[msg_body\]/i) {
$value = '$context->{message}->body_as_string';
$value =
sprintf
'((0 == index lc($context->{message}->as_entity->effective_type || "text"), "text") ? %s : undef)',
$value;
$required_keys{message} = 1;
} elsif ($value =~ /\[msg_part\-\>body\]/i) {
#FIXME:Should be recurcive...
$value =
'[map {$_->bodyhandle->as_string} grep { defined $_->bodyhandle and 0 == index ($_->effective_type || "text"), "text" } $context->{message}->as_entity->parts]';
$required_keys{message} = 1;
} elsif ($value =~ /\[msg_part\-\>type\]/i) {
$value =
'[map {$_->effective_type} $context->{message}->as_entity->parts]';
$required_keys{message} = 1;
} elsif ($value =~ /\[msg\-\>(\w+)\]/i) {
my $key = $1;
$value =
sprintf
'(exists $context->{message}{%s} ? $context->{message}{%s} : undef)',
$key, $key;
$required_keys{message} = 1;
} elsif ($value =~ /\[is_bcc\]/i) {
$value =
'Sympa::Scenario::message_is_bcc($that, $context->{message})';
$required_keys{list_object} = 1;
$required_keys{message} = 1;
} elsif ($value =~ /\[msg_encrypted\]/i) {
$value =
'Sympa::Scenario::message_encrypted($context->{message})';
$required_keys{message} = 1;
} elsif ($value =~ /\[(topic(?:_\w+)?)\]/i) {
# Useful only with send scenario.
my $key = $1;
$value = sprintf '$context->{%s}', $key;
$required_keys{$key} = 1;
$required_keys{message} = 1;
} elsif ($value =~ /\[current_date\]/i) {
$value = 'time()';
} elsif ($value =~ /\[listname\]/i) {
# Context should be a List from which value will be taken.
$value = '$that->{name}';
$required_keys{list_object} = 1;
} elsif ($value =~ /\[(\w+)\]/i) {
my $key = $1;
$value = sprintf '$context->{%s}', $key;
$required_keys{$key} = 1;
} elsif ($value =~ /^'(.*)'$/ || $value =~ /^"(.*)"$/) {
# Quoted string
my $str = $1;
$str =~ s{(\\.|.)}{($1 eq "'" or $1 eq "\\")? "\\\'" : $1}eg;
$value = sprintf "'%s'", $str;
} else {
# Texts with unknown format may be treated as the string constants
# for compatibility to loose parsing with earlier ver (<=6.2.48).
my $str = $value;
$str =~ s/([\\\'])/\\$1/g;
$value = sprintf "'%s'", $str;
}
push(@args, $value);
}
my $term = _compile_condition_term($rule, $condition_key, @args);
return unless $term;
return ("$negation$term", sort keys %required_keys);
}
sub _compile_condition_term {
my $rule = shift;
my $condition_key = shift;
my @args = @_;
# Getting rid of spaces.
$condition_key =~ s/^\s*//g;
$condition_key =~ s/\s*$//g;
if ($condition_key =~ /^(true|all)$/i) {
# condition that require 0 argument
if (@args) {
$log->syslog(
'err',
'Syntax error: Incorrect number of argument or incorrect argument syntax in %s',
$condition_key
);
return undef;
}
return '1';
} elsif ($condition_key =~ /^(is_listmaster|verify_netmask)$/) {
# condition that require 1 argument
unless (scalar @args == 1) {
$log->syslog('err',
'Syntax error: Incorrect argument number for condition %s',
$condition_key);
return undef;
}
} elsif ($condition_key =~ /^search$/o) {
# condition that require 1 or 2 args (search : historical reasons)
unless (scalar @args == 1 or scalar @args == 2) {
$log->syslog('err',
'Syntax error: Incorrect argument number for condition %s',
$condition_key);
return undef;
}
# We could search in the family if we got ref on Sympa::Family object.
return sprintf 'Sympa::Scenario::do_search($that, $context, %s)',
join ', ', @args;
} elsif (
$condition_key =~
# condition that require 2 args
/^(is_owner|is_editor|is_subscriber|less_than|match|equal|message|newer|older)$/o
) {
unless (scalar @args == 2) {
$log->syslog(
'err',
'Syntax error: Incorrect argument number (%d instead of %d) for condition %s',
scalar(@args),
2,
$condition_key
);
return undef;
}
if ($condition_key =~ /\A(is_owner|is_editor|is_subscriber)\z/) {
# Interpret '[listname]' as $that.
$args[0] = '$that' if $args[0] eq '$that->{name}';
}
} elsif ($condition_key =~ /^customcondition::(\w+)$/) {
my $mod = $1;
return sprintf 'do_verify_custom($that, %s, \'%s\', %s)',
_compile_hashref($rule), $mod, join ', ', @args;
} else {
$log->syslog('err', 'Syntax error: Unknown condition %s',
$condition_key);
return undef;
}
return sprintf 'Sympa::Scenario::do_%s($that, \'%s\', %s)',
$condition_key, $condition_key, join ', ', @args;
}
sub _compile_hashref {
my $hashref = shift;
return '{' . join(
', ',
map {
my ($k, $v) = ($_, $hashref->{$_});
if (ref $v eq 'ARRAY') {
$v = join(
', ',
map {
my $i = $_;
$i =~ s/([\\\'])/\\$1/g;
"'$i'";
} @$v
);
sprintf '%s => [%s]', $k, $v;
} else {
$v =~ s/([\\\'])/\\$1/g;
sprintf "%s => '%s'", $k, $v;
}
} sort keys %$hashref
) . '}';
}
sub message_is_bcc {
my $that = shift;
my $message = shift;
return '' unless $message;
#FIXME: need more accurate test.
return (
0 <= index(
lc join(', ',
$message->get_header('To'),
$message->get_header('Cc')),
lc $that->{'name'}
)
) ? 0 : 1;
}
sub message_encrypted {
my $message = shift;
return ($message and $message->{smime_crypted}) ? 'smime' : '';
}
sub safe_qr {
my $re = shift;
my $context = shift;
my $domain = $context->{domain};
$domain =~ s/[.]/[.]/g;
$re =~ s/[[](domain|host)[]]/$domain/g;
return do { local $SIG{__DIE__}; eval sprintf "qr'%s'i", $re };
}
##### condition : true
##### condition is_listmaster
sub do_is_listmaster {
my $that = shift;
my $condition_key = shift;
my @args = @_;
return 0 if not ref $args[0] and $args[0] eq 'nobody';