]>
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.)
258 my ($cmd, %param) = @_;
266 # see 'man bash' for option pipefail
267 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
272 $cmdstr = cmd2string
($cmd);
290 foreach my $p (keys %param) {
291 if ($p eq 'timeout') {
292 $timeout = $param{$p};
293 } elsif ($p eq 'umask') {
294 $old_umask = umask($param{$p});
295 } elsif ($p eq 'errmsg') {
296 $errmsg = $param{$p};
297 } elsif ($p eq 'input') {
299 } elsif ($p eq 'output') {
300 $output = $param{$p};
301 } elsif ($p eq 'outfunc') {
302 $outfunc = $param{$p};
303 } elsif ($p eq 'errfunc') {
304 $errfunc = $param{$p};
305 } elsif ($p eq 'logfunc') {
306 $logfunc = $param{$p};
307 } elsif ($p eq 'afterfork') {
308 $afterfork = $param{$p};
310 die "got unknown parameter '$p' for run_command\n";
315 my $origerrfunc = $errfunc;
319 &$origerrfunc("$laststderr\n");
321 print STDERR
"$laststderr\n" if $laststderr;
328 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
329 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
330 my $error = IO
::File-
>new();
332 # try to avoid locale related issues/warnings
333 my $lang = $param{lang
} || 'C';
338 local $ENV{LC_ALL
} = $lang;
340 # suppress LVM warnings like: "File descriptor 3 left open";
341 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
343 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
345 # if we pipe fron STDIN, open3 closes STDIN, so we we
346 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
347 # as soon as we open a new file.
348 # to avoid that we open /dev/null
349 if (!ref($writer) && !defined(fileno(STDIN
))) {
351 open(STDIN
, "</dev/null");
358 if ($orig_pid != $$) {
366 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
367 $oldtimeout = alarm($timeout) if $timeout;
369 &$afterfork() if $afterfork;
372 print $writer $input if defined $input;
376 my $select = new IO
::Select
;
377 $select->add($reader) if ref($reader);
378 $select->add($error);
383 my $starttime = time();
385 while ($select->count) {
386 my @handles = $select->can_read(1);
388 foreach my $h (@handles) {
390 my $count = sysread ($h, $buf, 4096);
391 if (!defined ($count)) {
397 $select->remove ($h) if !$count;
399 if ($outfunc || $logfunc) {
402 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
404 &$outfunc($line) if $outfunc;
405 &$logfunc($line) if $logfunc;
418 } elsif ($h eq $error) {
419 if ($errfunc || $logfunc) {
422 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
424 &$errfunc($line) if $errfunc;
425 &$logfunc($line) if $logfunc;
442 &$outfunc($outlog) if $outfunc && $outlog;
443 &$logfunc($outlog) if $logfunc && $outlog;
445 &$errfunc($errlog) if $errfunc && $errlog;
446 &$logfunc($errlog) if $logfunc && $errlog;
451 die "failed to execute\n";
452 } elsif (my $sig = ($? & 127)) {
453 die "got signal $sig\n";
454 } elsif (my $ec = ($? >> 8)) {
455 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
456 if ($errmsg && $laststderr) {
457 my $lerr = $laststderr;
461 die "exit code $ec\n";
472 if ($errmsg && $laststderr) {
473 &$errfunc(undef); # flush laststderr
476 umask ($old_umask) if defined($old_umask);
478 alarm($oldtimeout) if $oldtimeout;
481 if ($pid && ($err eq "got timeout\n")) {
484 die "command '$cmdstr' failed: $err";
488 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
491 die "command '$cmdstr' failed: $err";
499 my $listtxt = shift || '';
501 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
503 $listtxt =~ s/[,;]/ /g;
504 $listtxt =~ s/^\s+//;
506 my @data = split (/\s+/, $listtxt);
514 return $txt if !defined($txt);
522 # simple uri templates like "/vms/{vmid}"
523 sub template_replace
{
524 my ($tmpl, $data) = @_;
526 return $tmpl if !$tmpl;
529 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
531 $res .= ($data->{$3} || '-') if $2;
537 my ($filename, $fh, $data) = @_;
541 my $res = print $fh $data;
543 die "write to '$filename' failed\n" if !$res;
549 'at' => 'ftp.at.debian.org',
550 'au' => 'ftp.au.debian.org',
551 'be' => 'ftp.be.debian.org',
552 'bg' => 'ftp.bg.debian.org',
553 'br' => 'ftp.br.debian.org',
554 'ca' => 'ftp.ca.debian.org',
555 'ch' => 'ftp.ch.debian.org',
556 'cl' => 'ftp.cl.debian.org',
557 'cz' => 'ftp.cz.debian.org',
558 'de' => 'ftp.de.debian.org',
559 'dk' => 'ftp.dk.debian.org',
560 'ee' => 'ftp.ee.debian.org',
561 'es' => 'ftp.es.debian.org',
562 'fi' => 'ftp.fi.debian.org',
563 'fr' => 'ftp.fr.debian.org',
564 'gr' => 'ftp.gr.debian.org',
565 'hk' => 'ftp.hk.debian.org',
566 'hr' => 'ftp.hr.debian.org',
567 'hu' => 'ftp.hu.debian.org',
568 'ie' => 'ftp.ie.debian.org',
569 'is' => 'ftp.is.debian.org',
570 'it' => 'ftp.it.debian.org',
571 'jp' => 'ftp.jp.debian.org',
572 'kr' => 'ftp.kr.debian.org',
573 'mx' => 'ftp.mx.debian.org',
574 'nl' => 'ftp.nl.debian.org',
575 'no' => 'ftp.no.debian.org',
576 'nz' => 'ftp.nz.debian.org',
577 'pl' => 'ftp.pl.debian.org',
578 'pt' => 'ftp.pt.debian.org',
579 'ro' => 'ftp.ro.debian.org',
580 'ru' => 'ftp.ru.debian.org',
581 'se' => 'ftp.se.debian.org',
582 'si' => 'ftp.si.debian.org',
583 'sk' => 'ftp.sk.debian.org',
584 'tr' => 'ftp.tr.debian.org',
585 'tw' => 'ftp.tw.debian.org',
586 'gb' => 'ftp.uk.debian.org',
587 'us' => 'ftp.us.debian.org',
592 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
593 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
594 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
595 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
596 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
597 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
598 #'et' => [], # Ethopia or Estonia ??
599 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
600 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
601 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
602 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
603 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
604 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
605 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
606 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
607 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
608 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
609 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
610 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
611 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
612 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
613 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
614 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
615 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
616 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
617 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
618 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
619 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
620 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
621 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
623 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
626 my $kvmkeymaparray = [];
627 foreach my $lc (keys %$keymaphash) {
628 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
636 return $kvmkeymaparray;
640 my ($param, $key) = @_;
642 my $res = $param->{$key};
643 delete $param->{$key};
648 # Note: we use this to wait until vncterm/spiceterm is ready
649 sub wait_for_vnc_port
{
650 my ($port, $timeout) = @_;
652 $timeout = 5 if !$timeout;
654 my $starttime = [gettimeofday
];
657 while (($elapsed = tv_interval
($starttime)) < $timeout) {
658 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
659 while (defined (my $line = <$fh>)) {
660 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
661 if ($port == hex($2)) {
669 $sleeptime += 100000 if $sleeptime < 1000000;
676 sub next_unused_port
{
677 my ($range_start, $range_end, $family) = @_;
679 # We use a file to register allocated ports.
680 # Those registrations expires after $expiretime.
681 # We use this to avoid race conditions between
682 # allocation and use of ports.
684 my $filename = "/var/tmp/pve-reserved-ports";
693 if (my $fh = IO
::File-
>new ($filename, "r")) {
694 while (my $line = <$fh>) {
695 if ($line =~ m/^(\d+)\s(\d+)$/) {
696 my ($port, $timestamp) = ($1, $2);
697 if (($timestamp + $expiretime) > $ctime) {
698 $ports->{$port} = $timestamp; # not expired
706 for (my $p = $range_start; $p < $range_end; $p++) {
707 next if $ports->{$p}; # reserved
709 my $sock = IO
::Socket
::IP-
>new(Listen
=> 5,
714 GetAddrInfoFlags
=> 0);
719 $ports->{$p} = $ctime;
725 foreach my $p (keys %$ports) {
726 $data .= "$p $ports->{$p}\n";
729 file_set_contents
($filename, $data);
734 my $p = lock_file
($filename, 10, $code);
737 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
742 sub next_migrate_port
{
744 return next_unused_port
(60000, 60050, $family);
749 return next_unused_port
(5900, 6000, $family);
752 sub next_spice_port
{
754 return next_unused_port
(61000, 61099, $family);
757 # NOTE: NFS syscall can't be interrupted, so alarm does
758 # not work to provide timeouts.
759 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
760 # So the spawn external 'df' process instead of using
761 # Filesys::Df (which uses statfs syscall)
763 my ($path, $timeout) = @_;
765 my $cmd = [ 'df', '-P', '-B', '1', $path];
775 if (my ($fsid, $total, $used, $avail) = $line =~
776 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
784 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
791 # We use this to uniquely identify a process.
792 # An 'Unique Process ID' has the following format:
793 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
798 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
799 # more that 8 characters for pstart
800 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
801 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
806 my ($upid, $noerr) = @_;
811 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
812 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
813 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]+):$/) {
815 $res->{pid
} = hex($3);
816 $res->{pstart
} = hex($4);
817 $res->{starttime
} = hex($5);
822 my $subdir = substr($5, 7, 8);
823 $filename = "$pvetaskdir/$subdir/$upid";
826 return undef if $noerr;
827 die "unable to parse worker upid '$upid'\n";
830 return wantarray ?
($res, $filename) : $res;
836 my ($task, $filename) = upid_decode
($upid);
838 my $dirname = dirname
($filename);
841 my $wwwid = getpwnam('www-data') ||
842 die "getpwnam failed";
846 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
847 die "unable to create output file '$filename' - $!\n";
848 chown $wwwid, -1, $outfh;
853 sub upid_read_status
{
856 my ($task, $filename) = upid_decode
($upid);
857 my $fh = IO
::File-
>new($filename, "r");
858 return "unable to open file - $!" if !$fh;
860 sysseek($fh, -$maxlen, 2);
862 my $br = sysread($fh, $readbuf, $maxlen);
865 return "unable to extract last line"
866 if $readbuf !~ m/\n?(.+)$/;
868 if ($line =~ m/^TASK OK$/) {
870 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
873 return "unexpected status";
876 return "unable to read tail (got $br bytes)";
879 # useful functions to store comments in config files
883 # all control and hi-bit characters, and ':'
884 my $unsafe = "^\x20-\x39\x3b-\x7e";
885 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
891 return Encode
::decode
("utf8", uri_unescape
($data));
894 sub decode_utf8_parameters
{
897 foreach my $p (qw(comment description firstname lastname)) {
898 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
904 sub random_ether_addr
{
906 my ($seconds, $microseconds) = gettimeofday
;
908 my $rand = Digest
::SHA
::sha1_hex
($$, rand(), $seconds, $microseconds);
911 for (my $i = 0; $i < 6; $i++) {
912 my $ss = hex(substr($rand, $i*2, 2));
914 $ss &= 0xfe; # clear multicast
915 $ss |= 2; # set local id
917 $ss = sprintf("%02X", $ss);
932 return String
::ShellQuote
::shell_quote
($str);
938 die "no arguments" if !$cmd;
940 return $cmd if !ref($cmd);
943 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
945 return join (' ', @qa);
948 # split an shell argument string into an array,
952 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
956 my ($filename, $start, $limit, $filter) = @_;
961 my $fh = IO
::File-
>new($filename, "r");
964 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
965 return ($count, $lines);
968 $start = 0 if !$start;
969 $limit = 50 if !$limit;
974 # duplicate code, so that we do not slow down normal path
975 while (defined($line = <$fh>)) {
976 next if $line !~ m/$filter/;
977 next if $count++ < $start;
980 push @$lines, { n
=> $count, t
=> $line};
984 while (defined($line = <$fh>)) {
985 next if $count++ < $start;
988 push @$lines, { n
=> $count, t
=> $line};
995 # HACK: ExtJS store.guaranteeRange() does not like empty array
999 push @$lines, { n
=> $count, t
=> "no content"};
1002 return ($count, $lines);
1006 my ($start, $limit, $filter) = @_;
1011 $start = 0 if !$start;
1012 $limit = 50 if !$limit;
1017 return if $count++ < $start;
1018 return if $limit <= 0;
1019 push @$lines, { n
=> int($count), t
=> $line};
1023 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1024 run_command
($cmd, outfunc
=> $parser);
1026 # HACK: ExtJS store.guaranteeRange() does not like empty array
1030 push @$lines, { n
=> $count, t
=> "no content"};
1033 return ($count, $lines);
1036 sub dir_glob_regex
{
1037 my ($dir, $regex) = @_;
1039 my $dh = IO
::Dir-
>new ($dir);
1040 return wantarray ?
() : undef if !$dh;
1042 while (defined(my $tmp = $dh->read)) {
1043 if (my @res = $tmp =~ m/^($regex)$/) {
1045 return wantarray ?
@res : $tmp;
1050 return wantarray ?
() : undef;
1053 sub dir_glob_foreach
{
1054 my ($dir, $regex, $func) = @_;
1056 my $dh = IO
::Dir-
>new ($dir);
1058 while (defined(my $tmp = $dh->read)) {
1059 if (my @res = $tmp =~ m/^($regex)$/) {
1066 sub assert_if_modified
{
1067 my ($digest1, $digest2) = @_;
1069 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1070 die "detected modified configuration - file changed by other user? Try again.\n";
1074 # Digest for short strings
1075 # like FNV32a, but we only return 31 bits (positive numbers)
1079 my $hval = 0x811c9dc5;
1081 foreach my $c (unpack('C*', $string)) {
1089 $hval = $hval & 0xffffffff;
1091 return $hval & 0x7fffffff;
1094 sub fnv31a_hex
{ return sprintf("%X", fnv31a
(@_)); }
1096 sub unpack_sockaddr_in46
{
1098 my $family = Socket
::sockaddr_family
($sin);
1099 my ($port, $host) = ($family == AF_INET6 ? Socket
::unpack_sockaddr_in6
($sin)
1100 : Socket
::unpack_sockaddr_in
($sin));
1101 return ($family, $port, $host);
1104 sub getaddrinfo_all
{
1105 my ($hostname, @opts) = @_;
1106 my %hints = ( flags
=> AI_V4MAPPED
| AI_ALL
,
1108 my ($err, @res) = Socket
::getaddrinfo
($hostname, '0', \
%hints);
1109 die "failed to get address info for: $hostname: $err\n" if $err;
1113 sub get_host_address_family
{
1114 my ($hostname, $socktype) = @_;
1115 my @res = getaddrinfo_all
($hostname, socktype
=> $socktype);
1116 return $res[0]->{family
};
1119 # Parses any sane kind of host, or host+port pair:
1120 # The port is always optional and thus may be undef.
1121 sub parse_host_and_port
{
1123 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1124 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1125 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1127 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests