]> git.proxmox.com Git - pmg-api.git/blame - src/PMG/Utils.pm
pmgqm: handle smtputf8 data
[pmg-api.git] / src / PMG / Utils.pm
CommitLineData
758c7b6b
DM
1package PMG::Utils;
2
3use strict;
4use warnings;
2808da9f 5use Cwd;
758c7b6b 6use DBI;
b8ea5d5d 7use Net::Cmd;
758c7b6b 8use Net::SMTP;
26357b0a 9use IO::File;
cad3d400 10use File::stat;
d17c5265
DM
11use POSIX qw(strftime);
12use File::stat;
ff1c5a81 13use File::Basename;
972a3b0e 14use MIME::Entity;
758c7b6b
DM
15use MIME::Words;
16use MIME::Parser;
8210c7fa 17use Time::HiRes qw (gettimeofday);
2f7031b7 18use Time::Local;
26357b0a 19use Xdgmime;
d0d91cda 20use Data::Dumper;
62ebb4bc 21use Digest::SHA;
5d5af7c5 22use Digest::MD5;
f609bf7f 23use Net::IP;
9f67f5b3 24use Socket;
dff363d9
DM
25use RRDs;
26use Filesys::Df;
8208c076 27use Encode;
00eaaf69
DM
28use utf8;
29no utf8;
30
9a56f771 31use HTML::Entities;
16ad0786 32use JSON;
758c7b6b 33
dff363d9 34use PVE::ProcFSTools;
f609bf7f 35use PVE::Network;
5953119e 36use PVE::Tools;
758c7b6b 37use PVE::SafeSyslog;
f609bf7f 38use PVE::ProcFSTools;
d0d91cda 39use PMG::AtomicFile;
8210c7fa 40use PMG::MailQueue;
c4df1b85 41use PMG::SMTPPrinter;
18598b2c 42use PMG::MIMEUtils;
758c7b6b 43
6529020a
SI
44use base 'Exporter';
45
46our @EXPORT_OK = qw(
47postgres_admin_cmd
48);
49
6c54c10a 50my $valid_pmg_realms = ['pam', 'pmg', 'quarantine'];
62ebb4bc
DM
51
52PVE::JSONSchema::register_standard_option('realm', {
53 description => "Authentication domain ID",
6c54c10a
DM
54 type => 'string',
55 enum => $valid_pmg_realms,
62ebb4bc
DM
56 maxLength => 32,
57});
58
6214b5cf
DM
59PVE::JSONSchema::register_standard_option('pmg-starttime', {
60 description => "Only consider entries newer than 'starttime' (unix epoch). Default is 'now - 1day'.",
61 type => 'integer',
62 minimum => 0,
63 optional => 1,
64});
65
66PVE::JSONSchema::register_standard_option('pmg-endtime', {
67 description => "Only consider entries older than 'endtime' (unix epoch). This is set to '<start> + 1day' by default.",
68 type => 'integer',
69 minimum => 1,
70 optional => 1,
71});
72
62ebb4bc
DM
73PVE::JSONSchema::register_format('pmg-userid', \&verify_username);
74sub verify_username {
75 my ($username, $noerr) = @_;
76
77 $username = '' if !$username;
78 my $len = length($username);
79 if ($len < 3) {
80 die "user name '$username' is too short\n" if !$noerr;
81 return undef;
82 }
83 if ($len > 64) {
84 die "user name '$username' is too long ($len > 64)\n" if !$noerr;
85 return undef;
86 }
87
88 # we only allow a limited set of characters
89 # colon is not allowed, because we store usernames in
90 # colon separated lists)!
91 # slash is not allowed because it is used as pve API delimiter
92 # also see "man useradd"
6c54c10a
DM
93 my $realm_list = join('|', @$valid_pmg_realms);
94 if ($username =~ m!^([^\s:/]+)\@(${realm_list})$!) {
62ebb4bc
DM
95 return wantarray ? ($username, $1, $2) : $username;
96 }
97
98 die "value '$username' does not look like a valid user name\n" if !$noerr;
99
100 return undef;
101}
102
103PVE::JSONSchema::register_standard_option('userid', {
104 description => "User ID",
105 type => 'string', format => 'pmg-userid',
6b0180c3 106 minLength => 4,
62ebb4bc 107 maxLength => 64,
6b0180c3 108});
62ebb4bc
DM
109
110PVE::JSONSchema::register_standard_option('username', {
111 description => "Username (without realm)",
112 type => 'string',
113 pattern => '[^\s:\/\@]{3,60}',
6b0180c3 114 minLength => 4,
62ebb4bc
DM
115 maxLength => 64,
116});
117
01929101
DM
118PVE::JSONSchema::register_standard_option('pmg-email-address', {
119 description => "Email Address (allow most characters).",
120 type => 'string',
959e331c 121 pattern => '(?:[^\s\\\@]+\@[^\s\/\\\@]+)',
01929101
DM
122 maxLength => 512,
123 minLength => 3,
124});
125
1a1bde13
DC
126PVE::JSONSchema::register_standard_option('pmg-whiteblacklist-entry-list', {
127 description => "White/Blacklist entry list (allow most characters). Can contain globs",
128 type => 'string',
129 pattern => '(?:[^\s\/\\\;\,]+)(?:\,[^\s\/\\\;\,]+)*',
130 minLength => 3,
131});
132
758c7b6b
DM
133sub lastid {
134 my ($dbh, $seq) = @_;
135
136 return $dbh->last_insert_id(
137 undef, undef, undef, undef, { sequence => $seq});
138}
139
ab466078
DM
140# quote all regex operators
141sub quote_regex {
142 my $val = shift;
143
144 $val =~ s/([\(\)\[\]\/\}\+\*\?\.\|\^\$\\])/\\$1/g;
145
146 return $val;
147}
148
cad3d400
DM
149sub file_older_than {
150 my ($filename, $lasttime) = @_;
151
152 my $st = stat($filename);
153
154 return 0 if !defined($st);
155
156 return ($lasttime >= $st->ctime);
157}
158
758c7b6b
DM
159sub extract_filename {
160 my ($head) = @_;
161
162 if (my $value = $head->recommended_filename()) {
8210c7fa 163 chomp $value;
758c7b6b
DM
164 if (my $decvalue = MIME::Words::decode_mimewords($value)) {
165 $decvalue =~ s/\0/ /g;
5953119e 166 $decvalue = PVE::Tools::trim($decvalue);
758c7b6b
DM
167 return $decvalue;
168 }
169 }
170
171 return undef;
172}
173
174sub remove_marks {
18598b2c 175 my ($entity, $add_id) = @_;
758c7b6b 176
18598b2c 177 my $id = 1;
758c7b6b 178
18598b2c
DC
179 PMG::MIMEUtils::traverse_mime_parts($entity, sub {
180 my ($part) = @_;
181 foreach my $tag (grep {/^x-proxmox-tmp/i} $part->head->tags) {
182 $part->head->delete($tag);
183 }
758c7b6b 184
18598b2c 185 $part->head->replace('X-Proxmox-tmp-AID', $id) if $add_id;
758c7b6b 186
18598b2c
DC
187 $id++;
188 });
758c7b6b
DM
189}
190
191sub subst_values {
192 my ($body, $dh) = @_;
193
194 return if !$body;
195
196 foreach my $k (keys %$dh) {
197 my $v = $dh->{$k};
bd98f5a1
DM
198 if (defined($v)) {
199 $body =~ s/__\Q${k}\E__/$v/gs;
758c7b6b
DM
200 }
201 }
202
203 return $body;
204}
205
3650871c
SI
206sub subst_values_for_header {
207 my ($header, $dh) = @_;
208
209 my $res = '';
210 foreach my $line (split('\r?\n\s*', subst_values ($header, $dh))) {
211 $res .= "\n" if $res;
212 $res .= MIME::Words::encode_mimewords(encode('UTF-8', $line), 'Charset' => 'UTF-8');
213 }
214
215 # support for multiline values (i.e. __SPAM_INFO__)
216 $res =~ s/\n/\n\t/sg; # indent content
217 $res =~ s/\n\s*\n//sg; # remove empty line
218 $res =~ s/\n?\s*$//s; # remove trailing spaces
219
220 return $res;
221}
222
758c7b6b 223sub reinject_mail {
ad1c6bce 224 my ($entity, $sender, $targets, $xforward, $me, $params) = @_;
758c7b6b
DM
225
226 my $smtp;
227 my $resid;
228 my $rescode;
229 my $resmess;
230
231 eval {
ebd31d3e 232 my $smtp = Net::SMTP->new('::FFFF:127.0.0.1', Port => 10025, Hello => $me) ||
758c7b6b
DM
233 die "unable to connect to localhost at port 10025";
234
235 if (defined($xforward)) {
236 my $xfwd;
8210c7fa 237
758c7b6b
DM
238 foreach my $attr (keys %{$xforward}) {
239 $xfwd .= " $attr=$xforward->{$attr}";
240 }
241
242 if ($xfwd && $smtp->command("XFORWARD", $xfwd)->response() != CMD_OK) {
243 syslog('err', "xforward error - got: %s %s", $smtp->code, scalar($smtp->message));
244 }
245 }
246
00eaaf69
DM
247 my $has_utf8_targets = 0;
248 foreach my $target (@$targets) {
249 if (utf8::is_utf8($target)) {
250 $has_utf8_targets = 1;
251 last;
252 }
253 }
254
255 my $mail_opts = " BODY=8BITMIME";
256 my $sender_addr;
257 if (utf8::is_utf8($sender)) {
258 $sender_addr = encode('UTF-8', $smtp->_addr($sender));
259 $mail_opts .= " SMTPUTF8";
260 } else {
261 $sender_addr = $smtp->_addr($sender);
262 $mail_opts .= " SMTPUTF8" if $has_utf8_targets;
263 }
264
ad1c6bce
SI
265 if (defined($params->{mail})) {
266 my $mailparams = $params->{mail};
267 for my $p (keys %$mailparams) {
268 $mail_opts .= " $p=$mailparams->{$p}";
269 }
270 }
271
00eaaf69 272 if (!$smtp->_MAIL("FROM:" . $sender_addr . $mail_opts)) {
758c7b6b
DM
273 syslog('err', "smtp error - got: %s %s", $smtp->code, scalar ($smtp->message));
274 die "smtp from: ERROR";
275 }
276
00eaaf69
DM
277 foreach my $target (@$targets) {
278 my $rcpt_addr;
ad1c6bce
SI
279 my $rcpt_opts = '';
280 if (defined($params->{rcpt}->{$target})) {
281 my $rcptparams = $params->{rcpt}->{$target};
282 for my $p (keys %$rcptparams) {
283 $rcpt_opts .= " $p=$rcptparams->{$p}";
284 }
285 }
286
00eaaf69
DM
287 if (utf8::is_utf8($target)) {
288 $rcpt_addr = encode('UTF-8', $smtp->_addr($target));
289 } else {
290 $rcpt_addr = $smtp->_addr($target);
291 }
292 if (!$smtp->_RCPT("TO:" . $rcpt_addr . $rcpt_opts)) {
293 syslog ('err', "smtp error - got: %s %s", $smtp->code, scalar($smtp->message));
294 die "smtp to: ERROR";
295 }
758c7b6b
DM
296 }
297
298 # Output the head:
299 #$entity->sync_headers ();
300 $smtp->data();
301
302 my $out = PMG::SMTPPrinter->new($smtp);
303 $entity->print($out);
8210c7fa
DM
304
305 # make sure we always have a newline at the end of the mail
758c7b6b
DM
306 # else dataend() fails
307 $smtp->datasend("\n");
308
309 if ($smtp->dataend()) {
310 my @msgs = $smtp->message;
8210c7fa
DM
311 $resmess = $msgs[$#msgs];
312 ($resid) = $resmess =~ m/Ok: queued as ([0-9A-Z]+)/;
758c7b6b
DM
313 $rescode = $smtp->code;
314 if (!$resid) {
315 die sprintf("unexpected SMTP result - got: %s %s : WARNING", $smtp->code, $resmess);
8210c7fa 316 }
758c7b6b
DM
317 } else {
318 my @msgs = $smtp->message;
8210c7fa 319 $resmess = $msgs[$#msgs];
758c7b6b
DM
320 $rescode = $smtp->code;
321 die sprintf("sending data failed - got: %s %s : ERROR", $smtp->code, $resmess);
322 }
323 };
324 my $err = $@;
8210c7fa 325
758c7b6b 326 $smtp->quit if $smtp;
8210c7fa 327
758c7b6b
DM
328 if ($err) {
329 syslog ('err', $err);
330 }
331
332 return wantarray ? ($resid, $rescode, $resmess) : $resid;
333}
334
89d4d155
SI
335sub analyze_custom_check {
336 my ($queue, $dname, $pmg_cfg) = @_;
337
338 my $enable_custom_check = $pmg_cfg->get('admin', 'custom_check');
339 return undef if !$enable_custom_check;
340
341 my $timeout = 60*5;
342 my $customcheck_exe = $pmg_cfg->get('admin', 'custom_check_path');
343 my $customcheck_apiver = 'v1';
344 my ($csec, $usec) = gettimeofday();
345
346 my $vinfo;
347 my $spam_score;
348
349 eval {
350
351 my $log_err = sub {
352 my ($errmsg) = @_;
353 $errmsg =~ s/%/%%/;
354 syslog('err', $errmsg);
355 };
356
357 my $customcheck_output_apiver;
358 my $have_result;
359 my $parser = sub {
360 my ($line) = @_;
361
362 my $result_flag;
363 if ($line =~ /^v\d$/) {
364 die "api version already defined!\n" if defined($customcheck_output_apiver);
365 $customcheck_output_apiver = $line;
366 die "api version mismatch - expected $customcheck_apiver, got $customcheck_output_apiver !\n"
367 if ($customcheck_output_apiver ne $customcheck_apiver);
368 } elsif ($line =~ /^SCORE: (-?[0-9]+|.[0-9]+|[0-9]+.[0-9]+)$/) {
369 $spam_score = $1;
370 $result_flag = 1;
371 } elsif ($line =~ /^VIRUS: (.+)$/) {
372 $vinfo = $1;
373 $result_flag = 1;
374 } elsif ($line =~ /^OK$/) {
375 $result_flag = 1;
376 } else {
377 die "got unexpected output!\n";
378 }
379 die "got more than 1 result outputs\n" if ( $have_result && $result_flag);
380 $have_result = $result_flag;
381 };
382
383 PVE::Tools::run_command([$customcheck_exe, $customcheck_apiver, $dname],
384 errmsg => "$queue->{logid} custom check error",
385 errfunc => $log_err, outfunc => $parser, timeout => $timeout);
386
387 die "no api version returned\n" if !defined($customcheck_output_apiver);
388 die "no result output!\n" if !$have_result;
389 };
390 my $err = $@;
391
392 if ($vinfo) {
393 syslog('info', "$queue->{logid}: virus detected: $vinfo (custom)");
394 }
395
396 my ($csec_end, $usec_end) = gettimeofday();
397 $queue->{ptime_custom} =
398 int (($csec_end-$csec)*1000 + ($usec_end - $usec)/1000);
399
400 if ($err) {
401 syslog ('err', $err);
402 $vinfo = undef;
403 $queue->{errors} = 1;
404 }
405
406 $queue->{vinfo_custom} = $vinfo;
407 $queue->{spam_custom} = $spam_score;
408
409 return ($vinfo, $spam_score);
410}
411
8210c7fa
DM
412sub analyze_virus_clam {
413 my ($queue, $dname, $pmg_cfg) = @_;
414
415 my $timeout = 60*5;
416 my $vinfo;
417
418 my $clamdscan_opts = "--stdout";
419
420 my ($csec, $usec) = gettimeofday();
421
422 my $previous_alarm;
423
424 eval {
425
426 $previous_alarm = alarm($timeout);
427
428 $SIG{ALRM} = sub {
429 die "$queue->{logid}: Maximum time ($timeout sec) exceeded. " .
430 "virus analyze (clamav) failed: ERROR";
431 };
432
433 open(CMD, "/usr/bin/clamdscan $clamdscan_opts '$dname'|") ||
434 die "$queue->{logid}: can't exec clamdscan: $! : ERROR";
435
436 my $ifiles;
8210c7fa 437
54eaf7df
DM
438 my $response = '';
439 while (defined(my $line = <CMD>)) {
440 if ($line =~ m/^$dname.*:\s+([^ :]*)\s+FOUND$/) {
8210c7fa
DM
441 # we just use the first detected virus name
442 $vinfo = $1 if !$vinfo;
54eaf7df 443 } elsif ($line =~ m/^Infected files:\s(\d*)$/i) {
8210c7fa
DM
444 $ifiles = $1;
445 }
446
54eaf7df 447 $response .= $line;
8210c7fa
DM
448 }
449
450 close(CMD);
451
452 alarm(0); # avoid race conditions
453
454 if (!defined($ifiles)) {
455 die "$queue->{logid}: got undefined output from " .
54eaf7df 456 "virus detector: $response : ERROR";
8210c7fa
DM
457 }
458
459 if ($vinfo) {
54eaf7df 460 syslog('info', "$queue->{logid}: virus detected: $vinfo (clamav)");
8210c7fa
DM
461 }
462 };
463 my $err = $@;
464
465 alarm($previous_alarm);
466
467 my ($csec_end, $usec_end) = gettimeofday();
468 $queue->{ptime_clam} =
469 int (($csec_end-$csec)*1000 + ($usec_end - $usec)/1000);
470
471 if ($err) {
472 syslog ('err', $err);
473 $vinfo = undef;
474 $queue->{errors} = 1;
475 }
476
477 $queue->{vinfo_clam} = $vinfo;
478
479 return $vinfo ? "$vinfo (clamav)" : undef;
480}
481
6ccbc37f
DM
482sub analyze_virus_avast {
483 my ($queue, $dname, $pmg_cfg) = @_;
484
485 my $timeout = 60*5;
486 my $vinfo;
487
488 my ($csec, $usec) = gettimeofday();
489
490 my $previous_alarm;
491
492 eval {
493
494 $previous_alarm = alarm($timeout);
495
496 $SIG{ALRM} = sub {
497 die "$queue->{logid}: Maximum time ($timeout sec) exceeded. " .
498 "virus analyze (avast) failed: ERROR";
499 };
500
661d569a 501 open(my $cmd, '-|', 'scan', $dname) ||
6ccbc37f
DM
502 die "$queue->{logid}: can't exec avast scan: $! : ERROR";
503
504 my $response = '';
505 while (defined(my $line = <$cmd>)) {
506 if ($line =~ m/^$dname\s+(.*\S)\s*$/) {
507 # we just use the first detected virus name
508 $vinfo = $1 if !$vinfo;
509 }
510
511 $response .= $line;
512 }
513
514 close($cmd);
515
516 alarm(0); # avoid race conditions
517
518 if ($vinfo) {
519 syslog('info', "$queue->{logid}: virus detected: $vinfo (avast)");
520 }
521 };
522 my $err = $@;
523
524 alarm($previous_alarm);
525
526 my ($csec_end, $usec_end) = gettimeofday();
527 $queue->{ptime_clam} =
528 int (($csec_end-$csec)*1000 + ($usec_end - $usec)/1000);
529
530 if ($err) {
531 syslog ('err', $err);
532 $vinfo = undef;
533 $queue->{errors} = 1;
534 }
535
536 return undef if !$vinfo;
537
538 $queue->{vinfo_avast} = $vinfo;
539
540 return "$vinfo (avast)";
541}
542
8210c7fa
DM
543sub analyze_virus {
544 my ($queue, $filename, $pmg_cfg, $testmode) = @_;
545
546 # TODO: support other virus scanners?
547
6ccbc37f
DM
548 if ($testmode) {
549 my $vinfo_clam = analyze_virus_clam($queue, $filename, $pmg_cfg);
550 my $vinfo_avast = analyze_virus_avast($queue, $filename, $pmg_cfg);
551
552 return $vinfo_avast || $vinfo_clam;
553 }
554
555 my $enable_avast = $pmg_cfg->get('admin', 'avast');
556
557 if ($enable_avast) {
558 if (my $vinfo = analyze_virus_avast($queue, $filename, $pmg_cfg)) {
559 return $vinfo;
560 }
561 }
562
9acd4d57
DM
563 my $enable_clamav = $pmg_cfg->get('admin', 'clamav');
564
565 if ($enable_clamav) {
566 if (my $vinfo = analyze_virus_clam($queue, $filename, $pmg_cfg)) {
567 return $vinfo;
568 }
569 }
570
571 return undef;
8210c7fa
DM
572}
573
26357b0a
DM
574sub magic_mime_type_for_file {
575 my ($filename) = @_;
dff363d9 576
26357b0a
DM
577 # we do not use get_mime_type_for_file, because that considers
578 # filename extensions - we only want magic type detection
579
580 my $bufsize = Xdgmime::xdg_mime_get_max_buffer_extents();
581 die "got strange value for max_buffer_extents" if $bufsize > 4096*10;
582
583 my $ct = "application/octet-stream";
584
dff363d9 585 my $fh = IO::File->new("<$filename") ||
26357b0a
DM
586 die "unable to open file '$filename' - $!";
587
588 my ($buf, $len);
589 if (($len = $fh->read($buf, $bufsize)) > 0) {
590 $ct = xdg_mime_get_mime_type_for_data($buf, $len);
591 }
592 $fh->close();
dff363d9 593
26357b0a 594 die "unable to read file '$filename' - $!" if ($len < 0);
dff363d9 595
26357b0a
DM
596 return $ct;
597}
758c7b6b 598
1d4193a1
DM
599sub add_ct_marks {
600 my ($entity) = @_;
601
602 if (my $path = $entity->{PMX_decoded_path}) {
603
604 # set a reasonable default if magic does not give a result
605 $entity->{PMX_magic_ct} = $entity->head->mime_attr('content-type');
606
607 if (my $ct = magic_mime_type_for_file($path)) {
608 if ($ct ne 'application/octet-stream' || !$entity->{PMX_magic_ct}) {
609 $entity->{PMX_magic_ct} = $ct;
610 }
611 }
612
613 my $filename = $entity->head->recommended_filename;
614 $filename = basename($path) if !defined($filename) || $filename eq '';
615
616 if (my $ct = xdg_mime_get_mime_type_from_file_name($filename)) {
617 $entity->{PMX_glob_ct} = $ct;
618 }
619 }
620
621 foreach my $part ($entity->parts) {
622 add_ct_marks ($part);
623 }
624}
625
f609bf7f
DM
626# x509 certificate utils
627
896ef634
DM
628# only write output if something fails
629sub run_silent_cmd {
630 my ($cmd) = @_;
631
632 my $outbuf = '';
633
634 my $record_output = sub {
635 $outbuf .= shift;
636 $outbuf .= "\n";
637 };
638
639 eval {
640 PVE::Tools::run_command($cmd, outfunc => $record_output,
641 errfunc => $record_output);
642 };
643 my $err = $@;
644
645 if ($err) {
646 print STDERR $outbuf;
647 die $err;
648 }
649}
650
3278b571 651my $proxmox_tls_cert_fn = "/etc/pmg/pmg-tls.pem";
f609bf7f
DM
652
653sub gen_proxmox_tls_cert {
bc44eb02 654 my ($force) = @_;
f609bf7f 655
bc44eb02
DM
656 my $resolv = PVE::INotify::read_file('resolvconf');
657 my $domain = $resolv->{search};
658
659 my $company = $domain; # what else ?
660 my $cn = "*.$domain";
661
662 return if !$force && -f $proxmox_tls_cert_fn;
f609bf7f
DM
663
664 my $sslconf = <<__EOD__;
665RANDFILE = /root/.rnd
666extensions = v3_req
667
668[ req ]
669default_bits = 4096
670distinguished_name = req_distinguished_name
671req_extensions = v3_req
672prompt = no
673string_mask = nombstr
674
675[ req_distinguished_name ]
676organizationalUnitName = Proxmox Mail Gateway
677organizationName = $company
678commonName = $cn
679
680[ v3_req ]
681basicConstraints = CA:FALSE
682nsCertType = server
683keyUsage = nonRepudiation, digitalSignature, keyEncipherment
684__EOD__
685
3278b571 686 my $cfgfn = "/tmp/pmgtlsconf-$$.tmp";
f609bf7f
DM
687 my $fh = IO::File->new ($cfgfn, "w");
688 print $fh $sslconf;
689 close ($fh);
690
691 eval {
896ef634
DM
692 my $cmd = ['openssl', 'req', '-batch', '-x509', '-new', '-sha256',
693 '-config', $cfgfn, '-days', 3650, '-nodes',
694 '-out', $proxmox_tls_cert_fn,
695 '-keyout', $proxmox_tls_cert_fn];
696 run_silent_cmd($cmd);
f609bf7f
DM
697 };
698
699 if (my $err = $@) {
700 unlink $proxmox_tls_cert_fn;
701 unlink $cfgfn;
702 die "unable to generate proxmox certificate request:\n$err";
703 }
704
705 unlink $cfgfn;
706}
707
708sub find_local_network_for_ip {
1e88a529 709 my ($ip, $noerr) = @_;
f609bf7f
DM
710
711 my $testip = Net::IP->new($ip);
712
713 my $isv6 = $testip->version == 6;
714 my $routes = $isv6 ?
715 PVE::ProcFSTools::read_proc_net_ipv6_route() :
716 PVE::ProcFSTools::read_proc_net_route();
717
718 foreach my $entry (@$routes) {
719 my $mask;
720 if ($isv6) {
721 $mask = $entry->{prefix};
722 next if !$mask; # skip the default route...
723 } else {
724 $mask = $PVE::Network::ipv4_mask_hash_localnet->{$entry->{mask}};
725 next if !defined($mask);
726 }
727 my $cidr = "$entry->{dest}/$mask";
728 my $testnet = Net::IP->new($cidr);
729 my $overlap = $testnet->overlaps($testip);
730 if ($overlap == $Net::IP::IP_B_IN_A_OVERLAP ||
731 $overlap == $Net::IP::IP_IDENTICAL)
732 {
733 return $cidr;
734 }
735 }
736
1e88a529
DM
737 return undef if $noerr;
738
f609bf7f
DM
739 die "unable to detect local network for ip '$ip'\n";
740}
d0d91cda 741
ef07e4d0
DM
742my $service_aliases = {
743 'postfix' => 'postfix@-',
ef07e4d0
DM
744};
745
746sub lookup_real_service_name {
747 my $alias = shift;
748
4f06ff8a
SI
749 if ($alias eq 'postgres') {
750 my $pg_ver = get_pg_server_version();
0a05c9d2 751 return "postgresql\@${pg_ver}-main";
4f06ff8a
SI
752 }
753
ef07e4d0
DM
754 return $service_aliases->{$alias} // $alias;
755}
756
230b4e03
DM
757sub get_full_service_state {
758 my ($service) = @_;
759
760 my $res;
761
762 my $parser = sub {
763 my $line = shift;
764 if ($line =~ m/^([^=\s]+)=(.*)$/) {
765 $res->{$1} = $2;
766 }
767 };
768
0a05c9d2 769 $service = lookup_real_service_name($service);
230b4e03
DM
770 PVE::Tools::run_command(['systemctl', 'show', $service], outfunc => $parser);
771
772 return $res;
773}
774
00d8b7f7
DM
775our $db_service_list = [
776 'pmgpolicy', 'pmgmirror', 'pmgtunnel', 'pmg-smtp-filter' ];
777
cfdf6608
DM
778sub service_wait_stopped {
779 my ($timeout, $service_list) = @_;
780
781 my $starttime = time();
782
783 foreach my $service (@$service_list) {
784 PVE::Tools::run_command(['systemctl', 'stop', $service]);
785 }
786
787 while (1) {
788 my $wait = 0;
789
790 foreach my $service (@$service_list) {
791 my $ss = get_full_service_state($service);
792 my $state = $ss->{ActiveState} // 'unknown';
793
794 if ($state ne 'inactive') {
795 if ((time() - $starttime) > $timeout) {
796 syslog('err', "unable to stop services (got timeout)");
797 $wait = 0;
798 last;
799 }
800 $wait = 1;
801 }
802 }
803
804 last if !$wait;
805
806 sleep(1);
807 }
808}
809
3f85510e
DM
810sub service_cmd {
811 my ($service, $cmd) = @_;
812
813 die "unknown service command '$cmd'\n"
f6884917 814 if $cmd !~ m/^(start|stop|restart|reload|reload-or-restart)$/;
3f85510e
DM
815
816 if ($service eq 'pmgdaemon' || $service eq 'pmgproxy') {
822477d5
TL
817 die "invalid service cmd '$service $cmd': refusing to stop essential service!\n"
818 if $cmd eq 'stop';
81fa07d9
DM
819 } elsif ($service eq 'fetchmail') {
820 # use restart instead of start - else it does not start 'exited' unit
821 # after setting START_DAEMON=yes in /etc/default/fetchmail
822 $cmd = 'restart' if $cmd eq 'start';
3f85510e
DM
823 }
824
0a05c9d2 825 $service = lookup_real_service_name($service);
3f85510e
DM
826 PVE::Tools::run_command(['systemctl', $cmd, $service]);
827};
828
630d1ae3
DM
829sub run_postmap {
830 my ($filename) = @_;
831
832 # make sure the file exists (else postmap fails)
833 IO::File->new($filename, 'a', 0644);
834
1dc946d4 835 my $mtime_src = (CORE::stat($filename))[9] //
364f0a6c 836 die "unable to read mtime of $filename\n";
1dc946d4
DM
837
838 my $mtime_dst = (CORE::stat("$filename.db"))[9] // 0;
78982d93
DM
839
840 # if not changed, do nothing
1dc946d4 841 return if $mtime_src <= $mtime_dst;
78982d93 842
630d1ae3
DM
843 eval {
844 PVE::Tools::run_command(
845 ['/usr/sbin/postmap', $filename],
846 errmsg => "unable to update postfix table $filename");
847 };
848 my $err = $@;
849
850 warn $err if $err;
851}
852
d17c5265
DM
853sub clamav_dbstat {
854
855 my $res = [];
856
857 my $read_cvd_info = sub {
858 my ($dbname, $dbfile) = @_;
859
860 my $header;
861 my $fh = IO::File->new("<$dbfile");
862 if (!$fh) {
1359baef 863 warn "can't open ClamAV Database $dbname ($dbfile) - $!\n";
d17c5265
DM
864 return;
865 }
866 $fh->read($header, 512);
867 $fh->close();
868
869 ## ClamAV-VDB:16 Mar 2016 23-17 +0000:57:4218790:60:06386f34a16ebeea2733ab037f0536be:
870 if ($header =~ m/^(ClamAV-VDB):([^:]+):(\d+):(\d+):/) {
871 my ($ftype, $btime, $version, $nsigs) = ($1, $2, $3, $4);
872 push @$res, {
873 name => $dbname,
874 type => $ftype,
875 build_time => $btime,
876 version => $version,
877 nsigs => $nsigs,
878 };
879 } else {
880 warn "unable to parse ClamAV Database $dbname ($dbfile)\n";
881 }
882 };
883
884 # main database
885 my $filename = "/var/lib/clamav/main.inc/main.info";
886 $filename = "/var/lib/clamav/main.cvd" if ! -f $filename;
887
888 $read_cvd_info->('main', $filename) if -f $filename;
889
890 # daily database
891 $filename = "/var/lib/clamav/daily.inc/daily.info";
892 $filename = "/var/lib/clamav/daily.cvd" if ! -f $filename;
893 $filename = "/var/lib/clamav/daily.cld" if ! -f $filename;
894
895 $read_cvd_info->('daily', $filename) if -f $filename;
896
897 $filename = "/var/lib/clamav/bytecode.cvd";
898 $read_cvd_info->('bytecode', $filename) if -f $filename;
899
dabcd20e
DM
900 my $ss_dbs_fn = "/var/lib/clamav-unofficial-sigs/configs/ss-include-dbs.txt";
901 my $ss_dbs_files = {};
902 if (my $ssfh = IO::File->new("<${ss_dbs_fn}")) {
903 while (defined(my $line = <$ssfh>)) {
904 chomp $line;
905 $ss_dbs_files->{$line} = 1;
906 }
907 }
d17c5265
DM
908 my $last = 0;
909 my $nsigs = 0;
910 foreach $filename (</var/lib/clamav/*>) {
dabcd20e
DM
911 my $fn = basename($filename);
912 next if !$ss_dbs_files->{$fn};
913
d17c5265
DM
914 my $fh = IO::File->new("<$filename");
915 next if !defined($fh);
916 my $st = stat($fh);
917 next if !$st;
918 my $mtime = $st->mtime();
919 $last = $mtime if $mtime > $last;
920 while (defined(my $line = <$fh>)) { $nsigs++; }
921 }
922
923 if ($nsigs > 0) {
924 push @$res, {
9860e592 925 name => 'sanesecurity',
d17c5265 926 type => 'unofficial',
2d011fef 927 build_time => strftime("%d %b %Y %H-%M %z", localtime($last)),
d17c5265
DM
928 nsigs => $nsigs,
929 };
930 }
931
932 return $res;
933}
934
dff363d9
DM
935# RRD related code
936my $rrd_dir = "/var/lib/rrdcached/db";
937my $rrdcached_socket = "/var/run/rrdcached.sock";
938
939my $rrd_def_node = [
940 "DS:loadavg:GAUGE:120:0:U",
941 "DS:maxcpu:GAUGE:120:0:U",
942 "DS:cpu:GAUGE:120:0:U",
943 "DS:iowait:GAUGE:120:0:U",
944 "DS:memtotal:GAUGE:120:0:U",
945 "DS:memused:GAUGE:120:0:U",
946 "DS:swaptotal:GAUGE:120:0:U",
947 "DS:swapused:GAUGE:120:0:U",
948 "DS:roottotal:GAUGE:120:0:U",
949 "DS:rootused:GAUGE:120:0:U",
950 "DS:netin:DERIVE:120:0:U",
951 "DS:netout:DERIVE:120:0:U",
952
953 "RRA:AVERAGE:0.5:1:70", # 1 min avg - one hour
954 "RRA:AVERAGE:0.5:30:70", # 30 min avg - one day
955 "RRA:AVERAGE:0.5:180:70", # 3 hour avg - one week
956 "RRA:AVERAGE:0.5:720:70", # 12 hour avg - one month
957 "RRA:AVERAGE:0.5:10080:70", # 7 day avg - ony year
958
959 "RRA:MAX:0.5:1:70", # 1 min max - one hour
960 "RRA:MAX:0.5:30:70", # 30 min max - one day
961 "RRA:MAX:0.5:180:70", # 3 hour max - one week
962 "RRA:MAX:0.5:720:70", # 12 hour max - one month
963 "RRA:MAX:0.5:10080:70", # 7 day max - ony year
964];
965
966sub cond_create_rrd_file {
967 my ($filename, $rrddef) = @_;
968
969 return if -f $filename;
970
971 my @args = ($filename);
972
973 push @args, "--daemon" => "unix:${rrdcached_socket}"
974 if -S $rrdcached_socket;
975
976 push @args, '--step', 60;
977
978 push @args, @$rrddef;
979
980 # print "TEST: " . join(' ', @args) . "\n";
981
982 RRDs::create(@args);
983 my $err = RRDs::error;
984 die "RRD error: $err\n" if $err;
985}
986
987sub update_node_status_rrd {
988
989 my $filename = "$rrd_dir/pmg-node-v1.rrd";
990 cond_create_rrd_file($filename, $rrd_def_node);
991
992 my ($avg1, $avg5, $avg15) = PVE::ProcFSTools::read_loadavg();
993
994 my $stat = PVE::ProcFSTools::read_proc_stat();
995
996 my $netdev = PVE::ProcFSTools::read_proc_net_dev();
997
998 my ($uptime) = PVE::ProcFSTools::read_proc_uptime();
999
1000 my $cpuinfo = PVE::ProcFSTools::read_cpuinfo();
1001
1002 my $maxcpu = $cpuinfo->{cpus};
1003
1004 # traffic from/to physical interface cards
1005 my $netin = 0;
1006 my $netout = 0;
1007 foreach my $dev (keys %$netdev) {
170295f8 1008 next if $dev !~ m/^$PVE::Network::PHYSICAL_NIC_RE$/;
dff363d9
DM
1009 $netin += $netdev->{$dev}->{receive};
1010 $netout += $netdev->{$dev}->{transmit};
1011 }
1012
1013 my $meminfo = PVE::ProcFSTools::read_meminfo();
1014
1015 my $dinfo = df('/', 1); # output is bytes
1016
1017 my $ctime = time();
1018
1019 # everything not free is considered to be used
1020 my $dused = $dinfo->{blocks} - $dinfo->{bfree};
1021
1022 my $data = "$ctime:$avg1:$maxcpu:$stat->{cpu}:$stat->{wait}:" .
1023 "$meminfo->{memtotal}:$meminfo->{memused}:" .
1024 "$meminfo->{swaptotal}:$meminfo->{swapused}:" .
1025 "$dinfo->{blocks}:$dused:$netin:$netout";
1026
1027
1028 my @args = ($filename);
1029
1030 push @args, "--daemon" => "unix:${rrdcached_socket}"
1031 if -S $rrdcached_socket;
1032
1033 push @args, $data;
1034
1035 # print "TEST: " . join(' ', @args) . "\n";
1036
1037 RRDs::update(@args);
1038 my $err = RRDs::error;
1039 die "RRD error: $err\n" if $err;
1040}
1041
065b2986
DM
1042sub create_rrd_data {
1043 my ($rrdname, $timeframe, $cf) = @_;
1044
1045 my $rrd = "${rrd_dir}/$rrdname";
1046
1047 my $setup = {
1048 hour => [ 60, 70 ],
1049 day => [ 60*30, 70 ],
1050 week => [ 60*180, 70 ],
1051 month => [ 60*720, 70 ],
1052 year => [ 60*10080, 70 ],
1053 };
1054
1055 my ($reso, $count) = @{$setup->{$timeframe}};
1056 my $ctime = $reso*int(time()/$reso);
1057 my $req_start = $ctime - $reso*$count;
1058
1059 $cf = "AVERAGE" if !$cf;
1060
1061 my @args = (
1062 "-s" => $req_start,
1063 "-e" => $ctime - 1,
1064 "-r" => $reso,
1065 );
1066
1067 push @args, "--daemon" => "unix:${rrdcached_socket}"
1068 if -S $rrdcached_socket;
1069
1070 my ($start, $step, $names, $data) = RRDs::fetch($rrd, $cf, @args);
1071
1072 my $err = RRDs::error;
1073 die "RRD error: $err\n" if $err;
1074
1075 die "got wrong time resolution ($step != $reso)\n"
1076 if $step != $reso;
1077
1078 my $res = [];
1079 my $fields = scalar(@$names);
1080 for my $line (@$data) {
1081 my $entry = { 'time' => $start };
1082 $start += $step;
1083 for (my $i = 0; $i < $fields; $i++) {
1084 my $name = $names->[$i];
1085 if (defined(my $val = $line->[$i])) {
1086 $entry->{$name} = $val;
1087 } else {
1088 # leave empty fields undefined
1089 # maybe make this configurable?
1090 }
1091 }
1092 push @$res, $entry;
1093 }
1094
1095 return $res;
1096}
1097
8da6f9ec
DM
1098sub decode_to_html {
1099 my ($charset, $data) = @_;
1100
1101 my $res = $data;
1102
1103 eval { $res = encode_entities(decode($charset, $data)); };
1104
1105 return $res;
1106}
1107
15fcd85c 1108# assume enc contains utf-8 and mime-encoded data returns a perl-string (with wide characters)
46f9e9af
DM
1109sub decode_rfc1522 {
1110 my ($enc) = @_;
1111
1112 my $res = '';
1113
1114 return '' if !$enc;
1115
1116 eval {
1117 foreach my $r (MIME::Words::decode_mimewords($enc)) {
1118 my ($d, $cs) = @$r;
1119 if ($d) {
1120 if ($cs) {
1121 $res .= decode($cs, $d);
1122 } else {
15fcd85c 1123 $res .= try_decode_utf8($d);
46f9e9af
DM
1124 }
1125 }
1126 }
1127 };
1128
1129 $res = $enc if $@;
1130
1131 return $res;
1132}
1133
9a56f771
DM
1134sub rfc1522_to_html {
1135 my ($enc) = @_;
1136
1137 my $res = '';
1138
1139 return '' if !$enc;
1140
1141 eval {
1142 foreach my $r (MIME::Words::decode_mimewords($enc)) {
1143 my ($d, $cs) = @$r;
1144 if ($d) {
1145 if ($cs) {
6dfa0834 1146 $res .= encode('UTF-8', decode($cs, $d));
9a56f771 1147 } else {
6dfa0834 1148 $res .= $d;
9a56f771
DM
1149 }
1150 }
1151 }
6dfa0834 1152 $res = encode_entities(decode('UTF-8', $res));
9a56f771
DM
1153 };
1154
1155 $res = $enc if $@;
1156
1157 return $res;
1158}
1159
9d26ab13
DM
1160# RFC 2047 B-ENCODING http://rfc.net/rfc2047.html
1161# (Q-Encoding is complex and error prone)
1162sub bencode_header {
1163 my $txt = shift;
1164
1165 my $CRLF = "\015\012";
1166
1167 # Nonprintables (controls + x7F + 8bit):
1168 my $NONPRINT = "\\x00-\\x1F\\x7F-\\xFF";
1169
1170 # always use utf-8 (work with japanese character sets)
1171 $txt = encode("UTF-8", $txt);
1172
1173 return $txt if $txt !~ /[$NONPRINT]/o;
1174
1175 my $res = '';
1176
1177 while ($txt =~ s/^(.{1,42})//sm) {
1178 my $t = MIME::Words::encode_mimeword ($1, 'B', 'UTF-8');
1179 $res .= $res ? "\015\012\t$t" : $t;
1180 }
1181
1182 return $res;
1183}
1184
7d89adf4 1185sub load_sa_descriptions {
e325aa6f 1186 my ($additional_dirs) = @_;
7d89adf4
DM
1187
1188 my @dirs = ('/usr/share/spamassassin',
1189 '/usr/share/spamassassin-extra');
1190
e325aa6f
DC
1191 push @dirs, @$additional_dirs if @$additional_dirs;
1192
7d89adf4
DM
1193 my $res = {};
1194
1195 my $parse_sa_file = sub {
1196 my ($file) = @_;
1197
1198 open(my $fh,'<', $file);
1199 return if !defined($fh);
1200
1201 while (defined(my $line = <$fh>)) {
24780ff0 1202 if ($line =~ m/^(?:\s*)describe\s+(\S+)\s+(.*)\s*$/) {
7d89adf4
DM
1203 my ($name, $desc) = ($1, $2);
1204 next if $res->{$name};
1205 $res->{$name}->{desc} = $desc;
1206 if ($desc =~ m|[\(\s](http:\/\/\S+\.[^\s\.\)]+\.[^\s\.\)]+)|i) {
1207 $res->{$name}->{url} = $1;
1208 }
1209 }
1210 }
1211 close($fh);
1212 };
1213
1214 foreach my $dir (@dirs) {
1215 foreach my $file (<$dir/*.cf>) {
1216 $parse_sa_file->($file);
1217 }
1218 }
1219
cda67dee 1220 $res->{'ClamAVHeuristics'}->{desc} = "ClamAV heuristic tests";
0d5209bf 1221
7d89adf4
DM
1222 return $res;
1223}
1224
8162c745
DM
1225sub format_uptime {
1226 my ($uptime) = @_;
1227
1228 my $days = int($uptime/86400);
1229 $uptime -= $days*86400;
1230
1231 my $hours = int($uptime/3600);
1232 $uptime -= $hours*3600;
1233
1234 my $mins = $uptime/60;
1235
1236 if ($days) {
1237 my $ds = $days > 1 ? 'days' : 'day';
1238 return sprintf "%d $ds %02d:%02d", $days, $hours, $mins;
1239 } else {
1240 return sprintf "%02d:%02d", $hours, $mins;
1241 }
1242}
1243
3dfe317a
DM
1244sub finalize_report {
1245 my ($tt, $template, $data, $mailfrom, $receiver, $debug) = @_;
1246
1247 my $html = '';
1248
1249 $tt->process($template, $data, \$html) ||
1250 die $tt->error() . "\n";
1251
1252 my $title;
1253 if ($html =~ m|^\s*<title>(.*)</title>|m) {
1254 $title = $1;
1255 } else {
1256 die "unable to extract template title\n";
1257 }
1258
1259 my $top = MIME::Entity->build(
1260 Type => "multipart/related",
6dfa0834 1261 To => $data->{pmail_raw},
3dfe317a
DM
1262 From => $mailfrom,
1263 Subject => bencode_header(decode_entities($title)));
1264
1265 $top->attach(
1266 Data => $html,
1267 Type => "text/html",
1268 Encoding => $debug ? 'binary' : 'quoted-printable');
1269
1270 if ($debug) {
1271 $top->print();
1272 return;
1273 }
1359baef 1274 # we use an empty envelope sender (we don't want to receive NDRs)
3dfe317a
DM
1275 PMG::Utils::reinject_mail ($top, '', [$receiver], undef, $data->{fqdn});
1276}
1277
2f7031b7
DM
1278sub lookup_timespan {
1279 my ($timespan) = @_;
1280
1281 my (undef, undef, undef, $mday, $mon, $year) = localtime(time());
1282 my $daystart = timelocal(0, 0, 0, $mday, $mon, $year);
1283
1284 my $start;
1285 my $end;
1286
1287 if ($timespan eq 'today') {
1288 $start = $daystart;
1289 $end = $start + 86400;
1290 } elsif ($timespan eq 'yesterday') {
1291 $end = $daystart;
1292 $start = $end - 86400;
1293 } elsif ($timespan eq 'week') {
1294 $end = $daystart;
1295 $start = $end - 7*86400;
1296 } else {
1297 die "internal error";
1298 }
1299
1300 return ($start, $end);
1301}
1302
17a7c6c9
DM
1303my $rbl_scan_last_cursor;
1304my $rbl_scan_start_time = time();
1305
1306sub scan_journal_for_rbl_rejects {
1307
1308 # example postscreen log entry for RBL rejects
1309 # Aug 29 08:00:36 proxmox postfix/postscreen[11266]: NOQUEUE: reject: RCPT from [x.x.x.x]:1234: 550 5.7.1 Service unavailable; client [x.x.x.x] blocked using zen.spamhaus.org; from=<xxxx>, to=<yyyy>, proto=ESMTP, helo=<zzz>
1310
2e0e3415
DM
1311 # example for PREGREET reject
1312 # Dec 7 06:57:11 proxmox postfix/postscreen[32084]: PREGREET 14 after 0.23 from [x.x.x.x]:63492: EHLO yyyyy\r\n
1313
17a7c6c9
DM
1314 my $identifier = 'postfix/postscreen';
1315
2e0e3415
DM
1316 my $rbl_count = 0;
1317 my $pregreet_count = 0;
17a7c6c9
DM
1318
1319 my $parser = sub {
16ad0786 1320 my $log = decode_json(shift);
17a7c6c9 1321
71edb4d0
FG
1322 $rbl_scan_last_cursor = $log->{__CURSOR} if defined($log->{__CURSOR});
1323
16ad0786 1324 my $message = $log->{MESSAGE};
71edb4d0
FG
1325 return if !defined($message);
1326
16ad0786 1327 if ($message =~ m/^NOQUEUE:\sreject:.*550 5.7.1 Service unavailable/) {
2e0e3415 1328 $rbl_count++;
16ad0786 1329 } elsif ($message =~ m/^PREGREET\s\d+\safter\s/) {
2e0e3415
DM
1330 $pregreet_count++;
1331 }
17a7c6c9
DM
1332 };
1333
1334 # limit to last 5000 lines to avoid long delays
16ad0786
SI
1335 my $cmd = ['journalctl', '-o', 'json', '--output-fields', '__CURSOR,MESSAGE',
1336 '--no-pager', '--identifier', $identifier, '-n', 5000];
17a7c6c9
DM
1337
1338 if (defined($rbl_scan_last_cursor)) {
1339 push @$cmd, "--after-cursor=${rbl_scan_last_cursor}";
1340 } else {
1341 push @$cmd, "--since=@" . $rbl_scan_start_time;
1342 }
1343
1344 PVE::Tools::run_command($cmd, outfunc => $parser);
1345
2e0e3415 1346 return ($rbl_count, $pregreet_count);
17a7c6c9
DM
1347}
1348
5d5af7c5
DM
1349my $hwaddress;
1350
1351sub get_hwaddress {
1352
1353 return $hwaddress if defined ($hwaddress);
1354
1355 my $fn = '/etc/ssh/ssh_host_rsa_key.pub';
1356 my $sshkey = PVE::Tools::file_get_contents($fn);
1357 $hwaddress = uc(Digest::MD5::md5_hex($sshkey));
1358
1359 return $hwaddress;
1360}
1361
75ce5866
DM
1362my $default_locale = "en_US.UTF-8 UTF-8";
1363
1364sub cond_add_default_locale {
1365
1366 my $filename = "/etc/locale.gen";
1367
1368 open(my $infh, "<", $filename) || return;
1369
1370 while (defined(my $line = <$infh>)) {
1371 if ($line =~ m/^\Q${default_locale}\E/) {
1372 # already configured
1373 return;
1374 }
1375 }
1376
1377 seek($infh, 0, 0) // return; # seek failed
1378
1379 open(my $outfh, ">", "$filename.tmp") || return;
1380
1381 my $done;
1382 while (defined(my $line = <$infh>)) {
1383 if ($line =~ m/^#\s*\Q${default_locale}\E.*/) {
1384 print $outfh "${default_locale}\n" if !$done;
1385 $done = 1;
1386 } else {
1387 print $outfh $line;
1388 }
1389 }
1390
1391 print STDERR "generation pmg default locale\n";
1392
1393 rename("$filename.tmp", $filename) || return; # rename failed
1394
1395 system("dpkg-reconfigure locales -f noninteractive");
1396}
1397
6529020a
SI
1398sub postgres_admin_cmd {
1399 my ($cmd, $options, @params) = @_;
1400
1401 $cmd = ref($cmd) ? $cmd : [ $cmd ];
1402
1403 my $save_uid = POSIX::getuid();
1404 my $pg_uid = getpwnam('postgres') || die "getpwnam postgres failed\n";
1405
98ea163e
TL
1406 # cd to / to prevent warnings on EPERM (e.g. when running in /root)
1407 my $cwd = getcwd() || die "getcwd failed - $!\n";
2808da9f 1408 ($cwd) = ($cwd =~ m|^(/.*)$|); #untaint
98ea163e 1409 chdir('/') || die "could not chdir to '/' - $!\n";
6529020a
SI
1410 PVE::Tools::setresuid(-1, $pg_uid, -1) ||
1411 die "setresuid postgres ($pg_uid) failed - $!\n";
1412
1413 PVE::Tools::run_command([@$cmd, '-U', 'postgres', @params], %$options);
1414
1415 PVE::Tools::setresuid(-1, $save_uid, -1) ||
1416 die "setresuid back failed - $!\n";
2808da9f 1417
98ea163e 1418 chdir("$cwd") || die "could not chdir back to old working dir ($cwd) - $!\n";
6529020a
SI
1419}
1420
8ba63317
SI
1421sub get_pg_server_version {
1422 my $major_ver;
1423 my $parser = sub {
1424 my $line = shift;
1425 # example output:
1426 # 9.6.13
1427 # 11.4 (Debian 11.4-1)
1428 # see https://www.postgresql.org/support/versioning/
1429 my ($first_comp) = ($line =~ m/^\s*([0-9]+)/);
1430 if ($first_comp < 10) {
1431 ($major_ver) = ($line =~ m/^([0-9]+\.[0-9]+)\.[0-9]+/);
1432 } else {
1433 $major_ver = $first_comp;
1434 }
1435
1436 };
1437 eval {
1438 postgres_admin_cmd('psql', { outfunc => $parser }, '--quiet',
1439 '--tuples-only', '--no-align', '--command', 'show server_version;');
1440 };
1441
1442 die "Unable to determine currently running Postgresql server version\n"
1443 if ($@ || !defined($major_ver));
1444
1445 return $major_ver;
1446}
1447
592f4b80
SI
1448sub reload_smtp_filter {
1449
1450 my $pid_file = '/run/pmg-smtp-filter.pid';
1451 my $pid = PVE::Tools::file_read_firstline($pid_file);
1452
1453 return 0 if !$pid;
1454
1455 return 0 if $pid !~ m/^(\d+)$/;
1456 $pid = $1; # untaint
1457
1458 return kill (10, $pid); # send SIGUSR1
1459}
1460
567516ae
DC
1461sub domain_regex {
1462 my ($domains) = @_;
1463
1464 my @ra;
1465 foreach my $d (@$domains) {
1466 # skip domains with non-DNS name characters
1467 next if $d =~ m/[^A-Za-z0-9\-\.]/;
1468 if ($d =~ m/^\.(.*)$/) {
1469 my $dom = $1;
1470 $dom =~ s/\./\\\./g;
1471 push @ra, $dom;
1472 push @ra, "\.\*\\.$dom";
1473 } else {
1474 $d =~ s/\./\\\./g;
1475 push @ra, $d;
1476 }
1477 }
1478
1479 my $re = join ('|', @ra);
1480
1481 my $regex = qr/\@($re)$/i;
1482
1483 return $regex;
1484}
1485
d362c98d
SI
1486sub read_sa_channel {
1487 my ($filename) = @_;
1488
1489 my $content = PVE::Tools::file_get_contents($filename);
1490 my $channel = {
1491 filename => $filename,
1492 };
1493
1494 ($channel->{keyid}) = ($content =~ /^KEYID=([a-fA-F0-9]+)$/m);
1495 die "no KEYID in $filename!\n" if !defined($channel->{keyid});
1496 ($channel->{channelurl}) = ($content =~ /^CHANNELURL=(.+)$/m);
1497 die "no CHANNELURL in $filename!\n" if !defined($channel->{channelurl});
1498 ($channel->{gpgkey}) = ($content =~ /(?:^|\n)(-----BEGIN PGP PUBLIC KEY BLOCK-----.+-----END PGP PUBLIC KEY BLOCK-----)(?:\n|$)/s);
1499 die "no GPG public key in $filename!\n" if !defined($channel->{gpgkey});
1500
1501 return $channel;
1502};
1503
1504sub local_spamassassin_channels {
1505
1506 my $res = [];
1507
1508 my $local_channel_dir = '/etc/mail/spamassassin/channel.d/';
1509
1510 PVE::Tools::dir_glob_foreach($local_channel_dir, '.*\.conf', sub {
1511 my ($filename) = @_;
1512 my $channel = read_sa_channel($local_channel_dir.$filename);
1513 push(@$res, $channel);
1514 });
1515
1516 return $res;
1517}
567516ae 1518
98fd3ab0
SI
1519sub update_local_spamassassin_channels {
1520 my ($verbose) = @_;
1521 # import all configured channel's gpg-keys to sa-update's keyring
1522 my $localchannels = PMG::Utils::local_spamassassin_channels();
1523 for my $channel (@$localchannels) {
1524 my $importcmd = ['sa-update', '--import', $channel->{filename}];
1525 push @$importcmd, '-v' if $verbose;
1526
1527 print "Importing gpg key from $channel->{filename}\n" if $verbose;
1528 PVE::Tools::run_command($importcmd);
1529 }
1530
1531 my $fresh_updates = 0;
1532
1533 for my $channel (@$localchannels) {
1534 my $cmd = ['sa-update', '--channel', $channel->{channelurl}, '--gpgkey', $channel->{keyid}];
1535 push @$cmd, '-v' if $verbose;
1536
1537 print "Updating $channel->{channelurl}\n" if $verbose;
1538 my $ret = PVE::Tools::run_command($cmd, noerr => 1);
1539 die "updating $channel->{channelurl} failed - sa-update exited with $ret\n" if $ret >= 2;
1540
1541 $fresh_updates = 1 if $ret == 0;
1542 }
1543
1544 return $fresh_updates
1545}
1546
736b986f
DC
1547sub get_existing_object_id {
1548 my ($dbh, $obj_id, $obj_type, $value) = @_;
1549
1550 my $sth = $dbh->prepare("SELECT id FROM Object WHERE ".
1551 "Objectgroup_ID = ? AND ".
1552 "ObjectType = ? AND ".
1553 "Value = ?"
1554 );
1555 $sth->execute($obj_id, $obj_type, $value);
1556
1557 if (my $ref = $sth->fetchrow_hashref()) {
1558 return $ref->{id};
1559 }
1560
1561 return;
1562}
1563
15fcd85c
SI
1564sub try_decode_utf8 {
1565 my ($data) = @_;
1566 return eval { decode('UTF-8', $data, 1) } // $data;
1567}
1568
758c7b6b 15691;