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();
37 my ($data, $ref) = @_;
39 my @lines = split ('\n', $ref->{header
});
40 my $head = new Mail
::Header
(\
@lines);
44 $item->{id
} = sprintf("C%dR%dT%d", $ref->{cid
}, $ref->{rid
}, $ref->{ticketid
});
46 $item->{subject
} = PMG
::Utils
::rfc1522_to_html
(
47 PVE
::Tools
::trim
($head->get('subject')) || 'No Subject');
49 my $from = PMG
::Utils
::rfc1522_to_html
(PVE
::Tools
::trim
($head->get('from') // $ref->{sender
}));
50 my $sender = PMG
::Utils
::rfc1522_to_html
(PVE
::Tools
::trim
($head->get('sender')));
53 $item->{sender
} = $sender;
54 $item->{from
} = sprintf ("%s on behalf of %s", $sender, $from);
56 $item->{from
} = $from;
59 $item->{envelope_sender
} = $ref->{sender
};
60 $item->{pmail
} = $ref->{pmail
};
61 $item->{receiver
} = $ref->{receiver
} || $ref->{pmail
};
63 $item->{date
} = strftime
("%F", localtime($ref->{time}));
64 $item->{time} = strftime
("%H:%M:%S", localtime($ref->{time}));
66 $item->{bytes
} = $ref->{bytes
};
67 $item->{spamlevel
} = $ref->{spamlevel
};
68 $item->{spaminfo
} = $ref->{info
};
69 $item->{file
} = $ref->{file
};
71 my $basehref = "$data->{protocol_fqdn_port}/quarantine";
72 if ($data->{authmode
} ne 'ldap') {
73 my $ticket = uri_escape
($data->{ticket
});
74 $item->{href
} = "$basehref?ticket=$ticket&cselect=$item->{id}&date=$item->{date}";
76 $item->{href
} = "$basehref?cselect=$item->{id}&date=$item->{date}";
82 __PACKAGE__-
>register_method ({
86 description
=> "Print quarantine status (mails per user) for specified time span.",
88 additionalProperties
=> 0,
91 description
=> "Select time span.",
93 enum
=> ['today', 'yesterday', 'week'],
99 returns
=> { type
=> 'null'},
103 my $cinfo = PMG
::ClusterConfig-
>new();
104 my $role = $cinfo->{local}->{type
} // '-';
106 if (!(($role eq '-') || ($role eq 'master'))) {
107 warn "local node is not master\n";
111 my $cfg = PMG
::Config-
>new();
113 my $timespan = $param->{timespan
} // 'today';
115 my ($start, $end) = PMG
::Utils
::lookup_timespan
($timespan);
117 my $hostname = PVE
::INotify
::nodename
();
119 my $fqdn = $cfg->get('spamquar', 'hostname') //
120 PVE
::Tools
::get_fqdn
($hostname);
123 my $dbh = PMG
::DBTools
::open_ruledb
();
125 my $domains = PVE
::INotify
::read_file
('domains');
126 my $domainregex = PMG
::Utils
::domain_regex
([keys %$domains]);
128 my $sth = $dbh->prepare(
129 "SELECT pmail, AVG(spamlevel) as spamlevel, count(*) FROM CMailStore, CMSReceivers " .
130 "WHERE time >= $start AND time < $end AND " .
131 "QType = 'S' AND CID = CMailStore_CID AND RID = CMailStore_RID " .
132 "AND Status = 'N' " .
138 print "Count Spamlevel Mail\n";
140 while (my $ref = $sth->fetchrow_hashref()) {
142 my $extern = ($domainregex && $ref->{pmail
} !~ $domainregex);
143 my $hint = $extern ?
" (external address)" : "";
144 printf ("%-5d %10.2f %s$hint\n", $ref->{count
}, $ref->{spamlevel
}, $ref->{pmail
});
152 __PACKAGE__-
>register_method ({
156 description
=> "Generate and send spam report emails.",
158 additionalProperties
=> 0,
161 description
=> "Generate report for a single email address. If not specified, generate reports for all users.",
162 type
=> 'string', format
=> 'email',
166 description
=> "Select time span.",
168 enum
=> ['today', 'yesterday', 'week'],
173 description
=> "Spam report style. Default value is read from spam quarantine configuration.",
175 enum
=> ['short', 'verbose', 'custom'],
179 description
=> "Redirect spam report email to this address.",
180 type
=> 'string', format
=> 'email',
184 description
=> "Debug mode. Print raw email to stdout instead of sending them.",
191 returns
=> { type
=> 'null'},
195 my $cinfo = PMG
::ClusterConfig-
>new();
196 my $role = $cinfo->{local}->{type
} // '-';
198 if (!(($role eq '-') || ($role eq 'master'))) {
199 warn "local node is not master - not sending spam report\n";
203 my $cfg = PMG
::Config-
>new();
205 my $reportstyle = $param->{style
} // $cfg->get('spamquar', 'reportstyle');
207 # overwrite report style none when:
208 # - explicit receiver specified
209 # - when debug flag enabled
210 if ($reportstyle eq 'none') {
211 $reportstyle = 'verbose' if $param->{debug
} || defined($param->{receiver
});
214 return if $reportstyle eq 'none'; # do nothing
216 my $timespan = $param->{timespan
} // 'today';
218 my ($start, $end) = PMG
::Utils
::lookup_timespan
($timespan);
220 my $hostname = PVE
::INotify
::nodename
();
222 my $fqdn = $cfg->get('spamquar', 'hostname') //
223 PVE
::Tools
::get_fqdn
($hostname);
225 my $port = $cfg->get('spamquar', 'port') // 8006;
227 my $protocol = $cfg->get('spamquar', 'protocol') // 'https';
229 my $protocol_fqdn_port = "$protocol://$fqdn";
230 if (($protocol eq 'https' && $port != 443) ||
231 ($protocol eq 'http' && $port != 80)) {
232 $protocol_fqdn_port .= ":$port";
235 my $authmode = $cfg->get ('spamquar', 'authmode') // 'ticket';
238 protocol
=> $protocol,
241 hostname
=> $hostname,
242 date
=> strftime
("%F", localtime($end - 1)),
243 timespan
=> $timespan,
245 protocol_fqdn_port
=> $protocol_fqdn_port,
246 authmode
=> $authmode,
249 my $mailfrom = $cfg->get ('spamquar', 'mailfrom') //
250 "Proxmox Mail Gateway <postmaster>";
252 my $dbh = PMG
::DBTools
::open_ruledb
();
254 my $target = $param->{receiver
};
255 my $redirect = $param->{redirect
};
257 if (defined($redirect) && !defined($target)) {
258 die "can't redirect mails for all users\n";
261 my $domains = PVE
::INotify
::read_file
('domains');
262 my $domainregex = PMG
::Utils
::domain_regex
([keys %$domains]);
264 my $template = "spamreport-${reportstyle}.tt";
266 foreach my $path (@$PMG::Config
::tt_include_path
) {
267 if (-f
"$path/$template") { $found = 1; last; }
270 warn "unable to find template '$template' - using default\n";
271 $template = "spamreport-verbose.tt";
274 my $sth = $dbh->prepare(
275 "SELECT * FROM CMailStore, CMSReceivers " .
276 "WHERE time >= $start AND time < $end AND " .
277 ($target ?
"pmail = ? AND " : '') .
278 "QType = 'S' AND CID = CMailStore_CID AND RID = CMailStore_RID " .
279 "AND Status = 'N' " .
280 "ORDER BY pmail, time, receiver");
283 $sth->execute($target);
292 my $tt = PMG
::Config
::get_template_toolkit
();
296 my $extern = ($domainregex && $creceiver !~ $domainregex);
298 $data->{mailcount
} = $mailcount;
299 my $sendto = $redirect ?
$redirect : $creceiver;
300 PMG
::Utils
::finalize_report
($tt, $template, $data, $mailfrom, $sendto, $param->{debug
});
304 while (my $ref = $sth->fetchrow_hashref()) {
305 if ($creceiver ne $ref->{pmail
}) {
307 $finalize->() if $data;
309 $data = clone
($global_data);
311 $creceiver = $ref->{pmail
};
314 $data->{pmail
} = $creceiver;
315 $data->{managehref
} = "$protocol_fqdn_port/quarantine";
316 if ($data->{authmode
} ne 'ldap') {
317 $data->{ticket
} = PMG
::Ticket
::assemble_quarantine_ticket
($data->{pmail
});
318 my $esc_ticket = uri_escape
($data->{ticket
});
319 $data->{managehref
} .= "?ticket=${esc_ticket}";
324 push @{$data->{items
}}, get_item_data
($data, $ref);
331 $finalize->() if $data;
333 if (defined($target) && !$mailcount) {
334 print STDERR
"no mails for '$target'\n";
340 sub find_stale_files
{
341 my ($path, $lifetime, $purge) = @_;
343 return if ! -d
$path;
345 my (undef, undef, undef, $mday, $mon, $year) = localtime(time());
346 my $daystart = timelocal
(0, 0, 0, $mday, $mon, $year);
347 my $expire = $daystart - $lifetime*86400;
350 my $name = $File::Find
::name
;
351 return if $name !~ m
|^($path/.*)$|;
352 $name = $1; # untaint
353 my $stat = stat($name);
355 return if $stat->mtime >= $expire;
358 print "removed: $name\n";
365 find
({ wanted
=> $wanted, no_chdir
=> 1 }, $path);
368 sub test_quarantine_files
{
369 my ($spamlifetime, $viruslifetime, $purge) = @_;
371 print STDERR
"searching for stale files\n" if !$purge;
373 my $spooldir = $PMG::MailQueue
::spooldir
;
375 find_stale_files
("$spooldir/spam", $spamlifetime, $purge);
376 foreach my $dir (<"/var/spool/pmg/cluster/*/spam">) {
377 next if $dir !~ m
|^(/var/spool/pmg/cluster
/\d+/spam)$|;
379 find_stale_files
($dir, $spamlifetime, $purge);
382 find_stale_files
("$spooldir/virus", $viruslifetime, $purge);
383 foreach my $dir (<"/var/spool/pmg/cluster/*/virus">) {
384 next if $dir !~ m
|^(/var/spool/pmg/cluster
/\d+/virus
)$|;
386 find_stale_files
($dir, $viruslifetime, $purge);
390 __PACKAGE__-
>register_method ({
394 description
=> "Cleanup Quarantine database. Remove entries older than configured quarantine lifetime.",
396 additionalProperties
=> 0,
399 description
=> "Only search for quarantine files older than configured quarantine lifetime. Just print found files, but do not remove them.",
406 returns
=> { type
=> 'null'},
410 my $cfg = PMG
::Config-
>new();
412 my $spamlifetime = $cfg->get('spamquar', 'lifetime');
413 my $viruslifetime = $cfg->get ('virusquar', 'lifetime');
415 my $purge = !$param->{check
};
418 print STDERR
"purging database\n";
420 my $dbh = PMG
::DBTools
::open_ruledb
();
422 if (my $count = PMG
::DBTools
::purge_quarantine_database
($dbh, 'S', $spamlifetime)) {
423 print STDERR
"removed $count spam quarantine files\n";
426 if (my $count = PMG
::DBTools
::purge_quarantine_database
($dbh, 'V', $viruslifetime)) {
427 print STDERR
"removed $count virus quarantine files\n";
430 if (my $count = PMG
::DBTools
::purge_quarantine_database
($dbh, 'A', $spamlifetime)) {
431 print STDERR
"removed $count attachment quarantine files\n";
435 test_quarantine_files
($spamlifetime, $viruslifetime, $purge);
442 'purge' => [ __PACKAGE__
, 'purge', []],
443 'send' => [ __PACKAGE__
, 'send', []],
444 'status' => [ __PACKAGE__
, 'status', []],