1 package PMG
::CLI
::pmgqm
;
11 use POSIX
qw(strftime);
20 use PMG
::RESTEnvironment
;
26 use PMG
::ClusterConfig
;
28 use base
qw(PVE::CLIHandler);
30 sub setup_environment
{
31 PMG
::RESTEnvironment-
>setup_default_cli_env();
38 foreach my $d (@$domains) {
39 # skip domains with non-DNS name characters
40 next if $d =~ m/[^A-Za-z0-9\-\.]/;
41 if ($d =~ m/^\.(.*)$/) {
45 push @ra, "\.\*\\.$dom";
52 my $re = join ('|', @ra);
54 my $regex = qr/\@($re)$/i;
60 my ($data, $ref) = @_;
62 my @lines = split ('\n', $ref->{header
});
63 my $head = new Mail
::Header
(\
@lines);
67 $item->{id
} = sprintf("C%dR%d", $ref->{cid
}, $ref->{rid
});
69 $item->{subject
} = PMG
::Utils
::rfc1522_to_html
(
70 PVE
::Tools
::trim
($head->get('subject')) || 'No Subject');
72 my @fromarray = split('\s*,\s*', $head->get('from') || $ref->{sender
});
73 my $from = PMG
::Utils
::rfc1522_to_html
(PVE
::Tools
::trim
($fromarray[0]));
74 my $sender = PMG
::Utils
::rfc1522_to_html
(PVE
::Tools
::trim
($head->get('sender')));
77 $item->{sender
} = $sender;
78 $item->{from
} = sprintf ("%s on behalf of %s", $sender, $from);
80 $item->{from
} = $from;
83 $item->{pmail
} = $ref->{pmail
};
84 $item->{receiver
} = $ref->{receiver
} || $ref->{pmail
};
86 $item->{date
} = strftime
("%F", localtime($ref->{time}));
87 $item->{time} = strftime
("%H:%M:%S", localtime($ref->{time}));
89 $item->{bytes
} = $ref->{bytes
};
90 $item->{spamlevel
} = $ref->{spamlevel
};
91 $item->{spaminfo
} = $ref->{info
};
93 my $title = "Received: $item->{date} $item->{time}\n";
94 $title .= "From: $ref->{sender}\n";
95 $title .= "To: $ref->{receiver}\n" if $ref->{receiver
};
96 $title .= sprintf("Size: %d KB\n", int (($ref->{bytes
} + 1023) / 1024 ));
97 $title .= sprintf("Spam level: %d\n", $ref->{spamlevel
}) if $ref->{qtype
} eq 'S';
98 $title .= sprintf("Virus info: %s\n", encode_entities
($ref->{info
})) if $ref->{qtype
} eq 'V';
99 $title .= sprintf("File: %s", encode_entities
($ref->{file
}));
101 $item->{title
} = $title;
103 my $basehref = "https://$data->{fqdn}:$data->{port}/userquar";
105 $item->{wlhref
} = "$basehref?ticket=$data->{ticket}&cselect=$item->{id}&whitelist=1";
106 $item->{blhref
} = "$basehref?ticket=$data->{ticket}&cselect=$item->{id}&blacklist=1";
107 $item->{deliverhref
} = "$basehref?ticket=$data->{ticket}&cselect=$item->{id}&deliver=1";
108 $item->{deletehref
} = "$basehref?ticket=$data->{ticket}&cselect=$item->{id}&delete=1";
113 sub finalize_report
{
114 my ($tt, $template, $data, $mailfrom, $receiver, $debug) = @_;
118 $tt->process($template, $data, \
$html) ||
119 die $tt->error() . "\n";
122 if ($html =~ m
|^\s
*<title
>(.*)</title
>|m
) {
125 die "unable to extract template title\n";
128 my $top = MIME
::Entity-
>build(
129 Type
=> "multipart/related",
130 To
=> $data->{pmail
},
132 Subject
=> PMG
::Utils
::bencode_header
(decode_entities
($title)));
137 Encoding
=> $debug ?
'binary' : 'quoted-printable');
143 # we use an empty envelope sender (we dont want to receive NDRs)
144 PMG
::Utils
::reinject_mail
($top, '', [$receiver], undef, $data->{fqdn
});
147 __PACKAGE__-
>register_method ({
151 description
=> "Generate and send spam report emails.",
153 additionalProperties
=> 0,
156 description
=> "Generate report for a single email address. If not specified, generate reports for all users.",
157 type
=> 'string', format
=> 'email',
161 description
=> "Select time span.",
163 enum
=> ['today', 'yesterday', 'week'],
168 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.",
170 enum
=> ['none', 'short', 'verbose', 'custom'],
174 description
=> "Redirect spam report email to this address.",
175 type
=> 'string', format
=> 'email',
179 description
=> "Debug mode. Print raw email to stdout instead of sending them.",
186 returns
=> { type
=> 'null'},
190 my $cinfo = PMG
::ClusterConfig-
>new();
191 my $role = $cinfo->{local}->{type
} // '-';
193 if (!(($role eq '-') || ($role eq 'master'))) {
194 die "local node is not master - not sending spam report\n";
197 my $cfg = PMG
::Config-
>new();
199 my $reportstyle = $param->{style
} // $cfg->get('spamquar', 'reportstyle');
201 my $timespan = $param->{timespan
} // 'today';
203 my (undef, undef, undef, $mday, $mon, $year) = localtime(time());
204 my $daystart = timelocal
(0, 0, 0, $mday, $mon, $year);
209 if ($timespan eq 'today') {
211 $end = $start + 86400;
212 } elsif ($timespan eq 'yesterday') {
214 $start = $end - 86400;
215 } elsif ($timespan eq 'week') {
217 $start = $end - 7*86400;
219 die "internal error";
222 my $hostname = PVE
::INotify
::nodename
();
224 my $fqdn = $cfg->get('spamquar', 'hostname') //
225 PVE
::Tools
::get_fqdn
($hostname);
233 hostname
=> $hostname,
234 date
=> strftime
("%F", localtime($end - 1)),
235 timespan
=> $timespan,
239 my $mailfrom = $cfg->get ('spamquar', 'mailfrom') //
240 "Proxmox Mail Gateway <postmaster>";
242 my $dbh = PMG
::DBTools
::open_ruledb
();
244 my $target = $param->{receiver
};
245 my $redirect = $param->{redirect
};
247 if (defined($redirect) && !defined($target)) {
248 die "can't redirect mails for all users\n";
251 my $domains = PVE
::INotify
::read_file
('domains');
252 my $domainregex = domain_regex
([keys %$domains]);
256 if ($reportstyle ne 'none') {
258 $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";
269 my $sth = $dbh->prepare(
270 "SELECT * FROM CMailStore, CMSReceivers " .
271 "WHERE time >= $start AND time < $end AND " .
272 ($target ?
"pmail = ? AND " : '') .
273 "QType = 'S' AND CID = CMailStore_CID AND RID = CMailStore_RID " .
274 "AND Status = 'N' " .
275 "ORDER BY pmail, time, receiver");
278 $sth->execute($target);
288 my $tt = PMG
::Config
::get_template_toolkit
();
292 my $extern = ($domainregex && $creceiver !~ $domainregex);
296 $data->{mailcount
} = $mailcount;
297 my $sendto = $redirect ?
$redirect : $creceiver;
298 finalize_report
($tt, $template, $data, $mailfrom, $sendto, $param->{debug
});
301 my $hint = $extern ?
" (external address)" : "";
302 printf ("%-5d %s$hint\n", $mailcount, $creceiver);
306 while (my $ref = $sth->fetchrow_hashref()) {
307 if ($creceiver ne $ref->{pmail
}) {
309 $finalize->() if $data;
311 $data = clone
($global_data);
313 $creceiver = $ref->{pmail
};
316 $data->{pmail
} = $creceiver;
317 $data->{ticket
} = PMG
::Ticket
::assemble_quarantine_ticket
($data->{pmail
});
318 $data->{managehref
} = "https://$fqdn:$port?ticket=$data->{ticket}";
322 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 does 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";
431 test_quarantine_files
($spamlifetime, $viruslifetime, $purge);
438 'purge' => [ __PACKAGE__
, 'purge', []],
439 'send' => [ __PACKAGE__
, 'send', []],