lib/Mail/Decency/ContentFilter.pm

filter: Statementstmt 18.4% 93 / 505 Branchbran 0.0% 0 / 198 Conditioncond 0.0% 0 / 146 MC/DCmcdc 0.0% 0 / 83 Subroutinesub 50.0% 21 / 42 Podpod 93.7% 15 / 16 totaltotal 13.0% 129 / 990 CC 163 SCAR 64.6
CC
163
Cov
11%
init
1260.0
handle
1190.0
train
1186.0
CRAP 640.7
« lib/Mail/Decency/Core/Stats.pm ↑ Summary lib/Mail/Decency/Policy/Throttle.pm »
1 package Mail::Decency::ContentFilter;
2  
3 9 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 9 extends qw/
5 Mail::Decency::Core::Server
6 /;
7  
8 9 with qw/
9 Mail::Decency::Core::Stats
10 Mail::Decency::Core::DatabaseCreate
11 Mail::Decency::Core::Excludes
12 /;
13  
14 9 ▶use version 0.74; our $VERSION = qv( "v0.1.6" );
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 9 ▶use feature qw/ switch /;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 9 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 9 ▶use Scalar::Util qw/ weaken blessed /;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 9 ▶use YAML;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 9 ▶use MIME::Parser;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 9 ▶use MIME::Lite;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 9 ▶use IO::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 9 ▶use Net::SMTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 9 ▶use File::Path qw/ make_path /;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 9 ▶use File::Copy qw/ copy move /;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 9 ▶use File::Temp qw/ tempfile /;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 9 ▶use Cwd qw/ abs_path /;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 9 ▶use Crypt::OpenSSL::RSA;
Subroutine BEGIN: called CC=1 SCAR=0.0
30 9 ▶use Time::HiRes qw/ tv_interval gettimeofday /;
Subroutine BEGIN: called CC=1 SCAR=0.0
31  
32  
33 9 ▶use Mail::Decency::ContentFilter::Core::Constants;
Subroutine BEGIN: called CC=1 SCAR=0.0
34 9 ▶use Mail::Decency::Core::SessionItem::ContentFilter;
Subroutine BEGIN: called CC=1 SCAR=0.0
35 9 ▶use Mail::Decency::Core::POEForking::SMTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 9 ▶use Mail::Decency::Core::Exception;
Subroutine BEGIN: called CC=1 SCAR=0.0
37  
38 =head1 NAME
39  
40 Mail::Decency::ContentFilter
41  
42 =head1 SYNOPSIS
43  
44 use Mail::Decency::ContentFilter;
45
46 my $content_filter = Mail::Decency::ContentFilter->new( {
47 config => '/etc/decency/content-filter.yml'
48 } );
49
50 $content_filter->run;
51  
52 =head1 DESCRIPTION
53  
54 Postfix:Decency::ContentFilter implements multiple content filter
55  
56 =head1 POSTFIX
57  
58 You have to edit two files: master.cf and main.cf in /etc/postfix
59  
60  
61 =head2 master.cf
62  
63 Add the following to the end of your master.cf file:
64  
65 # the decency server itself
66 decency unix - - n - 4 smtp
67 -o smtp_send_xforward_command=yes
68 -o disable_dns_lookups=yes
69 -o max_use=20
70 -o smtp_send_xforward_command=yes
71 -o disable_mime_output_conversion=yes
72 -o smtp_destination_recipient_limit=1
73
74 # re-inject mails from decency for delivery
75 127.0.0.1:10250 inet n - - - - smtpd
76 -o content_filter=
77 -o receive_override_options=no_unknown_recipient_checks,no_header_body_checks,no_milters
78 -o smtpd_helo_restrictions=
79 -o smtpd_client_restrictions=
80 -o smtpd_sender_restrictions=
81 -o smtpd_recipient_restrictions=permit_mynetworks,reject_unauth_destination,permit
82 -o mynetworks=127.0.0.0/8
83 -o smtpd_authorized_xforward_hosts=127.0.0.0/8
84  
85  
86 =head2 main.cf
87  
88 There are two possible ways you can include this content filter into postfix. The first is via content_filter, the second via check_*_access, eg check_client_access.
89  
90 =over
91  
92 =item * content_filter
93  
94 The advantage: it is easy. The disadvantage: all mails (incoming, outgoing) will be filtered. In a one-mailserver-for-all configuration this might be ugly.
95  
96 # main.cf
97 content_filter = decency:127.0.0.1:16000
98  
99 =item * Via check_*_access
100  
101 And example using pcre on all mails would be:
102  
103 # main.cf
104 smtpd_client_restrictions =
105 # ...
106 check_client_access = pcre:/etc/postfix/decency-filter, reject
107 # ...
108  
109 Then in the /etc/postfix/decency-filter file:
110  
111 # /path/to/access
112 /./ FILTER decency:127.0.0.1:16000
113  
114  
115 =head1 CONFIG
116  
117 Provide either a hashref or a YAML file.
118  
119 Example:
120  
121 ---
122
123 spool_dir: /var/spool/decency
124
125 accept_scoring: 1
126 policy_verify_key: sign.pub
127
128 notification_from: 'Postmaster <postmaster@localhost>'
129
130 enable_stats: 1
131
132
133 include:
134 - logging.yml
135 - database.yml
136 - cache.yml
137
138 server:
139 host: 127.0.0.1
140 port: 16000
141 instances: 3
142
143 reinject:
144 host: 127.0.0.1
145 port: 10250
146
147 spam:
148 behavior: scoring
149 threshold: -50
150 handle: tag
151 noisy_headers: 1
152 spam_subject_prefix: "SPAM:"
153
154 # for handle: bounce or delete:
155 #notify_recipient: 1
156 #recipient_template: 'templates/spam-recipient-notify.tmpl'
157 #recipient_subject: 'Spam detection notification'
158
159 virus:
160 handle: bounce
161
162 # for handle: bounce, delete or quarantine
163 notify_sender: 1
164 notify_recipient: 1
165 sender_template: 'templates/virus-sender-notify.tmpl'
166 sender_subject: 'Virus detection notification'
167 recipient_template: 'templates/virus-recipient-notify.tmpl'
168 recipient_subject: 'Virus detection notification'
169
170
171 filters:
172 #- MimeAttribs: "content-filter/mime-attribs.yml"
173 - DKIM: "content-filter/dkim.yml"
174 # - ClamAV: content-filter/clamav.yml
175 - Bogofilter: content-filter/bogofilter.yml
176 #- DSPAM: content-filter/dspam.yml
177 - CRM114: content-filter/crm114.yml
178 - Razor: content-filter/razor.yml
179 - HoneyCollector: content-filter/honey-collector.yml
180 # -
181 # SpamAssassin:
182 # disable: 0
183 # default_user:
184 # weight_translate:
185 # 1: -100
186 # -2: 0
187 # -3: 100
188 - Archive: content-filter/archive.yml
189
190  
191  
192 =head1 CLASS ATTRIBUTES
193  
194  
195 =head2 spool_dir : Str
196  
197 The directory where to save received mails before filtering
198  
199 =cut
200  
201 9 has spool_dir => ( is => 'rw', isa => 'Str' );
202  
203 =head2 temp_dir : Str
204  
205 Holds temp files for modules
206  
207 =cut
208  
209 9 has temp_dir => ( is => 'rw', isa => 'Str' );
210  
211 =head2 queue_dir : Str
212  
213 Holds queued mails (currently working on)
214  
215 =cut
216  
217 9 has queue_dir => ( is => 'rw', isa => 'Str' );
218  
219 =head2 mime_output_dir : Str
220  
221 Directory for temporary mime output .. required by MIME::Parser
222  
223 Defaults to spool_dir/mime
224  
225 =cut
226  
227 9 has mime_output_dir => ( is => 'rw', isa => 'Str' );
228  
229 =head2 reinject_failure_dir : Str
230  
231 Directory for reinjection failures
232  
233 Defaults to spool_dir/failure
234  
235 =cut
236  
237 9 has reinject_failure_dir => ( is => 'rw', isa => 'Str' );
238  
239 =head2 quarantine_dir : Str
240  
241 Directory for quarantined mails (virus, spam)
242  
243 Defaults to spool_dir/quarantine
244  
245 =cut
246  
247 9 has quarantine_dir => ( is => 'rw', isa => 'Str' );
248  
249 =head2 spam_*
250  
251 There is either spam scoring, strict or keep.
252  
253 Keep account on positive or negative score per file. Each filter module may increment or decrement score on handling the file. The overall score determines in the end wheter to bounce or re-inject the mail.
254  
255 =head3 spam_behavior : Str
256  
257 How to determine what is spam. Either scoring, strict or ignore
258  
259 Default: scoring
260  
261 =cut
262  
263 9 has spam_behavior => ( is => 'rw', isa => 'Str', default => 'scoring' );
264  
265 =head3 spam_handle : Str
266  
267 What to do with recognized spam. Either tag, bounce or delete
268  
269 Default: tag
270  
271 =cut
272  
273 9 has spam_handle => ( is => 'rw', isa => 'Str', default => 'tag' );
274  
275 =head3 spam_subject_prefix : Str
276  
277 If spam_handle is tag: "Subject"-Attribute prefix for recognized SPAM mails.
278  
279 =cut
280  
281 9 has spam_subject_prefix => ( is => 'rw', isa => 'Str', predicate => 'has_spam_subject_prefix' );
282  
283 =head3 spam_threshold : Int
284  
285 For spam_behavior: scoring. Each cann add/remove a score for the filtered mail. SPAM scores are negative, HAM scores positive. If this threshold is reached, the mail is considered SPAM.
286  
287 Default: -100
288  
289 =cut
290  
291 9 has spam_threshold => ( is => 'rw', isa => 'Int', default => -100 );
292  
293 =head3 spam_notify_recipient : Bool
294  
295 If enabled -> send recipient notification if SPAM is recognized.
296  
297 Default: 0
298  
299 =cut
300  
301 9 has spam_notify_recipient => ( is => 'rw', isa => 'Bool', default => 0 );
302  
303 =head3 spam_recipient_template : Str
304  
305 Path to template used for SPAM notification.
306  
307 =cut
308  
309 9 has spam_recipient_template => ( is => 'rw', isa => 'Str' );
310  
311 =head3 spam_recipient_subject : Str
312  
313 Subject of the recipient's SPAM notification mail
314  
315 Default: Spam detected
316  
317 =cut
318  
319 9 has spam_recipient_subject => ( is => 'rw', isa => 'Str', default => 'Spam detected' );
320  
321 =head3 spam_noisy_headers : Bool
322  
323 Wheter X-Decency headers in mail should contain detailed information.
324  
325 Default: 0
326  
327 =cut
328  
329 9 has spam_noisy_headers => ( is => 'rw', isa => 'Bool', default => 0 );
330  
331 =head2 virus_*
332  
333 Virus handling
334  
335 =head3 virus_handle : Str
336  
337 What to do with infected mails ? Either: bounce, delete or quarantine
338  
339 Default: ignore
340  
341 =cut
342  
343 9 has virus_handle => ( is => 'rw', isa => 'Str', default => 'ignore' );
344  
345 =head3 virus_notify_recipient : Bool
346  
347 Wheter to notofy the recipient about infected mails.
348  
349 Default: 0
350  
351 =cut
352  
353 9 has virus_notify_recipient => ( is => 'rw', isa => 'Bool', default => 0 );
354  
355 =head3 virus_recipient_template : Str
356  
357 Path to template used for recipient notification
358  
359 =cut
360  
361 9 has virus_recipient_template => ( is => 'rw', isa => 'Str' );
362  
363 =head3 virus_recipient_subject : Str
364  
365 Subject of the recipient's notification mail
366  
367 Default: Virus detected
368  
369 =cut
370  
371 9 has virus_recipient_subject => ( is => 'rw', isa => 'Str', default => 'Virus detected' );
372  
373 =head3 virus_notify_sender : Str
374  
375 Wheter to notify the sender of an infected mail (NOT A GOOD IDEA: BACKSCATTER!)
376  
377 Default: 0
378  
379 =cut
380  
381 9 has virus_notify_sender => ( is => 'rw', isa => 'Bool', default => 0 );
382  
383 =head3 virus_sender_template : Str
384  
385 Path to sender notification template
386  
387 =cut
388  
389 9 has virus_sender_template => ( is => 'rw', isa => 'Str' );
390  
391 =head3 virus_sender_subject : Str
392  
393 Subject of the sender notification
394  
395 Default: Virus detected
396  
397 =cut
398  
399 9 has virus_sender_subject => ( is => 'rw', isa => 'Str', default => 'Virus detected' );
400  
401  
402 =head2 accept_scoring : Bool
403  
404 Wheter to accept scoring from (external) policy server.
405  
406 Default: 0
407  
408 =cut
409  
410 9 has accept_scoring => ( is => 'rw', isa => 'Bool', default => 0 );
411  
412 =head2 policy_verify_key : Str
413  
414 Path to public (verification) key for scoring verification
415  
416 Default: 0
417  
418 =cut
419  
420 0 ▶has policy_verify_key => ( is => 'rw', isa => 'Str', predicate => 'has_policy_verify_key', trigger => sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
421 0 my ( $self, $key_file ) = @_;
422
423 # check file
424 0 ▶ $key_file = $self->config_dir . "/$key_file"
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_config_dir and not -f $key_file 0 0 0
Condition0%0/3
$self->has_config_dir and not -f $key_file
!ll&&!rl&&r
000
MC/DC0%0/2
$self->has_config_dir and not -f $key_file
$self->has_config_dir not -f $key_file
Truth table0%0/3
A and not(B)
A= $self->has_config_dirB= not -f $key_file
ABresult
0X0
100
111
425 if $self->has_config_dir && ! -f $key_file;
426 0 ▶ die "Could not access policy_verify_key key file '$key_file'\n"
Branch: 1 branch
BranchTrueFalseTotal
unless -f $key_file 0 0 0
427 unless -f $key_file;
428
429 # read key
430 0 ▶ open my $fh, '<', $key_file
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $key_file or die "Cannot open policy_verify_key key file for read: $!\n" 0 0 0
431 or die "Cannot open policy_verify_key key file for read: $!\n";
432 0 my $key_content = join( "", <$fh> );
433 0 close $fh;
434
435 # store key
436 0 $self->policy_verify_key_rsa( Crypt::OpenSSL::RSA->new_public_key( $key_content ) );
437 0 $self->logger->info( "Setup verify key '$key_file'" );
438
439 0 return;
440 9 } );
441  
442 =head2 policy_verify_key_rsa : Crypt::OpenSSL::RSA
443  
444 Instance of verification key (L<Crypt::OpenSSL::RSA>)
445  
446 =cut
447  
448 9 has policy_verify_key_rsa => ( is => 'rw', isa => 'Crypt::OpenSSL::RSA' );
449  
450  
451 =head2 session_data : Mail::Decency::Core::SessionItem::ContentFilter
452  
453 SessionItem (L<Mail::Decency::Core::SessionItem::ContentFilter>) of the current handle file
454  
455 =cut
456  
457 9 has session_data => ( is => 'rw', isa => 'Mail::Decency::Core::SessionItem::ContentFilter' );
458  
459  
460 =head2 notification_from : Str
461  
462 Notification sender (from address)
463  
464 Default: Postmaster <postmaster@localhost>
465  
466 =cut
467  
468 9 has notification_from => ( is => 'rw', isa => 'Str', default => 'Postmaster <postmaster@localhost>' );
469  
470  
471 =head1 METHODS
472  
473 =head2 init
474  
475 Init cache, database, logger, dirs and content filter
476  
477 =cut
478  
479 0 ▶sub init {
Subroutine init: not called CC=35 SCAR=71.4
480 0 my ( $self ) = @_;
481
482 # init name
483 0 $self->name( "contentfilter" );
484
485 # mark es inited
486 0 $self->{ inited } ++;
487
488 0 $self->init_logger();
489 0 $self->init_cache();
490 0 $self->init_database();
491 0 $self->init_dirs();
492 0 $self->init_content_filters();
493
494 # set from..
495 $self->notification_from( $self->config->{ notification_from } )
496 0 ▶ if $self->config->{ notification_from };
Branch: 1 branch
BranchTrueFalseTotal
if $self->config->{"notification_from"} 0 0 0
497
498 # having scoring ?
499 0 ▶ if ( defined( my $virus_ref = $self->config->{ virus } ) && ref( $self->config->{ virus } ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $virus_ref = $self->config->{'virus'}) and ref $self->config->{'virus'}) { } 0 0 0
Condition0%0/3
defined(my $virus_ref = $self->config->{"virus"}) and ref $self->config->{"virus"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined(my $virus_ref = $self->config->{"virus"}) and ref $self->config->{"virus"}
defined(my $virus_ref = $self->config->{"virus"}) ref $self->config->{"virus"}
Truth table0%0/3
A and B
A= defined(my $virus_ref = $self->config->{"virus"})B= ref $self->config->{"virus"}
ABresult
0X0
100
111
500
501 # what's the basic behavior ?
502 die "behavior has to be set to 'ignore', 'scoring' or 'strict' in spam section\n"
503 unless $virus_ref->{ handle }
504 0 ▶ && $virus_ref->{ handle } =~ /^(?:bounce|delete|quarantine|ignore)$/
Branch: 1 branch
BranchTrueFalseTotal
unless $virus_ref->{"handle"} and $virus_ref->{"handle"} =~ /^(?:bounce|delete|quarantine|ignore)$/ 0 0 0
Condition0%0/3
$virus_ref->{"handle"} and $virus_ref->{"handle"} =~ /^(?:bounce|delete|quarantine|ignore)$/
!ll&&!rl&&r
000
MC/DC0%0/2
$virus_ref->{"handle"} and $virus_ref->{"handle"} =~ /^(?:bounce|delete|quarantine|ignore)$/
$virus_ref->{"handle"} $virus_ref->{"handle"} =~ /^(?:bounce|delete|quarantine|ignore)$/
Truth table0%0/3
A and B
A= $virus_ref->{"handle"}B= $virus_ref->{"handle"} =~ /^(?:bounce|delete|quarantine|ignore)$/
ABresult
0X0
100
111
505 ;
506 0 $self->virus_handle( $virus_ref->{ handle } );
507
508 # for bounce mode ..
509 0 ▶ if ( $self->virus_handle =~ /^(?:bounce|delete|quarantine)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->virus_handle =~ /^(?:bounce|delete|quarantine)$/) 0 0 0
510
511 # check for each direction ..
512 0 foreach my $direction( qw/ sender recipient / ) {
513 0 ▶ next if $direction eq 'sender' && $self->virus_handle eq 'bounce';
Branch: 1 branch
BranchTrueFalseTotal
if $direction eq "sender" and $self->virus_handle eq "bounce" 0 0 0
Condition0%0/3
$direction eq "sender" and $self->virus_handle eq "bounce"
!ll&&!rl&&r
000
MC/DC0%0/2
$direction eq "sender" and $self->virus_handle eq "bounce"
$direction eq "sender" $self->virus_handle eq "bounce"
Truth table0%0/3
A and B
A= $direction eq "sender"B= $self->virus_handle eq "bounce"
ABresult
0X0
100
111
514
515 # determine methods and parameter names
516 0 my $template = "${direction}_template"; # sender_template
517 0 my $template_meth = "virus_$template"; # virus_sender_template
518 0 my $enable = "notify_${direction}"; # notify_sender
519 0 my $enable_meth = "virus_$enable"; # virus_notify_sender
520
521 # is enabled ?
522 $self->$enable_meth( 1 )
523 0 ▶ if $virus_ref->{ $enable };
Branch: 1 branch
BranchTrueFalseTotal
if $virus_ref->{$enable} 0 0 0
524
525 # having custom template ?
526 0 ▶ if ( $self->$enable_meth() && $virus_ref->{ $template } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->$enable_meth and $virus_ref->{$template}) 0 0 0
Condition0%0/3
$self->$enable_meth and $virus_ref->{$template}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->$enable_meth and $virus_ref->{$template}
$self->$enable_meth $virus_ref->{$template}
Truth table0%0/3
A and B
A= $self->$enable_methB= $virus_ref->{$template}
ABresult
0X0
100
111
527 my $filename = -f $virus_ref->{ $template }
528 0 ▶ ? $virus_ref->{ $template }
Branch: 1 branch
BranchTrueFalseTotal
-f $virus_ref->{$template} ? : 0 0 0
529 : $self->config_dir. "/$virus_ref->{ $template }"
530 ;
531 0 ▶ die "Cant read from virus $template file '$filename'\n"
Branch: 1 branch
BranchTrueFalseTotal
unless -f $filename 0 0 0
532 unless -f $filename;
533
534 # template
535 0 $self->$template_meth( $filename );
536
537 # subject
538 0 my $subject = "${direction}_subject";
539 0 my $subject_meth = "virus_${subject}";
540 $self->$subject_meth( $virus_ref->{ $subject } )
541 0 ▶ if $virus_ref->{ $subject }
Branch: 1 branch
BranchTrueFalseTotal
if $virus_ref->{$subject} 0 0 0
542 }
543 }
544 }
545 }
546 else {
547 0 $self->virus_handle( 'ignore' );
548 }
549
550 # having spam things ?
551 0 ▶ if ( defined( my $spam_ref = $self->config->{ spam } ) && ref( $self->config->{ spam } ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $spam_ref = $self->config->{'spam'}) and ref $self->config->{'spam'}) { } 0 0 0
Condition0%0/3
defined(my $spam_ref = $self->config->{"spam"}) and ref $self->config->{"spam"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined(my $spam_ref = $self->config->{"spam"}) and ref $self->config->{"spam"}
defined(my $spam_ref = $self->config->{"spam"}) ref $self->config->{"spam"}
Truth table0%0/3
A and B
A= defined(my $spam_ref = $self->config->{"spam"})B= ref $self->config->{"spam"}
ABresult
0X0
100
111
552
553 # what's the basic behavior ?
554 die "behavior has to be set to 'ignore', 'scoring' or 'strict' in spam section\n"
555 unless $spam_ref->{ behavior }
556 0 ▶ && $spam_ref->{ behavior } =~ /^(?:scoring|strict|ignore)$/
Branch: 1 branch
BranchTrueFalseTotal
unless $spam_ref->{"behavior"} and $spam_ref->{"behavior"} =~ /^(?:scoring|strict|ignore)$/ 0 0 0
Condition0%0/3
$spam_ref->{"behavior"} and $spam_ref->{"behavior"} =~ /^(?:scoring|strict|ignore)$/
!ll&&!rl&&r
000
MC/DC0%0/2
$spam_ref->{"behavior"} and $spam_ref->{"behavior"} =~ /^(?:scoring|strict|ignore)$/
$spam_ref->{"behavior"} $spam_ref->{"behavior"} =~ /^(?:scoring|strict|ignore)$/
Truth table0%0/3
A and B
A= $spam_ref->{"behavior"}B= $spam_ref->{"behavior"} =~ /^(?:scoring|strict|ignore)$/
ABresult
0X0
100
111
557 ;
558 0 $self->spam_behavior( $spam_ref->{ behavior } );
559
560
561 # how to handle recognized spam ?
562 0 ▶ unless ( $self->spam_behavior eq 'ignore' ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->spam_behavior eq "ignore") 0 0 0
563 die "spam_handle has to be set to 'tag', 'bounce' or 'delete' in scoring!\n"
564 unless $spam_ref->{ handle }
565 0 ▶ && $spam_ref->{ handle } =~ /^(?:tag|bounce|delete)$/
Branch: 1 branch
BranchTrueFalseTotal
unless $spam_ref->{"handle"} and $spam_ref->{"handle"} =~ /^(?:tag|bounce|delete)$/ 0 0 0
Condition0%0/3
$spam_ref->{"handle"} and $spam_ref->{"handle"} =~ /^(?:tag|bounce|delete)$/
!ll&&!rl&&r
000
MC/DC0%0/2
$spam_ref->{"handle"} and $spam_ref->{"handle"} =~ /^(?:tag|bounce|delete)$/
$spam_ref->{"handle"} $spam_ref->{"handle"} =~ /^(?:tag|bounce|delete)$/
Truth table0%0/3
A and B
A= $spam_ref->{"handle"}B= $spam_ref->{"handle"} =~ /^(?:tag|bounce|delete)$/
ABresult
0X0
100
111
566 ;
567 0 $self->spam_handle( $spam_ref->{ handle } );
568
569 # any spam subject prefix ?
570 $self->spam_subject_prefix( $spam_ref->{ spam_subject_prefix } )
571 0 ▶ if $self->spam_handle eq 'tag' && $spam_ref->{ spam_subject_prefix };
Branch: 1 branch
BranchTrueFalseTotal
if $self->spam_handle eq "tag" and $spam_ref->{"spam_subject_prefix"} 0 0 0
Condition0%0/3
$self->spam_handle eq "tag" and $spam_ref->{"spam_subject_prefix"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->spam_handle eq "tag" and $spam_ref->{"spam_subject_prefix"}
$self->spam_handle eq "tag" $spam_ref->{"spam_subject_prefix"}
Truth table0%0/3
A and B
A= $self->spam_handle eq "tag"B= $spam_ref->{"spam_subject_prefix"}
ABresult
0X0
100
111
572
573 # wheter use noisy headers or not
574 0 ▶ $self->spam_noisy_headers( $spam_ref->{ noisy_headers } || 0 );
Condition0%0/2
$spam_ref->{'noisy_headers'} || 0
l!l
00
MC/DC0%0/1
$spam_ref->{'noisy_headers'} || 0
$spam_ref->{'noisy_headers'}
Truth table0%0/2
A
A= $spam_ref->{'noisy_headers'}
Aresult
11
00
575
576 # set threshold
577 0 ▶ if ( $self->spam_behavior eq 'scoring' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->spam_behavior eq "scoring") 0 0 0
578 die "Require threshold in spam section with behavior = scoring\n"
579 0 ▶ unless defined $spam_ref->{ threshold };
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spam_ref->{"threshold"} 0 0 0
580 0 $self->spam_threshold( $spam_ref->{ threshold } );
581 }
582
583 # enable notification of recipient on bounce or delete ?
584 0 ▶ if ( ( $self->spam_handle eq 'bounce' || $self->spam_handle eq 'delete' ) && $spam_ref->{ notify_recipient } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->spam_handle eq "bounce" || $self->spam_handle eq "delete" and $spam_ref->{"notify_recipient"}) 0 0 0
Condition0%0/6
$self->spam_handle eq "bounce" || $self->spam_handle eq "delete" and $spam_ref->{"notify_recipient"}
!ll&&!rl&&r
000
$self->spam_handle eq "bounce" or $self->spam_handle eq "delete"
l!l&&r!l&&!r
000
MC/DC0%0/3
$self->spam_handle eq "bounce" || $self->spam_handle eq "delete" and $spam_ref->{"notify_recipient"}
$self->spam_handle eq "bounce" $self->spam_handle eq "delete" $spam_ref->{"notify_recipient"}
Truth table0%0/5
A or B and C
A= $self->spam_handle eq "bounce"B= $self->spam_handle eq "delete"C= $spam_ref->{"notify_recipient"}
ABCresult
00X0
1X00
0100
1X11
0111
585 0 $self->spam_notify_recipient( 1 );
586
587 # having a template for those notifications ?
588 0 ▶ if ( $spam_ref->{ recipient_template } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spam_ref->{"recipient_template"}) 0 0 0
589 die "Cannot read from spam recipient_template file '$spam_ref->{ recipient_template }'\n"
590 0 ▶ unless -f $spam_ref->{ recipient_template };
Branch: 1 branch
BranchTrueFalseTotal
unless -f $spam_ref->{"recipient_template"} 0 0 0
591 0 $self->spam_recipient_template( $spam_ref->{ recipient_template } );
592 }
593 }
594 }
595 }
596 else {
597 0 $self->spam_behavior( 'ignore' );
598 }
599
600 # accept scoring from headers ?
601 0 ▶ if ( $self->config->{ accept_scoring } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->config->{"accept_scoring"}) 0 0 0
602 0 $self->accept_scoring( 1 );
603
604 # having verify key ?
605 0 ▶ if ( $self->config->{ policy_verify_key } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->config->{'policy_verify_key'}) { } 0 0 0
606 0 $self->policy_verify_key( $self->config->{ policy_verify_key } );
607 }
608
609 # hmm, this is not good -> warn
610 else {
611 0 $self->logger->error( "Warning: You accept scoring from external policy servers, but don't use a verification key! Spammers can inject positive scoring!" );
612 }
613 }
614
615 0 return;
616 }
617  
618  
619 =head2 init_dirs
620  
621 Inits the queue, checks spool dir for existing files -> read them
622  
623 =cut
624  
625 0 ▶sub init_dirs {
Subroutine init_dirs: not called CC=8 SCAR=42.8
Pod documented
626 0 my ( $self ) = @_;
627
628 # check and set spool dir
629 die "Require 'spool_dir' in config (path to directory where saving mails while filtering)\n"
630 0 ▶ unless $self->config->{ spool_dir };
Branch: 1 branch
BranchTrueFalseTotal
unless $self->config->{"spool_dir"} 0 0 0
631 make_path( $self->config->{ spool_dir }, { mode => 0700 } )
632 0 ▶ unless -d $self->config->{ spool_dir };
Branch: 1 branch
BranchTrueFalseTotal
unless -d $self->config->{"spool_dir"} 0 0 0
633 die "Require 'spool_dir'. '". $self->config->{ spool_dir }. "' is not a directory. Please create it!\n"
634 0 ▶ unless -d $self->config->{ spool_dir };
Branch: 1 branch
BranchTrueFalseTotal
unless -d $self->config->{"spool_dir"} 0 0 0
635 0 $self->spool_dir( $self->config->{ spool_dir } );
636
637 # make sub dirs
638 0 my %dirs = qw(
639 temp_dir temp
640 queue_dir queue
641 mime_output_dir mime
642 reinject_failure_dir failure
643 quarantine_dir quarantine
644 );
645 0 ▶ while( my( $name, $dir ) = each %dirs ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %dirs) 0 0 0
646 0 ▶ $self->config->{ $name } ||= $self->spool_dir. "/$dir";
Condition0%0/3
$self->config->{$name} ||= $self->spool_dir . "/$dir"
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->config->{$name} ||= $self->spool_dir . "/$dir"
$self->config->{$name} $self->spool_dir . "/$dir"
Truth table0%0/3
A ||= B
A= $self->config->{$name}B= $self->spool_dir . "/$dir"
ABresult
1X1
011
000
647 make_path( $self->config->{ $name }, { mode => 0700 } )
648 0 ▶ unless -d $self->config->{ $name };
Branch: 1 branch
BranchTrueFalseTotal
unless -d $self->config->{$name} 0 0 0
649 die "Could not non existing '$name' dir '". $self->config->{ $name }. "'. Please create yourself.\n"
650 0 ▶ unless -d $self->config->{ $name };
Branch: 1 branch
BranchTrueFalseTotal
unless -d $self->config->{$name} 0 0 0
651 0 $self->$name( $self->config->{ $name } );
652 0 $self->logger->debug2( "Set '$name'-dir to '". $self->$name. "'" );
653 }
654
655 0 return ;
656 }
657  
658  
659 =head2 init_content_filters
660  
661 Reads all content filters, creates instance and add to list of filters
662  
663 =cut
664  
665 0 ▶sub init_content_filters {
Subroutine init_content_filters: not called CC=5 SCAR=34.0
Pod documented
666 0 my ( $self ) = @_;
667
668 # check config
669 die "'filters' has to be an Array!\n"
670 if $self->config->{ filters }
671 0 ▶ && ! ref( $self->config->{ filters } ) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if $self->config->{"filters"} and !ref($self->config->{"filters"}) eq "ARRAY" 0 0 0
Condition0%0/3
$self->config->{"filters"} and !ref($self->config->{"filters"}) eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
$self->config->{"filters"} and !ref($self->config->{"filters"}) eq "ARRAY"
$self->config->{"filters"} !ref($self->config->{"filters"}) eq "ARRAY"
Truth table0%0/3
A and not(B)
A= $self->config->{"filters"}B= !ref($self->config->{"filters"}) eq "ARRAY"
ABresult
0X0
100
111
672
673 # get weak ref instance of self
674 0 weaken( my $self_weak = $self );
675
676
677 0 foreach my $filter_ref( @{ $self->config->{ filters } } ) {
678
679 # get name anf config
680 0 my ( $name, $config_ref ) = %$filter_ref;
681
682 # setup enw filter
683
684 0 my $filter = $self->gen_child(
685 "Mail::Decency::ContentFilter" => $name => $config_ref );
686 0 ▶ $filter_ref->{ $name } = $filter->config if $filter;
Branch: 1 branch
BranchTrueFalseTotal
if $filter 0 0 0
687 }
688
689 }
690  
691  
692 =head2 start
693  
694 Starts all POE servers without calling the POE::Kernel->run
695  
696 =cut
697  
698 0 ▶sub start {
Subroutine start: not called CC=1 SCAR=6.9
Pod documented
699 0 my ( $self ) = @_;
700
701 # we need a handle for ourselfs
702 0 weaken( my $self_weak = $self );
703
704 # start forking server
705 0 Mail::Decency::Core::POEForking::SMTP->new( $self, {
706 temp_mask => $self->spool_dir. "/mail-XXXXXX"
707 } );
708
709 }
710  
711  
712 =head2 run
713  
714 Start and run the server via POE::Kernel->run
715  
716 =cut
717  
718 0 ▶sub run {
Subroutine run: not called CC=1 SCAR=6.9
Pod documented
719 0 my ( $self ) = @_;
720 0 $self->start();
721 0 POE::Kernel->run;
722 }
723  
724  
725 =head2 train
726  
727 Train spam/ham into modules
728  
729 =cut
730  
731 0 ▶sub train {
Subroutine train: not called CC=35 SCAR=70.8
Pod documented
732 0 my ( $self, $args_ref ) = @_;
733
734 # get cmd method
735 my $train_cmd = $args_ref->{ spam }
736 0 ▶ ? 'cmd_learn_spam'
Branch: 1 branch
BranchTrueFalseTotal
$args_ref->{'spam'} ? : 0 0 0
737 : 'cmd_learn_ham'
738 ;
739
740 # determine all modules being trainable (Cmd)
741 my @trainable = map {
742 0 ▶ $_->can( $train_cmd )
Branch: 1 branch
BranchTrueFalseTotal
$_->can($train_cmd) ? : 0 0 0
743 ? [ $train_cmd => $_ ]
744 : [ train => $_ ]
745 ;
746 } grep {
747 $_->does( 'Mail::Decency::ContentFilter::Core::Spam' )
748 && ( $_->can( $train_cmd ) || $_->can( 'train' ) )
749 && ! $_->config->{ disable_train }
750 0 ▶ } @{ $self->childs };
Condition0%0/9
$_->does('Mail::Decency::ContentFilter::Core::Spam') && ($_->can($train_cmd) || $_->can('train')) && !$_->config->{'disable_train'}
!ll&&!rl&&r
000
$_->does("Mail::Decency::ContentFilter::Core::Spam") and $_->can($train_cmd) || $_->can("train")
!ll&&!rl&&r
000
$_->can($train_cmd) or $_->can("train")
l!l&&r!l&&!r
000
MC/DC0%0/4
$_->does('Mail::Decency::ContentFilter::Core::Spam') && ($_->can($train_cmd) || $_->can('train')) && !$_->config->{'disable_train'}
$_->does("Mail::Decency::ContentFilter::Core::Spam") $_->can($train_cmd) $_->can("train") !$_->config->{'disable_train'}
Truth table0%0/6
A and B or C && not(D)
A= $_->does("Mail::Decency::ContentFilter::Core::Spam")B= $_->can($train_cmd)C= $_->can("train")D= !$_->config->{'disable_train'}
ABCDresult
0XXX0
100X0
11X00
10100
11X11
10111
751
752 # none found ?
753 0 ▶ die "No trainable modules enabled\n"
Branch: 1 branch
BranchTrueFalseTotal
unless @trainable 0 0 0
754 unless @trainable;
755
756 # strip cmd_
757 0 $train_cmd =~ s/^cmd_//;
758
759 # having move ?
760 0 ▶ if ( $args_ref->{ move } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args_ref->{"move"}) 0 0 0
761 die "Move directory '$args_ref->{ move }' does not exist?\n"
762 0 ▶ unless -d $args_ref->{ move };
Branch: 1 branch
BranchTrueFalseTotal
unless -d $args_ref->{"move"} 0 0 0
763 0 $args_ref->{ move } =~ s#\/+$##;
764 }
765
766 # get all files for training
767 my @files = -d $args_ref->{ files }
768 ? glob( "$args_ref->{ files }/*" )
769 9 ▶ : glob( $args_ref->{ files } )
Subroutine BEGIN: called CC=1 SCAR=0.0
770 0 ▶ ;
Branch: 1 branch
BranchTrueFalseTotal
-d $args_ref->{'files'} ? : 0 0 0
771 0 ▶ die "No mails for training found for '$args_ref->{ files }'"
Branch: 1 branch
BranchTrueFalseTotal
unless @files 0 0 0
772 unless @files;
773
774 # begin training
775 0 my ( %trained, %not_required, %errors ) = ();
776 0 ▶ print "Will train ". ( scalar @files ). " messages as ". ( $args_ref->{ spam } ? 'SPAM' : 'HAM' ). "\n";
Branch: 1 branch
BranchTrueFalseTotal
$args_ref->{'spam'} ? : 0 0 0
777
778 0 my $start_ref = [ gettimeofday() ];
779
780 0 my $counter = 0;
781 0 my $amount = scalar @files;
782 0 foreach my $file( @files ) {
783 0 print "". ( ++$counter ). " / $amount: '$file'\n";
784
785 0 my ( $th, $tn ) = tempfile( $self->temp_dir. "/train-XXXXXX", UNLINK => 0 );
786 0 close $th;
787 0 copy( $file, $tn );
788 0 my $size = -s $tn;
789 0 $self->session_init( $tn, $size );
790
791 0 foreach my $ref( @trainable ) {
792 0 my ( $method, $module ) = @$ref;
793
794 # check wheter mail is spam or not
795 0 $self->session_data->spam_score( 0 );
796 0 eval {
797 0 $module->handle;
798 };
799
800 # stop here, if ..
801 0 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($args_ref->{"spam"} and $self->session_data->spam_score < 0 or $args_ref->{"ham"} and $self->session_data->spam_score >= 0) 0 0 0
Condition0%0/9
$args_ref->{"spam"} and $self->session_data->spam_score < 0 or $args_ref->{"ham"} and $self->session_data->spam_score >= 0
l!l&&r!l&&!r
000
$args_ref->{"spam"} and $self->session_data->spam_score < 0
!ll&&!rl&&r
000
$args_ref->{"ham"} and $self->session_data->spam_score >= 0
!ll&&!rl&&r
000
MC/DC0%0/4
$args_ref->{"spam"} and $self->session_data->spam_score < 0 or $args_ref->{"ham"} and $self->session_data->spam_score >= 0
$args_ref->{"spam"} $self->session_data->spam_score < 0 $args_ref->{"ham"} $self->session_data->spam_score >= 0
Truth table0%0/7
A and B or C and D
A= $args_ref->{"spam"}B= $self->session_data->spam_score < 0C= $args_ref->{"ham"}D= $self->session_data->spam_score >= 0
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
802
803 # .. mail should be spam and is recognized as such
804 ( $args_ref->{ spam } && $self->session_data->spam_score < 0 )
805
806 # .. mail should NOT be spam and also not recognized as spam
807 || ( $args_ref->{ ham } && $self->session_data->spam_score >= 0 )
808 ) {
809 0 print " = $module / Already trained\n";
810 0 $not_required{ "$module" }++;
811 0 next;
812 }
813
814 # run filter with train command now
815 0 my ( $res, $result, $exit_code );
816
817 0 ▶ if ( $method =~ /^cmd_/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method =~ /^cmd_/) { } 0 0 0
818 0 eval {
819 0 ( $res, $result, $exit_code ) = $module->cmd_filter( $train_cmd );
820 };
821 }
822 else {
823 0 eval {
824 0 ▶ ( $res, $result, $exit_code ) = $module->train( $args_ref->{ spam } ? 'spam' : 'ham' );
Branch: 1 branch
BranchTrueFalseTotal
$args_ref->{'spam'} ? : 0 0 0
825 };
826 }
827 0 my $error = $@;
828
829 # having unexpected error
830 0 ▶ if ( $error || ( $exit_code && $result ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($error or $exit_code and $result) { } 0 0 0
Condition0%0/6
$error or $exit_code and $result
l!l&&r!l&&!r
000
$exit_code and $result
!ll&&!rl&&r
000
MC/DC0%0/3
$error or $exit_code and $result
$error $exit_code $result
Truth table0%0/4
A or B and C
A= $errorB= $exit_codeC= $result
ABCresult
1XX1
0111
00X0
0100
831 0 ▶ my $message = $error || $result;
Condition0%0/3
$error || $result
l!l&&r!l&&!r
000
MC/DC0%0/2
$error || $result
$error $result
Truth table0%0/3
A || B
A= $errorB= $result
ABresult
1X1
011
000
832 0 print " * $module / Error\n*****\n$message\n*****\n\n";
833 0 $errors{ "$module" }++;
834 }
835
836 # all ok -> trained
837 else {
838 0 print " + $module / Success\n";
839 0 $trained{ "$module" }++;
840 }
841 }
842 0 unlink( $tn );
843 0 ▶ unlink( "$tn.info" ) if -f "$tn.info";
Branch: 1 branch
BranchTrueFalseTotal
if -f "$tn.info" 0 0 0
844
845 0 my $diff = tv_interval( $start_ref, [ gettimeofday() ] );
846 0 printf " > %.2f seconds remaining\n", ( ( $diff / $counter ) * $amount ) - $diff;
847
848 0 ▶ if ( $args_ref->{ move } ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($args_ref->{'move'}) { } 0 0 0
elsif ($args_ref->{'remove'}) { } 0 0 0
849 0 ( my $target = $file ) =~ s#^.*\/##;
850 0 $file = abs_path( $file );
851 0 $target = abs_path( "$args_ref->{ move }/$target" );
852 0 $target =~ s/[^0-9a-zA-Z\-_\.\/]/-/g;
853 0 $target =~ s/\-\-+/-/g;
854 0 $target =~ s/\-+$//;
855 0 $target =~ s/^\-+//;
856 0 ▶ move( $file, $target )
Branch: 1 branch
BranchTrueFalseTotal
move($file, $target) or die "Move error: $!\n" 0 0 0
857 or die "Move error: $!\n";
858 0 ▶ die "Oops, cannot move '$file' -> '$target'\n" unless -f $target;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $target 0 0 0
859 }
860 elsif ( $args_ref->{ remove } ) {
861 0 unlink( $file );
862 }
863 }
864
865 # print out skipped (ham/spam)
866 0 ▶ if ( scalar keys %not_required ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %not_required) 0 0 0
867 0 print "\n**** Not Required ****\n";
868 0 foreach my $name( sort keys %not_required ) {
869 0 print "$name: $not_required{ $name }\n";
870 }
871 }
872
873 # print out trained (ham/spam)
874 0 ▶ if ( scalar keys %trained ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %trained) { } 0 0 0
875 0 print "\n**** Trained ****\n";
876 0 foreach my $name( sort keys %trained ) {
877 0 print "$name: $trained{ $name }\n";
878 }
879 }
880 else {
881 0 print "\n**** None trained ****\n";
882 }
883
884 # print out errors (ham/spam)
885 0 ▶ if ( scalar keys %errors ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %errors) { } 0 0 0
886 0 print "\n**** Errors ****\n";
887 0 foreach my $name( sort keys %errors ) {
888 0 print "$name: $errors{ $name }\n";
889 }
890 }
891 else {
892 0 print "\n**** No Errors ****\n";
893 }
894 }
895  
896  
897  
898 =head2 get_handlers
899  
900 Returns code ref to handlers
901  
902 my $handlers_ref = $content_filter->get_handlers();
903 $handlers_ref->( {
904 file => '/tmp/somefile',
905 size => -s '/tmp/somefile',
906 from => 'sender@domain.tld',
907 to => 'recipient@domain.tld',
908 } );
909  
910 =cut
911  
912 0 ▶sub get_handlers {
Subroutine get_handlers: not called CC=1 SCAR=6.9
Pod documented
913 0 my ( $self ) = @_;
914
915 0 weaken( my $self_weak = $self );
916
917 # { file => '/path/to/file', from => "from@domain.tld", to => "to@domain.tld" }
918 0 ▶ return sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
919 0 my ( $ref ) = @_;
920
921 0 $self_weak->logger->debug3( "Handle new: $ref->{ file }, from: $ref->{ from }, to: $ref->{ to }" );
922
923 0 my ( $ok, $message );
924
925 # better eval that.. the server shold NOT die .
926 0 eval {
927
928 # write the from, to, size and such to yaml file
929 0 ▶ open my $fh, ">", $ref->{ file }. ".info"
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", $ref->{"file"} . '.info' or die qq[Cannot open '$ref->{"file"}' for read\n] 0 0 0
930 or die "Cannot open '$ref->{ file }' for read\n";
931
932 0 print $fh YAML::Dump( $ref );
933 0 close $fh;
934
935 0 ( $ok, $message ) = $self_weak->handle( $ref->{ file }, -s $ref->{ file } );
936 };
937
938 # log out error
939 0 ▶ if ( $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
940 0 $self_weak->logger->error( "Error handling '$ref->{ file }': $@" );
941 }
942
943 0 return ( $ok, $message );
944 }
945
946 0 }
947  
948  
949 =head2 handle
950  
951 Calls the handle method of all registered filters.
952  
953 Will be called from the job queue
954  
955 =cut
956  
957 0 ▶sub handle {
Subroutine handle: not called CC=34 SCAR=70.8
Pod documented
958 0 my ( $self, $file, $size ) = @_;
959
960 # setup mail info (mime, from, to and such)
961 0 eval {
962 0 $self->session_init( $file, $size );
963 };
964 0 ▶ if ( $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
965 0 $self->logger->error( "Cannot init session: $@" );
966 0 return;
967 }
968
969 # handle by all filters
970 0 my $status = 'ok';
971
972 EACH_FILTER:
973 0 foreach my $filter( @{ $self->childs } ) {
974 0 $self->logger->debug3( "Handle to '$filter'" );
975
976 0 ▶ if ( $self->has_exclusions && $self->do_exclude( $filter ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_exclusions and $self->do_exclude($filter)) 0 0 0
Condition0%0/3
$self->has_exclusions and $self->do_exclude($filter)
!ll&&!rl&&r
000
MC/DC0%0/2
$self->has_exclusions and $self->do_exclude($filter)
$self->has_exclusions $self->do_exclude($filter)
Truth table0%0/3
A and B
A= $self->has_exclusionsB= $self->do_exclude($filter)
ABresult
0X0
100
111
977 0 ▶ $self->logger->debug2( "Exclude $filter for ". ( $self->session_data->from || "" ). " -> ". $self->to );
Condition0%0/2
$self->session_data->from || ''
l!l
00
MC/DC0%0/1
$self->session_data->from || ''
$self->session_data->from
Truth table0%0/2
A
A= $self->session_data->from
Aresult
11
00
978 0 next;
979 }
980
981 # determine weight before, so we can increment stats
982 0 my $weight_before = $self->session_data->spam_score;
983 0 my $start_time_ref = [ gettimeofday() ];
984
985 0 eval {
986
987 # set alarm if timeout enabed
988 0 my $alarm = \( local $SIG{ ALRM } );
989 0 ▶ if ( $filter->timeout ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($filter->timeout) 0 0 0
990 0 ▶ $$alarm = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
991 0 Mail::Decency::Core::Exception::Timeout->throw( { message => "Timeout" } );
992 0 };
993 0 alarm( $filter->timeout + 1 );
994 }
995
996 # check size.. if to big for filter -> don't handle
997 0 ▶ if ( $filter->can( 'max_size' )
Branch: 1 branch
BranchTrueFalseTotal
if ($filter->can('max_size') and $filter->max_size and $self->session_data->file_size > $filter->max_size) { } 0 0 0
Condition0%0/6
$filter->can("max_size") and $filter->max_size and $self->session_data->file_size > $filter->max_size
!ll&&!rl&&r
000
$filter->can("max_size") and $filter->max_size
!ll&&!rl&&r
000
MC/DC0%0/3
$filter->can("max_size") and $filter->max_size and $self->session_data->file_size > $filter->max_size
$filter->can("max_size") $filter->max_size $self->session_data->file_size > $filter->max_size
Truth table0%0/4
A and B and C
A= $filter->can("max_size")B= $filter->max_sizeC= $self->session_data->file_size > $filter->max_size
ABCresult
0XX0
10X0
1100
1111
998 && $filter->max_size
999 && $self->session_data->file_size > $filter->max_size
1000 ) {
1001 0 Mail::Decency::Core::Exception::FileToBig->throw( { message => "File to big" } );
1002 }
1003
1004 # run the filter on the current file
1005 else {
1006 0 $filter->handle();
1007 }
1008 };
1009 0 my $err = $@;
1010
1011 # reset alarm
1012 0 ▶ alarm( 0 ) if $filter->timeout;
Branch: 1 branch
BranchTrueFalseTotal
if $filter->timeout 0 0 0
1013
1014
1015 #
1016 # STATI AFTER ERROR:
1017 # ok: mail is OK -> pass to next module
1018 # spam: mail is finally recognized as spam. Stop handling. Finish as spam.
1019 # virus: mail is infected by a virus. Stop handling. Finish as virus.
1020 # drop: mail is to be dropped. No further handling.
1021 #
1022
1023 0 ▶ if ( $err ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 0 0 0
1024
1025 0 given ( $err ) {
1026
1027 # got final SPAM
1028 0 ▶ when( blessed( $_ ) && $_->isa( 'Mail::Decency::Core::Exception::Spam' ) ) {
Condition0%0/3
builtin::blessed($_) && $_->isa('Mail::Decency::Core::Exception::Spam')
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($_) && $_->isa('Mail::Decency::Core::Exception::Spam')
builtin::blessed($_) $_->isa('Mail::Decency::Core::Exception::Spam')
Truth table0%0/3
A && B
A= builtin::blessed($_)B= $_->isa('Mail::Decency::Core::Exception::Spam')
ABresult
0X0
100
111
1029 0 $self->session_data->add_spam_details( $_->message );
1030 0 $self->logger->debug0( "Mail is spam after $filter, message: ". $_->message );
1031 0 $status = 'spam';
1032 }
1033
1034 # got final VIRUS
1035 0 ▶ when( blessed( $_ ) && $_->isa( 'Mail::Decency::Core::Exception::Virus' ) ) {
Condition0%0/3
builtin::blessed($_) && $_->isa('Mail::Decency::Core::Exception::Virus')
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($_) && $_->isa('Mail::Decency::Core::Exception::Virus')
builtin::blessed($_) $_->isa('Mail::Decency::Core::Exception::Virus')
Truth table0%0/3
A && B
A= builtin::blessed($_)B= $_->isa('Mail::Decency::Core::Exception::Virus')
ABresult
0X0
100
111
1036 0 $self->session_data->add_spam_details( $_->message );
1037 0 $self->logger->debug0( "Mail is virus after $filter, message: ". $_->message );
1038 0 $status = 'virus';
1039 }
1040
1041 # error: timeout
1042 0 ▶ when( blessed( $_ ) && $_->isa( 'Mail::Decency::Core::Exception::Drop' ) ) {
Condition0%0/3
builtin::blessed($_) && $_->isa('Mail::Decency::Core::Exception::Drop')
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($_) && $_->isa('Mail::Decency::Core::Exception::Drop')
builtin::blessed($_) $_->isa('Mail::Decency::Core::Exception::Drop')
Truth table0%0/3
A && B
A= builtin::blessed($_)B= $_->isa('Mail::Decency::Core::Exception::Drop')
ABresult
0X0
100
111
1043 0 $self->logger->debug0( "Dropping mail after $filter" );
1044 0 $status = 'drop';
1045 }
1046
1047 # file to big, ignore, log
1048 0 ▶ when( blessed( $_ ) && $_->isa( 'Mail::Decency::Core::Exception::FileToBig' ) ) {
Condition0%0/3
builtin::blessed($_) && $_->isa('Mail::Decency::Core::Exception::FileToBig')
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($_) && $_->isa('Mail::Decency::Core::Exception::FileToBig')
builtin::blessed($_) $_->isa('Mail::Decency::Core::Exception::FileToBig')
Truth table0%0/3
A && B
A= builtin::blessed($_)B= $_->isa('Mail::Decency::Core::Exception::FileToBig')
ABresult
0X0
100
111
1049 0 $self->logger->debug0( "File to big for $filter" );
1050 }
1051
1052 # error: timeout
1053 0 ▶ when( blessed( $_ ) && $_->isa( 'Mail::Decency::Core::Exception::Timeout' ) ) {
Condition0%0/3
builtin::blessed($_) && $_->isa('Mail::Decency::Core::Exception::Timeout')
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($_) && $_->isa('Mail::Decency::Core::Exception::Timeout')
builtin::blessed($_) $_->isa('Mail::Decency::Core::Exception::Timeout')
Truth table0%0/3
A && B
A= builtin::blessed($_)B= $_->isa('Mail::Decency::Core::Exception::Timeout')
ABresult
0X0
100
111
1054 0 $self->logger->error( "Timeout in $filter" );
1055 }
1056
1057 # got some unknown error
1058 0 default {
1059 0 $self->logger->error( "Error in $filter: $_" );
1060 }
1061 }
1062 }
1063
1064 # update stats
1065 0 ▶ if ( $self->enable_stats ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->enable_stats) 0 0 0
1066 0 my $weight_diff = $self->session_data->spam_score - $weight_before;
1067 0 $self->update_stats( $filter => uc( $status ) => $weight_diff, tv_interval( $start_time_ref, [ gettimeofday() ] ) );
1068 0 $self->logger->debug2( "Added $weight_diff ($filter)" );
1069 }
1070
1071 0 ▶ last EACH_FILTER if $status ne 'ok';
Branch: 1 branch
BranchTrueFalseTotal
if $status ne "ok" 0 0 0
1072 }
1073
1074 # write mail info to caches
1075 0 $self->session_write_cache;
1076
1077 # final code ..
1078 0 my $final_code = CF_FINAL_OK;
1079
1080 # having finish hooks ?
1081 0 foreach my $filter( @{ $self->childs } ) {
1082 0 ▶ if ( ! $filter->can( 'hook_pre_finish' ) || ( $self->has_exclusions && $self->do_exclude( $filter ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $filter->can("hook_pre_finish") or $self->has_exclusions and $self->do_exclude($filter)) 0 0 0
Condition0%0/6
not $filter->can("hook_pre_finish") or $self->has_exclusions and $self->do_exclude($filter)
l!l&&r!l&&!r
000
$self->has_exclusions and $self->do_exclude($filter)
!ll&&!rl&&r
000
MC/DC0%0/3
not $filter->can("hook_pre_finish") or $self->has_exclusions and $self->do_exclude($filter)
not $filter->can("hook_pre_finish") $self->has_exclusions $self->do_exclude($filter)
Truth table0%0/4
not(A) or B and C
A= not $filter->can("hook_pre_finish")B= $self->has_exclusionsC= $self->do_exclude($filter)
ABCresult
1XX1
0111
00X0
0100
1083 0 $self->logger->debug2( "Exclude $filter" );
1084 0 next;
1085 }
1086
1087 0 eval {
1088 0 ( $status, $final_code ) = $filter->hook_pre_finish( $status );
1089 };
1090 0 ▶ $self->logger->error( "Error in pre finsh hook for '$filter': $@" ) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
1091 }
1092
1093 # found virus ? take care of it!
1094 0 ▶ if ( $status eq 'virus' ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($status eq 'virus') { } 0 0 0
elsif ($status eq 'spam') { } 0 0 0
elsif ($status ne 'drop') { } 0 0 0
1095 0 $final_code = $self->finish_virus;
1096 }
1097
1098 # recognized spam ? see to it.
1099 elsif ( $status eq 'spam' ) {
1100 0 $final_code = $self->finish_spam;
1101 }
1102
1103 # ok, all ok -> regular finish
1104 elsif ( $status ne 'drop' ) {
1105 0 $final_code = $self->finish_ok;
1106 }
1107
1108 # having after-finish hooks ?
1109 0 foreach my $filter( @{ $self->childs } ) {
1110 0 ▶ if ( ! $filter->can( 'hook_post_finish' ) || ( $self->has_exclusions && $self->do_exclude( $filter ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $filter->can("hook_post_finish") or $self->has_exclusions and $self->do_exclude($filter)) 0 0 0
Condition0%0/6
not $filter->can("hook_post_finish") or $self->has_exclusions and $self->do_exclude($filter)
l!l&&r!l&&!r
000
$self->has_exclusions and $self->do_exclude($filter)
!ll&&!rl&&r
000
MC/DC0%0/3
not $filter->can("hook_post_finish") or $self->has_exclusions and $self->do_exclude($filter)
not $filter->can("hook_post_finish") $self->has_exclusions $self->do_exclude($filter)
Truth table0%0/4
not(A) or B and C
A= not $filter->can("hook_post_finish")B= $self->has_exclusionsC= $self->do_exclude($filter)
ABCresult
1XX1
0111
00X0
0100
1111 0 $self->logger->debug2( "Exclude $filter" );
1112 0 next;
1113 }
1114 0 eval {
1115 0 ( $status, $final_code ) = $filter->hook_post_finish( $status );
1116 };
1117 0 ▶ $self->logger->error( "Error in post finsh hook for '$filter': $@" ) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
1118 }
1119
1120
1121 # clear all
1122 0 my $spam_details = join( " / ", @{ $self->session_data->spam_details } );
1123 0 $self->session_data->cleanup;
1124
1125 # return the final code to the SMTP server, which will then either force the mta
1126 # (postfix) to bounce the mail by rejecting it or accept, to
1127 0 ▶ if ( $final_code == CF_FINAL_OK || $final_code == CF_FINAL_DELETED ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($final_code == 105 or $final_code == 107) { } 0 0 0
Condition0%0/3
$final_code == 105 or $final_code == 107
l!l&&r!l&&!r
000
MC/DC0%0/2
$final_code == 105 or $final_code == 107
$final_code == 105 $final_code == 107
Truth table0%0/3
A or B
A= $final_code == 105B= $final_code == 107
ABresult
1X1
011
000
1128 0 return ( 1 );
1129 }
1130 else {
1131 0 return ( 0, $spam_details );
1132 }
1133 }
1134  
1135  
1136 =head2 finish_spam
1137  
1138 Called after modules have filtered the mail. Will perform according to spam_handle directive.
1139  
1140 =over
1141  
1142 =item * delete
1143  
1144 Remvoe mail silently
1145  
1146 =item * bounce
1147  
1148 Bounce mail back to sender
1149  
1150 =item * ignore
1151  
1152 Ignore mail, simply forward
1153  
1154 =item * tag
1155  
1156 Tag mail, insert X-Decency-Status and X-Decency-Score headers. If detailed: also X-Decency-Details header.
1157  
1158 =back
1159  
1160 =cut
1161  
1162 0 ▶sub finish_spam {
Subroutine finish_spam: not called CC=7 SCAR=40.3
Pod documented
1163 0 my ( $self ) = @_;
1164
1165 0 my $session = $self->session_data;
1166 0 my $score = $session->spam_score;
1167 0 my @info = @{ $session->spam_details };
1168
1169 # just remove and ignore
1170 0 ▶ if ( $self->spam_handle eq 'delete' ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($self->spam_handle eq 'delete') { } 0 0 0
elsif ($self->spam_handle eq 'bounce') { } 0 0 0
elsif ($self->spam_handle eq 'ignore') { } 0 0 0
1171 0 $self->logger->info( sprintf( 'Delete spam mail from %s to %s, size %d with score %d',
1172 $session->from, $session->to, $session->file_size, $score ) );
1173 0 return CF_FINAL_DELETED;
1174 }
1175
1176 # do bounce mail
1177 elsif ( $self->spam_handle eq 'bounce' ) {
1178 0 $self->logger->info( sprintf( 'Bounce spam mail from %s to %s, size %d with score %d',
1179 $session->from, $session->to, $session->file_size, $score ) );
1180
1181 0 return CF_FINAL_BOUNCE;
1182 }
1183
1184 # do ignore mail, don't tag, do nothing like this
1185 elsif ( $self->spam_handle eq 'ignore' ) {
1186 0 return $self->reinject;
1187 }
1188
1189 # do tag mail
1190 else {
1191 0 my $header = $self->session_data->mime->head;
1192
1193 # prefix subject ?
1194 0 ▶ if ( $self->has_spam_subject_prefix ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_spam_subject_prefix) 0 0 0
1195 0 ▶ my $subject = $header->get( 'Subject' ) || '';
Condition0%0/2
$header->get('Subject') || ''
l!l
00
MC/DC0%0/1
$header->get('Subject') || ''
$header->get('Subject')
Truth table0%0/2
A
A= $header->get('Subject')
Aresult
11
00
1196 0 ( my $prefix = $self->spam_subject_prefix ) =~ s/ $//;
1197 0 $header->replace( 'Subject' => "$prefix $subject" );
1198 }
1199
1200 # add tag
1201 0 $header->replace( 'X-Decency-Result' => 'SPAM' );
1202 0 $header->replace( 'X-Decency-Score' => $score );
1203 0 ▶ $header->replace( 'X-Decency-Details' => join( " | ", @info ) )
Branch: 1 branch
BranchTrueFalseTotal
if $self->spam_noisy_headers 0 0 0
1204 if $self->spam_noisy_headers;
1205
1206 # update mime
1207 0 $self->session_data->write_mime;
1208
1209 # reinject
1210 0 return $self->reinject;
1211 }
1212 }
1213  
1214  
1215 =head2 finish_virus
1216  
1217 Mail has been recognized as infected. Handle it according to virus_handle
1218  
1219 =over
1220  
1221 =item * bounce
1222  
1223 Send back to sender
1224  
1225 =item * delete
1226  
1227 Silently remove
1228  
1229 =item * quarantine
1230  
1231 Do not deliver mail, move it into quarantine directory.
1232  
1233 =item * ignore
1234  
1235 Deliver to recipient
1236  
1237 =back
1238  
1239 =cut
1240  
1241 0 ▶sub finish_virus {
Subroutine finish_virus: not called CC=4 SCAR=30.0
Pod documented
1242 0 my ( $self ) = @_;
1243
1244 # get session..
1245 0 my $session = $self->session_data;
1246
1247 # don't do that .. however, here is the bounce
1248 0 ▶ if ( $self->virus_handle eq 'bounce' ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($self->virus_handle eq 'bounce') { } 0 0 0
elsif ($self->virus_handle eq 'delete') { } 0 0 0
elsif ($self->virus_handle eq 'quarantine') { } 0 0 0
1249 0 $self->logger->info( sprintf( 'Bounce virus infected mail from %s to %s, size %d with virus "%s"',
1250 $session->from, $session->to, $session->file_size, $session->virus ) );
1251 0 return CF_FINAL_BOUNCE;
1252 }
1253
1254 # don't do that .. however, here is the bounce
1255 elsif ( $self->virus_handle eq 'delete' ) {
1256 0 $self->logger->info( sprintf( 'Delete virus infected mail from %s to %s, size %d with virus "%s"',
1257 $session->from, $session->to, $session->file_size, $session->virus ) );
1258 0 return CF_FINAL_DELETED;
1259 }
1260
1261 # inject mail into qurantine dir
1262 elsif ( $self->virus_handle eq 'quarantine' ) {
1263 0 $self->logger->info( sprintf( 'Quarantine virus infected mail from %s to %s, size %d with virus "%s"',
1264 $session->from, $session->to, $session->file_size, $session->virus ) );
1265 0 $self->_save_mail_to_dir( 'quarantine_dir' );
1266 0 return CF_FINAL_DELETED;
1267 }
1268
1269 # don't do that ..
1270 else {
1271 0 $self->logger->info( sprintf( 'Delivering virus infected mail from %s to %s, size %d with virus "%s"',
1272 $session->from, $session->to, $session->file_size, $session->virus ) );
1273 0 return $self->reinject;
1274 }
1275 }
1276  
1277  
1278 =head2 finish_ok
1279  
1280 Called after mails has not been recognized as virus nor SPAM. Do deliver to recipient. With noisy_headers, include spam X-Decency-(Result|Score|Details) into header.
1281  
1282 =cut
1283  
1284 0 ▶sub finish_ok {
Subroutine finish_ok: not called CC=2 SCAR=17.9
Pod documented
1285 0 my ( $self ) = @_;
1286
1287 # being noisy -> set spam info even if not spam
1288 0 ▶ if ( $self->spam_noisy_headers ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->spam_noisy_headers) 0 0 0
1289 0 my $header = $self->session_data->mime->head;
1290 0 $header->replace( 'X-Decency-Result' => 'GOOD' );
1291 0 $header->replace( 'X-Decency-Score' => $self->session_data->spam_score );
1292 $header->replace( 'X-Decency-Details' => join( " | ",
1293 0 @{ $self->session_data->spam_details } ) );
1294
1295 # update mime
1296 0 $self->session_data->write_mime;
1297 }
1298
1299 0 return $self->reinject;
1300 }
1301  
1302  
1303 =head2 reinject
1304  
1305 Reinject mails to postfix queue, or archive in send-queue
1306  
1307 =cut
1308  
1309 0 ▶sub reinject {
Subroutine reinject: not called CC=8 SCAR=42.8
Pod documented
1310 0 my ( $self, $type ) = @_;
1311
1312 0 my $reinject_ref = $self->config->{ reinject };
1313
1314 0 eval {
1315
1316 my $smtp = Net::SMTP->new(
1317 $reinject_ref->{ host }. ":". $reinject_ref->{ port },
1318 0 ▶ Hello => 'decency',
Branch: 1 branch
BranchTrueFalseTotal
my $smtp = "Net::SMTP"->new($reinject_ref->{"host"} . ':' . $reinject_ref->{"port"}, "Hello", "decency", "Timeout", 30) or die "ARR: $!" 0 0 0
1319 Timeout => 30,
1320 #Debug => 1,
1321 ) or die "ARR: $!";
1322
1323 0 $smtp->hello( 'localhost' );
1324 0 $smtp->mail( $self->session_data->from );
1325 0 $smtp->to( $self->session_data->to );
1326 0 $smtp->data;
1327
1328 # parse file and print all lines
1329 0 open my $fh, '<', $self->session_data->file;
1330 0 ▶ while ( my $l = <$fh> ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $l = readline $fh)) 0 0 0
1331 0 chomp $l;
1332 0 ▶ $smtp->datasend( $l. CRLF ) or die $!;
Branch: 1 branch
BranchTrueFalseTotal
$smtp->datasend($l . "\r\n") or die $! 0 0 0
1333 }
1334
1335 # end data
1336 0 $smtp->dataend;
1337
1338 # get reponse message containg new ID
1339 0 my $message = $smtp->message;
1340
1341 # quit connection
1342 0 $smtp->quit;
1343
1344 # determine message
1345 0 ▶ if ( $message && $message =~ /queued as ([A-Z0-9]+)/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($message and $message =~ /queued as ([A-Z0-9]+)/) { } 0 0 0
Condition0%0/3
$message and $message =~ /queued as ([A-Z0-9]+)/
!ll&&!rl&&r
000
MC/DC0%0/2
$message and $message =~ /queued as ([A-Z0-9]+)/
$message $message =~ /queued as ([A-Z0-9]+)/
Truth table0%0/3
A and B
A= $messageB= $message =~ /queued as ([A-Z0-9]+)/
ABresult
0X0
100
111
1346 0 $self->logger->debug0( "Reinjected mail as $1" );
1347 0 $self->session_data->next_id( $1 );
1348 0 $self->session_write_cache;
1349 }
1350 else {
1351 0 Mail::Decency::Core::Exception::ReinjectFailure->throw( { message => "Could not reinject" } );
1352 }
1353 };
1354
1355 0 ▶ return CF_FINAL_OK unless $@;
Branch: 1 branch
BranchTrueFalseTotal
unless $@ 0 0 0
1356
1357 0 given ( $@ ) {
1358
1359 # reinect failure -> save to failure dir and log
1360 0 ▶ when( blessed( $_ ) && $_->isa( 'Mail::Decency::Core::Exception::ReinjectFailure' ) ) {
Condition0%0/3
builtin::blessed($_) && $_->isa('Mail::Decency::Core::Exception::ReinjectFailure')
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($_) && $_->isa('Mail::Decency::Core::Exception::ReinjectFailure')
builtin::blessed($_) $_->isa('Mail::Decency::Core::Exception::ReinjectFailure')
Truth table0%0/3
A && B
A= builtin::blessed($_)B= $_->isa('Mail::Decency::Core::Exception::ReinjectFailure')
ABresult
0X0
100
111
1361 0 $self->logger->error( "Could not retreive reinjection ID - possible error on reinjection ? Reinject manual." );
1362 0 $self->_save_mail_to_dir( 'reinject_failure_dir' );
1363 }
1364
1365 # some other error..
1366 0 default {
1367 0 $self->logger->error( "Could not reinject mail: $@" );
1368 }
1369 }
1370
1371 0 return CF_FINAL_ERROR;
1372 }
1373  
1374  
1375  
1376 =head2 send_notify
1377  
1378 Send either spam or virus notification
1379  
1380 $content_filter->send_notify( virus => recipient => 'recipient@domain.tld' );
1381  
1382 =cut
1383  
1384 0 ▶sub send_notify {
Subroutine send_notify: not called CC=12 SCAR=50.5
Pod documented
1385 0 my ( $self, $type, $direction, $to ) = @_;
1386 0 my $mime = $self->session_data->mime;
1387
1388 0 eval {
1389
1390 # build the multipart surrounding
1391 0 my $subject_method = "${type}_${direction}_subject";
1392 0 ▶ my $encaps = MIME::Entity->build(
Condition0%0/2
$self->$subject_method || uc($type) . ' notification'
l!l
00
MC/DC0%0/1
$self->$subject_method || uc($type) . ' notification'
$self->$subject_method
Truth table0%0/2
A
A= $self->$subject_method
Aresult
11
00
1393 Subject => $self->$subject_method || uc( $type ). " notification",
1394 From => $self->notification_from,
1395 To => $to,
1396 Type => 'multipart/mixed',
1397 'X-Mailer' => 'Decency'
1398 );
1399
1400 0 my @data = ();
1401 0 my $template_meth = "${type}_${direction}_template"; # eg spam_recipient_template
1402
1403 # get session
1404 0 my $session = $self->session_data;
1405
1406 # having a custom template ..
1407 0 ▶ if ( defined $self->$template_meth ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->$template_meth) { } 0 0 0
1408
1409 # read template ..
1410 0 ▶ open my $fh, '<', $self->$template_meth
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $self->$template_meth or die q[Cannot open '] . $self->$template_meth . "' for read: $!\n" 0 0 0
1411 or die "Cannot open '". $self->$template_meth. "' for read: $!\n";
1412
1413 # add reason of rejection
1414 0 my %template_vars = ( reason => $type );
1415
1416 # add virus name
1417 0 ▶ $template_vars{ virus } = $session->virus if $type eq 'virus';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "virus" 0 0 0
1418
1419 # add from, to
1420 0 $template_vars{ $_ } = $session->$_ for qw/ from to /;
1421
1422 # add subject, if any
1423 0 ▶ $template_vars{ subject } = $session->mime->head->get( 'Subject' ) || "(no subject)";
Condition0%0/2
$session->mime->head->get('Subject') || '(no subject)'
l!l
00
MC/DC0%0/1
$session->mime->head->get('Subject') || '(no subject)'
$session->mime->head->get('Subject')
Truth table0%0/2
A
A= $session->mime->head->get('Subject')
Aresult
11
00
1424
1425 # read and parse template
1426 @data = map {
1427 0 chomp;
1428 0 ▶ s/<%\s*([^%]+)\s*%>/defined $template_vars{ $1 } ? $template_vars{ $1 } : $1/egms;
Branch: 1 branch
BranchTrueFalseTotal
defined $template_vars{$1} ? : 0 0 0
1429 0 $_;
1430 } <$fh>;
1431
1432 # close template
1433 0 close $fh;
1434 }
1435 else {
1436 0 push @data, "Your mail to ". $session->to. " has been rejected.";
1437 0 push @data, "";
1438 0 ▶ push @data, "Subject of the mail: ". ( $session->mime->head->get( 'Subject' ) || "(no subject)" );
Condition0%0/2
$session->mime->head->get('Subject') || '(no subject)'
l!l
00
MC/DC0%0/1
$session->mime->head->get('Subject') || '(no subject)'
$session->mime->head->get('Subject')
Truth table0%0/2
A
A= $session->mime->head->get('Subject')
Aresult
11
00
1439 0 push @data, "";
1440 0 ▶ push @data, "Reason: categorized as ". $type. ( $type eq 'virus' ? " (". $session->virus. ")" : "" );
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'virus' ? : 0 0 0
1441 }
1442
1443 # add the template
1444 0 $encaps->add_part( MIME::Entity->build(
1445 Type => 'text/plain',
1446 Encoding => 'quoted-printable',
1447 Data => \@data
1448 ) );
1449
1450 0 ▶ unless ( $self->reinject( $encaps ) == CF_FINAL_OK ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->reinject($encaps) == 105) 0 0 0
1451 0 die "Error sending $type $direction notification mail to $to\n";
1452 }
1453 };
1454
1455 # having error ?
1456 0 ▶ if ( $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
1457 0 $self->logger->error( "Error in mime encapsulation: $@" );
1458 0 return 0;
1459 }
1460
1461 0 return 1;
1462 }
1463  
1464  
1465  
1466  
1467  
1468  
1469 =head2 session_init
1470  
1471 Inits the L<Mail::Decency::Core::SessionItem::ContentFilter> session object for the current handled mail.
1472  
1473 =cut
1474  
1475 0 ▶sub session_init {
Subroutine session_init: not called CC=6 SCAR=37.4
Pod documented
1476 0 my ( $self, $file, $size ) = @_;
1477
1478 # setup new info
1479 0 ( my $init_id = $file ) =~ s/[\/\\]/-/g;
1480 0 ▶ $self->session_data( Mail::Decency::Core::SessionItem::ContentFilter->new(
Condition0%0/2
$init_id || 'unknown-' . time
l!l
00
MC/DC0%0/1
$init_id || 'unknown-' . time
$init_id
Truth table0%0/2
A
A= $init_id
Aresult
11
00
1481 id => $init_id || "unknown-". time(),
1482 file => $file,
1483 mime_output_dir => $self->mime_output_dir,
1484 cache => $self->cache
1485 ) );
1486 0 my $session = $self->session_data;
1487
1488
1489 #
1490 # RETREIVE QUEUE ID, UPDATE FROM CONTENT FILTER CACHE
1491 #
1492
1493 # get last queue ID
1494 0 my @received = $session->mime->head->get( 'Received' );
1495 0 $self->logger->debug0( "received ". Dumper( \@received ) );
1496 0 my $received = shift @received;
1497 0 ▶ if ( $received && $received =~ /E?SMTP id ([A-Z0-9]+)/ms ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($received and $received =~ /E?SMTP id ([A-Z0-9]+)/ms) { } 0 0 0
Condition0%0/3
$received and $received =~ /E?SMTP id ([A-Z0-9]+)/ms
!ll&&!rl&&r
000
MC/DC0%0/2
$received and $received =~ /E?SMTP id ([A-Z0-9]+)/ms
$received $received =~ /E?SMTP id ([A-Z0-9]+)/ms
Truth table0%0/3
A and B
A= $receivedB= $received =~ /E?SMTP id ([A-Z0-9]+)/ms
ABresult
0X0
100
111
1498 0 my $id = $1;
1499 0 $session->id( $id );
1500
1501 # try read info from policy server from cache
1502 0 my $cached = $self->cache->get( "QUEUE-$id" );
1503 0 $self->logger->debug2( "Got cached $id ". Dumper( $cached ) );
1504 0 ▶ $session->update_from_cache( $cached )
Branch: 1 branch
BranchTrueFalseTotal
if $cached and ref $cached 0 0 0
Condition0%0/3
$cached and ref $cached
!ll&&!rl&&r
000
MC/DC0%0/2
$cached and ref $cached
$cached ref $cached
Truth table0%0/3
A and B
A= $cachedB= ref $cached
ABresult
0X0
100
111
1505 if $cached && ref( $cached );
1506 }
1507
1508 # oops, this should not happen, maybe in debug cases, if mails
1509 # are directyly injected into the content filter ?!
1510 else {
1511 0 $self->logger->error( "Could not determine Queue ID! No 'Received' header found! Postfix should set this!" );
1512 }
1513
1514 # retreive scoring from policy server, if any
1515 0 $session->retreive_policy_scoring( $self->accept_scoring );
1516
1517
1518 0 return $session;
1519 }
1520  
1521  
1522 =head2 session_write_cache
1523  
1524 Write session to cache. Called at the end of the session.
1525  
1526 =cut
1527  
1528 0 ▶sub session_write_cache {
Subroutine session_write_cache: not called CC=4 SCAR=30.0
Pod documented
1529 0 my ( $self ) = @_;
1530
1531 # get session to be cached
1532 0 my $session_ref = $self->session_data->for_cache;
1533
1534 # save to cache (max 10min..)
1535 0 $self->cache->set( "QUEUE-$session_ref->{ queue_id }", $session_ref, time() + 600 );
1536
1537 # write next to cache
1538 0 ▶ if ( $session_ref->{ next_id } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($session_ref->{"next_id"}) 0 0 0
1539 0 my %next = %{ $session_ref };
1540 0 $next{ queue_id } = $session_ref->{ next_id };
1541 0 $next{ prev_id } = $session_ref->{ queue_id };
1542 0 $next{ next_id } = undef;
1543 0 $self->cache->set( "QUEUE-$next{ queue_id }", \%next, time() + 600 );
1544
1545 0 $self->logger->debug3( "Store next id $session_ref->{ next_id } for $session_ref->{ queue_id }" );
1546 }
1547
1548 # re-write prev to cache (keep alive)
1549 0 ▶ if ( $session_ref->{ prev_id } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($session_ref->{"prev_id"}) 0 0 0
1550
1551 # get cached prev
1552 0 my $prev_cached = $self->cache->get( "QUEUE-$session_ref->{ prev_id }" );
1553
1554 # create new prev
1555 0 my %prev = %{ $session_ref };
1556 0 $prev{ queue_id } = $session_ref->{ prev_id };
1557 0 ▶ $prev{ prev_id } = $prev_cached ? $prev_cached->{ prev_id } : undef;
Branch: 1 branch
BranchTrueFalseTotal
$prev_cached ? : 0 0 0
1558 0 $prev{ next_id } = $session_ref->{ queue_id };
1559 0 $self->cache->set( "QUEUE-$prev{ queue_id }", \%prev, time() + 600 );
1560 0 $self->logger( debug3 => "Store prev id $session_ref->{ prev_id } for $session_ref->{ id }" );
1561 }
1562
1563 0 return ;
1564 }
1565  
1566  
1567  
1568  
1569 #
1570 # SPAM
1571 #
1572  
1573  
1574  
1575  
1576  
1577 =head2 add_spam_score
1578  
1579 Add spam score (positive/negative). If threshold is reached -> throw L<Mail::Decency::Core::Exception::Spam> exception.
1580  
1581 =cut
1582  
1583 0 ▶sub add_spam_score {
Subroutine add_spam_score: not called CC=7 SCAR=40.3
Pod documented
1584 0 my ( $self, $weight, $module, $message_ref ) = @_;
1585
1586 # get info
1587 0 my $session = $self->session_data;
1588
1589 # add score
1590 0 $session->add_spam_score( $weight );
1591
1592 # add info
1593 0 ▶ $message_ref ||= [];
Condition0%0/2
$message_ref ||= []
l!l
00
MC/DC0%0/1
$message_ref ||= []
$message_ref
Truth table0%0/2
A
A= $message_ref
Aresult
11
00
1594 0 ▶ $message_ref = [ $message_ref ] unless ref( $message_ref );
Branch: 1 branch
BranchTrueFalseTotal
unless ref $message_ref 0 0 0
1595 0 $session->add_spam_details( join( "; ",
1596 "Module: $module",
1597 "Score: $weight",
1598 @$message_ref
1599 ) );
1600
1601 # provide result based on config settings
1602 0 ▶ if ( (
Branch: 1 branch
BranchTrueFalseTotal
if ($session->spam_score < 0 and $self->spam_behavior eq "strict" or $self->spam_behavior eq "scoring" and $session->spam_score <= $self->spam_threshold) 0 0 0
Condition0%0/9
$session->spam_score < 0 and $self->spam_behavior eq "strict" or $self->spam_behavior eq "scoring" and $session->spam_score <= $self->spam_threshold
l!l&&r!l&&!r
000
$session->spam_score < 0 and $self->spam_behavior eq "strict"
!ll&&!rl&&r
000
$self->spam_behavior eq "scoring" and $session->spam_score <= $self->spam_threshold
!ll&&!rl&&r
000
MC/DC0%0/4
$session->spam_score < 0 and $self->spam_behavior eq "strict" or $self->spam_behavior eq "scoring" and $session->spam_score <= $self->spam_threshold
$session->spam_score < 0 $self->spam_behavior eq "strict" $self->spam_behavior eq "scoring" $session->spam_score <= $self->spam_threshold
Truth table0%0/7
A and B or C and D
A= $session->spam_score < 0B= $self->spam_behavior eq "strict"C= $self->spam_behavior eq "scoring"D= $session->spam_score <= $self->spam_threshold
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
1603 # strict hit
1604 $session->spam_score < 0
1605 && $self->spam_behavior eq 'strict'
1606 )
1607 || (
1608 # threshold hit
1609 $self->spam_behavior eq 'scoring'
1610 && $session->spam_score <= $self->spam_threshold
1611 ) ) {
1612 # throw ..
1613 0 Mail::Decency::Core::Exception::Spam->throw( { message => "Spam found" } );
1614 }
1615 }
1616  
1617  
1618 =head2 virus_info
1619  
1620 Virus is found. Throw L<Mail::Decency::Core::Exception::Virus> exception.
1621  
1622 =cut
1623  
1624 0 ▶sub found_virus {
Subroutine found_virus: not called CC=1 SCAR=6.9
Pod undocumented
1625 0 my ( $self, $info ) = @_;
1626 0 $self->session_data->virus( $info );
1627
1628 # throw final exception
1629 0 Mail::Decency::Core::Exception::Virus->throw( { message => "Virus found: $info" } );
1630 }
1631  
1632  
1633 =head2 _save_mail_to_dir
1634  
1635 Save a mail to some dir. Called from quarantine or reinjection failures
1636  
1637 =cut
1638  
1639 0 ▶sub _save_mail_to_dir {
Subroutine _save_mail_to_dir: not called CC=3 SCAR=24.8
1640 0 my ( $self, $dir_name ) = @_;
1641
1642 # determine from with replaced @
1643 0 ▶ ( my $from = $self->from || "unkown" ) =~ s/\@/-at-/;
Condition0%0/2
$self->from || 'unkown'
l!l
00
MC/DC0%0/1
$self->from || 'unkown'
$self->from
Truth table0%0/2
A
A= $self->from
Aresult
11
00
1644
1645 # determine to with replaced @
1646 0 ▶ ( my $to = $self->to || "unkown" ) =~ s/\@/-at-/;
Condition0%0/2
$self->to || 'unkown'
l!l
00
MC/DC0%0/1
$self->to || 'unkown'
$self->to
Truth table0%0/2
A
A= $self->to
Aresult
11
00
1647
1648 # format file <time>-<from>-<to> and replace possible problematic chars
1649 0 ( my $from_to = time(). "_FROM_${from}_TO_${to}" ) =~ s/[^\p{L}\d\-_\.]//gms;
1650
1651 # get tempfile (assures uniqueness)
1652 0 my ( $th, $failure_file )
1653 = tempfile( $self->$dir_name. "/$from_to-XXXXXX", UNLINK => 0 );
1654 0 close $th;
1655
1656 # copy file to archive folder
1657 0 copy( $self->file, $failure_file );
1658 }
1659  
1660 =head1 AUTHOR
1661  
1662 Ulrich Kautz <uk@fortrabbit.de>
1663  
1664 =head1 COPYRIGHT
1665  
1666 Copyright (c) 2010 the L</AUTHOR> as listed above
1667  
1668 =head1 LICENCSE
1669  
1670 This library is free software and may be distributed under the same terms as perl itself.
1671  
1672 =cut
1673  
1674  
1675 9 1;
« lib/Mail/Decency/Core/Stats.pm ↑ Summary lib/Mail/Decency/Policy/Throttle.pm »