]> git.proxmox.com Git - pve-common.git/blob - src/PVE/Tools.pm
tools: add extract_sensitive_params
[pve-common.git] / src / PVE / Tools.pm
1 package PVE::Tools;
2
3 use strict;
4 use warnings;
5 use POSIX qw(EINTR EEXIST EOPNOTSUPP);
6 use IO::Socket::IP;
7 use Socket qw(AF_INET AF_INET6 AI_ALL AI_V4MAPPED AI_CANONNAME SOCK_DGRAM
8 IPPROTO_TCP);
9 use IO::Select;
10 use File::Basename;
11 use File::Path qw(make_path);
12 use Filesys::Df (); # don't overwrite our df()
13 use IO::Pipe;
14 use IO::File;
15 use IO::Dir;
16 use IO::Handle;
17 use IPC::Open3;
18 use Fcntl qw(:DEFAULT :flock);
19 use base 'Exporter';
20 use URI::Escape;
21 use Encode;
22 use Digest::SHA;
23 use JSON;
24 use Text::ParseWords;
25 use String::ShellQuote;
26 use Time::HiRes qw(usleep gettimeofday tv_interval alarm);
27 use Scalar::Util 'weaken';
28 use Date::Format qw(time2str);
29
30 use PVE::Syscall;
31
32 # avoid warning when parsing long hex values with hex()
33 no warnings 'portable'; # Support for 64-bit ints required
34
35 our @EXPORT_OK = qw(
36 $IPV6RE
37 $IPV4RE
38 lock_file
39 lock_file_full
40 run_command
41 file_set_contents
42 file_get_contents
43 file_read_firstline
44 dir_glob_regex
45 dir_glob_foreach
46 split_list
47 template_replace
48 safe_print
49 trim
50 extract_param
51 extract_sensitive_params
52 file_copy
53 get_host_arch
54 O_PATH
55 O_TMPFILE
56 AT_EMPTY_PATH
57 AT_FDCWD
58 CLONE_NEWNS
59 CLONE_NEWUTS
60 CLONE_NEWIPC
61 CLONE_NEWUSER
62 CLONE_NEWPID
63 CLONE_NEWNET
64 );
65
66 my $pvelogdir = "/var/log/pve";
67 my $pvetaskdir = "$pvelogdir/tasks";
68
69 mkdir $pvelogdir;
70 mkdir $pvetaskdir;
71
72 my $IPV4OCTET = "(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])";
73 our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)";
74 my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})";
75 my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))";
76
77 our $IPV6RE = "(?:" .
78 "(?:(?:" . "(?:$IPV6H16:){6})$IPV6LS32)|" .
79 "(?:(?:" . "::(?:$IPV6H16:){5})$IPV6LS32)|" .
80 "(?:(?:(?:" . "$IPV6H16)?::(?:$IPV6H16:){4})$IPV6LS32)|" .
81 "(?:(?:(?:(?:$IPV6H16:){0,1}$IPV6H16)?::(?:$IPV6H16:){3})$IPV6LS32)|" .
82 "(?:(?:(?:(?:$IPV6H16:){0,2}$IPV6H16)?::(?:$IPV6H16:){2})$IPV6LS32)|" .
83 "(?:(?:(?:(?:$IPV6H16:){0,3}$IPV6H16)?::(?:$IPV6H16:){1})$IPV6LS32)|" .
84 "(?:(?:(?:(?:$IPV6H16:){0,4}$IPV6H16)?::" . ")$IPV6LS32)|" .
85 "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" . ")$IPV6H16)|" .
86 "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" . ")))";
87
88 our $IPRE = "(?:$IPV4RE|$IPV6RE)";
89
90 use constant {CLONE_NEWNS => 0x00020000,
91 CLONE_NEWUTS => 0x04000000,
92 CLONE_NEWIPC => 0x08000000,
93 CLONE_NEWUSER => 0x10000000,
94 CLONE_NEWPID => 0x20000000,
95 CLONE_NEWNET => 0x40000000};
96
97 use constant {O_PATH => 0x00200000,
98 O_CLOEXEC => 0x00080000,
99 O_TMPFILE => 0x00410000}; # This includes O_DIRECTORY
100
101 use constant {AT_EMPTY_PATH => 0x1000,
102 AT_FDCWD => -100};
103
104 sub run_with_timeout {
105 my ($timeout, $code, @param) = @_;
106
107 die "got timeout\n" if $timeout <= 0;
108
109 my $prev_alarm = alarm 0; # suspend outer alarm early
110
111 my $sigcount = 0;
112
113 my $res;
114
115 eval {
116 local $SIG{ALRM} = sub { $sigcount++; die "got timeout\n"; };
117 local $SIG{PIPE} = sub { $sigcount++; die "broken pipe\n" };
118 local $SIG{__DIE__}; # see SA bug 4631
119
120 alarm($timeout);
121
122 eval { $res = &$code(@param); };
123
124 alarm(0); # avoid race conditions
125
126 die $@ if $@;
127 };
128
129 my $err = $@;
130
131 alarm $prev_alarm;
132
133 # this shouldn't happen anymore?
134 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
135
136 die $err if $err;
137
138 return $res;
139 }
140
141 # flock: we use one file handle per process, so lock file
142 # can be nested multiple times and succeeds for the same process.
143 #
144 # Since this is the only way we lock now and we don't have the old
145 # 'lock(); code(); unlock();' pattern anymore we do not actually need to
146 # count how deep we're nesting. Therefore this hash now stores a weak reference
147 # to a boolean telling us whether we already have a lock.
148
149 my $lock_handles = {};
150
151 sub lock_file_full {
152 my ($filename, $timeout, $shared, $code, @param) = @_;
153
154 $timeout = 10 if !$timeout;
155
156 my $mode = $shared ? LOCK_SH : LOCK_EX;
157
158 my $lockhash = ($lock_handles->{$$} //= {});
159
160 # Returns a locked file handle.
161 my $get_locked_file = sub {
162 my $fh = IO::File->new(">>$filename")
163 or die "can't open file - $!\n";
164
165 if (!flock($fh, $mode|LOCK_NB)) {
166 print STDERR "trying to acquire lock...\n";
167 my $success;
168 while(1) {
169 $success = flock($fh, $mode);
170 # try again on EINTR (see bug #273)
171 if ($success || ($! != EINTR)) {
172 last;
173 }
174 }
175 if (!$success) {
176 print STDERR " failed\n";
177 die "can't acquire lock '$filename' - $!\n";
178 }
179 print STDERR " OK\n";
180 }
181
182 return $fh;
183 };
184
185 my $res;
186 my $checkptr = $lockhash->{$filename};
187 my $check = 0; # This must not go out of scope before running the code.
188 my $local_fh; # This must stay local
189 if (!$checkptr || !$$checkptr) {
190 # We cannot create a weak reference in a single atomic step, so we first
191 # create a false-value, then create a reference to it, then weaken it,
192 # and after successfully locking the file we change the boolean value.
193 #
194 # The reason for this is that if an outer SIGALRM throws an exception
195 # between creating the reference and weakening it, a subsequent call to
196 # lock_file_full() will see a leftover full reference to a valid
197 # variable. This variable must be 0 in order for said call to attempt to
198 # lock the file anew.
199 #
200 # An externally triggered exception elsewhere in the code will cause the
201 # weak reference to become 'undef', and since the file handle is only
202 # stored in the local scope in $local_fh, the file will be closed by
203 # perl's cleanup routines as well.
204 #
205 # This still assumes that an IO::File handle can properly deal with such
206 # exceptions thrown during its own destruction, but that's up to perls
207 # guts now.
208 $lockhash->{$filename} = \$check;
209 weaken $lockhash->{$filename};
210 $local_fh = eval { run_with_timeout($timeout, $get_locked_file) };
211 if ($@) {
212 $@ = "can't lock file '$filename' - $@";
213 return undef;
214 }
215 $check = 1;
216 }
217 $res = eval { &$code(@param); };
218 return undef if $@;
219 return $res;
220 }
221
222
223 sub lock_file {
224 my ($filename, $timeout, $code, @param) = @_;
225
226 return lock_file_full($filename, $timeout, 0, $code, @param);
227 }
228
229 sub file_set_contents {
230 my ($filename, $data, $perm) = @_;
231
232 $perm = 0644 if !defined($perm);
233
234 my $tmpname = "$filename.tmp.$$";
235
236 eval {
237 my ($fh, $tries) = (undef, 0);
238 while (!$fh && $tries++ < 3) {
239 $fh = IO::File->new($tmpname, O_WRONLY|O_CREAT|O_EXCL, $perm);
240 if (!$fh && $! == EEXIST) {
241 unlink($tmpname) or die "unable to delete old temp file: $!\n";
242 }
243 }
244 die "unable to open file '$tmpname' - $!\n" if !$fh;
245 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
246 die "closing file '$tmpname' failed - $!\n" unless close $fh;
247 };
248 my $err = $@;
249
250 if ($err) {
251 unlink $tmpname;
252 die $err;
253 }
254
255 if (!rename($tmpname, $filename)) {
256 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
257 unlink $tmpname;
258 die $msg;
259 }
260 }
261
262 sub file_get_contents {
263 my ($filename, $max) = @_;
264
265 my $fh = IO::File->new($filename, "r") ||
266 die "can't open '$filename' - $!\n";
267
268 my $content = safe_read_from($fh, $max, 0, $filename);
269
270 close $fh;
271
272 return $content;
273 }
274
275 sub file_copy {
276 my ($filename, $dst, $max, $perm) = @_;
277
278 file_set_contents ($dst, file_get_contents($filename, $max), $perm);
279 }
280
281 sub file_read_firstline {
282 my ($filename) = @_;
283
284 my $fh = IO::File->new ($filename, "r");
285 return undef if !$fh;
286 my $res = <$fh>;
287 chomp $res if $res;
288 $fh->close;
289 return $res;
290 }
291
292 sub safe_read_from {
293 my ($fh, $max, $oneline, $filename) = @_;
294
295 # pmxcfs file size limit
296 $max = 512*1024 if !$max;
297
298 my $subject = defined($filename) ? "file '$filename'" : 'input';
299
300 my $br = 0;
301 my $input = '';
302 my $count;
303 while ($count = sysread($fh, $input, 8192, $br)) {
304 $br += $count;
305 die "$subject too long - aborting\n" if $br > $max;
306 if ($oneline && $input =~ m/^(.*)\n/) {
307 $input = $1;
308 last;
309 }
310 }
311 die "unable to read $subject - $!\n" if !defined($count);
312
313 return $input;
314 }
315
316 # The $cmd parameter can be:
317 # -) a string
318 # This is generally executed by passing it to the shell with the -c option.
319 # However, it can be executed in one of two ways, depending on whether
320 # there's a pipe involved:
321 # *) with pipe: passed explicitly to bash -c, prefixed with:
322 # set -o pipefail &&
323 # *) without a pipe: passed to perl's open3 which uses 'sh -c'
324 # (Note that this may result in two different syntax requirements!)
325 # FIXME?
326 # -) an array of arguments (strings)
327 # Will be executed without interference from a shell. (Parameters are passed
328 # as is, no escape sequences of strings will be touched.)
329 # -) an array of arrays
330 # Each array represents a command, and each command's output is piped into
331 # the following command's standard input.
332 # For this a shell command string is created with pipe symbols between each
333 # command.
334 # Each command is a list of strings meant to end up in the final command
335 # unchanged. In order to achieve this, every argument is shell-quoted.
336 # Quoting can be disabled for a particular argument by turning it into a
337 # reference, this allows inserting arbitrary shell options.
338 # For instance: the $cmd [ [ 'echo', 'hello', \'>/dev/null' ] ] will not
339 # produce any output, while the $cmd [ [ 'echo', 'hello', '>/dev/null' ] ]
340 # will literally print: hello >/dev/null
341 sub run_command {
342 my ($cmd, %param) = @_;
343
344 my $old_umask;
345 my $cmdstr;
346
347 if (my $ref = ref($cmd)) {
348 if (ref($cmd->[0])) {
349 $cmdstr = 'set -o pipefail && ';
350 my $pipe = '';
351 foreach my $command (@$cmd) {
352 # concatenate quoted parameters
353 # strings which are passed by reference are NOT shell quoted
354 $cmdstr .= $pipe . join(' ', map { ref($_) ? $$_ : shellquote($_) } @$command);
355 $pipe = ' | ';
356 }
357 $cmd = [ '/bin/bash', '-c', "$cmdstr" ];
358 } else {
359 $cmdstr = cmd2string($cmd);
360 }
361 } else {
362 $cmdstr = $cmd;
363 if ($cmd =~ m/\|/) {
364 # see 'man bash' for option pipefail
365 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
366 } else {
367 $cmd = [ $cmd ];
368 }
369 }
370
371 my $errmsg;
372 my $laststderr;
373 my $timeout;
374 my $oldtimeout;
375 my $pid;
376 my $exitcode = -1;
377
378 my $outfunc;
379 my $errfunc;
380 my $logfunc;
381 my $input;
382 my $output;
383 my $afterfork;
384 my $noerr;
385 my $keeplocale;
386 my $quiet;
387
388 eval {
389
390 foreach my $p (keys %param) {
391 if ($p eq 'timeout') {
392 $timeout = $param{$p};
393 } elsif ($p eq 'umask') {
394 $old_umask = umask($param{$p});
395 } elsif ($p eq 'errmsg') {
396 $errmsg = $param{$p};
397 } elsif ($p eq 'input') {
398 $input = $param{$p};
399 } elsif ($p eq 'output') {
400 $output = $param{$p};
401 } elsif ($p eq 'outfunc') {
402 $outfunc = $param{$p};
403 } elsif ($p eq 'errfunc') {
404 $errfunc = $param{$p};
405 } elsif ($p eq 'logfunc') {
406 $logfunc = $param{$p};
407 } elsif ($p eq 'afterfork') {
408 $afterfork = $param{$p};
409 } elsif ($p eq 'noerr') {
410 $noerr = $param{$p};
411 } elsif ($p eq 'keeplocale') {
412 $keeplocale = $param{$p};
413 } elsif ($p eq 'quiet') {
414 $quiet = $param{$p};
415 } else {
416 die "got unknown parameter '$p' for run_command\n";
417 }
418 }
419
420 if ($errmsg) {
421 my $origerrfunc = $errfunc;
422 $errfunc = sub {
423 if ($laststderr) {
424 if ($origerrfunc) {
425 &$origerrfunc("$laststderr\n");
426 } else {
427 print STDERR "$laststderr\n" if $laststderr;
428 }
429 }
430 $laststderr = shift;
431 };
432 }
433
434 my $reader = $output && $output =~ m/^>&/ ? $output : IO::File->new();
435 my $writer = $input && $input =~ m/^<&/ ? $input : IO::File->new();
436 my $error = IO::File->new();
437
438 my $orig_pid = $$;
439
440 eval {
441 local $ENV{LC_ALL} = 'C' if !$keeplocale;
442
443 # suppress LVM warnings like: "File descriptor 3 left open";
444 local $ENV{LVM_SUPPRESS_FD_WARNINGS} = "1";
445
446 $pid = open3($writer, $reader, $error, @$cmd) || die $!;
447
448 # if we pipe fron STDIN, open3 closes STDIN, so we we
449 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
450 # as soon as we open a new file.
451 # to avoid that we open /dev/null
452 if (!ref($writer) && !defined(fileno(STDIN))) {
453 POSIX::close(0);
454 open(STDIN, "</dev/null");
455 }
456 };
457
458 my $err = $@;
459
460 # catch exec errors
461 if ($orig_pid != $$) {
462 warn "ERROR: $err";
463 POSIX::_exit (1);
464 kill ('KILL', $$);
465 }
466
467 die $err if $err;
468
469 local $SIG{ALRM} = sub { die "got timeout\n"; } if $timeout;
470 $oldtimeout = alarm($timeout) if $timeout;
471
472 &$afterfork() if $afterfork;
473
474 if (ref($writer)) {
475 print $writer $input if defined $input;
476 close $writer;
477 }
478
479 my $select = new IO::Select;
480 $select->add($reader) if ref($reader);
481 $select->add($error);
482
483 my $outlog = '';
484 my $errlog = '';
485
486 my $starttime = time();
487
488 while ($select->count) {
489 my @handles = $select->can_read(1);
490
491 foreach my $h (@handles) {
492 my $buf = '';
493 my $count = sysread ($h, $buf, 4096);
494 if (!defined ($count)) {
495 my $err = $!;
496 kill (9, $pid);
497 waitpid ($pid, 0);
498 die $err;
499 }
500 $select->remove ($h) if !$count;
501 if ($h eq $reader) {
502 if ($outfunc || $logfunc) {
503 eval {
504 while ($buf =~ s/^([^\010\r\n]*)(?:\n|(?:\010)+|\r\n?)//) {
505 my $line = $outlog . $1;
506 $outlog = '';
507 &$outfunc($line) if $outfunc;
508 &$logfunc($line) if $logfunc;
509 }
510 $outlog .= $buf;
511 };
512 my $err = $@;
513 if ($err) {
514 kill (9, $pid);
515 waitpid ($pid, 0);
516 die $err;
517 }
518 } elsif (!$quiet) {
519 print $buf;
520 *STDOUT->flush();
521 }
522 } elsif ($h eq $error) {
523 if ($errfunc || $logfunc) {
524 eval {
525 while ($buf =~ s/^([^\010\r\n]*)(?:\n|(?:\010)+|\r\n?)//) {
526 my $line = $errlog . $1;
527 $errlog = '';
528 &$errfunc($line) if $errfunc;
529 &$logfunc($line) if $logfunc;
530 }
531 $errlog .= $buf;
532 };
533 my $err = $@;
534 if ($err) {
535 kill (9, $pid);
536 waitpid ($pid, 0);
537 die $err;
538 }
539 } elsif (!$quiet) {
540 print STDERR $buf;
541 *STDERR->flush();
542 }
543 }
544 }
545 }
546
547 &$outfunc($outlog) if $outfunc && $outlog;
548 &$logfunc($outlog) if $logfunc && $outlog;
549
550 &$errfunc($errlog) if $errfunc && $errlog;
551 &$logfunc($errlog) if $logfunc && $errlog;
552
553 waitpid ($pid, 0);
554
555 if ($? == -1) {
556 die "failed to execute\n";
557 } elsif (my $sig = ($? & 127)) {
558 die "got signal $sig\n";
559 } elsif ($exitcode = ($? >> 8)) {
560 if (!($exitcode == 24 && ($cmdstr =~ m|^(\S+/)?rsync\s|))) {
561 if ($errmsg && $laststderr) {
562 my $lerr = $laststderr;
563 $laststderr = undef;
564 die "$lerr\n";
565 }
566 die "exit code $exitcode\n";
567 }
568 }
569
570 alarm(0);
571 };
572
573 my $err = $@;
574
575 alarm(0);
576
577 if ($errmsg && $laststderr) {
578 &$errfunc(undef); # flush laststderr
579 }
580
581 umask ($old_umask) if defined($old_umask);
582
583 alarm($oldtimeout) if $oldtimeout;
584
585 if ($err) {
586 if ($pid && ($err eq "got timeout\n")) {
587 kill (9, $pid);
588 waitpid ($pid, 0);
589 die "command '$cmdstr' failed: $err";
590 }
591
592 if ($errmsg) {
593 $err =~ s/^usermod:\s*// if $cmdstr =~ m|^(\S+/)?usermod\s|;
594 die "$errmsg: $err";
595 } elsif(!$noerr) {
596 die "command '$cmdstr' failed: $err";
597 }
598 }
599
600 return $exitcode;
601 }
602
603 # Run a command with a tcp socket as standard input.
604 sub pipe_socket_to_command {
605 my ($cmd, $ip, $port) = @_;
606
607 my $params = {
608 Listen => 1,
609 ReuseAddr => 1,
610 Proto => &Socket::IPPROTO_TCP,
611 GetAddrInfoFlags => 0,
612 LocalAddr => $ip,
613 LocalPort => $port,
614 };
615 my $socket = IO::Socket::IP->new(%$params) or die "failed to open socket: $!\n";
616
617 print "$ip\n$port\n"; # tell remote where to connect
618 *STDOUT->flush();
619
620 alarm 0;
621 local $SIG{ALRM} = sub { die "timed out waiting for client\n" };
622 alarm 30;
623 my $client = $socket->accept; # Wait for a client
624 alarm 0;
625 close($socket);
626
627 # We want that the command talks over the TCP socket and takes
628 # ownership of it, so that when it closes it the connection is
629 # terminated, so we need to be able to close the socket. So we
630 # can't really use PVE::Tools::run_command().
631 my $pid = fork() // die "fork failed: $!\n";
632 if (!$pid) {
633 POSIX::dup2(fileno($client), 0);
634 POSIX::dup2(fileno($client), 1);
635 close($client);
636 exec {$cmd->[0]} @$cmd or do {
637 warn "exec failed: $!\n";
638 POSIX::_exit(1);
639 };
640 }
641
642 close($client);
643 if (waitpid($pid, 0) != $pid) {
644 kill(15 => $pid); # if we got interrupted terminate the child
645 my $count = 0;
646 while (waitpid($pid, POSIX::WNOHANG) != $pid) {
647 usleep(100000);
648 $count++;
649 kill(9 => $pid), last if $count > 300; # 30 second timeout
650 }
651 }
652 if (my $sig = ($? & 127)) {
653 die "got signal $sig\n";
654 } elsif (my $exitcode = ($? >> 8)) {
655 die "exit code $exitcode\n";
656 }
657
658 return undef;
659 }
660
661 sub split_list {
662 my $listtxt = shift // '';
663
664 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
665
666 $listtxt =~ s/[,;]/ /g;
667 $listtxt =~ s/^\s+//;
668
669 my @data = split (/\s+/, $listtxt);
670
671 return @data;
672 }
673
674 sub trim {
675 my $txt = shift;
676
677 return $txt if !defined($txt);
678
679 $txt =~ s/^\s+//;
680 $txt =~ s/\s+$//;
681
682 return $txt;
683 }
684
685 # simple uri templates like "/vms/{vmid}"
686 sub template_replace {
687 my ($tmpl, $data) = @_;
688
689 return $tmpl if !$tmpl;
690
691 my $res = '';
692 while ($tmpl =~ m/([^{]+)?(\{([^}]+)\})?/g) {
693 $res .= $1 if $1;
694 $res .= ($data->{$3} || '-') if $2;
695 }
696 return $res;
697 }
698
699 sub safe_print {
700 my ($filename, $fh, $data) = @_;
701
702 return if !$data;
703
704 my $res = print $fh $data;
705
706 die "write to '$filename' failed\n" if !$res;
707 }
708
709 sub debmirrors {
710
711 return {
712 'at' => 'ftp.at.debian.org',
713 'au' => 'ftp.au.debian.org',
714 'be' => 'ftp.be.debian.org',
715 'bg' => 'ftp.bg.debian.org',
716 'br' => 'ftp.br.debian.org',
717 'ca' => 'ftp.ca.debian.org',
718 'ch' => 'ftp.ch.debian.org',
719 'cl' => 'ftp.cl.debian.org',
720 'cz' => 'ftp.cz.debian.org',
721 'de' => 'ftp.de.debian.org',
722 'dk' => 'ftp.dk.debian.org',
723 'ee' => 'ftp.ee.debian.org',
724 'es' => 'ftp.es.debian.org',
725 'fi' => 'ftp.fi.debian.org',
726 'fr' => 'ftp.fr.debian.org',
727 'gr' => 'ftp.gr.debian.org',
728 'hk' => 'ftp.hk.debian.org',
729 'hr' => 'ftp.hr.debian.org',
730 'hu' => 'ftp.hu.debian.org',
731 'ie' => 'ftp.ie.debian.org',
732 'is' => 'ftp.is.debian.org',
733 'it' => 'ftp.it.debian.org',
734 'jp' => 'ftp.jp.debian.org',
735 'kr' => 'ftp.kr.debian.org',
736 'mx' => 'ftp.mx.debian.org',
737 'nl' => 'ftp.nl.debian.org',
738 'no' => 'ftp.no.debian.org',
739 'nz' => 'ftp.nz.debian.org',
740 'pl' => 'ftp.pl.debian.org',
741 'pt' => 'ftp.pt.debian.org',
742 'ro' => 'ftp.ro.debian.org',
743 'ru' => 'ftp.ru.debian.org',
744 'se' => 'ftp.se.debian.org',
745 'si' => 'ftp.si.debian.org',
746 'sk' => 'ftp.sk.debian.org',
747 'tr' => 'ftp.tr.debian.org',
748 'tw' => 'ftp.tw.debian.org',
749 'gb' => 'ftp.uk.debian.org',
750 'us' => 'ftp.us.debian.org',
751 };
752 }
753
754 my $keymaphash = {
755 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
756 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
757 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
758 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
759 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
760 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
761 #'et' => [], # Ethopia or Estonia ??
762 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
763 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
764 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
765 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
766 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
767 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
768 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
769 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
770 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
771 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
772 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
773 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
774 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
775 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
776 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
777 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
778 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
779 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
780 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
781 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
782 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # don't know?
783 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
784 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
785 #'th' => [],
786 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
787 };
788
789 my $kvmkeymaparray = [];
790 foreach my $lc (sort keys %$keymaphash) {
791 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
792 }
793
794 sub kvmkeymaps {
795 return $keymaphash;
796 }
797
798 sub kvmkeymaplist {
799 return $kvmkeymaparray;
800 }
801
802 sub extract_param {
803 my ($param, $key) = @_;
804
805 my $res = $param->{$key};
806 delete $param->{$key};
807
808 return $res;
809 }
810
811 sub extract_sensitive_params :prototype($$$) {
812 my ($param, $sensitive_list, $delete_list) = @_;
813
814 my $sensitive;
815
816 my %delete = map { $_ => 1 } ($delete_list || [])->@*;
817
818 # always extract sensitive keys, so they don't get written to the www-data readable scfg
819 for my $opt (@$sensitive_list) {
820 # First handle deletions as explicitly setting `undef`, afterwards new values may override
821 # it.
822 if (exists($delete{$opt})) {
823 $sensitive->{$opt} = undef;
824 }
825
826 if (defined(my $value = extract_param($param, $opt))) {
827 $sensitive->{$opt} = $value;
828 }
829 }
830
831 return $sensitive;
832 }
833
834 # Note: we use this to wait until vncterm/spiceterm is ready
835 sub wait_for_vnc_port {
836 my ($port, $family, $timeout) = @_;
837
838 $timeout = 5 if !$timeout;
839 my $sleeptime = 0;
840 my $starttime = [gettimeofday];
841 my $elapsed;
842
843 my $cmd = ['/bin/ss', '-Htln', "sport = :$port"];
844 push @$cmd, $family == AF_INET6 ? '-6' : '-4' if defined($family);
845
846 my $found;
847 while (($elapsed = tv_interval($starttime)) < $timeout) {
848 # -Htln = don't print header, tcp, listening sockets only, numeric ports
849 run_command($cmd, outfunc => sub {
850 my $line = shift;
851 if ($line =~ m/^LISTEN\s+\d+\s+\d+\s+\S+:(\d+)\s/) {
852 $found = 1 if ($port == $1);
853 }
854 });
855 return 1 if $found;
856 $sleeptime += 100000 if $sleeptime < 1000000;
857 usleep($sleeptime);
858 }
859
860 die "Timeout while waiting for port '$port' to get ready!\n";
861 }
862
863 sub next_unused_port {
864 my ($range_start, $range_end, $family, $address) = @_;
865
866 # We use a file to register allocated ports.
867 # Those registrations expires after $expiretime.
868 # We use this to avoid race conditions between
869 # allocation and use of ports.
870
871 my $filename = "/var/tmp/pve-reserved-ports";
872
873 my $code = sub {
874
875 my $expiretime = 5;
876 my $ctime = time();
877
878 my $ports = {};
879
880 if (my $fh = IO::File->new ($filename, "r")) {
881 while (my $line = <$fh>) {
882 if ($line =~ m/^(\d+)\s(\d+)$/) {
883 my ($port, $timestamp) = ($1, $2);
884 if (($timestamp + $expiretime) > $ctime) {
885 $ports->{$port} = $timestamp; # not expired
886 }
887 }
888 }
889 }
890
891 my $newport;
892 my %sockargs = (Listen => 5,
893 ReuseAddr => 1,
894 Family => $family,
895 Proto => IPPROTO_TCP,
896 GetAddrInfoFlags => 0);
897 $sockargs{LocalAddr} = $address if defined($address);
898
899 for (my $p = $range_start; $p < $range_end; $p++) {
900 next if $ports->{$p}; # reserved
901
902 $sockargs{LocalPort} = $p;
903 my $sock = IO::Socket::IP->new(%sockargs);
904
905 if ($sock) {
906 close($sock);
907 $newport = $p;
908 $ports->{$p} = $ctime;
909 last;
910 }
911 }
912
913 my $data = "";
914 foreach my $p (keys %$ports) {
915 $data .= "$p $ports->{$p}\n";
916 }
917
918 file_set_contents($filename, $data);
919
920 return $newport;
921 };
922
923 my $p = lock_file('/var/lock/pve-ports.lck', 10, $code);
924 die $@ if $@;
925
926 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
927
928 return $p;
929 }
930
931 sub next_migrate_port {
932 my ($family, $address) = @_;
933 return next_unused_port(60000, 60050, $family, $address);
934 }
935
936 sub next_vnc_port {
937 my ($family, $address) = @_;
938 return next_unused_port(5900, 6000, $family, $address);
939 }
940
941 sub spice_port_range {
942 return (61000, 61999);
943 }
944
945 sub next_spice_port {
946 my ($family, $address) = @_;
947 return next_unused_port(spice_port_range(), $family, $address);
948 }
949
950 sub must_stringify {
951 my ($value) = @_;
952 eval { $value = "$value" };
953 return "error turning value into a string: $@" if $@;
954 return $value;
955 }
956
957 # sigkill after $timeout a $sub running in a fork if it can't write a pipe
958 # the $sub has to return a single scalar
959 sub run_fork_with_timeout {
960 my ($timeout, $sub) = @_;
961
962 my $res;
963 my $error;
964 my $pipe_out = IO::Pipe->new();
965
966 # disable pending alarms, save their remaining time
967 my $prev_alarm = alarm 0;
968
969 # avoid leaving a zombie if the parent gets interrupted
970 my $sig_received;
971
972 my $child = fork();
973 if (!defined($child)) {
974 die "fork failed: $!\n";
975 return $res;
976 }
977
978 if (!$child) {
979 $pipe_out->writer();
980
981 eval {
982 $res = $sub->();
983 print {$pipe_out} encode_json({ result => $res });
984 $pipe_out->flush();
985 };
986 if (my $err = $@) {
987 print {$pipe_out} encode_json({ error => must_stringify($err) });
988 $pipe_out->flush();
989 POSIX::_exit(1);
990 }
991 POSIX::_exit(0);
992 }
993
994 local $SIG{INT} = sub { $sig_received++; };
995 local $SIG{TERM} = sub {
996 $error //= "interrupted by unexpected signal\n";
997 kill('TERM', $child);
998 };
999
1000 $pipe_out->reader();
1001
1002 my $readvalues = sub {
1003 local $/ = undef;
1004 my $child_res = decode_json(readline_nointr($pipe_out));
1005 $res = $child_res->{result};
1006 $error = $child_res->{error};
1007 };
1008 eval {
1009 if (defined($timeout)) {
1010 run_with_timeout($timeout, $readvalues);
1011 } else {
1012 $readvalues->();
1013 }
1014 };
1015 warn $@ if $@;
1016 $pipe_out->close();
1017 kill('KILL', $child);
1018 waitpid($child, 0);
1019
1020 alarm $prev_alarm;
1021 die "interrupted by unexpected signal\n" if $sig_received;
1022
1023 die $error if $error;
1024 return $res;
1025 }
1026
1027 sub run_fork {
1028 my ($code) = @_;
1029 return run_fork_with_timeout(undef, $code);
1030 }
1031
1032 # NOTE: NFS syscall can't be interrupted, so alarm does
1033 # not work to provide timeouts.
1034 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
1035 # So fork() before using Filesys::Df
1036 sub df {
1037 my ($path, $timeout) = @_;
1038
1039 my $df = sub { return Filesys::Df::df($path, 1) };
1040
1041 my $res = eval { run_fork_with_timeout($timeout, $df) } // {};
1042 warn $@ if $@;
1043
1044 # untaint, but be flexible: PB usage can result in scientific notation
1045 my ($blocks, $used, $bavail) = map { defined($_) ? (/^([\d\.e\-+]+)$/) : 0 }
1046 $res->@{qw(blocks used bavail)};
1047
1048 return {
1049 total => $blocks,
1050 used => $used,
1051 avail => $bavail,
1052 };
1053 }
1054
1055 sub du {
1056 my ($path, $timeout) = @_;
1057
1058 my $size;
1059
1060 $timeout //= 10;
1061
1062 my $parser = sub {
1063 my $line = shift;
1064
1065 if ($line =~ m/^(\d+)\s+total$/) {
1066 $size = $1;
1067 }
1068 };
1069
1070 run_command(['du', '-scb', $path], outfunc => $parser, timeout => $timeout);
1071
1072 return $size;
1073 }
1074
1075 # UPID helper
1076 # We use this to uniquely identify a process.
1077 # An 'Unique Process ID' has the following format:
1078 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
1079
1080 sub upid_encode {
1081 my $d = shift;
1082
1083 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
1084 # more that 8 characters for pstart
1085 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid},
1086 $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id},
1087 $d->{user});
1088 }
1089
1090 sub upid_decode {
1091 my ($upid, $noerr) = @_;
1092
1093 my $res;
1094 my $filename;
1095
1096 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
1097 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
1098 if ($upid =~ m/^UPID:([a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8,9}):([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/) {
1099 $res->{node} = $1;
1100 $res->{pid} = hex($3);
1101 $res->{pstart} = hex($4);
1102 $res->{starttime} = hex($5);
1103 $res->{type} = $6;
1104 $res->{id} = $7;
1105 $res->{user} = $8;
1106
1107 my $subdir = substr($5, 7, 8);
1108 $filename = "$pvetaskdir/$subdir/$upid";
1109
1110 } else {
1111 return undef if $noerr;
1112 die "unable to parse worker upid '$upid'\n";
1113 }
1114
1115 return wantarray ? ($res, $filename) : $res;
1116 }
1117
1118 sub upid_open {
1119 my ($upid) = @_;
1120
1121 my ($task, $filename) = upid_decode($upid);
1122
1123 my $dirname = dirname($filename);
1124 make_path($dirname);
1125
1126 my $wwwid = getpwnam('www-data') ||
1127 die "getpwnam failed";
1128
1129 my $perm = 0640;
1130
1131 my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) ||
1132 die "unable to create output file '$filename' - $!\n";
1133 chown $wwwid, -1, $outfh;
1134
1135 return $outfh;
1136 };
1137
1138 sub upid_read_status {
1139 my ($upid) = @_;
1140
1141 my ($task, $filename) = upid_decode($upid);
1142 my $fh = IO::File->new($filename, "r");
1143 return "unable to open file - $!" if !$fh;
1144 my $maxlen = 4096;
1145 sysseek($fh, -$maxlen, 2);
1146 my $readbuf = '';
1147 my $br = sysread($fh, $readbuf, $maxlen);
1148 close($fh);
1149 if ($br) {
1150 return "unable to extract last line"
1151 if $readbuf !~ m/\n?(.+)$/;
1152 my $line = $1;
1153 if ($line =~ m/^TASK OK$/) {
1154 return 'OK';
1155 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
1156 return $1;
1157 } else {
1158 return "unexpected status";
1159 }
1160 }
1161 return "unable to read tail (got $br bytes)";
1162 }
1163
1164 # useful functions to store comments in config files
1165 sub encode_text {
1166 my ($text) = @_;
1167
1168 # all control and hi-bit characters, and ':'
1169 my $unsafe = "^\x20-\x39\x3b-\x7e";
1170 return uri_escape(Encode::encode("utf8", $text), $unsafe);
1171 }
1172
1173 sub decode_text {
1174 my ($data) = @_;
1175
1176 return Encode::decode("utf8", uri_unescape($data));
1177 }
1178
1179 # depreciated - do not use!
1180 # we now decode all parameters by default
1181 sub decode_utf8_parameters {
1182 my ($param) = @_;
1183
1184 foreach my $p (qw(comment description firstname lastname)) {
1185 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
1186 }
1187
1188 return $param;
1189 }
1190
1191 sub random_ether_addr {
1192 my ($prefix) = @_;
1193
1194 my ($seconds, $microseconds) = gettimeofday;
1195
1196 my $rand = Digest::SHA::sha1($$, rand(), $seconds, $microseconds);
1197
1198 # clear multicast, set local id
1199 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
1200
1201 my $addr = sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
1202 if (defined($prefix)) {
1203 $addr = uc($prefix) . substr($addr, length($prefix));
1204 }
1205 return $addr;
1206 }
1207
1208 sub shellquote {
1209 my $str = shift;
1210
1211 return String::ShellQuote::shell_quote($str);
1212 }
1213
1214 sub cmd2string {
1215 my ($cmd) = @_;
1216
1217 die "no arguments" if !$cmd;
1218
1219 return $cmd if !ref($cmd);
1220
1221 my @qa = ();
1222 foreach my $arg (@$cmd) { push @qa, shellquote($arg); }
1223
1224 return join (' ', @qa);
1225 }
1226
1227 # split an shell argument string into an array,
1228 sub split_args {
1229 my ($str) = @_;
1230
1231 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
1232 }
1233
1234 sub dump_logfile {
1235 my ($filename, $start, $limit, $filter) = @_;
1236
1237 my $lines = [];
1238 my $count = 0;
1239
1240 my $fh = IO::File->new($filename, "r");
1241 if (!$fh) {
1242 $count++;
1243 push @$lines, { n => $count, t => "unable to open file - $!"};
1244 return ($count, $lines);
1245 }
1246
1247 $start = 0 if !$start;
1248 $limit = 50 if !$limit;
1249
1250 my $line;
1251
1252 if ($filter) {
1253 # duplicate code, so that we do not slow down normal path
1254 while (defined($line = <$fh>)) {
1255 next if $line !~ m/$filter/;
1256 next if $count++ < $start;
1257 next if $limit <= 0;
1258 chomp $line;
1259 push @$lines, { n => $count, t => $line};
1260 $limit--;
1261 }
1262 } else {
1263 while (defined($line = <$fh>)) {
1264 next if $count++ < $start;
1265 next if $limit <= 0;
1266 chomp $line;
1267 push @$lines, { n => $count, t => $line};
1268 $limit--;
1269 }
1270 }
1271
1272 close($fh);
1273
1274 # HACK: ExtJS store.guaranteeRange() does not like empty array
1275 # so we add a line
1276 if (!$count) {
1277 $count++;
1278 push @$lines, { n => $count, t => "no content"};
1279 }
1280
1281 return ($count, $lines);
1282 }
1283
1284 sub dump_journal {
1285 my ($start, $limit, $since, $until, $service) = @_;
1286
1287 my $lines = [];
1288 my $count = 0;
1289
1290 $start = 0 if !$start;
1291 $limit = 50 if !$limit;
1292
1293 my $parser = sub {
1294 my $line = shift;
1295
1296 return if $count++ < $start;
1297 return if $limit <= 0;
1298 push @$lines, { n => int($count), t => $line};
1299 $limit--;
1300 };
1301
1302 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1303
1304 push @$cmd, '--unit', $service if $service;
1305 push @$cmd, '--since', $since if $since;
1306 push @$cmd, '--until', $until if $until;
1307 run_command($cmd, outfunc => $parser);
1308
1309 # HACK: ExtJS store.guaranteeRange() does not like empty array
1310 # so we add a line
1311 if (!$count) {
1312 $count++;
1313 push @$lines, { n => $count, t => "no content"};
1314 }
1315
1316 return ($count, $lines);
1317 }
1318
1319 sub dir_glob_regex {
1320 my ($dir, $regex) = @_;
1321
1322 my $dh = IO::Dir->new ($dir);
1323 return wantarray ? () : undef if !$dh;
1324
1325 while (defined(my $tmp = $dh->read)) {
1326 if (my @res = $tmp =~ m/^($regex)$/) {
1327 $dh->close;
1328 return wantarray ? @res : $tmp;
1329 }
1330 }
1331 $dh->close;
1332
1333 return wantarray ? () : undef;
1334 }
1335
1336 sub dir_glob_foreach {
1337 my ($dir, $regex, $func) = @_;
1338
1339 my $dh = IO::Dir->new ($dir);
1340 if (defined $dh) {
1341 while (defined(my $tmp = $dh->read)) {
1342 if (my @res = $tmp =~ m/^($regex)$/) {
1343 &$func (@res);
1344 }
1345 }
1346 }
1347 }
1348
1349 sub assert_if_modified {
1350 my ($digest1, $digest2) = @_;
1351
1352 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1353 die "detected modified configuration - file changed by other user? Try again.\n";
1354 }
1355 }
1356
1357 # Digest for short strings
1358 # like FNV32a, but we only return 31 bits (positive numbers)
1359 sub fnv31a {
1360 my ($string) = @_;
1361
1362 my $hval = 0x811c9dc5;
1363
1364 foreach my $c (unpack('C*', $string)) {
1365 $hval ^= $c;
1366 $hval += (
1367 (($hval << 1) ) +
1368 (($hval << 4) ) +
1369 (($hval << 7) ) +
1370 (($hval << 8) ) +
1371 (($hval << 24) ) );
1372 $hval = $hval & 0xffffffff;
1373 }
1374 return $hval & 0x7fffffff;
1375 }
1376
1377 sub fnv31a_hex { return sprintf("%X", fnv31a(@_)); }
1378
1379 sub unpack_sockaddr_in46 {
1380 my ($sin) = @_;
1381 my $family = Socket::sockaddr_family($sin);
1382 my ($port, $host) = ($family == AF_INET6 ? Socket::unpack_sockaddr_in6($sin)
1383 : Socket::unpack_sockaddr_in($sin));
1384 return ($family, $port, $host);
1385 }
1386
1387 sub getaddrinfo_all {
1388 my ($hostname, @opts) = @_;
1389 my %hints = ( flags => AI_V4MAPPED | AI_ALL,
1390 @opts );
1391 my ($err, @res) = Socket::getaddrinfo($hostname, '0', \%hints);
1392 die "failed to get address info for: $hostname: $err\n" if $err;
1393 return @res;
1394 }
1395
1396 sub get_host_address_family {
1397 my ($hostname, $socktype) = @_;
1398 my @res = getaddrinfo_all($hostname, socktype => $socktype);
1399 return $res[0]->{family};
1400 }
1401
1402 # get the fully qualified domain name of a host
1403 # same logic as hostname(1): The FQDN is the name getaddrinfo(3) returns,
1404 # given a nodename as a parameter
1405 sub get_fqdn {
1406 my ($nodename) = @_;
1407
1408 my $hints = {
1409 flags => AI_CANONNAME,
1410 socktype => SOCK_DGRAM
1411 };
1412
1413 my ($err, @addrs) = Socket::getaddrinfo($nodename, undef, $hints);
1414
1415 die "getaddrinfo: $err" if $err;
1416
1417 return $addrs[0]->{canonname};
1418 }
1419
1420 # Parses any sane kind of host, or host+port pair:
1421 # The port is always optional and thus may be undef.
1422 sub parse_host_and_port {
1423 my ($address) = @_;
1424 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1425 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1426 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1427 {
1428 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1429 }
1430 return; # nothing
1431 }
1432
1433 sub setresuid($$$) {
1434 my ($ruid, $euid, $suid) = @_;
1435 return 0 == syscall(PVE::Syscall::setresuid, $ruid, $euid, $suid);
1436 }
1437
1438 sub unshare($) {
1439 my ($flags) = @_;
1440 return 0 == syscall(PVE::Syscall::unshare, $flags);
1441 }
1442
1443 sub setns($$) {
1444 my ($fileno, $nstype) = @_;
1445 return 0 == syscall(PVE::Syscall::setns, $fileno, $nstype);
1446 }
1447
1448 sub syncfs($) {
1449 my ($fileno) = @_;
1450 return 0 == syscall(PVE::Syscall::syncfs, $fileno);
1451 }
1452
1453 sub fsync($) {
1454 my ($fileno) = @_;
1455 return 0 == syscall(PVE::Syscall::fsync, $fileno);
1456 }
1457
1458 sub sync_mountpoint {
1459 my ($path) = @_;
1460 sysopen my $fd, $path, O_RDONLY|O_CLOEXEC or die "failed to open $path: $!\n";
1461 my $syncfs_err;
1462 if (!syncfs(fileno($fd))) {
1463 $syncfs_err = "$!";
1464 }
1465 close($fd);
1466 die "syncfs '$path' failed - $syncfs_err\n" if defined $syncfs_err;
1467 }
1468
1469 # support sending multi-part mail messages with a text and or a HTML part
1470 # mailto may be a single email string or an array of receivers
1471 sub sendmail {
1472 my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_;
1473 my $mail_re = qr/[^-a-zA-Z0-9+._@]/;
1474
1475 $mailto = [ $mailto ] if !ref($mailto);
1476
1477 for my $to (@$mailto) {
1478 die "illegal character in mailto address\n" if $to =~ $mail_re;
1479 }
1480
1481 my $rcvrtxt = join (', ', @$mailto);
1482
1483 $mailfrom = $mailfrom || "root";
1484 die "illegal character in mailfrom address\n" if $mailfrom =~ $mail_re;
1485
1486 $author = $author // 'Proxmox VE';
1487
1488 open (MAIL, "|-", "sendmail", "-B", "8BITMIME", "-f", $mailfrom, "--", @$mailto) ||
1489 die "unable to open 'sendmail' - $!";
1490
1491 my $date = time2str('%a, %d %b %Y %H:%M:%S %z', time());
1492
1493 my $is_multipart = $text && $html;
1494
1495 # multipart spec see https://www.ietf.org/rfc/rfc1521.txt
1496 my $boundary = "----_=_NextPart_001_".int(time).$$;
1497
1498 if ($subject =~ /[^[:ascii:]]/) {
1499 $subject = Encode::encode('MIME-Header', $subject);
1500 }
1501
1502 if ($subject =~ /[^[:ascii:]]/ || $is_multipart) {
1503 print MAIL "MIME-Version: 1.0\n";
1504 }
1505 print MAIL "From: $author <$mailfrom>\n";
1506 print MAIL "To: $rcvrtxt\n";
1507 print MAIL "Date: $date\n";
1508 print MAIL "Subject: $subject\n";
1509
1510 if ($is_multipart) {
1511 print MAIL "Content-Type: multipart/alternative;\n";
1512 print MAIL "\tboundary=\"$boundary\"\n";
1513 print MAIL "\n";
1514 print MAIL "This is a multi-part message in MIME format.\n\n";
1515 print MAIL "--$boundary\n";
1516 }
1517
1518 if (defined($text)) {
1519 print MAIL "Content-Type: text/plain;\n";
1520 print MAIL "\tcharset=\"UTF-8\"\n";
1521 print MAIL "Content-Transfer-Encoding: 8bit\n";
1522 print MAIL "\n";
1523
1524 # avoid 'remove extra line breaks' issue (MS Outlook)
1525 my $fill = ' ';
1526 $text =~ s/^/$fill/gm;
1527
1528 print MAIL $text;
1529
1530 print MAIL "\n--$boundary\n" if $is_multipart;
1531 }
1532
1533 if (defined($html)) {
1534 print MAIL "Content-Type: text/html;\n";
1535 print MAIL "\tcharset=\"UTF-8\"\n";
1536 print MAIL "Content-Transfer-Encoding: 8bit\n";
1537 print MAIL "\n";
1538
1539 print MAIL $html;
1540
1541 print MAIL "\n--$boundary--\n" if $is_multipart;
1542 }
1543
1544 close(MAIL);
1545 }
1546
1547 sub tempfile {
1548 my ($perm, %opts) = @_;
1549
1550 # default permissions are stricter than with file_set_contents
1551 $perm = 0600 if !defined($perm);
1552
1553 my $dir = $opts{dir} // '/run';
1554 my $mode = $opts{mode} // O_RDWR;
1555 $mode |= O_EXCL if !$opts{allow_links};
1556
1557 my $fh = IO::File->new($dir, $mode | O_TMPFILE, $perm);
1558 if (!$fh && $! == EOPNOTSUPP) {
1559 $dir = '/tmp' if !defined($opts{dir});
1560 $dir .= "/.tmpfile.$$";
1561 $fh = IO::File->new($dir, $mode | O_CREAT | O_EXCL, $perm);
1562 unlink($dir) if $fh;
1563 }
1564 die "failed to create tempfile: $!\n" if !$fh;
1565 return $fh;
1566 }
1567
1568 sub tempfile_contents {
1569 my ($data, $perm, %opts) = @_;
1570
1571 my $fh = tempfile($perm, %opts);
1572 eval {
1573 die "unable to write to tempfile: $!\n" if !print {$fh} $data;
1574 die "unable to flush to tempfile: $!\n" if !defined($fh->flush());
1575 };
1576 if (my $err = $@) {
1577 close $fh;
1578 die $err;
1579 }
1580
1581 return ("/proc/$$/fd/".$fh->fileno, $fh);
1582 }
1583
1584 sub validate_ssh_public_keys {
1585 my ($raw) = @_;
1586 my @lines = split(/\n/, $raw);
1587
1588 foreach my $line (@lines) {
1589 next if $line =~ m/^\s*$/;
1590 eval {
1591 my ($filename, $handle) = tempfile_contents($line);
1592 run_command(["ssh-keygen", "-l", "-f", $filename],
1593 outfunc => sub {}, errfunc => sub {});
1594 };
1595 die "SSH public key validation error\n" if $@;
1596 }
1597 }
1598
1599 sub openat($$$;$) {
1600 my ($dirfd, $pathname, $flags, $mode) = @_;
1601 my $fd = syscall(PVE::Syscall::openat, $dirfd, $pathname, $flags, $mode//0);
1602 return undef if $fd < 0;
1603 # sysopen() doesn't deal with numeric file descriptors apparently
1604 # so we need to convert to a mode string for IO::Handle->new_from_fd
1605 my $flagstr = ($flags & O_RDWR) ? 'rw' : ($flags & O_WRONLY) ? 'w' : 'r';
1606 my $handle = IO::Handle->new_from_fd($fd, $flagstr);
1607 return $handle if $handle;
1608 my $err = $!; # save error before closing the raw fd
1609 syscall(PVE::Syscall::close, $fd); # close
1610 $! = $err;
1611 return undef;
1612 }
1613
1614 sub mkdirat($$$) {
1615 my ($dirfd, $name, $mode) = @_;
1616 return syscall(PVE::Syscall::mkdirat, $dirfd, $name, $mode) == 0;
1617 }
1618
1619 sub fchownat($$$$$) {
1620 my ($dirfd, $pathname, $owner, $group, $flags) = @_;
1621 return syscall(PVE::Syscall::fchownat, $dirfd, $pathname, $owner, $group, $flags) == 0;
1622 }
1623
1624 my $salt_starter = time();
1625
1626 sub encrypt_pw {
1627 my ($pw) = @_;
1628
1629 $salt_starter++;
1630 my $salt = substr(Digest::SHA::sha1_base64(time() + $salt_starter + $$), 0, 8);
1631
1632 # crypt does not want '+' in salt (see 'man crypt')
1633 $salt =~ s/\+/X/g;
1634
1635 return crypt(encode("utf8", $pw), "\$5\$$salt\$");
1636 }
1637
1638 # intended usage: convert_size($val, "kb" => "gb")
1639 # we round up to the next integer by default
1640 # E.g. `convert_size(1023, "b" => "kb")` returns 1
1641 # use $no_round_up to switch this off, above example would then return 0
1642 # this is also true for converting down e.g. 0.0005 gb to mb returns 1
1643 # (0 if $no_round_up is true)
1644 # allowed formats for value:
1645 # 1234
1646 # 1234.
1647 # 1234.1234
1648 # .1234
1649 sub convert_size {
1650 my ($value, $from, $to, $no_round_up) = @_;
1651
1652 my $units = {
1653 b => 0,
1654 kb => 1,
1655 mb => 2,
1656 gb => 3,
1657 tb => 4,
1658 pb => 5,
1659 };
1660
1661 die "no value given"
1662 if !defined($value) || $value eq "";
1663
1664 $from = lc($from // ''); $to = lc($to // '');
1665 die "unknown 'from' and/or 'to' units ($from => $to)"
1666 if !defined($units->{$from}) || !defined($units->{$to});
1667
1668 die "value '$value' is not a valid, positive number"
1669 if $value !~ m/^(?:[0-9]+\.?[0-9]*|[0-9]*\.[0-9]+)$/;
1670
1671 my $shift_amount = ($units->{$from} - $units->{$to}) * 10;
1672
1673 $value *= 2**$shift_amount;
1674 $value++ if !$no_round_up && ($value - int($value)) > 0.0;
1675
1676 return int($value);
1677 }
1678
1679 # uninterruptible readline
1680 # retries on EINTR
1681 sub readline_nointr {
1682 my ($fh) = @_;
1683 my $line;
1684 while (1) {
1685 $line = <$fh>;
1686 last if defined($line) || ($! != EINTR);
1687 }
1688 return $line;
1689 }
1690
1691 my $host_arch;
1692 sub get_host_arch {
1693 $host_arch = (POSIX::uname())[4] if !$host_arch;
1694 return $host_arch;
1695 }
1696
1697 # Devices are: [ (12 bits minor) (12 bits major) (8 bits minor) ]
1698 sub dev_t_major($) {
1699 my ($dev_t) = @_;
1700 return (int($dev_t) & 0xfff00) >> 8;
1701 }
1702
1703 sub dev_t_minor($) {
1704 my ($dev_t) = @_;
1705 $dev_t = int($dev_t);
1706 return (($dev_t >> 12) & 0xfff00) | ($dev_t & 0xff);
1707 }
1708
1709 # Given an array of array refs [ \[a b c], \[a b b], \[e b a] ]
1710 # Returns the intersection of elements as a single array [a b]
1711 sub array_intersect {
1712 my ($arrays) = @_;
1713
1714 if (!ref($arrays->[0])) {
1715 $arrays = [ grep { ref($_) eq 'ARRAY' } @_ ];
1716 }
1717
1718 return [] if scalar(@$arrays) == 0;
1719 return $arrays->[0] if scalar(@$arrays) == 1;
1720
1721 my $array_unique = sub {
1722 my %seen = ();
1723 return grep { ! $seen{ $_ }++ } @_;
1724 };
1725
1726 # base idea is to get all unique members from the first array, then
1727 # check the common elements with the next (uniquely made) one, only keep
1728 # those. Repeat for every array and at the end we only have those left
1729 # which exist in all arrays
1730 my $return_arr = [ $array_unique->(@{$arrays->[0]}) ];
1731 for my $i (1 .. $#$arrays) {
1732 my %count = ();
1733 # $return_arr is already unique, explicit at before the loop, implicit below.
1734 foreach my $element (@$return_arr, $array_unique->(@{$arrays->[$i]})) {
1735 $count{$element}++;
1736 }
1737 $return_arr = [];
1738 foreach my $element (keys %count) {
1739 push @$return_arr, $element if $count{$element} > 1;
1740 }
1741 last if scalar(@$return_arr) == 0; # empty intersection, early exit
1742 }
1743
1744 return $return_arr;
1745 }
1746
1747 sub open_tree($$$) {
1748 my ($dfd, $pathname, $flags) = @_;
1749 return PVE::Syscall::file_handle_result(syscall(
1750 &PVE::Syscall::open_tree,
1751 $dfd,
1752 $pathname,
1753 $flags,
1754 ));
1755 }
1756
1757 sub move_mount($$$$$) {
1758 my ($from_dirfd, $from_pathname, $to_dirfd, $to_pathname, $flags) = @_;
1759 return 0 == syscall(
1760 &PVE::Syscall::move_mount,
1761 $from_dirfd,
1762 $from_pathname,
1763 $to_dirfd,
1764 $to_pathname,
1765 $flags,
1766 );
1767 }
1768
1769 sub fsopen($$) {
1770 my ($fsname, $flags) = @_;
1771 return PVE::Syscall::file_handle_result(syscall(&PVE::Syscall::fsopen, $fsname, $flags));
1772 }
1773
1774 sub fsmount($$$) {
1775 my ($fd, $flags, $mount_attrs) = @_;
1776 return PVE::Syscall::file_handle_result(syscall(
1777 &PVE::Syscall::fsmount,
1778 $fd,
1779 $flags,
1780 $mount_attrs,
1781 ));
1782 }
1783
1784 sub fspick($$$) {
1785 my ($dirfd, $pathname, $flags) = @_;
1786 return PVE::Syscall::file_handle_result(syscall(
1787 &PVE::Syscall::fspick,
1788 $dirfd,
1789 $pathname,
1790 $flags,
1791 ));
1792 }
1793
1794 sub fsconfig($$$$$) {
1795 my ($fd, $command, $key, $value, $aux) = @_;
1796 return 0 == syscall(&PVE::Syscall::fsconfig, $fd, $command, $key, $value, $aux);
1797 }
1798
1799 # "raw" mount, old api, not for generic use (as it does not invoke any helpers).
1800 # use for lower level stuff such as bind/remount/... or simple tmpfs mounts
1801 sub mount($$$$$) {
1802 my ($source, $target, $filesystemtype, $mountflags, $data) = @_;
1803 return 0 == syscall(
1804 &PVE::Syscall::mount,
1805 $source,
1806 $target,
1807 $filesystemtype,
1808 $mountflags,
1809 $data,
1810 );
1811 }
1812
1813 sub safe_compare {
1814 my ($left, $right, $cmp) = @_;
1815
1816 return 0 if !defined($left) && !defined($right);
1817 return -1 if !defined($left);
1818 return 1 if !defined($right);
1819 return $cmp->($left, $right);
1820 }
1821
1822 1;