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