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