]>
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);
14 use Fcntl
qw(:DEFAULT :flock);
20 use String
::ShellQuote
;
21 use Time
::HiRes
qw(usleep gettimeofday tv_interval alarm);
23 # avoid warning when parsing long hex values with hex()
24 no warnings
'portable'; # Support for 64-bit ints required
44 my $pvelogdir = "/var/log/pve";
45 my $pvetaskdir = "$pvelogdir/tasks";
50 my $IPV4OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
51 our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)";
52 my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})";
53 my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))";
56 "(?:(?:" . "(?:$IPV6H16:){6})$IPV6LS32)|" .
57 "(?:(?:" . "::(?:$IPV6H16:){5})$IPV6LS32)|" .
58 "(?:(?:(?:" . "$IPV6H16)?::(?:$IPV6H16:){4})$IPV6LS32)|" .
59 "(?:(?:(?:(?:$IPV6H16:){0,1}$IPV6H16)?::(?:$IPV6H16:){3})$IPV6LS32)|" .
60 "(?:(?:(?:(?:$IPV6H16:){0,2}$IPV6H16)?::(?:$IPV6H16:){2})$IPV6LS32)|" .
61 "(?:(?:(?:(?:$IPV6H16:){0,3}$IPV6H16)?::(?:$IPV6H16:){1})$IPV6LS32)|" .
62 "(?:(?:(?:(?:$IPV6H16:){0,4}$IPV6H16)?::" . ")$IPV6LS32)|" .
63 "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" . ")$IPV6H16)|" .
64 "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" . ")))";
66 sub run_with_timeout
{
67 my ($timeout, $code, @param) = @_;
69 die "got timeout\n" if $timeout <= 0;
71 my $prev_alarm = alarm 0; # suspend outer alarm early
78 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
79 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
80 local $SIG{__DIE__
}; # see SA bug 4631
84 eval { $res = &$code(@param); };
86 alarm(0); # avoid race conditions
95 # this shouldn't happen anymore?
96 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
103 # flock: we use one file handle per process, so lock file
104 # can be called multiple times and succeeds for the same process.
106 my $lock_handles = {};
109 my ($filename, $timeout, $shared, $code, @param) = @_;
111 $timeout = 10 if !$timeout;
113 my $mode = $shared ? LOCK_SH
: LOCK_EX
;
115 my $lock_func = sub {
116 if (!$lock_handles->{$$}->{$filename}) {
117 $lock_handles->{$$}->{$filename} = new IO
::File
(">>$filename") ||
118 die "can't open file - $!\n";
121 if (!flock ($lock_handles->{$$}->{$filename}, $mode|LOCK_NB
)) {
122 print STDERR
"trying to aquire lock...";
125 $success = flock($lock_handles->{$$}->{$filename}, $mode);
126 # try again on EINTR (see bug #273)
127 if ($success || ($! != EINTR
)) {
132 print STDERR
" failed\n";
133 die "can't aquire lock - $!\n";
135 print STDERR
" OK\n";
141 eval { run_with_timeout
($timeout, $lock_func); };
144 $err = "can't lock file '$filename' - $err";
146 eval { $res = &$code(@param) };
150 if (my $fh = $lock_handles->{$$}->{$filename}) {
151 $lock_handles->{$$}->{$filename} = undef;
167 my ($filename, $timeout, $code, @param) = @_;
169 return lock_file_full
($filename, $timeout, 0, $code, @param);
172 sub file_set_contents
{
173 my ($filename, $data, $perm) = @_;
175 $perm = 0644 if !defined($perm);
177 my $tmpname = "$filename.tmp.$$";
180 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
181 die "unable to open file '$tmpname' - $!\n" if !$fh;
182 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
183 die "closing file '$tmpname' failed - $!\n" unless close $fh;
192 if (!rename($tmpname, $filename)) {
193 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
199 sub file_get_contents
{
200 my ($filename, $max) = @_;
202 my $fh = IO
::File-
>new($filename, "r") ||
203 die "can't open '$filename' - $!\n";
205 my $content = safe_read_from
($fh, $max);
212 sub file_read_firstline
{
215 my $fh = IO
::File-
>new ($filename, "r");
216 return undef if !$fh;
224 my ($fh, $max, $oneline) = @_;
226 $max = 32768 if !$max;
231 while ($count = sysread($fh, $input, 8192, $br)) {
233 die "input too long - aborting\n" if $br > $max;
234 if ($oneline && $input =~ m/^(.*)\n/) {
239 die "unable to read input - $!\n" if !defined($count);
244 # The $cmd parameter can be:
246 # This is generally executed by passing it to the shell with the -c option.
247 # However, it can be executed in one of two ways, depending on whether
248 # there's a pipe involved:
249 # *) with pipe: passed explicitly to bash -c, prefixed with:
251 # *) without a pipe: passed to perl's open3 which uses 'sh -c'
252 # (Note that this may result in two different syntax requirements!)
254 # -) an array of arguments (strings)
255 # Will be executed without interference from a shell. (Parameters are passed
256 # as is, no escape sequences of strings will be touched.)
257 # -) an array of arrays
258 # Each array represents a command, and each command's output is piped into
259 # the following command's standard input.
260 # For this a shell command string is created with pipe symbols between each
262 # Each command is a list of strings meant to end up in the final command
263 # unchanged. In order to achieve this, every argument is shell-quoted.
264 # Quoting can be disabled for a particular argument by turning it into a
265 # reference, this allows inserting arbitrary shell options.
266 # For instance: the $cmd [ [ 'echo', 'hello', \'>/dev/null' ] ] will not
267 # produce any output, while the $cmd [ [ 'echo', 'hello', '>/dev/null' ] ]
268 # will literally print: hello >/dev/null
270 my ($cmd, %param) = @_;
275 if (my $ref = ref($cmd)) {
276 if (ref($cmd->[0])) {
277 $cmdstr = 'set -o pipefail && ';
279 foreach my $command (@$cmd) {
280 # concatenate quoted parameters
281 # strings which are passed by reference are NOT shell quoted
282 $cmdstr .= $pipe . join(' ', map { ref($_) ?
$$_ : shellquote
($_) } @$command);
285 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmdstr" ];
287 $cmdstr = cmd2string
($cmd);
292 # see 'man bash' for option pipefail
293 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
314 foreach my $p (keys %param) {
315 if ($p eq 'timeout') {
316 $timeout = $param{$p};
317 } elsif ($p eq 'umask') {
318 $old_umask = umask($param{$p});
319 } elsif ($p eq 'errmsg') {
320 $errmsg = $param{$p};
321 } elsif ($p eq 'input') {
323 } elsif ($p eq 'output') {
324 $output = $param{$p};
325 } elsif ($p eq 'outfunc') {
326 $outfunc = $param{$p};
327 } elsif ($p eq 'errfunc') {
328 $errfunc = $param{$p};
329 } elsif ($p eq 'logfunc') {
330 $logfunc = $param{$p};
331 } elsif ($p eq 'afterfork') {
332 $afterfork = $param{$p};
334 die "got unknown parameter '$p' for run_command\n";
339 my $origerrfunc = $errfunc;
343 &$origerrfunc("$laststderr\n");
345 print STDERR
"$laststderr\n" if $laststderr;
352 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
353 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
354 my $error = IO
::File-
>new();
356 # try to avoid locale related issues/warnings
357 my $lang = $param{lang
} || 'C';
362 local $ENV{LC_ALL
} = $lang;
364 # suppress LVM warnings like: "File descriptor 3 left open";
365 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
367 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
369 # if we pipe fron STDIN, open3 closes STDIN, so we we
370 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
371 # as soon as we open a new file.
372 # to avoid that we open /dev/null
373 if (!ref($writer) && !defined(fileno(STDIN
))) {
375 open(STDIN
, "</dev/null");
382 if ($orig_pid != $$) {
390 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
391 $oldtimeout = alarm($timeout) if $timeout;
393 &$afterfork() if $afterfork;
396 print $writer $input if defined $input;
400 my $select = new IO
::Select
;
401 $select->add($reader) if ref($reader);
402 $select->add($error);
407 my $starttime = time();
409 while ($select->count) {
410 my @handles = $select->can_read(1);
412 foreach my $h (@handles) {
414 my $count = sysread ($h, $buf, 4096);
415 if (!defined ($count)) {
421 $select->remove ($h) if !$count;
423 if ($outfunc || $logfunc) {
426 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
428 &$outfunc($line) if $outfunc;
429 &$logfunc($line) if $logfunc;
442 } elsif ($h eq $error) {
443 if ($errfunc || $logfunc) {
446 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
448 &$errfunc($line) if $errfunc;
449 &$logfunc($line) if $logfunc;
466 &$outfunc($outlog) if $outfunc && $outlog;
467 &$logfunc($outlog) if $logfunc && $outlog;
469 &$errfunc($errlog) if $errfunc && $errlog;
470 &$logfunc($errlog) if $logfunc && $errlog;
475 die "failed to execute\n";
476 } elsif (my $sig = ($? & 127)) {
477 die "got signal $sig\n";
478 } elsif (my $ec = ($? >> 8)) {
479 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
480 if ($errmsg && $laststderr) {
481 my $lerr = $laststderr;
485 die "exit code $ec\n";
496 if ($errmsg && $laststderr) {
497 &$errfunc(undef); # flush laststderr
500 umask ($old_umask) if defined($old_umask);
502 alarm($oldtimeout) if $oldtimeout;
505 if ($pid && ($err eq "got timeout\n")) {
508 die "command '$cmdstr' failed: $err";
512 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
515 die "command '$cmdstr' failed: $err";
523 my $listtxt = shift || '';
525 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
527 $listtxt =~ s/[,;]/ /g;
528 $listtxt =~ s/^\s+//;
530 my @data = split (/\s+/, $listtxt);
538 return $txt if !defined($txt);
546 # simple uri templates like "/vms/{vmid}"
547 sub template_replace
{
548 my ($tmpl, $data) = @_;
550 return $tmpl if !$tmpl;
553 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
555 $res .= ($data->{$3} || '-') if $2;
561 my ($filename, $fh, $data) = @_;
565 my $res = print $fh $data;
567 die "write to '$filename' failed\n" if !$res;
573 'at' => 'ftp.at.debian.org',
574 'au' => 'ftp.au.debian.org',
575 'be' => 'ftp.be.debian.org',
576 'bg' => 'ftp.bg.debian.org',
577 'br' => 'ftp.br.debian.org',
578 'ca' => 'ftp.ca.debian.org',
579 'ch' => 'ftp.ch.debian.org',
580 'cl' => 'ftp.cl.debian.org',
581 'cz' => 'ftp.cz.debian.org',
582 'de' => 'ftp.de.debian.org',
583 'dk' => 'ftp.dk.debian.org',
584 'ee' => 'ftp.ee.debian.org',
585 'es' => 'ftp.es.debian.org',
586 'fi' => 'ftp.fi.debian.org',
587 'fr' => 'ftp.fr.debian.org',
588 'gr' => 'ftp.gr.debian.org',
589 'hk' => 'ftp.hk.debian.org',
590 'hr' => 'ftp.hr.debian.org',
591 'hu' => 'ftp.hu.debian.org',
592 'ie' => 'ftp.ie.debian.org',
593 'is' => 'ftp.is.debian.org',
594 'it' => 'ftp.it.debian.org',
595 'jp' => 'ftp.jp.debian.org',
596 'kr' => 'ftp.kr.debian.org',
597 'mx' => 'ftp.mx.debian.org',
598 'nl' => 'ftp.nl.debian.org',
599 'no' => 'ftp.no.debian.org',
600 'nz' => 'ftp.nz.debian.org',
601 'pl' => 'ftp.pl.debian.org',
602 'pt' => 'ftp.pt.debian.org',
603 'ro' => 'ftp.ro.debian.org',
604 'ru' => 'ftp.ru.debian.org',
605 'se' => 'ftp.se.debian.org',
606 'si' => 'ftp.si.debian.org',
607 'sk' => 'ftp.sk.debian.org',
608 'tr' => 'ftp.tr.debian.org',
609 'tw' => 'ftp.tw.debian.org',
610 'gb' => 'ftp.uk.debian.org',
611 'us' => 'ftp.us.debian.org',
616 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
617 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
618 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
619 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
620 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
621 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
622 #'et' => [], # Ethopia or Estonia ??
623 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
624 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
625 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
626 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
627 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
628 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
629 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
630 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
631 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
632 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
633 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
634 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
635 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
636 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
637 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
638 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
639 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
640 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
641 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
642 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
643 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
644 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
645 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
647 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
650 my $kvmkeymaparray = [];
651 foreach my $lc (keys %$keymaphash) {
652 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
660 return $kvmkeymaparray;
664 my ($param, $key) = @_;
666 my $res = $param->{$key};
667 delete $param->{$key};
672 # Note: we use this to wait until vncterm/spiceterm is ready
673 sub wait_for_vnc_port
{
674 my ($port, $timeout) = @_;
676 $timeout = 5 if !$timeout;
678 my $starttime = [gettimeofday
];
681 while (($elapsed = tv_interval
($starttime)) < $timeout) {
682 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
683 while (defined (my $line = <$fh>)) {
684 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
685 if ($port == hex($2)) {
693 $sleeptime += 100000 if $sleeptime < 1000000;
700 sub next_unused_port
{
701 my ($range_start, $range_end, $family) = @_;
703 # We use a file to register allocated ports.
704 # Those registrations expires after $expiretime.
705 # We use this to avoid race conditions between
706 # allocation and use of ports.
708 my $filename = "/var/tmp/pve-reserved-ports";
717 if (my $fh = IO
::File-
>new ($filename, "r")) {
718 while (my $line = <$fh>) {
719 if ($line =~ m/^(\d+)\s(\d+)$/) {
720 my ($port, $timestamp) = ($1, $2);
721 if (($timestamp + $expiretime) > $ctime) {
722 $ports->{$port} = $timestamp; # not expired
730 for (my $p = $range_start; $p < $range_end; $p++) {
731 next if $ports->{$p}; # reserved
733 my $sock = IO
::Socket
::IP-
>new(Listen
=> 5,
738 GetAddrInfoFlags
=> 0);
743 $ports->{$p} = $ctime;
749 foreach my $p (keys %$ports) {
750 $data .= "$p $ports->{$p}\n";
753 file_set_contents
($filename, $data);
758 my $p = lock_file
($filename, 10, $code);
761 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
766 sub next_migrate_port
{
768 return next_unused_port
(60000, 60050, $family);
773 return next_unused_port
(5900, 6000, $family);
776 sub next_spice_port
{
778 return next_unused_port
(61000, 61099, $family);
781 # NOTE: NFS syscall can't be interrupted, so alarm does
782 # not work to provide timeouts.
783 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
784 # So the spawn external 'df' process instead of using
785 # Filesys::Df (which uses statfs syscall)
787 my ($path, $timeout) = @_;
789 my $cmd = [ 'df', '-P', '-B', '1', $path];
799 if (my ($fsid, $total, $used, $avail) = $line =~
800 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
808 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
815 # We use this to uniquely identify a process.
816 # An 'Unique Process ID' has the following format:
817 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
822 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
823 # more that 8 characters for pstart
824 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
825 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
830 my ($upid, $noerr) = @_;
835 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
836 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
837 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]+):$/) {
839 $res->{pid
} = hex($3);
840 $res->{pstart
} = hex($4);
841 $res->{starttime
} = hex($5);
846 my $subdir = substr($5, 7, 8);
847 $filename = "$pvetaskdir/$subdir/$upid";
850 return undef if $noerr;
851 die "unable to parse worker upid '$upid'\n";
854 return wantarray ?
($res, $filename) : $res;
860 my ($task, $filename) = upid_decode
($upid);
862 my $dirname = dirname
($filename);
865 my $wwwid = getpwnam('www-data') ||
866 die "getpwnam failed";
870 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
871 die "unable to create output file '$filename' - $!\n";
872 chown $wwwid, -1, $outfh;
877 sub upid_read_status
{
880 my ($task, $filename) = upid_decode
($upid);
881 my $fh = IO
::File-
>new($filename, "r");
882 return "unable to open file - $!" if !$fh;
884 sysseek($fh, -$maxlen, 2);
886 my $br = sysread($fh, $readbuf, $maxlen);
889 return "unable to extract last line"
890 if $readbuf !~ m/\n?(.+)$/;
892 if ($line =~ m/^TASK OK$/) {
894 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
897 return "unexpected status";
900 return "unable to read tail (got $br bytes)";
903 # useful functions to store comments in config files
907 # all control and hi-bit characters, and ':'
908 my $unsafe = "^\x20-\x39\x3b-\x7e";
909 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
915 return Encode
::decode
("utf8", uri_unescape
($data));
918 sub decode_utf8_parameters
{
921 foreach my $p (qw(comment description firstname lastname)) {
922 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
928 sub random_ether_addr
{
930 my ($seconds, $microseconds) = gettimeofday
;
932 my $rand = Digest
::SHA
::sha1_hex
($$, rand(), $seconds, $microseconds);
935 for (my $i = 0; $i < 6; $i++) {
936 my $ss = hex(substr($rand, $i*2, 2));
938 $ss &= 0xfe; # clear multicast
939 $ss |= 2; # set local id
941 $ss = sprintf("%02X", $ss);
956 return String
::ShellQuote
::shell_quote
($str);
962 die "no arguments" if !$cmd;
964 return $cmd if !ref($cmd);
967 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
969 return join (' ', @qa);
972 # split an shell argument string into an array,
976 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
980 my ($filename, $start, $limit, $filter) = @_;
985 my $fh = IO
::File-
>new($filename, "r");
988 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
989 return ($count, $lines);
992 $start = 0 if !$start;
993 $limit = 50 if !$limit;
998 # duplicate code, so that we do not slow down normal path
999 while (defined($line = <$fh>)) {
1000 next if $line !~ m/$filter/;
1001 next if $count++ < $start;
1002 next if $limit <= 0;
1004 push @$lines, { n
=> $count, t
=> $line};
1008 while (defined($line = <$fh>)) {
1009 next if $count++ < $start;
1010 next if $limit <= 0;
1012 push @$lines, { n
=> $count, t
=> $line};
1019 # HACK: ExtJS store.guaranteeRange() does not like empty array
1023 push @$lines, { n
=> $count, t
=> "no content"};
1026 return ($count, $lines);
1030 my ($start, $limit, $filter) = @_;
1035 $start = 0 if !$start;
1036 $limit = 50 if !$limit;
1041 return if $count++ < $start;
1042 return if $limit <= 0;
1043 push @$lines, { n
=> int($count), t
=> $line};
1047 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1048 run_command
($cmd, outfunc
=> $parser);
1050 # HACK: ExtJS store.guaranteeRange() does not like empty array
1054 push @$lines, { n
=> $count, t
=> "no content"};
1057 return ($count, $lines);
1060 sub dir_glob_regex
{
1061 my ($dir, $regex) = @_;
1063 my $dh = IO
::Dir-
>new ($dir);
1064 return wantarray ?
() : undef if !$dh;
1066 while (defined(my $tmp = $dh->read)) {
1067 if (my @res = $tmp =~ m/^($regex)$/) {
1069 return wantarray ?
@res : $tmp;
1074 return wantarray ?
() : undef;
1077 sub dir_glob_foreach
{
1078 my ($dir, $regex, $func) = @_;
1080 my $dh = IO
::Dir-
>new ($dir);
1082 while (defined(my $tmp = $dh->read)) {
1083 if (my @res = $tmp =~ m/^($regex)$/) {
1090 sub assert_if_modified
{
1091 my ($digest1, $digest2) = @_;
1093 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1094 die "detected modified configuration - file changed by other user? Try again.\n";
1098 # Digest for short strings
1099 # like FNV32a, but we only return 31 bits (positive numbers)
1103 my $hval = 0x811c9dc5;
1105 foreach my $c (unpack('C*', $string)) {
1113 $hval = $hval & 0xffffffff;
1115 return $hval & 0x7fffffff;
1118 sub fnv31a_hex
{ return sprintf("%X", fnv31a
(@_)); }
1120 sub unpack_sockaddr_in46
{
1122 my $family = Socket
::sockaddr_family
($sin);
1123 my ($port, $host) = ($family == AF_INET6 ? Socket
::unpack_sockaddr_in6
($sin)
1124 : Socket
::unpack_sockaddr_in
($sin));
1125 return ($family, $port, $host);
1128 sub getaddrinfo_all
{
1129 my ($hostname, @opts) = @_;
1130 my %hints = ( flags
=> AI_V4MAPPED
| AI_ALL
,
1132 my ($err, @res) = Socket
::getaddrinfo
($hostname, '0', \
%hints);
1133 die "failed to get address info for: $hostname: $err\n" if $err;
1137 sub get_host_address_family
{
1138 my ($hostname, $socktype) = @_;
1139 my @res = getaddrinfo_all
($hostname, socktype
=> $socktype);
1140 return $res[0]->{family
};
1143 # Parses any sane kind of host, or host+port pair:
1144 # The port is always optional and thus may be undef.
1145 sub parse_host_and_port
{
1147 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1148 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1149 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1151 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests