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 # NOTE: NFS syscall can't be interrupted, so alarm does
843 # not work to provide timeouts.
844 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
845 # So fork() before using Filesys::Df
847 my ($path, $timeout) = @_;
855 my $pipe = IO
::Pipe-
>new();
857 if (!defined($child)) {
858 warn "fork failed: $!\n";
865 my $df = Filesys
::Df
::df
($path, 1);
866 print {$pipe} "$df->{blocks}\n$df->{used}\n$df->{bavail}\n";
878 my $readvalues = sub {
879 $res->{total
} = int((<$pipe> =~ /^(\d*)$/)[0]);
880 $res->{used
} = int((<$pipe> =~ /^(\d*)$/)[0]);
881 $res->{avail
} = int((<$pipe> =~ /^(\d*)$/)[0]);
884 run_with_timeout
($timeout, $readvalues);
888 kill('KILL', $child);
894 # We use this to uniquely identify a process.
895 # An 'Unique Process ID' has the following format:
896 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
901 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
902 # more that 8 characters for pstart
903 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
904 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
909 my ($upid, $noerr) = @_;
914 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
915 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
916 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]+):$/) {
918 $res->{pid
} = hex($3);
919 $res->{pstart
} = hex($4);
920 $res->{starttime
} = hex($5);
925 my $subdir = substr($5, 7, 8);
926 $filename = "$pvetaskdir/$subdir/$upid";
929 return undef if $noerr;
930 die "unable to parse worker upid '$upid'\n";
933 return wantarray ?
($res, $filename) : $res;
939 my ($task, $filename) = upid_decode
($upid);
941 my $dirname = dirname
($filename);
944 my $wwwid = getpwnam('www-data') ||
945 die "getpwnam failed";
949 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
950 die "unable to create output file '$filename' - $!\n";
951 chown $wwwid, -1, $outfh;
956 sub upid_read_status
{
959 my ($task, $filename) = upid_decode
($upid);
960 my $fh = IO
::File-
>new($filename, "r");
961 return "unable to open file - $!" if !$fh;
963 sysseek($fh, -$maxlen, 2);
965 my $br = sysread($fh, $readbuf, $maxlen);
968 return "unable to extract last line"
969 if $readbuf !~ m/\n?(.+)$/;
971 if ($line =~ m/^TASK OK$/) {
973 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
976 return "unexpected status";
979 return "unable to read tail (got $br bytes)";
982 # useful functions to store comments in config files
986 # all control and hi-bit characters, and ':'
987 my $unsafe = "^\x20-\x39\x3b-\x7e";
988 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
994 return Encode
::decode
("utf8", uri_unescape
($data));
997 # depreciated - do not use!
998 # we now decode all parameters by default
999 sub decode_utf8_parameters
{
1002 foreach my $p (qw(comment description firstname lastname)) {
1003 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
1009 sub random_ether_addr
{
1012 my ($seconds, $microseconds) = gettimeofday
;
1014 my $rand = Digest
::SHA
::sha1
($$, rand(), $seconds, $microseconds);
1016 # clear multicast, set local id
1017 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
1019 my $addr = sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
1020 if (defined($prefix)) {
1021 $addr = uc($prefix) . substr($addr, length($prefix));
1029 return String
::ShellQuote
::shell_quote
($str);
1035 die "no arguments" if !$cmd;
1037 return $cmd if !ref($cmd);
1040 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
1042 return join (' ', @qa);
1045 # split an shell argument string into an array,
1049 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
1053 my ($filename, $start, $limit, $filter) = @_;
1058 my $fh = IO
::File-
>new($filename, "r");
1061 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
1062 return ($count, $lines);
1065 $start = 0 if !$start;
1066 $limit = 50 if !$limit;
1071 # duplicate code, so that we do not slow down normal path
1072 while (defined($line = <$fh>)) {
1073 next if $line !~ m/$filter/;
1074 next if $count++ < $start;
1075 next if $limit <= 0;
1077 push @$lines, { n
=> $count, t
=> $line};
1081 while (defined($line = <$fh>)) {
1082 next if $count++ < $start;
1083 next if $limit <= 0;
1085 push @$lines, { n
=> $count, t
=> $line};
1092 # HACK: ExtJS store.guaranteeRange() does not like empty array
1096 push @$lines, { n
=> $count, t
=> "no content"};
1099 return ($count, $lines);
1103 my ($start, $limit, $since, $until, $service) = @_;
1108 $start = 0 if !$start;
1109 $limit = 50 if !$limit;
1114 return if $count++ < $start;
1115 return if $limit <= 0;
1116 push @$lines, { n
=> int($count), t
=> $line};
1120 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1122 push @$cmd, '--unit', $service if $service;
1123 push @$cmd, '--since', $since if $since;
1124 push @$cmd, '--until', $until if $until;
1125 run_command
($cmd, outfunc
=> $parser);
1127 # HACK: ExtJS store.guaranteeRange() does not like empty array
1131 push @$lines, { n
=> $count, t
=> "no content"};
1134 return ($count, $lines);
1137 sub dir_glob_regex
{
1138 my ($dir, $regex) = @_;
1140 my $dh = IO
::Dir-
>new ($dir);
1141 return wantarray ?
() : undef if !$dh;
1143 while (defined(my $tmp = $dh->read)) {
1144 if (my @res = $tmp =~ m/^($regex)$/) {
1146 return wantarray ?
@res : $tmp;
1151 return wantarray ?
() : undef;
1154 sub dir_glob_foreach
{
1155 my ($dir, $regex, $func) = @_;
1157 my $dh = IO
::Dir-
>new ($dir);
1159 while (defined(my $tmp = $dh->read)) {
1160 if (my @res = $tmp =~ m/^($regex)$/) {
1167 sub assert_if_modified
{
1168 my ($digest1, $digest2) = @_;
1170 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1171 die "detected modified configuration - file changed by other user? Try again.\n";
1175 # Digest for short strings
1176 # like FNV32a, but we only return 31 bits (positive numbers)
1180 my $hval = 0x811c9dc5;
1182 foreach my $c (unpack('C*', $string)) {
1190 $hval = $hval & 0xffffffff;
1192 return $hval & 0x7fffffff;
1195 sub fnv31a_hex
{ return sprintf("%X", fnv31a
(@_)); }
1197 sub unpack_sockaddr_in46
{
1199 my $family = Socket
::sockaddr_family
($sin);
1200 my ($port, $host) = ($family == AF_INET6 ? Socket
::unpack_sockaddr_in6
($sin)
1201 : Socket
::unpack_sockaddr_in
($sin));
1202 return ($family, $port, $host);
1205 sub getaddrinfo_all
{
1206 my ($hostname, @opts) = @_;
1207 my %hints = ( flags
=> AI_V4MAPPED
| AI_ALL
,
1209 my ($err, @res) = Socket
::getaddrinfo
($hostname, '0', \
%hints);
1210 die "failed to get address info for: $hostname: $err\n" if $err;
1214 sub get_host_address_family
{
1215 my ($hostname, $socktype) = @_;
1216 my @res = getaddrinfo_all
($hostname, socktype
=> $socktype);
1217 return $res[0]->{family
};
1220 # get the fully qualified domain name of a host
1221 # same logic as hostname(1): The FQDN is the name getaddrinfo(3) returns,
1222 # given a nodename as a parameter
1224 my ($nodename) = @_;
1227 flags
=> AI_CANONNAME
,
1228 socktype
=> SOCK_DGRAM
1231 my ($err, @addrs) = Socket
::getaddrinfo
($nodename, undef, $hints);
1233 die "getaddrinfo: $err" if $err;
1235 return $addrs[0]->{canonname
};
1238 # Parses any sane kind of host, or host+port pair:
1239 # The port is always optional and thus may be undef.
1240 sub parse_host_and_port
{
1242 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1243 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1244 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1246 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1253 return 0 == syscall(PVE
::Syscall
::unshare
, $flags);
1257 my ($fileno, $nstype) = @_;
1258 return 0 == syscall(PVE
::Syscall
::setns
, $fileno, $nstype);
1263 return 0 == syscall(PVE
::Syscall
::syncfs
, $fileno);
1266 sub sync_mountpoint
{
1268 sysopen my $fd, $path, O_PATH
or die "failed to open $path: $!\n";
1269 my $result = syncfs
(fileno($fd));
1274 # support sending multi-part mail messages with a text and or a HTML part
1275 # mailto may be a single email string or an array of receivers
1277 my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_;
1278 my $mail_re = qr/[^-a-zA-Z0-9+._@]/;
1280 $mailto = [ $mailto ] if !ref($mailto);
1282 foreach (@$mailto) {
1283 die "illegal character in mailto address\n"
1284 if ($_ =~ $mail_re);
1287 my $rcvrtxt = join (', ', @$mailto);
1289 $mailfrom = $mailfrom || "root";
1290 die "illegal character in mailfrom address\n"
1291 if $mailfrom =~ $mail_re;
1293 $author = $author || 'Proxmox VE';
1295 open (MAIL
, "|-", "sendmail", "-B", "8BITMIME", "-f", $mailfrom, @$mailto) ||
1296 die "unable to open 'sendmail' - $!";
1298 # multipart spec see https://www.ietf.org/rfc/rfc1521.txt
1299 my $boundary = "----_=_NextPart_001_".int(time).$$;
1301 print MAIL
"Content-Type: multipart/alternative;\n";
1302 print MAIL
"\tboundary=\"$boundary\"\n";
1303 print MAIL "MIME-Version
: 1.0\n";
1305 print MAIL "FROM
: $author <$mailfrom>\n";
1306 print MAIL "TO
: $rcvrtxt\n";
1307 print MAIL "SUBJECT
: $subject\n";
1309 print MAIL "This
is a multi-part message
in MIME format
.\n\n";
1310 print MAIL "--$boundary\n";
1312 if (defined($text)) {
1313 print MAIL "Content-Type
: text
/plain
;\n";
1314 print MAIL "\tcharset
=\"UTF8
\"\n";
1315 print MAIL "Content-Transfer-Encoding
: 8bit
\n";
1318 # avoid 'remove extra line breaks' issue (MS Outlook)
1320 $text =~ s/^/$fill/gm;
1324 print MAIL "\n--$boundary\n";
1327 if (defined($html)) {
1328 print MAIL "Content-Type
: text
/html
;\n";
1329 print MAIL "\tcharset
=\"UTF8
\"\n";
1330 print MAIL "Content-Transfer-Encoding
: 8bit
\n";
1335 print MAIL "\n--$boundary--\n";
1342 my ($perm, %opts) = @_;
1344 # default permissions are stricter than with file_set_contents
1345 $perm = 0600 if !defined($perm);
1347 my $dir = $opts{dir} // '/run';
1348 my $mode = $opts{mode} // O_RDWR;
1349 $mode |= O_EXCL if !$opts{allow_links};
1351 my $fh = IO::File->new($dir, $mode | O_TMPFILE, $perm);
1352 if (!$fh && $! == EOPNOTSUPP) {
1353 $dir = '/tmp' if !defined($opts{dir});
1354 $dir .= "/.tmpfile
.$$";
1355 $fh = IO::File->new($dir, $mode | O_CREAT | O_EXCL, $perm);
1356 unlink($dir) if $fh;
1358 die "failed to create tempfile
: $!\n" if !$fh;
1362 sub tempfile_contents {
1363 my ($data, $perm, %opts) = @_;
1365 my $fh = tempfile($perm, %opts);
1367 die "unable to
write to tempfile
: $!\n" if !print {$fh} $data;
1368 die "unable to flush to tempfile
: $!\n" if !defined($fh->flush());
1375 return ("/proc/$$/fd/".$fh->fileno, $fh);
1378 sub validate_ssh_public_keys {
1380 my @lines = split(/\n/, $raw);
1382 foreach my $line (@lines) {
1383 next if $line =~ m/^\s*$/;
1385 my ($filename, $handle) = tempfile_contents($line);
1386 run_command(["ssh-keygen
", "-l
", "-f
", $filename],
1387 outfunc => sub {}, errfunc => sub {});
1389 die "SSH public key validation error
\n" if $@;
1394 my ($dirfd, $pathname, $flags, $mode) = @_;
1395 my $fd = syscall(PVE::Syscall::openat, $dirfd, $pathname, $flags, $mode//0);
1396 return undef if $fd < 0;
1397 # sysopen() doesn't deal with numeric file descriptors apparently
1398 # so we need to convert to a mode string for IO::Handle->new_from_fd
1399 my $flagstr = ($flags & O_RDWR) ? 'rw' : ($flags & O_WRONLY) ? 'w' : 'r';
1400 my $handle = IO::Handle->new_from_fd($fd, $flagstr);
1401 return $handle if $handle;
1402 my $err = $!; # save error before closing the raw fd
1403 syscall(PVE::Syscall::close, $fd); # close
1409 my ($dirfd, $name, $mode) = @_;
1410 return syscall(PVE::Syscall::mkdirat, $dirfd, $name, $mode) == 0;
1413 # NOTE: This calls the dbus main loop and must not be used when another dbus
1414 # main loop is being used as we need to wait for the JobRemoved signal.
1415 # Polling the job status instead doesn't work because this doesn't give us the
1416 # distinction between success and failure.
1418 # Note that the description is mandatory for security reasons.
1419 sub enter_systemd_scope {
1420 my ($unit, $description, %extra) = @_;
1421 die "missing description
\n" if !defined($description);
1423 my $timeout = delete $extra{timeout};
1426 my $properties = [ [PIDs => [dbus_uint32($$)]] ];
1428 foreach my $key (keys %extra) {
1429 if ($key eq 'Slice' || $key eq 'KillMode') {
1430 push @$properties, [$key, $extra{$key}];
1431 } elsif ($key eq 'CPUShares') {
1432 push @$properties, [$key, dbus_uint64($extra{$key})];
1433 } elsif ($key eq 'CPUQuota') {
1434 push @$properties, ['CPUQuotaPerSecUSec',
1435 dbus_uint64($extra{$key} * 10000)];
1437 die "Don
't know how to encode $key for systemd scope\n";
1444 my $bus = Net::DBus->system();
1445 my $reactor = Net::DBus::Reactor->main();
1447 my $service = $bus->get_service('org
.freedesktop
.systemd1
');
1448 my $if = $service->get_object('/org/freedesktop
/systemd1
', 'org
.freedesktop
.systemd1
.Manager
');
1449 # Connect to the JobRemoved signal since we want to wait for it to finish
1453 my ($no_shutdown) = @_;
1454 $if->disconnect_from_signal('JobRemoved
', $sigid) if defined($if);
1457 $reactor->remove_timeout($timer) if defined($timer);
1459 return if $no_shutdown;
1460 $reactor->shutdown();
1463 $sigid = $if->connect_to_signal('JobRemoved
', sub {
1464 my ($id, $removed_job, $signaled_unit, $result) = @_;
1465 return if $signaled_unit ne $unit || $removed_job ne $job;
1467 die "systemd job failed\n" if $result ne 'done
';
1471 my $on_timeout = sub {
1473 die "systemd job timed out\n";
1476 $timer = $reactor->add_timeout($timeout * 1000, Net::DBus::Callback->new(method => $on_timeout))
1477 if defined($timeout);
1478 $job = $if->StartTransientUnit($unit, 'fail
', $properties, []);
1481 die "systemd job never completed\n" if !$done;
1484 my $salt_starter = time();
1490 my $salt = substr(Digest::SHA::sha1_base64(time() + $salt_starter + $$), 0, 8);
1492 # crypt does not want '+' in salt (see 'man
crypt')
1495 return crypt(encode("utf8", $pw), "\$5\$$salt\$");