5 use POSIX
qw(EINTR EEXIST EOPNOTSUPP);
7 use Socket
qw(AF_INET AF_INET6 AI_ALL AI_V4MAPPED AI_CANONNAME SOCK_DGRAM);
10 use File
::Path
qw(make_path);
11 use Filesys
::Df
(); # don't overwrite our df()
17 use Fcntl
qw(:DEFAULT :flock);
23 use String
::ShellQuote
;
24 use Time
::HiRes
qw(usleep gettimeofday tv_interval alarm);
25 use Net
::DBus
qw(dbus_uint32 dbus_uint64);
26 use Net
::DBus
::Callback
;
27 use Net
::DBus
::Reactor
;
28 use Scalar
::Util
'weaken';
31 # avoid warning when parsing long hex values with hex()
32 no warnings
'portable'; # Support for 64-bit ints required
55 my $pvelogdir = "/var/log/pve";
56 my $pvetaskdir = "$pvelogdir/tasks";
61 my $IPV4OCTET = "(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])";
62 our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)";
63 my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})";
64 my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))";
67 "(?:(?:" . "(?:$IPV6H16:){6})$IPV6LS32)|" .
68 "(?:(?:" . "::(?:$IPV6H16:){5})$IPV6LS32)|" .
69 "(?:(?:(?:" . "$IPV6H16)?::(?:$IPV6H16:){4})$IPV6LS32)|" .
70 "(?:(?:(?:(?:$IPV6H16:){0,1}$IPV6H16)?::(?:$IPV6H16:){3})$IPV6LS32)|" .
71 "(?:(?:(?:(?:$IPV6H16:){0,2}$IPV6H16)?::(?:$IPV6H16:){2})$IPV6LS32)|" .
72 "(?:(?:(?:(?:$IPV6H16:){0,3}$IPV6H16)?::(?:$IPV6H16:){1})$IPV6LS32)|" .
73 "(?:(?:(?:(?:$IPV6H16:){0,4}$IPV6H16)?::" . ")$IPV6LS32)|" .
74 "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" . ")$IPV6H16)|" .
75 "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" . ")))";
77 our $IPRE = "(?:$IPV4RE|$IPV6RE)";
79 use constant {CLONE_NEWNS
=> 0x00020000,
80 CLONE_NEWUTS
=> 0x04000000,
81 CLONE_NEWIPC
=> 0x08000000,
82 CLONE_NEWUSER
=> 0x10000000,
83 CLONE_NEWPID
=> 0x20000000,
84 CLONE_NEWNET
=> 0x40000000};
86 use constant {O_PATH
=> 0x00200000,
87 O_TMPFILE
=> 0x00410000}; # This includes O_DIRECTORY
89 sub run_with_timeout
{
90 my ($timeout, $code, @param) = @_;
92 die "got timeout\n" if $timeout <= 0;
94 my $prev_alarm = alarm 0; # suspend outer alarm early
101 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
102 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
103 local $SIG{__DIE__
}; # see SA bug 4631
107 eval { $res = &$code(@param); };
109 alarm(0); # avoid race conditions
118 # this shouldn't happen anymore?
119 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
126 # flock: we use one file handle per process, so lock file
127 # can be nested multiple times and succeeds for the same process.
129 # Since this is the only way we lock now and we don't have the old
130 # 'lock(); code(); unlock();' pattern anymore we do not actually need to
131 # count how deep we're nesting. Therefore this hash now stores a weak reference
132 # to a boolean telling us whether we already have a lock.
134 my $lock_handles = {};
137 my ($filename, $timeout, $shared, $code, @param) = @_;
139 $timeout = 10 if !$timeout;
141 my $mode = $shared ? LOCK_SH
: LOCK_EX
;
143 my $lockhash = ($lock_handles->{$$} //= {});
145 # Returns a locked file handle.
146 my $get_locked_file = sub {
147 my $fh = IO
::File-
>new(">>$filename")
148 or die "can't open file - $!\n";
150 if (!flock($fh, $mode|LOCK_NB
)) {
151 print STDERR
"trying to acquire lock...";
154 $success = flock($fh, $mode);
155 # try again on EINTR (see bug #273)
156 if ($success || ($! != EINTR
)) {
161 print STDERR
" failed\n";
162 die "can't acquire lock '$filename' - $!\n";
164 print STDERR
" OK\n";
171 my $checkptr = $lockhash->{$filename};
172 my $check = 0; # This must not go out of scope before running the code.
173 my $local_fh; # This must stay local
174 if (!$checkptr || !$$checkptr) {
175 # We cannot create a weak reference in a single atomic step, so we first
176 # create a false-value, then create a reference to it, then weaken it,
177 # and after successfully locking the file we change the boolean value.
179 # The reason for this is that if an outer SIGALRM throws an exception
180 # between creating the reference and weakening it, a subsequent call to
181 # lock_file_full() will see a leftover full reference to a valid
182 # variable. This variable must be 0 in order for said call to attempt to
183 # lock the file anew.
185 # An externally triggered exception elsewhere in the code will cause the
186 # weak reference to become 'undef', and since the file handle is only
187 # stored in the local scope in $local_fh, the file will be closed by
188 # perl's cleanup routines as well.
190 # This still assumes that an IO::File handle can properly deal with such
191 # exceptions thrown during its own destruction, but that's up to perls
193 $lockhash->{$filename} = \
$check;
194 weaken
$lockhash->{$filename};
195 $local_fh = eval { run_with_timeout
($timeout, $get_locked_file) };
197 $@ = "can't lock file '$filename' - $@";
202 $res = eval { &$code(@param); };
209 my ($filename, $timeout, $code, @param) = @_;
211 return lock_file_full
($filename, $timeout, 0, $code, @param);
214 sub file_set_contents
{
215 my ($filename, $data, $perm) = @_;
217 $perm = 0644 if !defined($perm);
219 my $tmpname = "$filename.tmp.$$";
222 my ($fh, $tries) = (undef, 0);
223 while (!$fh && $tries++ < 3) {
224 $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
|O_EXCL
, $perm);
225 if (!$fh && $! == EEXIST
) {
226 unlink($tmpname) or die "unable to delete old temp file: $!\n";
229 die "unable to open file '$tmpname' - $!\n" if !$fh;
230 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
231 die "closing file '$tmpname' failed - $!\n" unless close $fh;
240 if (!rename($tmpname, $filename)) {
241 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
247 sub file_get_contents
{
248 my ($filename, $max) = @_;
250 my $fh = IO
::File-
>new($filename, "r") ||
251 die "can't open '$filename' - $!\n";
253 my $content = safe_read_from
($fh, $max, 0, $filename);
261 my ($filename, $dst, $max, $perm) = @_;
263 file_set_contents
($dst, file_get_contents
($filename, $max), $perm);
266 sub file_read_firstline
{
269 my $fh = IO
::File-
>new ($filename, "r");
270 return undef if !$fh;
278 my ($fh, $max, $oneline, $filename) = @_;
280 $max = 32768 if !$max;
282 my $subject = defined($filename) ?
"file '$filename'" : 'input';
287 while ($count = sysread($fh, $input, 8192, $br)) {
289 die "$subject too long - aborting\n" if $br > $max;
290 if ($oneline && $input =~ m/^(.*)\n/) {
295 die "unable to read $subject - $!\n" if !defined($count);
300 # The $cmd parameter can be:
302 # This is generally executed by passing it to the shell with the -c option.
303 # However, it can be executed in one of two ways, depending on whether
304 # there's a pipe involved:
305 # *) with pipe: passed explicitly to bash -c, prefixed with:
307 # *) without a pipe: passed to perl's open3 which uses 'sh -c'
308 # (Note that this may result in two different syntax requirements!)
310 # -) an array of arguments (strings)
311 # Will be executed without interference from a shell. (Parameters are passed
312 # as is, no escape sequences of strings will be touched.)
313 # -) an array of arrays
314 # Each array represents a command, and each command's output is piped into
315 # the following command's standard input.
316 # For this a shell command string is created with pipe symbols between each
318 # Each command is a list of strings meant to end up in the final command
319 # unchanged. In order to achieve this, every argument is shell-quoted.
320 # Quoting can be disabled for a particular argument by turning it into a
321 # reference, this allows inserting arbitrary shell options.
322 # For instance: the $cmd [ [ 'echo', 'hello', \'>/dev/null' ] ] will not
323 # produce any output, while the $cmd [ [ 'echo', 'hello', '>/dev/null' ] ]
324 # will literally print: hello >/dev/null
326 my ($cmd, %param) = @_;
331 if (my $ref = ref($cmd)) {
332 if (ref($cmd->[0])) {
333 $cmdstr = 'set -o pipefail && ';
335 foreach my $command (@$cmd) {
336 # concatenate quoted parameters
337 # strings which are passed by reference are NOT shell quoted
338 $cmdstr .= $pipe . join(' ', map { ref($_) ?
$$_ : shellquote
($_) } @$command);
341 $cmd = [ '/bin/bash', '-c', "$cmdstr" ];
343 $cmdstr = cmd2string
($cmd);
348 # see 'man bash' for option pipefail
349 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
373 foreach my $p (keys %param) {
374 if ($p eq 'timeout') {
375 $timeout = $param{$p};
376 } elsif ($p eq 'umask') {
377 $old_umask = umask($param{$p});
378 } elsif ($p eq 'errmsg') {
379 $errmsg = $param{$p};
380 } elsif ($p eq 'input') {
382 } elsif ($p eq 'output') {
383 $output = $param{$p};
384 } elsif ($p eq 'outfunc') {
385 $outfunc = $param{$p};
386 } elsif ($p eq 'errfunc') {
387 $errfunc = $param{$p};
388 } elsif ($p eq 'logfunc') {
389 $logfunc = $param{$p};
390 } elsif ($p eq 'afterfork') {
391 $afterfork = $param{$p};
392 } elsif ($p eq 'noerr') {
394 } elsif ($p eq 'keeplocale') {
395 $keeplocale = $param{$p};
397 die "got unknown parameter '$p' for run_command\n";
402 my $origerrfunc = $errfunc;
406 &$origerrfunc("$laststderr\n");
408 print STDERR
"$laststderr\n" if $laststderr;
415 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
416 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
417 my $error = IO
::File-
>new();
422 local $ENV{LC_ALL
} = 'C' if !$keeplocale;
424 # suppress LVM warnings like: "File descriptor 3 left open";
425 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
427 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
429 # if we pipe fron STDIN, open3 closes STDIN, so we we
430 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
431 # as soon as we open a new file.
432 # to avoid that we open /dev/null
433 if (!ref($writer) && !defined(fileno(STDIN
))) {
435 open(STDIN
, "</dev/null");
442 if ($orig_pid != $$) {
450 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
451 $oldtimeout = alarm($timeout) if $timeout;
453 &$afterfork() if $afterfork;
456 print $writer $input if defined $input;
460 my $select = new IO
::Select
;
461 $select->add($reader) if ref($reader);
462 $select->add($error);
467 my $starttime = time();
469 while ($select->count) {
470 my @handles = $select->can_read(1);
472 foreach my $h (@handles) {
474 my $count = sysread ($h, $buf, 4096);
475 if (!defined ($count)) {
481 $select->remove ($h) if !$count;
483 if ($outfunc || $logfunc) {
486 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
488 &$outfunc($line) if $outfunc;
489 &$logfunc($line) if $logfunc;
502 } elsif ($h eq $error) {
503 if ($errfunc || $logfunc) {
506 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
508 &$errfunc($line) if $errfunc;
509 &$logfunc($line) if $logfunc;
526 &$outfunc($outlog) if $outfunc && $outlog;
527 &$logfunc($outlog) if $logfunc && $outlog;
529 &$errfunc($errlog) if $errfunc && $errlog;
530 &$logfunc($errlog) if $logfunc && $errlog;
535 die "failed to execute\n";
536 } elsif (my $sig = ($? & 127)) {
537 die "got signal $sig\n";
538 } elsif ($exitcode = ($? >> 8)) {
539 if (!($exitcode == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
540 if ($errmsg && $laststderr) {
541 my $lerr = $laststderr;
545 die "exit code $exitcode\n";
556 if ($errmsg && $laststderr) {
557 &$errfunc(undef); # flush laststderr
560 umask ($old_umask) if defined($old_umask);
562 alarm($oldtimeout) if $oldtimeout;
565 if ($pid && ($err eq "got timeout\n")) {
568 die "command '$cmdstr' failed: $err";
572 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
575 die "command '$cmdstr' failed: $err";
583 my $listtxt = shift || '';
585 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
587 $listtxt =~ s/[,;]/ /g;
588 $listtxt =~ s/^\s+//;
590 my @data = split (/\s+/, $listtxt);
598 return $txt if !defined($txt);
606 # simple uri templates like "/vms/{vmid}"
607 sub template_replace
{
608 my ($tmpl, $data) = @_;
610 return $tmpl if !$tmpl;
613 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
615 $res .= ($data->{$3} || '-') if $2;
621 my ($filename, $fh, $data) = @_;
625 my $res = print $fh $data;
627 die "write to '$filename' failed\n" if !$res;
633 'at' => 'ftp.at.debian.org',
634 'au' => 'ftp.au.debian.org',
635 'be' => 'ftp.be.debian.org',
636 'bg' => 'ftp.bg.debian.org',
637 'br' => 'ftp.br.debian.org',
638 'ca' => 'ftp.ca.debian.org',
639 'ch' => 'ftp.ch.debian.org',
640 'cl' => 'ftp.cl.debian.org',
641 'cz' => 'ftp.cz.debian.org',
642 'de' => 'ftp.de.debian.org',
643 'dk' => 'ftp.dk.debian.org',
644 'ee' => 'ftp.ee.debian.org',
645 'es' => 'ftp.es.debian.org',
646 'fi' => 'ftp.fi.debian.org',
647 'fr' => 'ftp.fr.debian.org',
648 'gr' => 'ftp.gr.debian.org',
649 'hk' => 'ftp.hk.debian.org',
650 'hr' => 'ftp.hr.debian.org',
651 'hu' => 'ftp.hu.debian.org',
652 'ie' => 'ftp.ie.debian.org',
653 'is' => 'ftp.is.debian.org',
654 'it' => 'ftp.it.debian.org',
655 'jp' => 'ftp.jp.debian.org',
656 'kr' => 'ftp.kr.debian.org',
657 'mx' => 'ftp.mx.debian.org',
658 'nl' => 'ftp.nl.debian.org',
659 'no' => 'ftp.no.debian.org',
660 'nz' => 'ftp.nz.debian.org',
661 'pl' => 'ftp.pl.debian.org',
662 'pt' => 'ftp.pt.debian.org',
663 'ro' => 'ftp.ro.debian.org',
664 'ru' => 'ftp.ru.debian.org',
665 'se' => 'ftp.se.debian.org',
666 'si' => 'ftp.si.debian.org',
667 'sk' => 'ftp.sk.debian.org',
668 'tr' => 'ftp.tr.debian.org',
669 'tw' => 'ftp.tw.debian.org',
670 'gb' => 'ftp.uk.debian.org',
671 'us' => 'ftp.us.debian.org',
676 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
677 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
678 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
679 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
680 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
681 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
682 #'et' => [], # Ethopia or Estonia ??
683 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
684 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
685 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
686 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
687 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
688 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
689 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
690 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
691 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
692 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
693 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
694 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
695 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
696 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
697 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
698 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
699 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
700 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
701 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
702 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
703 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
704 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
705 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
707 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
710 my $kvmkeymaparray = [];
711 foreach my $lc (sort keys %$keymaphash) {
712 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
720 return $kvmkeymaparray;
724 my ($param, $key) = @_;
726 my $res = $param->{$key};
727 delete $param->{$key};
732 # Note: we use this to wait until vncterm/spiceterm is ready
733 sub wait_for_vnc_port
{
734 my ($port, $timeout) = @_;
736 $timeout = 5 if !$timeout;
738 my $starttime = [gettimeofday
];
741 while (($elapsed = tv_interval
($starttime)) < $timeout) {
742 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
743 while (defined (my $line = <$fh>)) {
744 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
745 if ($port == hex($2)) {
753 $sleeptime += 100000 if $sleeptime < 1000000;
760 sub next_unused_port
{
761 my ($range_start, $range_end, $family, $address) = @_;
763 # We use a file to register allocated ports.
764 # Those registrations expires after $expiretime.
765 # We use this to avoid race conditions between
766 # allocation and use of ports.
768 my $filename = "/var/tmp/pve-reserved-ports";
777 if (my $fh = IO
::File-
>new ($filename, "r")) {
778 while (my $line = <$fh>) {
779 if ($line =~ m/^(\d+)\s(\d+)$/) {
780 my ($port, $timestamp) = ($1, $2);
781 if (($timestamp + $expiretime) > $ctime) {
782 $ports->{$port} = $timestamp; # not expired
789 my %sockargs = (Listen
=> 5,
793 GetAddrInfoFlags
=> 0);
794 $sockargs{LocalAddr
} = $address if defined($address);
796 for (my $p = $range_start; $p < $range_end; $p++) {
797 next if $ports->{$p}; # reserved
799 $sockargs{LocalPort
} = $p;
800 my $sock = IO
::Socket
::IP-
>new(%sockargs);
805 $ports->{$p} = $ctime;
811 foreach my $p (keys %$ports) {
812 $data .= "$p $ports->{$p}\n";
815 file_set_contents
($filename, $data);
820 my $p = lock_file
('/var/lock/pve-ports.lck', 10, $code);
823 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
828 sub next_migrate_port
{
829 my ($family, $address) = @_;
830 return next_unused_port
(60000, 60050, $family, $address);
834 my ($family, $address) = @_;
835 return next_unused_port
(5900, 6000, $family, $address);
838 sub next_spice_port
{
839 my ($family, $address) = @_;
840 return next_unused_port
(61000, 61099, $family, $address);
843 # NOTE: NFS syscall can't be interrupted, so alarm does
844 # not work to provide timeouts.
845 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
846 # So fork() before using Filesys::Df
848 my ($path, $timeout) = @_;
856 my $pipe = IO
::Pipe-
>new();
858 if (!defined($child)) {
859 warn "fork failed: $!\n";
866 my $df = Filesys
::Df
::df
($path, 1);
867 print {$pipe} "$df->{blocks}\n$df->{used}\n$df->{bavail}\n";
879 my $readvalues = sub {
880 $res->{total
} = int((<$pipe> =~ /^(\d*)$/)[0]);
881 $res->{used
} = int((<$pipe> =~ /^(\d*)$/)[0]);
882 $res->{avail
} = int((<$pipe> =~ /^(\d*)$/)[0]);
885 run_with_timeout
($timeout, $readvalues);
889 kill('KILL', $child);
895 # We use this to uniquely identify a process.
896 # An 'Unique Process ID' has the following format:
897 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
902 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
903 # more that 8 characters for pstart
904 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
905 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
910 my ($upid, $noerr) = @_;
915 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
916 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
917 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]+):$/) {
919 $res->{pid
} = hex($3);
920 $res->{pstart
} = hex($4);
921 $res->{starttime
} = hex($5);
926 my $subdir = substr($5, 7, 8);
927 $filename = "$pvetaskdir/$subdir/$upid";
930 return undef if $noerr;
931 die "unable to parse worker upid '$upid'\n";
934 return wantarray ?
($res, $filename) : $res;
940 my ($task, $filename) = upid_decode
($upid);
942 my $dirname = dirname
($filename);
945 my $wwwid = getpwnam('www-data') ||
946 die "getpwnam failed";
950 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
951 die "unable to create output file '$filename' - $!\n";
952 chown $wwwid, -1, $outfh;
957 sub upid_read_status
{
960 my ($task, $filename) = upid_decode
($upid);
961 my $fh = IO
::File-
>new($filename, "r");
962 return "unable to open file - $!" if !$fh;
964 sysseek($fh, -$maxlen, 2);
966 my $br = sysread($fh, $readbuf, $maxlen);
969 return "unable to extract last line"
970 if $readbuf !~ m/\n?(.+)$/;
972 if ($line =~ m/^TASK OK$/) {
974 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
977 return "unexpected status";
980 return "unable to read tail (got $br bytes)";
983 # useful functions to store comments in config files
987 # all control and hi-bit characters, and ':'
988 my $unsafe = "^\x20-\x39\x3b-\x7e";
989 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
995 return Encode
::decode
("utf8", uri_unescape
($data));
998 # depreciated - do not use!
999 # we now decode all parameters by default
1000 sub decode_utf8_parameters
{
1003 foreach my $p (qw(comment description firstname lastname)) {
1004 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
1010 sub random_ether_addr
{
1013 my ($seconds, $microseconds) = gettimeofday
;
1015 my $rand = Digest
::SHA
::sha1
($$, rand(), $seconds, $microseconds);
1017 # clear multicast, set local id
1018 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
1020 my $addr = sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
1021 if (defined($prefix)) {
1022 $addr = uc($prefix) . substr($addr, length($prefix));
1030 return String
::ShellQuote
::shell_quote
($str);
1036 die "no arguments" if !$cmd;
1038 return $cmd if !ref($cmd);
1041 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
1043 return join (' ', @qa);
1046 # split an shell argument string into an array,
1050 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
1054 my ($filename, $start, $limit, $filter) = @_;
1059 my $fh = IO
::File-
>new($filename, "r");
1062 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
1063 return ($count, $lines);
1066 $start = 0 if !$start;
1067 $limit = 50 if !$limit;
1072 # duplicate code, so that we do not slow down normal path
1073 while (defined($line = <$fh>)) {
1074 next if $line !~ m/$filter/;
1075 next if $count++ < $start;
1076 next if $limit <= 0;
1078 push @$lines, { n
=> $count, t
=> $line};
1082 while (defined($line = <$fh>)) {
1083 next if $count++ < $start;
1084 next if $limit <= 0;
1086 push @$lines, { n
=> $count, t
=> $line};
1093 # HACK: ExtJS store.guaranteeRange() does not like empty array
1097 push @$lines, { n
=> $count, t
=> "no content"};
1100 return ($count, $lines);
1104 my ($start, $limit, $since, $until, $service) = @_;
1109 $start = 0 if !$start;
1110 $limit = 50 if !$limit;
1115 return if $count++ < $start;
1116 return if $limit <= 0;
1117 push @$lines, { n
=> int($count), t
=> $line};
1121 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1123 push @$cmd, '--unit', $service if $service;
1124 push @$cmd, '--since', $since if $since;
1125 push @$cmd, '--until', $until if $until;
1126 run_command
($cmd, outfunc
=> $parser);
1128 # HACK: ExtJS store.guaranteeRange() does not like empty array
1132 push @$lines, { n
=> $count, t
=> "no content"};
1135 return ($count, $lines);
1138 sub dir_glob_regex
{
1139 my ($dir, $regex) = @_;
1141 my $dh = IO
::Dir-
>new ($dir);
1142 return wantarray ?
() : undef if !$dh;
1144 while (defined(my $tmp = $dh->read)) {
1145 if (my @res = $tmp =~ m/^($regex)$/) {
1147 return wantarray ?
@res : $tmp;
1152 return wantarray ?
() : undef;
1155 sub dir_glob_foreach
{
1156 my ($dir, $regex, $func) = @_;
1158 my $dh = IO
::Dir-
>new ($dir);
1160 while (defined(my $tmp = $dh->read)) {
1161 if (my @res = $tmp =~ m/^($regex)$/) {
1168 sub assert_if_modified
{
1169 my ($digest1, $digest2) = @_;
1171 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1172 die "detected modified configuration - file changed by other user? Try again.\n";
1176 # Digest for short strings
1177 # like FNV32a, but we only return 31 bits (positive numbers)
1181 my $hval = 0x811c9dc5;
1183 foreach my $c (unpack('C*', $string)) {
1191 $hval = $hval & 0xffffffff;
1193 return $hval & 0x7fffffff;
1196 sub fnv31a_hex
{ return sprintf("%X", fnv31a
(@_)); }
1198 sub unpack_sockaddr_in46
{
1200 my $family = Socket
::sockaddr_family
($sin);
1201 my ($port, $host) = ($family == AF_INET6 ? Socket
::unpack_sockaddr_in6
($sin)
1202 : Socket
::unpack_sockaddr_in
($sin));
1203 return ($family, $port, $host);
1206 sub getaddrinfo_all
{
1207 my ($hostname, @opts) = @_;
1208 my %hints = ( flags
=> AI_V4MAPPED
| AI_ALL
,
1210 my ($err, @res) = Socket
::getaddrinfo
($hostname, '0', \
%hints);
1211 die "failed to get address info for: $hostname: $err\n" if $err;
1215 sub get_host_address_family
{
1216 my ($hostname, $socktype) = @_;
1217 my @res = getaddrinfo_all
($hostname, socktype
=> $socktype);
1218 return $res[0]->{family
};
1221 # get the fully qualified domain name of a host
1222 # same logic as hostname(1): The FQDN is the name getaddrinfo(3) returns,
1223 # given a nodename as a parameter
1225 my ($nodename) = @_;
1228 flags
=> AI_CANONNAME
,
1229 socktype
=> SOCK_DGRAM
1232 my ($err, @addrs) = Socket
::getaddrinfo
($nodename, undef, $hints);
1234 die "getaddrinfo: $err" if $err;
1236 return $addrs[0]->{canonname
};
1239 # Parses any sane kind of host, or host+port pair:
1240 # The port is always optional and thus may be undef.
1241 sub parse_host_and_port
{
1243 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1244 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1245 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1247 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1254 return 0 == syscall(PVE
::Syscall
::unshare
, $flags);
1258 my ($fileno, $nstype) = @_;
1259 return 0 == syscall(PVE
::Syscall
::setns
, $fileno, $nstype);
1264 return 0 == syscall(PVE
::Syscall
::syncfs
, $fileno);
1267 sub sync_mountpoint
{
1269 sysopen my $fd, $path, O_PATH
or die "failed to open $path: $!\n";
1270 my $result = syncfs
(fileno($fd));
1275 # support sending multi-part mail messages with a text and or a HTML part
1276 # mailto may be a single email string or an array of receivers
1278 my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_;
1279 my $mail_re = qr/[^-a-zA-Z0-9+._@]/;
1281 $mailto = [ $mailto ] if !ref($mailto);
1283 foreach (@$mailto) {
1284 die "illegal character in mailto address\n"
1285 if ($_ =~ $mail_re);
1288 my $rcvrtxt = join (', ', @$mailto);
1290 $mailfrom = $mailfrom || "root";
1291 die "illegal character in mailfrom address\n"
1292 if $mailfrom =~ $mail_re;
1294 $author = $author || 'Proxmox VE';
1296 open (MAIL
, "|-", "sendmail", "-B", "8BITMIME", "-f", $mailfrom, @$mailto) ||
1297 die "unable to open 'sendmail' - $!";
1299 # multipart spec see https://www.ietf.org/rfc/rfc1521.txt
1300 my $boundary = "----_=_NextPart_001_".int(time).$$;
1302 print MAIL
"Content-Type: multipart/alternative;\n";
1303 print MAIL
"\tboundary=\"$boundary\"\n";
1304 print MAIL "MIME-Version
: 1.0\n";
1306 print MAIL "FROM
: $author <$mailfrom>\n";
1307 print MAIL "TO
: $rcvrtxt\n";
1308 print MAIL "SUBJECT
: $subject\n";
1310 print MAIL "This
is a multi-part message
in MIME format
.\n\n";
1311 print MAIL "--$boundary\n";
1313 if (defined($text)) {
1314 print MAIL "Content-Type
: text
/plain
;\n";
1315 print MAIL "\tcharset
=\"UTF8
\"\n";
1316 print MAIL "Content-Transfer-Encoding
: 8bit
\n";
1319 # avoid 'remove extra line breaks' issue (MS Outlook)
1321 $text =~ s/^/$fill/gm;
1325 print MAIL "\n--$boundary\n";
1328 if (defined($html)) {
1329 print MAIL "Content-Type
: text
/html
;\n";
1330 print MAIL "\tcharset
=\"UTF8
\"\n";
1331 print MAIL "Content-Transfer-Encoding
: 8bit
\n";
1336 print MAIL "\n--$boundary--\n";
1343 my ($perm, %opts) = @_;
1345 # default permissions are stricter than with file_set_contents
1346 $perm = 0600 if !defined($perm);
1348 my $dir = $opts{dir} // '/run';
1349 my $mode = $opts{mode} // O_RDWR;
1350 $mode |= O_EXCL if !$opts{allow_links};
1352 my $fh = IO::File->new($dir, $mode | O_TMPFILE, $perm);
1353 if (!$fh && $! == EOPNOTSUPP) {
1354 $dir = '/tmp' if !defined($opts{dir});
1355 $dir .= "/.tmpfile
.$$";
1356 $fh = IO::File->new($dir, $mode | O_CREAT | O_EXCL, $perm);
1357 unlink($dir) if $fh;
1359 die "failed to create tempfile
: $!\n" if !$fh;
1363 sub tempfile_contents {
1364 my ($data, $perm, %opts) = @_;
1366 my $fh = tempfile($perm, %opts);
1368 die "unable to
write to tempfile
: $!\n" if !print {$fh} $data;
1369 die "unable to flush to tempfile
: $!\n" if !defined($fh->flush());
1376 return ("/proc/$$/fd/".$fh->fileno, $fh);
1379 sub validate_ssh_public_keys {
1381 my @lines = split(/\n/, $raw);
1383 foreach my $line (@lines) {
1384 next if $line =~ m/^\s*$/;
1386 my ($filename, $handle) = tempfile_contents($line);
1387 run_command(["ssh-keygen
", "-l
", "-f
", $filename],
1388 outfunc => sub {}, errfunc => sub {});
1390 die "SSH public key validation error
\n" if $@;
1395 my ($dirfd, $pathname, $flags, $mode) = @_;
1396 my $fd = syscall(PVE::Syscall::openat, $dirfd, $pathname, $flags, $mode//0);
1397 return undef if $fd < 0;
1398 # sysopen() doesn't deal with numeric file descriptors apparently
1399 # so we need to convert to a mode string for IO::Handle->new_from_fd
1400 my $flagstr = ($flags & O_RDWR) ? 'rw' : ($flags & O_WRONLY) ? 'w' : 'r';
1401 my $handle = IO::Handle->new_from_fd($fd, $flagstr);
1402 return $handle if $handle;
1403 my $err = $!; # save error before closing the raw fd
1404 syscall(PVE::Syscall::close, $fd); # close
1410 my ($dirfd, $name, $mode) = @_;
1411 return syscall(PVE::Syscall::mkdirat, $dirfd, $name, $mode) == 0;
1414 # NOTE: This calls the dbus main loop and must not be used when another dbus
1415 # main loop is being used as we need to wait for the JobRemoved signal.
1416 # Polling the job status instead doesn't work because this doesn't give us the
1417 # distinction between success and failure.
1419 # Note that the description is mandatory for security reasons.
1420 sub enter_systemd_scope {
1421 my ($unit, $description, %extra) = @_;
1422 die "missing description
\n" if !defined($description);
1424 my $timeout = delete $extra{timeout};
1427 my $properties = [ [PIDs => [dbus_uint32($$)]] ];
1429 foreach my $key (keys %extra) {
1430 if ($key eq 'Slice' || $key eq 'KillMode') {
1431 push @$properties, [$key, $extra{$key}];
1432 } elsif ($key eq 'CPUShares') {
1433 push @$properties, [$key, dbus_uint64($extra{$key})];
1434 } elsif ($key eq 'CPUQuota') {
1435 push @$properties, ['CPUQuotaPerSecUSec',
1436 dbus_uint64($extra{$key} * 10000)];
1438 die "Don
't know how to encode $key for systemd scope\n";
1445 my $bus = Net::DBus->system();
1446 my $reactor = Net::DBus::Reactor->main();
1448 my $service = $bus->get_service('org
.freedesktop
.systemd1
');
1449 my $if = $service->get_object('/org/freedesktop
/systemd1
', 'org
.freedesktop
.systemd1
.Manager
');
1450 # Connect to the JobRemoved signal since we want to wait for it to finish
1454 my ($no_shutdown) = @_;
1455 $if->disconnect_from_signal('JobRemoved
', $sigid) if defined($if);
1458 $reactor->remove_timeout($timer) if defined($timer);
1460 return if $no_shutdown;
1461 $reactor->shutdown();
1464 $sigid = $if->connect_to_signal('JobRemoved
', sub {
1465 my ($id, $removed_job, $signaled_unit, $result) = @_;
1466 return if $signaled_unit ne $unit || $removed_job ne $job;
1468 die "systemd job failed\n" if $result ne 'done
';
1472 my $on_timeout = sub {
1474 die "systemd job timed out\n";
1477 $timer = $reactor->add_timeout($timeout * 1000, Net::DBus::Callback->new(method => $on_timeout))
1478 if defined($timeout);
1479 $job = $if->StartTransientUnit($unit, 'fail
', $properties, []);
1482 die "systemd job never completed\n" if !$done;
1485 my $salt_starter = time();
1491 my $salt = substr(Digest::SHA::sha1_base64(time() + $salt_starter + $$), 0, 8);
1493 # crypt does not want '+' in salt (see 'man
crypt')
1496 return crypt(encode("utf8", $pw), "\$5\$$salt\$");