5 use POSIX
qw(EINTR EEXIST EOPNOTSUPP);
7 use Socket
qw(AF_INET AF_INET6 AI_ALL AI_V4MAPPED AI_CANONNAME SOCK_DGRAM
11 use File
::Path
qw(make_path);
12 use Filesys
::Df
(); # don't overwrite our df()
18 use Fcntl
qw(:DEFAULT :flock);
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);
32 # avoid warning when parsing long hex values with hex()
33 no warnings
'portable'; # Support for 64-bit ints required
51 extract_sensitive_params
66 my $pvelogdir = "/var/log/pve";
67 my $pvetaskdir = "$pvelogdir/tasks";
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))";
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)?::" . ")))";
88 our $IPRE = "(?:$IPV4RE|$IPV6RE)";
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};
97 use constant {O_PATH
=> 0x00200000,
98 O_CLOEXEC
=> 0x00080000,
99 O_TMPFILE
=> 0x00410000}; # This includes O_DIRECTORY
101 use constant {AT_EMPTY_PATH
=> 0x1000,
104 sub run_with_timeout
{
105 my ($timeout, $code, @param) = @_;
107 die "got timeout\n" if $timeout <= 0;
109 my $prev_alarm = alarm 0; # suspend outer alarm early
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
122 eval { $res = &$code(@param); };
124 alarm(0); # avoid race conditions
133 # this shouldn't happen anymore?
134 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
141 # flock: we use one file handle per process, so lock file
142 # can be nested multiple times and succeeds for the same process.
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.
149 my $lock_handles = {};
152 my ($filename, $timeout, $shared, $code, @param) = @_;
154 $timeout = 10 if !$timeout;
156 my $mode = $shared ? LOCK_SH
: LOCK_EX
;
158 my $lockhash = ($lock_handles->{$$} //= {});
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";
165 if (!flock($fh, $mode|LOCK_NB
)) {
166 print STDERR
"trying to acquire lock...\n";
169 $success = flock($fh, $mode);
170 # try again on EINTR (see bug #273)
171 if ($success || ($! != EINTR
)) {
176 print STDERR
" failed\n";
177 die "can't acquire lock '$filename' - $!\n";
179 print STDERR
" OK\n";
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.
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.
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.
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
208 $lockhash->{$filename} = \
$check;
209 weaken
$lockhash->{$filename};
210 $local_fh = eval { run_with_timeout
($timeout, $get_locked_file) };
212 $@ = "can't lock file '$filename' - $@";
217 $res = eval { &$code(@param); };
224 my ($filename, $timeout, $code, @param) = @_;
226 return lock_file_full
($filename, $timeout, 0, $code, @param);
229 sub file_set_contents
{
230 my ($filename, $data, $perm) = @_;
232 $perm = 0644 if !defined($perm);
234 my $tmpname = "$filename.tmp.$$";
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";
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;
255 if (!rename($tmpname, $filename)) {
256 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
262 sub file_get_contents
{
263 my ($filename, $max) = @_;
265 my $fh = IO
::File-
>new($filename, "r") ||
266 die "can't open '$filename' - $!\n";
268 my $content = safe_read_from
($fh, $max, 0, $filename);
276 my ($filename, $dst, $max, $perm) = @_;
278 file_set_contents
($dst, file_get_contents
($filename, $max), $perm);
281 sub file_read_firstline
{
284 my $fh = IO
::File-
>new ($filename, "r");
285 return undef if !$fh;
293 my ($fh, $max, $oneline, $filename) = @_;
295 # pmxcfs file size limit
296 $max = 512*1024 if !$max;
298 my $subject = defined($filename) ?
"file '$filename'" : 'input';
303 while ($count = sysread($fh, $input, 8192, $br)) {
305 die "$subject too long - aborting\n" if $br > $max;
306 if ($oneline && $input =~ m/^(.*)\n/) {
311 die "unable to read $subject - $!\n" if !defined($count);
316 # The $cmd parameter can be:
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:
323 # *) without a pipe: passed to perl's open3 which uses 'sh -c'
324 # (Note that this may result in two different syntax requirements!)
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
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
342 my ($cmd, %param) = @_;
347 if (my $ref = ref($cmd)) {
348 if (ref($cmd->[0])) {
349 $cmdstr = 'set -o pipefail && ';
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);
357 $cmd = [ '/bin/bash', '-c', "$cmdstr" ];
359 $cmdstr = cmd2string
($cmd);
364 # see 'man bash' for option pipefail
365 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
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') {
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') {
411 } elsif ($p eq 'keeplocale') {
412 $keeplocale = $param{$p};
413 } elsif ($p eq 'quiet') {
416 die "got unknown parameter '$p' for run_command\n";
421 my $origerrfunc = $errfunc;
425 &$origerrfunc("$laststderr\n");
427 print STDERR
"$laststderr\n" if $laststderr;
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();
441 local $ENV{LC_ALL
} = 'C' if !$keeplocale;
443 # suppress LVM warnings like: "File descriptor 3 left open";
444 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
446 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
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
))) {
454 open(STDIN
, "</dev/null");
461 if ($orig_pid != $$) {
469 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
470 $oldtimeout = alarm($timeout) if $timeout;
472 &$afterfork() if $afterfork;
475 print $writer $input if defined $input;
479 my $select = new IO
::Select
;
480 $select->add($reader) if ref($reader);
481 $select->add($error);
486 my $starttime = time();
488 while ($select->count) {
489 my @handles = $select->can_read(1);
491 foreach my $h (@handles) {
493 my $count = sysread ($h, $buf, 4096);
494 if (!defined ($count)) {
500 $select->remove ($h) if !$count;
502 if ($outfunc || $logfunc) {
504 while ($buf =~ s/^([^\010\r\n]*)(?:\n|(?:\010)+|\r\n?)//) {
505 my $line = $outlog . $1;
507 &$outfunc($line) if $outfunc;
508 &$logfunc($line) if $logfunc;
522 } elsif ($h eq $error) {
523 if ($errfunc || $logfunc) {
525 while ($buf =~ s/^([^\010\r\n]*)(?:\n|(?:\010)+|\r\n?)//) {
526 my $line = $errlog . $1;
528 &$errfunc($line) if $errfunc;
529 &$logfunc($line) if $logfunc;
547 &$outfunc($outlog) if $outfunc && $outlog;
548 &$logfunc($outlog) if $logfunc && $outlog;
550 &$errfunc($errlog) if $errfunc && $errlog;
551 &$logfunc($errlog) if $logfunc && $errlog;
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;
566 die "exit code $exitcode\n";
577 if ($errmsg && $laststderr) {
578 &$errfunc(undef); # flush laststderr
581 umask ($old_umask) if defined($old_umask);
583 alarm($oldtimeout) if $oldtimeout;
586 if ($pid && ($err eq "got timeout\n")) {
589 die "command '$cmdstr' failed: $err";
593 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
596 die "command '$cmdstr' failed: $err";
603 # Run a command with a tcp socket as standard input.
604 sub pipe_socket_to_command
{
605 my ($cmd, $ip, $port) = @_;
610 Proto
=> &Socket
::IPPROTO_TCP
,
611 GetAddrInfoFlags
=> 0,
615 my $socket = IO
::Socket
::IP-
>new(%$params) or die "failed to open socket: $!\n";
617 print "$ip\n$port\n"; # tell remote where to connect
621 local $SIG{ALRM
} = sub { die "timed out waiting for client\n" };
623 my $client = $socket->accept; # Wait for a client
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";
633 POSIX
::dup2
(fileno($client), 0);
634 POSIX
::dup2
(fileno($client), 1);
636 exec {$cmd->[0]} @$cmd or do {
637 warn "exec failed: $!\n";
643 if (waitpid($pid, 0) != $pid) {
644 kill(15 => $pid); # if we got interrupted terminate the child
646 while (waitpid($pid, POSIX
::WNOHANG
) != $pid) {
649 kill(9 => $pid), last if $count > 300; # 30 second timeout
652 if (my $sig = ($? & 127)) {
653 die "got signal $sig\n";
654 } elsif (my $exitcode = ($? >> 8)) {
655 die "exit code $exitcode\n";
662 my $listtxt = shift // '';
664 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
666 $listtxt =~ s/[,;]/ /g;
667 $listtxt =~ s/^\s+//;
669 my @data = split (/\s+/, $listtxt);
677 return $txt if !defined($txt);
685 # simple uri templates like "/vms/{vmid}"
686 sub template_replace
{
687 my ($tmpl, $data) = @_;
689 return $tmpl if !$tmpl;
692 while ($tmpl =~ m/([^{]+)?(\{([^}]+)\})?/g) {
694 $res .= ($data->{$3} || '-') if $2;
700 my ($filename, $fh, $data) = @_;
704 my $res = print $fh $data;
706 die "write to '$filename' failed\n" if !$res;
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',
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'],
786 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
789 my $kvmkeymaparray = [];
790 foreach my $lc (sort keys %$keymaphash) {
791 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
799 return $kvmkeymaparray;
803 my ($param, $key) = @_;
805 my $res = $param->{$key};
806 delete $param->{$key};
811 # For extracting sensitive keys (e.g. password), to avoid writing them to www-data owned configs
812 sub extract_sensitive_params
:prototype($$$) {
813 my ($param, $sensitive_list, $delete_list) = @_;
815 my %delete = map { $_ => 1 } ($delete_list || [])->@*;
818 for my $opt (@$sensitive_list) {
819 # handle deletions as explicitly setting `undef`, so subs which only have $param but not
820 # $delete_list available can recognize them. Afterwards new values may override.
821 if (exists($delete{$opt})) {
822 $sensitive->{$opt} = undef;
825 if (defined(my $value = extract_param
($param, $opt))) {
826 $sensitive->{$opt} = $value;
833 # Note: we use this to wait until vncterm/spiceterm is ready
834 sub wait_for_vnc_port
{
835 my ($port, $family, $timeout) = @_;
837 $timeout = 5 if !$timeout;
839 my $starttime = [gettimeofday
];
842 my $cmd = ['/bin/ss', '-Htln', "sport = :$port"];
843 push @$cmd, $family == AF_INET6 ?
'-6' : '-4' if defined($family);
846 while (($elapsed = tv_interval
($starttime)) < $timeout) {
847 # -Htln = don't print header, tcp, listening sockets only, numeric ports
848 run_command
($cmd, outfunc
=> sub {
850 if ($line =~ m/^LISTEN\s+\d+\s+\d+\s+\S+:(\d+)\s/) {
851 $found = 1 if ($port == $1);
855 $sleeptime += 100000 if $sleeptime < 1000000;
859 die "Timeout while waiting for port '$port' to get ready!\n";
862 sub next_unused_port
{
863 my ($range_start, $range_end, $family, $address) = @_;
865 # We use a file to register allocated ports.
866 # Those registrations expires after $expiretime.
867 # We use this to avoid race conditions between
868 # allocation and use of ports.
870 my $filename = "/var/tmp/pve-reserved-ports";
879 if (my $fh = IO
::File-
>new ($filename, "r")) {
880 while (my $line = <$fh>) {
881 if ($line =~ m/^(\d+)\s(\d+)$/) {
882 my ($port, $timestamp) = ($1, $2);
883 if (($timestamp + $expiretime) > $ctime) {
884 $ports->{$port} = $timestamp; # not expired
891 my %sockargs = (Listen
=> 5,
894 Proto
=> IPPROTO_TCP
,
895 GetAddrInfoFlags
=> 0);
896 $sockargs{LocalAddr
} = $address if defined($address);
898 for (my $p = $range_start; $p < $range_end; $p++) {
899 next if $ports->{$p}; # reserved
901 $sockargs{LocalPort
} = $p;
902 my $sock = IO
::Socket
::IP-
>new(%sockargs);
907 $ports->{$p} = $ctime;
913 foreach my $p (keys %$ports) {
914 $data .= "$p $ports->{$p}\n";
917 file_set_contents
($filename, $data);
922 my $p = lock_file
('/var/lock/pve-ports.lck', 10, $code);
925 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
930 sub next_migrate_port
{
931 my ($family, $address) = @_;
932 return next_unused_port
(60000, 60050, $family, $address);
936 my ($family, $address) = @_;
937 return next_unused_port
(5900, 6000, $family, $address);
940 sub spice_port_range
{
941 return (61000, 61999);
944 sub next_spice_port
{
945 my ($family, $address) = @_;
946 return next_unused_port
(spice_port_range
(), $family, $address);
951 eval { $value = "$value" };
952 return "error turning value into a string: $@" if $@;
956 # sigkill after $timeout a $sub running in a fork if it can't write a pipe
957 # the $sub has to return a single scalar
958 sub run_fork_with_timeout
{
959 my ($timeout, $sub) = @_;
963 my $pipe_out = IO
::Pipe-
>new();
965 # disable pending alarms, save their remaining time
966 my $prev_alarm = alarm 0;
968 # avoid leaving a zombie if the parent gets interrupted
972 if (!defined($child)) {
973 die "fork failed: $!\n";
982 print {$pipe_out} encode_json
({ result
=> $res });
986 print {$pipe_out} encode_json
({ error
=> must_stringify
($err) });
993 local $SIG{INT
} = sub { $sig_received++; };
994 local $SIG{TERM
} = sub {
995 $error //= "interrupted by unexpected signal\n";
996 kill('TERM', $child);
1001 my $readvalues = sub {
1003 my $child_res = decode_json
(readline_nointr
($pipe_out));
1004 $res = $child_res->{result
};
1005 $error = $child_res->{error
};
1008 if (defined($timeout)) {
1009 run_with_timeout
($timeout, $readvalues);
1016 kill('KILL', $child);
1020 die "interrupted by unexpected signal\n" if $sig_received;
1022 die $error if $error;
1028 return run_fork_with_timeout
(undef, $code);
1031 # NOTE: NFS syscall can't be interrupted, so alarm does
1032 # not work to provide timeouts.
1033 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
1034 # So fork() before using Filesys::Df
1036 my ($path, $timeout) = @_;
1038 my $df = sub { return Filesys
::Df
::df
($path, 1) };
1040 my $res = eval { run_fork_with_timeout
($timeout, $df) } // {};
1043 # untaint, but be flexible: PB usage can result in scientific notation
1044 my ($blocks, $used, $bavail) = map { defined($_) ?
(/^([\d\.e\-+]+)$/) : 0 }
1045 $res->@{qw(blocks used bavail)};
1055 my ($path, $timeout) = @_;
1064 if ($line =~ m/^(\d+)\s+total$/) {
1069 run_command
(['du', '-scb', $path], outfunc
=> $parser, timeout
=> $timeout);
1075 # We use this to uniquely identify a process.
1076 # An 'Unique Process ID' has the following format:
1077 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
1082 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
1083 # more that 8 characters for pstart
1084 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
1085 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
1090 my ($upid, $noerr) = @_;
1095 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
1096 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
1097 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->{pid
} = hex($3);
1100 $res->{pstart
} = hex($4);
1101 $res->{starttime
} = hex($5);
1106 my $subdir = substr($5, 7, 8);
1107 $filename = "$pvetaskdir/$subdir/$upid";
1110 return undef if $noerr;
1111 die "unable to parse worker upid '$upid'\n";
1114 return wantarray ?
($res, $filename) : $res;
1120 my ($task, $filename) = upid_decode
($upid);
1122 my $dirname = dirname
($filename);
1123 make_path
($dirname);
1125 my $wwwid = getpwnam('www-data') ||
1126 die "getpwnam failed";
1130 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
1131 die "unable to create output file '$filename' - $!\n";
1132 chown $wwwid, -1, $outfh;
1137 sub upid_read_status
{
1140 my ($task, $filename) = upid_decode
($upid);
1141 my $fh = IO
::File-
>new($filename, "r");
1142 return "unable to open file - $!" if !$fh;
1144 sysseek($fh, -$maxlen, 2);
1146 my $br = sysread($fh, $readbuf, $maxlen);
1149 return "unable to extract last line"
1150 if $readbuf !~ m/\n?(.+)$/;
1152 if ($line =~ m/^TASK OK$/) {
1154 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
1157 return "unexpected status";
1160 return "unable to read tail (got $br bytes)";
1163 # useful functions to store comments in config files
1167 # all control and hi-bit characters, and ':'
1168 my $unsafe = "^\x20-\x39\x3b-\x7e";
1169 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
1175 return Encode
::decode
("utf8", uri_unescape
($data));
1178 # depreciated - do not use!
1179 # we now decode all parameters by default
1180 sub decode_utf8_parameters
{
1183 foreach my $p (qw(comment description firstname lastname)) {
1184 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
1190 sub random_ether_addr
{
1193 my ($seconds, $microseconds) = gettimeofday
;
1195 my $rand = Digest
::SHA
::sha1
($$, rand(), $seconds, $microseconds);
1197 # clear multicast, set local id
1198 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
1200 my $addr = sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
1201 if (defined($prefix)) {
1202 $addr = uc($prefix) . substr($addr, length($prefix));
1210 return String
::ShellQuote
::shell_quote
($str);
1216 die "no arguments" if !$cmd;
1218 return $cmd if !ref($cmd);
1221 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
1223 return join (' ', @qa);
1226 # split an shell argument string into an array,
1230 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
1234 my ($filename, $start, $limit, $filter) = @_;
1239 my $fh = IO
::File-
>new($filename, "r");
1242 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
1243 return ($count, $lines);
1246 $start = 0 if !$start;
1247 $limit = 50 if !$limit;
1252 # duplicate code, so that we do not slow down normal path
1253 while (defined($line = <$fh>)) {
1254 next if $line !~ m/$filter/;
1255 next if $count++ < $start;
1256 next if $limit <= 0;
1258 push @$lines, { n
=> $count, t
=> $line};
1262 while (defined($line = <$fh>)) {
1263 next if $count++ < $start;
1264 next if $limit <= 0;
1266 push @$lines, { n
=> $count, t
=> $line};
1273 # HACK: ExtJS store.guaranteeRange() does not like empty array
1277 push @$lines, { n
=> $count, t
=> "no content"};
1280 return ($count, $lines);
1284 my ($start, $limit, $since, $until, $service) = @_;
1289 $start = 0 if !$start;
1290 $limit = 50 if !$limit;
1295 return if $count++ < $start;
1296 return if $limit <= 0;
1297 push @$lines, { n
=> int($count), t
=> $line};
1301 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1303 push @$cmd, '--unit', $service if $service;
1304 push @$cmd, '--since', $since if $since;
1305 push @$cmd, '--until', $until if $until;
1306 run_command
($cmd, outfunc
=> $parser);
1308 # HACK: ExtJS store.guaranteeRange() does not like empty array
1312 push @$lines, { n
=> $count, t
=> "no content"};
1315 return ($count, $lines);
1318 sub dir_glob_regex
{
1319 my ($dir, $regex) = @_;
1321 my $dh = IO
::Dir-
>new ($dir);
1322 return wantarray ?
() : undef if !$dh;
1324 while (defined(my $tmp = $dh->read)) {
1325 if (my @res = $tmp =~ m/^($regex)$/) {
1327 return wantarray ?
@res : $tmp;
1332 return wantarray ?
() : undef;
1335 sub dir_glob_foreach
{
1336 my ($dir, $regex, $func) = @_;
1338 my $dh = IO
::Dir-
>new ($dir);
1340 while (defined(my $tmp = $dh->read)) {
1341 if (my @res = $tmp =~ m/^($regex)$/) {
1348 sub assert_if_modified
{
1349 my ($digest1, $digest2) = @_;
1351 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1352 die "detected modified configuration - file changed by other user? Try again.\n";
1356 # Digest for short strings
1357 # like FNV32a, but we only return 31 bits (positive numbers)
1361 my $hval = 0x811c9dc5;
1363 foreach my $c (unpack('C*', $string)) {
1371 $hval = $hval & 0xffffffff;
1373 return $hval & 0x7fffffff;
1376 sub fnv31a_hex
{ return sprintf("%X", fnv31a
(@_)); }
1378 sub unpack_sockaddr_in46
{
1380 my $family = Socket
::sockaddr_family
($sin);
1381 my ($port, $host) = ($family == AF_INET6 ? Socket
::unpack_sockaddr_in6
($sin)
1382 : Socket
::unpack_sockaddr_in
($sin));
1383 return ($family, $port, $host);
1386 sub getaddrinfo_all
{
1387 my ($hostname, @opts) = @_;
1388 my %hints = ( flags
=> AI_V4MAPPED
| AI_ALL
,
1390 my ($err, @res) = Socket
::getaddrinfo
($hostname, '0', \
%hints);
1391 die "failed to get address info for: $hostname: $err\n" if $err;
1395 sub get_host_address_family
{
1396 my ($hostname, $socktype) = @_;
1397 my @res = getaddrinfo_all
($hostname, socktype
=> $socktype);
1398 return $res[0]->{family
};
1401 # get the fully qualified domain name of a host
1402 # same logic as hostname(1): The FQDN is the name getaddrinfo(3) returns,
1403 # given a nodename as a parameter
1405 my ($nodename) = @_;
1408 flags
=> AI_CANONNAME
,
1409 socktype
=> SOCK_DGRAM
1412 my ($err, @addrs) = Socket
::getaddrinfo
($nodename, undef, $hints);
1414 die "getaddrinfo: $err" if $err;
1416 return $addrs[0]->{canonname
};
1419 # Parses any sane kind of host, or host+port pair:
1420 # The port is always optional and thus may be undef.
1421 sub parse_host_and_port
{
1423 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1424 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1425 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1427 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1432 sub setresuid
($$$) {
1433 my ($ruid, $euid, $suid) = @_;
1434 return 0 == syscall(PVE
::Syscall
::setresuid
, $ruid, $euid, $suid);
1439 return 0 == syscall(PVE
::Syscall
::unshare
, $flags);
1443 my ($fileno, $nstype) = @_;
1444 return 0 == syscall(PVE
::Syscall
::setns
, $fileno, $nstype);
1449 return 0 == syscall(PVE
::Syscall
::syncfs
, $fileno);
1454 return 0 == syscall(PVE
::Syscall
::fsync
, $fileno);
1457 sub sync_mountpoint
{
1459 sysopen my $fd, $path, O_RDONLY
|O_CLOEXEC
or die "failed to open $path: $!\n";
1461 if (!syncfs
(fileno($fd))) {
1465 die "syncfs '$path' failed - $syncfs_err\n" if defined $syncfs_err;
1468 # support sending multi-part mail messages with a text and or a HTML part
1469 # mailto may be a single email string or an array of receivers
1471 my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_;
1472 my $mail_re = qr/[^-a-zA-Z0-9+._@]/;
1474 $mailto = [ $mailto ] if !ref($mailto);
1476 for my $to (@$mailto) {
1477 die "illegal character in mailto address\n" if $to =~ $mail_re;
1480 my $rcvrtxt = join (', ', @$mailto);
1482 $mailfrom = $mailfrom || "root";
1483 die "illegal character in mailfrom address\n" if $mailfrom =~ $mail_re;
1485 $author = $author // 'Proxmox VE';
1487 open (MAIL
, "|-", "sendmail", "-B", "8BITMIME", "-f", $mailfrom, "--", @$mailto) ||
1488 die "unable to open 'sendmail' - $!";
1490 my $date = time2str
('%a, %d %b %Y %H:%M:%S %z', time());
1492 my $is_multipart = $text && $html;
1494 # multipart spec see https://www.ietf.org/rfc/rfc1521.txt
1495 my $boundary = "----_=_NextPart_001_".int(time).$$;
1497 if ($subject =~ /[^[:ascii:]]/) {
1498 $subject = Encode
::encode
('MIME-Header', $subject);
1501 if ($subject =~ /[^[:ascii:]]/ || $is_multipart) {
1502 print MAIL
"MIME-Version: 1.0\n";
1504 print MAIL
"From: $author <$mailfrom>\n";
1505 print MAIL
"To: $rcvrtxt\n";
1506 print MAIL
"Date: $date\n";
1507 print MAIL
"Subject: $subject\n";
1509 if ($is_multipart) {
1510 print MAIL
"Content-Type: multipart/alternative;\n";
1511 print MAIL
"\tboundary=\"$boundary\"\n";
1513 print MAIL "This
is a multi-part message
in MIME format
.\n\n";
1514 print MAIL "--$boundary\n";
1517 if (defined($text)) {
1518 print MAIL "Content-Type
: text
/plain
;\n";
1519 print MAIL "\tcharset
=\"UTF-8
\"\n";
1520 print MAIL "Content-Transfer-Encoding
: 8bit
\n";
1523 # avoid 'remove extra line breaks' issue (MS Outlook)
1525 $text =~ s/^/$fill/gm;
1529 print MAIL "\n--$boundary\n" if $is_multipart;
1532 if (defined($html)) {
1533 print MAIL "Content-Type
: text
/html
;\n";
1534 print MAIL "\tcharset
=\"UTF-8
\"\n";
1535 print MAIL "Content-Transfer-Encoding
: 8bit
\n";
1540 print MAIL "\n--$boundary--\n" if $is_multipart;
1547 my ($perm, %opts) = @_;
1549 # default permissions are stricter than with file_set_contents
1550 $perm = 0600 if !defined($perm);
1552 my $dir = $opts{dir} // '/run';
1553 my $mode = $opts{mode} // O_RDWR;
1554 $mode |= O_EXCL if !$opts{allow_links};
1556 my $fh = IO::File->new($dir, $mode | O_TMPFILE, $perm);
1557 if (!$fh && $! == EOPNOTSUPP) {
1558 $dir = '/tmp' if !defined($opts{dir});
1559 $dir .= "/.tmpfile
.$$";
1560 $fh = IO::File->new($dir, $mode | O_CREAT | O_EXCL, $perm);
1561 unlink($dir) if $fh;
1563 die "failed to create tempfile
: $!\n" if !$fh;
1567 sub tempfile_contents {
1568 my ($data, $perm, %opts) = @_;
1570 my $fh = tempfile($perm, %opts);
1572 die "unable to
write to tempfile
: $!\n" if !print {$fh} $data;
1573 die "unable to flush to tempfile
: $!\n" if !defined($fh->flush());
1580 return ("/proc/$$/fd/".$fh->fileno, $fh);
1583 sub validate_ssh_public_keys {
1585 my @lines = split(/\n/, $raw);
1587 foreach my $line (@lines) {
1588 next if $line =~ m/^\s*$/;
1590 my ($filename, $handle) = tempfile_contents($line);
1591 run_command(["ssh-keygen
", "-l
", "-f
", $filename],
1592 outfunc => sub {}, errfunc => sub {});
1594 die "SSH public key validation error
\n" if $@;
1599 my ($dirfd, $pathname, $flags, $mode) = @_;
1600 my $fd = syscall(PVE::Syscall::openat, $dirfd, $pathname, $flags, $mode//0);
1601 return undef if $fd < 0;
1602 # sysopen() doesn't deal with numeric file descriptors apparently
1603 # so we need to convert to a mode string for IO::Handle->new_from_fd
1604 my $flagstr = ($flags & O_RDWR) ? 'rw' : ($flags & O_WRONLY) ? 'w' : 'r';
1605 my $handle = IO::Handle->new_from_fd($fd, $flagstr);
1606 return $handle if $handle;
1607 my $err = $!; # save error before closing the raw fd
1608 syscall(PVE::Syscall::close, $fd); # close
1614 my ($dirfd, $name, $mode) = @_;
1615 return syscall(PVE::Syscall::mkdirat, $dirfd, $name, $mode) == 0;
1618 sub fchownat($$$$$) {
1619 my ($dirfd, $pathname, $owner, $group, $flags) = @_;
1620 return syscall(PVE::Syscall::fchownat, $dirfd, $pathname, $owner, $group, $flags) == 0;
1623 my $salt_starter = time();
1629 my $salt = substr(Digest::SHA::sha1_base64(time() + $salt_starter + $$), 0, 8);
1631 # crypt does not want '+' in salt (see 'man crypt')
1634 return crypt(encode("utf8
", $pw), "\
$5\$$salt\$");
1637 # intended usage: convert_size($val, "kb
" => "gb
")
1638 # we round up to the next integer by default
1639 # E.g. `convert_size(1023, "b
" => "kb
")` returns 1
1640 # use $no_round_up to switch this off, above example would then return 0
1641 # this is also true for converting down e.g. 0.0005 gb to mb returns 1
1642 # (0 if $no_round_up is true)
1643 # allowed formats for value:
1649 my ($value, $from, $to, $no_round_up) = @_;
1660 die "no value
given"
1661 if !defined($value) || $value eq "";
1663 $from = lc($from // ''); $to = lc($to // '');
1664 die "unknown
'from' and/or 'to' units
($from => $to)"
1665 if !defined($units->{$from}) || !defined($units->{$to});
1667 die "value
'$value' is not a valid
, positive number
"
1668 if $value !~ m/^(?:[0-9]+\.?[0-9]*|[0-9]*\.[0-9]+)$/;
1670 my $shift_amount = ($units->{$from} - $units->{$to}) * 10;
1672 $value *= 2**$shift_amount;
1673 $value++ if !$no_round_up && ($value - int($value)) > 0.0;
1678 # uninterruptible readline
1680 sub readline_nointr {
1685 last if defined($line) || ($! != EINTR);
1692 $host_arch = (POSIX::uname())[4] if !$host_arch;
1696 # Devices are: [ (12 bits minor) (12 bits major) (8 bits minor) ]
1697 sub dev_t_major($) {
1699 return (int($dev_t) & 0xfff00) >> 8;
1702 sub dev_t_minor($) {
1704 $dev_t = int($dev_t);
1705 return (($dev_t >> 12) & 0xfff00) | ($dev_t & 0xff);
1708 # Given an array of array refs [ \[a b c], \[a b b], \[e b a] ]
1709 # Returns the intersection of elements as a single array [a b]
1710 sub array_intersect {
1713 if (!ref($arrays->[0])) {
1714 $arrays = [ grep { ref($_) eq 'ARRAY' } @_ ];
1717 return [] if scalar(@$arrays) == 0;
1718 return $arrays->[0] if scalar(@$arrays) == 1;
1720 my $array_unique = sub {
1722 return grep { ! $seen{ $_ }++ } @_;
1725 # base idea is to get all unique members from the first array, then
1726 # check the common elements with the next (uniquely made) one, only keep
1727 # those. Repeat for every array and at the end we only have those left
1728 # which exist in all arrays
1729 my $return_arr = [ $array_unique->(@{$arrays->[0]}) ];
1730 for my $i (1 .. $#$arrays) {
1732 # $return_arr is already unique, explicit at before the loop, implicit below.
1733 foreach my $element (@$return_arr, $array_unique->(@{$arrays->[$i]})) {
1737 foreach my $element (keys %count) {
1738 push @$return_arr, $element if $count{$element} > 1;
1740 last if scalar(@$return_arr) == 0; # empty intersection, early exit
1746 sub open_tree($$$) {
1747 my ($dfd, $pathname, $flags) = @_;
1748 return PVE::Syscall::file_handle_result(syscall(
1749 &PVE::Syscall::open_tree,
1756 sub move_mount($$$$$) {
1757 my ($from_dirfd, $from_pathname, $to_dirfd, $to_pathname, $flags) = @_;
1758 return 0 == syscall(
1759 &PVE::Syscall::move_mount,
1769 my ($fsname, $flags) = @_;
1770 return PVE::Syscall::file_handle_result(syscall(&PVE::Syscall::fsopen, $fsname, $flags));
1774 my ($fd, $flags, $mount_attrs) = @_;
1775 return PVE::Syscall::file_handle_result(syscall(
1776 &PVE::Syscall::fsmount,
1784 my ($dirfd, $pathname, $flags) = @_;
1785 return PVE::Syscall::file_handle_result(syscall(
1786 &PVE::Syscall::fspick,
1793 sub fsconfig($$$$$) {
1794 my ($fd, $command, $key, $value, $aux) = @_;
1795 return 0 == syscall(&PVE::Syscall::fsconfig, $fd, $command, $key, $value, $aux);
1798 # "raw
" mount, old api, not for generic use (as it does not invoke any helpers).
1799 # use for lower level stuff such as bind/remount/... or simple tmpfs mounts
1801 my ($source, $target, $filesystemtype, $mountflags, $data) = @_;
1802 return 0 == syscall(
1803 &PVE::Syscall::mount,
1813 my ($left, $right, $cmp) = @_;
1815 return 0 if !defined($left) && !defined($right);
1816 return -1 if !defined($left);
1817 return 1 if !defined($right);
1818 return $cmp->($left, $right);