]> git.proxmox.com Git - pmg-api.git/blob - src/bin/pmg-smtp-filter
smtp-filter: whitespace and indentation clean-ups
[pmg-api.git] / src / bin / pmg-smtp-filter
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use Carp;
7 use Encode qw(encode);
8 use Getopt::Long;
9 use Time::HiRes qw (usleep gettimeofday tv_interval);
10 use POSIX qw(:sys_wait_h errno_h signal_h);
11
12 use MIME::Parser;
13 use MIME::WordDecoder qw(mime_to_perl_string);
14 use File::Path;
15 use Net::Server::PreFork;
16 use Net::Server::SIG qw(register_sig check_sigs);
17 use Net::SMTP;
18
19 use Fcntl ':flock';
20 use File::Basename;
21 use Xdgmime;
22
23 use PVE::SafeSyslog;
24 use PVE::ProcFSTools;
25 use PVE::INotify;
26
27 use Mail::SpamAssassin;
28 use Mail::SpamAssassin::NetSet;
29
30 use PMG::pmgcfg;
31 use PMG::Utils;
32 use PMG::Cluster;
33 use PMG::ClusterConfig;
34
35 use PMG::DBTools;
36 use PMG::RuleDB;
37 use PMG::RuleCache;
38 use PMG::ModGroup;
39 use PMG::AtomicFile;
40 use PMG::LDAPConfig;
41 use PMG::LDAPSet;
42 use PMG::Config;
43 use PMG::MailQueue;
44 use PMG::Unpack;
45 use PMG::SMTP;
46
47 use PMG::Unpack;
48 use PMG::Statistic;
49
50 use base qw(Net::Server::PreFork);
51
52 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
53
54 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
55
56 my $opt_commandline = [$0, @ARGV];
57 my $opt_max_dequeue = 1;
58 my $opt_dequeue_time = 30;
59
60 my $opt_ext_port = 10024;
61 my $opt_int_port = 10023;
62 my $opt_inject_port = 10025;
63
64 my $opt_testmode;
65 my $opt_untrusted;
66 my $opt_pidfile;
67 my $opt_database;
68
69 my $prog_name = 'pmg-smtp-filter';
70
71 initlog($prog_name, 'mail');
72
73 if (!GetOptions(
74 'testmode=s' => \$opt_testmode,
75 'pidfile=s' => \$opt_pidfile,
76 'untrusted' => \$opt_untrusted,
77 'database=s' => \$opt_database
78 )) {
79 die "usage error\n";
80 exit (-1);
81 }
82
83 $opt_pidfile = "/run/${prog_name}.pid" if !$opt_pidfile;
84
85 my $max_servers = 1;
86 my $min_servers = 1;
87 my $min_spare_servers = 0;
88 my $max_spare_servers = 0;
89 my $max_requests = 1;
90
91 if (!$opt_testmode) {
92 my $pmg_cfg = PMG::Config->new();
93
94 my $demo = $pmg_cfg->get('admin', 'demo');
95
96 if ($demo) {
97 syslog ('info', 'demo mode detected - not starting server');
98 exit (0);
99 }
100
101 my $memory = PMG::Config::Mail::physical_memory();
102 if ($memory < 3840) {
103 warn "total memory below 4 GiB, consider setting 'max_filters' manually to avoid OOM-kills\n"
104 if !defined($pmg_cfg->get('mail', 'max_filters', 1));
105 }
106
107 $max_servers = $pmg_cfg->get('mail', 'max_filters') + 2;
108 $min_servers = 2;
109 $min_spare_servers = 1;
110 $max_spare_servers = 4;
111 $max_requests = 20;
112 }
113
114 print "using pre-fork workers with min=$min_servers, max=$max_servers, min_spare=$min_spare_servers"
115 .", max_spare=$max_spare_servers, max_requests=$max_requests\n";
116
117 $opt_max_dequeue = 0 if $opt_testmode;
118
119 my $daemonize = 1;
120 if (defined ($ENV{BOUND_SOCKETS})) {
121 $daemonize = undef;
122 }
123
124 my $server_attr = {
125 port => [ $opt_int_port, $opt_ext_port ],
126 host => '127.0.0.1',
127 min_servers => $min_servers,
128 max_servers => $max_servers,
129 min_spare_servers => $min_spare_servers,
130 max_spare_servers => $max_spare_servers,
131 max_requests => $max_requests,
132 serialize => 'flock',
133 max_dequeue => $opt_max_dequeue,
134 check_for_dequeue => $opt_dequeue_time,
135 log_level => 3,
136 pid_file => $opt_pidfile,
137 no_close_by_child => 1,
138 no_client_stdout => 1,
139 commandline => $opt_commandline,
140 };
141
142 $server_attr->{setsid} = $daemonize if !$opt_testmode;
143
144 my $database;
145
146 if (defined($opt_database)) {
147 $database = $opt_database;
148 } else {
149 $database = $opt_testmode ? "Proxmox_testdb" : "Proxmox_ruledb";
150 }
151
152 $SIG{'__WARN__'} = sub {
153 my $err = $@;
154 my $t = $_[0];
155 chomp $t;
156 syslog('warning', "WARNING: %s", $t);
157 $@ = $err;
158 };
159
160 sub get_prox_vars {
161 my ($self, $queue, $entity, $msginfo, $rule, $targets, $spaminfo) = @_;
162
163 $spaminfo = {
164 sa_score => $queue->{sa_score},
165 sa_hits => $queue->{sa_hits},
166 sa_data => $queue->{sa_data},
167 sa_max => $queue->{sa_max}
168 } if !$spaminfo;
169
170 my $vars = {
171 'SUBJECT' => PMG::Utils::decode_rfc1522($entity->head->get ('subject', 0) || 'No Subject'),
172 'RULE' => $rule->{name},
173 'RULE_INFO' => $msginfo->{rule_info},
174 'SENDER' => $msginfo->{sender},
175 'SENDER_IP' => $msginfo->{xforward}->{addr},
176 'TARGETS' => join (', ', @$targets),
177 'RECEIVERS' => join (', ', @{$msginfo->{targets}}),
178 'SPAMLEVEL' => $spaminfo->{sa_score},
179 'SPAMSTARS' => '*' x (($spaminfo->{sa_score} || 0) > 100 ? 100 : $spaminfo->{sa_score} || 0),
180 'ADMIN' => $self->{pmg_cfg}->get('admin', 'email'),
181 'HOST' => $msginfo->{hostname},
182 'DOMAIN' => $msginfo->{domain},
183 'FQDN' => $msginfo->{fqdn},
184 'MSGID' => $queue->{msgid},
185 'VERSION' => PMG::pmgcfg::package() . "/" . PMG::pmgcfg::release() . "/" . PMG::pmgcfg::repoid(),
186 };
187
188 $vars->{__spaminfo} = $spaminfo;
189
190 if ($opt_testmode) {
191 if ($queue->{vinfo_clam} || $queue->{vinfo_avast} || $queue->{vinfo_custom}) {
192 $vars->{'VIRUS_INFO'} = "Virus Info:";
193 $vars->{'VIRUS_INFO'} .= " clam: $queue->{vinfo_clam}" if $queue->{vinfo_clam};
194 $vars->{'VIRUS_INFO'} .= " avast: $queue->{vinfo_avast}" if $queue->{vinfo_avast};
195 $vars->{'VIRUS_INFO'} .= " custom: $queue->{vinfo_custom}" if $queue->{vinfo_custom};
196 } else {
197 $vars->{'VIRUS_INFO'} = '';
198 }
199 } else {
200 if ($queue->{vinfo}) {
201 $vars->{'VIRUS_INFO'} = "Virus Info: $queue->{vinfo}\n";
202 } else {
203 $vars->{'VIRUS_INFO'} = '';
204 }
205 }
206
207 $vars->{'SPAM_HITS'} = $spaminfo->{sa_hits};
208
209 $vars->{'SPAM_INFO'} = '';
210 my $sscores = $spaminfo->{sa_data};
211
212 if (defined ($sscores) && @$sscores != -1) {
213 my $sa_text;
214 if ($opt_testmode) {
215 $sa_text = "Spam detection results: 100\n";
216 } else {
217 $sa_text = "Spam detection results: $spaminfo->{sa_score}\n";
218 }
219
220 foreach my $s (@$sscores) {
221 if ($opt_testmode) {
222 $sa_text .= sprintf ("%-22s %6s %s\n", $s->{rule}, 1, $s->{desc} || '-');
223 } else {
224 $sa_text .= sprintf ("%-22s %6s %s\n", $s->{rule}, $s->{score}, $s->{desc} || '-');
225 }
226 }
227 $vars->{'SPAM_INFO'} = $sa_text;
228 }
229
230 if ($opt_testmode) {
231 delete ($vars->{'ADMIN'});
232 #delete ($vars->{'SPAM_INFO'});
233 }
234
235 return $vars;
236 }
237
238 sub apply_rules {
239 my ($self, $queue, $msginfo, $entity, $ldap) = @_;
240
241 my $final;
242 my %rule_targets;
243 my %rule_actions;
244 my %rule_marks;
245 my %rule_spaminfo;
246 my $matching_rules = [];
247
248 my $rulecache = $self->{rulecache};
249 my $rules = $rulecache->rules ();
250 my $dbh = $self->{ruledb}->{dbh};
251
252 # first, we remove all conditional written 'X-' header attributes
253 foreach my $rule (@$rules) {
254 next if !$rule->{active};
255 next if ($rule->{direction} == 0) && $msginfo->{trusted};
256 next if ($rule->{direction} == 1) && !$msginfo->{trusted};
257
258 my $actions = $rulecache->get_actions ($rule->{id});
259 if ($actions) {
260 foreach my $action (@$actions) {
261 if ($action->isa ("PMG::RuleDB::ModField")) {
262 my $fname = $action->{field};
263 next if $fname !~ m/^X-/i;
264 $entity->head->delete($fname);
265 }
266 }
267 }
268 }
269
270 foreach my $rule (@$rules) {
271 next if !$rule->{active};
272 next if ($rule->{direction} == 0) && $msginfo->{trusted};
273 next if ($rule->{direction} == 1) && !$msginfo->{trusted};
274
275 # match from, when and what classes (not target dependent)
276 if (!($rulecache->from_match ($rule->{id}, $msginfo->{sender}, $msginfo->{xforward}->{addr}, $ldap) &&
277 $rulecache->when_match ($rule->{id}, time))) {
278 next;
279 }
280
281 my ($marks, $spaminfo) =
282 $rulecache->what_match ($rule->{id}, $queue, $entity, $msginfo, $dbh);
283
284 $rule_marks{$rule->{id}} = $marks;
285 $rule_spaminfo{$rule->{id}} = $spaminfo;
286
287 $rule_actions{$rule->{id}} = $rulecache->get_actions ($rule->{id});
288 my $fin = $rulecache->final ($rule->{id});
289
290 # match targets
291 foreach my $target (@{$msginfo->{targets}}) {
292 next if $final->{$target};
293 next if !defined ($rule_marks{$rule->{id}});
294 next if !defined ($rule_marks{$rule->{id}}->{$target});
295 next if !$rulecache->to_match ($rule->{id}, $target, $ldap);
296
297 $final->{$target} = $fin;
298
299 push @{$rule_targets{$rule->{id}}}, $target;
300 }
301 }
302
303 # Compute rule_info (summary about matching rule)
304 # this can be used for debugging
305 my $rule_info = "";
306 foreach my $rule (@$rules) {
307 next if !$rule_targets{$rule->{id}};
308
309 push @$matching_rules, $rule->{id};
310
311 $rule_info .= "Rule: $rule->{name}\n";
312
313 foreach my $target (@{$rule_targets{$rule->{id}}}) {
314 $rule_info .= " Receiver: $target\n";
315 }
316 foreach my $action (@{$rule_actions{$rule->{id}}}) {
317 $rule_info .= " Action: " . $action->short_desc () . "\n";
318 }
319
320 }
321 $msginfo->{rule_info} = $rule_info;
322
323 if ($msginfo->{testmode}) {
324 my $vars = $self->get_prox_vars($queue, $entity, $msginfo, undef, [], undef);
325 my $fh = $msginfo->{test_fh};
326 print $fh $rule_info;
327 }
328
329 # apply actions
330
331 my $mod_group = PMG::ModGroup->new($entity, $msginfo->{targets});
332
333 foreach my $rule (@$rules) {
334 my $targets = $rule_targets{$rule->{id}};
335 next if !$targets;
336
337 my $vars = $self->get_prox_vars (
338 $queue, $entity, $msginfo, $rule, $rule_targets{$rule->{id}}, $rule_spaminfo{$rule->{id}});
339
340 my @sorted_actions = sort {$a->priority <=> $b->priority} @{$rule_actions{$rule->{id}}};
341
342 foreach my $action (@sorted_actions) {
343 $action->execute(
344 $queue, $self->{ruledb}, $mod_group, $rule_targets{$rule->{id}}, $msginfo, $vars,
345 $rule_marks{$rule->{id}}, $ldap
346 );
347 last if $action->final;
348 }
349 }
350
351 # we deliver all mail not matched by any rule (default action = accept)
352 my $unmatched;
353 foreach my $target (@{$msginfo->{targets}}) {
354 next if $final->{$target};
355
356 push @$unmatched, $target;
357 }
358
359 if ($unmatched) {
360 my $accept = PMG::RuleDB::Accept->new ();
361 $accept->execute ($queue, $self->{ruledb}, $mod_group, $unmatched,
362 $msginfo, { RULE => 'default-accept' }, undef);
363 }
364
365 return $matching_rules;
366 }
367
368 # reload ruledb and pmg config
369 sub load_config {
370 my $self = shift;
371 my $prop = $self->{server};
372
373 if ($self->{ruledb}) {
374 $self->log ('info', "reloading configuration $database");
375 $self->{ruledb}->close ();
376 }
377
378 $self->{pmg_cfg} = PMG::Config->new();
379 $self->{cinfo} = PVE::INotify::read_file("cluster.conf");
380
381 # create spool directories
382 PMG::MailQueue::create_spooldirs($self->{cinfo}->{local}->{cid});
383
384 eval {
385 my $dbh = PMG::DBTools::open_ruledb ($database);
386 $self->{ruledb} = PMG::RuleDB->new ($dbh);
387
388 # load rulecache
389 $self->{rulecache} = PMG::RuleCache->new ($self->{ruledb});
390 };
391
392 my $err = $@;
393
394 if ($err) {
395 sleep (10); # reduce restart rate when postgres is down
396 die $err;
397 }
398
399 # create LDAP object
400 my $ldapconf = PVE::INotify::read_file('pmg-ldap.conf');
401 $self->{ldap} = PMG::LDAPSet->new_from_ldap_cfg($ldapconf, 1);
402
403 $self->{reload_config} = 0;
404 }
405
406 my $syslog_map = {
407 0 => 'err',
408 1 => 'warning',
409 2 => 'notice',
410 3 => 'info',
411 4 => 'debug'
412 };
413
414 sub log {
415 my ($self, $level, $msg, @therest) = @_;
416 my $prop = $self->{server};
417
418 return if $level =~ /^\d+$/ && $level > $prop->{log_level};
419
420 $level = $syslog_map->{$level} || $level;
421 if (@therest) {
422 syslog($level, $msg, @therest);
423 } else {
424 syslog ($level, $msg);
425 }
426 }
427
428 sub pre_loop_hook {
429 my $self = shift;
430 my $prop = $self->{server};
431
432 $prop->{log_level} = 3;
433
434 $self->log ('info', "Filter daemon (re)started (max. $max_servers processes)");
435
436 eval { PMG::MailQueue::cleanup_active(); };
437 $self->log (0, "Cleanup failures: $@") if $@;
438
439 my $sig_set = POSIX::SigSet->new;
440 $sig_set->addset (&POSIX::SIGHUP);
441 $sig_set->addset (&POSIX::SIGCHLD);
442 my $old_sig_set = POSIX::SigSet->new();
443
444 sigprocmask (SIG_UNBLOCK, $sig_set, $old_sig_set);
445
446 my ($backup_umask) = umask;
447
448 my $pmg_cfg = PMG::Config->new();
449 $pmg_cfg->write_smtp_filter_config();
450
451 # Note: you need to restart the daemon when you change 'rbl_checks'
452 my $rbl_checks = $pmg_cfg->get('spam', 'rbl_checks');
453
454 $self->{sa} = Mail::SpamAssassin->new ({
455 debug => 0,
456 local_tests_only => $opt_testmode || !$rbl_checks,
457 home_dir_for_helpers => '/root',
458 userstate_dir => '/root/.spamassassin',
459 dont_copy_prefs => 1,
460 stop_at_threshold => 0,
461 });
462
463 $self->{sa}->compile_now;
464
465 alarm (0); # SA forgets to clear alarm in some cases
466 umask ($backup_umask);
467 initlog ($prog_name, 'mail');
468
469 $SIG{'USR1'} = sub {
470 # reloading server configuration
471 if (defined $prop->{children}) {
472 foreach my $pid (keys %{$prop->{children}}) {
473 kill (10, $pid); # SIGUSR1 children
474 }
475 }
476 }
477 }
478
479 sub child_init_hook {
480 my $self = shift;
481
482 $0 = "$prog_name child";
483
484 # $self->log (3, "init child");
485
486 eval {
487 $self->load_config ();
488 };
489
490 if ($@) {
491 $self->log (0, $@);
492 $self->child_finish_hook;
493 exit;
494 }
495
496 $SIG{'USR1'} = sub {
497 $self->{reload_config} = 1;
498 }
499 }
500
501 sub child_finish_hook {
502 my $self = shift;
503
504 # $self->log (3, "finish child");
505 $self->{ruledb}->close () if $self->{ruledb};
506 }
507
508 my $last_dequeue_time = 0;
509
510 sub run_dequeue {
511 my $self = shift;
512
513 my $err;
514
515 # do database maintenance here, this is called every 30 secends
516
517 eval { PMG::Utils::update_node_status_rrd() };
518 if ($err = $@) {
519 $self->log(0, "ERROR: $err");
520 # continue
521 }
522
523 my $ctime = time();
524 my $tdiff = $ctime - $last_dequeue_time;
525
526 # return if tdiff less than 2 minutes
527 return if $tdiff < 2*60;
528 $last_dequeue_time = $ctime;
529
530 $self->log (2, "starting database maintenance");
531
532 my ($csec, $usec) = gettimeofday ();
533
534 my $cinfo = PVE::INotify::read_file("cluster.conf");
535
536 my $dbh = eval { PMG::DBTools::open_ruledb($database) };
537 if ($err = $@) {
538 $self->log (0, "ERROR: $err");
539 return;
540 }
541
542 eval { PMG::Statistic::update_stats($dbh, $cinfo) };
543 $err = $@;
544
545 if ($err) {
546 $self->log (0, $err);
547 } else {
548 my ($csec_end, $usec_end) = gettimeofday ();
549 my $ptime = int (($csec_end - $csec) * 1000 + ($usec_end - $usec) / 1000);
550 $self->log (2, "end database maintenance ($ptime ms)");
551 }
552
553 $dbh->disconnect() if $dbh;
554 }
555
556
557 sub unpack_entity {
558 my ($self, $unpack, $entity, $msginfo, $queue) = @_;
559
560 my ($magic, $path) = $entity->@{'PMX_magic_ct', 'PMX_decoded_path'};
561
562 if ($magic && $path) {
563 my $filename = basename ($path);
564
565 if (PMG::Unpack::is_archive ($magic)) {
566 $self->log (3, "$queue->{logid}: found archive '$filename' ($magic)");
567
568 my $start = [gettimeofday];
569
570 $unpack->{mime} = {};
571
572 eval { $unpack->unpack_archive ($path, $magic) };
573 $self->log (3, "$queue->{logid}: unpack failed - $@") if $@;
574
575 $entity->{PMX_content_types} = $unpack->{mime};
576 $entity->{PMX_filenames} = $unpack->{filenames};
577
578 if ($opt_testmode) {
579 my $types = join (", ", sort keys (%{$entity->{PMX_content_types}}));
580 my $fh = $msginfo->{test_fh};
581 $filename =~ s/\d+/X/g if $filename =~ m/^msg-\d+-\d+.msg/;
582 print $fh "Types:$filename: $types\n" if $types;
583 }
584
585 my $elapsed = int(tv_interval($start) * 1000);
586 $self->log (3, "$queue->{logid}: unpack archive '$filename' done ($elapsed ms)");
587 }
588 }
589
590 for my $part ($entity->parts) {
591 $self->unpack_entity ($unpack, $part, $msginfo, $queue);
592 }
593
594 }
595
596 sub handle_smtp {
597 my ($self, $smtp) = @_;
598
599 my ($csec, $usec) = gettimeofday ();
600
601 my $queue;
602 my $msginfo = {};
603 my $pmg_cfg = $self->{pmg_cfg};
604 my $ldap = $self->{ldap};
605 my $cinfo = $self->{cinfo};
606 my $lcid = $cinfo->{local}->{cid};
607
608 $msginfo->{test_fh} = PMG::AtomicFile->new("testresult.out", "w") if $opt_testmode;
609
610 $msginfo->{trusted} = $self->{trusted};
611
612
613 # PHASE 1 - save incoming mail (already done)
614 # on error: exit
615
616 $queue = $smtp->{queue};
617 $queue->{sa} = $self->{sa};
618 $queue->{clamav_heuristic_score} =
619 $opt_testmode ? 100 : $pmg_cfg->get('spam', 'clamav_heuristic_score');
620
621 $queue->{lic_valid} = 1;
622
623 my $matching_rules;
624
625 eval {
626 $msginfo->{testmode} = $opt_testmode;
627 $msginfo->{sender} = $smtp->{from};
628 $msginfo->{xforward} = $smtp->{xforward};
629 $msginfo->{targets} = $smtp->{to};
630 $msginfo->{param} = $smtp->{param};
631
632 my $dkim_sign = $msginfo->{trusted} && $pmg_cfg->get('admin', 'dkim_sign');
633 if ($dkim_sign) {
634 $msginfo->{dkim}->{sign} = $dkim_sign;
635 $msginfo->{dkim}->{sign_all} = $pmg_cfg->get('admin', 'dkim_sign_all_mail');
636 $msginfo->{dkim}->{selector} = $pmg_cfg->get('admin', 'dkim_selector');
637 }
638
639 $msginfo->{hostname} = PVE::INotify::nodename();
640 my $resolv = PVE::INotify::read_file('resolvconf');
641
642 $msginfo->{domain} = $resolv->{search};
643 $msginfo->{fqdn} = $msginfo->{hostname};
644 $msginfo->{fqdn} .= ".$msginfo->{domain}" if $msginfo->{domain};
645 $msginfo->{lcid} = $lcid;
646
647 # $msginfo->{targets} is case sensitive,
648 # but pmail is always lower case!
649
650 foreach my $t (@{$msginfo->{targets}}) {
651 my $res;
652 if ($ldap && ($res = $ldap->account_info ($t))) {
653 $msginfo->{pmail}->{$t} = $res->{pmail};
654 } else {
655 $msginfo->{pmail}->{$t} = lc ($t);
656 }
657 }
658
659 # PHASE 2 - parse mail
660 # on error: exit
661
662 my $maxfiles = $pmg_cfg->get('clamav', 'archivemaxfiles');
663
664 my ($entity, $max_aid) = $queue->parse_mail($maxfiles);
665 $msginfo->{max_aid} = $max_aid;
666
667 $self->log (3, "$queue->{logid}: new mail message-id=%s", $queue->{msgid});
668
669 # PHASE 3 - run external content analyzers
670 # (SPAM analyzer is run on demand later)
671 # on error: log error messages
672
673 # run custom script first
674 my ($vinfo, $custom_spaminfo) = PMG::Utils::analyze_custom_check(
675 $queue, $queue->{dataname}, $pmg_cfg, $opt_testmode);
676
677 # test for virus if none found
678 if (!defined($vinfo)) {
679 $vinfo = PMG::Utils::analyze_virus(
680 $queue, $queue->{dataname}, $pmg_cfg, $opt_testmode);
681
682 if ($vinfo && $vinfo =~ m/^Heuristics\.(.+)$/) {
683 my $hit = $1;
684 $queue->{clamav_heuristic} = $hit;
685 $vinfo = undef;
686 }
687 }
688 $queue->{vinfo} = $vinfo;
689
690 # always add this headers to incoming mails
691 # to enable user to report false negatives
692 if (!$msginfo->{trusted}) {
693 if ($queue->{vinfo}) {
694 $entity->head->replace('X-Proxmox-VInfo', $queue->{vinfo});
695 }
696 }
697
698 # we unpack after virus scanning, because this is more secure.
699 # This way virus scanners gets the whole mail files and are able
700 # to detect phishing signature for example - which would not work
701 # if we decompose first and only analyze the decomposed attachments.
702 # Disadvantage is that we need to unpack more than
703 # once (bad performance).
704
705 # should we scan content types inside archives
706
707 my $rulecache = $self->{rulecache};
708
709 my $scan_archives = 0;
710
711 if (($rulecache->{archivefilter_in} && !$msginfo->{trusted}) ||
712 ($rulecache->{archivefilter_out} && $msginfo->{trusted})) {
713 $scan_archives = 1;
714 }
715
716 if ($scan_archives && !$queue->{vinfo}) {
717
718 # unpack all archives - determine contained content types
719
720 my $decdir = $queue->{dumpdir} . "/__decoded_archives";
721 mkdir $decdir;
722
723 my $start = [gettimeofday];
724
725 my $unpack;
726 eval {
727
728 # limits: We use clamav limit for maxfiles, and scan
729 # only 4 levels, timeout of 30 seconds
730
731 $unpack = PMG::Unpack->new (
732 tmpdir => $decdir,
733 timeout => 30,
734 ctonly => 1, # only detect CTs
735 maxrec => -4,
736 maxfiles => $maxfiles);
737
738 $self->unpack_entity ($unpack, $entity, $msginfo, $queue);
739 };
740
741 my $err = $@;
742
743 $unpack->cleanup() if $unpack;
744
745 my $elapsed = int(tv_interval ($start) * 1000);
746
747 if ($err) {
748 $self->log (3, "$queue->{logid}: unpack archive failed ($elapsed ms) - $err");
749 }
750 }
751
752 # PHASE 4 - apply rules
753 # on error: exit (cleanup process should do the rest)
754 $msginfo->{maxspamsize} = $pmg_cfg->get('spam', 'maxspamsize');
755 if ($msginfo->{maxspamsize} <= 1024*64) {
756 $msginfo->{maxspamsize} = 1024*64;
757 }
758
759 if ($msginfo->{trusted}) {
760 my $hide = $pmg_cfg->get('mail', 'hide_received');
761 $entity->head->delete("Received") if $hide;
762 }
763
764 $matching_rules = $self->apply_rules($queue, $msginfo, $entity, $ldap);
765 };
766
767 my $err = $@;
768
769 $self->{errors} = $queue->{errors};
770
771 # restart on error
772 $self->{errors} = 1 if $err;
773
774 $queue->close ();
775
776 die $err if $err;
777
778 my ($csec_end, $usec_end) = gettimeofday ();
779 my $time_total =
780 int (($csec_end-$csec)*1000 + ($usec_end - $usec)/1000);
781
782 # PHASE 5 - log statistics
783 # on error: log error messages
784
785 eval {
786 my $dbh = $self->{ruledb}->{dbh};
787
788 my $where = "";
789 foreach my $rid (@$matching_rules) {
790 $where .= $where ? " OR ID = $rid" : "ID = $rid";
791 }
792
793 $dbh->do ("UPDATE Rule SET Count = Count + 1 WHERE $where") if $where;
794
795 my $insert_cmds = "SELECT nextval ('cstatistic_id_seq');INSERT INTO CStatistic " .
796 "(CID, RID, ID, Time, Bytes, Direction, Spamlevel, VirusInfo, PTime, Sender) VALUES (" .
797 "$lcid, currval('cstatistic_id_seq'), currval('cstatistic_id_seq'),";
798
799 $insert_cmds .= $queue->{rtime} . ',';
800 $insert_cmds .= $queue->{bytes} . ',';
801 $insert_cmds .= $dbh->quote($msginfo->{trusted} ? 0 : 1) . ',';
802 $insert_cmds .= ($queue->{sa_score} || 0) . ',';
803 $insert_cmds .= $dbh->quote($queue->{vinfo}) . ',';
804 $insert_cmds .= $time_total . ',';
805 $insert_cmds .= $dbh->quote(encode('UTF-8', $msginfo->{sender})) . ');';
806
807 foreach my $r (@{$msginfo->{targets}}) {
808 my $tmp = $dbh->quote(encode('UTF-8',$r));
809 my $blocked = $queue->{status}->{$r} eq 'blocked' ? 1 : 0;
810 $insert_cmds .= "INSERT INTO CReceivers (CStatistic_CID, CStatistic_RID, Receiver, Blocked) " .
811 "VALUES ($lcid, currval ('cstatistic_id_seq'), $tmp, '$blocked'); ";
812 }
813
814 $dbh->do($insert_cmds);
815 };
816 # save $err (because log clears $@)
817 $err = $@;
818
819 $time_total = $time_total/1000;
820
821 my $ptspam = ($queue->{ptime_spam} || 0)/1000;
822 my $ptclam = ($queue->{ptime_clam} || 0)/1000;
823 my $ptcustom = ($queue->{ptime_custom} || 0)/1000;
824
825 $self->log(3, "$queue->{logid}: processing time: ${time_total} seconds ($ptspam, $ptclam, $ptcustom)");
826
827 $msginfo->{test_fh}->close if $opt_testmode;
828
829 die $err if $err;
830 }
831
832 my $initial_memory_usage;
833
834 sub process_request {
835 my $self = shift;
836 my $prop = $self->{server};
837 my $sock = $prop->{client};
838
839 eval {
840
841 # make sure the ldap cache is up to date
842 $self->{ldap}->update (1);
843
844 $self->load_config() if $self->{reload_config};
845
846 $self->{trusted} = 0;
847 if ($prop->{sockport} == $opt_int_port && !$opt_untrusted) {
848 $self->{trusted} = 1;
849 }
850
851 my $smtp = PMG::SMTP->new ($sock);
852
853 my $maxcount = $max_requests - $prop->{requests};
854
855 my $count = $smtp->loop (\&handle_smtp, $self, $maxcount);
856 if ($count > 1) {
857 $prop->{requests} += $count - 1;
858 }
859 };
860
861 my $err = $@;
862
863 $self->log (0, $err) if $err;
864
865 kill(15, $prop->{ppid}) if $opt_testmode;
866
867 my $mem = PVE::ProcFSTools::read_memory_usage();
868 if (!defined($initial_memory_usage) || ($prop->{requests} < 10)) {
869 $initial_memory_usage = $mem->{resident};
870 }
871
872 if ($opt_testmode) {
873 $self->log (0, "memory usage: $mem->{size} bytes");
874 } else {
875 if ($self->{errors}) {
876 $self->log (0, "fast exit because of errors (free $mem->{size} bytes)");
877 $self->done (1);
878 } else {
879 my $diff = $mem->{resident} - $initial_memory_usage;
880 if ($diff > 5*1024*1024) {
881 $self->log (0, "fast exit to reduce server load (free $diff bytes)");
882 $self->done (1);
883 }
884 }
885 }
886
887 $self->done (1) if $err;
888 }
889
890 # test sig_hup with: for ((;;)) ;do kill -HUP `cat /run/${prog_name}.pid`; done;
891 # wrapper to avoid multiple calls to sig_hup
892 sub sig_hup {
893 my $self = shift;
894 my $prop = $self->{server};
895
896 return if defined ($prop->{_HUP}); # do not call twice
897
898 $self->SUPER::sig_hup();
899 }
900
901 sub restart_close_hook {
902 my $self = shift;
903
904 my $sig_set = POSIX::SigSet->new;
905 $sig_set->addset (&POSIX::SIGHUP);
906 $sig_set->addset (&POSIX::SIGCHLD); # to avoid zombies
907 my $old_sig_set = POSIX::SigSet->new();
908
909 sigprocmask (SIG_BLOCK, $sig_set, $old_sig_set);
910 }
911
912 sub pre_server_close_hook {
913 my $self = shift;
914 my $prop = $self->{server};
915
916 if (defined $prop->{_HUP}) {
917 undef $prop->{pid_file_unlink};
918 }
919
920 if (defined $prop->{children}) {
921 foreach my $pid (keys %{$prop->{children}}) {
922 kill (1, $pid); # HUP children
923 }
924 }
925
926 # nicely shutdown children (give them max 30 seconds to shut down)
927 my $previous_alarm = alarm(30);
928 eval {
929 local $SIG{ALRM} = sub { die "Timed Out!\n" };
930
931 my $pid;
932 1 while ((($pid = waitpid (-1, 0)) > 0) || ($! == EINTR));
933
934 alarm(0); # avoid race
935 };
936 alarm ($previous_alarm);
937 }
938
939 # initialize mime system before fork
940 xdg_mime_get_mime_type_for_file ($0);
941
942 my $server = bless {
943 server => $server_attr,
944 };
945
946 if (!$opt_testmode) {
947 $server->run ();
948 } else {
949 if (fork) {
950 $server->run();
951 } else {
952
953 my $sender ='sender@pmg.example';
954 my $targets = [
955 'target1@pmg.example',
956 'target2@pmg.example',
957 'target3@pmg.example',
958 ];
959
960 my $smtp;
961 while (!$smtp) {
962 $smtp = Net::SMTP->new ('127.0.0.1', Port => 10023);
963 last if $smtp;
964 usleep(10);
965 }
966
967 # syslog ('info', "connected to " . $smtp->domain);
968
969 $smtp->mail ($sender);
970 $smtp->to (@$targets);
971
972 $smtp->data();
973
974 open (TMP, $opt_testmode) ||
975 die "unable to upen file '$opt_testmode' - $! :ERROR";
976 while (<TMP>) {
977 $smtp->datasend ($_);
978 }
979 close TMP;
980
981 $smtp->datasend ("\n");
982 $smtp->dataend ();
983
984 $smtp->quit;
985 }
986 }
987
988 exit (0);
989
990 __END__
991
992 =head1 NAME
993
994 pmg-smtp-filter - the Proxmox mail filter
995
996 =head1 SYNOPSIS
997
998 pmg-smtp-filter [-u] [-t testfile]
999
1000 =head1 DESCRIPTION
1001
1002 Documentation is available at www.proxmox.com