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);
24 use String
::ShellQuote
;
25 use Time
::HiRes
qw(usleep gettimeofday tv_interval alarm);
26 use Net
::DBus
qw(dbus_uint32 dbus_uint64);
27 use Net
::DBus
::Callback
;
28 use Net
::DBus
::Reactor
;
29 use Scalar
::Util
'weaken';
32 # avoid warning when parsing long hex values with hex()
33 no warnings
'portable'; # Support for 64-bit ints required
56 my $pvelogdir = "/var/log/pve";
57 my $pvetaskdir = "$pvelogdir/tasks";
62 my $IPV4OCTET = "(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])";
63 our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)";
64 my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})";
65 my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))";
68 "(?:(?:" . "(?:$IPV6H16:){6})$IPV6LS32)|" .
69 "(?:(?:" . "::(?:$IPV6H16:){5})$IPV6LS32)|" .
70 "(?:(?:(?:" . "$IPV6H16)?::(?:$IPV6H16:){4})$IPV6LS32)|" .
71 "(?:(?:(?:(?:$IPV6H16:){0,1}$IPV6H16)?::(?:$IPV6H16:){3})$IPV6LS32)|" .
72 "(?:(?:(?:(?:$IPV6H16:){0,2}$IPV6H16)?::(?:$IPV6H16:){2})$IPV6LS32)|" .
73 "(?:(?:(?:(?:$IPV6H16:){0,3}$IPV6H16)?::(?:$IPV6H16:){1})$IPV6LS32)|" .
74 "(?:(?:(?:(?:$IPV6H16:){0,4}$IPV6H16)?::" . ")$IPV6LS32)|" .
75 "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" . ")$IPV6H16)|" .
76 "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" . ")))";
78 our $IPRE = "(?:$IPV4RE|$IPV6RE)";
80 use constant {CLONE_NEWNS
=> 0x00020000,
81 CLONE_NEWUTS
=> 0x04000000,
82 CLONE_NEWIPC
=> 0x08000000,
83 CLONE_NEWUSER
=> 0x10000000,
84 CLONE_NEWPID
=> 0x20000000,
85 CLONE_NEWNET
=> 0x40000000};
87 use constant {O_PATH
=> 0x00200000,
88 O_TMPFILE
=> 0x00410000}; # This includes O_DIRECTORY
90 sub run_with_timeout
{
91 my ($timeout, $code, @param) = @_;
93 die "got timeout\n" if $timeout <= 0;
95 my $prev_alarm = alarm 0; # suspend outer alarm early
102 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
103 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
104 local $SIG{__DIE__
}; # see SA bug 4631
108 eval { $res = &$code(@param); };
110 alarm(0); # avoid race conditions
119 # this shouldn't happen anymore?
120 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
127 # flock: we use one file handle per process, so lock file
128 # can be nested multiple times and succeeds for the same process.
130 # Since this is the only way we lock now and we don't have the old
131 # 'lock(); code(); unlock();' pattern anymore we do not actually need to
132 # count how deep we're nesting. Therefore this hash now stores a weak reference
133 # to a boolean telling us whether we already have a lock.
135 my $lock_handles = {};
138 my ($filename, $timeout, $shared, $code, @param) = @_;
140 $timeout = 10 if !$timeout;
142 my $mode = $shared ? LOCK_SH
: LOCK_EX
;
144 my $lockhash = ($lock_handles->{$$} //= {});
146 # Returns a locked file handle.
147 my $get_locked_file = sub {
148 my $fh = IO
::File-
>new(">>$filename")
149 or die "can't open file - $!\n";
151 if (!flock($fh, $mode|LOCK_NB
)) {
152 print STDERR
"trying to acquire lock...";
155 $success = flock($fh, $mode);
156 # try again on EINTR (see bug #273)
157 if ($success || ($! != EINTR
)) {
162 print STDERR
" failed\n";
163 die "can't acquire lock '$filename' - $!\n";
165 print STDERR
" OK\n";
172 my $checkptr = $lockhash->{$filename};
173 my $check = 0; # This must not go out of scope before running the code.
174 my $local_fh; # This must stay local
175 if (!$checkptr || !$$checkptr) {
176 # We cannot create a weak reference in a single atomic step, so we first
177 # create a false-value, then create a reference to it, then weaken it,
178 # and after successfully locking the file we change the boolean value.
180 # The reason for this is that if an outer SIGALRM throws an exception
181 # between creating the reference and weakening it, a subsequent call to
182 # lock_file_full() will see a leftover full reference to a valid
183 # variable. This variable must be 0 in order for said call to attempt to
184 # lock the file anew.
186 # An externally triggered exception elsewhere in the code will cause the
187 # weak reference to become 'undef', and since the file handle is only
188 # stored in the local scope in $local_fh, the file will be closed by
189 # perl's cleanup routines as well.
191 # This still assumes that an IO::File handle can properly deal with such
192 # exceptions thrown during its own destruction, but that's up to perls
194 $lockhash->{$filename} = \
$check;
195 weaken
$lockhash->{$filename};
196 $local_fh = eval { run_with_timeout
($timeout, $get_locked_file) };
198 $@ = "can't lock file '$filename' - $@";
203 $res = eval { &$code(@param); };
210 my ($filename, $timeout, $code, @param) = @_;
212 return lock_file_full
($filename, $timeout, 0, $code, @param);
215 sub file_set_contents
{
216 my ($filename, $data, $perm) = @_;
218 $perm = 0644 if !defined($perm);
220 my $tmpname = "$filename.tmp.$$";
223 my ($fh, $tries) = (undef, 0);
224 while (!$fh && $tries++ < 3) {
225 $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
|O_EXCL
, $perm);
226 if (!$fh && $! == EEXIST
) {
227 unlink($tmpname) or die "unable to delete old temp file: $!\n";
230 die "unable to open file '$tmpname' - $!\n" if !$fh;
231 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
232 die "closing file '$tmpname' failed - $!\n" unless close $fh;
241 if (!rename($tmpname, $filename)) {
242 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
248 sub file_get_contents
{
249 my ($filename, $max) = @_;
251 my $fh = IO
::File-
>new($filename, "r") ||
252 die "can't open '$filename' - $!\n";
254 my $content = safe_read_from
($fh, $max, 0, $filename);
262 my ($filename, $dst, $max, $perm) = @_;
264 file_set_contents
($dst, file_get_contents
($filename, $max), $perm);
267 sub file_read_firstline
{
270 my $fh = IO
::File-
>new ($filename, "r");
271 return undef if !$fh;
279 my ($fh, $max, $oneline, $filename) = @_;
281 $max = 32768 if !$max;
283 my $subject = defined($filename) ?
"file '$filename'" : 'input';
288 while ($count = sysread($fh, $input, 8192, $br)) {
290 die "$subject too long - aborting\n" if $br > $max;
291 if ($oneline && $input =~ m/^(.*)\n/) {
296 die "unable to read $subject - $!\n" if !defined($count);
301 # The $cmd parameter can be:
303 # This is generally executed by passing it to the shell with the -c option.
304 # However, it can be executed in one of two ways, depending on whether
305 # there's a pipe involved:
306 # *) with pipe: passed explicitly to bash -c, prefixed with:
308 # *) without a pipe: passed to perl's open3 which uses 'sh -c'
309 # (Note that this may result in two different syntax requirements!)
311 # -) an array of arguments (strings)
312 # Will be executed without interference from a shell. (Parameters are passed
313 # as is, no escape sequences of strings will be touched.)
314 # -) an array of arrays
315 # Each array represents a command, and each command's output is piped into
316 # the following command's standard input.
317 # For this a shell command string is created with pipe symbols between each
319 # Each command is a list of strings meant to end up in the final command
320 # unchanged. In order to achieve this, every argument is shell-quoted.
321 # Quoting can be disabled for a particular argument by turning it into a
322 # reference, this allows inserting arbitrary shell options.
323 # For instance: the $cmd [ [ 'echo', 'hello', \'>/dev/null' ] ] will not
324 # produce any output, while the $cmd [ [ 'echo', 'hello', '>/dev/null' ] ]
325 # will literally print: hello >/dev/null
327 my ($cmd, %param) = @_;
332 if (my $ref = ref($cmd)) {
333 if (ref($cmd->[0])) {
334 $cmdstr = 'set -o pipefail && ';
336 foreach my $command (@$cmd) {
337 # concatenate quoted parameters
338 # strings which are passed by reference are NOT shell quoted
339 $cmdstr .= $pipe . join(' ', map { ref($_) ?
$$_ : shellquote
($_) } @$command);
342 $cmd = [ '/bin/bash', '-c', "$cmdstr" ];
344 $cmdstr = cmd2string
($cmd);
349 # see 'man bash' for option pipefail
350 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
374 foreach my $p (keys %param) {
375 if ($p eq 'timeout') {
376 $timeout = $param{$p};
377 } elsif ($p eq 'umask') {
378 $old_umask = umask($param{$p});
379 } elsif ($p eq 'errmsg') {
380 $errmsg = $param{$p};
381 } elsif ($p eq 'input') {
383 } elsif ($p eq 'output') {
384 $output = $param{$p};
385 } elsif ($p eq 'outfunc') {
386 $outfunc = $param{$p};
387 } elsif ($p eq 'errfunc') {
388 $errfunc = $param{$p};
389 } elsif ($p eq 'logfunc') {
390 $logfunc = $param{$p};
391 } elsif ($p eq 'afterfork') {
392 $afterfork = $param{$p};
393 } elsif ($p eq 'noerr') {
395 } elsif ($p eq 'keeplocale') {
396 $keeplocale = $param{$p};
398 die "got unknown parameter '$p' for run_command\n";
403 my $origerrfunc = $errfunc;
407 &$origerrfunc("$laststderr\n");
409 print STDERR
"$laststderr\n" if $laststderr;
416 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
417 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
418 my $error = IO
::File-
>new();
423 local $ENV{LC_ALL
} = 'C' if !$keeplocale;
425 # suppress LVM warnings like: "File descriptor 3 left open";
426 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
428 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
430 # if we pipe fron STDIN, open3 closes STDIN, so we we
431 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
432 # as soon as we open a new file.
433 # to avoid that we open /dev/null
434 if (!ref($writer) && !defined(fileno(STDIN
))) {
436 open(STDIN
, "</dev/null");
443 if ($orig_pid != $$) {
451 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
452 $oldtimeout = alarm($timeout) if $timeout;
454 &$afterfork() if $afterfork;
457 print $writer $input if defined $input;
461 my $select = new IO
::Select
;
462 $select->add($reader) if ref($reader);
463 $select->add($error);
468 my $starttime = time();
470 while ($select->count) {
471 my @handles = $select->can_read(1);
473 foreach my $h (@handles) {
475 my $count = sysread ($h, $buf, 4096);
476 if (!defined ($count)) {
482 $select->remove ($h) if !$count;
484 if ($outfunc || $logfunc) {
487 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
489 &$outfunc($line) if $outfunc;
490 &$logfunc($line) if $logfunc;
503 } elsif ($h eq $error) {
504 if ($errfunc || $logfunc) {
507 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
509 &$errfunc($line) if $errfunc;
510 &$logfunc($line) if $logfunc;
527 &$outfunc($outlog) if $outfunc && $outlog;
528 &$logfunc($outlog) if $logfunc && $outlog;
530 &$errfunc($errlog) if $errfunc && $errlog;
531 &$logfunc($errlog) if $logfunc && $errlog;
536 die "failed to execute\n";
537 } elsif (my $sig = ($? & 127)) {
538 die "got signal $sig\n";
539 } elsif ($exitcode = ($? >> 8)) {
540 if (!($exitcode == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
541 if ($errmsg && $laststderr) {
542 my $lerr = $laststderr;
546 die "exit code $exitcode\n";
557 if ($errmsg && $laststderr) {
558 &$errfunc(undef); # flush laststderr
561 umask ($old_umask) if defined($old_umask);
563 alarm($oldtimeout) if $oldtimeout;
566 if ($pid && ($err eq "got timeout\n")) {
569 die "command '$cmdstr' failed: $err";
573 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
576 die "command '$cmdstr' failed: $err";
584 my $listtxt = shift || '';
586 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
588 $listtxt =~ s/[,;]/ /g;
589 $listtxt =~ s/^\s+//;
591 my @data = split (/\s+/, $listtxt);
599 return $txt if !defined($txt);
607 # simple uri templates like "/vms/{vmid}"
608 sub template_replace
{
609 my ($tmpl, $data) = @_;
611 return $tmpl if !$tmpl;
614 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
616 $res .= ($data->{$3} || '-') if $2;
622 my ($filename, $fh, $data) = @_;
626 my $res = print $fh $data;
628 die "write to '$filename' failed\n" if !$res;
634 'at' => 'ftp.at.debian.org',
635 'au' => 'ftp.au.debian.org',
636 'be' => 'ftp.be.debian.org',
637 'bg' => 'ftp.bg.debian.org',
638 'br' => 'ftp.br.debian.org',
639 'ca' => 'ftp.ca.debian.org',
640 'ch' => 'ftp.ch.debian.org',
641 'cl' => 'ftp.cl.debian.org',
642 'cz' => 'ftp.cz.debian.org',
643 'de' => 'ftp.de.debian.org',
644 'dk' => 'ftp.dk.debian.org',
645 'ee' => 'ftp.ee.debian.org',
646 'es' => 'ftp.es.debian.org',
647 'fi' => 'ftp.fi.debian.org',
648 'fr' => 'ftp.fr.debian.org',
649 'gr' => 'ftp.gr.debian.org',
650 'hk' => 'ftp.hk.debian.org',
651 'hr' => 'ftp.hr.debian.org',
652 'hu' => 'ftp.hu.debian.org',
653 'ie' => 'ftp.ie.debian.org',
654 'is' => 'ftp.is.debian.org',
655 'it' => 'ftp.it.debian.org',
656 'jp' => 'ftp.jp.debian.org',
657 'kr' => 'ftp.kr.debian.org',
658 'mx' => 'ftp.mx.debian.org',
659 'nl' => 'ftp.nl.debian.org',
660 'no' => 'ftp.no.debian.org',
661 'nz' => 'ftp.nz.debian.org',
662 'pl' => 'ftp.pl.debian.org',
663 'pt' => 'ftp.pt.debian.org',
664 'ro' => 'ftp.ro.debian.org',
665 'ru' => 'ftp.ru.debian.org',
666 'se' => 'ftp.se.debian.org',
667 'si' => 'ftp.si.debian.org',
668 'sk' => 'ftp.sk.debian.org',
669 'tr' => 'ftp.tr.debian.org',
670 'tw' => 'ftp.tw.debian.org',
671 'gb' => 'ftp.uk.debian.org',
672 'us' => 'ftp.us.debian.org',
677 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
678 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
679 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
680 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
681 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
682 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
683 #'et' => [], # Ethopia or Estonia ??
684 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
685 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
686 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
687 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
688 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
689 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
690 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
691 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
692 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
693 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
694 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
695 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
696 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
697 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
698 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
699 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
700 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
701 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
702 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
703 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
704 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
705 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
706 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
708 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
711 my $kvmkeymaparray = [];
712 foreach my $lc (sort keys %$keymaphash) {
713 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
721 return $kvmkeymaparray;
725 my ($param, $key) = @_;
727 my $res = $param->{$key};
728 delete $param->{$key};
733 # Note: we use this to wait until vncterm/spiceterm is ready
734 sub wait_for_vnc_port
{
735 my ($port, $timeout) = @_;
737 $timeout = 5 if !$timeout;
739 my $starttime = [gettimeofday
];
743 while (($elapsed = tv_interval
($starttime)) < $timeout) {
744 # -Htln = don't print header, tcp, listening sockets only, numeric ports
745 run_command
(['/bin/ss', '-Htln', "sport = :$port"], outfunc
=> sub {
747 if ($line =~ m/^LISTEN\s+\d+\s+\d+\s+\S+:(\d+)\s/) {
748 $found = 1 if ($port == $1);
752 $sleeptime += 100000 if $sleeptime < 1000000;
759 sub next_unused_port
{
760 my ($range_start, $range_end, $family, $address) = @_;
762 # We use a file to register allocated ports.
763 # Those registrations expires after $expiretime.
764 # We use this to avoid race conditions between
765 # allocation and use of ports.
767 my $filename = "/var/tmp/pve-reserved-ports";
776 if (my $fh = IO
::File-
>new ($filename, "r")) {
777 while (my $line = <$fh>) {
778 if ($line =~ m/^(\d+)\s(\d+)$/) {
779 my ($port, $timestamp) = ($1, $2);
780 if (($timestamp + $expiretime) > $ctime) {
781 $ports->{$port} = $timestamp; # not expired
788 my %sockargs = (Listen
=> 5,
791 Proto
=> IPPROTO_TCP
,
792 GetAddrInfoFlags
=> 0);
793 $sockargs{LocalAddr
} = $address if defined($address);
795 for (my $p = $range_start; $p < $range_end; $p++) {
796 next if $ports->{$p}; # reserved
798 $sockargs{LocalPort
} = $p;
799 my $sock = IO
::Socket
::IP-
>new(%sockargs);
804 $ports->{$p} = $ctime;
810 foreach my $p (keys %$ports) {
811 $data .= "$p $ports->{$p}\n";
814 file_set_contents
($filename, $data);
819 my $p = lock_file
('/var/lock/pve-ports.lck', 10, $code);
822 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
827 sub next_migrate_port
{
828 my ($family, $address) = @_;
829 return next_unused_port
(60000, 60050, $family, $address);
833 my ($family, $address) = @_;
834 return next_unused_port
(5900, 6000, $family, $address);
837 sub next_spice_port
{
838 my ($family, $address) = @_;
839 return next_unused_port
(61000, 61099, $family, $address);
842 # sigkill after $timeout a $sub running in a fork if it can't write a pipe
843 # the $sub has to return a single scalar
844 sub run_fork_with_timeout
{
845 my ($timeout, $sub) = @_;
849 my $pipe_out = IO
::Pipe-
>new();
850 my $pipe_err = IO
::Pipe-
>new();
852 # disable pending alarms, save their remaining time
853 my $prev_alarm = alarm 0;
855 # trap before forking to avoid leaving a zombie if the parent get killed
857 local $SIG{INT
} = $SIG{TERM
} = $SIG{QUIT
} = $SIG{HUP
} = $SIG{PIPE
} = sub {
862 if (!defined($child)) {
863 die "fork failed: $!\n";
873 print {$pipe_out} "$res";
877 print {$pipe_err} "$err";
887 my $readvalues = sub {
890 $error = <$pipe_err>;
893 run_with_timeout
($timeout, $readvalues);
898 kill('KILL', $child);
902 die "interrupted by unexpected signal\n" if $sig_received;
904 die $error if $error;
908 # NOTE: NFS syscall can't be interrupted, so alarm does
909 # not work to provide timeouts.
910 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
911 # So fork() before using Filesys::Df
913 my ($path, $timeout) = @_;
921 my $pipe = IO
::Pipe-
>new();
923 if (!defined($child)) {
924 warn "fork failed: $!\n";
931 my $df = Filesys
::Df
::df
($path, 1);
932 print {$pipe} "$df->{blocks}\n$df->{used}\n$df->{bavail}\n";
944 my $readvalues = sub {
945 $res->{total
} = int((<$pipe> =~ /^(\d*)$/)[0]);
946 $res->{used
} = int((<$pipe> =~ /^(\d*)$/)[0]);
947 $res->{avail
} = int((<$pipe> =~ /^(\d*)$/)[0]);
950 run_with_timeout
($timeout, $readvalues);
954 kill('KILL', $child);
960 # We use this to uniquely identify a process.
961 # An 'Unique Process ID' has the following format:
962 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
967 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
968 # more that 8 characters for pstart
969 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
970 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
975 my ($upid, $noerr) = @_;
980 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
981 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
982 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]+):$/) {
984 $res->{pid
} = hex($3);
985 $res->{pstart
} = hex($4);
986 $res->{starttime
} = hex($5);
991 my $subdir = substr($5, 7, 8);
992 $filename = "$pvetaskdir/$subdir/$upid";
995 return undef if $noerr;
996 die "unable to parse worker upid '$upid'\n";
999 return wantarray ?
($res, $filename) : $res;
1005 my ($task, $filename) = upid_decode
($upid);
1007 my $dirname = dirname
($filename);
1008 make_path
($dirname);
1010 my $wwwid = getpwnam('www-data') ||
1011 die "getpwnam failed";
1015 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
1016 die "unable to create output file '$filename' - $!\n";
1017 chown $wwwid, -1, $outfh;
1022 sub upid_read_status
{
1025 my ($task, $filename) = upid_decode
($upid);
1026 my $fh = IO
::File-
>new($filename, "r");
1027 return "unable to open file - $!" if !$fh;
1029 sysseek($fh, -$maxlen, 2);
1031 my $br = sysread($fh, $readbuf, $maxlen);
1034 return "unable to extract last line"
1035 if $readbuf !~ m/\n?(.+)$/;
1037 if ($line =~ m/^TASK OK$/) {
1039 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
1042 return "unexpected status";
1045 return "unable to read tail (got $br bytes)";
1048 # useful functions to store comments in config files
1052 # all control and hi-bit characters, and ':'
1053 my $unsafe = "^\x20-\x39\x3b-\x7e";
1054 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
1060 return Encode
::decode
("utf8", uri_unescape
($data));
1063 # depreciated - do not use!
1064 # we now decode all parameters by default
1065 sub decode_utf8_parameters
{
1068 foreach my $p (qw(comment description firstname lastname)) {
1069 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
1075 sub random_ether_addr
{
1078 my ($seconds, $microseconds) = gettimeofday
;
1080 my $rand = Digest
::SHA
::sha1
($$, rand(), $seconds, $microseconds);
1082 # clear multicast, set local id
1083 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
1085 my $addr = sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
1086 if (defined($prefix)) {
1087 $addr = uc($prefix) . substr($addr, length($prefix));
1095 return String
::ShellQuote
::shell_quote
($str);
1101 die "no arguments" if !$cmd;
1103 return $cmd if !ref($cmd);
1106 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
1108 return join (' ', @qa);
1111 # split an shell argument string into an array,
1115 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
1119 my ($filename, $start, $limit, $filter) = @_;
1124 my $fh = IO
::File-
>new($filename, "r");
1127 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
1128 return ($count, $lines);
1131 $start = 0 if !$start;
1132 $limit = 50 if !$limit;
1137 # duplicate code, so that we do not slow down normal path
1138 while (defined($line = <$fh>)) {
1139 next if $line !~ m/$filter/;
1140 next if $count++ < $start;
1141 next if $limit <= 0;
1143 push @$lines, { n
=> $count, t
=> $line};
1147 while (defined($line = <$fh>)) {
1148 next if $count++ < $start;
1149 next if $limit <= 0;
1151 push @$lines, { n
=> $count, t
=> $line};
1158 # HACK: ExtJS store.guaranteeRange() does not like empty array
1162 push @$lines, { n
=> $count, t
=> "no content"};
1165 return ($count, $lines);
1169 my ($start, $limit, $since, $until, $service) = @_;
1174 $start = 0 if !$start;
1175 $limit = 50 if !$limit;
1180 return if $count++ < $start;
1181 return if $limit <= 0;
1182 push @$lines, { n
=> int($count), t
=> $line};
1186 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1188 push @$cmd, '--unit', $service if $service;
1189 push @$cmd, '--since', $since if $since;
1190 push @$cmd, '--until', $until if $until;
1191 run_command
($cmd, outfunc
=> $parser);
1193 # HACK: ExtJS store.guaranteeRange() does not like empty array
1197 push @$lines, { n
=> $count, t
=> "no content"};
1200 return ($count, $lines);
1203 sub dir_glob_regex
{
1204 my ($dir, $regex) = @_;
1206 my $dh = IO
::Dir-
>new ($dir);
1207 return wantarray ?
() : undef if !$dh;
1209 while (defined(my $tmp = $dh->read)) {
1210 if (my @res = $tmp =~ m/^($regex)$/) {
1212 return wantarray ?
@res : $tmp;
1217 return wantarray ?
() : undef;
1220 sub dir_glob_foreach
{
1221 my ($dir, $regex, $func) = @_;
1223 my $dh = IO
::Dir-
>new ($dir);
1225 while (defined(my $tmp = $dh->read)) {
1226 if (my @res = $tmp =~ m/^($regex)$/) {
1233 sub assert_if_modified
{
1234 my ($digest1, $digest2) = @_;
1236 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1237 die "detected modified configuration - file changed by other user? Try again.\n";
1241 # Digest for short strings
1242 # like FNV32a, but we only return 31 bits (positive numbers)
1246 my $hval = 0x811c9dc5;
1248 foreach my $c (unpack('C*', $string)) {
1256 $hval = $hval & 0xffffffff;
1258 return $hval & 0x7fffffff;
1261 sub fnv31a_hex
{ return sprintf("%X", fnv31a
(@_)); }
1263 sub unpack_sockaddr_in46
{
1265 my $family = Socket
::sockaddr_family
($sin);
1266 my ($port, $host) = ($family == AF_INET6 ? Socket
::unpack_sockaddr_in6
($sin)
1267 : Socket
::unpack_sockaddr_in
($sin));
1268 return ($family, $port, $host);
1271 sub getaddrinfo_all
{
1272 my ($hostname, @opts) = @_;
1273 my %hints = ( flags
=> AI_V4MAPPED
| AI_ALL
,
1275 my ($err, @res) = Socket
::getaddrinfo
($hostname, '0', \
%hints);
1276 die "failed to get address info for: $hostname: $err\n" if $err;
1280 sub get_host_address_family
{
1281 my ($hostname, $socktype) = @_;
1282 my @res = getaddrinfo_all
($hostname, socktype
=> $socktype);
1283 return $res[0]->{family
};
1286 # get the fully qualified domain name of a host
1287 # same logic as hostname(1): The FQDN is the name getaddrinfo(3) returns,
1288 # given a nodename as a parameter
1290 my ($nodename) = @_;
1293 flags
=> AI_CANONNAME
,
1294 socktype
=> SOCK_DGRAM
1297 my ($err, @addrs) = Socket
::getaddrinfo
($nodename, undef, $hints);
1299 die "getaddrinfo: $err" if $err;
1301 return $addrs[0]->{canonname
};
1304 # Parses any sane kind of host, or host+port pair:
1305 # The port is always optional and thus may be undef.
1306 sub parse_host_and_port
{
1308 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1309 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1310 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1312 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1319 return 0 == syscall(PVE
::Syscall
::unshare
, $flags);
1323 my ($fileno, $nstype) = @_;
1324 return 0 == syscall(PVE
::Syscall
::setns
, $fileno, $nstype);
1329 return 0 == syscall(PVE
::Syscall
::syncfs
, $fileno);
1332 sub sync_mountpoint
{
1334 sysopen my $fd, $path, O_PATH
or die "failed to open $path: $!\n";
1335 my $result = syncfs
(fileno($fd));
1340 # support sending multi-part mail messages with a text and or a HTML part
1341 # mailto may be a single email string or an array of receivers
1343 my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_;
1344 my $mail_re = qr/[^-a-zA-Z0-9+._@]/;
1346 $mailto = [ $mailto ] if !ref($mailto);
1348 foreach (@$mailto) {
1349 die "illegal character in mailto address\n"
1350 if ($_ =~ $mail_re);
1353 my $rcvrtxt = join (', ', @$mailto);
1355 $mailfrom = $mailfrom || "root";
1356 die "illegal character in mailfrom address\n"
1357 if $mailfrom =~ $mail_re;
1359 $author = $author || 'Proxmox VE';
1361 open (MAIL
, "|-", "sendmail", "-B", "8BITMIME", "-f", $mailfrom, @$mailto) ||
1362 die "unable to open 'sendmail' - $!";
1364 # multipart spec see https://www.ietf.org/rfc/rfc1521.txt
1365 my $boundary = "----_=_NextPart_001_".int(time).$$;
1367 print MAIL
"Content-Type: multipart/alternative;\n";
1368 print MAIL
"\tboundary=\"$boundary\"\n";
1369 print MAIL "MIME-Version
: 1.0\n";
1371 print MAIL "FROM
: $author <$mailfrom>\n";
1372 print MAIL "TO
: $rcvrtxt\n";
1373 print MAIL "SUBJECT
: $subject\n";
1375 print MAIL "This
is a multi-part message
in MIME format
.\n\n";
1376 print MAIL "--$boundary\n";
1378 if (defined($text)) {
1379 print MAIL "Content-Type
: text
/plain
;\n";
1380 print MAIL "\tcharset
=\"UTF8
\"\n";
1381 print MAIL "Content-Transfer-Encoding
: 8bit
\n";
1384 # avoid 'remove extra line breaks' issue (MS Outlook)
1386 $text =~ s/^/$fill/gm;
1390 print MAIL "\n--$boundary\n";
1393 if (defined($html)) {
1394 print MAIL "Content-Type
: text
/html
;\n";
1395 print MAIL "\tcharset
=\"UTF8
\"\n";
1396 print MAIL "Content-Transfer-Encoding
: 8bit
\n";
1401 print MAIL "\n--$boundary--\n";
1408 my ($perm, %opts) = @_;
1410 # default permissions are stricter than with file_set_contents
1411 $perm = 0600 if !defined($perm);
1413 my $dir = $opts{dir} // '/run';
1414 my $mode = $opts{mode} // O_RDWR;
1415 $mode |= O_EXCL if !$opts{allow_links};
1417 my $fh = IO::File->new($dir, $mode | O_TMPFILE, $perm);
1418 if (!$fh && $! == EOPNOTSUPP) {
1419 $dir = '/tmp' if !defined($opts{dir});
1420 $dir .= "/.tmpfile
.$$";
1421 $fh = IO::File->new($dir, $mode | O_CREAT | O_EXCL, $perm);
1422 unlink($dir) if $fh;
1424 die "failed to create tempfile
: $!\n" if !$fh;
1428 sub tempfile_contents {
1429 my ($data, $perm, %opts) = @_;
1431 my $fh = tempfile($perm, %opts);
1433 die "unable to
write to tempfile
: $!\n" if !print {$fh} $data;
1434 die "unable to flush to tempfile
: $!\n" if !defined($fh->flush());
1441 return ("/proc/$$/fd/".$fh->fileno, $fh);
1444 sub validate_ssh_public_keys {
1446 my @lines = split(/\n/, $raw);
1448 foreach my $line (@lines) {
1449 next if $line =~ m/^\s*$/;
1451 my ($filename, $handle) = tempfile_contents($line);
1452 run_command(["ssh-keygen
", "-l
", "-f
", $filename],
1453 outfunc => sub {}, errfunc => sub {});
1455 die "SSH public key validation error
\n" if $@;
1460 my ($dirfd, $pathname, $flags, $mode) = @_;
1461 my $fd = syscall(PVE::Syscall::openat, $dirfd, $pathname, $flags, $mode//0);
1462 return undef if $fd < 0;
1463 # sysopen() doesn't deal with numeric file descriptors apparently
1464 # so we need to convert to a mode string for IO::Handle->new_from_fd
1465 my $flagstr = ($flags & O_RDWR) ? 'rw' : ($flags & O_WRONLY) ? 'w' : 'r';
1466 my $handle = IO::Handle->new_from_fd($fd, $flagstr);
1467 return $handle if $handle;
1468 my $err = $!; # save error before closing the raw fd
1469 syscall(PVE::Syscall::close, $fd); # close
1475 my ($dirfd, $name, $mode) = @_;
1476 return syscall(PVE::Syscall::mkdirat, $dirfd, $name, $mode) == 0;
1479 # NOTE: This calls the dbus main loop and must not be used when another dbus
1480 # main loop is being used as we need to wait for the JobRemoved signal.
1481 # Polling the job status instead doesn't work because this doesn't give us the
1482 # distinction between success and failure.
1484 # Note that the description is mandatory for security reasons.
1485 sub enter_systemd_scope {
1486 my ($unit, $description, %extra) = @_;
1487 die "missing description
\n" if !defined($description);
1489 my $timeout = delete $extra{timeout};
1492 my $properties = [ [PIDs => [dbus_uint32($$)]] ];
1494 foreach my $key (keys %extra) {
1495 if ($key eq 'Slice' || $key eq 'KillMode') {
1496 push @$properties, [$key, $extra{$key}];
1497 } elsif ($key eq 'CPUShares') {
1498 push @$properties, [$key, dbus_uint64($extra{$key})];
1499 } elsif ($key eq 'CPUQuota') {
1500 push @$properties, ['CPUQuotaPerSecUSec',
1501 dbus_uint64($extra{$key} * 10000)];
1503 die "Don
't know how to encode $key for systemd scope\n";
1510 my $bus = Net::DBus->system();
1511 my $reactor = Net::DBus::Reactor->main();
1513 my $service = $bus->get_service('org
.freedesktop
.systemd1
');
1514 my $if = $service->get_object('/org/freedesktop
/systemd1
', 'org
.freedesktop
.systemd1
.Manager
');
1515 # Connect to the JobRemoved signal since we want to wait for it to finish
1519 my ($no_shutdown) = @_;
1520 $if->disconnect_from_signal('JobRemoved
', $sigid) if defined($if);
1523 $reactor->remove_timeout($timer) if defined($timer);
1525 return if $no_shutdown;
1526 $reactor->shutdown();
1529 $sigid = $if->connect_to_signal('JobRemoved
', sub {
1530 my ($id, $removed_job, $signaled_unit, $result) = @_;
1531 return if $signaled_unit ne $unit || $removed_job ne $job;
1533 die "systemd job failed\n" if $result ne 'done
';
1537 my $on_timeout = sub {
1539 die "systemd job timed out\n";
1542 $timer = $reactor->add_timeout($timeout * 1000, Net::DBus::Callback->new(method => $on_timeout))
1543 if defined($timeout);
1544 $job = $if->StartTransientUnit($unit, 'fail
', $properties, []);
1547 die "systemd job never completed\n" if !$done;
1550 my $salt_starter = time();
1556 my $salt = substr(Digest::SHA::sha1_base64(time() + $salt_starter + $$), 0, 8);
1558 # crypt does not want '+' in salt (see 'man
crypt')
1561 return crypt(encode("utf8", $pw), "\$5\$$salt\$");