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