]>
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);
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;
77 local $SIG{ALRM
} = sub { $sigcount++; }; # catch alarm outside eval
80 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
81 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
82 local $SIG{__DIE__
}; # see SA bug 4631
84 $prev_alarm = alarm($timeout);
86 $res = &$code(@param);
88 alarm(0); # avoid race conditions
93 alarm($prev_alarm) if defined($prev_alarm);
95 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
102 # flock: we use one file handle per process, so lock file
103 # can be called multiple times and succeeds for the same process.
105 my $lock_handles = {};
108 my ($filename, $timeout, $shared, $code, @param) = @_;
110 $timeout = 10 if !$timeout;
112 my $mode = $shared ? LOCK_SH
: LOCK_EX
;
114 my $lock_func = sub {
115 if (!$lock_handles->{$$}->{$filename}) {
116 $lock_handles->{$$}->{$filename} = new IO
::File
(">>$filename") ||
117 die "can't open file - $!\n";
120 if (!flock ($lock_handles->{$$}->{$filename}, $mode|LOCK_NB
)) {
121 print STDERR
"trying to aquire lock...";
124 $success = flock($lock_handles->{$$}->{$filename}, $mode);
125 # try again on EINTR (see bug #273)
126 if ($success || ($! != EINTR
)) {
131 print STDERR
" failed\n";
132 die "can't aquire lock - $!\n";
134 print STDERR
" OK\n";
140 eval { run_with_timeout
($timeout, $lock_func); };
143 $err = "can't lock file '$filename' - $err";
145 eval { $res = &$code(@param) };
149 if (my $fh = $lock_handles->{$$}->{$filename}) {
150 $lock_handles->{$$}->{$filename} = undef;
166 my ($filename, $timeout, $code, @param) = @_;
168 return lock_file_full
($filename, $timeout, 0, $code, @param);
171 sub file_set_contents
{
172 my ($filename, $data, $perm) = @_;
174 $perm = 0644 if !defined($perm);
176 my $tmpname = "$filename.tmp.$$";
179 my $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
, $perm);
180 die "unable to open file '$tmpname' - $!\n" if !$fh;
181 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
182 die "closing file '$tmpname' failed - $!\n" unless close $fh;
191 if (!rename($tmpname, $filename)) {
192 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
198 sub file_get_contents
{
199 my ($filename, $max) = @_;
201 my $fh = IO
::File-
>new($filename, "r") ||
202 die "can't open '$filename' - $!\n";
204 my $content = safe_read_from
($fh, $max);
211 sub file_read_firstline
{
214 my $fh = IO
::File-
>new ($filename, "r");
215 return undef if !$fh;
223 my ($fh, $max, $oneline) = @_;
225 $max = 32768 if !$max;
230 while ($count = sysread($fh, $input, 8192, $br)) {
232 die "input too long - aborting\n" if $br > $max;
233 if ($oneline && $input =~ m/^(.*)\n/) {
238 die "unable to read input - $!\n" if !defined($count);
244 my ($cmd, %param) = @_;
252 # see 'man bash' for option pipefail
253 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
258 $cmdstr = cmd2string
($cmd);
276 foreach my $p (keys %param) {
277 if ($p eq 'timeout') {
278 $timeout = $param{$p};
279 } elsif ($p eq 'umask') {
280 $old_umask = umask($param{$p});
281 } elsif ($p eq 'errmsg') {
282 $errmsg = $param{$p};
283 } elsif ($p eq 'input') {
285 } elsif ($p eq 'output') {
286 $output = $param{$p};
287 } elsif ($p eq 'outfunc') {
288 $outfunc = $param{$p};
289 } elsif ($p eq 'errfunc') {
290 $errfunc = $param{$p};
291 } elsif ($p eq 'logfunc') {
292 $logfunc = $param{$p};
293 } elsif ($p eq 'afterfork') {
294 $afterfork = $param{$p};
296 die "got unknown parameter '$p' for run_command\n";
301 my $origerrfunc = $errfunc;
305 &$origerrfunc("$laststderr\n");
307 print STDERR
"$laststderr\n" if $laststderr;
314 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
315 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
316 my $error = IO
::File-
>new();
318 # try to avoid locale related issues/warnings
319 my $lang = $param{lang
} || 'C';
324 local $ENV{LC_ALL
} = $lang;
326 # suppress LVM warnings like: "File descriptor 3 left open";
327 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
329 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
331 # if we pipe fron STDIN, open3 closes STDIN, so we we
332 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
333 # as soon as we open a new file.
334 # to avoid that we open /dev/null
335 if (!ref($writer) && !defined(fileno(STDIN
))) {
337 open(STDIN
, "</dev/null");
344 if ($orig_pid != $$) {
352 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
353 $oldtimeout = alarm($timeout) if $timeout;
355 &$afterfork() if $afterfork;
358 print $writer $input if defined $input;
362 my $select = new IO
::Select
;
363 $select->add($reader) if ref($reader);
364 $select->add($error);
369 my $starttime = time();
371 while ($select->count) {
372 my @handles = $select->can_read(1);
374 foreach my $h (@handles) {
376 my $count = sysread ($h, $buf, 4096);
377 if (!defined ($count)) {
383 $select->remove ($h) if !$count;
385 if ($outfunc || $logfunc) {
388 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
390 &$outfunc($line) if $outfunc;
391 &$logfunc($line) if $logfunc;
404 } elsif ($h eq $error) {
405 if ($errfunc || $logfunc) {
408 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
410 &$errfunc($line) if $errfunc;
411 &$logfunc($line) if $logfunc;
428 &$outfunc($outlog) if $outfunc && $outlog;
429 &$logfunc($outlog) if $logfunc && $outlog;
431 &$errfunc($errlog) if $errfunc && $errlog;
432 &$logfunc($errlog) if $logfunc && $errlog;
437 die "failed to execute\n";
438 } elsif (my $sig = ($? & 127)) {
439 die "got signal $sig\n";
440 } elsif (my $ec = ($? >> 8)) {
441 if (!($ec == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
442 if ($errmsg && $laststderr) {
443 my $lerr = $laststderr;
447 die "exit code $ec\n";
458 if ($errmsg && $laststderr) {
459 &$errfunc(undef); # flush laststderr
462 umask ($old_umask) if defined($old_umask);
464 alarm($oldtimeout) if $oldtimeout;
467 if ($pid && ($err eq "got timeout\n")) {
470 die "command '$cmdstr' failed: $err";
474 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
477 die "command '$cmdstr' failed: $err";
485 my $listtxt = shift || '';
487 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
489 $listtxt =~ s/[,;]/ /g;
490 $listtxt =~ s/^\s+//;
492 my @data = split (/\s+/, $listtxt);
500 return $txt if !defined($txt);
508 # simple uri templates like "/vms/{vmid}"
509 sub template_replace
{
510 my ($tmpl, $data) = @_;
512 return $tmpl if !$tmpl;
515 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
517 $res .= ($data->{$3} || '-') if $2;
523 my ($filename, $fh, $data) = @_;
527 my $res = print $fh $data;
529 die "write to '$filename' failed\n" if !$res;
535 'at' => 'ftp.at.debian.org',
536 'au' => 'ftp.au.debian.org',
537 'be' => 'ftp.be.debian.org',
538 'bg' => 'ftp.bg.debian.org',
539 'br' => 'ftp.br.debian.org',
540 'ca' => 'ftp.ca.debian.org',
541 'ch' => 'ftp.ch.debian.org',
542 'cl' => 'ftp.cl.debian.org',
543 'cz' => 'ftp.cz.debian.org',
544 'de' => 'ftp.de.debian.org',
545 'dk' => 'ftp.dk.debian.org',
546 'ee' => 'ftp.ee.debian.org',
547 'es' => 'ftp.es.debian.org',
548 'fi' => 'ftp.fi.debian.org',
549 'fr' => 'ftp.fr.debian.org',
550 'gr' => 'ftp.gr.debian.org',
551 'hk' => 'ftp.hk.debian.org',
552 'hr' => 'ftp.hr.debian.org',
553 'hu' => 'ftp.hu.debian.org',
554 'ie' => 'ftp.ie.debian.org',
555 'is' => 'ftp.is.debian.org',
556 'it' => 'ftp.it.debian.org',
557 'jp' => 'ftp.jp.debian.org',
558 'kr' => 'ftp.kr.debian.org',
559 'mx' => 'ftp.mx.debian.org',
560 'nl' => 'ftp.nl.debian.org',
561 'no' => 'ftp.no.debian.org',
562 'nz' => 'ftp.nz.debian.org',
563 'pl' => 'ftp.pl.debian.org',
564 'pt' => 'ftp.pt.debian.org',
565 'ro' => 'ftp.ro.debian.org',
566 'ru' => 'ftp.ru.debian.org',
567 'se' => 'ftp.se.debian.org',
568 'si' => 'ftp.si.debian.org',
569 'sk' => 'ftp.sk.debian.org',
570 'tr' => 'ftp.tr.debian.org',
571 'tw' => 'ftp.tw.debian.org',
572 'gb' => 'ftp.uk.debian.org',
573 'us' => 'ftp.us.debian.org',
578 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
579 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
580 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
581 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
582 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
583 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
584 #'et' => [], # Ethopia or Estonia ??
585 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
586 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
587 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
588 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
589 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
590 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
591 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
592 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
593 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
594 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
595 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
596 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
597 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
598 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
599 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
600 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
601 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
602 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
603 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
604 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
605 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
606 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
607 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
609 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
612 my $kvmkeymaparray = [];
613 foreach my $lc (keys %$keymaphash) {
614 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
622 return $kvmkeymaparray;
626 my ($param, $key) = @_;
628 my $res = $param->{$key};
629 delete $param->{$key};
634 # Note: we use this to wait until vncterm/spiceterm is ready
635 sub wait_for_vnc_port
{
636 my ($port, $timeout) = @_;
638 $timeout = 5 if !$timeout;
640 my $starttime = [gettimeofday
];
643 while (($elapsed = tv_interval
($starttime)) < $timeout) {
644 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
645 while (defined (my $line = <$fh>)) {
646 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
647 if ($port == hex($2)) {
655 $sleeptime += 100000 if $sleeptime < 1000000;
662 sub next_unused_port
{
663 my ($range_start, $range_end, $family) = @_;
665 # We use a file to register allocated ports.
666 # Those registrations expires after $expiretime.
667 # We use this to avoid race conditions between
668 # allocation and use of ports.
670 my $filename = "/var/tmp/pve-reserved-ports";
679 if (my $fh = IO
::File-
>new ($filename, "r")) {
680 while (my $line = <$fh>) {
681 if ($line =~ m/^(\d+)\s(\d+)$/) {
682 my ($port, $timestamp) = ($1, $2);
683 if (($timestamp + $expiretime) > $ctime) {
684 $ports->{$port} = $timestamp; # not expired
692 for (my $p = $range_start; $p < $range_end; $p++) {
693 next if $ports->{$p}; # reserved
695 my $sock = IO
::Socket
::IP-
>new(Listen
=> 5,
700 GetAddrInfoFlags
=> 0);
705 $ports->{$p} = $ctime;
711 foreach my $p (keys %$ports) {
712 $data .= "$p $ports->{$p}\n";
715 file_set_contents
($filename, $data);
720 my $p = lock_file
($filename, 10, $code);
723 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
728 sub next_migrate_port
{
730 return next_unused_port
(60000, 60050, $family);
735 return next_unused_port
(5900, 6000, $family);
738 sub next_spice_port
{
740 return next_unused_port
(61000, 61099, $family);
743 # NOTE: NFS syscall can't be interrupted, so alarm does
744 # not work to provide timeouts.
745 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
746 # So the spawn external 'df' process instead of using
747 # Filesys::Df (which uses statfs syscall)
749 my ($path, $timeout) = @_;
751 my $cmd = [ 'df', '-P', '-B', '1', $path];
761 if (my ($fsid, $total, $used, $avail) = $line =~
762 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
770 eval { run_command
($cmd, timeout
=> $timeout, outfunc
=> $parser); };
777 # We use this to uniquely identify a process.
778 # An 'Unique Process ID' has the following format:
779 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
784 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
785 # more that 8 characters for pstart
786 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
787 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
792 my ($upid, $noerr) = @_;
797 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
798 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
799 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]+):$/) {
801 $res->{pid
} = hex($3);
802 $res->{pstart
} = hex($4);
803 $res->{starttime
} = hex($5);
808 my $subdir = substr($5, 7, 8);
809 $filename = "$pvetaskdir/$subdir/$upid";
812 return undef if $noerr;
813 die "unable to parse worker upid '$upid'\n";
816 return wantarray ?
($res, $filename) : $res;
822 my ($task, $filename) = upid_decode
($upid);
824 my $dirname = dirname
($filename);
827 my $wwwid = getpwnam('www-data') ||
828 die "getpwnam failed";
832 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
833 die "unable to create output file '$filename' - $!\n";
834 chown $wwwid, -1, $outfh;
839 sub upid_read_status
{
842 my ($task, $filename) = upid_decode
($upid);
843 my $fh = IO
::File-
>new($filename, "r");
844 return "unable to open file - $!" if !$fh;
846 sysseek($fh, -$maxlen, 2);
848 my $br = sysread($fh, $readbuf, $maxlen);
851 return "unable to extract last line"
852 if $readbuf !~ m/\n?(.+)$/;
854 if ($line =~ m/^TASK OK$/) {
856 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
859 return "unexpected status";
862 return "unable to read tail (got $br bytes)";
865 # useful functions to store comments in config files
869 # all control and hi-bit characters, and ':'
870 my $unsafe = "^\x20-\x39\x3b-\x7e";
871 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
877 return Encode
::decode
("utf8", uri_unescape
($data));
880 sub decode_utf8_parameters
{
883 foreach my $p (qw(comment description firstname lastname)) {
884 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
890 sub random_ether_addr
{
892 my ($seconds, $microseconds) = gettimeofday
;
894 my $rand = Digest
::SHA
::sha1_hex
($$, rand(), $seconds, $microseconds);
897 for (my $i = 0; $i < 6; $i++) {
898 my $ss = hex(substr($rand, $i*2, 2));
900 $ss &= 0xfe; # clear multicast
901 $ss |= 2; # set local id
903 $ss = sprintf("%02X", $ss);
918 return String
::ShellQuote
::shell_quote
($str);
924 die "no arguments" if !$cmd;
926 return $cmd if !ref($cmd);
929 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
931 return join (' ', @qa);
934 # split an shell argument string into an array,
938 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
942 my ($filename, $start, $limit, $filter) = @_;
947 my $fh = IO
::File-
>new($filename, "r");
950 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
951 return ($count, $lines);
954 $start = 0 if !$start;
955 $limit = 50 if !$limit;
960 # duplicate code, so that we do not slow down normal path
961 while (defined($line = <$fh>)) {
962 next if $line !~ m/$filter/;
963 next if $count++ < $start;
966 push @$lines, { n
=> $count, t
=> $line};
970 while (defined($line = <$fh>)) {
971 next if $count++ < $start;
974 push @$lines, { n
=> $count, t
=> $line};
981 # HACK: ExtJS store.guaranteeRange() does not like empty array
985 push @$lines, { n
=> $count, t
=> "no content"};
988 return ($count, $lines);
992 my ($start, $limit, $filter) = @_;
997 $start = 0 if !$start;
998 $limit = 50 if !$limit;
1003 return if $count++ < $start;
1004 return if $limit <= 0;
1005 push @$lines, { n
=> int($count), t
=> $line};
1009 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1010 run_command
($cmd, outfunc
=> $parser);
1012 # HACK: ExtJS store.guaranteeRange() does not like empty array
1016 push @$lines, { n
=> $count, t
=> "no content"};
1019 return ($count, $lines);
1022 sub dir_glob_regex
{
1023 my ($dir, $regex) = @_;
1025 my $dh = IO
::Dir-
>new ($dir);
1026 return wantarray ?
() : undef if !$dh;
1028 while (defined(my $tmp = $dh->read)) {
1029 if (my @res = $tmp =~ m/^($regex)$/) {
1031 return wantarray ?
@res : $tmp;
1036 return wantarray ?
() : undef;
1039 sub dir_glob_foreach
{
1040 my ($dir, $regex, $func) = @_;
1042 my $dh = IO
::Dir-
>new ($dir);
1044 while (defined(my $tmp = $dh->read)) {
1045 if (my @res = $tmp =~ m/^($regex)$/) {
1052 sub assert_if_modified
{
1053 my ($digest1, $digest2) = @_;
1055 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1056 die "detected modified configuration - file changed by other user? Try again.\n";
1060 # Digest for short strings
1061 # like FNV32a, but we only return 31 bits (positive numbers)
1065 my $hval = 0x811c9dc5;
1067 foreach my $c (unpack('C*', $string)) {
1075 $hval = $hval & 0xffffffff;
1077 return $hval & 0x7fffffff;
1080 sub fnv31a_hex
{ return sprintf("%X", fnv31a
(@_)); }
1082 sub unpack_sockaddr_in46
{
1084 my $family = Socket
::sockaddr_family
($sin);
1085 my ($port, $host) = ($family == AF_INET6 ? Socket
::unpack_sockaddr_in6
($sin)
1086 : Socket
::unpack_sockaddr_in
($sin));
1087 return ($family, $port, $host);
1090 sub getaddrinfo_all
{
1091 my ($hostname, @opts) = @_;
1092 my %hints = ( flags
=> AI_V4MAPPED
| AI_ALL
,
1094 my ($err, @res) = Socket
::getaddrinfo
($hostname, '0', \
%hints);
1095 die "failed to get address info for: $hostname: $err\n" if $err;
1099 sub get_host_address_family
{
1100 my ($hostname, $socktype) = @_;
1101 my @res = getaddrinfo_all
($hostname, socktype
=> $socktype);
1102 return $res[0]->{family
};