]>
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]|(?:2[0-4]|1[0-9]|[1-9])?[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 our $IPRE = "(?:$IPV4RE|$IPV6RE)";
68 use constant (CLONE_NEWNS
=> 0x00020000,
69 CLONE_NEWUTS
=> 0x04000000,
70 CLONE_NEWIPC
=> 0x08000000,
71 CLONE_NEWUSER
=> 0x10000000,
72 CLONE_NEWPID
=> 0x20000000,
73 CLONE_NEWNET
=> 0x40000000);
75 sub run_with_timeout
{
76 my ($timeout, $code, @param) = @_;
78 die "got timeout\n" if $timeout <= 0;
80 my $prev_alarm = alarm 0; # suspend outer alarm early
87 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
88 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
89 local $SIG{__DIE__
}; # see SA bug 4631
93 eval { $res = &$code(@param); };
95 alarm(0); # avoid race conditions
104 # this shouldn't happen anymore?
105 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
112 # flock: we use one file handle per process, so lock file
113 # can be called multiple times and succeeds for the same process.
115 my $lock_handles = {};
118 my ($filename, $timeout, $shared, $code, @param) = @_;
120 $timeout = 10 if !$timeout;
122 my $mode = $shared ? LOCK_SH
: LOCK_EX
;
124 my $lock_func = sub {
125 if (!$lock_handles->{$$}->{$filename}) {
126 $lock_handles->{$$}->{$filename} = new IO
::File
(">>$filename") ||
127 die "can't open file - $!\n";
130 if (!flock ($lock_handles->{$$}->{$filename}, $mode|LOCK_NB
)) {
131 print STDERR
"trying to aquire lock...";
134 $success = flock($lock_handles->{$$}->{$filename}, $mode);
135 # try again on EINTR (see bug #273)
136 if ($success || ($! != EINTR
)) {
141 print STDERR
" failed\n";
142 die "can't aquire lock - $!\n";
144 print STDERR
" OK\n";
150 eval { run_with_timeout
($timeout, $lock_func); };
153 $err = "can't lock file '$filename' - $err";
155 eval { $res = &$code(@param) };
159 if (my $fh = $lock_handles->{$$}->{$filename}) {
160 $lock_handles->{$$}->{$filename} = undef;
176 my ($filename, $timeout, $code, @param) = @_;
178 return lock_file_full
($filename, $timeout, 0, $code, @param);
181 sub file_set_contents
{
182 my ($filename, $data, $perm) = @_;
184 $perm = 0644 if !defined($perm);
186 my $tmpname = "$filename.tmp.$$";
189 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
190 die "unable to open file '$tmpname' - $!\n" if !$fh;
191 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
192 die "closing file '$tmpname' failed - $!\n" unless close $fh;
201 if (!rename($tmpname, $filename)) {
202 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
208 sub file_get_contents
{
209 my ($filename, $max) = @_;
211 my $fh = IO
::File-
>new($filename, "r") ||
212 die "can't open '$filename' - $!\n";
214 my $content = safe_read_from
($fh, $max);
221 sub file_read_firstline
{
224 my $fh = IO
::File-
>new ($filename, "r");
225 return undef if !$fh;
233 my ($fh, $max, $oneline) = @_;
235 $max = 32768 if !$max;
240 while ($count = sysread($fh, $input, 8192, $br)) {
242 die "input too long - aborting\n" if $br > $max;
243 if ($oneline && $input =~ m/^(.*)\n/) {
248 die "unable to read input - $!\n" if !defined($count);
253 # The $cmd parameter can be:
255 # This is generally executed by passing it to the shell with the -c option.
256 # However, it can be executed in one of two ways, depending on whether
257 # there's a pipe involved:
258 # *) with pipe: passed explicitly to bash -c, prefixed with:
260 # *) without a pipe: passed to perl's open3 which uses 'sh -c'
261 # (Note that this may result in two different syntax requirements!)
263 # -) an array of arguments (strings)
264 # Will be executed without interference from a shell. (Parameters are passed
265 # as is, no escape sequences of strings will be touched.)
266 # -) an array of arrays
267 # Each array represents a command, and each command's output is piped into
268 # the following command's standard input.
269 # For this a shell command string is created with pipe symbols between each
271 # Each command is a list of strings meant to end up in the final command
272 # unchanged. In order to achieve this, every argument is shell-quoted.
273 # Quoting can be disabled for a particular argument by turning it into a
274 # reference, this allows inserting arbitrary shell options.
275 # For instance: the $cmd [ [ 'echo', 'hello', \'>/dev/null' ] ] will not
276 # produce any output, while the $cmd [ [ 'echo', 'hello', '>/dev/null' ] ]
277 # will literally print: hello >/dev/null
279 my ($cmd, %param) = @_;
284 if (my $ref = ref($cmd)) {
285 if (ref($cmd->[0])) {
286 $cmdstr = 'set -o pipefail && ';
288 foreach my $command (@$cmd) {
289 # concatenate quoted parameters
290 # strings which are passed by reference are NOT shell quoted
291 $cmdstr .= $pipe . join(' ', map { ref($_) ?
$$_ : shellquote
($_) } @$command);
294 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmdstr" ];
296 $cmdstr = cmd2string
($cmd);
301 # see 'man bash' for option pipefail
302 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
323 foreach my $p (keys %param) {
324 if ($p eq 'timeout') {
325 $timeout = $param{$p};
326 } elsif ($p eq 'umask') {
327 $old_umask = umask($param{$p});
328 } elsif ($p eq 'errmsg') {
329 $errmsg = $param{$p};
330 } elsif ($p eq 'input') {
332 } elsif ($p eq 'output') {
333 $output = $param{$p};
334 } elsif ($p eq 'outfunc') {
335 $outfunc = $param{$p};
336 } elsif ($p eq 'errfunc') {
337 $errfunc = $param{$p};
338 } elsif ($p eq 'logfunc') {
339 $logfunc = $param{$p};
340 } elsif ($p eq 'afterfork') {
341 $afterfork = $param{$p};
343 die "got unknown parameter '$p' for run_command\n";
348 my $origerrfunc = $errfunc;
352 &$origerrfunc("$laststderr\n");
354 print STDERR
"$laststderr\n" if $laststderr;
361 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
362 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
363 my $error = IO
::File-
>new();
365 # try to avoid locale related issues/warnings
366 my $lang = $param{lang
} || 'C';
371 local $ENV{LC_ALL
} = $lang;
373 # suppress LVM warnings like: "File descriptor 3 left open";
374 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
376 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
378 # if we pipe fron STDIN, open3 closes STDIN, so we we
379 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
380 # as soon as we open a new file.
381 # to avoid that we open /dev/null
382 if (!ref($writer) && !defined(fileno(STDIN
))) {
384 open(STDIN
, "</dev/null");
391 if ($orig_pid != $$) {
399 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
400 $oldtimeout = alarm($timeout) if $timeout;
402 &$afterfork() if $afterfork;
405 print $writer $input if defined $input;
409 my $select = new IO
::Select
;
410 $select->add($reader) if ref($reader);
411 $select->add($error);
416 my $starttime = time();
418 while ($select->count) {
419 my @handles = $select->can_read(1);
421 foreach my $h (@handles) {
423 my $count = sysread ($h, $buf, 4096);
424 if (!defined ($count)) {
430 $select->remove ($h) if !$count;
432 if ($outfunc || $logfunc) {
435 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
437 &$outfunc($line) if $outfunc;
438 &$logfunc($line) if $logfunc;
451 } elsif ($h eq $error) {
452 if ($errfunc || $logfunc) {
455 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
457 &$errfunc($line) if $errfunc;
458 &$logfunc($line) if $logfunc;
475 &$outfunc($outlog) if $outfunc && $outlog;
476 &$logfunc($outlog) if $logfunc && $outlog;
478 &$errfunc($errlog) if $errfunc && $errlog;
479 &$logfunc($errlog) if $logfunc && $errlog;
484 die "failed to execute\n";
485 } elsif (my $sig = ($? & 127)) {
486 die "got signal $sig\n";
487 } elsif (my $ec = ($? >> 8)) {
488 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
489 if ($errmsg && $laststderr) {
490 my $lerr = $laststderr;
494 die "exit code $ec\n";
505 if ($errmsg && $laststderr) {
506 &$errfunc(undef); # flush laststderr
509 umask ($old_umask) if defined($old_umask);
511 alarm($oldtimeout) if $oldtimeout;
514 if ($pid && ($err eq "got timeout\n")) {
517 die "command '$cmdstr' failed: $err";
521 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
524 die "command '$cmdstr' failed: $err";
532 my $listtxt = shift || '';
534 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
536 $listtxt =~ s/[,;]/ /g;
537 $listtxt =~ s/^\s+//;
539 my @data = split (/\s+/, $listtxt);
547 return $txt if !defined($txt);
555 # simple uri templates like "/vms/{vmid}"
556 sub template_replace
{
557 my ($tmpl, $data) = @_;
559 return $tmpl if !$tmpl;
562 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
564 $res .= ($data->{$3} || '-') if $2;
570 my ($filename, $fh, $data) = @_;
574 my $res = print $fh $data;
576 die "write to '$filename' failed\n" if !$res;
582 'at' => 'ftp.at.debian.org',
583 'au' => 'ftp.au.debian.org',
584 'be' => 'ftp.be.debian.org',
585 'bg' => 'ftp.bg.debian.org',
586 'br' => 'ftp.br.debian.org',
587 'ca' => 'ftp.ca.debian.org',
588 'ch' => 'ftp.ch.debian.org',
589 'cl' => 'ftp.cl.debian.org',
590 'cz' => 'ftp.cz.debian.org',
591 'de' => 'ftp.de.debian.org',
592 'dk' => 'ftp.dk.debian.org',
593 'ee' => 'ftp.ee.debian.org',
594 'es' => 'ftp.es.debian.org',
595 'fi' => 'ftp.fi.debian.org',
596 'fr' => 'ftp.fr.debian.org',
597 'gr' => 'ftp.gr.debian.org',
598 'hk' => 'ftp.hk.debian.org',
599 'hr' => 'ftp.hr.debian.org',
600 'hu' => 'ftp.hu.debian.org',
601 'ie' => 'ftp.ie.debian.org',
602 'is' => 'ftp.is.debian.org',
603 'it' => 'ftp.it.debian.org',
604 'jp' => 'ftp.jp.debian.org',
605 'kr' => 'ftp.kr.debian.org',
606 'mx' => 'ftp.mx.debian.org',
607 'nl' => 'ftp.nl.debian.org',
608 'no' => 'ftp.no.debian.org',
609 'nz' => 'ftp.nz.debian.org',
610 'pl' => 'ftp.pl.debian.org',
611 'pt' => 'ftp.pt.debian.org',
612 'ro' => 'ftp.ro.debian.org',
613 'ru' => 'ftp.ru.debian.org',
614 'se' => 'ftp.se.debian.org',
615 'si' => 'ftp.si.debian.org',
616 'sk' => 'ftp.sk.debian.org',
617 'tr' => 'ftp.tr.debian.org',
618 'tw' => 'ftp.tw.debian.org',
619 'gb' => 'ftp.uk.debian.org',
620 'us' => 'ftp.us.debian.org',
625 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
626 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
627 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
628 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
629 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
630 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
631 #'et' => [], # Ethopia or Estonia ??
632 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
633 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
634 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
635 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
636 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
637 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
638 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
639 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
640 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
641 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
642 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
643 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
644 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
645 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
646 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
647 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
648 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
649 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
650 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
651 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
652 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
653 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
654 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
656 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
659 my $kvmkeymaparray = [];
660 foreach my $lc (keys %$keymaphash) {
661 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
669 return $kvmkeymaparray;
673 my ($param, $key) = @_;
675 my $res = $param->{$key};
676 delete $param->{$key};
681 # Note: we use this to wait until vncterm/spiceterm is ready
682 sub wait_for_vnc_port
{
683 my ($port, $timeout) = @_;
685 $timeout = 5 if !$timeout;
687 my $starttime = [gettimeofday
];
690 while (($elapsed = tv_interval
($starttime)) < $timeout) {
691 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
692 while (defined (my $line = <$fh>)) {
693 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
694 if ($port == hex($2)) {
702 $sleeptime += 100000 if $sleeptime < 1000000;
709 sub next_unused_port
{
710 my ($range_start, $range_end, $family) = @_;
712 # We use a file to register allocated ports.
713 # Those registrations expires after $expiretime.
714 # We use this to avoid race conditions between
715 # allocation and use of ports.
717 my $filename = "/var/tmp/pve-reserved-ports";
726 if (my $fh = IO
::File-
>new ($filename, "r")) {
727 while (my $line = <$fh>) {
728 if ($line =~ m/^(\d+)\s(\d+)$/) {
729 my ($port, $timestamp) = ($1, $2);
730 if (($timestamp + $expiretime) > $ctime) {
731 $ports->{$port} = $timestamp; # not expired
739 for (my $p = $range_start; $p < $range_end; $p++) {
740 next if $ports->{$p}; # reserved
742 my $sock = IO
::Socket
::IP-
>new(Listen
=> 5,
747 GetAddrInfoFlags
=> 0);
752 $ports->{$p} = $ctime;
758 foreach my $p (keys %$ports) {
759 $data .= "$p $ports->{$p}\n";
762 file_set_contents
($filename, $data);
767 my $p = lock_file
($filename, 10, $code);
770 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
775 sub next_migrate_port
{
777 return next_unused_port
(60000, 60050, $family);
782 return next_unused_port
(5900, 6000, $family);
785 sub next_spice_port
{
787 return next_unused_port
(61000, 61099, $family);
790 # NOTE: NFS syscall can't be interrupted, so alarm does
791 # not work to provide timeouts.
792 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
793 # So the spawn external 'df' process instead of using
794 # Filesys::Df (which uses statfs syscall)
796 my ($path, $timeout) = @_;
798 my $cmd = [ 'df', '-P', '-B', '1', $path];
808 if (my ($fsid, $total, $used, $avail) = $line =~
809 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
817 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
824 # We use this to uniquely identify a process.
825 # An 'Unique Process ID' has the following format:
826 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
831 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
832 # more that 8 characters for pstart
833 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
834 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
839 my ($upid, $noerr) = @_;
844 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
845 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
846 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]+):$/) {
848 $res->{pid
} = hex($3);
849 $res->{pstart
} = hex($4);
850 $res->{starttime
} = hex($5);
855 my $subdir = substr($5, 7, 8);
856 $filename = "$pvetaskdir/$subdir/$upid";
859 return undef if $noerr;
860 die "unable to parse worker upid '$upid'\n";
863 return wantarray ?
($res, $filename) : $res;
869 my ($task, $filename) = upid_decode
($upid);
871 my $dirname = dirname
($filename);
874 my $wwwid = getpwnam('www-data') ||
875 die "getpwnam failed";
879 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
880 die "unable to create output file '$filename' - $!\n";
881 chown $wwwid, -1, $outfh;
886 sub upid_read_status
{
889 my ($task, $filename) = upid_decode
($upid);
890 my $fh = IO
::File-
>new($filename, "r");
891 return "unable to open file - $!" if !$fh;
893 sysseek($fh, -$maxlen, 2);
895 my $br = sysread($fh, $readbuf, $maxlen);
898 return "unable to extract last line"
899 if $readbuf !~ m/\n?(.+)$/;
901 if ($line =~ m/^TASK OK$/) {
903 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
906 return "unexpected status";
909 return "unable to read tail (got $br bytes)";
912 # useful functions to store comments in config files
916 # all control and hi-bit characters, and ':'
917 my $unsafe = "^\x20-\x39\x3b-\x7e";
918 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
924 return Encode
::decode
("utf8", uri_unescape
($data));
927 sub decode_utf8_parameters
{
930 foreach my $p (qw(comment description firstname lastname)) {
931 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
937 sub random_ether_addr
{
939 my ($seconds, $microseconds) = gettimeofday
;
941 my $rand = Digest
::SHA
::sha1_hex
($$, rand(), $seconds, $microseconds);
943 # clear multicast, set local id
944 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
946 return sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
952 return String
::ShellQuote
::shell_quote
($str);
958 die "no arguments" if !$cmd;
960 return $cmd if !ref($cmd);
963 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
965 return join (' ', @qa);
968 # split an shell argument string into an array,
972 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
976 my ($filename, $start, $limit, $filter) = @_;
981 my $fh = IO
::File-
>new($filename, "r");
984 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
985 return ($count, $lines);
988 $start = 0 if !$start;
989 $limit = 50 if !$limit;
994 # duplicate code, so that we do not slow down normal path
995 while (defined($line = <$fh>)) {
996 next if $line !~ m/$filter/;
997 next if $count++ < $start;
1000 push @$lines, { n
=> $count, t
=> $line};
1004 while (defined($line = <$fh>)) {
1005 next if $count++ < $start;
1006 next if $limit <= 0;
1008 push @$lines, { n
=> $count, t
=> $line};
1015 # HACK: ExtJS store.guaranteeRange() does not like empty array
1019 push @$lines, { n
=> $count, t
=> "no content"};
1022 return ($count, $lines);
1026 my ($start, $limit, $filter) = @_;
1031 $start = 0 if !$start;
1032 $limit = 50 if !$limit;
1037 return if $count++ < $start;
1038 return if $limit <= 0;
1039 push @$lines, { n
=> int($count), t
=> $line};
1043 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1044 run_command
($cmd, outfunc
=> $parser);
1046 # HACK: ExtJS store.guaranteeRange() does not like empty array
1050 push @$lines, { n
=> $count, t
=> "no content"};
1053 return ($count, $lines);
1056 sub dir_glob_regex
{
1057 my ($dir, $regex) = @_;
1059 my $dh = IO
::Dir-
>new ($dir);
1060 return wantarray ?
() : undef if !$dh;
1062 while (defined(my $tmp = $dh->read)) {
1063 if (my @res = $tmp =~ m/^($regex)$/) {
1065 return wantarray ?
@res : $tmp;
1070 return wantarray ?
() : undef;
1073 sub dir_glob_foreach
{
1074 my ($dir, $regex, $func) = @_;
1076 my $dh = IO
::Dir-
>new ($dir);
1078 while (defined(my $tmp = $dh->read)) {
1079 if (my @res = $tmp =~ m/^($regex)$/) {
1086 sub assert_if_modified
{
1087 my ($digest1, $digest2) = @_;
1089 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1090 die "detected modified configuration - file changed by other user? Try again.\n";
1094 # Digest for short strings
1095 # like FNV32a, but we only return 31 bits (positive numbers)
1099 my $hval = 0x811c9dc5;
1101 foreach my $c (unpack('C*', $string)) {
1109 $hval = $hval & 0xffffffff;
1111 return $hval & 0x7fffffff;
1114 sub fnv31a_hex
{ return sprintf("%X", fnv31a
(@_)); }
1116 sub unpack_sockaddr_in46
{
1118 my $family = Socket
::sockaddr_family
($sin);
1119 my ($port, $host) = ($family == AF_INET6 ? Socket
::unpack_sockaddr_in6
($sin)
1120 : Socket
::unpack_sockaddr_in
($sin));
1121 return ($family, $port, $host);
1124 sub getaddrinfo_all
{
1125 my ($hostname, @opts) = @_;
1126 my %hints = ( flags
=> AI_V4MAPPED
| AI_ALL
,
1128 my ($err, @res) = Socket
::getaddrinfo
($hostname, '0', \
%hints);
1129 die "failed to get address info for: $hostname: $err\n" if $err;
1133 sub get_host_address_family
{
1134 my ($hostname, $socktype) = @_;
1135 my @res = getaddrinfo_all
($hostname, socktype
=> $socktype);
1136 return $res[0]->{family
};
1139 # Parses any sane kind of host, or host+port pair:
1140 # The port is always optional and thus may be undef.
1141 sub parse_host_and_port
{
1143 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1144 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1145 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1147 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1154 syscall 272, $flags;