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 if ($data->{authmode
} ne 'ldap') {
74 my $ticket = uri_escape
($data->{ticket
});
75 $item->{href
} = "$basehref?ticket=$ticket&cselect=$item->{id}&date=$item->{date}";
77 $item->{href
} = "$basehref?cselect=$item->{id}&date=$item->{date}";
83 __PACKAGE__-
>register_method ({
87 description
=> "Print quarantine status (mails per user) for specified time span.",
89 additionalProperties
=> 0,
92 description
=> "Select time span.",
94 enum
=> ['today', 'yesterday', 'week'],
100 returns
=> { type
=> 'null'},
104 my $cinfo = PMG
::ClusterConfig-
>new();
105 my $role = $cinfo->{local}->{type
} // '-';
107 if (!(($role eq '-') || ($role eq 'master'))) {
108 warn "local node is not master\n";
112 my $cfg = PMG
::Config-
>new();
114 my $timespan = $param->{timespan
} // 'today';
116 my ($start, $end) = PMG
::Utils
::lookup_timespan
($timespan);
118 my $hostname = PVE
::INotify
::nodename
();
120 my $fqdn = $cfg->get('spamquar', 'hostname') //
121 PVE
::Tools
::get_fqdn
($hostname);
124 my $dbh = PMG
::DBTools
::open_ruledb
();
126 my $domains = PVE
::INotify
::read_file
('domains');
127 my $domainregex = PMG
::Utils
::domain_regex
([keys %$domains]);
129 my $sth = $dbh->prepare(
130 "SELECT pmail, AVG(spamlevel) as spamlevel, count(*) FROM CMailStore, CMSReceivers " .
131 "WHERE time >= $start AND time < $end AND " .
132 "QType = 'S' AND CID = CMailStore_CID AND RID = CMailStore_RID " .
133 "AND Status = 'N' " .
139 print "Count Spamlevel Mail\n";
141 while (my $ref = $sth->fetchrow_hashref()) {
143 my $extern = ($domainregex && $ref->{pmail
} !~ $domainregex);
144 my $hint = $extern ?
" (external address)" : "";
145 printf ("%-5d %10.2f %s$hint\n", $ref->{count
}, $ref->{spamlevel
}, $ref->{pmail
});
153 __PACKAGE__-
>register_method ({
157 description
=> "Generate and send spam report emails.",
159 additionalProperties
=> 0,
162 description
=> "Generate report for a single email address. If not specified, generate reports for all users.",
163 type
=> 'string', format
=> 'email',
167 description
=> "Select time span.",
169 enum
=> ['today', 'yesterday', 'week'],
174 description
=> "Spam report style. Default value is read from spam quarantine configuration.",
176 enum
=> ['short', 'verbose', 'custom'],
180 description
=> "Redirect spam report email to this address.",
181 type
=> 'string', format
=> 'email',
185 description
=> "Debug mode. Print raw email to stdout instead of sending them.",
192 returns
=> { type
=> 'null'},
196 my $cinfo = PMG
::ClusterConfig-
>new();
197 my $role = $cinfo->{local}->{type
} // '-';
199 if (!(($role eq '-') || ($role eq 'master'))) {
200 warn "local node is not master - not sending spam report\n";
204 my $cfg = PMG
::Config-
>new();
206 my $reportstyle = $param->{style
} // $cfg->get('spamquar', 'reportstyle');
208 # overwrite report style none when:
209 # - explicit receiver specified
210 # - when debug flag enabled
211 if ($reportstyle eq 'none') {
212 $reportstyle = 'verbose' if $param->{debug
} || defined($param->{receiver
});
215 return if $reportstyle eq 'none'; # do nothing
217 my $timespan = $param->{timespan
} // 'today';
219 my ($start, $end) = PMG
::Utils
::lookup_timespan
($timespan);
221 my $hostname = PVE
::INotify
::nodename
();
223 my $fqdn = $cfg->get('spamquar', 'hostname') //
224 PVE
::Tools
::get_fqdn
($hostname);
226 my $port = $cfg->get('spamquar', 'port') // 8006;
228 my $protocol = $cfg->get('spamquar', 'protocol') // 'https';
230 my $protocol_fqdn_port = "$protocol://$fqdn";
231 if (($protocol eq 'https' && $port != 443) ||
232 ($protocol eq 'http' && $port != 80)) {
233 $protocol_fqdn_port .= ":$port";
236 my $authmode = $cfg->get ('spamquar', 'authmode') // 'ticket';
239 protocol
=> $protocol,
242 hostname
=> $hostname,
243 date
=> strftime
("%F", localtime($end - 1)),
244 timespan
=> $timespan,
246 protocol_fqdn_port
=> $protocol_fqdn_port,
247 authmode
=> $authmode,
250 my $mailfrom = $cfg->get ('spamquar', 'mailfrom') //
251 "Proxmox Mail Gateway <postmaster>";
253 my $dbh = PMG
::DBTools
::open_ruledb
();
255 my $target = $param->{receiver
};
256 my $redirect = $param->{redirect
};
258 if (defined($redirect) && !defined($target)) {
259 die "can't redirect mails for all users\n";
262 my $domains = PVE
::INotify
::read_file
('domains');
263 my $domainregex = PMG
::Utils
::domain_regex
([keys %$domains]);
265 my $template = "spamreport-${reportstyle}.tt";
267 foreach my $path (@$PMG::Config
::tt_include_path
) {
268 if (-f
"$path/$template") { $found = 1; last; }
271 warn "unable to find template '$template' - using default\n";
272 $template = "spamreport-verbose.tt";
275 my $sth = $dbh->prepare(
276 "SELECT * FROM CMailStore, CMSReceivers " .
277 "WHERE time >= $start AND time < $end AND " .
278 ($target ?
"pmail = ? AND " : '') .
279 "QType = 'S' AND CID = CMailStore_CID AND RID = CMailStore_RID " .
280 "AND Status = 'N' " .
281 "ORDER BY pmail, time, receiver");
284 $sth->execute($target);
293 my $tt = PMG
::Config
::get_template_toolkit
();
297 my $extern = ($domainregex && $creceiver !~ $domainregex);
299 $data->{mailcount
} = $mailcount;
300 my $sendto = $redirect ?
$redirect : $creceiver;
301 PMG
::Utils
::finalize_report
($tt, $template, $data, $mailfrom, $sendto, $param->{debug
});
305 while (my $ref = $sth->fetchrow_hashref()) {
306 if ($creceiver ne $ref->{pmail
}) {
308 $finalize->() if $data;
310 $data = clone
($global_data);
312 $creceiver = $ref->{pmail
};
315 $data->{pmail
} = $creceiver;
316 $data->{managehref
} = "$protocol_fqdn_port/quarantine";
317 if ($data->{authmode
} ne 'ldap') {
318 $data->{ticket
} = PMG
::Ticket
::assemble_quarantine_ticket
($data->{pmail
});
319 my $esc_ticket = uri_escape
($data->{ticket
});
320 $data->{managehref
} .= "?ticket=${esc_ticket}";
325 push @{$data->{items
}}, get_item_data
($data, $ref);
332 $finalize->() if $data;
334 if (defined($target) && !$mailcount) {
335 print STDERR
"no mails for '$target'\n";
341 sub find_stale_files
{
342 my ($path, $lifetime, $purge) = @_;
344 return if ! -d
$path;
346 my (undef, undef, undef, $mday, $mon, $year) = localtime(time());
347 my $daystart = timelocal
(0, 0, 0, $mday, $mon, $year);
348 my $expire = $daystart - $lifetime*86400;
351 my $name = $File::Find
::name
;
352 return if $name !~ m
|^($path/.*)$|;
353 $name = $1; # untaint
354 my $stat = stat($name);
356 return if $stat->mtime >= $expire;
359 print "removed: $name\n";
366 find
({ wanted
=> $wanted, no_chdir
=> 1 }, $path);
369 sub test_quarantine_files
{
370 my ($spamlifetime, $viruslifetime, $purge) = @_;
372 print STDERR
"searching for stale files\n" if !$purge;
374 my $spooldir = $PMG::MailQueue
::spooldir
;
376 find_stale_files
("$spooldir/spam", $spamlifetime, $purge);
377 foreach my $dir (<"/var/spool/pmg/cluster/*/spam">) {
378 next if $dir !~ m
|^(/var/spool/pmg/cluster
/\d+/spam)$|;
380 find_stale_files
($dir, $spamlifetime, $purge);
383 find_stale_files
("$spooldir/virus", $viruslifetime, $purge);
384 foreach my $dir (<"/var/spool/pmg/cluster/*/virus">) {
385 next if $dir !~ m
|^(/var/spool/pmg/cluster
/\d+/virus
)$|;
387 find_stale_files
($dir, $viruslifetime, $purge);
391 __PACKAGE__-
>register_method ({
395 description
=> "Cleanup Quarantine database. Remove entries older than configured quarantine lifetime.",
397 additionalProperties
=> 0,
400 description
=> "Only search for quarantine files older than configured quarantine lifetime. Just print found files, but do not remove them.",
407 returns
=> { type
=> 'null'},
411 my $cfg = PMG
::Config-
>new();
413 my $spamlifetime = $cfg->get('spamquar', 'lifetime');
414 my $viruslifetime = $cfg->get ('virusquar', 'lifetime');
416 my $purge = !$param->{check
};
419 print STDERR
"purging database\n";
421 my $dbh = PMG
::DBTools
::open_ruledb
();
423 if (my $count = PMG
::DBTools
::purge_quarantine_database
($dbh, 'S', $spamlifetime)) {
424 print STDERR
"removed $count spam quarantine files\n";
427 if (my $count = PMG
::DBTools
::purge_quarantine_database
($dbh, 'V', $viruslifetime)) {
428 print STDERR
"removed $count virus quarantine files\n";
431 if (my $count = PMG
::DBTools
::purge_quarantine_database
($dbh, 'A', $spamlifetime)) {
432 print STDERR
"removed $count attachment quarantine files\n";
436 test_quarantine_files
($spamlifetime, $viruslifetime, $purge);
443 'purge' => [ __PACKAGE__
, 'purge', []],
444 'send' => [ __PACKAGE__
, 'send', []],
445 'status' => [ __PACKAGE__
, 'status', []],