]> git.proxmox.com Git - pmg-api.git/blame - src/bin/pmg-smtp-filter
pmg-smtp-filter: rename proxtest.com to pmg.example
[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
DM
72
73if (!GetOptions ('testmode=s' => \$opt_testmode,
f62194b2
DM
74 'pidfile=s' => \$opt_pidfile,
75 'untrusted' => \$opt_untrusted,
6f4aeba1
DM
76 'database=s' => \$opt_database)) {
77 die "usage error\n";
78 exit (-1);
79}
80
83e9f427 81$opt_pidfile = "/run/${prog_name}.pid" if !$opt_pidfile;
6f4aeba1
DM
82
83my $max_servers = 1;
84my $min_servers = 1;
85my $min_spare_servers = 0;
86my $max_spare_servers = 0;
87my $max_requests = 1;
88
89if (!$opt_testmode) {
f62194b2
DM
90 my $pmg_cfg = PMG::Config->new();
91
ac5d1312 92 my $demo = $pmg_cfg->get('admin', 'demo');
6f4aeba1
DM
93
94 if ($demo) {
95 syslog ('info', 'demo mode detected - not starting server');
96 exit (0);
97 }
98
f4027a70
TL
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
f62194b2 105 $max_servers = $pmg_cfg->get('mail', 'max_filters') + 2;
6f4aeba1
DM
106 $min_servers = 2;
107 $min_spare_servers = 1;
108 $max_spare_servers = 4;
109 $max_requests = 20;
110}
111
2da9c7bf
TL
112print "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
6f4aeba1
DM
115$opt_max_dequeue = 0 if $opt_testmode;
116
117my $daemonize = 1;
118if (defined ($ENV{BOUND_SOCKETS})) {
119 $daemonize = undef;
120}
121
122my $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
142my $database;
143
144if (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
158sub 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 = {
3650871c 169 'SUBJECT' => PMG::Utils::decode_rfc1522($entity->head->get ('subject', 0) || 'No Subject'),
6f4aeba1
DM
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),
ac5d1312 178 'ADMIN' => $self->{pmg_cfg}->get('admin', 'email'),
6f4aeba1
DM
179 'HOST' => $msginfo->{hostname},
180 'DOMAIN' => $msginfo->{domain},
181 'FQDN' => $msginfo->{fqdn},
182 'MSGID' => $queue->{msgid},
1c15ce0f 183 'VERSION' => PMG::pmgcfg::package() . "/" . PMG::pmgcfg::release() . "/" . PMG::pmgcfg::repoid(),
6f4aeba1
DM
184 };
185
186 $vars->{__spaminfo} = $spaminfo;
187
188 if ($opt_testmode) {
4c4fec6b 189 if ($queue->{vinfo_clam} || $queue->{vinfo_avast} || $queue->{vinfo_custom}) {
6f4aeba1
DM
190 $vars->{'VIRUS_INFO'} = "Virus Info:";
191 $vars->{'VIRUS_INFO'} .= " clam: $queue->{vinfo_clam}" if $queue->{vinfo_clam};
6ccbc37f 192 $vars->{'VIRUS_INFO'} .= " avast: $queue->{vinfo_avast}" if $queue->{vinfo_avast};
4c4fec6b 193 $vars->{'VIRUS_INFO'} .= " custom: $queue->{vinfo_custom}" if $queue->{vinfo_custom};
6f4aeba1
DM
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) {
ab2d0e56 220 $sa_text .= sprintf ("%-22s %6s %s\n", $s->{rule}, 1, $s->{desc} || '-');
6f4aeba1 221 } else {
ab2d0e56 222 $sa_text .= sprintf ("%-22s %6s %s\n", $s->{rule}, $s->{score}, $s->{desc} || '-');
6f4aeba1
DM
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
236sub 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;
90ce7abb 243 my %rule_spaminfo;
6f4aeba1
DM
244 my $matching_rules = [];
245
246 my $rulecache = $self->{rulecache};
247 my $rules = $rulecache->rules ();
248 my $dbh = $self->{ruledb}->{dbh};
f62194b2
DM
249
250 # first, we remove all conditional written 'X-' header attributes
6f4aeba1
DM
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) {
521dca53 259 if ($action->isa ("PMG::RuleDB::ModField")) {
6f4aeba1
DM
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
90ce7abb 279 my ($marks, $spaminfo) =
6f4aeba1
DM
280 $rulecache->what_match ($rule->{id}, $queue, $entity, $msginfo, $dbh);
281
90ce7abb
DC
282 $rule_marks{$rule->{id}} = $marks;
283 $rule_spaminfo{$rule->{id}} = $spaminfo;
284
6f4aeba1
DM
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});
6f4aeba1
DM
293 next if !$rulecache->to_match ($rule->{id}, $target, $ldap);
294
295 $final->{$target} = $fin;
296
297 push @{$rule_targets{$rule->{id}}}, $target;
f62194b2 298 }
6f4aeba1
DM
299 }
300
301 # Compute rule_info (summary about matching rule)
f62194b2 302 # this can be used for debugging
6f4aeba1
DM
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";
f62194b2 313 }
6f4aeba1
DM
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}) {
2d611b3b 322 my $vars = $self->get_prox_vars($queue, $entity, $msginfo, undef, [], undef);
6f4aeba1 323 my $fh = $msginfo->{test_fh};
2d611b3b 324 print $fh $rule_info;
6f4aeba1
DM
325 }
326
327 # apply actions
328
f62194b2 329 my $mod_group = PMG::ModGroup->new($entity, $msginfo->{targets});
6f4aeba1
DM
330
331 foreach my $rule (@$rules) {
332 my $targets = $rule_targets{$rule->{id}};
333 next if !$targets;
f62194b2 334
ab2d0e56 335 my $vars = $self->get_prox_vars (
90ce7abb 336 $queue, $entity, $msginfo, $rule, $rule_targets{$rule->{id}}, $rule_spaminfo{$rule->{id}});
6f4aeba1 337
ab2d0e56 338 my @sorted_actions = sort {$a->priority <=> $b->priority} @{$rule_actions{$rule->{id}}};
f62194b2 339
6f4aeba1 340 foreach my $action (@sorted_actions) {
ab2d0e56
TL
341 $action->execute(
342 $queue, $self->{ruledb}, $mod_group, $rule_targets{$rule->{id}}, $msginfo, $vars,
90ce7abb 343 $rule_marks{$rule->{id}}, $ldap
ab2d0e56 344 );
6f4aeba1
DM
345 last if $action->final;
346 }
347 }
348
ab2d0e56 349 # we deliver all mail not matched by any rule (default action = accept)
6f4aeba1
DM
350 my $unmatched;
351 foreach my $target (@{$msginfo->{targets}}) {
352 next if $final->{$target};
353
354 push @$unmatched, $target;
355 }
356
357 if ($unmatched) {
521dca53 358 my $accept = PMG::RuleDB::Accept->new ();
f62194b2 359 $accept->execute ($queue, $self->{ruledb}, $mod_group, $unmatched,
ecf08b56 360 $msginfo, { RULE => 'default-accept' }, undef);
6f4aeba1
DM
361 }
362
363 return $matching_rules;
364}
365
f62194b2 366# reload ruledb and pmg config
6f4aeba1
DM
367sub load_config {
368 my $self = shift;
369 my $prop = $self->{server};
370
371 if ($self->{ruledb}) {
76bf5338 372 $self->log ('info', "reloading configuration $database");
6f4aeba1
DM
373 $self->{ruledb}->close ();
374 }
375
f62194b2
DM
376 $self->{pmg_cfg} = PMG::Config->new();
377 $self->{cinfo} = PVE::INotify::read_file("cluster.conf");
6f4aeba1 378
ab6aa17b
DM
379 # create spool directories
380 PMG::MailQueue::create_spooldirs($self->{cinfo}->{local}->{cid});
381
6f4aeba1 382 eval {
f62194b2
DM
383 my $dbh = PMG::DBTools::open_ruledb ($database);
384 $self->{ruledb} = PMG::RuleDB->new ($dbh);
6f4aeba1
DM
385
386 # load rulecache
f62194b2 387 $self->{rulecache} = PMG::RuleCache->new ($self->{ruledb});
6f4aeba1
DM
388 };
389
390 my $err = $@;
391
392 if ($err) {
393 sleep (10); # reduce restart rate when postgres is down
394 die $err;
395 }
396
f62194b2 397 # create LDAP object
7b3c53bd
DM
398 my $ldapconf = PVE::INotify::read_file('pmg-ldap.conf');
399 $self->{ldap} = PMG::LDAPSet->new_from_ldap_cfg($ldapconf, 1);
6f4aeba1 400
f62194b2 401 $self->{reload_config} = 0;
6f4aeba1
DM
402}
403
f62194b2
DM
404my $syslog_map = {
405 0 => 'err',
406 1 => 'warning',
407 2 => 'notice',
408 3 => 'info',
409 4 => 'debug'
410};
411
6f4aeba1
DM
412sub log {
413 my ($self, $level, $msg, @therest) = @_;
414 my $prop = $self->{server};
415
416 return if $level =~ /^\d+$/ && $level > $prop->{log_level};
417
f62194b2 418 $level = $syslog_map->{$level} || $level;
6f4aeba1
DM
419 if (@therest) {
420 syslog($level, $msg, @therest);
421 } else {
422 syslog ($level, $msg);
423 }
424}
425
426sub pre_loop_hook {
427 my $self = shift;
428 my $prop = $self->{server};
429
430 $prop->{log_level} = 3;
431
76bf5338 432 $self->log ('info', "Filter daemon (re)started (max. $max_servers processes)");
6f4aeba1 433
521dca53 434 eval { PMG::MailQueue::cleanup_active(); };
6f4aeba1
DM
435 $self->log (0, "Cleanup failures: $@") if $@;
436
437 my $sig_set = POSIX::SigSet->new;
f62194b2
DM
438 $sig_set->addset (&POSIX::SIGHUP);
439 $sig_set->addset (&POSIX::SIGCHLD);
6f4aeba1
DM
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
f62194b2 446 my $pmg_cfg = PMG::Config->new();
e5b31a61 447 $pmg_cfg->write_smtp_filter_config();
f62194b2
DM
448
449 # Note: you need to restart the daemon when you change 'rbl_checks'
450 my $rbl_checks = $pmg_cfg->get('spam', 'rbl_checks');
6f4aeba1
DM
451
452 $self->{sa} = Mail::SpamAssassin->new ({
453 debug => 0,
f62194b2 454 local_tests_only => $opt_testmode || !$rbl_checks,
6f4aeba1
DM
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);
e646f7ca 465 initlog ($prog_name, 'mail');
6f4aeba1
DM
466
467 $SIG{'USR1'} = sub {
468 # reloading server configuration
469 if (defined $prop->{children}) {
470 foreach my $pid (keys %{$prop->{children}}) {
1359baef 471 kill (10, $pid); # SIGUSR1 children
6f4aeba1
DM
472 }
473 }
474 }
475}
476
477sub child_init_hook {
478 my $self = shift;
479
e646f7ca 480 $0 = "$prog_name child";
6f4aeba1
DM
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 {
f62194b2 495 $self->{reload_config} = 1;
6f4aeba1
DM
496 }
497}
498
499sub child_finish_hook {
500 my $self = shift;
f62194b2 501
6f4aeba1
DM
502 # $self->log (3, "finish child");
503 $self->{ruledb}->close () if $self->{ruledb};
504}
505
dff363d9
DM
506my $last_dequeue_time = 0;
507
6f4aeba1
DM
508sub run_dequeue {
509 my $self = shift;
510
dff363d9
DM
511 my $err;
512
ab2d0e56 513 # do database maintenance here, this is called every 30 secends
6f4aeba1 514
ab2d0e56 515 eval { PMG::Utils::update_node_status_rrd() };
dff363d9 516 if ($err = $@) {
b902c0b8 517 $self->log(0, "ERROR: $err");
dff363d9
DM
518 # continue
519 }
520
de199535
DM
521 my $ctime = time();
522 my $tdiff = $ctime - $last_dequeue_time;
523
524 # return if tdiff less than 2 minutes
dff363d9 525 return if $tdiff < 2*60;
de199535
DM
526 $last_dequeue_time = $ctime;
527
1359baef 528 $self->log (2, "starting database maintenance");
6f4aeba1
DM
529
530 my ($csec, $usec) = gettimeofday ();
531
f62194b2
DM
532 my $cinfo = PVE::INotify::read_file("cluster.conf");
533
ab2d0e56 534 my $dbh = eval { PMG::DBTools::open_ruledb($database) };
dff363d9 535 if ($err = $@) {
b902c0b8 536 $self->log (0, "ERROR: $err");
6f4aeba1
DM
537 return;
538 }
539
ab2d0e56 540 eval { PMG::Statistic::update_stats($dbh, $cinfo) };
6f4aeba1
DM
541 $err = $@;
542
6f4aeba1 543 if ($err) {
b902c0b8 544 $self->log (0, $err);
6f4aeba1 545 } else {
ab2d0e56
TL
546 my ($csec_end, $usec_end) = gettimeofday ();
547 my $ptime = int (($csec_end - $csec) * 1000 + ($usec_end - $usec) / 1000);
1359baef 548 $self->log (2, "end database maintenance ($ptime ms)");
6f4aeba1
DM
549 }
550
551 $dbh->disconnect() if $dbh;
552}
553
554
555sub unpack_entity {
556 my ($self, $unpack, $entity, $msginfo, $queue) = @_;
557
ab2d0e56 558 my ($magic, $path) = $entity->@{'PMX_magic_ct', 'PMX_decoded_path'};
6f4aeba1 559
ab2d0e56 560 if ($magic && $path) {
6f4aeba1
DM
561 my $filename = basename ($path);
562
521dca53 563 if (PMG::Unpack::is_archive ($magic)) {
6f4aeba1
DM
564 $self->log (3, "$queue->{logid}: found archive '$filename' ($magic)");
565
566 my $start = [gettimeofday];
567
568 $unpack->{mime} = {};
569
ab2d0e56 570 eval { $unpack->unpack_archive ($path, $magic) };
6f4aeba1
DM
571 $self->log (3, "$queue->{logid}: unpack failed - $@") if $@;
572
573 $entity->{PMX_content_types} = $unpack->{mime};
29d30ef8 574 $entity->{PMX_filenames} = $unpack->{filenames};
f62194b2 575
6f4aeba1
DM
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
ab2d0e56 583 my $elapsed = int(tv_interval($start) * 1000);
6f4aeba1
DM
584 $self->log (3, "$queue->{logid}: unpack archive '$filename' done ($elapsed ms)");
585 }
586 }
587
ab2d0e56 588 for my $part ($entity->parts) {
6f4aeba1
DM
589 $self->unpack_entity ($unpack, $part, $msginfo, $queue);
590 }
591
592}
593
594sub handle_smtp {
595 my ($self, $smtp) = @_;
596
597 my ($csec, $usec) = gettimeofday ();
598
599 my $queue;
600 my $msginfo = {};
f62194b2 601 my $pmg_cfg = $self->{pmg_cfg};
6f4aeba1
DM
602 my $ldap = $self->{ldap};
603 my $cinfo = $self->{cinfo};
604 my $lcid = $cinfo->{local}->{cid};
f62194b2 605
ab2d0e56 606 $msginfo->{test_fh} = PMG::AtomicFile->new("testresult.out", "w") if $opt_testmode;
6f4aeba1
DM
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};
cda67dee
DM
616 $queue->{clamav_heuristic_score} =
617 $opt_testmode ? 100 : $pmg_cfg->get('spam', 'clamav_heuristic_score');
6f4aeba1 618
f62194b2 619 $queue->{lic_valid} = 1;
6f4aeba1
DM
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};
ad1c6bce 628 $msginfo->{param} = $smtp->{param};
6f4aeba1 629
7ea41925
SI
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
f62194b2
DM
637 $msginfo->{hostname} = PVE::INotify::nodename();
638 my $resolv = PVE::INotify::read_file('resolvconf');
639
640 $msginfo->{domain} = $resolv->{search};
da14f4e1
ML
641 $msginfo->{fqdn} = $msginfo->{hostname};
642 $msginfo->{fqdn} .= ".$msginfo->{domain}" if $msginfo->{domain};
6f4aeba1 643 $msginfo->{lcid} = $lcid;
f62194b2 644
6f4aeba1
DM
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
6f4aeba1 659
f62194b2
DM
660 my $maxfiles = $pmg_cfg->get('clamav', 'archivemaxfiles');
661
20f69ed0
DC
662 my ($entity, $max_aid) = $queue->parse_mail($maxfiles);
663 $msginfo->{max_aid} = $max_aid;
6f4aeba1
DM
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
4c4fec6b
SI
671 # run custom script first
672 my ($vinfo, $custom_spaminfo) = PMG::Utils::analyze_custom_check(
f62194b2 673 $queue, $queue->{dataname}, $pmg_cfg, $opt_testmode);
6f4aeba1 674
4c4fec6b
SI
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);
0d5209bf 679
4c4fec6b
SI
680 if ($vinfo && $vinfo =~ m/^Heuristics\.(.+)$/) {
681 my $hit = $1;
682 $queue->{clamav_heuristic} = $hit;
683 $vinfo = undef;
684 }
685 }
0d5209bf
DM
686 $queue->{vinfo} = $vinfo;
687
6f4aeba1
DM
688 # always add this headers to incoming mails
689 # to enable user to report false negatives
690 if (!$msginfo->{trusted}) {
6f4aeba1
DM
691 if ($queue->{vinfo}) {
692 $entity->head->replace('X-Proxmox-VInfo', $queue->{vinfo});
693 }
6f4aeba1
DM
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.
f62194b2 700 # Disadvantage is that we need to unpack more than
6f4aeba1 701 # once (bad performance).
f62194b2 702
6f4aeba1
DM
703 # should we scan content types inside archives
704
6f4aeba1
DM
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];
f62194b2 722
6f4aeba1
DM
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
521dca53
DM
729 $unpack = PMG::Unpack->new (
730 tmpdir => $decdir,
731 timeout => 30,
732 ctonly => 1, # only detect CTs
733 maxrec => -4,
734 maxfiles => $maxfiles);
6f4aeba1 735
f62194b2 736 $self->unpack_entity ($unpack, $entity, $msginfo, $queue);
6f4aeba1
DM
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)
f62194b2 752 $msginfo->{maxspamsize} = $pmg_cfg->get('spam', 'maxspamsize');
6f4aeba1
DM
753 if ($msginfo->{maxspamsize} <= 1024*64) {
754 $msginfo->{maxspamsize} = 1024*64;
755 }
756
757 if ($msginfo->{trusted}) {
f62194b2 758 my $hide = $pmg_cfg->get('mail', 'hide_received');
6f4aeba1
DM
759 $entity->head->delete("Received") if $hide;
760 }
761
f62194b2 762 $matching_rules = $self->apply_rules($queue, $msginfo, $entity, $ldap);
6f4aeba1 763 };
f62194b2 764
6f4aeba1
DM
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 ();
f62194b2 777 my $time_total =
6f4aeba1
DM
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};
2579281e 785
6f4aeba1
DM
786 my $where = "";
787 foreach my $rid (@$matching_rules) {
788 $where .= $where ? " OR ID = $rid" : "ID = $rid";
789 }
2579281e
DM
790
791 $dbh->do ("UPDATE Rule SET Count = Count + 1 WHERE $where") if $where;
6f4aeba1
DM
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 (" .
2579281e 795 "$lcid, currval('cstatistic_id_seq'), currval('cstatistic_id_seq'),";
6f4aeba1
DM
796
797 $insert_cmds .= $queue->{rtime} . ',';
798 $insert_cmds .= $queue->{bytes} . ',';
2579281e 799 $insert_cmds .= $dbh->quote($msginfo->{trusted} ? 0 : 1) . ',';
6f4aeba1 800 $insert_cmds .= ($queue->{sa_score} || 0) . ',';
2579281e 801 $insert_cmds .= $dbh->quote($queue->{vinfo}) . ',';
6f4aeba1 802 $insert_cmds .= $time_total . ',';
c53efc6e 803 $insert_cmds .= $dbh->quote(encode('UTF-8', $msginfo->{sender})) . ');';
6f4aeba1
DM
804
805 foreach my $r (@{$msginfo->{targets}}) {
c53efc6e 806 my $tmp = $dbh->quote(encode('UTF-8',$r));
6f4aeba1
DM
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
2579281e 812 $dbh->do($insert_cmds);
6f4aeba1 813 };
6f4aeba1
DM
814 # save $err (because log clears $@)
815 $err = $@;
816
817 $time_total = $time_total/1000;
818
819 my $ptspam = ($queue->{ptime_spam} || 0)/1000;
6f4aeba1 820 my $ptclam = ($queue->{ptime_clam} || 0)/1000;
4c4fec6b 821 my $ptcustom = ($queue->{ptime_custom} || 0)/1000;
6f4aeba1 822
4c4fec6b 823 $self->log(3, "$queue->{logid}: processing time: ${time_total} seconds ($ptspam, $ptclam, $ptcustom)");
6f4aeba1
DM
824
825 $msginfo->{test_fh}->close if $opt_testmode;
826
2579281e 827 die $err if $err;
6f4aeba1
DM
828}
829
ab6aa17b 830my $initial_memory_usage;
6f4aeba1
DM
831
832sub 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
f62194b2 842 $self->load_config() if $self->{reload_config};
6f4aeba1
DM
843
844 $self->{trusted} = 0;
845 if ($prop->{sockport} == $opt_int_port && !$opt_untrusted) {
846 $self->{trusted} = 1;
847 }
848
521dca53 849 my $smtp = PMG::SMTP->new ($sock);
6f4aeba1
DM
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 };
f62194b2 858
6f4aeba1
DM
859 my $err = $@;
860
861 $self->log (0, $err) if $err;
862
24244199 863 kill(15, $prop->{ppid}) if $opt_testmode;
6f4aeba1 864
f62194b2 865 my $mem = PVE::ProcFSTools::read_memory_usage();
ab6aa17b
DM
866 if (!defined($initial_memory_usage) || ($prop->{requests} < 10)) {
867 $initial_memory_usage = $mem->{resident};
868 }
6f4aeba1
DM
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);
ab6aa17b
DM
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 }
6f4aeba1
DM
883 }
884
885 $self->done (1) if $err;
886}
887
83e9f427 888# test sig_hup with: for ((;;)) ;do kill -HUP `cat /run/${prog_name}.pid`; done;
6f4aeba1
DM
889# wrapper to avoid multiple calls to sig_hup
890sub 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
899sub restart_close_hook {
900 my $self = shift;
901
902 my $sig_set = POSIX::SigSet->new;
f62194b2 903 $sig_set->addset (&POSIX::SIGHUP);
6f4aeba1
DM
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
910sub pre_server_close_hook {
911 my $self = shift;
912 my $prop = $self->{server};
913
914 if (defined $prop->{_HUP}) {
f62194b2 915 undef $prop->{pid_file_unlink};
6f4aeba1
DM
916 }
917
918 if (defined $prop->{children}) {
919 foreach my $pid (keys %{$prop->{children}}) {
1359baef 920 kill (1, $pid); # HUP children
6f4aeba1
DM
921 }
922 }
923
1359baef 924 # nicely shutdown children (give them max 30 seconds to shut down)
08f49442 925 my $previous_alarm = alarm(30);
6f4aeba1
DM
926 eval {
927 local $SIG{ALRM} = sub { die "Timed Out!\n" };
f62194b2 928
6f4aeba1
DM
929 my $pid;
930 1 while ((($pid = waitpid (-1, 0)) > 0) || ($! == EINTR));
08f49442
DM
931
932 alarm(0); # avoid race
6f4aeba1
DM
933 };
934 alarm ($previous_alarm);
935}
936
937# initialize mime system before fork
938xdg_mime_get_mime_type_for_file ($0);
939
940my $server = bless {
941 server => $server_attr,
942};
943
944if (!$opt_testmode) {
945 $server->run ();
946} else {
947 if (fork) {
21853580 948 $server->run();
6f4aeba1 949 } else {
21853580 950
f913a510
SI
951 my $sender ='sender@pmg.example';
952 my $targets = ['target1@pmg.example',
953 'target2@pmg.example',
954 'target3@pmg.example'];
6f4aeba1 955
21853580
DM
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 }
6f4aeba1
DM
962
963 # syslog ('info', "connected to " . $smtp->domain);
964
965 $smtp->mail ($sender);
966 $smtp->to (@$targets);
967
968 $smtp->data();
969
f62194b2
DM
970 open (TMP, $opt_testmode) ||
971 die "unable to upen file '$opt_testmode' - $! :ERROR";
6f4aeba1
DM
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
984exit (0);
985
986__END__
987
988=head1 NAME
f62194b2
DM
989
990pmg-smtp-filter - the Proxmox mail filter
6f4aeba1
DM
991
992=head1 SYNOPSIS
993
f62194b2 994pmg-smtp-filter [-u] [-t testfile]
6f4aeba1
DM
995
996=head1 DESCRIPTION
997
998Documentation is available at www.proxmox.com