]>
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 sub run_with_timeout
{
79 my ($timeout, $code, @param) = @_;
81 die "got timeout\n" if $timeout <= 0;
83 my $prev_alarm = alarm 0; # suspend outer alarm early
90 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
91 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
92 local $SIG{__DIE__
}; # see SA bug 4631
96 eval { $res = &$code(@param); };
98 alarm(0); # avoid race conditions
107 # this shouldn't happen anymore?
108 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
115 # flock: we use one file handle per process, so lock file
116 # can be called multiple times and succeeds for the same process.
118 my $lock_handles = {};
121 my ($filename, $timeout, $shared, $code, @param) = @_;
123 $timeout = 10 if !$timeout;
125 my $mode = $shared ? LOCK_SH
: LOCK_EX
;
127 my $lock_func = sub {
128 if (!$lock_handles->{$$}->{$filename}) {
129 $lock_handles->{$$}->{$filename} = new IO
::File
(">>$filename") ||
130 die "can't open file - $!\n";
133 if (!flock ($lock_handles->{$$}->{$filename}, $mode|LOCK_NB
)) {
134 print STDERR
"trying to aquire lock...";
137 $success = flock($lock_handles->{$$}->{$filename}, $mode);
138 # try again on EINTR (see bug #273)
139 if ($success || ($! != EINTR
)) {
144 print STDERR
" failed\n";
145 die "can't aquire lock - $!\n";
147 print STDERR
" OK\n";
153 eval { run_with_timeout
($timeout, $lock_func); };
156 $err = "can't lock file '$filename' - $err";
158 eval { $res = &$code(@param) };
162 if (my $fh = $lock_handles->{$$}->{$filename}) {
163 $lock_handles->{$$}->{$filename} = undef;
179 my ($filename, $timeout, $code, @param) = @_;
181 return lock_file_full
($filename, $timeout, 0, $code, @param);
184 sub file_set_contents
{
185 my ($filename, $data, $perm) = @_;
187 $perm = 0644 if !defined($perm);
189 my $tmpname = "$filename.tmp.$$";
192 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
193 die "unable to open file '$tmpname' - $!\n" if !$fh;
194 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
195 die "closing file '$tmpname' failed - $!\n" unless close $fh;
204 if (!rename($tmpname, $filename)) {
205 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
211 sub file_get_contents
{
212 my ($filename, $max) = @_;
214 my $fh = IO
::File-
>new($filename, "r") ||
215 die "can't open '$filename' - $!\n";
217 my $content = safe_read_from
($fh, $max);
225 my ($filename, $dst, $max, $perm) = @_;
227 file_set_contents
($dst, file_get_contents
($filename, $max), $perm);
230 sub file_read_firstline
{
233 my $fh = IO
::File-
>new ($filename, "r");
234 return undef if !$fh;
242 my ($fh, $max, $oneline) = @_;
244 $max = 32768 if !$max;
249 while ($count = sysread($fh, $input, 8192, $br)) {
251 die "input too long - aborting\n" if $br > $max;
252 if ($oneline && $input =~ m/^(.*)\n/) {
257 die "unable to read input - $!\n" if !defined($count);
262 # The $cmd parameter can be:
264 # This is generally executed by passing it to the shell with the -c option.
265 # However, it can be executed in one of two ways, depending on whether
266 # there's a pipe involved:
267 # *) with pipe: passed explicitly to bash -c, prefixed with:
269 # *) without a pipe: passed to perl's open3 which uses 'sh -c'
270 # (Note that this may result in two different syntax requirements!)
272 # -) an array of arguments (strings)
273 # Will be executed without interference from a shell. (Parameters are passed
274 # as is, no escape sequences of strings will be touched.)
275 # -) an array of arrays
276 # Each array represents a command, and each command's output is piped into
277 # the following command's standard input.
278 # For this a shell command string is created with pipe symbols between each
280 # Each command is a list of strings meant to end up in the final command
281 # unchanged. In order to achieve this, every argument is shell-quoted.
282 # Quoting can be disabled for a particular argument by turning it into a
283 # reference, this allows inserting arbitrary shell options.
284 # For instance: the $cmd [ [ 'echo', 'hello', \'>/dev/null' ] ] will not
285 # produce any output, while the $cmd [ [ 'echo', 'hello', '>/dev/null' ] ]
286 # will literally print: hello >/dev/null
288 my ($cmd, %param) = @_;
293 if (my $ref = ref($cmd)) {
294 if (ref($cmd->[0])) {
295 $cmdstr = 'set -o pipefail && ';
297 foreach my $command (@$cmd) {
298 # concatenate quoted parameters
299 # strings which are passed by reference are NOT shell quoted
300 $cmdstr .= $pipe . join(' ', map { ref($_) ?
$$_ : shellquote
($_) } @$command);
303 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmdstr" ];
305 $cmdstr = cmd2string
($cmd);
310 # see 'man bash' for option pipefail
311 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
332 foreach my $p (keys %param) {
333 if ($p eq 'timeout') {
334 $timeout = $param{$p};
335 } elsif ($p eq 'umask') {
336 $old_umask = umask($param{$p});
337 } elsif ($p eq 'errmsg') {
338 $errmsg = $param{$p};
339 } elsif ($p eq 'input') {
341 } elsif ($p eq 'output') {
342 $output = $param{$p};
343 } elsif ($p eq 'outfunc') {
344 $outfunc = $param{$p};
345 } elsif ($p eq 'errfunc') {
346 $errfunc = $param{$p};
347 } elsif ($p eq 'logfunc') {
348 $logfunc = $param{$p};
349 } elsif ($p eq 'afterfork') {
350 $afterfork = $param{$p};
352 die "got unknown parameter '$p' for run_command\n";
357 my $origerrfunc = $errfunc;
361 &$origerrfunc("$laststderr\n");
363 print STDERR
"$laststderr\n" if $laststderr;
370 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
371 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
372 my $error = IO
::File-
>new();
374 # try to avoid locale related issues/warnings
375 my $lang = $param{lang
} || 'C';
380 local $ENV{LC_ALL
} = $lang;
382 # suppress LVM warnings like: "File descriptor 3 left open";
383 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
385 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
387 # if we pipe fron STDIN, open3 closes STDIN, so we we
388 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
389 # as soon as we open a new file.
390 # to avoid that we open /dev/null
391 if (!ref($writer) && !defined(fileno(STDIN
))) {
393 open(STDIN
, "</dev/null");
400 if ($orig_pid != $$) {
408 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
409 $oldtimeout = alarm($timeout) if $timeout;
411 &$afterfork() if $afterfork;
414 print $writer $input if defined $input;
418 my $select = new IO
::Select
;
419 $select->add($reader) if ref($reader);
420 $select->add($error);
425 my $starttime = time();
427 while ($select->count) {
428 my @handles = $select->can_read(1);
430 foreach my $h (@handles) {
432 my $count = sysread ($h, $buf, 4096);
433 if (!defined ($count)) {
439 $select->remove ($h) if !$count;
441 if ($outfunc || $logfunc) {
444 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
446 &$outfunc($line) if $outfunc;
447 &$logfunc($line) if $logfunc;
460 } elsif ($h eq $error) {
461 if ($errfunc || $logfunc) {
464 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
466 &$errfunc($line) if $errfunc;
467 &$logfunc($line) if $logfunc;
484 &$outfunc($outlog) if $outfunc && $outlog;
485 &$logfunc($outlog) if $logfunc && $outlog;
487 &$errfunc($errlog) if $errfunc && $errlog;
488 &$logfunc($errlog) if $logfunc && $errlog;
493 die "failed to execute\n";
494 } elsif (my $sig = ($? & 127)) {
495 die "got signal $sig\n";
496 } elsif (my $ec = ($? >> 8)) {
497 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
498 if ($errmsg && $laststderr) {
499 my $lerr = $laststderr;
503 die "exit code $ec\n";
514 if ($errmsg && $laststderr) {
515 &$errfunc(undef); # flush laststderr
518 umask ($old_umask) if defined($old_umask);
520 alarm($oldtimeout) if $oldtimeout;
523 if ($pid && ($err eq "got timeout\n")) {
526 die "command '$cmdstr' failed: $err";
530 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
533 die "command '$cmdstr' failed: $err";
541 my $listtxt = shift || '';
543 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
545 $listtxt =~ s/[,;]/ /g;
546 $listtxt =~ s/^\s+//;
548 my @data = split (/\s+/, $listtxt);
556 return $txt if !defined($txt);
564 # simple uri templates like "/vms/{vmid}"
565 sub template_replace
{
566 my ($tmpl, $data) = @_;
568 return $tmpl if !$tmpl;
571 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
573 $res .= ($data->{$3} || '-') if $2;
579 my ($filename, $fh, $data) = @_;
583 my $res = print $fh $data;
585 die "write to '$filename' failed\n" if !$res;
591 'at' => 'ftp.at.debian.org',
592 'au' => 'ftp.au.debian.org',
593 'be' => 'ftp.be.debian.org',
594 'bg' => 'ftp.bg.debian.org',
595 'br' => 'ftp.br.debian.org',
596 'ca' => 'ftp.ca.debian.org',
597 'ch' => 'ftp.ch.debian.org',
598 'cl' => 'ftp.cl.debian.org',
599 'cz' => 'ftp.cz.debian.org',
600 'de' => 'ftp.de.debian.org',
601 'dk' => 'ftp.dk.debian.org',
602 'ee' => 'ftp.ee.debian.org',
603 'es' => 'ftp.es.debian.org',
604 'fi' => 'ftp.fi.debian.org',
605 'fr' => 'ftp.fr.debian.org',
606 'gr' => 'ftp.gr.debian.org',
607 'hk' => 'ftp.hk.debian.org',
608 'hr' => 'ftp.hr.debian.org',
609 'hu' => 'ftp.hu.debian.org',
610 'ie' => 'ftp.ie.debian.org',
611 'is' => 'ftp.is.debian.org',
612 'it' => 'ftp.it.debian.org',
613 'jp' => 'ftp.jp.debian.org',
614 'kr' => 'ftp.kr.debian.org',
615 'mx' => 'ftp.mx.debian.org',
616 'nl' => 'ftp.nl.debian.org',
617 'no' => 'ftp.no.debian.org',
618 'nz' => 'ftp.nz.debian.org',
619 'pl' => 'ftp.pl.debian.org',
620 'pt' => 'ftp.pt.debian.org',
621 'ro' => 'ftp.ro.debian.org',
622 'ru' => 'ftp.ru.debian.org',
623 'se' => 'ftp.se.debian.org',
624 'si' => 'ftp.si.debian.org',
625 'sk' => 'ftp.sk.debian.org',
626 'tr' => 'ftp.tr.debian.org',
627 'tw' => 'ftp.tw.debian.org',
628 'gb' => 'ftp.uk.debian.org',
629 'us' => 'ftp.us.debian.org',
634 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
635 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
636 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
637 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
638 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
639 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
640 #'et' => [], # Ethopia or Estonia ??
641 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
642 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
643 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
644 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
645 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
646 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
647 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
648 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
649 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
650 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
651 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
652 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
653 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
654 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
655 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
656 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
657 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
658 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
659 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
660 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
661 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
662 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
663 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
665 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
668 my $kvmkeymaparray = [];
669 foreach my $lc (keys %$keymaphash) {
670 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
678 return $kvmkeymaparray;
682 my ($param, $key) = @_;
684 my $res = $param->{$key};
685 delete $param->{$key};
690 # Note: we use this to wait until vncterm/spiceterm is ready
691 sub wait_for_vnc_port
{
692 my ($port, $timeout) = @_;
694 $timeout = 5 if !$timeout;
696 my $starttime = [gettimeofday
];
699 while (($elapsed = tv_interval
($starttime)) < $timeout) {
700 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
701 while (defined (my $line = <$fh>)) {
702 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
703 if ($port == hex($2)) {
711 $sleeptime += 100000 if $sleeptime < 1000000;
718 sub next_unused_port
{
719 my ($range_start, $range_end, $family) = @_;
721 # We use a file to register allocated ports.
722 # Those registrations expires after $expiretime.
723 # We use this to avoid race conditions between
724 # allocation and use of ports.
726 my $filename = "/var/tmp/pve-reserved-ports";
735 if (my $fh = IO
::File-
>new ($filename, "r")) {
736 while (my $line = <$fh>) {
737 if ($line =~ m/^(\d+)\s(\d+)$/) {
738 my ($port, $timestamp) = ($1, $2);
739 if (($timestamp + $expiretime) > $ctime) {
740 $ports->{$port} = $timestamp; # not expired
748 for (my $p = $range_start; $p < $range_end; $p++) {
749 next if $ports->{$p}; # reserved
751 my $sock = IO
::Socket
::IP-
>new(Listen
=> 5,
756 GetAddrInfoFlags
=> 0);
761 $ports->{$p} = $ctime;
767 foreach my $p (keys %$ports) {
768 $data .= "$p $ports->{$p}\n";
771 file_set_contents
($filename, $data);
776 my $p = lock_file
($filename, 10, $code);
779 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
784 sub next_migrate_port
{
786 return next_unused_port
(60000, 60050, $family);
791 return next_unused_port
(5900, 6000, $family);
794 sub next_spice_port
{
796 return next_unused_port
(61000, 61099, $family);
799 # NOTE: NFS syscall can't be interrupted, so alarm does
800 # not work to provide timeouts.
801 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
802 # So fork() before using Filesys::Df
804 my ($path, $timeout) = @_;
812 my $pipe = IO
::Pipe-
>new();
814 if (!defined($child)) {
815 warn "fork failed: $!\n";
822 my $df = Filesys
::Df
::df
($path, 1);
823 print {$pipe} "$df->{blocks}\n$df->{used}\n$df->{bavail}\n";
835 my $readvalues = sub {
836 $res->{total
} = int(<$pipe>);
837 $res->{used
} = int(<$pipe>);
838 $res->{avail
} = int(<$pipe>);
841 run_with_timeout
($timeout, $readvalues);
845 kill('KILL', $child);
851 # We use this to uniquely identify a process.
852 # An 'Unique Process ID' has the following format:
853 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
858 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
859 # more that 8 characters for pstart
860 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
861 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
866 my ($upid, $noerr) = @_;
871 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
872 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
873 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]+):$/) {
875 $res->{pid
} = hex($3);
876 $res->{pstart
} = hex($4);
877 $res->{starttime
} = hex($5);
882 my $subdir = substr($5, 7, 8);
883 $filename = "$pvetaskdir/$subdir/$upid";
886 return undef if $noerr;
887 die "unable to parse worker upid '$upid'\n";
890 return wantarray ?
($res, $filename) : $res;
896 my ($task, $filename) = upid_decode
($upid);
898 my $dirname = dirname
($filename);
901 my $wwwid = getpwnam('www-data') ||
902 die "getpwnam failed";
906 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
907 die "unable to create output file '$filename' - $!\n";
908 chown $wwwid, -1, $outfh;
913 sub upid_read_status
{
916 my ($task, $filename) = upid_decode
($upid);
917 my $fh = IO
::File-
>new($filename, "r");
918 return "unable to open file - $!" if !$fh;
920 sysseek($fh, -$maxlen, 2);
922 my $br = sysread($fh, $readbuf, $maxlen);
925 return "unable to extract last line"
926 if $readbuf !~ m/\n?(.+)$/;
928 if ($line =~ m/^TASK OK$/) {
930 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
933 return "unexpected status";
936 return "unable to read tail (got $br bytes)";
939 # useful functions to store comments in config files
943 # all control and hi-bit characters, and ':'
944 my $unsafe = "^\x20-\x39\x3b-\x7e";
945 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
951 return Encode
::decode
("utf8", uri_unescape
($data));
954 sub decode_utf8_parameters
{
957 foreach my $p (qw(comment description firstname lastname)) {
958 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
964 sub random_ether_addr
{
966 my ($seconds, $microseconds) = gettimeofday
;
968 my $rand = Digest
::SHA
::sha1_hex
($$, rand(), $seconds, $microseconds);
970 # clear multicast, set local id
971 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
973 return sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
979 return String
::ShellQuote
::shell_quote
($str);
985 die "no arguments" if !$cmd;
987 return $cmd if !ref($cmd);
990 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
992 return join (' ', @qa);
995 # split an shell argument string into an array,
999 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
1003 my ($filename, $start, $limit, $filter) = @_;
1008 my $fh = IO
::File-
>new($filename, "r");
1011 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
1012 return ($count, $lines);
1015 $start = 0 if !$start;
1016 $limit = 50 if !$limit;
1021 # duplicate code, so that we do not slow down normal path
1022 while (defined($line = <$fh>)) {
1023 next if $line !~ m/$filter/;
1024 next if $count++ < $start;
1025 next if $limit <= 0;
1027 push @$lines, { n
=> $count, t
=> $line};
1031 while (defined($line = <$fh>)) {
1032 next if $count++ < $start;
1033 next if $limit <= 0;
1035 push @$lines, { n
=> $count, t
=> $line};
1042 # HACK: ExtJS store.guaranteeRange() does not like empty array
1046 push @$lines, { n
=> $count, t
=> "no content"};
1049 return ($count, $lines);
1053 my ($start, $limit, $filter) = @_;
1058 $start = 0 if !$start;
1059 $limit = 50 if !$limit;
1064 return if $count++ < $start;
1065 return if $limit <= 0;
1066 push @$lines, { n
=> int($count), t
=> $line};
1070 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1071 run_command
($cmd, outfunc
=> $parser);
1073 # HACK: ExtJS store.guaranteeRange() does not like empty array
1077 push @$lines, { n
=> $count, t
=> "no content"};
1080 return ($count, $lines);
1083 sub dir_glob_regex
{
1084 my ($dir, $regex) = @_;
1086 my $dh = IO
::Dir-
>new ($dir);
1087 return wantarray ?
() : undef if !$dh;
1089 while (defined(my $tmp = $dh->read)) {
1090 if (my @res = $tmp =~ m/^($regex)$/) {
1092 return wantarray ?
@res : $tmp;
1097 return wantarray ?
() : undef;
1100 sub dir_glob_foreach
{
1101 my ($dir, $regex, $func) = @_;
1103 my $dh = IO
::Dir-
>new ($dir);
1105 while (defined(my $tmp = $dh->read)) {
1106 if (my @res = $tmp =~ m/^($regex)$/) {
1113 sub assert_if_modified
{
1114 my ($digest1, $digest2) = @_;
1116 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1117 die "detected modified configuration - file changed by other user? Try again.\n";
1121 # Digest for short strings
1122 # like FNV32a, but we only return 31 bits (positive numbers)
1126 my $hval = 0x811c9dc5;
1128 foreach my $c (unpack('C*', $string)) {
1136 $hval = $hval & 0xffffffff;
1138 return $hval & 0x7fffffff;
1141 sub fnv31a_hex
{ return sprintf("%X", fnv31a
(@_)); }
1143 sub unpack_sockaddr_in46
{
1145 my $family = Socket
::sockaddr_family
($sin);
1146 my ($port, $host) = ($family == AF_INET6 ? Socket
::unpack_sockaddr_in6
($sin)
1147 : Socket
::unpack_sockaddr_in
($sin));
1148 return ($family, $port, $host);
1151 sub getaddrinfo_all
{
1152 my ($hostname, @opts) = @_;
1153 my %hints = ( flags
=> AI_V4MAPPED
| AI_ALL
,
1155 my ($err, @res) = Socket
::getaddrinfo
($hostname, '0', \
%hints);
1156 die "failed to get address info for: $hostname: $err\n" if $err;
1160 sub get_host_address_family
{
1161 my ($hostname, $socktype) = @_;
1162 my @res = getaddrinfo_all
($hostname, socktype
=> $socktype);
1163 return $res[0]->{family
};
1166 # Parses any sane kind of host, or host+port pair:
1167 # The port is always optional and thus may be undef.
1168 sub parse_host_and_port
{
1170 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1171 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1172 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1174 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1181 return 0 == syscall(272, $flags);