Quarantine/Batch.pm untested

filter: Statementstmt 0.0% 0 / 419 Branchbran 0.0% 0 / 136 Conditioncond 0.0% 0 / 50 MC/DCmcdc 0.0% 0 / 28 Subroutinesub 0.0% 0 / 31 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 681 CC 69 SCAR 48.8
CC
69
Cov
0%
prune_headers
272.0
sender_agent
272.0
recipient_agent
156.0
CRAP 131.9
1 # Copyright(C) 2006 David Muir Sharnoff <muir@idiom.com>
2 #
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with this program; if not, write to the Free Software Foundation, Inc.,
15 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
16 #
17 # This software is available without the GPL: please write if you need
18 # a non-GPL license. All submissions of patches must come with a
19 # copyright grant so that David Sharnoff remains able to change the
20 # license at will.
21  
22 package Qpsmtpd::Plugin::Quarantine::Batch;
23  
24 require Exporter;
25 use OOPS;
26 use strict;
27 use Qpsmtpd::Plugin::Quarantine::Common;
28 use Qpsmtpd::Plugin::Quarantine::Sendmail;
29 use Mail::SendVarious;
30 use Mail::SendVarious qw(make_message $mail_error);
31 use Scalar::Util qw(refaddr);
32 use IO::Pipe;
33 use Time::CTime;
34  
35 my $mailq_timefmt = "%a %b %d %X";
36  
37 our @ISA = qw(Exporter);
38 our @EXPORT = qw(cronjob sendqueued mailq);
39 our @EXPORT_OK = qw(
40 find_oldest_bucket prune_headers
41 prune_recipients generate_recipients
42 prune_senders generate_senders
43 walk_eval
44 indent);
45  
46 my $debug = 0;
47  
48 my $recipients_deleted = 0;
49 my $recipients_settings = 0;
50 my $recipients_count = 0;
51 my $senders_deleted = 0;
52 my $senders_count = 0;
53 my $senders_with_settings = 0;
54 my $stride = 100;
55  
56 sub cronjob
57 {
58 my $start = time;
59  
60 print "# upgrades?\n";
61 upgrade();
62  
63 print "# cleaning out messages\n" if $debug;
64 my $messages_deleted = 0;
65 for(;;) {
66 my $done;
67 my $del;
68 my $diskused = message_store_size();
69 transaction(sub {
70 my $oops = get_oops();
71 my $oldest = find_oldest_bucket($oops);
72 if ($oldest and (time - $oldest) / 86400 > $defaults{message_longevity}) {
73 printf "# Oldest bucket is dated %s, must prune headers\n", scalar(localtime($oldest)) if $debug;
74 $del = prune_headers($oops);
75 } elsif ($diskused / 1024000 > $defaults{message_store_size}) {
76 printf "# Oldest bucket is dated %s, we're over our disk quote -- must prune headers\n", scalar(localtime($oldest)) if $debug;
77 $del = prune_headers($oops);
78 } else {
79 printf "# Oldest bucket is dated %s, we're done\n", scalar(localtime($oldest)) if $debug;
80 $done = 1;
81 }
82 $oops->commit() if $del;
83 });
84 $messages_deleted += $del;
85 last if $done;
86 }
87  
88 print "Messages deleted: $messages_deleted\n\n";
89 print "\n\n";
90  
91 print "# cleaning up recipients...\n" if $debug;
92 prune_recipients();
93 print "Recipients deleted: $recipients_deleted\n";
94 print "Recipients kept: $recipients_count\n";
95 print "Recipients with settings: $recipients_settings\n";
96 print "\n\n";
97  
98 print "# cleaning up senders...\n" if $debug;
99 prune_senders();
100 print "Senders kept: $senders_count\n";
101 print "Senders with settings: $senders_with_settings\n";
102 print "Senders deleted: $senders_deleted\n";
103 print "\n\n";
104  
105  
106 printf "Time for batch run: %d (seconds)\n", time - $start;
107 }
108  
109 sub upgrade
110 {
111 transaction(sub {
112 {
113 print " Upgrade oops?\n";
114 my $oops = OOPS->new(oops_args(), auto_ugprade => 1);
115 $oops->commit;
116 }
117 my $version;
118 {
119 my $oops = get_oops();
120 my $qd = $oops->{quarantine};
121 $version = $qd->{version};
122 }
123 if ($version <= 0.31) {
124 my $oops = get_oops();
125 my $qd = $oops->{quarantine};
126 print "Fixing 3600 hours/day problem\n";
127  
128 my $time = time;
129 my $b0 = $qd->{buckets};
130 my $b0count = 0;
131 for my $day (sort { $a <=> $b } keys %{$b0}) {
132 print " Remapping ".scalar(gmtime($day*86400))."\n";
133 my $b1count = 0;
134 my $b1 = $b0->{$day};
135 for my $bucket (keys %{$b1}) {
136 my $oldtime = $day * 86400 + $bucket * 24;
137 print " Bucket at ".scalar(gmtime($oldtime))."\n";
138 my $b2 = $b1->{$bucket};
139 my $count = 0;
140 for my $header_checksum (keys %$b2) {
141 $qd->{buckets3}{int($oldtime / 86400)}{int(($oldtime % 86400) / 3600)}{$header_checksum} = $b2->{$header_checksum};
142 $oops->virtual_object($qd->{buckets3}{int($oldtime / 86400)}, 1);
143 $oops->virtual_object($qd->{buckets3}{int($oldtime / 86400)}{int(($oldtime % 86400) / 3600)}, 1);
144 $count++;
145 }
146 print " $count headers moved\n";
147 $b1count += $count;
148 delete $b1->{$bucket};
149 }
150 print " $b1count moved\n";
151 $b0count += $b1count;
152 delete $b0->{$day};
153 }
154 print "Total moved: $b0count\n";
155 $oops->commit();
156 }
157 if ($version < 0.34) {
158 $| = 1;
159 transaction(sub {
160 my $oops = get_oops();
161 print "Counting up message storage space...\n";
162 my $qd = $oops->{quarantine};
163 $qd->{diskused} = {}
164 unless $qd->{diskused};
165 bless $qd->{diskused}, 'Quarantine::DiskUsage';
166 $oops->virtual_object($qd->{diskused}, 1);
167 });
168  
169 my $tsize = 0;
170 my $tcount = 0;
171 my $size;
172 my $count;
173 my @buf;
174  
175 require Qpsmtpd::Plugin::Quarantine;
176  
177 walk_eval(
178 50,
179 sub {
180 my $oops = shift;
181 return $oops->{quarantine}{bodies};
182 },
183 sub {
184 my ($oops, @bodies) = @_;
185 my $size = 0;
186 my $count = 0;
187 my $qd = $oops->{quarantine};
188 for my $bdsum (@bodies) {
189 my $pbody = $qd->{bodies}{$bdsum};
190 return unless $pbody;
191 return if $pbody->{size};
192 $pbody->{size} = length($pbody->{body});
193 $size += $pbody->{size};
194 $count += 1;
195 print "." if ($tcount + $count) % 10 == 0;
196 }
197 $qd->{diskused}{$$ % $defaults{size_storage_array_size}} += $size + $count * $defaults{message_size_overhead};
198 $tsize += $size;
199 $tcount += $count;
200 print "C";
201 },
202 allatonce => 1,
203 );
204  
205 printf "\n%d messages using %.1fMB\n", $tcount, $tsize / 1024000;
206  
207 }
208 if ($version < 0.37) {
209 print "Running database fsck\n";
210 use OOPS::Fsck;
211 $OOPS::Fsck::check_batchsize = 2000;
212 fsck(oops_args());
213 print "Done with fsck\n";
214 }
215 if ($version < 0.37) {
216 print "Running database GC\n";
217 use OOPS::GC;
218 $OOPS::GC::too_many_todo = 50_000;
219 $OOPS::GC::work_length = 10_000;
220 $OOPS::GC::clear_batchsize = 4000;
221 $OOPS::GC::virtual_hash_slice = 3_000;
222 $OOPS::GC::maximum_spill_size = 10_000;
223 }
224 update_version();
225 });
226 }
227  
228 sub update_version
229 {
230 my ($oops) = @_;
231 my $doit = sub {
232 my $qd = $oops->{quarantine};
233 require Qpsmtpd::Plugin::Quarantine;
234 $qd->{version} = $Qpsmtpd::Plugin::Quarantine::VERSION;
235 };
236 if ($oops) {
237 &$doit();
238 } else {
239 transaction(sub {
240 $oops = get_oops();
241 &$doit();
242 $oops->commit;
243 });
244 }
245 }
246  
247 sub find_oldest_bucket
248 {
249 my ($oops) = @_;
250  
251 my $qd = $oops->{quarantine};
252  
253 my $b0 = $qd->{buckets3};
254  
255 my ($b0first) = sort { $a <=> $b } keys %{$b0};
256 my $b1 = $b0->{$b0first};
257 my ($b1first) = sort { $a <=> $b } keys %{$b1};
258  
259 my $bucket = $b1->{$b1first};
260  
261 return ($b0, $b0first, $b1, $b1first, $bucket) if wantarray;
262 return $b0first * 86400 + $b1first * 3600;
263 }
264  
265 sub message_store_size
266 {
267 transaction(sub {
268 my $oops = get_oops();
269 my $qd = $oops->{quarantine};
270 my $size = 0;
271 for my $v (values %{$qd->{diskused}}) {
272 $size += $v;
273 }
274 printf "Disk space used %.1fMB\n", $size / 1024000;
275 return $size;
276 });
277 }
278  
279 my $mqueue_sent;
280 my $mqueue_unsent;
281  
282 sub sendqueued
283 {
284 walk_eval($defaults{mqueue_stride_length}, sub {
285 my $oops = shift;
286 return $oops->{quarantine}{mqueue};
287 }, \&mqueue_agent, allatonce => 1);
288 }
289  
290 sub mqueue_agent
291 {
292 my ($oops, @mqueue) = @_;
293 for my $mqueue (@mqueue) {
294 my $mq = $oops->{mqueue}{$mqueue};
295 next unless time - $mq->{last_attempt} >= $defaults{mqueue_minimum_gap};
296 $oops->lock($oops->{mqueue}{$mqueue});
297 }
298 for my $mqueue (@mqueue) {
299 my $mq = $oops->{mqueue}{$mqueue};
300 next unless time - $mq->{last_attempt} >= $defaults{mqueue_minimum_gap};
301 mqueue_agent2($oops, $mqueue);
302 }
303 }
304  
305 sub mqueue_agent2
306 {
307 my ($oops, $mqueue) = @_;
308 my $mq = $oops->{mqueue}{$mqueue} || return;
309  
310 if (sendmail(%$mq, debuglogger => sub { 1 }, errorlogger => sub { 1 })) {
311 delete $oops->{mqueue}{$mqueue};
312 $mqueue_sent++;
313 return;
314 }
315 $mq->{last_attempt} = time;
316 $mq->{attempt_count}++;
317 $mq->{last_error} = $mail_error;
318  
319 if (time - $mq->{first_attempt} >= $mq->{mqueue_maximum_keep}
320 and $mq->{attempt_count} >= $defaults{mqueue_minimum_attempts})
321 {
322 delete $oops->{mqueue}{$mqueue};
323 if ($mq->{from} ne "<>" && $mq->{from} ne $defaults{bounce_from} && $mq->{from} =~ /^mailer-daemon\@/i) {
324 my (undef, $mes) = make_message(%$mq);
325 sendmail_or_postpone(
326 from => $defaults{bounce_from},
327 subject => "Returned mail: $mq->{last_error}",
328 to => $mq->{from},
329 body => <<END,
330 We attempted to send a message on your behalf but we could
331 not do so. The specific problem we had was:
332  
333 $mq->{last_error}
334  
335 The message we were trying to send was:
336  
337 $mes
338 END
339 debuglogger => sub { 1 },
340 );
341 }
342 }
343 }
344  
345 sub mqueue_postcommit
346 {
347 send_postponed();
348 }
349  
350 sub mailq
351 {
352 my $oops = get_oops(readonly => 1, less_caching => 1);
353 my $qd = $oops->{quarantine};
354 my $count = 0;
355 my $size = 0;
356 for my $mqueue (keys %{$qd->{mqueue}}) {
357 my $mq = $qd->{mqueue}{$mqueue};
358 my ($from, $message, @to) = make_message(%$mq);
359 printf "%15s %6d %20s %s\n", $mqueue, length($message), strftime($mailq_timefmt, localtime($mq->{first_attempt})), $from;
360 print " ($mq->{last_error})\n";
361 for my $t (@to) {
362 print "\t\t\t\t\t $t\n";
363 }
364 $count++;
365 $size += length($message);
366 }
367 printf "-- %d Kbytes in %d Requests.\n", $size / 1024, $count;
368 }
369  
370 sub prune_headers
371 {
372 my ($oops, $messages) = @_;
373  
374 $messages = $defaults{delete_batchsize}
375 unless $messages;
376  
377 print "Pruning $messages messages\n" if $debug > 2;
378  
379 my $qd = $oops->{quarantine};
380  
381 my ($b0, $b0first, $b1, $b1first, $bucket);
382  
383 for(;;) {
384 ($b0, $b0first, $b1, $b1first, $bucket) = find_oldest_bucket($oops);
385 last if $bucket && %$bucket;
386 if (%$b1) {
387 print "Deleting b1first $b1first\n" if $debug >2;
388 delete $b1->{$b1first};
389 redo;
390 }
391 if (%$b0) {
392 print "Deleting b0first $b0first\n" if $debug >2;
393 delete $b0->{$b0first};
394 redo;
395 }
396 die "no messages";
397 }
398  
399 my $pruned = 0;
400 my ($hcksum, $pheader);
401 while (($hcksum, $pheader) = each(%$bucket)) {
402 return --$pruned if $pruned++ >= $messages;
403  
404 my $wasdone = $pheader->{done};
405 my $pbody = $pheader->{body};
406 my $psender = $pheader->{sender};
407 my $recipients = $pheader->{recipients};
408  
409 print STDERR <<END if $debug > 3;
410 Removing....
411 From $psender->{address}
412 From: $pheader->{from}To: $pheader->{to}Subject: $pheader->{subject}Date: $pheader->{date}
413 END
414  
415 %$pheader = ();
416  
417 if (refaddr($pbody->{last_reference}) == refaddr($pheader)) {
418 delete $pbody->{last_reference};
419 my $bcksum = $pbody->{cksum};
420 delete $qd->{bodies}{$bcksum};
421 $qd->{diskused}{$$ % $defaults{size_storage_array_size}}
422 -= $pbody->{size};
423  
424 print STDERR "(body too)\n\n" if $debug > 3
425 } else {
426 print STDERR "\n" if $debug > 3;
427 }
428 delete $bucket->{$hcksum};
429 delete $qd->{headers}{$hcksum};
430 delete $psender->{headers}{$hcksum};
431 for my $r (@{$pheader->{recipients}}) {
432 my $rd = $qd->{recipients}{$r};
433 if ($rd->{headers}{$hcksum}) {
434 delete $rd->{headers}{$hcksum};
435 $rd->{mcount}-- unless $wasdone;
436 }
437 }
438 }
439 print "Only pruned $pruned messages\n" if $debug >2;
440 delete $b1->{$b1first};
441 return $pruned;
442 }
443  
444  
445 sub prune_recipients
446 {
447 walk_eval($defaults{recipent_stride_length}, sub { my $oops = shift; return $oops->{quarantine}{recipients} }, \&recipient_agent);
448 }
449  
450 sub recipient_agent
451 {
452 my ($oops, $recipient) = @_;
453 my $qd = $oops->{quarantine};
454 my $rd = $qd->{recipients}{$recipient};
455 unless ($rd) {
456 print STDERR "That's odd, cannot find recipient '$recipient'\n";
457 delete $qd->{recipients}{$recipient};
458 return;
459 }
460 unless ($rd->{headers}) {
461 print STDERR "Recipient $recipient invalid, deleting\n";
462 delete $qd->{recipients}{$recipient};
463 $recipients_deleted++;
464 return;
465 }
466 my $msgcount = %{$rd->{headers}} ? scalar(%{$rd->{headers}}) : 0;
467 print "Recipient: $recipient..." if $debug;
468 printf " (has %d messages)", $msgcount if $debug;
469 printf " %d days idle...", (time - $rd->{last_timestamp})/86400 if $debug;
470 print " has settings" if $debug && $rd->has_settings;
471 if (
472 (
473 (time - $rd->{last_timestamp}) / 86400 > $defaults{keep_idle_recipients}
474 &&
475 ! $msgcount
476 )
477 ||
478 (
479 (time - $rd->{last_timestamp}) / 86400 > $defaults{message_longevity}
480 &&
481 ! $rd->has_settings()
482 &&
483 ! $msgcount
484 )
485 ) {
486 delete $qd->{recipients}{$recipient};
487 $recipients_deleted++;
488 print " DELETE" if $debug;
489 } else {
490 $recipients_settings++ if $rd->has_settings();
491 $recipients_count++;
492 }
493 print "\n" if $debug;
494 }
495  
496 sub prune_senders
497 {
498 walk_eval($defaults{sender_stride_length}, sub { my $oops = shift; return $oops->{quarantine}{senders} }, \&sender_agent);
499 }
500  
501 sub sender_agent
502 {
503 my ($oops, $sender) = @_;
504 my $qd = $oops->{quarantine};
505 my $psender = $qd->{senders}{$sender};
506 unless ($psender) {
507 print STDERR "That's odd, cannot find sender '$sender'\n";
508 delete $qd->{senders}{$sender};
509 return;
510 }
511  
512 print "Sender: $sender" if $debug;
513  
514  
515 my ($ip, $tstamp);
516 my $kept;
517 while (($ip, $tstamp) = each %{$psender->{send_ip_used}}) {
518 printf " (from %s %d ago)", $ip, (time - $tstamp)/86400 if $debug;
519 if (time - $tstamp > 86400 * $defaults{renotify_sender_ip} * 2) {
520 print "[D]" if $debug;
521 delete $psender->{send_ip_used}{$ip};
522 } else {
523 $kept++;
524 }
525 }
526  
527 my $spams_sent;
528 my $today = time / 86400;
529 my $count = 0;
530 for my $spamday (keys %{$psender->{spams_sent_perday}}) {
531 if ($today - $spamday > $defaults{sender_history_to_keep}) {
532 delete $psender->{spams_sent_perday}{$spamday};
533 next;
534 }
535 $spams_sent += $psender->{spams_sent_perday}{$spamday};
536 $count++;
537 }
538 delete $psender->{spams_sent_perday} unless $spams_sent;
539 printf " %d spams in %d days", $spams_sent, $count if $debug;
540  
541 if ($spams_sent >= $defaults{report_senders_after}) {
542 print "\n" if $debug;
543 print "Sender $sender has sent $spams_sent in the last $defaults{sender_history_to_keep} days\n";
544 my ($hsum, $pheader);
545 while (($hsum, $pheader) = each %{$psender->{headers}}) {
546 print "\nFor example:\n";
547 indent($pheader->{header});
548 indent($pheader->{body}{body}, limit => 100);
549 last;
550 }
551 }
552  
553 my $has_settings = $psender->has_settings();
554  
555 printf " kept:%d ss/day:%d settings:%d headers:%s", $kept, scalar(%$psender->{spams_sent_perday}), !!$has_settings, scalar(%{$psender->{headers}}) if $debug;
556  
557 if (! $kept && ! scalar(%$psender->{spams_sent_perday}) && ! $has_settings && ! scalar(%{$psender->{headers}})) {
558 print " DELETE" if $debug;
559 delete $qd->{senders}{$sender};
560 $senders_deleted++;
561 } else {
562 $senders_count++;
563 $senders_with_settings++ if $has_settings;
564 }
565 print "\n" if $debug;
566 }
567  
568 sub indent
569 {
570 my ($text, %args) = @_;
571 my $tab = $args{indent} || "\t";
572 my $limit = $args{limit} || 0;
573 while (--$limit != 0 && $text =~ /^(.*)/gm) {
574 print "$tab$1\n";
575 }
576 }
577  
578 sub walk_eval
579 {
580 my ($stride, $get_hash, $agent, %opts) = @_;
581 my $done = 0;
582 my $last = undef;
583 $stride ||= 100;
584 while (! $done) {
585 transaction(sub {
586 my $oops = get_oops();
587 my $hash = &$get_hash($oops);
588 my @items = walk_hash(%$hash, $stride, $last);
589 if ($opts{allatonce}) {
590 &$agent($oops, @items);
591 } else {
592 for my $item (@items) {
593 &$agent($oops, $item);
594 }
595 }
596 $oops->commit();
597 $last = $items[$#items];
598 $done = 1 unless @items == $stride;
599 });
600 }
601 }
602  
603 1;