]> git.proxmox.com Git - pmg-api.git/blame - src/bin/pmg-smtp-filter
smtp-filter: whitespace and indentation clean-ups
[pmg-api.git] / src / bin / pmg-smtp-filter
CommitLineData
b429250e 1#!/usr/bin/perl
6f4aeba1
DM
2
3use strict;
f62194b2
DM
4use warnings;
5
6f4aeba1 6use Carp;
c53efc6e 7use Encode qw(encode);
6f4aeba1 8use Getopt::Long;
21853580 9use Time::HiRes qw (usleep gettimeofday tv_interval);
6f4aeba1
DM
10use POSIX qw(:sys_wait_h errno_h signal_h);
11
12use MIME::Parser;
6296d93f 13use MIME::WordDecoder qw(mime_to_perl_string);
6f4aeba1
DM
14use File::Path;
15use Net::Server::PreFork;
16use Net::Server::SIG qw(register_sig check_sigs);
97662001
DM
17use Net::SMTP;
18
6f4aeba1
DM
19use Fcntl ':flock';
20use File::Basename;
6f4aeba1 21use Xdgmime;
f62194b2
DM
22
23use PVE::SafeSyslog;
24use PVE::ProcFSTools;
25use PVE::INotify;
6f4aeba1
DM
26
27use Mail::SpamAssassin;
28use Mail::SpamAssassin::NetSet;
6f4aeba1 29
f62194b2
DM
30use PMG::pmgcfg;
31use PMG::Utils;
32use PMG::Cluster;
9f67f5b3 33use PMG::ClusterConfig;
6f4aeba1 34
f62194b2
DM
35use PMG::DBTools;
36use PMG::RuleDB;
37use PMG::RuleCache;
38use PMG::ModGroup;
39use PMG::AtomicFile;
7b3c53bd 40use PMG::LDAPConfig;
f62194b2
DM
41use PMG::LDAPSet;
42use PMG::Config;
a43bcf61 43use PMG::MailQueue;
91a5af02 44use PMG::Unpack;
521dca53 45use PMG::SMTP;
6f4aeba1 46
521dca53
DM
47use PMG::Unpack;
48use PMG::Statistic;
f62194b2
DM
49
50use base qw(Net::Server::PreFork);
6f4aeba1 51
c2c21ccf
SI
52$ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
53
54delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
55
6f4aeba1
DM
56my $opt_commandline = [$0, @ARGV];
57my $opt_max_dequeue = 1;
dff363d9 58my $opt_dequeue_time = 30;
6f4aeba1
DM
59
60my $opt_ext_port = 10024;
61my $opt_int_port = 10023;
62my $opt_inject_port = 10025;
63
64my $opt_testmode;
65my $opt_untrusted;
66my $opt_pidfile;
67my $opt_database;
68
e646f7ca
DM
69my $prog_name = 'pmg-smtp-filter';
70
71initlog($prog_name, 'mail');
6f4aeba1 72
e952aea7
TL
73if (!GetOptions(
74 'testmode=s' => \$opt_testmode,
75 'pidfile=s' => \$opt_pidfile,
76 'untrusted' => \$opt_untrusted,
77 'database=s' => \$opt_database
78)) {
6f4aeba1
DM
79 die "usage error\n";
80 exit (-1);
81}
82
83e9f427 83$opt_pidfile = "/run/${prog_name}.pid" if !$opt_pidfile;
6f4aeba1
DM
84
85my $max_servers = 1;
86my $min_servers = 1;
87my $min_spare_servers = 0;
88my $max_spare_servers = 0;
89my $max_requests = 1;
90
91if (!$opt_testmode) {
f62194b2
DM
92 my $pmg_cfg = PMG::Config->new();
93
ac5d1312 94 my $demo = $pmg_cfg->get('admin', 'demo');
6f4aeba1
DM
95
96 if ($demo) {
97 syslog ('info', 'demo mode detected - not starting server');
98 exit (0);
99 }
100
f4027a70
TL
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
f62194b2 107 $max_servers = $pmg_cfg->get('mail', 'max_filters') + 2;
6f4aeba1
DM
108 $min_servers = 2;
109 $min_spare_servers = 1;
110 $max_spare_servers = 4;
111 $max_requests = 20;
112}
113
2da9c7bf
TL
114print "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
6f4aeba1
DM
117$opt_max_dequeue = 0 if $opt_testmode;
118
119my $daemonize = 1;
120if (defined ($ENV{BOUND_SOCKETS})) {
121 $daemonize = undef;
122}
123
124my $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
144my $database;
145
146if (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
160sub 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 = {
3650871c 171 'SUBJECT' => PMG::Utils::decode_rfc1522($entity->head->get ('subject', 0) || 'No Subject'),
6f4aeba1
DM
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),
ac5d1312 180 'ADMIN' => $self->{pmg_cfg}->get('admin', 'email'),
6f4aeba1
DM
181 'HOST' => $msginfo->{hostname},
182 'DOMAIN' => $msginfo->{domain},
183 'FQDN' => $msginfo->{fqdn},
184 'MSGID' => $queue->{msgid},
1c15ce0f 185 'VERSION' => PMG::pmgcfg::package() . "/" . PMG::pmgcfg::release() . "/" . PMG::pmgcfg::repoid(),
6f4aeba1
DM
186 };
187
188 $vars->{__spaminfo} = $spaminfo;
189
190 if ($opt_testmode) {
4c4fec6b 191 if ($queue->{vinfo_clam} || $queue->{vinfo_avast} || $queue->{vinfo_custom}) {
6f4aeba1
DM
192 $vars->{'VIRUS_INFO'} = "Virus Info:";
193 $vars->{'VIRUS_INFO'} .= " clam: $queue->{vinfo_clam}" if $queue->{vinfo_clam};
6ccbc37f 194 $vars->{'VIRUS_INFO'} .= " avast: $queue->{vinfo_avast}" if $queue->{vinfo_avast};
4c4fec6b 195 $vars->{'VIRUS_INFO'} .= " custom: $queue->{vinfo_custom}" if $queue->{vinfo_custom};
6f4aeba1
DM
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) {
ab2d0e56 222 $sa_text .= sprintf ("%-22s %6s %s\n", $s->{rule}, 1, $s->{desc} || '-');
6f4aeba1 223 } else {
ab2d0e56 224 $sa_text .= sprintf ("%-22s %6s %s\n", $s->{rule}, $s->{score}, $s->{desc} || '-');
6f4aeba1
DM
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
238sub 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;
90ce7abb 245 my %rule_spaminfo;
6f4aeba1
DM
246 my $matching_rules = [];
247
248 my $rulecache = $self->{rulecache};
249 my $rules = $rulecache->rules ();
250 my $dbh = $self->{ruledb}->{dbh};
f62194b2
DM
251
252 # first, we remove all conditional written 'X-' header attributes
6f4aeba1
DM
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) {
521dca53 261 if ($action->isa ("PMG::RuleDB::ModField")) {
6f4aeba1
DM
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
90ce7abb 281 my ($marks, $spaminfo) =
6f4aeba1
DM
282 $rulecache->what_match ($rule->{id}, $queue, $entity, $msginfo, $dbh);
283
90ce7abb
DC
284 $rule_marks{$rule->{id}} = $marks;
285 $rule_spaminfo{$rule->{id}} = $spaminfo;
286
6f4aeba1
DM
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});
6f4aeba1
DM
295 next if !$rulecache->to_match ($rule->{id}, $target, $ldap);
296
297 $final->{$target} = $fin;
298
299 push @{$rule_targets{$rule->{id}}}, $target;
f62194b2 300 }
6f4aeba1
DM
301 }
302
303 # Compute rule_info (summary about matching rule)
f62194b2 304 # this can be used for debugging
6f4aeba1
DM
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";
f62194b2 315 }
6f4aeba1
DM
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}) {
2d611b3b 324 my $vars = $self->get_prox_vars($queue, $entity, $msginfo, undef, [], undef);
6f4aeba1 325 my $fh = $msginfo->{test_fh};
2d611b3b 326 print $fh $rule_info;
6f4aeba1
DM
327 }
328
329 # apply actions
330
f62194b2 331 my $mod_group = PMG::ModGroup->new($entity, $msginfo->{targets});
6f4aeba1
DM
332
333 foreach my $rule (@$rules) {
334 my $targets = $rule_targets{$rule->{id}};
335 next if !$targets;
f62194b2 336
ab2d0e56 337 my $vars = $self->get_prox_vars (
90ce7abb 338 $queue, $entity, $msginfo, $rule, $rule_targets{$rule->{id}}, $rule_spaminfo{$rule->{id}});
6f4aeba1 339
ab2d0e56 340 my @sorted_actions = sort {$a->priority <=> $b->priority} @{$rule_actions{$rule->{id}}};
f62194b2 341
6f4aeba1 342 foreach my $action (@sorted_actions) {
ab2d0e56
TL
343 $action->execute(
344 $queue, $self->{ruledb}, $mod_group, $rule_targets{$rule->{id}}, $msginfo, $vars,
90ce7abb 345 $rule_marks{$rule->{id}}, $ldap
ab2d0e56 346 );
6f4aeba1
DM
347 last if $action->final;
348 }
349 }
350
ab2d0e56 351 # we deliver all mail not matched by any rule (default action = accept)
6f4aeba1
DM
352 my $unmatched;
353 foreach my $target (@{$msginfo->{targets}}) {
354 next if $final->{$target};
355
356 push @$unmatched, $target;
357 }
358
359 if ($unmatched) {
521dca53 360 my $accept = PMG::RuleDB::Accept->new ();
f62194b2 361 $accept->execute ($queue, $self->{ruledb}, $mod_group, $unmatched,
ecf08b56 362 $msginfo, { RULE => 'default-accept' }, undef);
6f4aeba1
DM
363 }
364
365 return $matching_rules;
366}
367
f62194b2 368# reload ruledb and pmg config
6f4aeba1
DM
369sub load_config {
370 my $self = shift;
371 my $prop = $self->{server};
372
373 if ($self->{ruledb}) {
76bf5338 374 $self->log ('info', "reloading configuration $database");
6f4aeba1
DM
375 $self->{ruledb}->close ();
376 }
377
f62194b2
DM
378 $self->{pmg_cfg} = PMG::Config->new();
379 $self->{cinfo} = PVE::INotify::read_file("cluster.conf");
6f4aeba1 380
ab6aa17b
DM
381 # create spool directories
382 PMG::MailQueue::create_spooldirs($self->{cinfo}->{local}->{cid});
383
6f4aeba1 384 eval {
f62194b2
DM
385 my $dbh = PMG::DBTools::open_ruledb ($database);
386 $self->{ruledb} = PMG::RuleDB->new ($dbh);
6f4aeba1
DM
387
388 # load rulecache
f62194b2 389 $self->{rulecache} = PMG::RuleCache->new ($self->{ruledb});
6f4aeba1
DM
390 };
391
392 my $err = $@;
393
394 if ($err) {
395 sleep (10); # reduce restart rate when postgres is down
396 die $err;
397 }
398
f62194b2 399 # create LDAP object
7b3c53bd
DM
400 my $ldapconf = PVE::INotify::read_file('pmg-ldap.conf');
401 $self->{ldap} = PMG::LDAPSet->new_from_ldap_cfg($ldapconf, 1);
6f4aeba1 402
f62194b2 403 $self->{reload_config} = 0;
6f4aeba1
DM
404}
405
f62194b2
DM
406my $syslog_map = {
407 0 => 'err',
408 1 => 'warning',
409 2 => 'notice',
410 3 => 'info',
411 4 => 'debug'
412};
413
6f4aeba1
DM
414sub log {
415 my ($self, $level, $msg, @therest) = @_;
416 my $prop = $self->{server};
417
418 return if $level =~ /^\d+$/ && $level > $prop->{log_level};
419
f62194b2 420 $level = $syslog_map->{$level} || $level;
6f4aeba1
DM
421 if (@therest) {
422 syslog($level, $msg, @therest);
423 } else {
424 syslog ($level, $msg);
425 }
426}
427
428sub pre_loop_hook {
429 my $self = shift;
430 my $prop = $self->{server};
431
432 $prop->{log_level} = 3;
433
76bf5338 434 $self->log ('info', "Filter daemon (re)started (max. $max_servers processes)");
6f4aeba1 435
521dca53 436 eval { PMG::MailQueue::cleanup_active(); };
6f4aeba1
DM
437 $self->log (0, "Cleanup failures: $@") if $@;
438
439 my $sig_set = POSIX::SigSet->new;
f62194b2
DM
440 $sig_set->addset (&POSIX::SIGHUP);
441 $sig_set->addset (&POSIX::SIGCHLD);
6f4aeba1
DM
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
f62194b2 448 my $pmg_cfg = PMG::Config->new();
e5b31a61 449 $pmg_cfg->write_smtp_filter_config();
f62194b2
DM
450
451 # Note: you need to restart the daemon when you change 'rbl_checks'
452 my $rbl_checks = $pmg_cfg->get('spam', 'rbl_checks');
6f4aeba1
DM
453
454 $self->{sa} = Mail::SpamAssassin->new ({
455 debug => 0,
f62194b2 456 local_tests_only => $opt_testmode || !$rbl_checks,
6f4aeba1
DM
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);
e646f7ca 467 initlog ($prog_name, 'mail');
6f4aeba1
DM
468
469 $SIG{'USR1'} = sub {
470 # reloading server configuration
471 if (defined $prop->{children}) {
472 foreach my $pid (keys %{$prop->{children}}) {
1359baef 473 kill (10, $pid); # SIGUSR1 children
6f4aeba1
DM
474 }
475 }
476 }
477}
478
479sub child_init_hook {
480 my $self = shift;
481
e646f7ca 482 $0 = "$prog_name child";
6f4aeba1
DM
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 {
f62194b2 497 $self->{reload_config} = 1;
6f4aeba1
DM
498 }
499}
500
501sub child_finish_hook {
502 my $self = shift;
f62194b2 503
6f4aeba1
DM
504 # $self->log (3, "finish child");
505 $self->{ruledb}->close () if $self->{ruledb};
506}
507
dff363d9
DM
508my $last_dequeue_time = 0;
509
6f4aeba1
DM
510sub run_dequeue {
511 my $self = shift;
512
dff363d9
DM
513 my $err;
514
ab2d0e56 515 # do database maintenance here, this is called every 30 secends
6f4aeba1 516
ab2d0e56 517 eval { PMG::Utils::update_node_status_rrd() };
dff363d9 518 if ($err = $@) {
b902c0b8 519 $self->log(0, "ERROR: $err");
dff363d9
DM
520 # continue
521 }
522
de199535
DM
523 my $ctime = time();
524 my $tdiff = $ctime - $last_dequeue_time;
525
526 # return if tdiff less than 2 minutes
dff363d9 527 return if $tdiff < 2*60;
de199535
DM
528 $last_dequeue_time = $ctime;
529
1359baef 530 $self->log (2, "starting database maintenance");
6f4aeba1
DM
531
532 my ($csec, $usec) = gettimeofday ();
533
f62194b2
DM
534 my $cinfo = PVE::INotify::read_file("cluster.conf");
535
ab2d0e56 536 my $dbh = eval { PMG::DBTools::open_ruledb($database) };
dff363d9 537 if ($err = $@) {
b902c0b8 538 $self->log (0, "ERROR: $err");
6f4aeba1
DM
539 return;
540 }
541
ab2d0e56 542 eval { PMG::Statistic::update_stats($dbh, $cinfo) };
6f4aeba1
DM
543 $err = $@;
544
6f4aeba1 545 if ($err) {
b902c0b8 546 $self->log (0, $err);
6f4aeba1 547 } else {
ab2d0e56
TL
548 my ($csec_end, $usec_end) = gettimeofday ();
549 my $ptime = int (($csec_end - $csec) * 1000 + ($usec_end - $usec) / 1000);
1359baef 550 $self->log (2, "end database maintenance ($ptime ms)");
6f4aeba1
DM
551 }
552
553 $dbh->disconnect() if $dbh;
554}
555
556
557sub unpack_entity {
558 my ($self, $unpack, $entity, $msginfo, $queue) = @_;
559
ab2d0e56 560 my ($magic, $path) = $entity->@{'PMX_magic_ct', 'PMX_decoded_path'};
6f4aeba1 561
ab2d0e56 562 if ($magic && $path) {
6f4aeba1
DM
563 my $filename = basename ($path);
564
521dca53 565 if (PMG::Unpack::is_archive ($magic)) {
6f4aeba1
DM
566 $self->log (3, "$queue->{logid}: found archive '$filename' ($magic)");
567
568 my $start = [gettimeofday];
569
570 $unpack->{mime} = {};
571
ab2d0e56 572 eval { $unpack->unpack_archive ($path, $magic) };
6f4aeba1
DM
573 $self->log (3, "$queue->{logid}: unpack failed - $@") if $@;
574
575 $entity->{PMX_content_types} = $unpack->{mime};
29d30ef8 576 $entity->{PMX_filenames} = $unpack->{filenames};
f62194b2 577
6f4aeba1
DM
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
ab2d0e56 585 my $elapsed = int(tv_interval($start) * 1000);
6f4aeba1
DM
586 $self->log (3, "$queue->{logid}: unpack archive '$filename' done ($elapsed ms)");
587 }
588 }
589
ab2d0e56 590 for my $part ($entity->parts) {
6f4aeba1
DM
591 $self->unpack_entity ($unpack, $part, $msginfo, $queue);
592 }
593
594}
595
596sub handle_smtp {
597 my ($self, $smtp) = @_;
598
599 my ($csec, $usec) = gettimeofday ();
600
601 my $queue;
602 my $msginfo = {};
f62194b2 603 my $pmg_cfg = $self->{pmg_cfg};
6f4aeba1
DM
604 my $ldap = $self->{ldap};
605 my $cinfo = $self->{cinfo};
606 my $lcid = $cinfo->{local}->{cid};
f62194b2 607
ab2d0e56 608 $msginfo->{test_fh} = PMG::AtomicFile->new("testresult.out", "w") if $opt_testmode;
6f4aeba1
DM
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};
cda67dee
DM
618 $queue->{clamav_heuristic_score} =
619 $opt_testmode ? 100 : $pmg_cfg->get('spam', 'clamav_heuristic_score');
6f4aeba1 620
f62194b2 621 $queue->{lic_valid} = 1;
6f4aeba1
DM
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};
ad1c6bce 630 $msginfo->{param} = $smtp->{param};
6f4aeba1 631
7ea41925
SI
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
f62194b2
DM
639 $msginfo->{hostname} = PVE::INotify::nodename();
640 my $resolv = PVE::INotify::read_file('resolvconf');
641
642 $msginfo->{domain} = $resolv->{search};
da14f4e1
ML
643 $msginfo->{fqdn} = $msginfo->{hostname};
644 $msginfo->{fqdn} .= ".$msginfo->{domain}" if $msginfo->{domain};
6f4aeba1 645 $msginfo->{lcid} = $lcid;
f62194b2 646
6f4aeba1
DM
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
6f4aeba1 661
f62194b2
DM
662 my $maxfiles = $pmg_cfg->get('clamav', 'archivemaxfiles');
663
20f69ed0
DC
664 my ($entity, $max_aid) = $queue->parse_mail($maxfiles);
665 $msginfo->{max_aid} = $max_aid;
6f4aeba1
DM
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
4c4fec6b
SI
673 # run custom script first
674 my ($vinfo, $custom_spaminfo) = PMG::Utils::analyze_custom_check(
f62194b2 675 $queue, $queue->{dataname}, $pmg_cfg, $opt_testmode);
6f4aeba1 676
4c4fec6b
SI
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);
0d5209bf 681
4c4fec6b
SI
682 if ($vinfo && $vinfo =~ m/^Heuristics\.(.+)$/) {
683 my $hit = $1;
684 $queue->{clamav_heuristic} = $hit;
685 $vinfo = undef;
686 }
687 }
0d5209bf
DM
688 $queue->{vinfo} = $vinfo;
689
6f4aeba1
DM
690 # always add this headers to incoming mails
691 # to enable user to report false negatives
692 if (!$msginfo->{trusted}) {
6f4aeba1
DM
693 if ($queue->{vinfo}) {
694 $entity->head->replace('X-Proxmox-VInfo', $queue->{vinfo});
695 }
6f4aeba1
DM
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.
f62194b2 702 # Disadvantage is that we need to unpack more than
6f4aeba1 703 # once (bad performance).
f62194b2 704
6f4aeba1
DM
705 # should we scan content types inside archives
706
6f4aeba1
DM
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];
f62194b2 724
6f4aeba1
DM
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
521dca53
DM
731 $unpack = PMG::Unpack->new (
732 tmpdir => $decdir,
733 timeout => 30,
734 ctonly => 1, # only detect CTs
735 maxrec => -4,
736 maxfiles => $maxfiles);
6f4aeba1 737
f62194b2 738 $self->unpack_entity ($unpack, $entity, $msginfo, $queue);
6f4aeba1
DM
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)
f62194b2 754 $msginfo->{maxspamsize} = $pmg_cfg->get('spam', 'maxspamsize');
6f4aeba1
DM
755 if ($msginfo->{maxspamsize} <= 1024*64) {
756 $msginfo->{maxspamsize} = 1024*64;
757 }
758
759 if ($msginfo->{trusted}) {
f62194b2 760 my $hide = $pmg_cfg->get('mail', 'hide_received');
6f4aeba1
DM
761 $entity->head->delete("Received") if $hide;
762 }
763
f62194b2 764 $matching_rules = $self->apply_rules($queue, $msginfo, $entity, $ldap);
6f4aeba1 765 };
f62194b2 766
6f4aeba1
DM
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 ();
f62194b2 779 my $time_total =
6f4aeba1
DM
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};
2579281e 787
6f4aeba1
DM
788 my $where = "";
789 foreach my $rid (@$matching_rules) {
790 $where .= $where ? " OR ID = $rid" : "ID = $rid";
791 }
2579281e
DM
792
793 $dbh->do ("UPDATE Rule SET Count = Count + 1 WHERE $where") if $where;
6f4aeba1
DM
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 (" .
2579281e 797 "$lcid, currval('cstatistic_id_seq'), currval('cstatistic_id_seq'),";
6f4aeba1
DM
798
799 $insert_cmds .= $queue->{rtime} . ',';
800 $insert_cmds .= $queue->{bytes} . ',';
2579281e 801 $insert_cmds .= $dbh->quote($msginfo->{trusted} ? 0 : 1) . ',';
6f4aeba1 802 $insert_cmds .= ($queue->{sa_score} || 0) . ',';
2579281e 803 $insert_cmds .= $dbh->quote($queue->{vinfo}) . ',';
6f4aeba1 804 $insert_cmds .= $time_total . ',';
c53efc6e 805 $insert_cmds .= $dbh->quote(encode('UTF-8', $msginfo->{sender})) . ');';
6f4aeba1
DM
806
807 foreach my $r (@{$msginfo->{targets}}) {
c53efc6e 808 my $tmp = $dbh->quote(encode('UTF-8',$r));
6f4aeba1
DM
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
2579281e 814 $dbh->do($insert_cmds);
6f4aeba1 815 };
6f4aeba1
DM
816 # save $err (because log clears $@)
817 $err = $@;
818
819 $time_total = $time_total/1000;
820
821 my $ptspam = ($queue->{ptime_spam} || 0)/1000;
6f4aeba1 822 my $ptclam = ($queue->{ptime_clam} || 0)/1000;
4c4fec6b 823 my $ptcustom = ($queue->{ptime_custom} || 0)/1000;
6f4aeba1 824
4c4fec6b 825 $self->log(3, "$queue->{logid}: processing time: ${time_total} seconds ($ptspam, $ptclam, $ptcustom)");
6f4aeba1
DM
826
827 $msginfo->{test_fh}->close if $opt_testmode;
828
2579281e 829 die $err if $err;
6f4aeba1
DM
830}
831
ab6aa17b 832my $initial_memory_usage;
6f4aeba1
DM
833
834sub 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
f62194b2 844 $self->load_config() if $self->{reload_config};
6f4aeba1
DM
845
846 $self->{trusted} = 0;
847 if ($prop->{sockport} == $opt_int_port && !$opt_untrusted) {
848 $self->{trusted} = 1;
849 }
850
521dca53 851 my $smtp = PMG::SMTP->new ($sock);
6f4aeba1
DM
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 };
f62194b2 860
6f4aeba1
DM
861 my $err = $@;
862
863 $self->log (0, $err) if $err;
864
24244199 865 kill(15, $prop->{ppid}) if $opt_testmode;
6f4aeba1 866
f62194b2 867 my $mem = PVE::ProcFSTools::read_memory_usage();
ab6aa17b
DM
868 if (!defined($initial_memory_usage) || ($prop->{requests} < 10)) {
869 $initial_memory_usage = $mem->{resident};
870 }
6f4aeba1
DM
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);
ab6aa17b
DM
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 }
6f4aeba1
DM
885 }
886
887 $self->done (1) if $err;
888}
889
83e9f427 890# test sig_hup with: for ((;;)) ;do kill -HUP `cat /run/${prog_name}.pid`; done;
6f4aeba1
DM
891# wrapper to avoid multiple calls to sig_hup
892sub 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
901sub restart_close_hook {
902 my $self = shift;
903
904 my $sig_set = POSIX::SigSet->new;
f62194b2 905 $sig_set->addset (&POSIX::SIGHUP);
6f4aeba1
DM
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
912sub pre_server_close_hook {
913 my $self = shift;
914 my $prop = $self->{server};
915
916 if (defined $prop->{_HUP}) {
f62194b2 917 undef $prop->{pid_file_unlink};
6f4aeba1
DM
918 }
919
920 if (defined $prop->{children}) {
921 foreach my $pid (keys %{$prop->{children}}) {
1359baef 922 kill (1, $pid); # HUP children
6f4aeba1
DM
923 }
924 }
925
1359baef 926 # nicely shutdown children (give them max 30 seconds to shut down)
08f49442 927 my $previous_alarm = alarm(30);
6f4aeba1
DM
928 eval {
929 local $SIG{ALRM} = sub { die "Timed Out!\n" };
f62194b2 930
6f4aeba1
DM
931 my $pid;
932 1 while ((($pid = waitpid (-1, 0)) > 0) || ($! == EINTR));
08f49442
DM
933
934 alarm(0); # avoid race
6f4aeba1
DM
935 };
936 alarm ($previous_alarm);
937}
938
939# initialize mime system before fork
940xdg_mime_get_mime_type_for_file ($0);
941
942my $server = bless {
943 server => $server_attr,
944};
945
946if (!$opt_testmode) {
947 $server->run ();
948} else {
949 if (fork) {
21853580 950 $server->run();
6f4aeba1 951 } else {
21853580 952
f913a510 953 my $sender ='sender@pmg.example';
e952aea7
TL
954 my $targets = [
955 'target1@pmg.example',
956 'target2@pmg.example',
957 'target3@pmg.example',
958 ];
6f4aeba1 959
21853580
DM
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 }
6f4aeba1
DM
966
967 # syslog ('info', "connected to " . $smtp->domain);
968
969 $smtp->mail ($sender);
970 $smtp->to (@$targets);
971
972 $smtp->data();
973
f62194b2
DM
974 open (TMP, $opt_testmode) ||
975 die "unable to upen file '$opt_testmode' - $! :ERROR";
6f4aeba1
DM
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
988exit (0);
989
990__END__
991
992=head1 NAME
f62194b2
DM
993
994pmg-smtp-filter - the Proxmox mail filter
6f4aeba1
DM
995
996=head1 SYNOPSIS
997
f62194b2 998pmg-smtp-filter [-u] [-t testfile]
6f4aeba1
DM
999
1000=head1 DESCRIPTION
1001
1002Documentation is available at www.proxmox.com