]>
git.proxmox.com Git - pve-common.git/blob - src/PVE/Tools.pm
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()
16 use Fcntl
qw(:DEFAULT :flock);
22 use String
::ShellQuote
;
23 use Time
::HiRes
qw(usleep gettimeofday tv_interval alarm);
25 # avoid warning when parsing long hex values with hex()
26 no warnings
'portable'; # Support for 64-bit ints required
47 my $pvelogdir = "/var/log/pve";
48 my $pvetaskdir = "$pvelogdir/tasks";
53 my $IPV4OCTET = "(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])";
54 our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)";
55 my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})";
56 my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))";
59 "(?:(?:" . "(?:$IPV6H16:){6})$IPV6LS32)|" .
60 "(?:(?:" . "::(?:$IPV6H16:){5})$IPV6LS32)|" .
61 "(?:(?:(?:" . "$IPV6H16)?::(?:$IPV6H16:){4})$IPV6LS32)|" .
62 "(?:(?:(?:(?:$IPV6H16:){0,1}$IPV6H16)?::(?:$IPV6H16:){3})$IPV6LS32)|" .
63 "(?:(?:(?:(?:$IPV6H16:){0,2}$IPV6H16)?::(?:$IPV6H16:){2})$IPV6LS32)|" .
64 "(?:(?:(?:(?:$IPV6H16:){0,3}$IPV6H16)?::(?:$IPV6H16:){1})$IPV6LS32)|" .
65 "(?:(?:(?:(?:$IPV6H16:){0,4}$IPV6H16)?::" . ")$IPV6LS32)|" .
66 "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" . ")$IPV6H16)|" .
67 "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" . ")))";
69 our $IPRE = "(?:$IPV4RE|$IPV6RE)";
71 use constant {CLONE_NEWNS
=> 0x00020000,
72 CLONE_NEWUTS
=> 0x04000000,
73 CLONE_NEWIPC
=> 0x08000000,
74 CLONE_NEWUSER
=> 0x10000000,
75 CLONE_NEWPID
=> 0x20000000,
76 CLONE_NEWNET
=> 0x40000000};
78 use constant O_PATH
=> 0x10000000;
80 sub run_with_timeout
{
81 my ($timeout, $code, @param) = @_;
83 die "got timeout\n" if $timeout <= 0;
85 my $prev_alarm = alarm 0; # suspend outer alarm early
92 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
93 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
94 local $SIG{__DIE__
}; # see SA bug 4631
98 eval { $res = &$code(@param); };
100 alarm(0); # avoid race conditions
109 # this shouldn't happen anymore?
110 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
117 # flock: we use one file handle per process, so lock file
118 # can be called multiple times and succeeds for the same process.
120 my $lock_handles = {};
123 my ($filename, $timeout, $shared, $code, @param) = @_;
125 $timeout = 10 if !$timeout;
127 my $mode = $shared ? LOCK_SH
: LOCK_EX
;
129 my $lock_func = sub {
130 if (!$lock_handles->{$$}->{$filename}) {
131 my $fh = new IO
::File
(">>$filename") ||
132 die "can't open file - $!\n";
133 $lock_handles->{$$}->{$filename} = { fh
=> $fh, refcount
=> 0};
136 if (!flock($lock_handles->{$$}->{$filename}->{fh
}, $mode|LOCK_NB
)) {
137 print STDERR
"trying to acquire lock...";
140 $success = flock($lock_handles->{$$}->{$filename}->{fh
}, $mode);
141 # try again on EINTR (see bug #273)
142 if ($success || ($! != EINTR
)) {
147 print STDERR
" failed\n";
148 die "can't acquire lock '$filename' - $!\n";
150 print STDERR
" OK\n";
152 $lock_handles->{$$}->{$filename}->{refcount
}++;
157 eval { run_with_timeout
($timeout, $lock_func); };
160 $err = "can't lock file '$filename' - $err";
162 eval { $res = &$code(@param) };
166 if (my $fh = $lock_handles->{$$}->{$filename}->{fh
}) {
167 my $refcount = --$lock_handles->{$$}->{$filename}->{refcount
};
168 if ($refcount <= 0) {
169 $lock_handles->{$$}->{$filename} = undef;
186 my ($filename, $timeout, $code, @param) = @_;
188 return lock_file_full
($filename, $timeout, 0, $code, @param);
191 sub file_set_contents
{
192 my ($filename, $data, $perm) = @_;
194 $perm = 0644 if !defined($perm);
196 my $tmpname = "$filename.tmp.$$";
199 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
200 die "unable to open file '$tmpname' - $!\n" if !$fh;
201 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
202 die "closing file '$tmpname' failed - $!\n" unless close $fh;
211 if (!rename($tmpname, $filename)) {
212 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
218 sub file_get_contents
{
219 my ($filename, $max) = @_;
221 my $fh = IO
::File-
>new($filename, "r") ||
222 die "can't open '$filename' - $!\n";
224 my $content = safe_read_from
($fh, $max);
232 my ($filename, $dst, $max, $perm) = @_;
234 file_set_contents
($dst, file_get_contents
($filename, $max), $perm);
237 sub file_read_firstline
{
240 my $fh = IO
::File-
>new ($filename, "r");
241 return undef if !$fh;
249 my ($fh, $max, $oneline) = @_;
251 $max = 32768 if !$max;
256 while ($count = sysread($fh, $input, 8192, $br)) {
258 die "input too long - aborting\n" if $br > $max;
259 if ($oneline && $input =~ m/^(.*)\n/) {
264 die "unable to read input - $!\n" if !defined($count);
269 # The $cmd parameter can be:
271 # This is generally executed by passing it to the shell with the -c option.
272 # However, it can be executed in one of two ways, depending on whether
273 # there's a pipe involved:
274 # *) with pipe: passed explicitly to bash -c, prefixed with:
276 # *) without a pipe: passed to perl's open3 which uses 'sh -c'
277 # (Note that this may result in two different syntax requirements!)
279 # -) an array of arguments (strings)
280 # Will be executed without interference from a shell. (Parameters are passed
281 # as is, no escape sequences of strings will be touched.)
282 # -) an array of arrays
283 # Each array represents a command, and each command's output is piped into
284 # the following command's standard input.
285 # For this a shell command string is created with pipe symbols between each
287 # Each command is a list of strings meant to end up in the final command
288 # unchanged. In order to achieve this, every argument is shell-quoted.
289 # Quoting can be disabled for a particular argument by turning it into a
290 # reference, this allows inserting arbitrary shell options.
291 # For instance: the $cmd [ [ 'echo', 'hello', \'>/dev/null' ] ] will not
292 # produce any output, while the $cmd [ [ 'echo', 'hello', '>/dev/null' ] ]
293 # will literally print: hello >/dev/null
295 my ($cmd, %param) = @_;
300 if (my $ref = ref($cmd)) {
301 if (ref($cmd->[0])) {
302 $cmdstr = 'set -o pipefail && ';
304 foreach my $command (@$cmd) {
305 # concatenate quoted parameters
306 # strings which are passed by reference are NOT shell quoted
307 $cmdstr .= $pipe . join(' ', map { ref($_) ?
$$_ : shellquote
($_) } @$command);
310 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmdstr" ];
312 $cmdstr = cmd2string
($cmd);
317 # see 'man bash' for option pipefail
318 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
341 foreach my $p (keys %param) {
342 if ($p eq 'timeout') {
343 $timeout = $param{$p};
344 } elsif ($p eq 'umask') {
345 $old_umask = umask($param{$p});
346 } elsif ($p eq 'errmsg') {
347 $errmsg = $param{$p};
348 } elsif ($p eq 'input') {
350 } elsif ($p eq 'output') {
351 $output = $param{$p};
352 } elsif ($p eq 'outfunc') {
353 $outfunc = $param{$p};
354 } elsif ($p eq 'errfunc') {
355 $errfunc = $param{$p};
356 } elsif ($p eq 'logfunc') {
357 $logfunc = $param{$p};
358 } elsif ($p eq 'afterfork') {
359 $afterfork = $param{$p};
360 } elsif ($p eq 'noerr') {
363 die "got unknown parameter '$p' for run_command\n";
368 my $origerrfunc = $errfunc;
372 &$origerrfunc("$laststderr\n");
374 print STDERR
"$laststderr\n" if $laststderr;
381 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
382 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
383 my $error = IO
::File-
>new();
385 # try to avoid locale related issues/warnings
386 my $lang = $param{lang
} || 'C';
391 local $ENV{LC_ALL
} = $lang;
393 # suppress LVM warnings like: "File descriptor 3 left open";
394 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
396 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
398 # if we pipe fron STDIN, open3 closes STDIN, so we we
399 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
400 # as soon as we open a new file.
401 # to avoid that we open /dev/null
402 if (!ref($writer) && !defined(fileno(STDIN
))) {
404 open(STDIN
, "</dev/null");
411 if ($orig_pid != $$) {
419 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
420 $oldtimeout = alarm($timeout) if $timeout;
422 &$afterfork() if $afterfork;
425 print $writer $input if defined $input;
429 my $select = new IO
::Select
;
430 $select->add($reader) if ref($reader);
431 $select->add($error);
436 my $starttime = time();
438 while ($select->count) {
439 my @handles = $select->can_read(1);
441 foreach my $h (@handles) {
443 my $count = sysread ($h, $buf, 4096);
444 if (!defined ($count)) {
450 $select->remove ($h) if !$count;
452 if ($outfunc || $logfunc) {
455 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
457 &$outfunc($line) if $outfunc;
458 &$logfunc($line) if $logfunc;
471 } elsif ($h eq $error) {
472 if ($errfunc || $logfunc) {
475 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
477 &$errfunc($line) if $errfunc;
478 &$logfunc($line) if $logfunc;
495 &$outfunc($outlog) if $outfunc && $outlog;
496 &$logfunc($outlog) if $logfunc && $outlog;
498 &$errfunc($errlog) if $errfunc && $errlog;
499 &$logfunc($errlog) if $logfunc && $errlog;
504 die "failed to execute\n";
505 } elsif (my $sig = ($? & 127)) {
506 die "got signal $sig\n";
507 } elsif ($exitcode = ($? >> 8)) {
508 if (!($exitcode == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
509 if ($errmsg && $laststderr) {
510 my $lerr = $laststderr;
514 die "exit code $exitcode\n";
525 if ($errmsg && $laststderr) {
526 &$errfunc(undef); # flush laststderr
529 umask ($old_umask) if defined($old_umask);
531 alarm($oldtimeout) if $oldtimeout;
534 if ($pid && ($err eq "got timeout\n")) {
537 die "command '$cmdstr' failed: $err";
541 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
544 die "command '$cmdstr' failed: $err";
552 my $listtxt = shift || '';
554 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
556 $listtxt =~ s/[,;]/ /g;
557 $listtxt =~ s/^\s+//;
559 my @data = split (/\s+/, $listtxt);
567 return $txt if !defined($txt);
575 # simple uri templates like "/vms/{vmid}"
576 sub template_replace
{
577 my ($tmpl, $data) = @_;
579 return $tmpl if !$tmpl;
582 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
584 $res .= ($data->{$3} || '-') if $2;
590 my ($filename, $fh, $data) = @_;
594 my $res = print $fh $data;
596 die "write to '$filename' failed\n" if !$res;
602 'at' => 'ftp.at.debian.org',
603 'au' => 'ftp.au.debian.org',
604 'be' => 'ftp.be.debian.org',
605 'bg' => 'ftp.bg.debian.org',
606 'br' => 'ftp.br.debian.org',
607 'ca' => 'ftp.ca.debian.org',
608 'ch' => 'ftp.ch.debian.org',
609 'cl' => 'ftp.cl.debian.org',
610 'cz' => 'ftp.cz.debian.org',
611 'de' => 'ftp.de.debian.org',
612 'dk' => 'ftp.dk.debian.org',
613 'ee' => 'ftp.ee.debian.org',
614 'es' => 'ftp.es.debian.org',
615 'fi' => 'ftp.fi.debian.org',
616 'fr' => 'ftp.fr.debian.org',
617 'gr' => 'ftp.gr.debian.org',
618 'hk' => 'ftp.hk.debian.org',
619 'hr' => 'ftp.hr.debian.org',
620 'hu' => 'ftp.hu.debian.org',
621 'ie' => 'ftp.ie.debian.org',
622 'is' => 'ftp.is.debian.org',
623 'it' => 'ftp.it.debian.org',
624 'jp' => 'ftp.jp.debian.org',
625 'kr' => 'ftp.kr.debian.org',
626 'mx' => 'ftp.mx.debian.org',
627 'nl' => 'ftp.nl.debian.org',
628 'no' => 'ftp.no.debian.org',
629 'nz' => 'ftp.nz.debian.org',
630 'pl' => 'ftp.pl.debian.org',
631 'pt' => 'ftp.pt.debian.org',
632 'ro' => 'ftp.ro.debian.org',
633 'ru' => 'ftp.ru.debian.org',
634 'se' => 'ftp.se.debian.org',
635 'si' => 'ftp.si.debian.org',
636 'sk' => 'ftp.sk.debian.org',
637 'tr' => 'ftp.tr.debian.org',
638 'tw' => 'ftp.tw.debian.org',
639 'gb' => 'ftp.uk.debian.org',
640 'us' => 'ftp.us.debian.org',
645 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
646 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
647 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
648 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
649 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
650 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
651 #'et' => [], # Ethopia or Estonia ??
652 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
653 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
654 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
655 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
656 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
657 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
658 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
659 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
660 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
661 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
662 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
663 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
664 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
665 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
666 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
667 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
668 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
669 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
670 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
671 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
672 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
673 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
674 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
676 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
679 my $kvmkeymaparray = [];
680 foreach my $lc (keys %$keymaphash) {
681 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
689 return $kvmkeymaparray;
693 my ($param, $key) = @_;
695 my $res = $param->{$key};
696 delete $param->{$key};
701 # Note: we use this to wait until vncterm/spiceterm is ready
702 sub wait_for_vnc_port
{
703 my ($port, $timeout) = @_;
705 $timeout = 5 if !$timeout;
707 my $starttime = [gettimeofday
];
710 while (($elapsed = tv_interval
($starttime)) < $timeout) {
711 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
712 while (defined (my $line = <$fh>)) {
713 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
714 if ($port == hex($2)) {
722 $sleeptime += 100000 if $sleeptime < 1000000;
729 sub next_unused_port
{
730 my ($range_start, $range_end, $family) = @_;
732 # We use a file to register allocated ports.
733 # Those registrations expires after $expiretime.
734 # We use this to avoid race conditions between
735 # allocation and use of ports.
737 my $filename = "/var/tmp/pve-reserved-ports";
746 if (my $fh = IO
::File-
>new ($filename, "r")) {
747 while (my $line = <$fh>) {
748 if ($line =~ m/^(\d+)\s(\d+)$/) {
749 my ($port, $timestamp) = ($1, $2);
750 if (($timestamp + $expiretime) > $ctime) {
751 $ports->{$port} = $timestamp; # not expired
759 for (my $p = $range_start; $p < $range_end; $p++) {
760 next if $ports->{$p}; # reserved
762 my $sock = IO
::Socket
::IP-
>new(Listen
=> 5,
767 GetAddrInfoFlags
=> 0);
772 $ports->{$p} = $ctime;
778 foreach my $p (keys %$ports) {
779 $data .= "$p $ports->{$p}\n";
782 file_set_contents
($filename, $data);
787 my $p = lock_file
($filename, 10, $code);
790 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
795 sub next_migrate_port
{
797 return next_unused_port
(60000, 60050, $family);
802 return next_unused_port
(5900, 6000, $family);
805 sub next_spice_port
{
807 return next_unused_port
(61000, 61099, $family);
810 # NOTE: NFS syscall can't be interrupted, so alarm does
811 # not work to provide timeouts.
812 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
813 # So fork() before using Filesys::Df
815 my ($path, $timeout) = @_;
823 my $pipe = IO
::Pipe-
>new();
825 if (!defined($child)) {
826 warn "fork failed: $!\n";
833 my $df = Filesys
::Df
::df
($path, 1);
834 print {$pipe} "$df->{blocks}\n$df->{used}\n$df->{bavail}\n";
846 my $readvalues = sub {
847 $res->{total
} = int(<$pipe>);
848 $res->{used
} = int(<$pipe>);
849 $res->{avail
} = int(<$pipe>);
852 run_with_timeout
($timeout, $readvalues);
856 kill('KILL', $child);
862 # We use this to uniquely identify a process.
863 # An 'Unique Process ID' has the following format:
864 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
869 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
870 # more that 8 characters for pstart
871 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
872 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
877 my ($upid, $noerr) = @_;
882 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
883 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
884 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]+):$/) {
886 $res->{pid
} = hex($3);
887 $res->{pstart
} = hex($4);
888 $res->{starttime
} = hex($5);
893 my $subdir = substr($5, 7, 8);
894 $filename = "$pvetaskdir/$subdir/$upid";
897 return undef if $noerr;
898 die "unable to parse worker upid '$upid'\n";
901 return wantarray ?
($res, $filename) : $res;
907 my ($task, $filename) = upid_decode
($upid);
909 my $dirname = dirname
($filename);
912 my $wwwid = getpwnam('www-data') ||
913 die "getpwnam failed";
917 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
918 die "unable to create output file '$filename' - $!\n";
919 chown $wwwid, -1, $outfh;
924 sub upid_read_status
{
927 my ($task, $filename) = upid_decode
($upid);
928 my $fh = IO
::File-
>new($filename, "r");
929 return "unable to open file - $!" if !$fh;
931 sysseek($fh, -$maxlen, 2);
933 my $br = sysread($fh, $readbuf, $maxlen);
936 return "unable to extract last line"
937 if $readbuf !~ m/\n?(.+)$/;
939 if ($line =~ m/^TASK OK$/) {
941 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
944 return "unexpected status";
947 return "unable to read tail (got $br bytes)";
950 # useful functions to store comments in config files
954 # all control and hi-bit characters, and ':'
955 my $unsafe = "^\x20-\x39\x3b-\x7e";
956 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
962 return Encode
::decode
("utf8", uri_unescape
($data));
965 sub decode_utf8_parameters
{
968 foreach my $p (qw(comment description firstname lastname)) {
969 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
975 sub random_ether_addr
{
977 my ($seconds, $microseconds) = gettimeofday
;
979 my $rand = Digest
::SHA
::sha1_hex
($$, rand(), $seconds, $microseconds);
981 # clear multicast, set local id
982 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
984 return sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
990 return String
::ShellQuote
::shell_quote
($str);
996 die "no arguments" if !$cmd;
998 return $cmd if !ref($cmd);
1001 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
1003 return join (' ', @qa);
1006 # split an shell argument string into an array,
1010 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
1014 my ($filename, $start, $limit, $filter) = @_;
1019 my $fh = IO
::File-
>new($filename, "r");
1022 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
1023 return ($count, $lines);
1026 $start = 0 if !$start;
1027 $limit = 50 if !$limit;
1032 # duplicate code, so that we do not slow down normal path
1033 while (defined($line = <$fh>)) {
1034 next if $line !~ m/$filter/;
1035 next if $count++ < $start;
1036 next if $limit <= 0;
1038 push @$lines, { n
=> $count, t
=> $line};
1042 while (defined($line = <$fh>)) {
1043 next if $count++ < $start;
1044 next if $limit <= 0;
1046 push @$lines, { n
=> $count, t
=> $line};
1053 # HACK: ExtJS store.guaranteeRange() does not like empty array
1057 push @$lines, { n
=> $count, t
=> "no content"};
1060 return ($count, $lines);
1064 my ($start, $limit, $since, $until) = @_;
1069 $start = 0 if !$start;
1070 $limit = 50 if !$limit;
1075 return if $count++ < $start;
1076 return if $limit <= 0;
1077 push @$lines, { n
=> int($count), t
=> $line};
1081 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1083 push @$cmd, '--since', $since if $since;
1084 push @$cmd, '--until', $until if $until;
1085 run_command
($cmd, outfunc
=> $parser);
1087 # HACK: ExtJS store.guaranteeRange() does not like empty array
1091 push @$lines, { n
=> $count, t
=> "no content"};
1094 return ($count, $lines);
1097 sub dir_glob_regex
{
1098 my ($dir, $regex) = @_;
1100 my $dh = IO
::Dir-
>new ($dir);
1101 return wantarray ?
() : undef if !$dh;
1103 while (defined(my $tmp = $dh->read)) {
1104 if (my @res = $tmp =~ m/^($regex)$/) {
1106 return wantarray ?
@res : $tmp;
1111 return wantarray ?
() : undef;
1114 sub dir_glob_foreach
{
1115 my ($dir, $regex, $func) = @_;
1117 my $dh = IO
::Dir-
>new ($dir);
1119 while (defined(my $tmp = $dh->read)) {
1120 if (my @res = $tmp =~ m/^($regex)$/) {
1127 sub assert_if_modified
{
1128 my ($digest1, $digest2) = @_;
1130 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1131 die "detected modified configuration - file changed by other user? Try again.\n";
1135 # Digest for short strings
1136 # like FNV32a, but we only return 31 bits (positive numbers)
1140 my $hval = 0x811c9dc5;
1142 foreach my $c (unpack('C*', $string)) {
1150 $hval = $hval & 0xffffffff;
1152 return $hval & 0x7fffffff;
1155 sub fnv31a_hex
{ return sprintf("%X", fnv31a
(@_)); }
1157 sub unpack_sockaddr_in46
{
1159 my $family = Socket
::sockaddr_family
($sin);
1160 my ($port, $host) = ($family == AF_INET6 ? Socket
::unpack_sockaddr_in6
($sin)
1161 : Socket
::unpack_sockaddr_in
($sin));
1162 return ($family, $port, $host);
1165 sub getaddrinfo_all
{
1166 my ($hostname, @opts) = @_;
1167 my %hints = ( flags
=> AI_V4MAPPED
| AI_ALL
,
1169 my ($err, @res) = Socket
::getaddrinfo
($hostname, '0', \
%hints);
1170 die "failed to get address info for: $hostname: $err\n" if $err;
1174 sub get_host_address_family
{
1175 my ($hostname, $socktype) = @_;
1176 my @res = getaddrinfo_all
($hostname, socktype
=> $socktype);
1177 return $res[0]->{family
};
1180 # Parses any sane kind of host, or host+port pair:
1181 # The port is always optional and thus may be undef.
1182 sub parse_host_and_port
{
1184 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1185 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1186 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1188 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1195 return 0 == syscall(272, $flags);
1199 my ($fileno, $nstype) = @_;
1200 return 0 == syscall(308, $fileno, $nstype);
1205 return 0 == syscall(306, $fileno);
1208 sub sync_mountpoint
{
1210 sysopen my $fd, $path, O_PATH
or die "failed to open $path: $!\n";
1211 my $result = syncfs
(fileno($fd));