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