]>
Commit | Line | Data |
---|---|---|
e143e9d8 DM |
1 | package PVE::Tools; |
2 | ||
3 | use strict; | |
c36f332e | 4 | use warnings; |
b5d12b08 | 5 | use POSIX qw(EINTR); |
00dc9d0f | 6 | use IO::Socket::IP; |
a956854f | 7 | use Socket qw(AF_INET AF_INET6 AI_ALL AI_V4MAPPED); |
e143e9d8 DM |
8 | use IO::Select; |
9 | use File::Basename; | |
10 | use File::Path qw(make_path); | |
11 | use IO::File; | |
7eb283fb | 12 | use IO::Dir; |
e143e9d8 DM |
13 | use IPC::Open3; |
14 | use Fcntl qw(:DEFAULT :flock); | |
15 | use base 'Exporter'; | |
16 | use URI::Escape; | |
17 | use Encode; | |
568ba6a4 | 18 | use Digest::SHA; |
e38bcd35 | 19 | use Text::ParseWords; |
7514b23a | 20 | use String::ShellQuote; |
c38cea65 | 21 | use Time::HiRes qw(usleep gettimeofday tv_interval alarm); |
e143e9d8 | 22 | |
57eeea0c DM |
23 | # avoid warning when parsing long hex values with hex() |
24 | no warnings 'portable'; # Support for 64-bit ints required | |
25 | ||
e143e9d8 | 26 | our @EXPORT_OK = qw( |
602ec0cd DM |
27 | $IPV6RE |
28 | $IPV4RE | |
e143e9d8 | 29 | lock_file |
493004a2 | 30 | lock_file_full |
e143e9d8 DM |
31 | run_command |
32 | file_set_contents | |
33 | file_get_contents | |
34 | file_read_firstline | |
7eb283fb DM |
35 | dir_glob_regex |
36 | dir_glob_foreach | |
e143e9d8 DM |
37 | split_list |
38 | template_replace | |
39 | safe_print | |
40 | trim | |
41 | extract_param | |
42 | ); | |
43 | ||
44 | my $pvelogdir = "/var/log/pve"; | |
45 | my $pvetaskdir = "$pvelogdir/tasks"; | |
46 | ||
47 | mkdir $pvelogdir; | |
48 | mkdir $pvetaskdir; | |
49 | ||
cd9bd252 | 50 | my $IPV4OCTET = "(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])"; |
602ec0cd DM |
51 | our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)"; |
52 | my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})"; | |
53 | my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))"; | |
54 | ||
55 | our $IPV6RE = "(?:" . | |
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)?::" . ")))"; | |
65 | ||
176b1186 WB |
66 | our $IPRE = "(?:$IPV4RE|$IPV6RE)"; |
67 | ||
952fd95e WB |
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); | |
74 | ||
0f0990f1 DM |
75 | sub run_with_timeout { |
76 | my ($timeout, $code, @param) = @_; | |
e143e9d8 | 77 | |
0f0990f1 | 78 | die "got timeout\n" if $timeout <= 0; |
e143e9d8 | 79 | |
c38cea65 | 80 | my $prev_alarm = alarm 0; # suspend outer alarm early |
0f0990f1 DM |
81 | |
82 | my $sigcount = 0; | |
e143e9d8 DM |
83 | |
84 | my $res; | |
85 | ||
e143e9d8 | 86 | eval { |
0f0990f1 DM |
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 | |
e143e9d8 | 90 | |
c38cea65 | 91 | alarm($timeout); |
e143e9d8 | 92 | |
c38cea65 | 93 | eval { $res = &$code(@param); }; |
0f0990f1 DM |
94 | |
95 | alarm(0); # avoid race conditions | |
c38cea65 WB |
96 | |
97 | die $@ if $@; | |
0f0990f1 DM |
98 | }; |
99 | ||
100 | my $err = $@; | |
101 | ||
c38cea65 | 102 | alarm $prev_alarm; |
0f0990f1 | 103 | |
c38cea65 | 104 | # this shouldn't happen anymore? |
0f0990f1 DM |
105 | die "unknown error" if $sigcount && !$err; # seems to happen sometimes |
106 | ||
107 | die $err if $err; | |
108 | ||
109 | return $res; | |
110 | } | |
e143e9d8 | 111 | |
0f0990f1 DM |
112 | # flock: we use one file handle per process, so lock file |
113 | # can be called multiple times and succeeds for the same process. | |
114 | ||
115 | my $lock_handles = {}; | |
116 | ||
493004a2 DM |
117 | sub lock_file_full { |
118 | my ($filename, $timeout, $shared, $code, @param) = @_; | |
0f0990f1 DM |
119 | |
120 | $timeout = 10 if !$timeout; | |
121 | ||
493004a2 DM |
122 | my $mode = $shared ? LOCK_SH : LOCK_EX; |
123 | ||
0f0990f1 | 124 | my $lock_func = sub { |
e143e9d8 DM |
125 | if (!$lock_handles->{$$}->{$filename}) { |
126 | $lock_handles->{$$}->{$filename} = new IO::File (">>$filename") || | |
0f0990f1 | 127 | die "can't open file - $!\n"; |
e143e9d8 DM |
128 | } |
129 | ||
493004a2 | 130 | if (!flock ($lock_handles->{$$}->{$filename}, $mode|LOCK_NB)) { |
e143e9d8 | 131 | print STDERR "trying to aquire lock..."; |
b5d12b08 DM |
132 | my $success; |
133 | while(1) { | |
493004a2 | 134 | $success = flock($lock_handles->{$$}->{$filename}, $mode); |
b5d12b08 DM |
135 | # try again on EINTR (see bug #273) |
136 | if ($success || ($! != EINTR)) { | |
137 | last; | |
138 | } | |
139 | } | |
140 | if (!$success) { | |
e143e9d8 | 141 | print STDERR " failed\n"; |
0f0990f1 | 142 | die "can't aquire lock - $!\n"; |
e143e9d8 DM |
143 | } |
144 | print STDERR " OK\n"; | |
145 | } | |
e143e9d8 DM |
146 | }; |
147 | ||
0f0990f1 | 148 | my $res; |
e143e9d8 | 149 | |
0f0990f1 DM |
150 | eval { run_with_timeout($timeout, $lock_func); }; |
151 | my $err = $@; | |
152 | if ($err) { | |
153 | $err = "can't lock file '$filename' - $err"; | |
154 | } else { | |
155 | eval { $res = &$code(@param) }; | |
156 | $err = $@; | |
157 | } | |
e143e9d8 | 158 | |
b192b930 | 159 | if (my $fh = $lock_handles->{$$}->{$filename}) { |
e143e9d8 DM |
160 | $lock_handles->{$$}->{$filename} = undef; |
161 | close ($fh); | |
162 | } | |
163 | ||
164 | if ($err) { | |
165 | $@ = $err; | |
166 | return undef; | |
167 | } | |
168 | ||
169 | $@ = undef; | |
170 | ||
171 | return $res; | |
172 | } | |
173 | ||
493004a2 DM |
174 | |
175 | sub lock_file { | |
176 | my ($filename, $timeout, $code, @param) = @_; | |
177 | ||
178 | return lock_file_full($filename, $timeout, 0, $code, @param); | |
179 | } | |
180 | ||
e143e9d8 DM |
181 | sub file_set_contents { |
182 | my ($filename, $data, $perm) = @_; | |
183 | ||
184 | $perm = 0644 if !defined($perm); | |
185 | ||
186 | my $tmpname = "$filename.tmp.$$"; | |
187 | ||
188 | eval { | |
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; | |
193 | }; | |
194 | my $err = $@; | |
195 | ||
196 | if ($err) { | |
197 | unlink $tmpname; | |
198 | die $err; | |
199 | } | |
200 | ||
201 | if (!rename($tmpname, $filename)) { | |
202 | my $msg = "close (rename) atomic file '$filename' failed: $!\n"; | |
203 | unlink $tmpname; | |
204 | die $msg; | |
205 | } | |
206 | } | |
207 | ||
208 | sub file_get_contents { | |
209 | my ($filename, $max) = @_; | |
210 | ||
211 | my $fh = IO::File->new($filename, "r") || | |
212 | die "can't open '$filename' - $!\n"; | |
213 | ||
214 | my $content = safe_read_from($fh, $max); | |
215 | ||
216 | close $fh; | |
217 | ||
218 | return $content; | |
219 | } | |
220 | ||
221 | sub file_read_firstline { | |
222 | my ($filename) = @_; | |
223 | ||
224 | my $fh = IO::File->new ($filename, "r"); | |
225 | return undef if !$fh; | |
226 | my $res = <$fh>; | |
88955a2e | 227 | chomp $res if $res; |
e143e9d8 DM |
228 | $fh->close; |
229 | return $res; | |
230 | } | |
231 | ||
232 | sub safe_read_from { | |
233 | my ($fh, $max, $oneline) = @_; | |
234 | ||
235 | $max = 32768 if !$max; | |
236 | ||
237 | my $br = 0; | |
238 | my $input = ''; | |
239 | my $count; | |
240 | while ($count = sysread($fh, $input, 8192, $br)) { | |
241 | $br += $count; | |
242 | die "input too long - aborting\n" if $br > $max; | |
243 | if ($oneline && $input =~ m/^(.*)\n/) { | |
244 | $input = $1; | |
245 | last; | |
246 | } | |
247 | } | |
248 | die "unable to read input - $!\n" if !defined($count); | |
249 | ||
250 | return $input; | |
251 | } | |
252 | ||
bd9c3a36 WB |
253 | # The $cmd parameter can be: |
254 | # -) a string | |
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: | |
259 | # set -o pipefail && | |
260 | # *) without a pipe: passed to perl's open3 which uses 'sh -c' | |
261 | # (Note that this may result in two different syntax requirements!) | |
262 | # FIXME? | |
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.) | |
fcdc0cfc WB |
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 | |
270 | # command. | |
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 | |
e143e9d8 DM |
278 | sub run_command { |
279 | my ($cmd, %param) = @_; | |
280 | ||
281 | my $old_umask; | |
ded47a61 | 282 | my $cmdstr; |
e143e9d8 | 283 | |
fcdc0cfc WB |
284 | if (my $ref = ref($cmd)) { |
285 | if (ref($cmd->[0])) { | |
286 | $cmdstr = 'set -o pipefail && '; | |
287 | my $pipe = ''; | |
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); | |
292 | $pipe = ' | '; | |
293 | } | |
294 | $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmdstr" ]; | |
295 | } else { | |
296 | $cmdstr = cmd2string($cmd); | |
297 | } | |
298 | } else { | |
ded47a61 | 299 | $cmdstr = $cmd; |
22d4efe6 | 300 | if ($cmd =~ m/\|/) { |
e0cabd2c DM |
301 | # see 'man bash' for option pipefail |
302 | $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ]; | |
303 | } else { | |
304 | $cmd = [ $cmd ]; | |
305 | } | |
ded47a61 | 306 | } |
e143e9d8 DM |
307 | |
308 | my $errmsg; | |
309 | my $laststderr; | |
310 | my $timeout; | |
311 | my $oldtimeout; | |
312 | my $pid; | |
313 | ||
4630cb95 DM |
314 | my $outfunc; |
315 | my $errfunc; | |
316 | my $logfunc; | |
317 | my $input; | |
318 | my $output; | |
a417477c | 319 | my $afterfork; |
4630cb95 | 320 | |
e143e9d8 | 321 | eval { |
e143e9d8 DM |
322 | |
323 | foreach my $p (keys %param) { | |
324 | if ($p eq 'timeout') { | |
325 | $timeout = $param{$p}; | |
326 | } elsif ($p eq 'umask') { | |
eb9e24df | 327 | $old_umask = umask($param{$p}); |
e143e9d8 DM |
328 | } elsif ($p eq 'errmsg') { |
329 | $errmsg = $param{$p}; | |
e143e9d8 DM |
330 | } elsif ($p eq 'input') { |
331 | $input = $param{$p}; | |
1c50a24a DM |
332 | } elsif ($p eq 'output') { |
333 | $output = $param{$p}; | |
e143e9d8 DM |
334 | } elsif ($p eq 'outfunc') { |
335 | $outfunc = $param{$p}; | |
336 | } elsif ($p eq 'errfunc') { | |
337 | $errfunc = $param{$p}; | |
776fbfa8 DM |
338 | } elsif ($p eq 'logfunc') { |
339 | $logfunc = $param{$p}; | |
a417477c DM |
340 | } elsif ($p eq 'afterfork') { |
341 | $afterfork = $param{$p}; | |
e143e9d8 DM |
342 | } else { |
343 | die "got unknown parameter '$p' for run_command\n"; | |
344 | } | |
345 | } | |
346 | ||
4630cb95 DM |
347 | if ($errmsg) { |
348 | my $origerrfunc = $errfunc; | |
349 | $errfunc = sub { | |
350 | if ($laststderr) { | |
351 | if ($origerrfunc) { | |
352 | &$origerrfunc("$laststderr\n"); | |
353 | } else { | |
354 | print STDERR "$laststderr\n" if $laststderr; | |
355 | } | |
356 | } | |
357 | $laststderr = shift; | |
358 | }; | |
359 | } | |
360 | ||
1c50a24a DM |
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(); | |
364 | ||
e143e9d8 DM |
365 | # try to avoid locale related issues/warnings |
366 | my $lang = $param{lang} || 'C'; | |
367 | ||
368 | my $orig_pid = $$; | |
369 | ||
370 | eval { | |
329351e2 | 371 | local $ENV{LC_ALL} = $lang; |
e143e9d8 DM |
372 | |
373 | # suppress LVM warnings like: "File descriptor 3 left open"; | |
374 | local $ENV{LVM_SUPPRESS_FD_WARNINGS} = "1"; | |
375 | ||
376 | $pid = open3($writer, $reader, $error, @$cmd) || die $!; | |
f38995ab DM |
377 | |
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))) { | |
383 | POSIX::close(0); | |
384 | open(STDIN, "</dev/null"); | |
385 | } | |
e143e9d8 DM |
386 | }; |
387 | ||
388 | my $err = $@; | |
389 | ||
390 | # catch exec errors | |
391 | if ($orig_pid != $$) { | |
392 | warn "ERROR: $err"; | |
393 | POSIX::_exit (1); | |
394 | kill ('KILL', $$); | |
395 | } | |
396 | ||
397 | die $err if $err; | |
398 | ||
399 | local $SIG{ALRM} = sub { die "got timeout\n"; } if $timeout; | |
400 | $oldtimeout = alarm($timeout) if $timeout; | |
401 | ||
a417477c DM |
402 | &$afterfork() if $afterfork; |
403 | ||
f38995ab DM |
404 | if (ref($writer)) { |
405 | print $writer $input if defined $input; | |
406 | close $writer; | |
407 | } | |
e143e9d8 DM |
408 | |
409 | my $select = new IO::Select; | |
f38995ab | 410 | $select->add($reader) if ref($reader); |
e143e9d8 DM |
411 | $select->add($error); |
412 | ||
413 | my $outlog = ''; | |
414 | my $errlog = ''; | |
415 | ||
416 | my $starttime = time(); | |
417 | ||
418 | while ($select->count) { | |
419 | my @handles = $select->can_read(1); | |
420 | ||
421 | foreach my $h (@handles) { | |
422 | my $buf = ''; | |
423 | my $count = sysread ($h, $buf, 4096); | |
424 | if (!defined ($count)) { | |
425 | my $err = $!; | |
426 | kill (9, $pid); | |
427 | waitpid ($pid, 0); | |
428 | die $err; | |
429 | } | |
430 | $select->remove ($h) if !$count; | |
431 | if ($h eq $reader) { | |
776fbfa8 | 432 | if ($outfunc || $logfunc) { |
e143e9d8 DM |
433 | eval { |
434 | $outlog .= $buf; | |
435 | while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) { | |
436 | my $line = $1; | |
776fbfa8 DM |
437 | &$outfunc($line) if $outfunc; |
438 | &$logfunc($line) if $logfunc; | |
e143e9d8 DM |
439 | } |
440 | }; | |
441 | my $err = $@; | |
442 | if ($err) { | |
443 | kill (9, $pid); | |
444 | waitpid ($pid, 0); | |
445 | die $err; | |
446 | } | |
447 | } else { | |
448 | print $buf; | |
449 | *STDOUT->flush(); | |
450 | } | |
451 | } elsif ($h eq $error) { | |
776fbfa8 | 452 | if ($errfunc || $logfunc) { |
e143e9d8 DM |
453 | eval { |
454 | $errlog .= $buf; | |
455 | while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) { | |
456 | my $line = $1; | |
776fbfa8 DM |
457 | &$errfunc($line) if $errfunc; |
458 | &$logfunc($line) if $logfunc; | |
e143e9d8 DM |
459 | } |
460 | }; | |
461 | my $err = $@; | |
462 | if ($err) { | |
463 | kill (9, $pid); | |
464 | waitpid ($pid, 0); | |
465 | die $err; | |
466 | } | |
467 | } else { | |
468 | print STDERR $buf; | |
469 | *STDERR->flush(); | |
470 | } | |
471 | } | |
472 | } | |
473 | } | |
474 | ||
475 | &$outfunc($outlog) if $outfunc && $outlog; | |
776fbfa8 DM |
476 | &$logfunc($outlog) if $logfunc && $outlog; |
477 | ||
e143e9d8 | 478 | &$errfunc($errlog) if $errfunc && $errlog; |
776fbfa8 | 479 | &$logfunc($errlog) if $logfunc && $errlog; |
e143e9d8 DM |
480 | |
481 | waitpid ($pid, 0); | |
482 | ||
483 | if ($? == -1) { | |
484 | die "failed to execute\n"; | |
485 | } elsif (my $sig = ($? & 127)) { | |
486 | die "got signal $sig\n"; | |
487 | } elsif (my $ec = ($? >> 8)) { | |
1c50a24a DM |
488 | if (!($ec == 24 && ($cmdstr =~ m|^(\S+/)?rsync\s|))) { |
489 | if ($errmsg && $laststderr) { | |
490 | my $lerr = $laststderr; | |
491 | $laststderr = undef; | |
492 | die "$lerr\n"; | |
493 | } | |
494 | die "exit code $ec\n"; | |
e143e9d8 | 495 | } |
e143e9d8 DM |
496 | } |
497 | ||
498 | alarm(0); | |
499 | }; | |
500 | ||
501 | my $err = $@; | |
502 | ||
503 | alarm(0); | |
504 | ||
4630cb95 DM |
505 | if ($errmsg && $laststderr) { |
506 | &$errfunc(undef); # flush laststderr | |
507 | } | |
e143e9d8 DM |
508 | |
509 | umask ($old_umask) if defined($old_umask); | |
510 | ||
511 | alarm($oldtimeout) if $oldtimeout; | |
512 | ||
513 | if ($err) { | |
514 | if ($pid && ($err eq "got timeout\n")) { | |
515 | kill (9, $pid); | |
516 | waitpid ($pid, 0); | |
517 | die "command '$cmdstr' failed: $err"; | |
518 | } | |
519 | ||
520 | if ($errmsg) { | |
adbc988d | 521 | $err =~ s/^usermod:\s*// if $cmdstr =~ m|^(\S+/)?usermod\s|; |
e143e9d8 DM |
522 | die "$errmsg: $err"; |
523 | } else { | |
524 | die "command '$cmdstr' failed: $err"; | |
525 | } | |
526 | } | |
1c50a24a DM |
527 | |
528 | return undef; | |
e143e9d8 DM |
529 | } |
530 | ||
531 | sub split_list { | |
532 | my $listtxt = shift || ''; | |
533 | ||
d2b0374d DM |
534 | return split (/\0/, $listtxt) if $listtxt =~ m/\0/; |
535 | ||
536 | $listtxt =~ s/[,;]/ /g; | |
e143e9d8 DM |
537 | $listtxt =~ s/^\s+//; |
538 | ||
539 | my @data = split (/\s+/, $listtxt); | |
540 | ||
541 | return @data; | |
542 | } | |
543 | ||
544 | sub trim { | |
545 | my $txt = shift; | |
546 | ||
547 | return $txt if !defined($txt); | |
548 | ||
549 | $txt =~ s/^\s+//; | |
550 | $txt =~ s/\s+$//; | |
551 | ||
552 | return $txt; | |
553 | } | |
554 | ||
555 | # simple uri templates like "/vms/{vmid}" | |
556 | sub template_replace { | |
557 | my ($tmpl, $data) = @_; | |
558 | ||
3250f5c7 DM |
559 | return $tmpl if !$tmpl; |
560 | ||
e143e9d8 DM |
561 | my $res = ''; |
562 | while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) { | |
563 | $res .= $1 if $1; | |
564 | $res .= ($data->{$3} || '-') if $2; | |
565 | } | |
566 | return $res; | |
567 | } | |
568 | ||
569 | sub safe_print { | |
570 | my ($filename, $fh, $data) = @_; | |
571 | ||
572 | return if !$data; | |
573 | ||
574 | my $res = print $fh $data; | |
575 | ||
576 | die "write to '$filename' failed\n" if !$res; | |
577 | } | |
578 | ||
579 | sub debmirrors { | |
580 | ||
581 | return { | |
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', | |
621 | }; | |
622 | } | |
623 | ||
910d57b0 DM |
624 | my $keymaphash = { |
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' ], | |
5a5ca434 DM |
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 ], | |
910d57b0 DM |
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], | |
9934cd0b | 654 | 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'], |
910d57b0 | 655 | #'th' => [], |
c10cc112 | 656 | 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef], |
910d57b0 DM |
657 | }; |
658 | ||
659 | my $kvmkeymaparray = []; | |
660 | foreach my $lc (keys %$keymaphash) { | |
661 | push @$kvmkeymaparray, $keymaphash->{$lc}->[1]; | |
662 | } | |
663 | ||
e143e9d8 | 664 | sub kvmkeymaps { |
910d57b0 DM |
665 | return $keymaphash; |
666 | } | |
667 | ||
668 | sub kvmkeymaplist { | |
669 | return $kvmkeymaparray; | |
e143e9d8 DM |
670 | } |
671 | ||
672 | sub extract_param { | |
673 | my ($param, $key) = @_; | |
674 | ||
675 | my $res = $param->{$key}; | |
676 | delete $param->{$key}; | |
677 | ||
678 | return $res; | |
679 | } | |
680 | ||
eb7047f6 | 681 | # Note: we use this to wait until vncterm/spiceterm is ready |
ec6d95b4 DM |
682 | sub wait_for_vnc_port { |
683 | my ($port, $timeout) = @_; | |
684 | ||
685 | $timeout = 5 if !$timeout; | |
eb7047f6 DM |
686 | my $sleeptime = 0; |
687 | my $starttime = [gettimeofday]; | |
688 | my $elapsed; | |
ec6d95b4 | 689 | |
eb7047f6 | 690 | while (($elapsed = tv_interval($starttime)) < $timeout) { |
ec6d95b4 DM |
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)) { | |
695 | close($fh); | |
696 | return 1; | |
697 | } | |
698 | } | |
699 | } | |
700 | close($fh); | |
701 | } | |
eb7047f6 DM |
702 | $sleeptime += 100000 if $sleeptime < 1000000; |
703 | usleep($sleeptime); | |
ec6d95b4 DM |
704 | } |
705 | ||
706 | return undef; | |
707 | } | |
708 | ||
59b3f563 | 709 | sub next_unused_port { |
46775218 | 710 | my ($range_start, $range_end, $family) = @_; |
59b3f563 DM |
711 | |
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. | |
716 | ||
717 | my $filename = "/var/tmp/pve-reserved-ports"; | |
e143e9d8 | 718 | |
59b3f563 | 719 | my $code = sub { |
e143e9d8 | 720 | |
59b3f563 DM |
721 | my $expiretime = 5; |
722 | my $ctime = time(); | |
e143e9d8 | 723 | |
59b3f563 DM |
724 | my $ports = {}; |
725 | ||
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 | |
732 | } | |
733 | } | |
734 | } | |
e143e9d8 | 735 | } |
59b3f563 DM |
736 | |
737 | my $newport; | |
738 | ||
739 | for (my $p = $range_start; $p < $range_end; $p++) { | |
740 | next if $ports->{$p}; # reserved | |
741 | ||
00dc9d0f | 742 | my $sock = IO::Socket::IP->new(Listen => 5, |
00dc9d0f WB |
743 | LocalPort => $p, |
744 | ReuseAddr => 1, | |
46775218 | 745 | Family => $family, |
e43b3a0f WB |
746 | Proto => 0, |
747 | GetAddrInfoFlags => 0); | |
59b3f563 DM |
748 | |
749 | if ($sock) { | |
750 | close($sock); | |
751 | $newport = $p; | |
752 | $ports->{$p} = $ctime; | |
753 | last; | |
754 | } | |
755 | } | |
756 | ||
757 | my $data = ""; | |
758 | foreach my $p (keys %$ports) { | |
759 | $data .= "$p $ports->{$p}\n"; | |
760 | } | |
761 | ||
762 | file_set_contents($filename, $data); | |
e143e9d8 | 763 | |
59b3f563 DM |
764 | return $newport; |
765 | }; | |
766 | ||
767 | my $p = lock_file($filename, 10, $code); | |
768 | die $@ if $@; | |
769 | ||
770 | die "unable to find free port (${range_start}-${range_end})\n" if !$p; | |
771 | ||
772 | return $p; | |
773 | } | |
774 | ||
775 | sub next_migrate_port { | |
46775218 WB |
776 | my ($family) = @_; |
777 | return next_unused_port(60000, 60050, $family); | |
59b3f563 DM |
778 | } |
779 | ||
780 | sub next_vnc_port { | |
46775218 WB |
781 | my ($family) = @_; |
782 | return next_unused_port(5900, 6000, $family); | |
59b3f563 | 783 | } |
e143e9d8 | 784 | |
2f13cbb5 | 785 | sub next_spice_port { |
46775218 WB |
786 | my ($family) = @_; |
787 | return next_unused_port(61000, 61099, $family); | |
2f13cbb5 DM |
788 | } |
789 | ||
e143e9d8 DM |
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) | |
795 | sub df { | |
796 | my ($path, $timeout) = @_; | |
797 | ||
798 | my $cmd = [ 'df', '-P', '-B', '1', $path]; | |
799 | ||
800 | my $res = { | |
801 | total => 0, | |
802 | used => 0, | |
803 | avail => 0, | |
804 | }; | |
805 | ||
806 | my $parser = sub { | |
807 | my $line = shift; | |
808 | if (my ($fsid, $total, $used, $avail) = $line =~ | |
809 | m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) { | |
810 | $res = { | |
811 | total => $total, | |
812 | used => $used, | |
813 | avail => $avail, | |
814 | }; | |
815 | } | |
816 | }; | |
817 | eval { run_command($cmd, timeout => $timeout, outfunc => $parser); }; | |
818 | warn $@ if $@; | |
819 | ||
820 | return $res; | |
821 | } | |
822 | ||
823 | # UPID helper | |
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" | |
827 | ||
828 | sub upid_encode { | |
829 | my $d = shift; | |
830 | ||
19cec230 DM |
831 | # Note: pstart can be > 32bit if uptime > 497 days, so this can result in |
832 | # more that 8 characters for pstart | |
e143e9d8 DM |
833 | return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid}, |
834 | $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id}, | |
835 | $d->{user}); | |
836 | } | |
837 | ||
838 | sub upid_decode { | |
839 | my ($upid, $noerr) = @_; | |
840 | ||
841 | my $res; | |
842 | my $filename; | |
843 | ||
844 | # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user" | |
19cec230 DM |
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]+):$/) { | |
e143e9d8 | 847 | $res->{node} = $1; |
3702f038 DM |
848 | $res->{pid} = hex($3); |
849 | $res->{pstart} = hex($4); | |
850 | $res->{starttime} = hex($5); | |
851 | $res->{type} = $6; | |
852 | $res->{id} = $7; | |
853 | $res->{user} = $8; | |
854 | ||
855 | my $subdir = substr($5, 7, 8); | |
e143e9d8 DM |
856 | $filename = "$pvetaskdir/$subdir/$upid"; |
857 | ||
858 | } else { | |
859 | return undef if $noerr; | |
860 | die "unable to parse worker upid '$upid'\n"; | |
861 | } | |
862 | ||
863 | return wantarray ? ($res, $filename) : $res; | |
864 | } | |
865 | ||
866 | sub upid_open { | |
867 | my ($upid) = @_; | |
868 | ||
869 | my ($task, $filename) = upid_decode($upid); | |
870 | ||
871 | my $dirname = dirname($filename); | |
872 | make_path($dirname); | |
873 | ||
874 | my $wwwid = getpwnam('www-data') || | |
875 | die "getpwnam failed"; | |
876 | ||
877 | my $perm = 0640; | |
878 | ||
879 | my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) || | |
880 | die "unable to create output file '$filename' - $!\n"; | |
2b8e0f12 | 881 | chown $wwwid, -1, $outfh; |
e143e9d8 DM |
882 | |
883 | return $outfh; | |
884 | }; | |
885 | ||
886 | sub upid_read_status { | |
887 | my ($upid) = @_; | |
888 | ||
889 | my ($task, $filename) = upid_decode($upid); | |
890 | my $fh = IO::File->new($filename, "r"); | |
891 | return "unable to open file - $!" if !$fh; | |
cc9121d3 | 892 | my $maxlen = 4096; |
e143e9d8 DM |
893 | sysseek($fh, -$maxlen, 2); |
894 | my $readbuf = ''; | |
895 | my $br = sysread($fh, $readbuf, $maxlen); | |
896 | close($fh); | |
897 | if ($br) { | |
898 | return "unable to extract last line" | |
899 | if $readbuf !~ m/\n?(.+)$/; | |
900 | my $line = $1; | |
901 | if ($line =~ m/^TASK OK$/) { | |
902 | return 'OK'; | |
903 | } elsif ($line =~ m/^TASK ERROR: (.+)$/) { | |
904 | return $1; | |
905 | } else { | |
906 | return "unexpected status"; | |
907 | } | |
908 | } | |
909 | return "unable to read tail (got $br bytes)"; | |
910 | } | |
911 | ||
912 | # useful functions to store comments in config files | |
913 | sub encode_text { | |
914 | my ($text) = @_; | |
915 | ||
916 | # all control and hi-bit characters, and ':' | |
917 | my $unsafe = "^\x20-\x39\x3b-\x7e"; | |
918 | return uri_escape(Encode::encode("utf8", $text), $unsafe); | |
919 | } | |
920 | ||
921 | sub decode_text { | |
922 | my ($data) = @_; | |
923 | ||
924 | return Encode::decode("utf8", uri_unescape($data)); | |
925 | } | |
926 | ||
815b2aba DM |
927 | sub decode_utf8_parameters { |
928 | my ($param) = @_; | |
929 | ||
34ebb226 | 930 | foreach my $p (qw(comment description firstname lastname)) { |
815b2aba DM |
931 | $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p}; |
932 | } | |
933 | ||
934 | return $param; | |
935 | } | |
936 | ||
a413a515 DM |
937 | sub random_ether_addr { |
938 | ||
46a11c00 DM |
939 | my ($seconds, $microseconds) = gettimeofday; |
940 | ||
941 | my $rand = Digest::SHA::sha1_hex($$, rand(), $seconds, $microseconds); | |
a413a515 | 942 | |
de9a267f PM |
943 | # clear multicast, set local id |
944 | vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2; | |
a413a515 | 945 | |
de9a267f PM |
946 | my $mac = sprintf("%02X:" x 6, unpack("C6", $rand)); |
947 | ||
948 | # remove superfluous ":" at end | |
949 | chop($mac); | |
a413a515 DM |
950 | |
951 | return $mac; | |
952 | } | |
e143e9d8 | 953 | |
762e3223 DM |
954 | sub shellquote { |
955 | my $str = shift; | |
956 | ||
7514b23a | 957 | return String::ShellQuote::shell_quote($str); |
762e3223 DM |
958 | } |
959 | ||
65e1d3fc DM |
960 | sub cmd2string { |
961 | my ($cmd) = @_; | |
962 | ||
963 | die "no arguments" if !$cmd; | |
964 | ||
965 | return $cmd if !ref($cmd); | |
966 | ||
967 | my @qa = (); | |
968 | foreach my $arg (@$cmd) { push @qa, shellquote($arg); } | |
969 | ||
970 | return join (' ', @qa); | |
971 | } | |
972 | ||
e38bcd35 | 973 | # split an shell argument string into an array, |
f9125663 DM |
974 | sub split_args { |
975 | my ($str) = @_; | |
976 | ||
e38bcd35 | 977 | return $str ? [ Text::ParseWords::shellwords($str) ] : []; |
f9125663 DM |
978 | } |
979 | ||
804b1041 | 980 | sub dump_logfile { |
eb7e5538 | 981 | my ($filename, $start, $limit, $filter) = @_; |
804b1041 DM |
982 | |
983 | my $lines = []; | |
984 | my $count = 0; | |
985 | ||
986 | my $fh = IO::File->new($filename, "r"); | |
987 | if (!$fh) { | |
988 | $count++; | |
989 | push @$lines, { n => $count, t => "unable to open file - $!"}; | |
990 | return ($count, $lines); | |
991 | } | |
992 | ||
993 | $start = 0 if !$start; | |
994 | $limit = 50 if !$limit; | |
995 | ||
996 | my $line; | |
eb7e5538 DM |
997 | |
998 | if ($filter) { | |
999 | # duplicate code, so that we do not slow down normal path | |
1000 | while (defined($line = <$fh>)) { | |
1001 | next if $line !~ m/$filter/; | |
1002 | next if $count++ < $start; | |
1003 | next if $limit <= 0; | |
1004 | chomp $line; | |
1005 | push @$lines, { n => $count, t => $line}; | |
1006 | $limit--; | |
1007 | } | |
1008 | } else { | |
1009 | while (defined($line = <$fh>)) { | |
1010 | next if $count++ < $start; | |
1011 | next if $limit <= 0; | |
1012 | chomp $line; | |
1013 | push @$lines, { n => $count, t => $line}; | |
1014 | $limit--; | |
1015 | } | |
804b1041 DM |
1016 | } |
1017 | ||
1018 | close($fh); | |
1019 | ||
6de95a66 DM |
1020 | # HACK: ExtJS store.guaranteeRange() does not like empty array |
1021 | # so we add a line | |
1022 | if (!$count) { | |
1023 | $count++; | |
1024 | push @$lines, { n => $count, t => "no content"}; | |
1025 | } | |
1026 | ||
1027 | return ($count, $lines); | |
1028 | } | |
1029 | ||
1030 | sub dump_journal { | |
1031 | my ($start, $limit, $filter) = @_; | |
1032 | ||
1033 | my $lines = []; | |
1034 | my $count = 0; | |
1035 | ||
1036 | $start = 0 if !$start; | |
1037 | $limit = 50 if !$limit; | |
1038 | ||
1039 | my $parser = sub { | |
1040 | my $line = shift; | |
1041 | ||
1042 | return if $count++ < $start; | |
1043 | return if $limit <= 0; | |
1044 | push @$lines, { n => int($count), t => $line}; | |
1045 | $limit--; | |
1046 | }; | |
1047 | ||
1048 | my $cmd = ['journalctl', '-o', 'short', '--no-pager']; | |
1049 | run_command($cmd, outfunc => $parser); | |
1050 | ||
804b1041 DM |
1051 | # HACK: ExtJS store.guaranteeRange() does not like empty array |
1052 | # so we add a line | |
1053 | if (!$count) { | |
1054 | $count++; | |
1055 | push @$lines, { n => $count, t => "no content"}; | |
1056 | } | |
1057 | ||
1058 | return ($count, $lines); | |
1059 | } | |
1060 | ||
7eb283fb DM |
1061 | sub dir_glob_regex { |
1062 | my ($dir, $regex) = @_; | |
1063 | ||
1064 | my $dh = IO::Dir->new ($dir); | |
1065 | return wantarray ? () : undef if !$dh; | |
1066 | ||
1067 | while (defined(my $tmp = $dh->read)) { | |
1068 | if (my @res = $tmp =~ m/^($regex)$/) { | |
1069 | $dh->close; | |
1070 | return wantarray ? @res : $tmp; | |
1071 | } | |
1072 | } | |
1073 | $dh->close; | |
1074 | ||
1075 | return wantarray ? () : undef; | |
1076 | } | |
1077 | ||
1078 | sub dir_glob_foreach { | |
1079 | my ($dir, $regex, $func) = @_; | |
1080 | ||
1081 | my $dh = IO::Dir->new ($dir); | |
1082 | if (defined $dh) { | |
1083 | while (defined(my $tmp = $dh->read)) { | |
1084 | if (my @res = $tmp =~ m/^($regex)$/) { | |
1085 | &$func (@res); | |
1086 | } | |
1087 | } | |
1088 | } | |
1089 | } | |
1090 | ||
a345b9d5 DM |
1091 | sub assert_if_modified { |
1092 | my ($digest1, $digest2) = @_; | |
1093 | ||
1094 | if ($digest1 && $digest2 && ($digest1 ne $digest2)) { | |
212fc0b7 | 1095 | die "detected modified configuration - file changed by other user? Try again.\n"; |
a345b9d5 DM |
1096 | } |
1097 | } | |
1098 | ||
2d3bca34 DM |
1099 | # Digest for short strings |
1100 | # like FNV32a, but we only return 31 bits (positive numbers) | |
1101 | sub fnv31a { | |
1102 | my ($string) = @_; | |
1103 | ||
1104 | my $hval = 0x811c9dc5; | |
1105 | ||
1106 | foreach my $c (unpack('C*', $string)) { | |
1107 | $hval ^= $c; | |
1108 | $hval += ( | |
1109 | (($hval << 1) ) + | |
1110 | (($hval << 4) ) + | |
1111 | (($hval << 7) ) + | |
1112 | (($hval << 8) ) + | |
1113 | (($hval << 24) ) ); | |
1114 | $hval = $hval & 0xffffffff; | |
1115 | } | |
1116 | return $hval & 0x7fffffff; | |
1117 | } | |
1118 | ||
1119 | sub fnv31a_hex { return sprintf("%X", fnv31a(@_)); } | |
1120 | ||
8df6b794 WB |
1121 | sub unpack_sockaddr_in46 { |
1122 | my ($sin) = @_; | |
1123 | my $family = Socket::sockaddr_family($sin); | |
1124 | my ($port, $host) = ($family == AF_INET6 ? Socket::unpack_sockaddr_in6($sin) | |
1125 | : Socket::unpack_sockaddr_in($sin)); | |
1126 | return ($family, $port, $host); | |
1127 | } | |
1128 | ||
a0b6ef52 WB |
1129 | sub getaddrinfo_all { |
1130 | my ($hostname, @opts) = @_; | |
a956854f | 1131 | my %hints = ( flags => AI_V4MAPPED | AI_ALL, |
a0b6ef52 | 1132 | @opts ); |
a956854f | 1133 | my ($err, @res) = Socket::getaddrinfo($hostname, '0', \%hints); |
a0b6ef52 WB |
1134 | die "failed to get address info for: $hostname: $err\n" if $err; |
1135 | return @res; | |
1136 | } | |
a956854f | 1137 | |
a0b6ef52 WB |
1138 | sub get_host_address_family { |
1139 | my ($hostname, $socktype) = @_; | |
1140 | my @res = getaddrinfo_all($hostname, socktype => $socktype); | |
1141 | return $res[0]->{family}; | |
a956854f WB |
1142 | } |
1143 | ||
b2613777 WB |
1144 | # Parses any sane kind of host, or host+port pair: |
1145 | # The port is always optional and thus may be undef. | |
1146 | sub parse_host_and_port { | |
1147 | my ($address) = @_; | |
1148 | if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port' | |
1149 | $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port' | |
1150 | $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot | |
1151 | { | |
1152 | return ($1, $2, 1); # end with 1 to support simple if(parse...) tests | |
1153 | } | |
1154 | return; # nothing | |
1155 | } | |
1156 | ||
952fd95e WB |
1157 | sub unshare { |
1158 | my ($flags) = @_; | |
1159 | syscall 272, $flags; | |
1160 | } | |
1161 | ||
e143e9d8 | 1162 | 1; |