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%dT%d", $ref->{cid
}, $ref->{rid
}, $ref->{ticketid
});
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->{envelope_sender
} = $ref->{sender
};
86 $item->{pmail
} = $ref->{pmail
};
87 $item->{receiver
} = $ref->{receiver
} || $ref->{pmail
};
89 $item->{date
} = strftime
("%F", localtime($ref->{time}));
90 $item->{time} = strftime
("%H:%M:%S", localtime($ref->{time}));
92 $item->{bytes
} = $ref->{bytes
};
93 $item->{spamlevel
} = $ref->{spamlevel
};
94 $item->{spaminfo
} = $ref->{info
};
95 $item->{file
} = $ref->{file
};
97 my $basehref = "$data->{protocol}://$data->{fqdn}:$data->{port}/quarantine";
98 my $ticket = uri_escape
($data->{ticket
});
99 $item->{href
} = "$basehref?ticket=$ticket&cselect=$item->{id}&date=$item->{date}";
104 __PACKAGE__-
>register_method ({
108 description
=> "Print quarantine status (mails per user) for specified time span.",
110 additionalProperties
=> 0,
113 description
=> "Select time span.",
115 enum
=> ['today', 'yesterday', 'week'],
121 returns
=> { type
=> 'null'},
125 my $cinfo = PMG
::ClusterConfig-
>new();
126 my $role = $cinfo->{local}->{type
} // '-';
128 if (!(($role eq '-') || ($role eq 'master'))) {
129 die "local node is not mastern";
132 my $cfg = PMG
::Config-
>new();
134 my $timespan = $param->{timespan
} // 'today';
136 my ($start, $end) = PMG
::Utils
::lookup_timespan
($timespan);
138 my $hostname = PVE
::INotify
::nodename
();
140 my $fqdn = $cfg->get('spamquar', 'hostname') //
141 PVE
::Tools
::get_fqdn
($hostname);
144 my $dbh = PMG
::DBTools
::open_ruledb
();
146 my $domains = PVE
::INotify
::read_file
('domains');
147 my $domainregex = domain_regex
([keys %$domains]);
149 my $sth = $dbh->prepare(
150 "SELECT pmail, AVG(spamlevel) as spamlevel, count(*) FROM CMailStore, CMSReceivers " .
151 "WHERE time >= $start AND time < $end AND " .
152 "QType = 'S' AND CID = CMailStore_CID AND RID = CMailStore_RID " .
153 "AND Status = 'N' " .
159 print "Count Spamlevel Mail\n";
161 while (my $ref = $sth->fetchrow_hashref()) {
163 my $extern = ($domainregex && $ref->{pmail
} !~ $domainregex);
164 my $hint = $extern ?
" (external address)" : "";
165 printf ("%-5d %10.2f %s$hint\n", $ref->{count
}, $ref->{spamlevel
}, $ref->{pmail
});
173 __PACKAGE__-
>register_method ({
177 description
=> "Generate and send spam report emails.",
179 additionalProperties
=> 0,
182 description
=> "Generate report for a single email address. If not specified, generate reports for all users.",
183 type
=> 'string', format
=> 'email',
187 description
=> "Select time span.",
189 enum
=> ['today', 'yesterday', 'week'],
194 description
=> "Spam report style. Default value is read from spam quarantine configuration.",
196 enum
=> ['short', 'verbose', 'custom'],
200 description
=> "Redirect spam report email to this address.",
201 type
=> 'string', format
=> 'email',
205 description
=> "Debug mode. Print raw email to stdout instead of sending them.",
212 returns
=> { type
=> 'null'},
216 my $cinfo = PMG
::ClusterConfig-
>new();
217 my $role = $cinfo->{local}->{type
} // '-';
219 if (!(($role eq '-') || ($role eq 'master'))) {
220 die "local node is not master - not sending spam report\n";
223 my $cfg = PMG
::Config-
>new();
225 my $reportstyle = $param->{style
} // $cfg->get('spamquar', 'reportstyle');
227 # overwrite report style none when:
228 # - explicit receiver specified
229 # - when debug flag enabled
230 if ($reportstyle eq 'none') {
231 $reportstyle = 'verbose' if $param->{debug
} || defined($param->{receiver
});
234 return if $reportstyle eq 'none'; # do nothing
236 my $timespan = $param->{timespan
} // 'today';
238 my ($start, $end) = PMG
::Utils
::lookup_timespan
($timespan);
240 my $hostname = PVE
::INotify
::nodename
();
242 my $fqdn = $cfg->get('spamquar', 'hostname') //
243 PVE
::Tools
::get_fqdn
($hostname);
245 my $port = $cfg->get('spamquar', 'port') // 8006;
247 my $protocol = $cfg->get('spamquar', 'protocol') // 'https';
250 protocol
=> $protocol,
253 hostname
=> $hostname,
254 date
=> strftime
("%F", localtime($end - 1)),
255 timespan
=> $timespan,
259 my $mailfrom = $cfg->get ('spamquar', 'mailfrom') //
260 "Proxmox Mail Gateway <postmaster>";
262 my $dbh = PMG
::DBTools
::open_ruledb
();
264 my $target = $param->{receiver
};
265 my $redirect = $param->{redirect
};
267 if (defined($redirect) && !defined($target)) {
268 die "can't redirect mails for all users\n";
271 my $domains = PVE
::INotify
::read_file
('domains');
272 my $domainregex = domain_regex
([keys %$domains]);
274 my $template = "spamreport-${reportstyle}.tt";
276 foreach my $path (@$PMG::Config
::tt_include_path
) {
277 if (-f
"$path/$template") { $found = 1; last; }
280 warn "unable to find template '$template' - using default\n";
281 $template = "spamreport-verbose.tt";
284 my $sth = $dbh->prepare(
285 "SELECT * FROM CMailStore, CMSReceivers " .
286 "WHERE time >= $start AND time < $end AND " .
287 ($target ?
"pmail = ? AND " : '') .
288 "QType = 'S' AND CID = CMailStore_CID AND RID = CMailStore_RID " .
289 "AND Status = 'N' " .
290 "ORDER BY pmail, time, receiver");
293 $sth->execute($target);
303 my $tt = PMG
::Config
::get_template_toolkit
();
307 my $extern = ($domainregex && $creceiver !~ $domainregex);
309 $data->{mailcount
} = $mailcount;
310 my $sendto = $redirect ?
$redirect : $creceiver;
311 PMG
::Utils
::finalize_report
($tt, $template, $data, $mailfrom, $sendto, $param->{debug
});
315 while (my $ref = $sth->fetchrow_hashref()) {
316 if ($creceiver ne $ref->{pmail
}) {
318 $finalize->() if $data;
320 $data = clone
($global_data);
322 $creceiver = $ref->{pmail
};
325 $data->{pmail
} = $creceiver;
326 $data->{ticket
} = PMG
::Ticket
::assemble_quarantine_ticket
($data->{pmail
});
327 my $esc_ticket = uri_escape
($data->{ticket
});
328 $data->{managehref
} = "$protocol://$fqdn:$port/quarantine?ticket=${esc_ticket}";
331 push @{$data->{items
}}, get_item_data
($data, $ref);
339 $finalize->() if $data;
341 if (defined($target) && !$mailcount) {
342 print STDERR
"no mails for '$target'\n";
348 sub find_stale_files
{
349 my ($path, $lifetime, $purge) = @_;
351 return if ! -d
$path;
353 my (undef, undef, undef, $mday, $mon, $year) = localtime(time());
354 my $daystart = timelocal
(0, 0, 0, $mday, $mon, $year);
355 my $expire = $daystart - $lifetime*86400;
358 my $name = $File::Find
::name
;
359 return if $name !~ m
|^($path/.*)$|;
360 $name = $1; # untaint
361 my $stat = stat($name);
363 return if $stat->mtime >= $expire;
366 print "removed: $name\n";
373 find
({ wanted
=> $wanted, no_chdir
=> 1 }, $path);
376 sub test_quarantine_files
{
377 my ($spamlifetime, $viruslifetime, $purge) = @_;
379 print STDERR
"searching for stale files\n" if !$purge;
381 my $spooldir = $PMG::MailQueue
::spooldir
;
383 find_stale_files
("$spooldir/spam", $spamlifetime, $purge);
384 foreach my $dir (<"/var/spool/pmg/cluster/*/spam">) {
385 next if $dir !~ m
|^(/var/spool/pmg/cluster
/\d+/spam)$|;
387 find_stale_files
($dir, $spamlifetime, $purge);
390 find_stale_files
("$spooldir/virus", $viruslifetime, $purge);
391 foreach my $dir (<"/var/spool/pmg/cluster/*/virus">) {
392 next if $dir !~ m
|^(/var/spool/pmg/cluster
/\d+/virus
)$|;
394 find_stale_files
($dir, $viruslifetime, $purge);
398 __PACKAGE__-
>register_method ({
402 description
=> "Cleanup Quarantine database. Remove entries older than configured quarantine lifetime.",
404 additionalProperties
=> 0,
407 description
=> "Only search for quarantine files older than configured quarantine lifetime. Just print found files, but do not remove them.",
414 returns
=> { type
=> 'null'},
418 my $cfg = PMG
::Config-
>new();
420 my $spamlifetime = $cfg->get('spamquar', 'lifetime');
421 my $viruslifetime = $cfg->get ('virusquar', 'lifetime');
423 my $purge = !$param->{check
};
426 print STDERR
"purging database\n";
428 my $dbh = PMG
::DBTools
::open_ruledb
();
430 if (my $count = PMG
::DBTools
::purge_quarantine_database
($dbh, 'S', $spamlifetime)) {
431 print STDERR
"removed $count spam quarantine files\n";
434 if (my $count = PMG
::DBTools
::purge_quarantine_database
($dbh, 'V', $viruslifetime)) {
435 print STDERR
"removed $count virus quarantine files\n";
438 if (my $count = PMG
::DBTools
::purge_quarantine_database
($dbh, 'A', $spamlifetime)) {
439 print STDERR
"removed $count attachment quarantine files\n";
443 test_quarantine_files
($spamlifetime, $viruslifetime, $purge);
450 'purge' => [ __PACKAGE__
, 'purge', []],
451 'send' => [ __PACKAGE__
, 'send', []],
452 'status' => [ __PACKAGE__
, 'status', []],