]>
git.proxmox.com Git - pve-common.git/blob - src/PVE/Tools.pm
577a8bc2a70c6e915e6f1c6ba6b74e64cc37d466
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);
245 my ($cmd, %param) = @_;
253 # see 'man bash' for option pipefail
254 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
259 $cmdstr = cmd2string
($cmd);
277 foreach my $p (keys %param) {
278 if ($p eq 'timeout') {
279 $timeout = $param{$p};
280 } elsif ($p eq 'umask') {
281 $old_umask = umask($param{$p});
282 } elsif ($p eq 'errmsg') {
283 $errmsg = $param{$p};
284 } elsif ($p eq 'input') {
286 } elsif ($p eq 'output') {
287 $output = $param{$p};
288 } elsif ($p eq 'outfunc') {
289 $outfunc = $param{$p};
290 } elsif ($p eq 'errfunc') {
291 $errfunc = $param{$p};
292 } elsif ($p eq 'logfunc') {
293 $logfunc = $param{$p};
294 } elsif ($p eq 'afterfork') {
295 $afterfork = $param{$p};
297 die "got unknown parameter '$p' for run_command\n";
302 my $origerrfunc = $errfunc;
306 &$origerrfunc("$laststderr\n");
308 print STDERR
"$laststderr\n" if $laststderr;
315 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
316 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
317 my $error = IO
::File-
>new();
319 # try to avoid locale related issues/warnings
320 my $lang = $param{lang
} || 'C';
325 local $ENV{LC_ALL
} = $lang;
327 # suppress LVM warnings like: "File descriptor 3 left open";
328 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
330 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
332 # if we pipe fron STDIN, open3 closes STDIN, so we we
333 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
334 # as soon as we open a new file.
335 # to avoid that we open /dev/null
336 if (!ref($writer) && !defined(fileno(STDIN
))) {
338 open(STDIN
, "</dev/null");
345 if ($orig_pid != $$) {
353 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
354 $oldtimeout = alarm($timeout) if $timeout;
356 &$afterfork() if $afterfork;
359 print $writer $input if defined $input;
363 my $select = new IO
::Select
;
364 $select->add($reader) if ref($reader);
365 $select->add($error);
370 my $starttime = time();
372 while ($select->count) {
373 my @handles = $select->can_read(1);
375 foreach my $h (@handles) {
377 my $count = sysread ($h, $buf, 4096);
378 if (!defined ($count)) {
384 $select->remove ($h) if !$count;
386 if ($outfunc || $logfunc) {
389 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
391 &$outfunc($line) if $outfunc;
392 &$logfunc($line) if $logfunc;
405 } elsif ($h eq $error) {
406 if ($errfunc || $logfunc) {
409 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
411 &$errfunc($line) if $errfunc;
412 &$logfunc($line) if $logfunc;
429 &$outfunc($outlog) if $outfunc && $outlog;
430 &$logfunc($outlog) if $logfunc && $outlog;
432 &$errfunc($errlog) if $errfunc && $errlog;
433 &$logfunc($errlog) if $logfunc && $errlog;
438 die "failed to execute\n";
439 } elsif (my $sig = ($? & 127)) {
440 die "got signal $sig\n";
441 } elsif (my $ec = ($? >> 8)) {
442 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
443 if ($errmsg && $laststderr) {
444 my $lerr = $laststderr;
448 die "exit code $ec\n";
459 if ($errmsg && $laststderr) {
460 &$errfunc(undef); # flush laststderr
463 umask ($old_umask) if defined($old_umask);
465 alarm($oldtimeout) if $oldtimeout;
468 if ($pid && ($err eq "got timeout\n")) {
471 die "command '$cmdstr' failed: $err";
475 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
478 die "command '$cmdstr' failed: $err";
486 my $listtxt = shift || '';
488 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
490 $listtxt =~ s/[,;]/ /g;
491 $listtxt =~ s/^\s+//;
493 my @data = split (/\s+/, $listtxt);
501 return $txt if !defined($txt);
509 # simple uri templates like "/vms/{vmid}"
510 sub template_replace
{
511 my ($tmpl, $data) = @_;
513 return $tmpl if !$tmpl;
516 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
518 $res .= ($data->{$3} || '-') if $2;
524 my ($filename, $fh, $data) = @_;
528 my $res = print $fh $data;
530 die "write to '$filename' failed\n" if !$res;
536 'at' => 'ftp.at.debian.org',
537 'au' => 'ftp.au.debian.org',
538 'be' => 'ftp.be.debian.org',
539 'bg' => 'ftp.bg.debian.org',
540 'br' => 'ftp.br.debian.org',
541 'ca' => 'ftp.ca.debian.org',
542 'ch' => 'ftp.ch.debian.org',
543 'cl' => 'ftp.cl.debian.org',
544 'cz' => 'ftp.cz.debian.org',
545 'de' => 'ftp.de.debian.org',
546 'dk' => 'ftp.dk.debian.org',
547 'ee' => 'ftp.ee.debian.org',
548 'es' => 'ftp.es.debian.org',
549 'fi' => 'ftp.fi.debian.org',
550 'fr' => 'ftp.fr.debian.org',
551 'gr' => 'ftp.gr.debian.org',
552 'hk' => 'ftp.hk.debian.org',
553 'hr' => 'ftp.hr.debian.org',
554 'hu' => 'ftp.hu.debian.org',
555 'ie' => 'ftp.ie.debian.org',
556 'is' => 'ftp.is.debian.org',
557 'it' => 'ftp.it.debian.org',
558 'jp' => 'ftp.jp.debian.org',
559 'kr' => 'ftp.kr.debian.org',
560 'mx' => 'ftp.mx.debian.org',
561 'nl' => 'ftp.nl.debian.org',
562 'no' => 'ftp.no.debian.org',
563 'nz' => 'ftp.nz.debian.org',
564 'pl' => 'ftp.pl.debian.org',
565 'pt' => 'ftp.pt.debian.org',
566 'ro' => 'ftp.ro.debian.org',
567 'ru' => 'ftp.ru.debian.org',
568 'se' => 'ftp.se.debian.org',
569 'si' => 'ftp.si.debian.org',
570 'sk' => 'ftp.sk.debian.org',
571 'tr' => 'ftp.tr.debian.org',
572 'tw' => 'ftp.tw.debian.org',
573 'gb' => 'ftp.uk.debian.org',
574 'us' => 'ftp.us.debian.org',
579 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
580 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
581 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
582 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
583 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
584 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
585 #'et' => [], # Ethopia or Estonia ??
586 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
587 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
588 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
589 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
590 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
591 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
592 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
593 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
594 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
595 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
596 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
597 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
598 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
599 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
600 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
601 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
602 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
603 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
604 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
605 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
606 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
607 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
608 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
610 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
613 my $kvmkeymaparray = [];
614 foreach my $lc (keys %$keymaphash) {
615 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
623 return $kvmkeymaparray;
627 my ($param, $key) = @_;
629 my $res = $param->{$key};
630 delete $param->{$key};
635 # Note: we use this to wait until vncterm/spiceterm is ready
636 sub wait_for_vnc_port
{
637 my ($port, $timeout) = @_;
639 $timeout = 5 if !$timeout;
641 my $starttime = [gettimeofday
];
644 while (($elapsed = tv_interval
($starttime)) < $timeout) {
645 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
646 while (defined (my $line = <$fh>)) {
647 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
648 if ($port == hex($2)) {
656 $sleeptime += 100000 if $sleeptime < 1000000;
663 sub next_unused_port
{
664 my ($range_start, $range_end, $family) = @_;
666 # We use a file to register allocated ports.
667 # Those registrations expires after $expiretime.
668 # We use this to avoid race conditions between
669 # allocation and use of ports.
671 my $filename = "/var/tmp/pve-reserved-ports";
680 if (my $fh = IO
::File-
>new ($filename, "r")) {
681 while (my $line = <$fh>) {
682 if ($line =~ m/^(\d+)\s(\d+)$/) {
683 my ($port, $timestamp) = ($1, $2);
684 if (($timestamp + $expiretime) > $ctime) {
685 $ports->{$port} = $timestamp; # not expired
693 for (my $p = $range_start; $p < $range_end; $p++) {
694 next if $ports->{$p}; # reserved
696 my $sock = IO
::Socket
::IP-
>new(Listen
=> 5,
701 GetAddrInfoFlags
=> 0);
706 $ports->{$p} = $ctime;
712 foreach my $p (keys %$ports) {
713 $data .= "$p $ports->{$p}\n";
716 file_set_contents
($filename, $data);
721 my $p = lock_file
($filename, 10, $code);
724 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
729 sub next_migrate_port
{
731 return next_unused_port
(60000, 60050, $family);
736 return next_unused_port
(5900, 6000, $family);
739 sub next_spice_port
{
741 return next_unused_port
(61000, 61099, $family);
744 # NOTE: NFS syscall can't be interrupted, so alarm does
745 # not work to provide timeouts.
746 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
747 # So the spawn external 'df' process instead of using
748 # Filesys::Df (which uses statfs syscall)
750 my ($path, $timeout) = @_;
752 my $cmd = [ 'df', '-P', '-B', '1', $path];
762 if (my ($fsid, $total, $used, $avail) = $line =~
763 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
771 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
778 # We use this to uniquely identify a process.
779 # An 'Unique Process ID' has the following format:
780 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
785 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
786 # more that 8 characters for pstart
787 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
788 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
793 my ($upid, $noerr) = @_;
798 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
799 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
800 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]+):$/) {
802 $res->{pid
} = hex($3);
803 $res->{pstart
} = hex($4);
804 $res->{starttime
} = hex($5);
809 my $subdir = substr($5, 7, 8);
810 $filename = "$pvetaskdir/$subdir/$upid";
813 return undef if $noerr;
814 die "unable to parse worker upid '$upid'\n";
817 return wantarray ?
($res, $filename) : $res;
823 my ($task, $filename) = upid_decode
($upid);
825 my $dirname = dirname
($filename);
828 my $wwwid = getpwnam('www-data') ||
829 die "getpwnam failed";
833 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
834 die "unable to create output file '$filename' - $!\n";
835 chown $wwwid, -1, $outfh;
840 sub upid_read_status
{
843 my ($task, $filename) = upid_decode
($upid);
844 my $fh = IO
::File-
>new($filename, "r");
845 return "unable to open file - $!" if !$fh;
847 sysseek($fh, -$maxlen, 2);
849 my $br = sysread($fh, $readbuf, $maxlen);
852 return "unable to extract last line"
853 if $readbuf !~ m/\n?(.+)$/;
855 if ($line =~ m/^TASK OK$/) {
857 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
860 return "unexpected status";
863 return "unable to read tail (got $br bytes)";
866 # useful functions to store comments in config files
870 # all control and hi-bit characters, and ':'
871 my $unsafe = "^\x20-\x39\x3b-\x7e";
872 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
878 return Encode
::decode
("utf8", uri_unescape
($data));
881 sub decode_utf8_parameters
{
884 foreach my $p (qw(comment description firstname lastname)) {
885 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
891 sub random_ether_addr
{
893 my ($seconds, $microseconds) = gettimeofday
;
895 my $rand = Digest
::SHA
::sha1_hex
($$, rand(), $seconds, $microseconds);
898 for (my $i = 0; $i < 6; $i++) {
899 my $ss = hex(substr($rand, $i*2, 2));
901 $ss &= 0xfe; # clear multicast
902 $ss |= 2; # set local id
904 $ss = sprintf("%02X", $ss);
919 return String
::ShellQuote
::shell_quote
($str);
925 die "no arguments" if !$cmd;
927 return $cmd if !ref($cmd);
930 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
932 return join (' ', @qa);
935 # split an shell argument string into an array,
939 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
943 my ($filename, $start, $limit, $filter) = @_;
948 my $fh = IO
::File-
>new($filename, "r");
951 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
952 return ($count, $lines);
955 $start = 0 if !$start;
956 $limit = 50 if !$limit;
961 # duplicate code, so that we do not slow down normal path
962 while (defined($line = <$fh>)) {
963 next if $line !~ m/$filter/;
964 next if $count++ < $start;
967 push @$lines, { n
=> $count, t
=> $line};
971 while (defined($line = <$fh>)) {
972 next if $count++ < $start;
975 push @$lines, { n
=> $count, t
=> $line};
982 # HACK: ExtJS store.guaranteeRange() does not like empty array
986 push @$lines, { n
=> $count, t
=> "no content"};
989 return ($count, $lines);
993 my ($start, $limit, $filter) = @_;
998 $start = 0 if !$start;
999 $limit = 50 if !$limit;
1004 return if $count++ < $start;
1005 return if $limit <= 0;
1006 push @$lines, { n
=> int($count), t
=> $line};
1010 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1011 run_command
($cmd, outfunc
=> $parser);
1013 # HACK: ExtJS store.guaranteeRange() does not like empty array
1017 push @$lines, { n
=> $count, t
=> "no content"};
1020 return ($count, $lines);
1023 sub dir_glob_regex
{
1024 my ($dir, $regex) = @_;
1026 my $dh = IO
::Dir-
>new ($dir);
1027 return wantarray ?
() : undef if !$dh;
1029 while (defined(my $tmp = $dh->read)) {
1030 if (my @res = $tmp =~ m/^($regex)$/) {
1032 return wantarray ?
@res : $tmp;
1037 return wantarray ?
() : undef;
1040 sub dir_glob_foreach
{
1041 my ($dir, $regex, $func) = @_;
1043 my $dh = IO
::Dir-
>new ($dir);
1045 while (defined(my $tmp = $dh->read)) {
1046 if (my @res = $tmp =~ m/^($regex)$/) {
1053 sub assert_if_modified
{
1054 my ($digest1, $digest2) = @_;
1056 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1057 die "detected modified configuration - file changed by other user? Try again.\n";
1061 # Digest for short strings
1062 # like FNV32a, but we only return 31 bits (positive numbers)
1066 my $hval = 0x811c9dc5;
1068 foreach my $c (unpack('C*', $string)) {
1076 $hval = $hval & 0xffffffff;
1078 return $hval & 0x7fffffff;
1081 sub fnv31a_hex
{ return sprintf("%X", fnv31a
(@_)); }
1083 sub unpack_sockaddr_in46
{
1085 my $family = Socket
::sockaddr_family
($sin);
1086 my ($port, $host) = ($family == AF_INET6 ? Socket
::unpack_sockaddr_in6
($sin)
1087 : Socket
::unpack_sockaddr_in
($sin));
1088 return ($family, $port, $host);
1091 sub getaddrinfo_all
{
1092 my ($hostname, @opts) = @_;
1093 my %hints = ( flags
=> AI_V4MAPPED
| AI_ALL
,
1095 my ($err, @res) = Socket
::getaddrinfo
($hostname, '0', \
%hints);
1096 die "failed to get address info for: $hostname: $err\n" if $err;
1100 sub get_host_address_family
{
1101 my ($hostname, $socktype) = @_;
1102 my @res = getaddrinfo_all
($hostname, socktype
=> $socktype);
1103 return $res[0]->{family
};
1106 # Parses any sane kind of host, or host+port pair:
1107 # The port is always optional and thus may be undef.
1108 sub parse_host_and_port
{
1110 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1111 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1112 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1114 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests