]>
Commit | Line | Data |
---|---|---|
1 | package PVE::Tools; | |
2 | ||
3 | use strict; | |
4 | use warnings; | |
5 | use POSIX qw(EINTR); | |
6 | use IO::Socket::IP; | |
7 | use Socket qw(AF_INET AF_INET6 AI_ALL AI_V4MAPPED); | |
8 | use IO::Select; | |
9 | use File::Basename; | |
10 | use File::Path qw(make_path); | |
11 | use IO::File; | |
12 | use IO::Dir; | |
13 | use IPC::Open3; | |
14 | use Fcntl qw(:DEFAULT :flock); | |
15 | use base 'Exporter'; | |
16 | use URI::Escape; | |
17 | use Encode; | |
18 | use Digest::SHA; | |
19 | use Text::ParseWords; | |
20 | use String::ShellQuote; | |
21 | use Time::HiRes qw(usleep gettimeofday tv_interval alarm); | |
22 | ||
23 | # avoid warning when parsing long hex values with hex() | |
24 | no warnings 'portable'; # Support for 64-bit ints required | |
25 | ||
26 | our @EXPORT_OK = qw( | |
27 | $IPV6RE | |
28 | $IPV4RE | |
29 | lock_file | |
30 | lock_file_full | |
31 | run_command | |
32 | file_set_contents | |
33 | file_get_contents | |
34 | file_read_firstline | |
35 | dir_glob_regex | |
36 | dir_glob_foreach | |
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 | ||
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))"; | |
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 | ||
66 | use constant (CLONE_NEWNS => 0x00020000, | |
67 | CLONE_NEWUTS => 0x04000000, | |
68 | CLONE_NEWIPC => 0x08000000, | |
69 | CLONE_NEWUSER => 0x10000000, | |
70 | CLONE_NEWPID => 0x20000000, | |
71 | CLONE_NEWNET => 0x40000000); | |
72 | ||
73 | sub run_with_timeout { | |
74 | my ($timeout, $code, @param) = @_; | |
75 | ||
76 | die "got timeout\n" if $timeout <= 0; | |
77 | ||
78 | my $prev_alarm = alarm 0; # suspend outer alarm early | |
79 | ||
80 | my $sigcount = 0; | |
81 | ||
82 | my $res; | |
83 | ||
84 | eval { | |
85 | local $SIG{ALRM} = sub { $sigcount++; die "got timeout\n"; }; | |
86 | local $SIG{PIPE} = sub { $sigcount++; die "broken pipe\n" }; | |
87 | local $SIG{__DIE__}; # see SA bug 4631 | |
88 | ||
89 | alarm($timeout); | |
90 | ||
91 | eval { $res = &$code(@param); }; | |
92 | ||
93 | alarm(0); # avoid race conditions | |
94 | ||
95 | die $@ if $@; | |
96 | }; | |
97 | ||
98 | my $err = $@; | |
99 | ||
100 | alarm $prev_alarm; | |
101 | ||
102 | # this shouldn't happen anymore? | |
103 | die "unknown error" if $sigcount && !$err; # seems to happen sometimes | |
104 | ||
105 | die $err if $err; | |
106 | ||
107 | return $res; | |
108 | } | |
109 | ||
110 | # flock: we use one file handle per process, so lock file | |
111 | # can be called multiple times and succeeds for the same process. | |
112 | ||
113 | my $lock_handles = {}; | |
114 | ||
115 | sub lock_file_full { | |
116 | my ($filename, $timeout, $shared, $code, @param) = @_; | |
117 | ||
118 | $timeout = 10 if !$timeout; | |
119 | ||
120 | my $mode = $shared ? LOCK_SH : LOCK_EX; | |
121 | ||
122 | my $lock_func = sub { | |
123 | if (!$lock_handles->{$$}->{$filename}) { | |
124 | $lock_handles->{$$}->{$filename} = new IO::File (">>$filename") || | |
125 | die "can't open file - $!\n"; | |
126 | } | |
127 | ||
128 | if (!flock ($lock_handles->{$$}->{$filename}, $mode|LOCK_NB)) { | |
129 | print STDERR "trying to aquire lock..."; | |
130 | my $success; | |
131 | while(1) { | |
132 | $success = flock($lock_handles->{$$}->{$filename}, $mode); | |
133 | # try again on EINTR (see bug #273) | |
134 | if ($success || ($! != EINTR)) { | |
135 | last; | |
136 | } | |
137 | } | |
138 | if (!$success) { | |
139 | print STDERR " failed\n"; | |
140 | die "can't aquire lock - $!\n"; | |
141 | } | |
142 | print STDERR " OK\n"; | |
143 | } | |
144 | }; | |
145 | ||
146 | my $res; | |
147 | ||
148 | eval { run_with_timeout($timeout, $lock_func); }; | |
149 | my $err = $@; | |
150 | if ($err) { | |
151 | $err = "can't lock file '$filename' - $err"; | |
152 | } else { | |
153 | eval { $res = &$code(@param) }; | |
154 | $err = $@; | |
155 | } | |
156 | ||
157 | if (my $fh = $lock_handles->{$$}->{$filename}) { | |
158 | $lock_handles->{$$}->{$filename} = undef; | |
159 | close ($fh); | |
160 | } | |
161 | ||
162 | if ($err) { | |
163 | $@ = $err; | |
164 | return undef; | |
165 | } | |
166 | ||
167 | $@ = undef; | |
168 | ||
169 | return $res; | |
170 | } | |
171 | ||
172 | ||
173 | sub lock_file { | |
174 | my ($filename, $timeout, $code, @param) = @_; | |
175 | ||
176 | return lock_file_full($filename, $timeout, 0, $code, @param); | |
177 | } | |
178 | ||
179 | sub file_set_contents { | |
180 | my ($filename, $data, $perm) = @_; | |
181 | ||
182 | $perm = 0644 if !defined($perm); | |
183 | ||
184 | my $tmpname = "$filename.tmp.$$"; | |
185 | ||
186 | eval { | |
187 | my $fh = IO::File->new($tmpname, O_WRONLY|O_CREAT, $perm); | |
188 | die "unable to open file '$tmpname' - $!\n" if !$fh; | |
189 | die "unable to write '$tmpname' - $!\n" unless print $fh $data; | |
190 | die "closing file '$tmpname' failed - $!\n" unless close $fh; | |
191 | }; | |
192 | my $err = $@; | |
193 | ||
194 | if ($err) { | |
195 | unlink $tmpname; | |
196 | die $err; | |
197 | } | |
198 | ||
199 | if (!rename($tmpname, $filename)) { | |
200 | my $msg = "close (rename) atomic file '$filename' failed: $!\n"; | |
201 | unlink $tmpname; | |
202 | die $msg; | |
203 | } | |
204 | } | |
205 | ||
206 | sub file_get_contents { | |
207 | my ($filename, $max) = @_; | |
208 | ||
209 | my $fh = IO::File->new($filename, "r") || | |
210 | die "can't open '$filename' - $!\n"; | |
211 | ||
212 | my $content = safe_read_from($fh, $max); | |
213 | ||
214 | close $fh; | |
215 | ||
216 | return $content; | |
217 | } | |
218 | ||
219 | sub file_read_firstline { | |
220 | my ($filename) = @_; | |
221 | ||
222 | my $fh = IO::File->new ($filename, "r"); | |
223 | return undef if !$fh; | |
224 | my $res = <$fh>; | |
225 | chomp $res if $res; | |
226 | $fh->close; | |
227 | return $res; | |
228 | } | |
229 | ||
230 | sub safe_read_from { | |
231 | my ($fh, $max, $oneline) = @_; | |
232 | ||
233 | $max = 32768 if !$max; | |
234 | ||
235 | my $br = 0; | |
236 | my $input = ''; | |
237 | my $count; | |
238 | while ($count = sysread($fh, $input, 8192, $br)) { | |
239 | $br += $count; | |
240 | die "input too long - aborting\n" if $br > $max; | |
241 | if ($oneline && $input =~ m/^(.*)\n/) { | |
242 | $input = $1; | |
243 | last; | |
244 | } | |
245 | } | |
246 | die "unable to read input - $!\n" if !defined($count); | |
247 | ||
248 | return $input; | |
249 | } | |
250 | ||
251 | # The $cmd parameter can be: | |
252 | # -) a string | |
253 | # This is generally executed by passing it to the shell with the -c option. | |
254 | # However, it can be executed in one of two ways, depending on whether | |
255 | # there's a pipe involved: | |
256 | # *) with pipe: passed explicitly to bash -c, prefixed with: | |
257 | # set -o pipefail && | |
258 | # *) without a pipe: passed to perl's open3 which uses 'sh -c' | |
259 | # (Note that this may result in two different syntax requirements!) | |
260 | # FIXME? | |
261 | # -) an array of arguments (strings) | |
262 | # Will be executed without interference from a shell. (Parameters are passed | |
263 | # as is, no escape sequences of strings will be touched.) | |
264 | # -) an array of arrays | |
265 | # Each array represents a command, and each command's output is piped into | |
266 | # the following command's standard input. | |
267 | # For this a shell command string is created with pipe symbols between each | |
268 | # command. | |
269 | # Each command is a list of strings meant to end up in the final command | |
270 | # unchanged. In order to achieve this, every argument is shell-quoted. | |
271 | # Quoting can be disabled for a particular argument by turning it into a | |
272 | # reference, this allows inserting arbitrary shell options. | |
273 | # For instance: the $cmd [ [ 'echo', 'hello', \'>/dev/null' ] ] will not | |
274 | # produce any output, while the $cmd [ [ 'echo', 'hello', '>/dev/null' ] ] | |
275 | # will literally print: hello >/dev/null | |
276 | sub run_command { | |
277 | my ($cmd, %param) = @_; | |
278 | ||
279 | my $old_umask; | |
280 | my $cmdstr; | |
281 | ||
282 | if (my $ref = ref($cmd)) { | |
283 | if (ref($cmd->[0])) { | |
284 | $cmdstr = 'set -o pipefail && '; | |
285 | my $pipe = ''; | |
286 | foreach my $command (@$cmd) { | |
287 | # concatenate quoted parameters | |
288 | # strings which are passed by reference are NOT shell quoted | |
289 | $cmdstr .= $pipe . join(' ', map { ref($_) ? $$_ : shellquote($_) } @$command); | |
290 | $pipe = ' | '; | |
291 | } | |
292 | $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmdstr" ]; | |
293 | } else { | |
294 | $cmdstr = cmd2string($cmd); | |
295 | } | |
296 | } else { | |
297 | $cmdstr = $cmd; | |
298 | if ($cmd =~ m/\|/) { | |
299 | # see 'man bash' for option pipefail | |
300 | $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ]; | |
301 | } else { | |
302 | $cmd = [ $cmd ]; | |
303 | } | |
304 | } | |
305 | ||
306 | my $errmsg; | |
307 | my $laststderr; | |
308 | my $timeout; | |
309 | my $oldtimeout; | |
310 | my $pid; | |
311 | ||
312 | my $outfunc; | |
313 | my $errfunc; | |
314 | my $logfunc; | |
315 | my $input; | |
316 | my $output; | |
317 | my $afterfork; | |
318 | ||
319 | eval { | |
320 | ||
321 | foreach my $p (keys %param) { | |
322 | if ($p eq 'timeout') { | |
323 | $timeout = $param{$p}; | |
324 | } elsif ($p eq 'umask') { | |
325 | $old_umask = umask($param{$p}); | |
326 | } elsif ($p eq 'errmsg') { | |
327 | $errmsg = $param{$p}; | |
328 | } elsif ($p eq 'input') { | |
329 | $input = $param{$p}; | |
330 | } elsif ($p eq 'output') { | |
331 | $output = $param{$p}; | |
332 | } elsif ($p eq 'outfunc') { | |
333 | $outfunc = $param{$p}; | |
334 | } elsif ($p eq 'errfunc') { | |
335 | $errfunc = $param{$p}; | |
336 | } elsif ($p eq 'logfunc') { | |
337 | $logfunc = $param{$p}; | |
338 | } elsif ($p eq 'afterfork') { | |
339 | $afterfork = $param{$p}; | |
340 | } else { | |
341 | die "got unknown parameter '$p' for run_command\n"; | |
342 | } | |
343 | } | |
344 | ||
345 | if ($errmsg) { | |
346 | my $origerrfunc = $errfunc; | |
347 | $errfunc = sub { | |
348 | if ($laststderr) { | |
349 | if ($origerrfunc) { | |
350 | &$origerrfunc("$laststderr\n"); | |
351 | } else { | |
352 | print STDERR "$laststderr\n" if $laststderr; | |
353 | } | |
354 | } | |
355 | $laststderr = shift; | |
356 | }; | |
357 | } | |
358 | ||
359 | my $reader = $output && $output =~ m/^>&/ ? $output : IO::File->new(); | |
360 | my $writer = $input && $input =~ m/^<&/ ? $input : IO::File->new(); | |
361 | my $error = IO::File->new(); | |
362 | ||
363 | # try to avoid locale related issues/warnings | |
364 | my $lang = $param{lang} || 'C'; | |
365 | ||
366 | my $orig_pid = $$; | |
367 | ||
368 | eval { | |
369 | local $ENV{LC_ALL} = $lang; | |
370 | ||
371 | # suppress LVM warnings like: "File descriptor 3 left open"; | |
372 | local $ENV{LVM_SUPPRESS_FD_WARNINGS} = "1"; | |
373 | ||
374 | $pid = open3($writer, $reader, $error, @$cmd) || die $!; | |
375 | ||
376 | # if we pipe fron STDIN, open3 closes STDIN, so we we | |
377 | # a perl warning "Filehandle STDIN reopened as GENXYZ .. " | |
378 | # as soon as we open a new file. | |
379 | # to avoid that we open /dev/null | |
380 | if (!ref($writer) && !defined(fileno(STDIN))) { | |
381 | POSIX::close(0); | |
382 | open(STDIN, "</dev/null"); | |
383 | } | |
384 | }; | |
385 | ||
386 | my $err = $@; | |
387 | ||
388 | # catch exec errors | |
389 | if ($orig_pid != $$) { | |
390 | warn "ERROR: $err"; | |
391 | POSIX::_exit (1); | |
392 | kill ('KILL', $$); | |
393 | } | |
394 | ||
395 | die $err if $err; | |
396 | ||
397 | local $SIG{ALRM} = sub { die "got timeout\n"; } if $timeout; | |
398 | $oldtimeout = alarm($timeout) if $timeout; | |
399 | ||
400 | &$afterfork() if $afterfork; | |
401 | ||
402 | if (ref($writer)) { | |
403 | print $writer $input if defined $input; | |
404 | close $writer; | |
405 | } | |
406 | ||
407 | my $select = new IO::Select; | |
408 | $select->add($reader) if ref($reader); | |
409 | $select->add($error); | |
410 | ||
411 | my $outlog = ''; | |
412 | my $errlog = ''; | |
413 | ||
414 | my $starttime = time(); | |
415 | ||
416 | while ($select->count) { | |
417 | my @handles = $select->can_read(1); | |
418 | ||
419 | foreach my $h (@handles) { | |
420 | my $buf = ''; | |
421 | my $count = sysread ($h, $buf, 4096); | |
422 | if (!defined ($count)) { | |
423 | my $err = $!; | |
424 | kill (9, $pid); | |
425 | waitpid ($pid, 0); | |
426 | die $err; | |
427 | } | |
428 | $select->remove ($h) if !$count; | |
429 | if ($h eq $reader) { | |
430 | if ($outfunc || $logfunc) { | |
431 | eval { | |
432 | $outlog .= $buf; | |
433 | while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) { | |
434 | my $line = $1; | |
435 | &$outfunc($line) if $outfunc; | |
436 | &$logfunc($line) if $logfunc; | |
437 | } | |
438 | }; | |
439 | my $err = $@; | |
440 | if ($err) { | |
441 | kill (9, $pid); | |
442 | waitpid ($pid, 0); | |
443 | die $err; | |
444 | } | |
445 | } else { | |
446 | print $buf; | |
447 | *STDOUT->flush(); | |
448 | } | |
449 | } elsif ($h eq $error) { | |
450 | if ($errfunc || $logfunc) { | |
451 | eval { | |
452 | $errlog .= $buf; | |
453 | while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) { | |
454 | my $line = $1; | |
455 | &$errfunc($line) if $errfunc; | |
456 | &$logfunc($line) if $logfunc; | |
457 | } | |
458 | }; | |
459 | my $err = $@; | |
460 | if ($err) { | |
461 | kill (9, $pid); | |
462 | waitpid ($pid, 0); | |
463 | die $err; | |
464 | } | |
465 | } else { | |
466 | print STDERR $buf; | |
467 | *STDERR->flush(); | |
468 | } | |
469 | } | |
470 | } | |
471 | } | |
472 | ||
473 | &$outfunc($outlog) if $outfunc && $outlog; | |
474 | &$logfunc($outlog) if $logfunc && $outlog; | |
475 | ||
476 | &$errfunc($errlog) if $errfunc && $errlog; | |
477 | &$logfunc($errlog) if $logfunc && $errlog; | |
478 | ||
479 | waitpid ($pid, 0); | |
480 | ||
481 | if ($? == -1) { | |
482 | die "failed to execute\n"; | |
483 | } elsif (my $sig = ($? & 127)) { | |
484 | die "got signal $sig\n"; | |
485 | } elsif (my $ec = ($? >> 8)) { | |
486 | if (!($ec == 24 && ($cmdstr =~ m|^(\S+/)?rsync\s|))) { | |
487 | if ($errmsg && $laststderr) { | |
488 | my $lerr = $laststderr; | |
489 | $laststderr = undef; | |
490 | die "$lerr\n"; | |
491 | } | |
492 | die "exit code $ec\n"; | |
493 | } | |
494 | } | |
495 | ||
496 | alarm(0); | |
497 | }; | |
498 | ||
499 | my $err = $@; | |
500 | ||
501 | alarm(0); | |
502 | ||
503 | if ($errmsg && $laststderr) { | |
504 | &$errfunc(undef); # flush laststderr | |
505 | } | |
506 | ||
507 | umask ($old_umask) if defined($old_umask); | |
508 | ||
509 | alarm($oldtimeout) if $oldtimeout; | |
510 | ||
511 | if ($err) { | |
512 | if ($pid && ($err eq "got timeout\n")) { | |
513 | kill (9, $pid); | |
514 | waitpid ($pid, 0); | |
515 | die "command '$cmdstr' failed: $err"; | |
516 | } | |
517 | ||
518 | if ($errmsg) { | |
519 | $err =~ s/^usermod:\s*// if $cmdstr =~ m|^(\S+/)?usermod\s|; | |
520 | die "$errmsg: $err"; | |
521 | } else { | |
522 | die "command '$cmdstr' failed: $err"; | |
523 | } | |
524 | } | |
525 | ||
526 | return undef; | |
527 | } | |
528 | ||
529 | sub split_list { | |
530 | my $listtxt = shift || ''; | |
531 | ||
532 | return split (/\0/, $listtxt) if $listtxt =~ m/\0/; | |
533 | ||
534 | $listtxt =~ s/[,;]/ /g; | |
535 | $listtxt =~ s/^\s+//; | |
536 | ||
537 | my @data = split (/\s+/, $listtxt); | |
538 | ||
539 | return @data; | |
540 | } | |
541 | ||
542 | sub trim { | |
543 | my $txt = shift; | |
544 | ||
545 | return $txt if !defined($txt); | |
546 | ||
547 | $txt =~ s/^\s+//; | |
548 | $txt =~ s/\s+$//; | |
549 | ||
550 | return $txt; | |
551 | } | |
552 | ||
553 | # simple uri templates like "/vms/{vmid}" | |
554 | sub template_replace { | |
555 | my ($tmpl, $data) = @_; | |
556 | ||
557 | return $tmpl if !$tmpl; | |
558 | ||
559 | my $res = ''; | |
560 | while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) { | |
561 | $res .= $1 if $1; | |
562 | $res .= ($data->{$3} || '-') if $2; | |
563 | } | |
564 | return $res; | |
565 | } | |
566 | ||
567 | sub safe_print { | |
568 | my ($filename, $fh, $data) = @_; | |
569 | ||
570 | return if !$data; | |
571 | ||
572 | my $res = print $fh $data; | |
573 | ||
574 | die "write to '$filename' failed\n" if !$res; | |
575 | } | |
576 | ||
577 | sub debmirrors { | |
578 | ||
579 | return { | |
580 | 'at' => 'ftp.at.debian.org', | |
581 | 'au' => 'ftp.au.debian.org', | |
582 | 'be' => 'ftp.be.debian.org', | |
583 | 'bg' => 'ftp.bg.debian.org', | |
584 | 'br' => 'ftp.br.debian.org', | |
585 | 'ca' => 'ftp.ca.debian.org', | |
586 | 'ch' => 'ftp.ch.debian.org', | |
587 | 'cl' => 'ftp.cl.debian.org', | |
588 | 'cz' => 'ftp.cz.debian.org', | |
589 | 'de' => 'ftp.de.debian.org', | |
590 | 'dk' => 'ftp.dk.debian.org', | |
591 | 'ee' => 'ftp.ee.debian.org', | |
592 | 'es' => 'ftp.es.debian.org', | |
593 | 'fi' => 'ftp.fi.debian.org', | |
594 | 'fr' => 'ftp.fr.debian.org', | |
595 | 'gr' => 'ftp.gr.debian.org', | |
596 | 'hk' => 'ftp.hk.debian.org', | |
597 | 'hr' => 'ftp.hr.debian.org', | |
598 | 'hu' => 'ftp.hu.debian.org', | |
599 | 'ie' => 'ftp.ie.debian.org', | |
600 | 'is' => 'ftp.is.debian.org', | |
601 | 'it' => 'ftp.it.debian.org', | |
602 | 'jp' => 'ftp.jp.debian.org', | |
603 | 'kr' => 'ftp.kr.debian.org', | |
604 | 'mx' => 'ftp.mx.debian.org', | |
605 | 'nl' => 'ftp.nl.debian.org', | |
606 | 'no' => 'ftp.no.debian.org', | |
607 | 'nz' => 'ftp.nz.debian.org', | |
608 | 'pl' => 'ftp.pl.debian.org', | |
609 | 'pt' => 'ftp.pt.debian.org', | |
610 | 'ro' => 'ftp.ro.debian.org', | |
611 | 'ru' => 'ftp.ru.debian.org', | |
612 | 'se' => 'ftp.se.debian.org', | |
613 | 'si' => 'ftp.si.debian.org', | |
614 | 'sk' => 'ftp.sk.debian.org', | |
615 | 'tr' => 'ftp.tr.debian.org', | |
616 | 'tw' => 'ftp.tw.debian.org', | |
617 | 'gb' => 'ftp.uk.debian.org', | |
618 | 'us' => 'ftp.us.debian.org', | |
619 | }; | |
620 | } | |
621 | ||
622 | my $keymaphash = { | |
623 | 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'], | |
624 | 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ], | |
625 | 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ], | |
626 | 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef], | |
627 | 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ], | |
628 | 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'], | |
629 | #'et' => [], # Ethopia or Estonia ?? | |
630 | 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'], | |
631 | #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'], | |
632 | 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'], | |
633 | 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'], | |
634 | 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'], | |
635 | 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'], | |
636 | #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2? | |
637 | 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef], | |
638 | 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'], | |
639 | 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'], | |
640 | 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef], | |
641 | 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'], | |
642 | #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7? | |
643 | 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'], | |
644 | 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef], | |
645 | #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?], | |
646 | 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'], | |
647 | 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef], | |
648 | 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'], | |
649 | 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'], | |
650 | #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know? | |
651 | 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef], | |
652 | 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'], | |
653 | #'th' => [], | |
654 | 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef], | |
655 | }; | |
656 | ||
657 | my $kvmkeymaparray = []; | |
658 | foreach my $lc (keys %$keymaphash) { | |
659 | push @$kvmkeymaparray, $keymaphash->{$lc}->[1]; | |
660 | } | |
661 | ||
662 | sub kvmkeymaps { | |
663 | return $keymaphash; | |
664 | } | |
665 | ||
666 | sub kvmkeymaplist { | |
667 | return $kvmkeymaparray; | |
668 | } | |
669 | ||
670 | sub extract_param { | |
671 | my ($param, $key) = @_; | |
672 | ||
673 | my $res = $param->{$key}; | |
674 | delete $param->{$key}; | |
675 | ||
676 | return $res; | |
677 | } | |
678 | ||
679 | # Note: we use this to wait until vncterm/spiceterm is ready | |
680 | sub wait_for_vnc_port { | |
681 | my ($port, $timeout) = @_; | |
682 | ||
683 | $timeout = 5 if !$timeout; | |
684 | my $sleeptime = 0; | |
685 | my $starttime = [gettimeofday]; | |
686 | my $elapsed; | |
687 | ||
688 | while (($elapsed = tv_interval($starttime)) < $timeout) { | |
689 | if (my $fh = IO::File->new ("/proc/net/tcp", "r")) { | |
690 | while (defined (my $line = <$fh>)) { | |
691 | if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) { | |
692 | if ($port == hex($2)) { | |
693 | close($fh); | |
694 | return 1; | |
695 | } | |
696 | } | |
697 | } | |
698 | close($fh); | |
699 | } | |
700 | $sleeptime += 100000 if $sleeptime < 1000000; | |
701 | usleep($sleeptime); | |
702 | } | |
703 | ||
704 | return undef; | |
705 | } | |
706 | ||
707 | sub next_unused_port { | |
708 | my ($range_start, $range_end, $family) = @_; | |
709 | ||
710 | # We use a file to register allocated ports. | |
711 | # Those registrations expires after $expiretime. | |
712 | # We use this to avoid race conditions between | |
713 | # allocation and use of ports. | |
714 | ||
715 | my $filename = "/var/tmp/pve-reserved-ports"; | |
716 | ||
717 | my $code = sub { | |
718 | ||
719 | my $expiretime = 5; | |
720 | my $ctime = time(); | |
721 | ||
722 | my $ports = {}; | |
723 | ||
724 | if (my $fh = IO::File->new ($filename, "r")) { | |
725 | while (my $line = <$fh>) { | |
726 | if ($line =~ m/^(\d+)\s(\d+)$/) { | |
727 | my ($port, $timestamp) = ($1, $2); | |
728 | if (($timestamp + $expiretime) > $ctime) { | |
729 | $ports->{$port} = $timestamp; # not expired | |
730 | } | |
731 | } | |
732 | } | |
733 | } | |
734 | ||
735 | my $newport; | |
736 | ||
737 | for (my $p = $range_start; $p < $range_end; $p++) { | |
738 | next if $ports->{$p}; # reserved | |
739 | ||
740 | my $sock = IO::Socket::IP->new(Listen => 5, | |
741 | LocalPort => $p, | |
742 | ReuseAddr => 1, | |
743 | Family => $family, | |
744 | Proto => 0, | |
745 | GetAddrInfoFlags => 0); | |
746 | ||
747 | if ($sock) { | |
748 | close($sock); | |
749 | $newport = $p; | |
750 | $ports->{$p} = $ctime; | |
751 | last; | |
752 | } | |
753 | } | |
754 | ||
755 | my $data = ""; | |
756 | foreach my $p (keys %$ports) { | |
757 | $data .= "$p $ports->{$p}\n"; | |
758 | } | |
759 | ||
760 | file_set_contents($filename, $data); | |
761 | ||
762 | return $newport; | |
763 | }; | |
764 | ||
765 | my $p = lock_file($filename, 10, $code); | |
766 | die $@ if $@; | |
767 | ||
768 | die "unable to find free port (${range_start}-${range_end})\n" if !$p; | |
769 | ||
770 | return $p; | |
771 | } | |
772 | ||
773 | sub next_migrate_port { | |
774 | my ($family) = @_; | |
775 | return next_unused_port(60000, 60050, $family); | |
776 | } | |
777 | ||
778 | sub next_vnc_port { | |
779 | my ($family) = @_; | |
780 | return next_unused_port(5900, 6000, $family); | |
781 | } | |
782 | ||
783 | sub next_spice_port { | |
784 | my ($family) = @_; | |
785 | return next_unused_port(61000, 61099, $family); | |
786 | } | |
787 | ||
788 | # NOTE: NFS syscall can't be interrupted, so alarm does | |
789 | # not work to provide timeouts. | |
790 | # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation" | |
791 | # So the spawn external 'df' process instead of using | |
792 | # Filesys::Df (which uses statfs syscall) | |
793 | sub df { | |
794 | my ($path, $timeout) = @_; | |
795 | ||
796 | my $cmd = [ 'df', '-P', '-B', '1', $path]; | |
797 | ||
798 | my $res = { | |
799 | total => 0, | |
800 | used => 0, | |
801 | avail => 0, | |
802 | }; | |
803 | ||
804 | my $parser = sub { | |
805 | my $line = shift; | |
806 | if (my ($fsid, $total, $used, $avail) = $line =~ | |
807 | m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) { | |
808 | $res = { | |
809 | total => $total, | |
810 | used => $used, | |
811 | avail => $avail, | |
812 | }; | |
813 | } | |
814 | }; | |
815 | eval { run_command($cmd, timeout => $timeout, outfunc => $parser); }; | |
816 | warn $@ if $@; | |
817 | ||
818 | return $res; | |
819 | } | |
820 | ||
821 | # UPID helper | |
822 | # We use this to uniquely identify a process. | |
823 | # An 'Unique Process ID' has the following format: | |
824 | # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user" | |
825 | ||
826 | sub upid_encode { | |
827 | my $d = shift; | |
828 | ||
829 | # Note: pstart can be > 32bit if uptime > 497 days, so this can result in | |
830 | # more that 8 characters for pstart | |
831 | return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid}, | |
832 | $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id}, | |
833 | $d->{user}); | |
834 | } | |
835 | ||
836 | sub upid_decode { | |
837 | my ($upid, $noerr) = @_; | |
838 | ||
839 | my $res; | |
840 | my $filename; | |
841 | ||
842 | # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user" | |
843 | # Note: allow up to 9 characters for pstart (work until 20 years uptime) | |
844 | 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]+):$/) { | |
845 | $res->{node} = $1; | |
846 | $res->{pid} = hex($3); | |
847 | $res->{pstart} = hex($4); | |
848 | $res->{starttime} = hex($5); | |
849 | $res->{type} = $6; | |
850 | $res->{id} = $7; | |
851 | $res->{user} = $8; | |
852 | ||
853 | my $subdir = substr($5, 7, 8); | |
854 | $filename = "$pvetaskdir/$subdir/$upid"; | |
855 | ||
856 | } else { | |
857 | return undef if $noerr; | |
858 | die "unable to parse worker upid '$upid'\n"; | |
859 | } | |
860 | ||
861 | return wantarray ? ($res, $filename) : $res; | |
862 | } | |
863 | ||
864 | sub upid_open { | |
865 | my ($upid) = @_; | |
866 | ||
867 | my ($task, $filename) = upid_decode($upid); | |
868 | ||
869 | my $dirname = dirname($filename); | |
870 | make_path($dirname); | |
871 | ||
872 | my $wwwid = getpwnam('www-data') || | |
873 | die "getpwnam failed"; | |
874 | ||
875 | my $perm = 0640; | |
876 | ||
877 | my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) || | |
878 | die "unable to create output file '$filename' - $!\n"; | |
879 | chown $wwwid, -1, $outfh; | |
880 | ||
881 | return $outfh; | |
882 | }; | |
883 | ||
884 | sub upid_read_status { | |
885 | my ($upid) = @_; | |
886 | ||
887 | my ($task, $filename) = upid_decode($upid); | |
888 | my $fh = IO::File->new($filename, "r"); | |
889 | return "unable to open file - $!" if !$fh; | |
890 | my $maxlen = 4096; | |
891 | sysseek($fh, -$maxlen, 2); | |
892 | my $readbuf = ''; | |
893 | my $br = sysread($fh, $readbuf, $maxlen); | |
894 | close($fh); | |
895 | if ($br) { | |
896 | return "unable to extract last line" | |
897 | if $readbuf !~ m/\n?(.+)$/; | |
898 | my $line = $1; | |
899 | if ($line =~ m/^TASK OK$/) { | |
900 | return 'OK'; | |
901 | } elsif ($line =~ m/^TASK ERROR: (.+)$/) { | |
902 | return $1; | |
903 | } else { | |
904 | return "unexpected status"; | |
905 | } | |
906 | } | |
907 | return "unable to read tail (got $br bytes)"; | |
908 | } | |
909 | ||
910 | # useful functions to store comments in config files | |
911 | sub encode_text { | |
912 | my ($text) = @_; | |
913 | ||
914 | # all control and hi-bit characters, and ':' | |
915 | my $unsafe = "^\x20-\x39\x3b-\x7e"; | |
916 | return uri_escape(Encode::encode("utf8", $text), $unsafe); | |
917 | } | |
918 | ||
919 | sub decode_text { | |
920 | my ($data) = @_; | |
921 | ||
922 | return Encode::decode("utf8", uri_unescape($data)); | |
923 | } | |
924 | ||
925 | sub decode_utf8_parameters { | |
926 | my ($param) = @_; | |
927 | ||
928 | foreach my $p (qw(comment description firstname lastname)) { | |
929 | $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p}; | |
930 | } | |
931 | ||
932 | return $param; | |
933 | } | |
934 | ||
935 | sub random_ether_addr { | |
936 | ||
937 | my ($seconds, $microseconds) = gettimeofday; | |
938 | ||
939 | my $rand = Digest::SHA::sha1_hex($$, rand(), $seconds, $microseconds); | |
940 | ||
941 | my $mac = ''; | |
942 | for (my $i = 0; $i < 6; $i++) { | |
943 | my $ss = hex(substr($rand, $i*2, 2)); | |
944 | if (!$i) { | |
945 | $ss &= 0xfe; # clear multicast | |
946 | $ss |= 2; # set local id | |
947 | } | |
948 | $ss = sprintf("%02X", $ss); | |
949 | ||
950 | if (!$i) { | |
951 | $mac .= "$ss"; | |
952 | } else { | |
953 | $mac .= ":$ss"; | |
954 | } | |
955 | } | |
956 | ||
957 | return $mac; | |
958 | } | |
959 | ||
960 | sub shellquote { | |
961 | my $str = shift; | |
962 | ||
963 | return String::ShellQuote::shell_quote($str); | |
964 | } | |
965 | ||
966 | sub cmd2string { | |
967 | my ($cmd) = @_; | |
968 | ||
969 | die "no arguments" if !$cmd; | |
970 | ||
971 | return $cmd if !ref($cmd); | |
972 | ||
973 | my @qa = (); | |
974 | foreach my $arg (@$cmd) { push @qa, shellquote($arg); } | |
975 | ||
976 | return join (' ', @qa); | |
977 | } | |
978 | ||
979 | # split an shell argument string into an array, | |
980 | sub split_args { | |
981 | my ($str) = @_; | |
982 | ||
983 | return $str ? [ Text::ParseWords::shellwords($str) ] : []; | |
984 | } | |
985 | ||
986 | sub dump_logfile { | |
987 | my ($filename, $start, $limit, $filter) = @_; | |
988 | ||
989 | my $lines = []; | |
990 | my $count = 0; | |
991 | ||
992 | my $fh = IO::File->new($filename, "r"); | |
993 | if (!$fh) { | |
994 | $count++; | |
995 | push @$lines, { n => $count, t => "unable to open file - $!"}; | |
996 | return ($count, $lines); | |
997 | } | |
998 | ||
999 | $start = 0 if !$start; | |
1000 | $limit = 50 if !$limit; | |
1001 | ||
1002 | my $line; | |
1003 | ||
1004 | if ($filter) { | |
1005 | # duplicate code, so that we do not slow down normal path | |
1006 | while (defined($line = <$fh>)) { | |
1007 | next if $line !~ m/$filter/; | |
1008 | next if $count++ < $start; | |
1009 | next if $limit <= 0; | |
1010 | chomp $line; | |
1011 | push @$lines, { n => $count, t => $line}; | |
1012 | $limit--; | |
1013 | } | |
1014 | } else { | |
1015 | while (defined($line = <$fh>)) { | |
1016 | next if $count++ < $start; | |
1017 | next if $limit <= 0; | |
1018 | chomp $line; | |
1019 | push @$lines, { n => $count, t => $line}; | |
1020 | $limit--; | |
1021 | } | |
1022 | } | |
1023 | ||
1024 | close($fh); | |
1025 | ||
1026 | # HACK: ExtJS store.guaranteeRange() does not like empty array | |
1027 | # so we add a line | |
1028 | if (!$count) { | |
1029 | $count++; | |
1030 | push @$lines, { n => $count, t => "no content"}; | |
1031 | } | |
1032 | ||
1033 | return ($count, $lines); | |
1034 | } | |
1035 | ||
1036 | sub dump_journal { | |
1037 | my ($start, $limit, $filter) = @_; | |
1038 | ||
1039 | my $lines = []; | |
1040 | my $count = 0; | |
1041 | ||
1042 | $start = 0 if !$start; | |
1043 | $limit = 50 if !$limit; | |
1044 | ||
1045 | my $parser = sub { | |
1046 | my $line = shift; | |
1047 | ||
1048 | return if $count++ < $start; | |
1049 | return if $limit <= 0; | |
1050 | push @$lines, { n => int($count), t => $line}; | |
1051 | $limit--; | |
1052 | }; | |
1053 | ||
1054 | my $cmd = ['journalctl', '-o', 'short', '--no-pager']; | |
1055 | run_command($cmd, outfunc => $parser); | |
1056 | ||
1057 | # HACK: ExtJS store.guaranteeRange() does not like empty array | |
1058 | # so we add a line | |
1059 | if (!$count) { | |
1060 | $count++; | |
1061 | push @$lines, { n => $count, t => "no content"}; | |
1062 | } | |
1063 | ||
1064 | return ($count, $lines); | |
1065 | } | |
1066 | ||
1067 | sub dir_glob_regex { | |
1068 | my ($dir, $regex) = @_; | |
1069 | ||
1070 | my $dh = IO::Dir->new ($dir); | |
1071 | return wantarray ? () : undef if !$dh; | |
1072 | ||
1073 | while (defined(my $tmp = $dh->read)) { | |
1074 | if (my @res = $tmp =~ m/^($regex)$/) { | |
1075 | $dh->close; | |
1076 | return wantarray ? @res : $tmp; | |
1077 | } | |
1078 | } | |
1079 | $dh->close; | |
1080 | ||
1081 | return wantarray ? () : undef; | |
1082 | } | |
1083 | ||
1084 | sub dir_glob_foreach { | |
1085 | my ($dir, $regex, $func) = @_; | |
1086 | ||
1087 | my $dh = IO::Dir->new ($dir); | |
1088 | if (defined $dh) { | |
1089 | while (defined(my $tmp = $dh->read)) { | |
1090 | if (my @res = $tmp =~ m/^($regex)$/) { | |
1091 | &$func (@res); | |
1092 | } | |
1093 | } | |
1094 | } | |
1095 | } | |
1096 | ||
1097 | sub assert_if_modified { | |
1098 | my ($digest1, $digest2) = @_; | |
1099 | ||
1100 | if ($digest1 && $digest2 && ($digest1 ne $digest2)) { | |
1101 | die "detected modified configuration - file changed by other user? Try again.\n"; | |
1102 | } | |
1103 | } | |
1104 | ||
1105 | # Digest for short strings | |
1106 | # like FNV32a, but we only return 31 bits (positive numbers) | |
1107 | sub fnv31a { | |
1108 | my ($string) = @_; | |
1109 | ||
1110 | my $hval = 0x811c9dc5; | |
1111 | ||
1112 | foreach my $c (unpack('C*', $string)) { | |
1113 | $hval ^= $c; | |
1114 | $hval += ( | |
1115 | (($hval << 1) ) + | |
1116 | (($hval << 4) ) + | |
1117 | (($hval << 7) ) + | |
1118 | (($hval << 8) ) + | |
1119 | (($hval << 24) ) ); | |
1120 | $hval = $hval & 0xffffffff; | |
1121 | } | |
1122 | return $hval & 0x7fffffff; | |
1123 | } | |
1124 | ||
1125 | sub fnv31a_hex { return sprintf("%X", fnv31a(@_)); } | |
1126 | ||
1127 | sub unpack_sockaddr_in46 { | |
1128 | my ($sin) = @_; | |
1129 | my $family = Socket::sockaddr_family($sin); | |
1130 | my ($port, $host) = ($family == AF_INET6 ? Socket::unpack_sockaddr_in6($sin) | |
1131 | : Socket::unpack_sockaddr_in($sin)); | |
1132 | return ($family, $port, $host); | |
1133 | } | |
1134 | ||
1135 | sub getaddrinfo_all { | |
1136 | my ($hostname, @opts) = @_; | |
1137 | my %hints = ( flags => AI_V4MAPPED | AI_ALL, | |
1138 | @opts ); | |
1139 | my ($err, @res) = Socket::getaddrinfo($hostname, '0', \%hints); | |
1140 | die "failed to get address info for: $hostname: $err\n" if $err; | |
1141 | return @res; | |
1142 | } | |
1143 | ||
1144 | sub get_host_address_family { | |
1145 | my ($hostname, $socktype) = @_; | |
1146 | my @res = getaddrinfo_all($hostname, socktype => $socktype); | |
1147 | return $res[0]->{family}; | |
1148 | } | |
1149 | ||
1150 | # Parses any sane kind of host, or host+port pair: | |
1151 | # The port is always optional and thus may be undef. | |
1152 | sub parse_host_and_port { | |
1153 | my ($address) = @_; | |
1154 | if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port' | |
1155 | $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port' | |
1156 | $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot | |
1157 | { | |
1158 | return ($1, $2, 1); # end with 1 to support simple if(parse...) tests | |
1159 | } | |
1160 | return; # nothing | |
1161 | } | |
1162 | ||
1163 | sub unshare { | |
1164 | my ($flags) = @_; | |
1165 | syscall 272, $flags; | |
1166 | } | |
1167 | ||
1168 | 1; |