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