7 use Socket
qw(AF_INET AF_INET6 AI_ALL AI_V4MAPPED);
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
;
29 # avoid warning when parsing long hex values with hex()
30 no warnings
'portable'; # Support for 64-bit ints required
53 my $pvelogdir = "/var/log/pve";
54 my $pvetaskdir = "$pvelogdir/tasks";
59 my $IPV4OCTET = "(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])";
60 our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)";
61 my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})";
62 my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))";
65 "(?:(?:" . "(?:$IPV6H16:){6})$IPV6LS32)|" .
66 "(?:(?:" . "::(?:$IPV6H16:){5})$IPV6LS32)|" .
67 "(?:(?:(?:" . "$IPV6H16)?::(?:$IPV6H16:){4})$IPV6LS32)|" .
68 "(?:(?:(?:(?:$IPV6H16:){0,1}$IPV6H16)?::(?:$IPV6H16:){3})$IPV6LS32)|" .
69 "(?:(?:(?:(?:$IPV6H16:){0,2}$IPV6H16)?::(?:$IPV6H16:){2})$IPV6LS32)|" .
70 "(?:(?:(?:(?:$IPV6H16:){0,3}$IPV6H16)?::(?:$IPV6H16:){1})$IPV6LS32)|" .
71 "(?:(?:(?:(?:$IPV6H16:){0,4}$IPV6H16)?::" . ")$IPV6LS32)|" .
72 "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" . ")$IPV6H16)|" .
73 "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" . ")))";
75 our $IPRE = "(?:$IPV4RE|$IPV6RE)";
77 use constant {CLONE_NEWNS
=> 0x00020000,
78 CLONE_NEWUTS
=> 0x04000000,
79 CLONE_NEWIPC
=> 0x08000000,
80 CLONE_NEWUSER
=> 0x10000000,
81 CLONE_NEWPID
=> 0x20000000,
82 CLONE_NEWNET
=> 0x40000000};
84 use constant {O_PATH
=> 0x00200000,
85 O_TMPFILE
=> 0x00410000}; # This includes O_DIRECTORY
87 sub run_with_timeout
{
88 my ($timeout, $code, @param) = @_;
90 die "got timeout\n" if $timeout <= 0;
92 my $prev_alarm = alarm 0; # suspend outer alarm early
99 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
100 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
101 local $SIG{__DIE__
}; # see SA bug 4631
105 eval { $res = &$code(@param); };
107 alarm(0); # avoid race conditions
116 # this shouldn't happen anymore?
117 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
124 # flock: we use one file handle per process, so lock file
125 # can be called multiple times and succeeds for the same process.
127 my $lock_handles = {};
130 my ($filename, $timeout, $shared, $code, @param) = @_;
132 $timeout = 10 if !$timeout;
134 my $mode = $shared ? LOCK_SH
: LOCK_EX
;
136 my $lock_func = sub {
137 if (!$lock_handles->{$$}->{$filename}) {
138 my $fh = new IO
::File
(">>$filename") ||
139 die "can't open file - $!\n";
140 $lock_handles->{$$}->{$filename} = { fh
=> $fh, refcount
=> 0};
143 if (!flock($lock_handles->{$$}->{$filename}->{fh
}, $mode|LOCK_NB
)) {
144 print STDERR
"trying to acquire lock...";
147 $success = flock($lock_handles->{$$}->{$filename}->{fh
}, $mode);
148 # try again on EINTR (see bug #273)
149 if ($success || ($! != EINTR
)) {
154 print STDERR
" failed\n";
155 die "can't acquire lock '$filename' - $!\n";
157 print STDERR
" OK\n";
159 $lock_handles->{$$}->{$filename}->{refcount
}++;
164 eval { run_with_timeout
($timeout, $lock_func); };
167 $err = "can't lock file '$filename' - $err";
169 eval { $res = &$code(@param) };
173 if (my $fh = $lock_handles->{$$}->{$filename}->{fh
}) {
174 my $refcount = --$lock_handles->{$$}->{$filename}->{refcount
};
175 if ($refcount <= 0) {
176 $lock_handles->{$$}->{$filename} = undef;
193 my ($filename, $timeout, $code, @param) = @_;
195 return lock_file_full
($filename, $timeout, 0, $code, @param);
198 sub file_set_contents
{
199 my ($filename, $data, $perm) = @_;
201 $perm = 0644 if !defined($perm);
203 my $tmpname = "$filename.tmp.$$";
206 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
207 die "unable to open file '$tmpname' - $!\n" if !$fh;
208 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
209 die "closing file '$tmpname' failed - $!\n" unless close $fh;
218 if (!rename($tmpname, $filename)) {
219 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
225 sub file_get_contents
{
226 my ($filename, $max) = @_;
228 my $fh = IO
::File-
>new($filename, "r") ||
229 die "can't open '$filename' - $!\n";
231 my $content = safe_read_from
($fh, $max);
239 my ($filename, $dst, $max, $perm) = @_;
241 file_set_contents
($dst, file_get_contents
($filename, $max), $perm);
244 sub file_read_firstline
{
247 my $fh = IO
::File-
>new ($filename, "r");
248 return undef if !$fh;
256 my ($fh, $max, $oneline) = @_;
258 $max = 32768 if !$max;
263 while ($count = sysread($fh, $input, 8192, $br)) {
265 die "input too long - aborting\n" if $br > $max;
266 if ($oneline && $input =~ m/^(.*)\n/) {
271 die "unable to read input - $!\n" if !defined($count);
276 # The $cmd parameter can be:
278 # This is generally executed by passing it to the shell with the -c option.
279 # However, it can be executed in one of two ways, depending on whether
280 # there's a pipe involved:
281 # *) with pipe: passed explicitly to bash -c, prefixed with:
283 # *) without a pipe: passed to perl's open3 which uses 'sh -c'
284 # (Note that this may result in two different syntax requirements!)
286 # -) an array of arguments (strings)
287 # Will be executed without interference from a shell. (Parameters are passed
288 # as is, no escape sequences of strings will be touched.)
289 # -) an array of arrays
290 # Each array represents a command, and each command's output is piped into
291 # the following command's standard input.
292 # For this a shell command string is created with pipe symbols between each
294 # Each command is a list of strings meant to end up in the final command
295 # unchanged. In order to achieve this, every argument is shell-quoted.
296 # Quoting can be disabled for a particular argument by turning it into a
297 # reference, this allows inserting arbitrary shell options.
298 # For instance: the $cmd [ [ 'echo', 'hello', \'>/dev/null' ] ] will not
299 # produce any output, while the $cmd [ [ 'echo', 'hello', '>/dev/null' ] ]
300 # will literally print: hello >/dev/null
302 my ($cmd, %param) = @_;
307 if (my $ref = ref($cmd)) {
308 if (ref($cmd->[0])) {
309 $cmdstr = 'set -o pipefail && ';
311 foreach my $command (@$cmd) {
312 # concatenate quoted parameters
313 # strings which are passed by reference are NOT shell quoted
314 $cmdstr .= $pipe . join(' ', map { ref($_) ?
$$_ : shellquote
($_) } @$command);
317 $cmd = [ '/bin/bash', '-c', "$cmdstr" ];
319 $cmdstr = cmd2string
($cmd);
324 # see 'man bash' for option pipefail
325 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
348 foreach my $p (keys %param) {
349 if ($p eq 'timeout') {
350 $timeout = $param{$p};
351 } elsif ($p eq 'umask') {
352 $old_umask = umask($param{$p});
353 } elsif ($p eq 'errmsg') {
354 $errmsg = $param{$p};
355 } elsif ($p eq 'input') {
357 } elsif ($p eq 'output') {
358 $output = $param{$p};
359 } elsif ($p eq 'outfunc') {
360 $outfunc = $param{$p};
361 } elsif ($p eq 'errfunc') {
362 $errfunc = $param{$p};
363 } elsif ($p eq 'logfunc') {
364 $logfunc = $param{$p};
365 } elsif ($p eq 'afterfork') {
366 $afterfork = $param{$p};
367 } elsif ($p eq 'noerr') {
370 die "got unknown parameter '$p' for run_command\n";
375 my $origerrfunc = $errfunc;
379 &$origerrfunc("$laststderr\n");
381 print STDERR
"$laststderr\n" if $laststderr;
388 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
389 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
390 my $error = IO
::File-
>new();
392 # try to avoid locale related issues/warnings
393 my $lang = $param{lang
} || 'C';
398 local $ENV{LC_ALL
} = $lang;
400 # suppress LVM warnings like: "File descriptor 3 left open";
401 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
403 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
405 # if we pipe fron STDIN, open3 closes STDIN, so we we
406 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
407 # as soon as we open a new file.
408 # to avoid that we open /dev/null
409 if (!ref($writer) && !defined(fileno(STDIN
))) {
411 open(STDIN
, "</dev/null");
418 if ($orig_pid != $$) {
426 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
427 $oldtimeout = alarm($timeout) if $timeout;
429 &$afterfork() if $afterfork;
432 print $writer $input if defined $input;
436 my $select = new IO
::Select
;
437 $select->add($reader) if ref($reader);
438 $select->add($error);
443 my $starttime = time();
445 while ($select->count) {
446 my @handles = $select->can_read(1);
448 foreach my $h (@handles) {
450 my $count = sysread ($h, $buf, 4096);
451 if (!defined ($count)) {
457 $select->remove ($h) if !$count;
459 if ($outfunc || $logfunc) {
462 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
464 &$outfunc($line) if $outfunc;
465 &$logfunc($line) if $logfunc;
478 } elsif ($h eq $error) {
479 if ($errfunc || $logfunc) {
482 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
484 &$errfunc($line) if $errfunc;
485 &$logfunc($line) if $logfunc;
502 &$outfunc($outlog) if $outfunc && $outlog;
503 &$logfunc($outlog) if $logfunc && $outlog;
505 &$errfunc($errlog) if $errfunc && $errlog;
506 &$logfunc($errlog) if $logfunc && $errlog;
511 die "failed to execute\n";
512 } elsif (my $sig = ($? & 127)) {
513 die "got signal $sig\n";
514 } elsif ($exitcode = ($? >> 8)) {
515 if (!($exitcode == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
516 if ($errmsg && $laststderr) {
517 my $lerr = $laststderr;
521 die "exit code $exitcode\n";
532 if ($errmsg && $laststderr) {
533 &$errfunc(undef); # flush laststderr
536 umask ($old_umask) if defined($old_umask);
538 alarm($oldtimeout) if $oldtimeout;
541 if ($pid && ($err eq "got timeout\n")) {
544 die "command '$cmdstr' failed: $err";
548 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
551 die "command '$cmdstr' failed: $err";
559 my $listtxt = shift || '';
561 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
563 $listtxt =~ s/[,;]/ /g;
564 $listtxt =~ s/^\s+//;
566 my @data = split (/\s+/, $listtxt);
574 return $txt if !defined($txt);
582 # simple uri templates like "/vms/{vmid}"
583 sub template_replace
{
584 my ($tmpl, $data) = @_;
586 return $tmpl if !$tmpl;
589 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
591 $res .= ($data->{$3} || '-') if $2;
597 my ($filename, $fh, $data) = @_;
601 my $res = print $fh $data;
603 die "write to '$filename' failed\n" if !$res;
609 'at' => 'ftp.at.debian.org',
610 'au' => 'ftp.au.debian.org',
611 'be' => 'ftp.be.debian.org',
612 'bg' => 'ftp.bg.debian.org',
613 'br' => 'ftp.br.debian.org',
614 'ca' => 'ftp.ca.debian.org',
615 'ch' => 'ftp.ch.debian.org',
616 'cl' => 'ftp.cl.debian.org',
617 'cz' => 'ftp.cz.debian.org',
618 'de' => 'ftp.de.debian.org',
619 'dk' => 'ftp.dk.debian.org',
620 'ee' => 'ftp.ee.debian.org',
621 'es' => 'ftp.es.debian.org',
622 'fi' => 'ftp.fi.debian.org',
623 'fr' => 'ftp.fr.debian.org',
624 'gr' => 'ftp.gr.debian.org',
625 'hk' => 'ftp.hk.debian.org',
626 'hr' => 'ftp.hr.debian.org',
627 'hu' => 'ftp.hu.debian.org',
628 'ie' => 'ftp.ie.debian.org',
629 'is' => 'ftp.is.debian.org',
630 'it' => 'ftp.it.debian.org',
631 'jp' => 'ftp.jp.debian.org',
632 'kr' => 'ftp.kr.debian.org',
633 'mx' => 'ftp.mx.debian.org',
634 'nl' => 'ftp.nl.debian.org',
635 'no' => 'ftp.no.debian.org',
636 'nz' => 'ftp.nz.debian.org',
637 'pl' => 'ftp.pl.debian.org',
638 'pt' => 'ftp.pt.debian.org',
639 'ro' => 'ftp.ro.debian.org',
640 'ru' => 'ftp.ru.debian.org',
641 'se' => 'ftp.se.debian.org',
642 'si' => 'ftp.si.debian.org',
643 'sk' => 'ftp.sk.debian.org',
644 'tr' => 'ftp.tr.debian.org',
645 'tw' => 'ftp.tw.debian.org',
646 'gb' => 'ftp.uk.debian.org',
647 'us' => 'ftp.us.debian.org',
652 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
653 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
654 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
655 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
656 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
657 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
658 #'et' => [], # Ethopia or Estonia ??
659 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
660 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
661 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
662 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
663 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
664 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
665 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
666 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
667 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
668 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
669 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
670 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
671 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
672 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
673 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
674 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
675 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
676 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
677 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
678 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
679 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
680 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
681 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
683 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
686 my $kvmkeymaparray = [];
687 foreach my $lc (sort keys %$keymaphash) {
688 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
696 return $kvmkeymaparray;
700 my ($param, $key) = @_;
702 my $res = $param->{$key};
703 delete $param->{$key};
708 # Note: we use this to wait until vncterm/spiceterm is ready
709 sub wait_for_vnc_port
{
710 my ($port, $timeout) = @_;
712 $timeout = 5 if !$timeout;
714 my $starttime = [gettimeofday
];
717 while (($elapsed = tv_interval
($starttime)) < $timeout) {
718 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
719 while (defined (my $line = <$fh>)) {
720 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
721 if ($port == hex($2)) {
729 $sleeptime += 100000 if $sleeptime < 1000000;
736 sub next_unused_port
{
737 my ($range_start, $range_end, $family) = @_;
739 # We use a file to register allocated ports.
740 # Those registrations expires after $expiretime.
741 # We use this to avoid race conditions between
742 # allocation and use of ports.
744 my $filename = "/var/tmp/pve-reserved-ports";
753 if (my $fh = IO
::File-
>new ($filename, "r")) {
754 while (my $line = <$fh>) {
755 if ($line =~ m/^(\d+)\s(\d+)$/) {
756 my ($port, $timestamp) = ($1, $2);
757 if (($timestamp + $expiretime) > $ctime) {
758 $ports->{$port} = $timestamp; # not expired
766 for (my $p = $range_start; $p < $range_end; $p++) {
767 next if $ports->{$p}; # reserved
769 my $sock = IO
::Socket
::IP-
>new(Listen
=> 5,
774 GetAddrInfoFlags
=> 0);
779 $ports->{$p} = $ctime;
785 foreach my $p (keys %$ports) {
786 $data .= "$p $ports->{$p}\n";
789 file_set_contents
($filename, $data);
794 my $p = lock_file
($filename, 10, $code);
797 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
802 sub next_migrate_port
{
804 return next_unused_port
(60000, 60050, $family);
809 return next_unused_port
(5900, 6000, $family);
812 sub next_spice_port
{
814 return next_unused_port
(61000, 61099, $family);
817 # NOTE: NFS syscall can't be interrupted, so alarm does
818 # not work to provide timeouts.
819 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
820 # So fork() before using Filesys::Df
822 my ($path, $timeout) = @_;
830 my $pipe = IO
::Pipe-
>new();
832 if (!defined($child)) {
833 warn "fork failed: $!\n";
840 my $df = Filesys
::Df
::df
($path, 1);
841 print {$pipe} "$df->{blocks}\n$df->{used}\n$df->{bavail}\n";
853 my $readvalues = sub {
854 $res->{total
} = int((<$pipe> =~ /^(\d*)$/)[0]);
855 $res->{used
} = int((<$pipe> =~ /^(\d*)$/)[0]);
856 $res->{avail
} = int((<$pipe> =~ /^(\d*)$/)[0]);
859 run_with_timeout
($timeout, $readvalues);
863 kill('KILL', $child);
869 # We use this to uniquely identify a process.
870 # An 'Unique Process ID' has the following format:
871 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
876 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
877 # more that 8 characters for pstart
878 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
879 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
884 my ($upid, $noerr) = @_;
889 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
890 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
891 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]+):$/) {
893 $res->{pid
} = hex($3);
894 $res->{pstart
} = hex($4);
895 $res->{starttime
} = hex($5);
900 my $subdir = substr($5, 7, 8);
901 $filename = "$pvetaskdir/$subdir/$upid";
904 return undef if $noerr;
905 die "unable to parse worker upid '$upid'\n";
908 return wantarray ?
($res, $filename) : $res;
914 my ($task, $filename) = upid_decode
($upid);
916 my $dirname = dirname
($filename);
919 my $wwwid = getpwnam('www-data') ||
920 die "getpwnam failed";
924 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
925 die "unable to create output file '$filename' - $!\n";
926 chown $wwwid, -1, $outfh;
931 sub upid_read_status
{
934 my ($task, $filename) = upid_decode
($upid);
935 my $fh = IO
::File-
>new($filename, "r");
936 return "unable to open file - $!" if !$fh;
938 sysseek($fh, -$maxlen, 2);
940 my $br = sysread($fh, $readbuf, $maxlen);
943 return "unable to extract last line"
944 if $readbuf !~ m/\n?(.+)$/;
946 if ($line =~ m/^TASK OK$/) {
948 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
951 return "unexpected status";
954 return "unable to read tail (got $br bytes)";
957 # useful functions to store comments in config files
961 # all control and hi-bit characters, and ':'
962 my $unsafe = "^\x20-\x39\x3b-\x7e";
963 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
969 return Encode
::decode
("utf8", uri_unescape
($data));
972 sub decode_utf8_parameters
{
975 foreach my $p (qw(comment description firstname lastname)) {
976 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
982 sub random_ether_addr
{
984 my ($seconds, $microseconds) = gettimeofday
;
986 my $rand = Digest
::SHA
::sha1
($$, rand(), $seconds, $microseconds);
988 # clear multicast, set local id
989 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
991 return sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
997 return String
::ShellQuote
::shell_quote
($str);
1003 die "no arguments" if !$cmd;
1005 return $cmd if !ref($cmd);
1008 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
1010 return join (' ', @qa);
1013 # split an shell argument string into an array,
1017 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
1021 my ($filename, $start, $limit, $filter) = @_;
1026 my $fh = IO
::File-
>new($filename, "r");
1029 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
1030 return ($count, $lines);
1033 $start = 0 if !$start;
1034 $limit = 50 if !$limit;
1039 # duplicate code, so that we do not slow down normal path
1040 while (defined($line = <$fh>)) {
1041 next if $line !~ m/$filter/;
1042 next if $count++ < $start;
1043 next if $limit <= 0;
1045 push @$lines, { n
=> $count, t
=> $line};
1049 while (defined($line = <$fh>)) {
1050 next if $count++ < $start;
1051 next if $limit <= 0;
1053 push @$lines, { n
=> $count, t
=> $line};
1060 # HACK: ExtJS store.guaranteeRange() does not like empty array
1064 push @$lines, { n
=> $count, t
=> "no content"};
1067 return ($count, $lines);
1071 my ($start, $limit, $since, $until) = @_;
1076 $start = 0 if !$start;
1077 $limit = 50 if !$limit;
1082 return if $count++ < $start;
1083 return if $limit <= 0;
1084 push @$lines, { n
=> int($count), t
=> $line};
1088 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1090 push @$cmd, '--since', $since if $since;
1091 push @$cmd, '--until', $until if $until;
1092 run_command
($cmd, outfunc
=> $parser);
1094 # HACK: ExtJS store.guaranteeRange() does not like empty array
1098 push @$lines, { n
=> $count, t
=> "no content"};
1101 return ($count, $lines);
1104 sub dir_glob_regex
{
1105 my ($dir, $regex) = @_;
1107 my $dh = IO
::Dir-
>new ($dir);
1108 return wantarray ?
() : undef if !$dh;
1110 while (defined(my $tmp = $dh->read)) {
1111 if (my @res = $tmp =~ m/^($regex)$/) {
1113 return wantarray ?
@res : $tmp;
1118 return wantarray ?
() : undef;
1121 sub dir_glob_foreach
{
1122 my ($dir, $regex, $func) = @_;
1124 my $dh = IO
::Dir-
>new ($dir);
1126 while (defined(my $tmp = $dh->read)) {
1127 if (my @res = $tmp =~ m/^($regex)$/) {
1134 sub assert_if_modified
{
1135 my ($digest1, $digest2) = @_;
1137 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1138 die "detected modified configuration - file changed by other user? Try again.\n";
1142 # Digest for short strings
1143 # like FNV32a, but we only return 31 bits (positive numbers)
1147 my $hval = 0x811c9dc5;
1149 foreach my $c (unpack('C*', $string)) {
1157 $hval = $hval & 0xffffffff;
1159 return $hval & 0x7fffffff;
1162 sub fnv31a_hex
{ return sprintf("%X", fnv31a
(@_)); }
1164 sub unpack_sockaddr_in46
{
1166 my $family = Socket
::sockaddr_family
($sin);
1167 my ($port, $host) = ($family == AF_INET6 ? Socket
::unpack_sockaddr_in6
($sin)
1168 : Socket
::unpack_sockaddr_in
($sin));
1169 return ($family, $port, $host);
1172 sub getaddrinfo_all
{
1173 my ($hostname, @opts) = @_;
1174 my %hints = ( flags
=> AI_V4MAPPED
| AI_ALL
,
1176 my ($err, @res) = Socket
::getaddrinfo
($hostname, '0', \
%hints);
1177 die "failed to get address info for: $hostname: $err\n" if $err;
1181 sub get_host_address_family
{
1182 my ($hostname, $socktype) = @_;
1183 my @res = getaddrinfo_all
($hostname, socktype
=> $socktype);
1184 return $res[0]->{family
};
1187 # Parses any sane kind of host, or host+port pair:
1188 # The port is always optional and thus may be undef.
1189 sub parse_host_and_port
{
1191 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1192 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1193 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1195 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1202 return 0 == syscall(272, $flags);
1206 my ($fileno, $nstype) = @_;
1207 return 0 == syscall(308, $fileno, $nstype);
1212 return 0 == syscall(306, $fileno);
1215 sub sync_mountpoint
{
1217 sysopen my $fd, $path, O_PATH
or die "failed to open $path: $!\n";
1218 my $result = syncfs
(fileno($fd));
1223 # support sending multi-part mail messages with a text and or a HTML part
1224 # mailto may be a single email string or an array of receivers
1226 my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_;
1227 my $mail_re = qr/[^-a-zA-Z0-9+._@]/;
1229 $mailto = [ $mailto ] if !ref($mailto);
1231 foreach (@$mailto) {
1232 die "illegal character in mailto address\n"
1233 if ($_ =~ $mail_re);
1236 my $rcvrtxt = join (', ', @$mailto);
1238 $mailfrom = $mailfrom || "root";
1239 die "illegal character in mailfrom address\n"
1240 if $mailfrom =~ $mail_re;
1242 $author = $author || 'Proxmox VE';
1244 open (MAIL
, "|-", "sendmail", "-B", "8BITMIME", "-f", $mailfrom, @$mailto) ||
1245 die "unable to open 'sendmail' - $!";
1247 # multipart spec see https://www.ietf.org/rfc/rfc1521.txt
1248 my $boundary = "----_=_NextPart_001_".int(time).$$;
1250 print MAIL
"Content-Type: multipart/alternative;\n";
1251 print MAIL
"\tboundary=\"$boundary\"\n";
1252 print MAIL "MIME-Version
: 1.0\n";
1254 print MAIL "FROM
: $author <$mailfrom>\n";
1255 print MAIL "TO
: $rcvrtxt\n";
1256 print MAIL "SUBJECT
: $subject\n";
1258 print MAIL "This
is a multi-part message
in MIME format
.\n\n";
1259 print MAIL "--$boundary\n";
1261 if (defined($text)) {
1262 print MAIL "Content-Type
: text
/plain
;\n";
1263 print MAIL "\tcharset
=\"UTF8
\"\n";
1264 print MAIL "Content-Transfer-Encoding
: 8bit
\n";
1267 # avoid 'remove extra line breaks' issue (MS Outlook)
1269 $text =~ s/^/$fill/gm;
1273 print MAIL "\n--$boundary\n";
1276 if (defined($html)) {
1277 print MAIL "Content-Type
: text
/html
;\n";
1278 print MAIL "\tcharset
=\"UTF8
\"\n";
1279 print MAIL "Content-Transfer-Encoding
: 8bit
\n";
1284 print MAIL "\n--$boundary--\n";
1291 my ($perm, %opts) = @_;
1293 # default permissions are stricter than with file_set_contents
1294 $perm = 0600 if !defined($perm);
1296 my $dir = $opts{dir} // '/tmp';
1297 my $mode = $opts{mode} // O_RDWR;
1298 $mode |= O_EXCL if !$opts{allow_links};
1300 my $fh = IO::File->new($dir, $mode | O_TMPFILE, $perm)
1301 or die "failed to create tempfile
: $!\n";
1305 sub tempfile_contents {
1306 my ($data, $perm, %opts) = @_;
1308 my $fh = tempfile($perm, %opts);
1310 die "unable to
write to tempfile
: $!\n" if !print {$fh} $data;
1311 die "unable to flush to tempfile
: $!\n" if !defined($fh->flush());
1318 return ("/proc/$$/fd/".$fh->fileno, $fh);
1321 sub validate_ssh_public_keys {
1323 my @lines = split(/\n/, $raw);
1325 foreach my $line (@lines) {
1326 next if $line =~ m/^\s*$/;
1328 my ($filename, $handle) = tempfile_contents($line);
1329 run_command(["ssh-keygen
", "-l
", "-f
", $filename],
1330 outfunc => sub {}, errfunc => sub {});
1332 die "SSH public key validation error
\n" if $@;
1337 my ($dirfd, $pathname, $flags, $mode) = @_;
1338 my $fd = syscall(257, $dirfd, $pathname, $flags, $mode//0);
1339 return undef if $fd < 0;
1340 # sysopen() doesn't deal with numeric file descriptors apparently
1341 # so we need to convert to a mode string for IO::Handle->new_from_fd
1342 my $flagstr = ($flags & O_RDWR) ? 'rw' : ($flags & O_WRONLY) ? 'w' : 'r';
1343 my $handle = IO::Handle->new_from_fd($fd, $flagstr);
1344 return $handle if $handle;
1345 my $err = $!; # save error before closing the raw fd
1346 syscall(3, $fd); # close
1352 my ($dirfd, $name, $mode) = @_;
1353 return syscall(258, $dirfd, $name, $mode) == 0;
1356 # NOTE: This calls the dbus main loop and must not be used when another dbus
1357 # main loop is being used as we need to wait for the JobRemoved signal.
1358 # Polling the job status instead doesn't work because this doesn't give us the
1359 # distinction between success and failure.
1361 # Note that the description is mandatory for security reasons.
1362 sub enter_systemd_scope {
1363 my ($unit, $description, %extra) = @_;
1364 die "missing description
\n" if !defined($description);
1366 my $timeout = delete $extra{timeout};
1369 my $properties = [ [PIDs => [dbus_uint32($$)]] ];
1371 foreach my $key (keys %extra) {
1372 if ($key eq 'Slice' || $key eq 'KillMode') {
1373 push @$properties, [$key, $extra{$key}];
1374 } elsif ($key eq 'CPUShares') {
1375 push @$properties, [$key, dbus_uint64($extra{$key})];
1376 } elsif ($key eq 'CPUQuota') {
1377 push @$properties, ['CPUQuotaPerSecUSec',
1378 dbus_uint64($extra{$key} * 10000)];
1380 die "Don
't know how to encode $key for systemd scope\n";
1387 my $bus = Net::DBus->system();
1388 my $reactor = Net::DBus::Reactor->main();
1390 my $service = $bus->get_service('org
.freedesktop
.systemd1
');
1391 my $if = $service->get_object('/org/freedesktop
/systemd1
', 'org
.freedesktop
.systemd1
.Manager
');
1392 # Connect to the JobRemoved signal since we want to wait for it to finish
1396 my ($no_shutdown) = @_;
1397 $if->disconnect_from_signal('JobRemoved
', $sigid) if defined($if);
1400 $reactor->remove_timeout($timer) if defined($timer);
1402 return if $no_shutdown;
1403 $reactor->shutdown();
1406 $sigid = $if->connect_to_signal('JobRemoved
', sub {
1407 my ($id, $removed_job, $signaled_unit, $result) = @_;
1408 return if $signaled_unit ne $unit || $removed_job ne $job;
1410 die "systemd job failed\n" if $result ne 'done
';
1414 my $on_timeout = sub {
1416 die "systemd job timed out\n";
1419 $timer = $reactor->add_timeout($timeout * 1000, Net::DBus::Callback->new(method => $on_timeout))
1420 if defined($timeout);
1421 $job = $if->StartTransientUnit($unit, 'fail
', $properties, []);
1424 die "systemd job never completed\n" if !$done;