]> git.proxmox.com Git - pmg-api.git/blob - src/PMG/CLI/pmgqm.pm
dkim: add QID in warnings
[pmg-api.git] / src / PMG / CLI / pmgqm.pm
1 package PMG::CLI::pmgqm;
2
3 use strict;
4 use Data::Dumper;
5 use Template;
6 use MIME::Entity;
7 use HTML::Entities;
8 use Time::Local;
9 use Clone 'clone';
10 use Mail::Header;
11 use POSIX qw(strftime);
12 use File::Find;
13 use File::stat;
14 use URI::Escape;
15
16 use PVE::SafeSyslog;
17 use PVE::Tools;
18 use PVE::INotify;
19 use PVE::CLIHandler;
20
21 use PMG::RESTEnvironment;
22 use PMG::Utils;
23 use PMG::Ticket;
24 use PMG::DBTools;
25 use PMG::RuleDB;
26 use PMG::Config;
27 use PMG::ClusterConfig;
28 use PMG::API2::Quarantine;
29
30 use base qw(PVE::CLIHandler);
31
32 sub setup_environment {
33 PMG::RESTEnvironment->setup_default_cli_env();
34 }
35
36 sub get_item_data {
37 my ($data, $ref) = @_;
38
39 my @lines = split ('\n', $ref->{header});
40 my $head = new Mail::Header(\@lines);
41
42 my $item = {};
43
44 $item->{id} = sprintf("C%dR%dT%d", $ref->{cid}, $ref->{rid}, $ref->{ticketid});
45
46 $item->{subject} = PMG::Utils::rfc1522_to_html(
47 PVE::Tools::trim($head->get('subject')) || 'No Subject');
48
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')));
52
53 if ($sender) {
54 $item->{sender} = $sender;
55 $item->{from} = sprintf ("%s on behalf of %s", $sender, $from);
56 } else {
57 $item->{from} = $from;
58 }
59
60 $item->{envelope_sender} = $ref->{sender};
61 $item->{pmail} = $ref->{pmail};
62 $item->{receiver} = $ref->{receiver} || $ref->{pmail};
63
64 $item->{date} = strftime("%F", localtime($ref->{time}));
65 $item->{time} = strftime("%H:%M:%S", localtime($ref->{time}));
66
67 $item->{bytes} = $ref->{bytes};
68 $item->{spamlevel} = $ref->{spamlevel};
69 $item->{spaminfo} = $ref->{info};
70 $item->{file} = $ref->{file};
71
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}";
75
76 return $item;
77 }
78
79 __PACKAGE__->register_method ({
80 name => 'status',
81 path => 'status',
82 method => 'POST',
83 description => "Print quarantine status (mails per user) for specified time span.",
84 parameters => {
85 additionalProperties => 0,
86 properties => {
87 timespan => {
88 description => "Select time span.",
89 type => 'string',
90 enum => ['today', 'yesterday', 'week'],
91 default => 'today',
92 optional => 1,
93 },
94 },
95 },
96 returns => { type => 'null'},
97 code => sub {
98 my ($param) = @_;
99
100 my $cinfo = PMG::ClusterConfig->new();
101 my $role = $cinfo->{local}->{type} // '-';
102
103 if (!(($role eq '-') || ($role eq 'master'))) {
104 warn "local node is not master\n";
105 return;
106 }
107
108 my $cfg = PMG::Config->new();
109
110 my $timespan = $param->{timespan} // 'today';
111
112 my ($start, $end) = PMG::Utils::lookup_timespan($timespan);
113
114 my $hostname = PVE::INotify::nodename();
115
116 my $fqdn = $cfg->get('spamquar', 'hostname') //
117 PVE::Tools::get_fqdn($hostname);
118
119
120 my $dbh = PMG::DBTools::open_ruledb();
121
122 my $domains = PVE::INotify::read_file('domains');
123 my $domainregex = PMG::Utils::domain_regex([keys %$domains]);
124
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' " .
130 "GROUP BY pmail " .
131 "ORDER BY pmail");
132
133 $sth->execute();
134
135 print "Count Spamlevel Mail\n";
136 my $res = [];
137 while (my $ref = $sth->fetchrow_hashref()) {
138 push @$res, $ref;
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});
142 }
143
144 $sth->finish();
145
146 return undef;
147 }});
148
149 __PACKAGE__->register_method ({
150 name => 'send',
151 path => 'send',
152 method => 'POST',
153 description => "Generate and send spam report emails.",
154 parameters => {
155 additionalProperties => 0,
156 properties => {
157 receiver => {
158 description => "Generate report for a single email address. If not specified, generate reports for all users.",
159 type => 'string', format => 'email',
160 optional => 1,
161 },
162 timespan => {
163 description => "Select time span.",
164 type => 'string',
165 enum => ['today', 'yesterday', 'week'],
166 default => 'today',
167 optional => 1,
168 },
169 style => {
170 description => "Spam report style. Default value is read from spam quarantine configuration.",
171 type => 'string',
172 enum => ['short', 'verbose', 'custom'],
173 optional => 1,
174 },
175 redirect => {
176 description => "Redirect spam report email to this address.",
177 type => 'string', format => 'email',
178 optional => 1,
179 },
180 debug => {
181 description => "Debug mode. Print raw email to stdout instead of sending them.",
182 type => 'boolean',
183 optional => 1,
184 default => 0,
185 }
186 },
187 },
188 returns => { type => 'null'},
189 code => sub {
190 my ($param) = @_;
191
192 my $cinfo = PMG::ClusterConfig->new();
193 my $role = $cinfo->{local}->{type} // '-';
194
195 if (!(($role eq '-') || ($role eq 'master'))) {
196 warn "local node is not master - not sending spam report\n";
197 return;
198 }
199
200 my $cfg = PMG::Config->new();
201
202 my $reportstyle = $param->{style} // $cfg->get('spamquar', 'reportstyle');
203
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});
209 }
210
211 return if $reportstyle eq 'none'; # do nothing
212
213 my $timespan = $param->{timespan} // 'today';
214
215 my ($start, $end) = PMG::Utils::lookup_timespan($timespan);
216
217 my $hostname = PVE::INotify::nodename();
218
219 my $fqdn = $cfg->get('spamquar', 'hostname') //
220 PVE::Tools::get_fqdn($hostname);
221
222 my $port = $cfg->get('spamquar', 'port') // 8006;
223
224 my $protocol = $cfg->get('spamquar', 'protocol') // 'https';
225
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";
230 }
231
232 my $global_data = {
233 protocol => $protocol,
234 port => $port,
235 fqdn => $fqdn,
236 hostname => $hostname,
237 date => strftime("%F", localtime($end - 1)),
238 timespan => $timespan,
239 items => [],
240 protocol_fqdn_port => $protocol_fqdn_port,
241 };
242
243 my $mailfrom = $cfg->get ('spamquar', 'mailfrom') //
244 "Proxmox Mail Gateway <postmaster>";
245
246 my $dbh = PMG::DBTools::open_ruledb();
247
248 my $target = $param->{receiver};
249 my $redirect = $param->{redirect};
250
251 if (defined($redirect) && !defined($target)) {
252 die "can't redirect mails for all users\n";
253 }
254
255 my $domains = PVE::INotify::read_file('domains');
256 my $domainregex = PMG::Utils::domain_regex([keys %$domains]);
257
258 my $template = "spamreport-${reportstyle}.tt";
259 my $found = 0;
260 foreach my $path (@$PMG::Config::tt_include_path) {
261 if (-f "$path/$template") { $found = 1; last; }
262 }
263 if (!$found) {
264 warn "unable to find template '$template' - using default\n";
265 $template = "spamreport-verbose.tt";
266 }
267
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");
275
276 if ($target) {
277 $sth->execute($target);
278 } else {
279 $sth->execute();
280 }
281
282 my $mailcount = 0;
283 my $creceiver = '';
284 my $data;
285
286 my $tt = PMG::Config::get_template_toolkit();
287
288 my $finalize = sub {
289
290 my $extern = ($domainregex && $creceiver !~ $domainregex);
291 if (!$extern) {
292 $data->{mailcount} = $mailcount;
293 my $sendto = $redirect ? $redirect : $creceiver;
294 PMG::Utils::finalize_report($tt, $template, $data, $mailfrom, $sendto, $param->{debug});
295 }
296 };
297
298 while (my $ref = $sth->fetchrow_hashref()) {
299 if ($creceiver ne $ref->{pmail}) {
300
301 $finalize->() if $data;
302
303 $data = clone($global_data);
304
305 $creceiver = $ref->{pmail};
306 $mailcount = 0;
307
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}";
312 }
313
314 push @{$data->{items}}, get_item_data($data, $ref);
315
316 $mailcount++;
317 }
318
319 $sth->finish();
320
321 $finalize->() if $data;
322
323 if (defined($target) && !$mailcount) {
324 print STDERR "no mails for '$target'\n";
325 }
326
327 return undef;
328 }});
329
330 sub find_stale_files {
331 my ($path, $lifetime, $purge) = @_;
332
333 return if ! -d $path;
334
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;
338
339 my $wanted = sub {
340 my $name = $File::Find::name;
341 return if $name !~ m|^($path/.*)$|;
342 $name = $1; # untaint
343 my $stat = stat($name);
344 return if ! -f _;
345 return if $stat->mtime >= $expire;
346 if ($purge) {
347 if (unlink($name)) {
348 print "removed: $name\n";
349 }
350 } else {
351 print "$name\n";
352 }
353 };
354
355 find({ wanted => $wanted, no_chdir => 1 }, $path);
356 }
357
358 sub test_quarantine_files {
359 my ($spamlifetime, $viruslifetime, $purge) = @_;
360
361 print STDERR "searching for stale files\n" if !$purge;
362
363 my $spooldir = $PMG::MailQueue::spooldir;
364
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)$|;
368 $dir = $1; # untaint
369 find_stale_files ($dir, $spamlifetime, $purge);
370 }
371
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)$|;
375 $dir = $1; # untaint
376 find_stale_files ($dir, $viruslifetime, $purge);
377 }
378 }
379
380 __PACKAGE__->register_method ({
381 name => 'purge',
382 path => 'purge',
383 method => 'POST',
384 description => "Cleanup Quarantine database. Remove entries older than configured quarantine lifetime.",
385 parameters => {
386 additionalProperties => 0,
387 properties => {
388 check => {
389 description => "Only search for quarantine files older than configured quarantine lifetime. Just print found files, but do not remove them.",
390 type => 'boolean',
391 optional => 1,
392 default => 0,
393 }
394 }
395 },
396 returns => { type => 'null'},
397 code => sub {
398 my ($param) = @_;
399
400 my $cfg = PMG::Config->new();
401
402 my $spamlifetime = $cfg->get('spamquar', 'lifetime');
403 my $viruslifetime = $cfg->get ('virusquar', 'lifetime');
404
405 my $purge = !$param->{check};
406
407 if ($purge) {
408 print STDERR "purging database\n";
409
410 my $dbh = PMG::DBTools::open_ruledb();
411
412 if (my $count = PMG::DBTools::purge_quarantine_database($dbh, 'S', $spamlifetime)) {
413 print STDERR "removed $count spam quarantine files\n";
414 }
415
416 if (my $count = PMG::DBTools::purge_quarantine_database($dbh, 'V', $viruslifetime)) {
417 print STDERR "removed $count virus quarantine files\n";
418 }
419
420 if (my $count = PMG::DBTools::purge_quarantine_database($dbh, 'A', $spamlifetime)) {
421 print STDERR "removed $count attachment quarantine files\n";
422 }
423 }
424
425 test_quarantine_files($spamlifetime, $viruslifetime, $purge);
426
427 return undef;
428 }});
429
430
431 our $cmddef = {
432 'purge' => [ __PACKAGE__, 'purge', []],
433 'send' => [ __PACKAGE__, 'send', []],
434 'status' => [ __PACKAGE__, 'status', []],
435 };
436
437 1;