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