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 @fromarray = split('\s*,\s*', $head->get('from') || $ref->{sender
});
50 my $from = PMG
::Utils
::rfc1522_to_html
(PVE
::Tools
::trim
($fromarray[0]));
51 my $sender = PMG
::Utils
::rfc1522_to_html
(PVE
::Tools
::trim
($head->get('sender')));
54 $item->{sender
} = $sender;
55 $item->{from
} = sprintf ("%s on behalf of %s", $sender, $from);
57 $item->{from
} = $from;
60 $item->{envelope_sender
} = $ref->{sender
};
61 $item->{pmail
} = $ref->{pmail
};
62 $item->{receiver
} = $ref->{receiver
} || $ref->{pmail
};
64 $item->{date
} = strftime
("%F", localtime($ref->{time}));
65 $item->{time} = strftime
("%H:%M:%S", localtime($ref->{time}));
67 $item->{bytes
} = $ref->{bytes
};
68 $item->{spamlevel
} = $ref->{spamlevel
};
69 $item->{spaminfo
} = $ref->{info
};
70 $item->{file
} = $ref->{file
};
72 my $basehref = "$data->{protocol_fqdn_port}/quarantine";
73 my $ticket = uri_escape
($data->{ticket
});
74 $item->{href
} = "$basehref?ticket=$ticket&cselect=$item->{id}&date=$item->{date}";
79 __PACKAGE__-
>register_method ({
83 description
=> "Print quarantine status (mails per user) for specified time span.",
85 additionalProperties
=> 0,
88 description
=> "Select time span.",
90 enum
=> ['today', 'yesterday', 'week'],
96 returns
=> { type
=> 'null'},
100 my $cinfo = PMG
::ClusterConfig-
>new();
101 my $role = $cinfo->{local}->{type
} // '-';
103 if (!(($role eq '-') || ($role eq 'master'))) {
104 warn "local node is not master\n";
108 my $cfg = PMG
::Config-
>new();
110 my $timespan = $param->{timespan
} // 'today';
112 my ($start, $end) = PMG
::Utils
::lookup_timespan
($timespan);
114 my $hostname = PVE
::INotify
::nodename
();
116 my $fqdn = $cfg->get('spamquar', 'hostname') //
117 PVE
::Tools
::get_fqdn
($hostname);
120 my $dbh = PMG
::DBTools
::open_ruledb
();
122 my $domains = PVE
::INotify
::read_file
('domains');
123 my $domainregex = PMG
::Utils
::domain_regex
([keys %$domains]);
125 my $sth = $dbh->prepare(
126 "SELECT pmail, AVG(spamlevel) as spamlevel, count(*) FROM CMailStore, CMSReceivers " .
127 "WHERE time >= $start AND time < $end AND " .
128 "QType = 'S' AND CID = CMailStore_CID AND RID = CMailStore_RID " .
129 "AND Status = 'N' " .
135 print "Count Spamlevel Mail\n";
137 while (my $ref = $sth->fetchrow_hashref()) {
139 my $extern = ($domainregex && $ref->{pmail
} !~ $domainregex);
140 my $hint = $extern ?
" (external address)" : "";
141 printf ("%-5d %10.2f %s$hint\n", $ref->{count
}, $ref->{spamlevel
}, $ref->{pmail
});
149 __PACKAGE__-
>register_method ({
153 description
=> "Generate and send spam report emails.",
155 additionalProperties
=> 0,
158 description
=> "Generate report for a single email address. If not specified, generate reports for all users.",
159 type
=> 'string', format
=> 'email',
163 description
=> "Select time span.",
165 enum
=> ['today', 'yesterday', 'week'],
170 description
=> "Spam report style. Default value is read from spam quarantine configuration.",
172 enum
=> ['short', 'verbose', 'custom'],
176 description
=> "Redirect spam report email to this address.",
177 type
=> 'string', format
=> 'email',
181 description
=> "Debug mode. Print raw email to stdout instead of sending them.",
188 returns
=> { type
=> 'null'},
192 my $cinfo = PMG
::ClusterConfig-
>new();
193 my $role = $cinfo->{local}->{type
} // '-';
195 if (!(($role eq '-') || ($role eq 'master'))) {
196 warn "local node is not master - not sending spam report\n";
200 my $cfg = PMG
::Config-
>new();
202 my $reportstyle = $param->{style
} // $cfg->get('spamquar', 'reportstyle');
204 # overwrite report style none when:
205 # - explicit receiver specified
206 # - when debug flag enabled
207 if ($reportstyle eq 'none') {
208 $reportstyle = 'verbose' if $param->{debug
} || defined($param->{receiver
});
211 return if $reportstyle eq 'none'; # do nothing
213 my $timespan = $param->{timespan
} // 'today';
215 my ($start, $end) = PMG
::Utils
::lookup_timespan
($timespan);
217 my $hostname = PVE
::INotify
::nodename
();
219 my $fqdn = $cfg->get('spamquar', 'hostname') //
220 PVE
::Tools
::get_fqdn
($hostname);
222 my $port = $cfg->get('spamquar', 'port') // 8006;
224 my $protocol = $cfg->get('spamquar', 'protocol') // 'https';
226 my $protocol_fqdn_port = "$protocol://$fqdn";
227 if (($protocol eq 'https' && $port != 443) ||
228 ($protocol eq 'http' && $port != 80)) {
229 $protocol_fqdn_port .= ":$port";
233 protocol
=> $protocol,
236 hostname
=> $hostname,
237 date
=> strftime
("%F", localtime($end - 1)),
238 timespan
=> $timespan,
240 protocol_fqdn_port
=> $protocol_fqdn_port,
243 my $mailfrom = $cfg->get ('spamquar', 'mailfrom') //
244 "Proxmox Mail Gateway <postmaster>";
246 my $dbh = PMG
::DBTools
::open_ruledb
();
248 my $target = $param->{receiver
};
249 my $redirect = $param->{redirect
};
251 if (defined($redirect) && !defined($target)) {
252 die "can't redirect mails for all users\n";
255 my $domains = PVE
::INotify
::read_file
('domains');
256 my $domainregex = PMG
::Utils
::domain_regex
([keys %$domains]);
258 my $template = "spamreport-${reportstyle}.tt";
260 foreach my $path (@$PMG::Config
::tt_include_path
) {
261 if (-f
"$path/$template") { $found = 1; last; }
264 warn "unable to find template '$template' - using default\n";
265 $template = "spamreport-verbose.tt";
268 my $sth = $dbh->prepare(
269 "SELECT * FROM CMailStore, CMSReceivers " .
270 "WHERE time >= $start AND time < $end AND " .
271 ($target ?
"pmail = ? AND " : '') .
272 "QType = 'S' AND CID = CMailStore_CID AND RID = CMailStore_RID " .
273 "AND Status = 'N' " .
274 "ORDER BY pmail, time, receiver");
277 $sth->execute($target);
286 my $tt = PMG
::Config
::get_template_toolkit
();
290 my $extern = ($domainregex && $creceiver !~ $domainregex);
292 $data->{mailcount
} = $mailcount;
293 my $sendto = $redirect ?
$redirect : $creceiver;
294 PMG
::Utils
::finalize_report
($tt, $template, $data, $mailfrom, $sendto, $param->{debug
});
298 while (my $ref = $sth->fetchrow_hashref()) {
299 if ($creceiver ne $ref->{pmail
}) {
301 $finalize->() if $data;
303 $data = clone
($global_data);
305 $creceiver = $ref->{pmail
};
308 $data->{pmail
} = $creceiver;
309 $data->{ticket
} = PMG
::Ticket
::assemble_quarantine_ticket
($data->{pmail
});
310 my $esc_ticket = uri_escape
($data->{ticket
});
311 $data->{managehref
} = "$protocol_fqdn_port/quarantine?ticket=${esc_ticket}";
314 push @{$data->{items
}}, get_item_data
($data, $ref);
321 $finalize->() if $data;
323 if (defined($target) && !$mailcount) {
324 print STDERR
"no mails for '$target'\n";
330 sub find_stale_files
{
331 my ($path, $lifetime, $purge) = @_;
333 return if ! -d
$path;
335 my (undef, undef, undef, $mday, $mon, $year) = localtime(time());
336 my $daystart = timelocal
(0, 0, 0, $mday, $mon, $year);
337 my $expire = $daystart - $lifetime*86400;
340 my $name = $File::Find
::name
;
341 return if $name !~ m
|^($path/.*)$|;
342 $name = $1; # untaint
343 my $stat = stat($name);
345 return if $stat->mtime >= $expire;
348 print "removed: $name\n";
355 find
({ wanted
=> $wanted, no_chdir
=> 1 }, $path);
358 sub test_quarantine_files
{
359 my ($spamlifetime, $viruslifetime, $purge) = @_;
361 print STDERR
"searching for stale files\n" if !$purge;
363 my $spooldir = $PMG::MailQueue
::spooldir
;
365 find_stale_files
("$spooldir/spam", $spamlifetime, $purge);
366 foreach my $dir (<"/var/spool/pmg/cluster/*/spam">) {
367 next if $dir !~ m
|^(/var/spool/pmg/cluster
/\d+/spam)$|;
369 find_stale_files
($dir, $spamlifetime, $purge);
372 find_stale_files
("$spooldir/virus", $viruslifetime, $purge);
373 foreach my $dir (<"/var/spool/pmg/cluster/*/virus">) {
374 next if $dir !~ m
|^(/var/spool/pmg/cluster
/\d+/virus
)$|;
376 find_stale_files
($dir, $viruslifetime, $purge);
380 __PACKAGE__-
>register_method ({
384 description
=> "Cleanup Quarantine database. Remove entries older than configured quarantine lifetime.",
386 additionalProperties
=> 0,
389 description
=> "Only search for quarantine files older than configured quarantine lifetime. Just print found files, but do not remove them.",
396 returns
=> { type
=> 'null'},
400 my $cfg = PMG
::Config-
>new();
402 my $spamlifetime = $cfg->get('spamquar', 'lifetime');
403 my $viruslifetime = $cfg->get ('virusquar', 'lifetime');
405 my $purge = !$param->{check
};
408 print STDERR
"purging database\n";
410 my $dbh = PMG
::DBTools
::open_ruledb
();
412 if (my $count = PMG
::DBTools
::purge_quarantine_database
($dbh, 'S', $spamlifetime)) {
413 print STDERR
"removed $count spam quarantine files\n";
416 if (my $count = PMG
::DBTools
::purge_quarantine_database
($dbh, 'V', $viruslifetime)) {
417 print STDERR
"removed $count virus quarantine files\n";
420 if (my $count = PMG
::DBTools
::purge_quarantine_database
($dbh, 'A', $spamlifetime)) {
421 print STDERR
"removed $count attachment quarantine files\n";
425 test_quarantine_files
($spamlifetime, $viruslifetime, $purge);
432 'purge' => [ __PACKAGE__
, 'purge', []],
433 'send' => [ __PACKAGE__
, 'send', []],
434 'status' => [ __PACKAGE__
, 'status', []],