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