1 package PMG
::CLI
::pmgqm
;
11 use POSIX
qw(strftime);
21 use PMG
::RESTEnvironment
;
27 use PMG
::ClusterConfig
;
28 use PMG
::API2
::Quarantine
;
30 use base
qw(PVE::CLIHandler);
32 sub setup_environment
{
33 PMG
::RESTEnvironment-
>setup_default_cli_env();
40 foreach my $d (@$domains) {
41 # skip domains with non-DNS name characters
42 next if $d =~ m/[^A-Za-z0-9\-\.]/;
43 if ($d =~ m/^\.(.*)$/) {
47 push @ra, "\.\*\\.$dom";
54 my $re = join ('|', @ra);
56 my $regex = qr/\@($re)$/i;
62 my ($data, $ref) = @_;
64 my @lines = split ('\n', $ref->{header
});
65 my $head = new Mail
::Header
(\
@lines);
69 $item->{id
} = sprintf("C%dR%d", $ref->{cid
}, $ref->{rid
});
71 $item->{subject
} = PMG
::Utils
::rfc1522_to_html
(
72 PVE
::Tools
::trim
($head->get('subject')) || 'No Subject');
74 my @fromarray = split('\s*,\s*', $head->get('from') || $ref->{sender
});
75 my $from = PMG
::Utils
::rfc1522_to_html
(PVE
::Tools
::trim
($fromarray[0]));
76 my $sender = PMG
::Utils
::rfc1522_to_html
(PVE
::Tools
::trim
($head->get('sender')));
79 $item->{sender
} = $sender;
80 $item->{from
} = sprintf ("%s on behalf of %s", $sender, $from);
82 $item->{from
} = $from;
85 $item->{pmail
} = $ref->{pmail
};
86 $item->{receiver
} = $ref->{receiver
} || $ref->{pmail
};
88 $item->{date
} = strftime
("%F", localtime($ref->{time}));
89 $item->{time} = strftime
("%H:%M:%S", localtime($ref->{time}));
91 $item->{bytes
} = $ref->{bytes
};
92 $item->{spamlevel
} = $ref->{spamlevel
};
93 $item->{spaminfo
} = $ref->{info
};
95 my $title = "Received: $item->{date} $item->{time}\n";
96 $title .= "From: $ref->{sender}\n";
97 $title .= "To: $ref->{receiver}\n" if $ref->{receiver
};
98 $title .= sprintf("Size: %d KB\n", int (($ref->{bytes
} + 1023) / 1024 ));
99 $title .= sprintf("Spam level: %d\n", $ref->{spamlevel
}) if $ref->{qtype
} eq 'S';
100 $title .= sprintf("Virus info: %s\n", encode_entities
($ref->{info
})) if $ref->{qtype
} eq 'V';
101 $title .= sprintf("File: %s", encode_entities
($ref->{file
}));
103 $item->{title
} = $title;
105 my $basehref = "https://$data->{fqdn}:$data->{port}/quarantine";
106 my $ticket = uri_escape
($data->{ticket
});
107 $item->{wlhref
} = "$basehref?ticket=$ticket&cselect=$item->{id}&action=whitelist";
108 $item->{blhref
} = "$basehref?ticket=$ticket&cselect=$item->{id}&action=blacklist";
109 $item->{deliverhref
} = "$basehref?ticket=$ticket&cselect=$item->{id}&action=deliver";
110 $item->{deletehref
} = "$basehref?ticket=$ticket&cselect=$item->{id}&action=delete";
115 __PACKAGE__-
>register_method ({
119 description
=> "Generate and send spam report emails.",
121 additionalProperties
=> 0,
124 description
=> "Generate report for a single email address. If not specified, generate reports for all users.",
125 type
=> 'string', format
=> 'email',
129 description
=> "Select time span.",
131 enum
=> ['today', 'yesterday', 'week'],
136 description
=> "Spam report style. Value 'none' just prints the spam counts and does not send any emails. Default value is read from spam quarantine configuration.",
138 enum
=> ['none', 'short', 'verbose', 'custom'],
142 description
=> "Redirect spam report email to this address.",
143 type
=> 'string', format
=> 'email',
147 description
=> "Debug mode. Print raw email to stdout instead of sending them.",
154 returns
=> { type
=> 'null'},
158 my $cinfo = PMG
::ClusterConfig-
>new();
159 my $role = $cinfo->{local}->{type
} // '-';
161 if (!(($role eq '-') || ($role eq 'master'))) {
162 die "local node is not master - not sending spam report\n";
165 my $cfg = PMG
::Config-
>new();
167 my $reportstyle = $param->{style
} // $cfg->get('spamquar', 'reportstyle');
169 my $timespan = $param->{timespan
} // 'today';
171 my (undef, undef, undef, $mday, $mon, $year) = localtime(time());
172 my $daystart = timelocal
(0, 0, 0, $mday, $mon, $year);
177 if ($timespan eq 'today') {
179 $end = $start + 86400;
180 } elsif ($timespan eq 'yesterday') {
182 $start = $end - 86400;
183 } elsif ($timespan eq 'week') {
185 $start = $end - 7*86400;
187 die "internal error";
190 my $hostname = PVE
::INotify
::nodename
();
192 my $fqdn = $cfg->get('spamquar', 'hostname') //
193 PVE
::Tools
::get_fqdn
($hostname);
201 hostname
=> $hostname,
202 date
=> strftime
("%F", localtime($end - 1)),
203 timespan
=> $timespan,
207 my $mailfrom = $cfg->get ('spamquar', 'mailfrom') //
208 "Proxmox Mail Gateway <postmaster>";
210 my $dbh = PMG
::DBTools
::open_ruledb
();
212 my $target = $param->{receiver
};
213 my $redirect = $param->{redirect
};
215 if (defined($redirect) && !defined($target)) {
216 die "can't redirect mails for all users\n";
219 my $domains = PVE
::INotify
::read_file
('domains');
220 my $domainregex = domain_regex
([keys %$domains]);
224 if ($reportstyle ne 'none') {
226 $template = "spamreport-${reportstyle}.tt";
228 foreach my $path (@$PMG::Config
::tt_include_path
) {
229 if (-f
"$path/$template") { $found = 1; last; }
232 warn "unable to find template '$template' - using default\n";
233 $template = "spamreport-verbose.tt";
237 my $sth = $dbh->prepare(
238 "SELECT * FROM CMailStore, CMSReceivers " .
239 "WHERE time >= $start AND time < $end AND " .
240 ($target ?
"pmail = ? AND " : '') .
241 "QType = 'S' AND CID = CMailStore_CID AND RID = CMailStore_RID " .
242 "AND Status = 'N' " .
243 "ORDER BY pmail, time, receiver");
246 $sth->execute($target);
256 my $tt = PMG
::Config
::get_template_toolkit
();
260 my $extern = ($domainregex && $creceiver !~ $domainregex);
264 $data->{mailcount
} = $mailcount;
265 my $sendto = $redirect ?
$redirect : $creceiver;
266 PMG
::Utils
::finalize_report
($tt, $template, $data, $mailfrom, $sendto, $param->{debug
});
269 my $hint = $extern ?
" (external address)" : "";
270 printf ("%-5d %s$hint\n", $mailcount, $creceiver);
274 while (my $ref = $sth->fetchrow_hashref()) {
275 if ($creceiver ne $ref->{pmail
}) {
277 $finalize->() if $data;
279 $data = clone
($global_data);
281 $creceiver = $ref->{pmail
};
284 $data->{pmail
} = $creceiver;
285 $data->{ticket
} = PMG
::Ticket
::assemble_quarantine_ticket
($data->{pmail
});
286 my $esc_ticket = uri_escape
($data->{ticket
});
287 $data->{managehref
} = "https://$fqdn:$port/quarantine?ticket=${esc_ticket}";
291 push @{$data->{items
}}, get_item_data
($data, $ref);
300 $finalize->() if $data;
302 if (defined($target) && !$mailcount) {
303 print STDERR
"no mails for '$target'\n";
309 sub find_stale_files
{
310 my ($path, $lifetime, $purge) = @_;
312 return if ! -d
$path;
314 my (undef, undef, undef, $mday, $mon, $year) = localtime(time());
315 my $daystart = timelocal
(0, 0, 0, $mday, $mon, $year);
316 my $expire = $daystart - $lifetime*86400;
319 my $name = $File::Find
::name
;
320 return if $name !~ m
|^($path/.*)$|;
321 $name = $1; # untaint
322 my $stat = stat($name);
324 return if $stat->mtime >= $expire;
327 print "removed: $name\n";
334 find
({ wanted
=> $wanted, no_chdir
=> 1 }, $path);
337 sub test_quarantine_files
{
338 my ($spamlifetime, $viruslifetime, $purge) = @_;
340 print STDERR
"searching for stale files\n" if !$purge;
342 my $spooldir = $PMG::MailQueue
::spooldir
;
344 find_stale_files
("$spooldir/spam", $spamlifetime, $purge);
345 foreach my $dir (<"/var/spool/pmg/cluster/*/spam">) {
346 next if $dir !~ m
|^(/var/spool/pmg/cluster
/\d+/spam)$|;
348 find_stale_files
($dir, $spamlifetime, $purge);
351 find_stale_files
("$spooldir/virus", $viruslifetime, $purge);
352 foreach my $dir (<"/var/spool/pmg/cluster/*/virus">) {
353 next if $dir !~ m
|^(/var/spool/pmg/cluster
/\d+/virus
)$|;
355 find_stale_files
($dir, $viruslifetime, $purge);
359 __PACKAGE__-
>register_method ({
363 description
=> "Cleanup Quarantine database. Remove entries older than configured quarantine lifetime.",
365 additionalProperties
=> 0,
368 description
=> "Only search for quarantine files older than configured quarantine lifetime. Just print found files, but do not remove them.",
375 returns
=> { type
=> 'null'},
379 my $cfg = PMG
::Config-
>new();
381 my $spamlifetime = $cfg->get('spamquar', 'lifetime');
382 my $viruslifetime = $cfg->get ('virusquar', 'lifetime');
384 my $purge = !$param->{check
};
387 print STDERR
"purging database\n";
389 my $dbh = PMG
::DBTools
::open_ruledb
();
391 if (my $count = PMG
::DBTools
::purge_quarantine_database
($dbh, 'S', $spamlifetime)) {
392 print STDERR
"removed $count spam quarantine files\n";
395 if (my $count = PMG
::DBTools
::purge_quarantine_database
($dbh, 'V', $viruslifetime)) {
396 print STDERR
"removed $count virus quarantine files\n";
400 test_quarantine_files
($spamlifetime, $viruslifetime, $purge);
407 'purge' => [ __PACKAGE__
, 'purge', []],
408 'send' => [ __PACKAGE__
, 'send', []],
409 'spam' => [ 'PMG::API2::Quarantine', 'spam', [], undef, sub {
411 print "Day Count AVG(Spam)\n";
412 foreach my $ref (@$res) {
413 print sprintf("%-12s %5d %10.2f\n",
414 strftime
("%F", localtime($ref->{day
})),
415 $ref->{count
}, $ref->{spamavg
});