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);
26 # avoid warning when parsing long hex values with hex()
27 no warnings
'portable'; # Support for 64-bit ints required
50 my $pvelogdir = "/var/log/pve";
51 my $pvetaskdir = "$pvelogdir/tasks";
56 my $IPV4OCTET = "(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])";
57 our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)";
58 my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})";
59 my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))";
62 "(?:(?:" . "(?:$IPV6H16:){6})$IPV6LS32)|" .
63 "(?:(?:" . "::(?:$IPV6H16:){5})$IPV6LS32)|" .
64 "(?:(?:(?:" . "$IPV6H16)?::(?:$IPV6H16:){4})$IPV6LS32)|" .
65 "(?:(?:(?:(?:$IPV6H16:){0,1}$IPV6H16)?::(?:$IPV6H16:){3})$IPV6LS32)|" .
66 "(?:(?:(?:(?:$IPV6H16:){0,2}$IPV6H16)?::(?:$IPV6H16:){2})$IPV6LS32)|" .
67 "(?:(?:(?:(?:$IPV6H16:){0,3}$IPV6H16)?::(?:$IPV6H16:){1})$IPV6LS32)|" .
68 "(?:(?:(?:(?:$IPV6H16:){0,4}$IPV6H16)?::" . ")$IPV6LS32)|" .
69 "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" . ")$IPV6H16)|" .
70 "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" . ")))";
72 our $IPRE = "(?:$IPV4RE|$IPV6RE)";
74 use constant {CLONE_NEWNS
=> 0x00020000,
75 CLONE_NEWUTS
=> 0x04000000,
76 CLONE_NEWIPC
=> 0x08000000,
77 CLONE_NEWUSER
=> 0x10000000,
78 CLONE_NEWPID
=> 0x20000000,
79 CLONE_NEWNET
=> 0x40000000};
81 use constant {O_PATH
=> 0x00200000,
82 O_TMPFILE
=> 0x00410000}; # This includes O_DIRECTORY
84 sub run_with_timeout
{
85 my ($timeout, $code, @param) = @_;
87 die "got timeout\n" if $timeout <= 0;
89 my $prev_alarm = alarm 0; # suspend outer alarm early
96 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
97 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
98 local $SIG{__DIE__
}; # see SA bug 4631
102 eval { $res = &$code(@param); };
104 alarm(0); # avoid race conditions
113 # this shouldn't happen anymore?
114 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
121 # flock: we use one file handle per process, so lock file
122 # can be called multiple times and succeeds for the same process.
124 my $lock_handles = {};
127 my ($filename, $timeout, $shared, $code, @param) = @_;
129 $timeout = 10 if !$timeout;
131 my $mode = $shared ? LOCK_SH
: LOCK_EX
;
133 my $lock_func = sub {
134 if (!$lock_handles->{$$}->{$filename}) {
135 my $fh = new IO
::File
(">>$filename") ||
136 die "can't open file - $!\n";
137 $lock_handles->{$$}->{$filename} = { fh
=> $fh, refcount
=> 0};
140 if (!flock($lock_handles->{$$}->{$filename}->{fh
}, $mode|LOCK_NB
)) {
141 print STDERR
"trying to acquire lock...";
144 $success = flock($lock_handles->{$$}->{$filename}->{fh
}, $mode);
145 # try again on EINTR (see bug #273)
146 if ($success || ($! != EINTR
)) {
151 print STDERR
" failed\n";
152 die "can't acquire lock '$filename' - $!\n";
154 print STDERR
" OK\n";
156 $lock_handles->{$$}->{$filename}->{refcount
}++;
161 eval { run_with_timeout
($timeout, $lock_func); };
164 $err = "can't lock file '$filename' - $err";
166 eval { $res = &$code(@param) };
170 if (my $fh = $lock_handles->{$$}->{$filename}->{fh
}) {
171 my $refcount = --$lock_handles->{$$}->{$filename}->{refcount
};
172 if ($refcount <= 0) {
173 $lock_handles->{$$}->{$filename} = undef;
190 my ($filename, $timeout, $code, @param) = @_;
192 return lock_file_full
($filename, $timeout, 0, $code, @param);
195 sub file_set_contents
{
196 my ($filename, $data, $perm) = @_;
198 $perm = 0644 if !defined($perm);
200 my $tmpname = "$filename.tmp.$$";
203 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
204 die "unable to open file '$tmpname' - $!\n" if !$fh;
205 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
206 die "closing file '$tmpname' failed - $!\n" unless close $fh;
215 if (!rename($tmpname, $filename)) {
216 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
222 sub file_get_contents
{
223 my ($filename, $max) = @_;
225 my $fh = IO
::File-
>new($filename, "r") ||
226 die "can't open '$filename' - $!\n";
228 my $content = safe_read_from
($fh, $max);
236 my ($filename, $dst, $max, $perm) = @_;
238 file_set_contents
($dst, file_get_contents
($filename, $max), $perm);
241 sub file_read_firstline
{
244 my $fh = IO
::File-
>new ($filename, "r");
245 return undef if !$fh;
253 my ($fh, $max, $oneline) = @_;
255 $max = 32768 if !$max;
260 while ($count = sysread($fh, $input, 8192, $br)) {
262 die "input too long - aborting\n" if $br > $max;
263 if ($oneline && $input =~ m/^(.*)\n/) {
268 die "unable to read input - $!\n" if !defined($count);
273 # The $cmd parameter can be:
275 # This is generally executed by passing it to the shell with the -c option.
276 # However, it can be executed in one of two ways, depending on whether
277 # there's a pipe involved:
278 # *) with pipe: passed explicitly to bash -c, prefixed with:
280 # *) without a pipe: passed to perl's open3 which uses 'sh -c'
281 # (Note that this may result in two different syntax requirements!)
283 # -) an array of arguments (strings)
284 # Will be executed without interference from a shell. (Parameters are passed
285 # as is, no escape sequences of strings will be touched.)
286 # -) an array of arrays
287 # Each array represents a command, and each command's output is piped into
288 # the following command's standard input.
289 # For this a shell command string is created with pipe symbols between each
291 # Each command is a list of strings meant to end up in the final command
292 # unchanged. In order to achieve this, every argument is shell-quoted.
293 # Quoting can be disabled for a particular argument by turning it into a
294 # reference, this allows inserting arbitrary shell options.
295 # For instance: the $cmd [ [ 'echo', 'hello', \'>/dev/null' ] ] will not
296 # produce any output, while the $cmd [ [ 'echo', 'hello', '>/dev/null' ] ]
297 # will literally print: hello >/dev/null
299 my ($cmd, %param) = @_;
304 if (my $ref = ref($cmd)) {
305 if (ref($cmd->[0])) {
306 $cmdstr = 'set -o pipefail && ';
308 foreach my $command (@$cmd) {
309 # concatenate quoted parameters
310 # strings which are passed by reference are NOT shell quoted
311 $cmdstr .= $pipe . join(' ', map { ref($_) ?
$$_ : shellquote
($_) } @$command);
314 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmdstr" ];
316 $cmdstr = cmd2string
($cmd);
321 # see 'man bash' for option pipefail
322 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
345 foreach my $p (keys %param) {
346 if ($p eq 'timeout') {
347 $timeout = $param{$p};
348 } elsif ($p eq 'umask') {
349 $old_umask = umask($param{$p});
350 } elsif ($p eq 'errmsg') {
351 $errmsg = $param{$p};
352 } elsif ($p eq 'input') {
354 } elsif ($p eq 'output') {
355 $output = $param{$p};
356 } elsif ($p eq 'outfunc') {
357 $outfunc = $param{$p};
358 } elsif ($p eq 'errfunc') {
359 $errfunc = $param{$p};
360 } elsif ($p eq 'logfunc') {
361 $logfunc = $param{$p};
362 } elsif ($p eq 'afterfork') {
363 $afterfork = $param{$p};
364 } elsif ($p eq 'noerr') {
367 die "got unknown parameter '$p' for run_command\n";
372 my $origerrfunc = $errfunc;
376 &$origerrfunc("$laststderr\n");
378 print STDERR
"$laststderr\n" if $laststderr;
385 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
386 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
387 my $error = IO
::File-
>new();
389 # try to avoid locale related issues/warnings
390 my $lang = $param{lang
} || 'C';
395 local $ENV{LC_ALL
} = $lang;
397 # suppress LVM warnings like: "File descriptor 3 left open";
398 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
400 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
402 # if we pipe fron STDIN, open3 closes STDIN, so we we
403 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
404 # as soon as we open a new file.
405 # to avoid that we open /dev/null
406 if (!ref($writer) && !defined(fileno(STDIN
))) {
408 open(STDIN
, "</dev/null");
415 if ($orig_pid != $$) {
423 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
424 $oldtimeout = alarm($timeout) if $timeout;
426 &$afterfork() if $afterfork;
429 print $writer $input if defined $input;
433 my $select = new IO
::Select
;
434 $select->add($reader) if ref($reader);
435 $select->add($error);
440 my $starttime = time();
442 while ($select->count) {
443 my @handles = $select->can_read(1);
445 foreach my $h (@handles) {
447 my $count = sysread ($h, $buf, 4096);
448 if (!defined ($count)) {
454 $select->remove ($h) if !$count;
456 if ($outfunc || $logfunc) {
459 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
461 &$outfunc($line) if $outfunc;
462 &$logfunc($line) if $logfunc;
475 } elsif ($h eq $error) {
476 if ($errfunc || $logfunc) {
479 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
481 &$errfunc($line) if $errfunc;
482 &$logfunc($line) if $logfunc;
499 &$outfunc($outlog) if $outfunc && $outlog;
500 &$logfunc($outlog) if $logfunc && $outlog;
502 &$errfunc($errlog) if $errfunc && $errlog;
503 &$logfunc($errlog) if $logfunc && $errlog;
508 die "failed to execute\n";
509 } elsif (my $sig = ($? & 127)) {
510 die "got signal $sig\n";
511 } elsif ($exitcode = ($? >> 8)) {
512 if (!($exitcode == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
513 if ($errmsg && $laststderr) {
514 my $lerr = $laststderr;
518 die "exit code $exitcode\n";
529 if ($errmsg && $laststderr) {
530 &$errfunc(undef); # flush laststderr
533 umask ($old_umask) if defined($old_umask);
535 alarm($oldtimeout) if $oldtimeout;
538 if ($pid && ($err eq "got timeout\n")) {
541 die "command '$cmdstr' failed: $err";
545 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
548 die "command '$cmdstr' failed: $err";
556 my $listtxt = shift || '';
558 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
560 $listtxt =~ s/[,;]/ /g;
561 $listtxt =~ s/^\s+//;
563 my @data = split (/\s+/, $listtxt);
571 return $txt if !defined($txt);
579 # simple uri templates like "/vms/{vmid}"
580 sub template_replace
{
581 my ($tmpl, $data) = @_;
583 return $tmpl if !$tmpl;
586 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
588 $res .= ($data->{$3} || '-') if $2;
594 my ($filename, $fh, $data) = @_;
598 my $res = print $fh $data;
600 die "write to '$filename' failed\n" if !$res;
606 'at' => 'ftp.at.debian.org',
607 'au' => 'ftp.au.debian.org',
608 'be' => 'ftp.be.debian.org',
609 'bg' => 'ftp.bg.debian.org',
610 'br' => 'ftp.br.debian.org',
611 'ca' => 'ftp.ca.debian.org',
612 'ch' => 'ftp.ch.debian.org',
613 'cl' => 'ftp.cl.debian.org',
614 'cz' => 'ftp.cz.debian.org',
615 'de' => 'ftp.de.debian.org',
616 'dk' => 'ftp.dk.debian.org',
617 'ee' => 'ftp.ee.debian.org',
618 'es' => 'ftp.es.debian.org',
619 'fi' => 'ftp.fi.debian.org',
620 'fr' => 'ftp.fr.debian.org',
621 'gr' => 'ftp.gr.debian.org',
622 'hk' => 'ftp.hk.debian.org',
623 'hr' => 'ftp.hr.debian.org',
624 'hu' => 'ftp.hu.debian.org',
625 'ie' => 'ftp.ie.debian.org',
626 'is' => 'ftp.is.debian.org',
627 'it' => 'ftp.it.debian.org',
628 'jp' => 'ftp.jp.debian.org',
629 'kr' => 'ftp.kr.debian.org',
630 'mx' => 'ftp.mx.debian.org',
631 'nl' => 'ftp.nl.debian.org',
632 'no' => 'ftp.no.debian.org',
633 'nz' => 'ftp.nz.debian.org',
634 'pl' => 'ftp.pl.debian.org',
635 'pt' => 'ftp.pt.debian.org',
636 'ro' => 'ftp.ro.debian.org',
637 'ru' => 'ftp.ru.debian.org',
638 'se' => 'ftp.se.debian.org',
639 'si' => 'ftp.si.debian.org',
640 'sk' => 'ftp.sk.debian.org',
641 'tr' => 'ftp.tr.debian.org',
642 'tw' => 'ftp.tw.debian.org',
643 'gb' => 'ftp.uk.debian.org',
644 'us' => 'ftp.us.debian.org',
649 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
650 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
651 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
652 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
653 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
654 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
655 #'et' => [], # Ethopia or Estonia ??
656 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
657 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
658 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
659 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
660 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
661 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
662 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
663 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
664 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
665 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
666 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
667 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
668 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
669 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
670 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
671 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
672 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
673 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
674 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
675 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
676 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
677 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
678 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
680 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
683 my $kvmkeymaparray = [];
684 foreach my $lc (sort keys %$keymaphash) {
685 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
693 return $kvmkeymaparray;
697 my ($param, $key) = @_;
699 my $res = $param->{$key};
700 delete $param->{$key};
705 # Note: we use this to wait until vncterm/spiceterm is ready
706 sub wait_for_vnc_port
{
707 my ($port, $timeout) = @_;
709 $timeout = 5 if !$timeout;
711 my $starttime = [gettimeofday
];
714 while (($elapsed = tv_interval
($starttime)) < $timeout) {
715 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
716 while (defined (my $line = <$fh>)) {
717 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
718 if ($port == hex($2)) {
726 $sleeptime += 100000 if $sleeptime < 1000000;
733 sub next_unused_port
{
734 my ($range_start, $range_end, $family) = @_;
736 # We use a file to register allocated ports.
737 # Those registrations expires after $expiretime.
738 # We use this to avoid race conditions between
739 # allocation and use of ports.
741 my $filename = "/var/tmp/pve-reserved-ports";
750 if (my $fh = IO
::File-
>new ($filename, "r")) {
751 while (my $line = <$fh>) {
752 if ($line =~ m/^(\d+)\s(\d+)$/) {
753 my ($port, $timestamp) = ($1, $2);
754 if (($timestamp + $expiretime) > $ctime) {
755 $ports->{$port} = $timestamp; # not expired
763 for (my $p = $range_start; $p < $range_end; $p++) {
764 next if $ports->{$p}; # reserved
766 my $sock = IO
::Socket
::IP-
>new(Listen
=> 5,
771 GetAddrInfoFlags
=> 0);
776 $ports->{$p} = $ctime;
782 foreach my $p (keys %$ports) {
783 $data .= "$p $ports->{$p}\n";
786 file_set_contents
($filename, $data);
791 my $p = lock_file
($filename, 10, $code);
794 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
799 sub next_migrate_port
{
801 return next_unused_port
(60000, 60050, $family);
806 return next_unused_port
(5900, 6000, $family);
809 sub next_spice_port
{
811 return next_unused_port
(61000, 61099, $family);
814 # NOTE: NFS syscall can't be interrupted, so alarm does
815 # not work to provide timeouts.
816 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
817 # So fork() before using Filesys::Df
819 my ($path, $timeout) = @_;
827 my $pipe = IO
::Pipe-
>new();
829 if (!defined($child)) {
830 warn "fork failed: $!\n";
837 my $df = Filesys
::Df
::df
($path, 1);
838 print {$pipe} "$df->{blocks}\n$df->{used}\n$df->{bavail}\n";
850 my $readvalues = sub {
851 $res->{total
} = int(<$pipe>);
852 $res->{used
} = int(<$pipe>);
853 $res->{avail
} = int(<$pipe>);
856 run_with_timeout
($timeout, $readvalues);
860 kill('KILL', $child);
866 # We use this to uniquely identify a process.
867 # An 'Unique Process ID' has the following format:
868 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
873 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
874 # more that 8 characters for pstart
875 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
876 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
881 my ($upid, $noerr) = @_;
886 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
887 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
888 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]+):$/) {
890 $res->{pid
} = hex($3);
891 $res->{pstart
} = hex($4);
892 $res->{starttime
} = hex($5);
897 my $subdir = substr($5, 7, 8);
898 $filename = "$pvetaskdir/$subdir/$upid";
901 return undef if $noerr;
902 die "unable to parse worker upid '$upid'\n";
905 return wantarray ?
($res, $filename) : $res;
911 my ($task, $filename) = upid_decode
($upid);
913 my $dirname = dirname
($filename);
916 my $wwwid = getpwnam('www-data') ||
917 die "getpwnam failed";
921 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
922 die "unable to create output file '$filename' - $!\n";
923 chown $wwwid, -1, $outfh;
928 sub upid_read_status
{
931 my ($task, $filename) = upid_decode
($upid);
932 my $fh = IO
::File-
>new($filename, "r");
933 return "unable to open file - $!" if !$fh;
935 sysseek($fh, -$maxlen, 2);
937 my $br = sysread($fh, $readbuf, $maxlen);
940 return "unable to extract last line"
941 if $readbuf !~ m/\n?(.+)$/;
943 if ($line =~ m/^TASK OK$/) {
945 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
948 return "unexpected status";
951 return "unable to read tail (got $br bytes)";
954 # useful functions to store comments in config files
958 # all control and hi-bit characters, and ':'
959 my $unsafe = "^\x20-\x39\x3b-\x7e";
960 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
966 return Encode
::decode
("utf8", uri_unescape
($data));
969 sub decode_utf8_parameters
{
972 foreach my $p (qw(comment description firstname lastname)) {
973 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
979 sub random_ether_addr
{
981 my ($seconds, $microseconds) = gettimeofday
;
983 my $rand = Digest
::SHA
::sha1_hex
($$, rand(), $seconds, $microseconds);
985 # clear multicast, set local id
986 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
988 return sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
994 return String
::ShellQuote
::shell_quote
($str);
1000 die "no arguments" if !$cmd;
1002 return $cmd if !ref($cmd);
1005 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
1007 return join (' ', @qa);
1010 # split an shell argument string into an array,
1014 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
1018 my ($filename, $start, $limit, $filter) = @_;
1023 my $fh = IO
::File-
>new($filename, "r");
1026 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
1027 return ($count, $lines);
1030 $start = 0 if !$start;
1031 $limit = 50 if !$limit;
1036 # duplicate code, so that we do not slow down normal path
1037 while (defined($line = <$fh>)) {
1038 next if $line !~ m/$filter/;
1039 next if $count++ < $start;
1040 next if $limit <= 0;
1042 push @$lines, { n
=> $count, t
=> $line};
1046 while (defined($line = <$fh>)) {
1047 next if $count++ < $start;
1048 next if $limit <= 0;
1050 push @$lines, { n
=> $count, t
=> $line};
1057 # HACK: ExtJS store.guaranteeRange() does not like empty array
1061 push @$lines, { n
=> $count, t
=> "no content"};
1064 return ($count, $lines);
1068 my ($start, $limit, $since, $until) = @_;
1073 $start = 0 if !$start;
1074 $limit = 50 if !$limit;
1079 return if $count++ < $start;
1080 return if $limit <= 0;
1081 push @$lines, { n
=> int($count), t
=> $line};
1085 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1087 push @$cmd, '--since', $since if $since;
1088 push @$cmd, '--until', $until if $until;
1089 run_command
($cmd, outfunc
=> $parser);
1091 # HACK: ExtJS store.guaranteeRange() does not like empty array
1095 push @$lines, { n
=> $count, t
=> "no content"};
1098 return ($count, $lines);
1101 sub dir_glob_regex
{
1102 my ($dir, $regex) = @_;
1104 my $dh = IO
::Dir-
>new ($dir);
1105 return wantarray ?
() : undef if !$dh;
1107 while (defined(my $tmp = $dh->read)) {
1108 if (my @res = $tmp =~ m/^($regex)$/) {
1110 return wantarray ?
@res : $tmp;
1115 return wantarray ?
() : undef;
1118 sub dir_glob_foreach
{
1119 my ($dir, $regex, $func) = @_;
1121 my $dh = IO
::Dir-
>new ($dir);
1123 while (defined(my $tmp = $dh->read)) {
1124 if (my @res = $tmp =~ m/^($regex)$/) {
1131 sub assert_if_modified
{
1132 my ($digest1, $digest2) = @_;
1134 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1135 die "detected modified configuration - file changed by other user? Try again.\n";
1139 # Digest for short strings
1140 # like FNV32a, but we only return 31 bits (positive numbers)
1144 my $hval = 0x811c9dc5;
1146 foreach my $c (unpack('C*', $string)) {
1154 $hval = $hval & 0xffffffff;
1156 return $hval & 0x7fffffff;
1159 sub fnv31a_hex
{ return sprintf("%X", fnv31a
(@_)); }
1161 sub unpack_sockaddr_in46
{
1163 my $family = Socket
::sockaddr_family
($sin);
1164 my ($port, $host) = ($family == AF_INET6 ? Socket
::unpack_sockaddr_in6
($sin)
1165 : Socket
::unpack_sockaddr_in
($sin));
1166 return ($family, $port, $host);
1169 sub getaddrinfo_all
{
1170 my ($hostname, @opts) = @_;
1171 my %hints = ( flags
=> AI_V4MAPPED
| AI_ALL
,
1173 my ($err, @res) = Socket
::getaddrinfo
($hostname, '0', \
%hints);
1174 die "failed to get address info for: $hostname: $err\n" if $err;
1178 sub get_host_address_family
{
1179 my ($hostname, $socktype) = @_;
1180 my @res = getaddrinfo_all
($hostname, socktype
=> $socktype);
1181 return $res[0]->{family
};
1184 # Parses any sane kind of host, or host+port pair:
1185 # The port is always optional and thus may be undef.
1186 sub parse_host_and_port
{
1188 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1189 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1190 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1192 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1199 return 0 == syscall(272, $flags);
1203 my ($fileno, $nstype) = @_;
1204 return 0 == syscall(308, $fileno, $nstype);
1209 return 0 == syscall(306, $fileno);
1212 sub sync_mountpoint
{
1214 sysopen my $fd, $path, O_PATH
or die "failed to open $path: $!\n";
1215 my $result = syncfs
(fileno($fd));
1220 # support sending multi-part mail messages with a text and or a HTML part
1221 # mailto may be a single email string or an array of receivers
1223 my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_;
1225 $mailto = [ $mailto ] if !ref($mailto);
1228 foreach my $r (@$mailto) {
1229 $rcvrarg .= " '$r'";
1231 my $rcvrtxt = join (', ', @$mailto);
1233 $mailfrom = $mailfrom || "root";
1234 $author = $author || 'Proxmox VE';
1236 open (MAIL
,"|sendmail -B 8BITMIME -f $mailfrom $rcvrarg") ||
1237 die "unable to open 'sendmail' - $!";
1239 # multipart spec see https://www.ietf.org/rfc/rfc1521.txt
1240 my $boundary = "----_=_NextPart_001_".int(time).$$;
1242 print MAIL
"Content-Type: multipart/alternative;\n";
1243 print MAIL
"\tboundary=\"$boundary\"\n";
1244 print MAIL "MIME-Version
: 1.0\n";
1246 print MAIL "FROM
: $author <$mailfrom>\n";
1247 print MAIL "TO
: $rcvrtxt\n";
1248 print MAIL "SUBJECT
: $subject\n";
1250 print MAIL "This
is a multi-part message
in MIME format
.\n\n";
1251 print MAIL "--$boundary\n";
1253 if (defined($text)) {
1254 print MAIL "Content-Type
: text
/plain
;\n";
1255 print MAIL "\tcharset
=\"UTF8
\"\n";
1256 print MAIL "Content-Transfer-Encoding
: 8bit
\n";
1259 # avoid 'remove extra line breaks' issue (MS Outlook)
1261 $text =~ s/^/$fill/gm;
1265 print MAIL "\n--$boundary\n";
1268 if (defined($html)) {
1269 print MAIL "Content-Type
: text
/html
;\n";
1270 print MAIL "\tcharset
=\"UTF8
\"\n";
1271 print MAIL "Content-Transfer-Encoding
: 8bit
\n";
1276 print MAIL "\n--$boundary--\n";
1283 my ($perm, %opts) = @_;
1285 # default permissions are stricter than with file_set_contents
1286 $perm = 0600 if !defined($perm);
1288 my $dir = $opts{dir} // '/tmp';
1289 my $mode = $opts{mode} // O_RDWR;
1290 $mode |= O_EXCL if !$opts{allow_links};
1292 my $fh = IO::File->new($dir, $mode | O_TMPFILE, $perm)
1293 or die "failed to create tempfile
: $!\n";
1297 sub tempfile_contents {
1298 my ($data, $perm, %opts) = @_;
1300 my $fh = tempfile($perm, %opts);
1302 die "unable to
write to tempfile
: $!\n" if !print {$fh} $data;
1303 die "unable to flush to tempfile
: $!\n" if !defined($fh->flush());
1310 return ("/proc/$$/fd/".$fh->fileno, $fh);
1313 sub validate_ssh_public_keys {
1315 my @lines = split(/\n/, $raw);
1317 foreach my $line (@lines) {
1318 next if $line =~ m/^\s*$/;
1320 my ($filename, $handle) = tempfile_contents($line);
1321 run_command(["ssh-keygen
", "-l
", "-f
", $filename],
1322 outfunc => sub {}, errfunc => sub {});
1324 die "SSH public key validation error
\n" if $@;
1329 my ($dirfd, $pathname, $flags, $mode) = @_;
1330 my $fd = syscall(257, $dirfd, $pathname, $flags, $mode//0);
1331 return undef if $fd < 0;
1332 # sysopen() doesn't deal with numeric file descriptors apparently
1333 # so we need to convert to a mode string for IO::Handle->new_from_fd
1334 my $flagstr = ($flags & O_RDWR) ? 'rw' : ($flags & O_WRONLY) ? 'w' : 'r';
1335 my $handle = IO::Handle->new_from_fd($fd, $flagstr);
1336 return $handle if $handle;
1337 my $err = $!; # save error before closing the raw fd
1338 syscall(3, $fd); # close
1344 my ($dirfd, $name, $mode) = @_;
1345 return syscall(258, $dirfd, $name, $mode) == 0;