]>
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 use constant (CLONE_NEWNS
=> 0x00020000,
67 CLONE_NEWUTS
=> 0x04000000,
68 CLONE_NEWIPC
=> 0x08000000,
69 CLONE_NEWUSER
=> 0x10000000,
70 CLONE_NEWPID
=> 0x20000000,
71 CLONE_NEWNET
=> 0x40000000);
73 sub run_with_timeout
{
74 my ($timeout, $code, @param) = @_;
76 die "got timeout\n" if $timeout <= 0;
78 my $prev_alarm = alarm 0; # suspend outer alarm early
85 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
86 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
87 local $SIG{__DIE__
}; # see SA bug 4631
91 eval { $res = &$code(@param); };
93 alarm(0); # avoid race conditions
102 # this shouldn't happen anymore?
103 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
110 # flock: we use one file handle per process, so lock file
111 # can be called multiple times and succeeds for the same process.
113 my $lock_handles = {};
116 my ($filename, $timeout, $shared, $code, @param) = @_;
118 $timeout = 10 if !$timeout;
120 my $mode = $shared ? LOCK_SH
: LOCK_EX
;
122 my $lock_func = sub {
123 if (!$lock_handles->{$$}->{$filename}) {
124 $lock_handles->{$$}->{$filename} = new IO
::File
(">>$filename") ||
125 die "can't open file - $!\n";
128 if (!flock ($lock_handles->{$$}->{$filename}, $mode|LOCK_NB
)) {
129 print STDERR
"trying to aquire lock...";
132 $success = flock($lock_handles->{$$}->{$filename}, $mode);
133 # try again on EINTR (see bug #273)
134 if ($success || ($! != EINTR
)) {
139 print STDERR
" failed\n";
140 die "can't aquire lock - $!\n";
142 print STDERR
" OK\n";
148 eval { run_with_timeout
($timeout, $lock_func); };
151 $err = "can't lock file '$filename' - $err";
153 eval { $res = &$code(@param) };
157 if (my $fh = $lock_handles->{$$}->{$filename}) {
158 $lock_handles->{$$}->{$filename} = undef;
174 my ($filename, $timeout, $code, @param) = @_;
176 return lock_file_full
($filename, $timeout, 0, $code, @param);
179 sub file_set_contents
{
180 my ($filename, $data, $perm) = @_;
182 $perm = 0644 if !defined($perm);
184 my $tmpname = "$filename.tmp.$$";
187 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
188 die "unable to open file '$tmpname' - $!\n" if !$fh;
189 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
190 die "closing file '$tmpname' failed - $!\n" unless close $fh;
199 if (!rename($tmpname, $filename)) {
200 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
206 sub file_get_contents
{
207 my ($filename, $max) = @_;
209 my $fh = IO
::File-
>new($filename, "r") ||
210 die "can't open '$filename' - $!\n";
212 my $content = safe_read_from
($fh, $max);
219 sub file_read_firstline
{
222 my $fh = IO
::File-
>new ($filename, "r");
223 return undef if !$fh;
231 my ($fh, $max, $oneline) = @_;
233 $max = 32768 if !$max;
238 while ($count = sysread($fh, $input, 8192, $br)) {
240 die "input too long - aborting\n" if $br > $max;
241 if ($oneline && $input =~ m/^(.*)\n/) {
246 die "unable to read input - $!\n" if !defined($count);
251 # The $cmd parameter can be:
253 # This is generally executed by passing it to the shell with the -c option.
254 # However, it can be executed in one of two ways, depending on whether
255 # there's a pipe involved:
256 # *) with pipe: passed explicitly to bash -c, prefixed with:
258 # *) without a pipe: passed to perl's open3 which uses 'sh -c'
259 # (Note that this may result in two different syntax requirements!)
261 # -) an array of arguments (strings)
262 # Will be executed without interference from a shell. (Parameters are passed
263 # as is, no escape sequences of strings will be touched.)
264 # -) an array of arrays
265 # Each array represents a command, and each command's output is piped into
266 # the following command's standard input.
267 # For this a shell command string is created with pipe symbols between each
269 # Each command is a list of strings meant to end up in the final command
270 # unchanged. In order to achieve this, every argument is shell-quoted.
271 # Quoting can be disabled for a particular argument by turning it into a
272 # reference, this allows inserting arbitrary shell options.
273 # For instance: the $cmd [ [ 'echo', 'hello', \'>/dev/null' ] ] will not
274 # produce any output, while the $cmd [ [ 'echo', 'hello', '>/dev/null' ] ]
275 # will literally print: hello >/dev/null
277 my ($cmd, %param) = @_;
282 if (my $ref = ref($cmd)) {
283 if (ref($cmd->[0])) {
284 $cmdstr = 'set -o pipefail && ';
286 foreach my $command (@$cmd) {
287 # concatenate quoted parameters
288 # strings which are passed by reference are NOT shell quoted
289 $cmdstr .= $pipe . join(' ', map { ref($_) ?
$$_ : shellquote
($_) } @$command);
292 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmdstr" ];
294 $cmdstr = cmd2string
($cmd);
299 # see 'man bash' for option pipefail
300 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
321 foreach my $p (keys %param) {
322 if ($p eq 'timeout') {
323 $timeout = $param{$p};
324 } elsif ($p eq 'umask') {
325 $old_umask = umask($param{$p});
326 } elsif ($p eq 'errmsg') {
327 $errmsg = $param{$p};
328 } elsif ($p eq 'input') {
330 } elsif ($p eq 'output') {
331 $output = $param{$p};
332 } elsif ($p eq 'outfunc') {
333 $outfunc = $param{$p};
334 } elsif ($p eq 'errfunc') {
335 $errfunc = $param{$p};
336 } elsif ($p eq 'logfunc') {
337 $logfunc = $param{$p};
338 } elsif ($p eq 'afterfork') {
339 $afterfork = $param{$p};
341 die "got unknown parameter '$p' for run_command\n";
346 my $origerrfunc = $errfunc;
350 &$origerrfunc("$laststderr\n");
352 print STDERR
"$laststderr\n" if $laststderr;
359 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
360 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
361 my $error = IO
::File-
>new();
363 # try to avoid locale related issues/warnings
364 my $lang = $param{lang
} || 'C';
369 local $ENV{LC_ALL
} = $lang;
371 # suppress LVM warnings like: "File descriptor 3 left open";
372 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
374 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
376 # if we pipe fron STDIN, open3 closes STDIN, so we we
377 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
378 # as soon as we open a new file.
379 # to avoid that we open /dev/null
380 if (!ref($writer) && !defined(fileno(STDIN
))) {
382 open(STDIN
, "</dev/null");
389 if ($orig_pid != $$) {
397 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
398 $oldtimeout = alarm($timeout) if $timeout;
400 &$afterfork() if $afterfork;
403 print $writer $input if defined $input;
407 my $select = new IO
::Select
;
408 $select->add($reader) if ref($reader);
409 $select->add($error);
414 my $starttime = time();
416 while ($select->count) {
417 my @handles = $select->can_read(1);
419 foreach my $h (@handles) {
421 my $count = sysread ($h, $buf, 4096);
422 if (!defined ($count)) {
428 $select->remove ($h) if !$count;
430 if ($outfunc || $logfunc) {
433 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
435 &$outfunc($line) if $outfunc;
436 &$logfunc($line) if $logfunc;
449 } elsif ($h eq $error) {
450 if ($errfunc || $logfunc) {
453 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
455 &$errfunc($line) if $errfunc;
456 &$logfunc($line) if $logfunc;
473 &$outfunc($outlog) if $outfunc && $outlog;
474 &$logfunc($outlog) if $logfunc && $outlog;
476 &$errfunc($errlog) if $errfunc && $errlog;
477 &$logfunc($errlog) if $logfunc && $errlog;
482 die "failed to execute\n";
483 } elsif (my $sig = ($? & 127)) {
484 die "got signal $sig\n";
485 } elsif (my $ec = ($? >> 8)) {
486 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
487 if ($errmsg && $laststderr) {
488 my $lerr = $laststderr;
492 die "exit code $ec\n";
503 if ($errmsg && $laststderr) {
504 &$errfunc(undef); # flush laststderr
507 umask ($old_umask) if defined($old_umask);
509 alarm($oldtimeout) if $oldtimeout;
512 if ($pid && ($err eq "got timeout\n")) {
515 die "command '$cmdstr' failed: $err";
519 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
522 die "command '$cmdstr' failed: $err";
530 my $listtxt = shift || '';
532 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
534 $listtxt =~ s/[,;]/ /g;
535 $listtxt =~ s/^\s+//;
537 my @data = split (/\s+/, $listtxt);
545 return $txt if !defined($txt);
553 # simple uri templates like "/vms/{vmid}"
554 sub template_replace
{
555 my ($tmpl, $data) = @_;
557 return $tmpl if !$tmpl;
560 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
562 $res .= ($data->{$3} || '-') if $2;
568 my ($filename, $fh, $data) = @_;
572 my $res = print $fh $data;
574 die "write to '$filename' failed\n" if !$res;
580 'at' => 'ftp.at.debian.org',
581 'au' => 'ftp.au.debian.org',
582 'be' => 'ftp.be.debian.org',
583 'bg' => 'ftp.bg.debian.org',
584 'br' => 'ftp.br.debian.org',
585 'ca' => 'ftp.ca.debian.org',
586 'ch' => 'ftp.ch.debian.org',
587 'cl' => 'ftp.cl.debian.org',
588 'cz' => 'ftp.cz.debian.org',
589 'de' => 'ftp.de.debian.org',
590 'dk' => 'ftp.dk.debian.org',
591 'ee' => 'ftp.ee.debian.org',
592 'es' => 'ftp.es.debian.org',
593 'fi' => 'ftp.fi.debian.org',
594 'fr' => 'ftp.fr.debian.org',
595 'gr' => 'ftp.gr.debian.org',
596 'hk' => 'ftp.hk.debian.org',
597 'hr' => 'ftp.hr.debian.org',
598 'hu' => 'ftp.hu.debian.org',
599 'ie' => 'ftp.ie.debian.org',
600 'is' => 'ftp.is.debian.org',
601 'it' => 'ftp.it.debian.org',
602 'jp' => 'ftp.jp.debian.org',
603 'kr' => 'ftp.kr.debian.org',
604 'mx' => 'ftp.mx.debian.org',
605 'nl' => 'ftp.nl.debian.org',
606 'no' => 'ftp.no.debian.org',
607 'nz' => 'ftp.nz.debian.org',
608 'pl' => 'ftp.pl.debian.org',
609 'pt' => 'ftp.pt.debian.org',
610 'ro' => 'ftp.ro.debian.org',
611 'ru' => 'ftp.ru.debian.org',
612 'se' => 'ftp.se.debian.org',
613 'si' => 'ftp.si.debian.org',
614 'sk' => 'ftp.sk.debian.org',
615 'tr' => 'ftp.tr.debian.org',
616 'tw' => 'ftp.tw.debian.org',
617 'gb' => 'ftp.uk.debian.org',
618 'us' => 'ftp.us.debian.org',
623 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
624 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
625 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
626 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
627 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
628 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
629 #'et' => [], # Ethopia or Estonia ??
630 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
631 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
632 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
633 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
634 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
635 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
636 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
637 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
638 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
639 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
640 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
641 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
642 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
643 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
644 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
645 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
646 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
647 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
648 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
649 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
650 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
651 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
652 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
654 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
657 my $kvmkeymaparray = [];
658 foreach my $lc (keys %$keymaphash) {
659 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
667 return $kvmkeymaparray;
671 my ($param, $key) = @_;
673 my $res = $param->{$key};
674 delete $param->{$key};
679 # Note: we use this to wait until vncterm/spiceterm is ready
680 sub wait_for_vnc_port
{
681 my ($port, $timeout) = @_;
683 $timeout = 5 if !$timeout;
685 my $starttime = [gettimeofday
];
688 while (($elapsed = tv_interval
($starttime)) < $timeout) {
689 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
690 while (defined (my $line = <$fh>)) {
691 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
692 if ($port == hex($2)) {
700 $sleeptime += 100000 if $sleeptime < 1000000;
707 sub next_unused_port
{
708 my ($range_start, $range_end, $family) = @_;
710 # We use a file to register allocated ports.
711 # Those registrations expires after $expiretime.
712 # We use this to avoid race conditions between
713 # allocation and use of ports.
715 my $filename = "/var/tmp/pve-reserved-ports";
724 if (my $fh = IO
::File-
>new ($filename, "r")) {
725 while (my $line = <$fh>) {
726 if ($line =~ m/^(\d+)\s(\d+)$/) {
727 my ($port, $timestamp) = ($1, $2);
728 if (($timestamp + $expiretime) > $ctime) {
729 $ports->{$port} = $timestamp; # not expired
737 for (my $p = $range_start; $p < $range_end; $p++) {
738 next if $ports->{$p}; # reserved
740 my $sock = IO
::Socket
::IP-
>new(Listen
=> 5,
745 GetAddrInfoFlags
=> 0);
750 $ports->{$p} = $ctime;
756 foreach my $p (keys %$ports) {
757 $data .= "$p $ports->{$p}\n";
760 file_set_contents
($filename, $data);
765 my $p = lock_file
($filename, 10, $code);
768 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
773 sub next_migrate_port
{
775 return next_unused_port
(60000, 60050, $family);
780 return next_unused_port
(5900, 6000, $family);
783 sub next_spice_port
{
785 return next_unused_port
(61000, 61099, $family);
788 # NOTE: NFS syscall can't be interrupted, so alarm does
789 # not work to provide timeouts.
790 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
791 # So the spawn external 'df' process instead of using
792 # Filesys::Df (which uses statfs syscall)
794 my ($path, $timeout) = @_;
796 my $cmd = [ 'df', '-P', '-B', '1', $path];
806 if (my ($fsid, $total, $used, $avail) = $line =~
807 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
815 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
822 # We use this to uniquely identify a process.
823 # An 'Unique Process ID' has the following format:
824 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
829 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
830 # more that 8 characters for pstart
831 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
832 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
837 my ($upid, $noerr) = @_;
842 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
843 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
844 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]+):$/) {
846 $res->{pid
} = hex($3);
847 $res->{pstart
} = hex($4);
848 $res->{starttime
} = hex($5);
853 my $subdir = substr($5, 7, 8);
854 $filename = "$pvetaskdir/$subdir/$upid";
857 return undef if $noerr;
858 die "unable to parse worker upid '$upid'\n";
861 return wantarray ?
($res, $filename) : $res;
867 my ($task, $filename) = upid_decode
($upid);
869 my $dirname = dirname
($filename);
872 my $wwwid = getpwnam('www-data') ||
873 die "getpwnam failed";
877 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
878 die "unable to create output file '$filename' - $!\n";
879 chown $wwwid, -1, $outfh;
884 sub upid_read_status
{
887 my ($task, $filename) = upid_decode
($upid);
888 my $fh = IO
::File-
>new($filename, "r");
889 return "unable to open file - $!" if !$fh;
891 sysseek($fh, -$maxlen, 2);
893 my $br = sysread($fh, $readbuf, $maxlen);
896 return "unable to extract last line"
897 if $readbuf !~ m/\n?(.+)$/;
899 if ($line =~ m/^TASK OK$/) {
901 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
904 return "unexpected status";
907 return "unable to read tail (got $br bytes)";
910 # useful functions to store comments in config files
914 # all control and hi-bit characters, and ':'
915 my $unsafe = "^\x20-\x39\x3b-\x7e";
916 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
922 return Encode
::decode
("utf8", uri_unescape
($data));
925 sub decode_utf8_parameters
{
928 foreach my $p (qw(comment description firstname lastname)) {
929 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
935 sub random_ether_addr
{
937 my ($seconds, $microseconds) = gettimeofday
;
939 my $rand = Digest
::SHA
::sha1_hex
($$, rand(), $seconds, $microseconds);
942 for (my $i = 0; $i < 6; $i++) {
943 my $ss = hex(substr($rand, $i*2, 2));
945 $ss &= 0xfe; # clear multicast
946 $ss |= 2; # set local id
948 $ss = sprintf("%02X", $ss);
963 return String
::ShellQuote
::shell_quote
($str);
969 die "no arguments" if !$cmd;
971 return $cmd if !ref($cmd);
974 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
976 return join (' ', @qa);
979 # split an shell argument string into an array,
983 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
987 my ($filename, $start, $limit, $filter) = @_;
992 my $fh = IO
::File-
>new($filename, "r");
995 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
996 return ($count, $lines);
999 $start = 0 if !$start;
1000 $limit = 50 if !$limit;
1005 # duplicate code, so that we do not slow down normal path
1006 while (defined($line = <$fh>)) {
1007 next if $line !~ m/$filter/;
1008 next if $count++ < $start;
1009 next if $limit <= 0;
1011 push @$lines, { n
=> $count, t
=> $line};
1015 while (defined($line = <$fh>)) {
1016 next if $count++ < $start;
1017 next if $limit <= 0;
1019 push @$lines, { n
=> $count, t
=> $line};
1026 # HACK: ExtJS store.guaranteeRange() does not like empty array
1030 push @$lines, { n
=> $count, t
=> "no content"};
1033 return ($count, $lines);
1037 my ($start, $limit, $filter) = @_;
1042 $start = 0 if !$start;
1043 $limit = 50 if !$limit;
1048 return if $count++ < $start;
1049 return if $limit <= 0;
1050 push @$lines, { n
=> int($count), t
=> $line};
1054 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1055 run_command
($cmd, outfunc
=> $parser);
1057 # HACK: ExtJS store.guaranteeRange() does not like empty array
1061 push @$lines, { n
=> $count, t
=> "no content"};
1064 return ($count, $lines);
1067 sub dir_glob_regex
{
1068 my ($dir, $regex) = @_;
1070 my $dh = IO
::Dir-
>new ($dir);
1071 return wantarray ?
() : undef if !$dh;
1073 while (defined(my $tmp = $dh->read)) {
1074 if (my @res = $tmp =~ m/^($regex)$/) {
1076 return wantarray ?
@res : $tmp;
1081 return wantarray ?
() : undef;
1084 sub dir_glob_foreach
{
1085 my ($dir, $regex, $func) = @_;
1087 my $dh = IO
::Dir-
>new ($dir);
1089 while (defined(my $tmp = $dh->read)) {
1090 if (my @res = $tmp =~ m/^($regex)$/) {
1097 sub assert_if_modified
{
1098 my ($digest1, $digest2) = @_;
1100 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1101 die "detected modified configuration - file changed by other user? Try again.\n";
1105 # Digest for short strings
1106 # like FNV32a, but we only return 31 bits (positive numbers)
1110 my $hval = 0x811c9dc5;
1112 foreach my $c (unpack('C*', $string)) {
1120 $hval = $hval & 0xffffffff;
1122 return $hval & 0x7fffffff;
1125 sub fnv31a_hex
{ return sprintf("%X", fnv31a
(@_)); }
1127 sub unpack_sockaddr_in46
{
1129 my $family = Socket
::sockaddr_family
($sin);
1130 my ($port, $host) = ($family == AF_INET6 ? Socket
::unpack_sockaddr_in6
($sin)
1131 : Socket
::unpack_sockaddr_in
($sin));
1132 return ($family, $port, $host);
1135 sub getaddrinfo_all
{
1136 my ($hostname, @opts) = @_;
1137 my %hints = ( flags
=> AI_V4MAPPED
| AI_ALL
,
1139 my ($err, @res) = Socket
::getaddrinfo
($hostname, '0', \
%hints);
1140 die "failed to get address info for: $hostname: $err\n" if $err;
1144 sub get_host_address_family
{
1145 my ($hostname, $socktype) = @_;
1146 my @res = getaddrinfo_all
($hostname, socktype
=> $socktype);
1147 return $res[0]->{family
};
1150 # Parses any sane kind of host, or host+port pair:
1151 # The port is always optional and thus may be undef.
1152 sub parse_host_and_port
{
1154 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1155 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1156 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1158 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1165 syscall 272, $flags;