]> git.proxmox.com Git - pmg-api.git/blame - bin/pmgpolicy
scan_journal_for_rbl_rejects: new helper to extract RBL rejects from journal
[pmg-api.git] / bin / pmgpolicy
CommitLineData
3164123a 1#!/usr/bin/perl
ddaec666
DM
2
3use strict;
3164123a 4use warnings;
ddaec666 5use Getopt::Long;
ddaec666
DM
6use POSIX qw(errno_h signal_h);
7
8use Net::Server::PreForkSimple;
9use Net::DNS::Resolver;
10use Mail::SPF;
11use Fcntl;
12use Fcntl ':flock';
13use IO::Multiplex;
3164123a 14use Time::HiRes qw(gettimeofday);
ddaec666 15
3164123a
DM
16use PVE::INotify;
17use PVE::Tools;
18use PVE::SafeSyslog;
ddaec666 19
3164123a
DM
20use PMG::Utils;
21use PMG::RuleDB;
22use PMG::DBTools;
23use PMG::RuleCache;
24use PMG::Config;
25use PMG::ClusterConfig;
26
27use base qw(Net::Server::PreForkSimple);
ddaec666
DM
28
29my $greylist_delay = 3*60; # greylist window
30my $greylist_lifetime = 3600*24*2; # retry window
31my $greylist_awlifetime = 3600*24*36; # expire window
32
33my $opt_commandline = [$0, @ARGV];
34my $opt_policy_port = 10022;
35my $opt_max_dequeue = 1;
36my $opt_dequeue_time = 60*2;
37
38my $opt_testmode;
39my $opt_pidfile;
40my $opt_database;
41
3164123a
DM
42if (!GetOptions ('pidfile=s' => \$opt_pidfile,
43 'testmode' => \$opt_testmode,
ddaec666
DM
44 'database=s' => \$opt_database)) {
45 die "usage error\n";
46 exit (-1);
47}
48
3164123a 49$opt_pidfile = "/var/run/pmgpolicy.pid" if !$opt_pidfile;
ddaec666
DM
50$opt_max_dequeue = 0 if $opt_testmode;
51
3164123a
DM
52initlog('pmgpolicy', 'mail');
53
54my $max_servers = 5;
ddaec666
DM
55
56if (!$opt_testmode) {
57
3164123a
DM
58 my $pmg_cfg = PMG::Config->new ();
59 my $demo = $pmg_cfg->get('admin', 'demo');
60 $max_servers = $pmg_cfg->get('mail', 'max_policy');
ddaec666
DM
61
62 if ($demo) {
3164123a
DM
63 syslog('info', 'demo mode detected - not starting server');
64 exit(0);
ddaec666
DM
65 }
66}
67
68my $daemonize = 1;
69if (defined ($ENV{BOUND_SOCKETS})) {
70 $daemonize = undef;
71}
72
ddaec666
DM
73
74my $server_attr = {
75 port => [ $opt_policy_port ],
76 host => '127.0.0.1',
77 max_servers => $max_servers,
78 max_dequeue => $opt_max_dequeue,
79 check_for_dequeue => $opt_dequeue_time,
80 log_level => 3,
81 pid_file => $opt_pidfile,
82 commandline => $opt_commandline,
83 no_close_by_child => 1,
84 setsid => $daemonize,
85};
86
87my $database;
88if (defined($opt_database)) {
89 $database = $opt_database;
90} else {
91 $database = "Proxmox_ruledb";
92}
93
94$SIG{'__WARN__'} = sub {
95 my $err = $@;
96 my $t = $_[0];
97 chomp $t;
98 syslog('warning', "WARNING: %s", $t);
99 $@ = $err;
100};
101
102sub run_dequeue {
103 my $self = shift;
104
3164123a 105 $self->log(2, "starting greylist database maintainance");
ddaec666
DM
106
107 my ($csec, $usec) = gettimeofday ();
108
cff666e6 109 my $cinfo = PMG::ClusterConfig->new();
ddaec666 110 my $lcid = $cinfo->{local}->{cid};
3164123a
DM
111 my $role = $cinfo->{local}->{type} // '-';
112
ddaec666 113 my $dbh;
3164123a 114
ddaec666 115 eval {
3164123a 116 $dbh = PMG::DBTools::open_ruledb($database);
ddaec666
DM
117 };
118 my $err = $@;
119
120 if ($err) {
b902c0b8 121 $self->log(0, "ERROR: $err");
ddaec666
DM
122 return;
123 }
124
3164123a 125 my $now = time();
ddaec666
DM
126
127 my $ecount = 0;
128
ddaec666
DM
129 eval {
130
131 $dbh->begin_work;
132
133 # we do not lock the table here to avoid delays
134 # but that is OK, because we only touch expired records
135 # which do not change nornmally
136 ## $dbh->do ("LOCK TABLE CGreylist IN ROW EXCLUSIVE MODE");
137
138 # move expired and undelivered records from Greylist to Statistic
3164123a 139
ddaec666 140 my $rntxt = '';
3164123a 141 if (!$lcid) {
ddaec666
DM
142 $rntxt = "AND CID = 0";
143 } else {
3164123a 144 if ($role eq 'master') {
ddaec666
DM
145 # master is responsible for all non-cluster (deleted) nodes
146 foreach my $rcid (@{$cinfo->{remnodes}}) {
147 $rntxt .= $rntxt ? " AND CID != $rcid" : "AND (CID != $rcid";
148 }
149 $rntxt .= ")" if $rntxt;
150 } else {
151 $rntxt = "AND (CID = 0 OR CID = $lcid)";
152 }
153 }
154
155
156 my $cmds = '';
157
3164123a
DM
158 my $sth = $dbh->prepare(
159 "SELECT distinct instance, sender FROM CGreylist " .
160 "WHERE passed = 0 AND extime < ? $rntxt");
ddaec666
DM
161
162 $sth->execute ($now);
163
164
165 while (my $ref = $sth->fetchrow_hashref()) {
3164123a
DM
166 my $sth2 = $dbh->prepare(
167 "SELECT * FROM CGreylist WHERE instance = ? AND sender = ?");
ddaec666
DM
168 $sth2->execute ($ref->{instance}, $ref->{sender});
169 my $rctime;
170 my @rcvrs;
171 my $bc = 0;
172
173 while (my $ref2 = $sth2->fetchrow_hashref()) {
174 $rctime = $ref2->{rctime} if !$rctime;
175 $bc += $ref2->{blocked};
176 push @rcvrs, $ref2->{receiver};
177 }
178
179 $sth2->finish();
180
181 # hack: sometimes query sth2 does not return anything - maybe a
182 # postgres bug? We simply ignore (when rctime is undefined) it
183 # to avoid problems.
184
185 if ($rctime) {
3164123a
DM
186 $cmds .= "SELECT nextval ('cstatistic_id_seq');" .
187 "INSERT INTO CStatistic " .
ddaec666
DM
188 "(CID, RID, ID, Time, Bytes, Direction, Spamlevel, VirusInfo, PTime, Sender) VALUES (" .
189 "$lcid, currval ('cstatistic_id_seq'), currval ('cstatistic_id_seq'), ";
190
191 my $sl = $bc >= 100000 ? 4 : 5;
192 $cmds .= $rctime . ", 0, '1', $sl, NULL, 0, ";
193 $cmds .= $dbh->quote ($ref->{sender}) . ');';
194
195 foreach my $r (@rcvrs) {
196 my $tmp = $dbh->quote ($r);
197 $cmds .= "INSERT INTO CReceivers (CStatistic_CID, CStatistic_RID, Receiver, Blocked) ".
198 "VALUES ($lcid, currval ('cstatistic_id_seq'), $tmp, '1'); ";
199 }
200 }
201
202 if (length ($cmds) > 100000) {
203 $dbh->do ($cmds);
204 $cmds = '';
205 }
206
ddaec666
DM
207 $ecount++;
208
209 # this produces too much log traffic
210 # my $targets = join (", ", @rcvrs);
211 #my $msg = "expire mail $ref->{instance} from $ref->{sender} to $targets";
b902c0b8 212 #$self->log (0, $msg);
ddaec666
DM
213 }
214
215 $dbh->do ($cmds) if $cmds;
216
217 $sth->finish();
218
219 if ($ecount > 0) {
220 my $msg = "found $ecount expired mails in greylisting database";
221 $self->log (0, $msg);
222 }
223
224 $dbh->do ("DELETE FROM CGreylist WHERE extime < $now");
225
226 $dbh->commit;
227 };
228
229 $err = $@;
230
231 my ($csec_end, $usec_end) = gettimeofday ();
232 my $ptime = int (($csec_end-$csec)*1000 + ($usec_end - $usec)/1000);
233
234 if ($err) {
235 $dbh->rollback if $dbh;
b902c0b8 236 $self->log(0, $err);
ddaec666 237 } else {
3164123a 238 $self->log(2, "end greylist database maintainance ($ptime ms)");
ddaec666
DM
239 }
240
241 $dbh->disconnect() if $dbh;
242}
243
244sub pre_loop_hook {
3164123a 245 my $self = shift;
ddaec666 246
3164123a 247 my $prop = $self->{server};
ddaec666 248
3164123a 249 $prop->{log_level} = 3;
ddaec666 250
3164123a 251 $self->log(0, "Policy daemon (re)started");
ddaec666 252
3164123a
DM
253 $SIG{'USR1'} = sub {
254 # reloading server configuration
255 if (defined $prop->{children}) {
256 foreach my $pid (keys %{$prop->{children}}) {
08f49442 257 kill(10, $pid); # SIGUSR1 childs
3164123a
DM
258 }
259 }
260 };
ddaec666 261
3164123a
DM
262 my $sig_set = POSIX::SigSet->new;
263 $sig_set->addset (&POSIX::SIGHUP);
264 $sig_set->addset (&POSIX::SIGCHLD);
265 my $old_sig_set = POSIX::SigSet->new();
266
267 sigprocmask (SIG_UNBLOCK, $sig_set, $old_sig_set);
ddaec666
DM
268}
269
270sub load_config {
3164123a 271 my $self = shift;
ddaec666 272
3164123a 273 my $prop = $self->{server};
ddaec666 274
3164123a
DM
275 if ($self->{ruledb}) {
276 $self->log(0, "reloading configuration $database");
277 $self->{ruledb}->close();
278 }
ddaec666 279
3164123a 280 my $pmg_cfg = PMG::Config->new ();
3164123a
DM
281 $self->{use_spf} = $pmg_cfg->get('mail', 'spf');
282 $self->{use_greylist} = $pmg_cfg->get('mail', 'greylist');
ddaec666 283
1dc67c8f
DM
284 if ($opt_testmode) {
285 $self->{use_spf} = 1;
286 $self->{use_greylist} = 1;
287 }
288
3164123a 289 my $nodename = PVE::INotify::nodename();
4bb79830 290 $self->{fqdn} = PVE::Tools::get_fqdn($nodename);
ddaec666 291
cff666e6 292 my $cinfo = PMG::ClusterConfig->new();
3164123a
DM
293 my $lcid = $cinfo->{local}->{cid};
294 $self->{cinfo} = $cinfo;
295 $self->{lcid} = $lcid;
ddaec666 296
3164123a 297 my $dbh;
ddaec666 298
3164123a
DM
299 eval {
300 $dbh = PMG::DBTools::open_ruledb($database);
301 $self->{ruledb} = PMG::RuleDB->new($dbh);
302 $self->{rulecache} = PMG::RuleCache->new($self->{ruledb});
303 };
304 if (my $err = $@) {
b902c0b8 305 $self->log(0, "ERROR: unable to load database : $err");
3164123a 306 }
ddaec666 307
3164123a
DM
308 $self->{reload_config} = 0;
309}
ddaec666 310
3164123a
DM
311sub child_init_hook {
312 my $self = shift;
313
314 my $prop = $self->{server};
ddaec666 315
3164123a 316 $0 = 'pmgpolicy child';
ddaec666 317
3164123a
DM
318 setup_fork_signal_mask(0); # unblocking signals for children
319
320 eval {
321 $self->load_config();
322
323 $self->{mux} = IO::Multiplex->new();
324 $self->{mux}->set_callback_object($self);
325
326 my %dnsargs = (
327 tcp_timeout => 3,
328 udp_timeout => 3,
329 retry => 1,
330 retrans => 0,
331 dnsrch => 0,
332 defnames => 0,
333 );
334
335 if ($opt_testmode) {
336 # $dnsargs{nameservers} = [ qw (213.129.232.1 213.129.226.2) ];
337 }
ddaec666 338
3164123a
DM
339 $self->{dns_resolver} = Net::DNS::Resolver->new(%dnsargs);
340
341 $self->{spf_server} = Mail::SPF::Server->new(
342 hostname => $self->{fqdn}, dns_resolver => $self->{dns_resolver});
343 };
344 if (my $err = $@) {
b902c0b8 345 $self->log(0, $err);
3164123a
DM
346 $self->child_finish_hook;
347 exit(-1);
348 }
349
350 $SIG{'USR1'} = sub {
351 $self->{reload_config} = 1;
352 }
ddaec666
DM
353}
354
355sub child_finish_hook {
3164123a 356 my $self = shift;
ddaec666 357
3164123a 358 my $prop = $self->{server};
ddaec666 359
3164123a
DM
360 $self->{ruledb}->close() if $self->{ruledb};
361}
ddaec666
DM
362
363sub get_spf_result {
364 my ($self, $instance, $ip, $helo, $sender) = @_;
365
366 my $result;
367 my $spf_header;
368 my $local_expl;
369 my $auth_expl;
370
371 # we only use helo tests when we have no sender,
3164123a 372 # helo is sometimes empty, so we cant use SPF helo tests
ddaec666
DM
373 # in that case - strange
374 if ($helo && !$sender) {
375 my $query;
376
3164123a 377 if (defined ($self->{cache}->{$instance}) &&
ddaec666
DM
378 defined ($self->{cache}->{$instance}->{spf_helo_result})) {
379
380 $query = $self->{cache}->{$instance}->{spf_helo_result};
381
382 } else {
3164123a
DM
383 my $request = Mail::SPF::Request->new(
384 scope => 'helo', identity => $helo, ip_address => $ip);
385
386 $query = $self->{cache}->{$instance}->{spf_helo_result} =
ddaec666
DM
387 $self->{spf_server}->process ($request);
388 }
389
390 $result = $query->code;
391 $spf_header = $query->received_spf_header;
392 $local_expl = $query->local_explanation;
393 $auth_expl = $query->authority_explanation if $query->is_code('fail');
394
395 # return if we get a definitive result
396 if ($result eq 'pass' || $result eq 'fail' || $result eq 'temperror') {
397 return ($result, $spf_header, $local_expl, $auth_expl);
398 }
399 }
400
401 if ($sender) {
402
403 my $query;
404
3164123a 405 if (defined ($self->{cache}->{$instance}) &&
ddaec666 406 defined ($self->{cache}->{$instance}->{spf_mfrom_result})) {
3164123a 407
ddaec666
DM
408 $query = $self->{cache}->{$instance}->{spf_mfrom_result};
409
410 } else {
411
3164123a
DM
412 my $request = Mail::SPF::Request->new(
413 scope => 'mfrom', identity => $sender,
414 ip_address => $ip, helo_identity => $helo);
415
ddaec666
DM
416 $query = $self->{cache}->{$instance}->{spf_mfrom_result} =
417 $self->{spf_server}->process($request);
418 }
419
420 $result = $query->code;
421 $spf_header = $query->received_spf_header;
422 $local_expl = $query->local_explanation;
423 $auth_expl = $query->authority_explanation if $query->is_code('fail');
424
425 return ($result, $spf_header, $local_expl, $auth_expl);
426 }
427
428 return undef;
429}
430
431sub is_backup_mx {
432 my ($self, $ip, $receiver) = @_;
433
434 my ($rdomain) = $receiver =~ /([^@]+)$/;
435
436 my $dkey = "BKMX:$rdomain";
437
438 if (defined ($self->{cache}->{$dkey}) &&
439 ($self->{cache}->{$dkey}->{status} == 1)) {
440 return $self->{cache}->{$dkey}->{$ip};
441 }
442
443 my $resolver = $self->{dns_resolver};
444
3164123a 445 if (my $mx = $resolver->send($rdomain, 'MX')) {
ddaec666
DM
446 $self->{cache}->{$dkey}->{status} = 1;
447 my @mxa = grep { $_->type eq 'MX' } $mx->answer;
448 my @mxl = sort { $a->preference <=> $b->preference } @mxa;
449 # shift @mxl; # optionaly skip primary MX ?
450 foreach my $rr (@mxl) {
451 my $a = $resolver->send ($rr->exchange, 'A');
452 if ($a) {
453 foreach my $rra ($a->answer) {
454 if ($rra->type eq 'A') {
455 $self->{cache}->{$dkey}->{$rra->address} = 1;
456 }
457 }
458 }
459 }
460 } else {
461 $self->{cache}->{$dkey}->{status} = 0;
462 }
463
464 return $self->{cache}->{$dkey}->{$ip};
465}
466
467sub greylist_value {
468 my ($self, $ctime, $helo, $ip, $sender, $rcpt, $instance) = @_;
469
470 my $rulecache = $self->{rulecache};
471
472 my $dbh = $self->{ruledb}->{dbh};
473
474 # try to reconnect if database connection is broken
475 if (!$dbh->ping) {
3164123a 476 $self->log(0, 'Database connection broken - trying to reconnect');
ddaec666
DM
477 my $dbh;
478 eval {
3164123a 479 $dbh = PMG::DBTools::open_ruledb($database);
ddaec666
DM
480 };
481 my $err = $@;
482 if ($err) {
b902c0b8 483 $self->log(0, "unable to reconnect to database server: $err");
ddaec666
DM
484 return 'dunno';
485 }
3164123a 486 $self->{ruledb} = PMG::RuleDB->new($dbh);
ddaec666
DM
487 }
488
489 # some sender substitutions
490 my ($user, $domain) = split('@', $sender, 2);
491 if (defined ($user) && defined ($domain)) {
492 # see http://cr.yp.to/proto/verp.txt
493 $user =~ s/\+.*//; # strip extensions (mailing-list VERP)
494 $user =~ s/\b\d+\b/#/g; #replace nubmers in VERP address
495 $sender = "$user\@$domain";
496 }
497
3164123a
DM
498 if ($self->is_backup_mx($ip, $rcpt)) {
499 $self->log(3, "accept mails from backup MX host - $ip");
ddaec666
DM
500 return 'dunno';
501 }
502
503 # greylist exclusion (sender whitelist)
504 if ($rulecache->greylist_match ($sender, $ip)) {
3164123a 505 $self->log(3, "accept mails from whitelist - $ip");
ddaec666
DM
506 return 'dunno';
507 }
508
ddaec666
DM
509 # greylist exclusion (receiver whitelist)
510 if ($rulecache->greylist_match_receiver ($rcpt)) {
3164123a 511 $self->log(3, "accept mails to whitelist - <$rcpt>");
ddaec666
DM
512 return 'dunno';
513 }
514
515 my ($net, $host) = $ip =~ m/(\d+\.\d+\.\d+)\.(\d+)/;
516 my $spf_header;
517
3164123a 518 if ((!$opt_testmode && $self->{use_spf}) ||
ddaec666
DM
519 ($opt_testmode && ($rcpt =~ m/^testspf/))) {
520
521 # ask SPF
522 my $spf_result;
523 my $local_expl,
524 my $auth_expl;
525
526 my $previous_alarm;
527
528 my ($result, $smtp_comment, $header_comment);
529
530 eval {
3164123a 531 $previous_alarm = alarm(10);
ddaec666 532 local $SIG{ALRM} = sub { die "SPF timeout\n" };
3164123a
DM
533
534 ($result, $spf_header, $local_expl, $auth_expl) =
535 $self->get_spf_result($instance, $ip, $helo, $sender);
536
537 alarm(0); # avoid race condition
ddaec666 538 };
ddaec666
DM
539 my $err = $@;
540
3164123a 541 alarm($previous_alarm) if defined($previous_alarm);
ddaec666
DM
542
543 if ($err) {
544 $err = $err->text if UNIVERSAL::isa ($err, 'Mail::SPF::Exception');
b902c0b8 545 $self->log (0, $err);
ddaec666
DM
546 } else {
547
548 if ($result && $result eq 'pass') {
3164123a 549 $self->log(3, "SPF says $result");
ddaec666
DM
550 $spf_result = $spf_header ? "prepend $spf_header" : 'dunno';
551 }
3164123a 552
ddaec666 553 if ($result && $result eq 'fail') {
3164123a
DM
554 $self->log(3, "SPF says $result");
555 $spf_result = "reject ${auth_expl}";
556
ddaec666
DM
557 eval {
558
559 $dbh->begin_work;
560
561 # try to avoid locks everywhere - we use merge instead of insert
562 #$dbh->do ("LOCK TABLE CGreylist IN ROW EXCLUSIVE MODE");
3164123a 563
ddaec666 564 # check if there is already a record in the GL database
3164123a
DM
565 my $sth = $dbh->prepare(
566 "SELECT * FROM CGreylist " .
567 "where IPNet = ? AND Sender = ? AND Receiver = ?");
ddaec666 568
3164123a 569 $sth->execute($net, $sender, $rcpt);
ddaec666
DM
570 my $ref = $sth->fetchrow_hashref();
571 $sth->finish();
572
573 # else add an entry to the GL Database with short
3164123a 574 # expiration time. run_dequeue() moves those entries into the statistic
ddaec666
DM
575 # table later. We set 'blocked' to 100000 to identify those entries.
576
3164123a 577 if (!defined($ref->{rctime})) {
ddaec666 578
2e049252 579 $dbh->do($PMG::DBTools::cgreylist_merge_sql, undef,
3164123a
DM
580 $net, $host, $sender, $rcpt, $instance,
581 $ctime, $ctime + 10, 0, 100000, 0, $ctime, $self->{lcid});
ddaec666
DM
582 }
583
584 $dbh->commit;
585 };
3164123a 586 if (my $err = $@) {
ddaec666 587 $dbh->rollback;
b902c0b8 588 $self->log(0, $err);
ddaec666
DM
589 }
590 }
591 }
592
593 return $spf_result if $spf_result;
594 }
595
596
597 my $res = $spf_header ? "prepend $spf_header" : 'dunno';
598
599 return $res if !$self->{use_greylist};
600
3164123a
DM
601 my $defer_res = "defer_if_permit Service is unavailable (try later)";
602
ddaec666
DM
603 eval {
604
605 # we dont use alarm here, because it does not work with DBI
606
607 $dbh->begin_work;
608
609 # try to avoid locks everywhere - we use merge instead of insert
610 #$dbh->do ("LOCK TABLE CGreylist IN ROW EXCLUSIVE MODE");
611
3164123a
DM
612 my $sth = $dbh->prepare(
613 "SELECT * FROM CGreylist " .
614 "where IPNet = ? AND Sender = ? AND Receiver = ?");
615
616 $sth->execute($net, $sender, $rcpt);
ddaec666 617
ddaec666
DM
618 my $ref = $sth->fetchrow_hashref();
619
620 $sth->finish();
621
3164123a 622 if (!defined($ref->{rctime})) {
ddaec666 623
2e049252
DM
624 $dbh->do($PMG::DBTools::cgreylist_merge_sql, undef,
625 $net, $host, $sender, $rcpt, $instance,
626 $ctime, $ctime + $greylist_lifetime, 0, 1, 0, $ctime, $self->{lcid});
ddaec666
DM
627
628 $res = $defer_res;
3164123a 629 $self->log(3, "defer greylisted mail");
ddaec666 630 } else {
3164123a 631 my $age = $ctime - $ref->{rctime};
ddaec666
DM
632
633 if ($age < $greylist_delay) {
634 # defer (resent within greylist_delay window)
635 $res = $defer_res;
3164123a
DM
636 $self->log(3, "defer greylisted mail");
637 $dbh->do("UPDATE CGreylist " .
638 "SET Blocked = Blocked + 1, Host = ?, MTime = ? " .
639 "WHERE IPNet = ? AND Sender = ? AND Receiver = ?", undef,
640 $host, $ctime, $net, $sender, $rcpt);
ddaec666
DM
641 } else {
642 if ($ctime < $ref->{extime}) {
643 # accept (not expired)
644 my $lifetime = $sender eq "" ? 0 : $greylist_awlifetime;
645 my $delay = $ref->{passed} ? "" : "Delay = $age, ";
3164123a
DM
646 $dbh->do("UPDATE CGreylist " .
647 "SET Passed = Passed + 1, $delay Host = ?, ExTime = ?, MTime = ? " .
648 "WHERE IPNet = ? AND Sender = ? AND Receiver = ?", undef,
649 $host, $ctime + $lifetime, $ctime, $net, $sender, $rcpt);
ddaec666
DM
650 } else {
651 # defer (record is expired)
652 $res = $defer_res;
3164123a
DM
653 $dbh->do("UPDATE CGreylist " .
654 "SET Host = ?, RCTime = ?, ExTime = ?, MTime = ?, Instance = ?, " .
655 "Blocked = 1, Passed = 0 " .
656 "WHERE IPNet = ? AND Sender = ? AND Receiver = ?", undef,
657 $host, $ctime, $ctime + $greylist_lifetime, $ctime, $instance,
658 $net, $sender, $rcpt);
ddaec666 659 }
3164123a 660 }
ddaec666
DM
661 }
662
663 $dbh->commit;
664 };
3164123a
DM
665 if (my $err = $@) {
666 $dbh->rollback;
b902c0b8 667 $self->log (0, $err);
ddaec666
DM
668 }
669
670 return $res;
671}
672
3164123a 673# shutdown connections: we need this - else file handles are
ddaec666
DM
674# not closed and we run out of handles
675sub mux_eof {
676 my ($self, $mux, $fh) = @_;
677
678 $mux->shutdown($fh, 1);
679}
680
681sub mux_input {
682 my ($self, $mux, $fh, $dataref) = @_;
683 my $prop = $self->{server};
3164123a 684
ddaec666
DM
685 my $attribute = {};
686
687 eval {
3164123a 688 $self->load_config() if $self->{reload_config};
ddaec666
DM
689
690 while ($$dataref =~ s/^([^\r\n]*)\r?\n//) {
691 my $line = $1;
692 next if !defined ($line);
693
694 if ($line =~ m/([^=]+)=(.*)/) {
695 $attribute->{substr($1, 0, 255)} = substr($2, 0, 255);
3164123a 696 } elsif ($line eq '') {
ddaec666
DM
697 my $res = 'dunno';
698 my $ctime = time;
699
700 if ($opt_testmode) {
701 die "undefined test time :ERROR" if !defined $attribute->{testtime};
702 $ctime = $attribute->{testtime};
703 }
704
3164123a 705 if ($attribute->{instance} && $attribute->{recipient} &&
ddaec666
DM
706 $attribute->{client_address} && $attribute->{request} &&
707 $attribute->{request} eq 'smtpd_access_policy') {
3164123a 708
ddaec666 709 eval {
3164123a
DM
710
711 $res = $self->greylist_value(
712 $ctime,
713 lc ($attribute->{helo_name}),
714 lc ($attribute->{client_address}),
715 lc ($attribute->{sender}),
716 lc ($attribute->{recipient}),
717 lc ($attribute->{instance}));
ddaec666 718 };
3164123a 719 if (my $err = $@) {
b902c0b8 720 $self->log(0, $err);
3164123a 721 }
ddaec666
DM
722 }
723
724 print $fh "action=$res\n\n";
725
726 $attribute = {};
727 } else {
3164123a 728 $self->log(0, "greylist policy protocol error - got '%s'", $line);
ddaec666
DM
729 }
730 }
731 };
3164123a 732 my $err = $@;
ddaec666
DM
733
734 # remove remaining data, if any
735 if ($$dataref ne '') {
3164123a 736 $self->log(0, "greylist policy protocol error - unused data '%s'", $$dataref);
ddaec666
DM
737 $$dataref = '';
738 }
739
b902c0b8 740 $self->log(0, $err) if $err;
ddaec666
DM
741}
742
743sub restart_close_hook {
3164123a 744 my $self = shift;
ddaec666 745
3164123a
DM
746 my $sig_set = POSIX::SigSet->new;
747 $sig_set->addset(&POSIX::SIGHUP);
748 $sig_set->addset(&POSIX::SIGCHLD); # to avoid zombies
749 my $old_sig_set = POSIX::SigSet->new();
ddaec666 750
3164123a 751 sigprocmask(SIG_BLOCK, $sig_set, $old_sig_set);
ddaec666
DM
752}
753
754sub pre_server_close_hook {
3164123a
DM
755 my $self = shift;
756
757 my $prop = $self->{server};
ddaec666 758
3164123a
DM
759 if (defined $prop->{_HUP}) {
760 undef $prop->{pid_file_unlink};
761 }
08f49442
DM
762
763 if (defined $prop->{children}) {
764 foreach my $pid (keys %{$prop->{children}}) {
765 kill(1, $pid); # HUP childs
766 }
767 }
768
769 # nicely shutdown childs (give them max 30 seconds to shut down)
770 my $previous_alarm = alarm(30);
771 eval {
772 local $SIG{ALRM} = sub { die "Timed Out!\n" };
773
774 my $pid;
775 1 while ((($pid = waitpid(-1, 0)) > 0) || ($! == EINTR));
776
777 alarm(0); # avoid race
778 };
779 alarm ($previous_alarm);
ddaec666
DM
780}
781
782sub setup_fork_signal_mask {
783 my $block = shift;
784
785 my $sig_set = POSIX::SigSet->new;
3164123a
DM
786 $sig_set->addset(&POSIX::SIGINT);
787 $sig_set->addset(&POSIX::SIGTERM);
788 $sig_set->addset(&POSIX::SIGQUIT);
789 $sig_set->addset(&POSIX::SIGHUP);
ddaec666
DM
790 my $old_sig_set = POSIX::SigSet->new();
791
792 if ($block) {
793 sigprocmask (SIG_BLOCK, $sig_set, $old_sig_set);
794 } else {
795 sigprocmask (SIG_UNBLOCK, $sig_set, $old_sig_set);
796 }
797}
798
799# subroutine to start up a specified number of children.
800# We need to block signals until handlers are set up correctly.
3164123a
DM
801# Else its possible that HUP occurs after fork, which triggers
802# singal TERM at childs and calls server_close() instead of
ddaec666
DM
803# simply exit the child.
804# Note: on server startup signals are setup to trigger
805# asynchronously for a short period of time (in PreForkSimple]::loop,
3164123a 806# run_n_children is called before run_parent)
ddaec666 807# Net::Server::PreFork does not have this problem, because it is using
3164123a 808# signal HUP stop children
ddaec666 809sub run_n_children {
3164123a
DM
810 my ($self, $n) = @_;
811
ddaec666 812 my $prop = $self->{server};
ddaec666 813
3164123a
DM
814 setup_fork_signal_mask(1); # block signals
815
816 $self->SUPER::run_n_children($n);
ddaec666 817
3164123a 818 setup_fork_signal_mask(0); # unblocking signals for parent
ddaec666
DM
819}
820
3164123a 821# test sig_hup with: for ((;;)) ;do kill -HUP `cat /var/run/pmgpolicy.pid`; done;
ddaec666
DM
822# wrapper to avoid multiple calls to sig_hup
823sub sig_hup {
3164123a
DM
824 my $self = shift;
825
826 my $prop = $self->{server};
ddaec666 827
3164123a 828 return if defined($prop->{_HUP}); # do not call twice
ddaec666 829
3164123a 830 $self->SUPER::sig_hup();
ddaec666
DM
831}
832
833### child process which will accept on the port
834sub run_child {
3164123a 835 my $self = shift;
ddaec666 836
3164123a 837 my $prop = $self->{server};
ddaec666 838
3164123a 839 $self->log(4, "Child Preforked ($$)\n");
ddaec666 840
3164123a
DM
841 # set correct signal handlers before enabling signals again
842 $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = $SIG{HUP} = sub {
843 $self->child_finish_hook;
844 exit;
845 };
ddaec666 846
3164123a 847 delete $prop->{children};
ddaec666 848
3164123a 849 $self->child_init_hook;
ddaec666 850
3164123a 851 # accept connections
ddaec666 852
3164123a 853 my $sock = $prop->{sock}->[0];
ddaec666 854
3164123a
DM
855 # make sure we got a good sock
856 if (!defined ($sock)){
857 $self->log(0, "ERROR: Received a bad socket");
858 exit (-1);
859 }
860
861 # sometimes the socket is not usable, don't know why
862 my $flags = fcntl($sock, F_GETFL, 0);
863 if (!$flags) {
b902c0b8 864 $self->log(0, "socket not ready - $!");
3164123a
DM
865 exit (-1);
866 }
ddaec666 867
3164123a
DM
868 # cache is limited, because postfix does max. 100 queries
869 $self->{cache} = {};
ddaec666 870
3164123a
DM
871 eval {
872 my $mux = $self->{mux};
873 $mux->listen ($sock);
874 $mux->loop;
875 };
876 if (my $err = $@) {
b902c0b8 877 $self->log(0, "ERROR: $err");
3164123a 878 }
ddaec666 879
3164123a 880 $self->child_finish_hook;
ddaec666 881
3164123a 882 exit;
ddaec666
DM
883}
884
3164123a
DM
885my $syslog_map = {
886 0 => 'err',
887 1 => 'warning',
888 2 => 'notice',
889 3 => 'info',
890 4 => 'debug'
891};
892
ddaec666
DM
893sub log {
894 my ($self, $level, $msg, @therest) = @_;
3164123a 895
ddaec666
DM
896 my $prop = $self->{server};
897
898 return if $level =~ /^\d+$/ && $level > $prop->{log_level};
899
3164123a 900 $level = $syslog_map->{$level} || $level;
ddaec666
DM
901 if (@therest) {
902 syslog($level, $msg, @therest);
903 } else {
904 syslog ($level, $msg);
905 }
906}
907
908my $server = bless {
909 server => $server_attr,
910};
911
912$server->sig_chld(); # avoid zombies after restart
913
914$server->run ();
915
916exit (0);
917
918__END__
919
920=head1 NAME
3164123a
DM
921
922pmgpolicy - The Proxmox policy daemon
ddaec666
DM
923
924=head1 SYNOPSIS
925
3164123a 926pmgpolicy
ddaec666
DM
927
928=head1 DESCRIPTION
929
930Documentation is available at www.proxmox.com