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