]> git.proxmox.com Git - pve-common.git/blame - src/PVE/Tools.pm
fix O_PATH value
[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
d0229d1d 78use constant O_PATH => 0x00200000;
44acb12c 79
0f0990f1
DM
80sub run_with_timeout {
81 my ($timeout, $code, @param) = @_;
e143e9d8 82
0f0990f1 83 die "got timeout\n" if $timeout <= 0;
e143e9d8 84
c38cea65 85 my $prev_alarm = alarm 0; # suspend outer alarm early
0f0990f1
DM
86
87 my $sigcount = 0;
e143e9d8
DM
88
89 my $res;
90
e143e9d8 91 eval {
0f0990f1
DM
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
e143e9d8 95
c38cea65 96 alarm($timeout);
e143e9d8 97
c38cea65 98 eval { $res = &$code(@param); };
0f0990f1
DM
99
100 alarm(0); # avoid race conditions
c38cea65
WB
101
102 die $@ if $@;
0f0990f1
DM
103 };
104
105 my $err = $@;
106
c38cea65 107 alarm $prev_alarm;
0f0990f1 108
c38cea65 109 # this shouldn't happen anymore?
0f0990f1
DM
110 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
111
112 die $err if $err;
113
114 return $res;
115}
e143e9d8 116
0f0990f1
DM
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
120my $lock_handles = {};
121
493004a2
DM
122sub lock_file_full {
123 my ($filename, $timeout, $shared, $code, @param) = @_;
0f0990f1
DM
124
125 $timeout = 10 if !$timeout;
126
493004a2
DM
127 my $mode = $shared ? LOCK_SH : LOCK_EX;
128
0f0990f1 129 my $lock_func = sub {
e143e9d8 130 if (!$lock_handles->{$$}->{$filename}) {
f127adab
FG
131 my $fh = new IO::File(">>$filename") ||
132 die "can't open file - $!\n";
133 $lock_handles->{$$}->{$filename} = { fh => $fh, refcount => 0};
e143e9d8
DM
134 }
135
f127adab 136 if (!flock($lock_handles->{$$}->{$filename}->{fh}, $mode|LOCK_NB)) {
b148e99f 137 print STDERR "trying to acquire lock...";
b5d12b08
DM
138 my $success;
139 while(1) {
f127adab 140 $success = flock($lock_handles->{$$}->{$filename}->{fh}, $mode);
b5d12b08
DM
141 # try again on EINTR (see bug #273)
142 if ($success || ($! != EINTR)) {
143 last;
144 }
145 }
146 if (!$success) {
e143e9d8 147 print STDERR " failed\n";
b148e99f 148 die "can't acquire lock '$filename' - $!\n";
e143e9d8
DM
149 }
150 print STDERR " OK\n";
151 }
f127adab 152 $lock_handles->{$$}->{$filename}->{refcount}++;
e143e9d8
DM
153 };
154
0f0990f1 155 my $res;
e143e9d8 156
0f0990f1
DM
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 }
e143e9d8 165
f127adab
FG
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 }
e143e9d8
DM
172 }
173
174 if ($err) {
175 $@ = $err;
176 return undef;
177 }
178
179 $@ = undef;
180
181 return $res;
182}
183
493004a2
DM
184
185sub lock_file {
186 my ($filename, $timeout, $code, @param) = @_;
187
188 return lock_file_full($filename, $timeout, 0, $code, @param);
189}
190
e143e9d8
DM
191sub 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
218sub 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
23e0e0d7
WL
231sub file_copy {
232 my ($filename, $dst, $max, $perm) = @_;
233
234 file_set_contents ($dst, file_get_contents($filename, $max), $perm);
235}
236
e143e9d8
DM
237sub file_read_firstline {
238 my ($filename) = @_;
239
240 my $fh = IO::File->new ($filename, "r");
241 return undef if !$fh;
242 my $res = <$fh>;
88955a2e 243 chomp $res if $res;
e143e9d8
DM
244 $fh->close;
245 return $res;
246}
247
248sub 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
bd9c3a36
WB
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.)
fcdc0cfc
WB
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
e143e9d8
DM
294sub run_command {
295 my ($cmd, %param) = @_;
296
297 my $old_umask;
ded47a61 298 my $cmdstr;
e143e9d8 299
fcdc0cfc
WB
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 {
ded47a61 315 $cmdstr = $cmd;
22d4efe6 316 if ($cmd =~ m/\|/) {
e0cabd2c
DM
317 # see 'man bash' for option pipefail
318 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
319 } else {
320 $cmd = [ $cmd ];
321 }
ded47a61 322 }
e143e9d8
DM
323
324 my $errmsg;
325 my $laststderr;
326 my $timeout;
327 my $oldtimeout;
328 my $pid;
7e826928 329 my $exitcode;
e143e9d8 330
4630cb95
DM
331 my $outfunc;
332 my $errfunc;
333 my $logfunc;
334 my $input;
335 my $output;
a417477c 336 my $afterfork;
7e826928 337 my $noerr;
4630cb95 338
e143e9d8 339 eval {
e143e9d8
DM
340
341 foreach my $p (keys %param) {
342 if ($p eq 'timeout') {
343 $timeout = $param{$p};
344 } elsif ($p eq 'umask') {
eb9e24df 345 $old_umask = umask($param{$p});
e143e9d8
DM
346 } elsif ($p eq 'errmsg') {
347 $errmsg = $param{$p};
e143e9d8
DM
348 } elsif ($p eq 'input') {
349 $input = $param{$p};
1c50a24a
DM
350 } elsif ($p eq 'output') {
351 $output = $param{$p};
e143e9d8
DM
352 } elsif ($p eq 'outfunc') {
353 $outfunc = $param{$p};
354 } elsif ($p eq 'errfunc') {
355 $errfunc = $param{$p};
776fbfa8
DM
356 } elsif ($p eq 'logfunc') {
357 $logfunc = $param{$p};
a417477c
DM
358 } elsif ($p eq 'afterfork') {
359 $afterfork = $param{$p};
7e826928
TL
360 } elsif ($p eq 'noerr') {
361 $noerr = $param{$p};
e143e9d8
DM
362 } else {
363 die "got unknown parameter '$p' for run_command\n";
364 }
365 }
366
4630cb95
DM
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
1c50a24a
DM
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
e143e9d8
DM
385 # try to avoid locale related issues/warnings
386 my $lang = $param{lang} || 'C';
387
388 my $orig_pid = $$;
389
390 eval {
329351e2 391 local $ENV{LC_ALL} = $lang;
e143e9d8
DM
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 $!;
f38995ab
DM
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 }
e143e9d8
DM
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
a417477c
DM
422 &$afterfork() if $afterfork;
423
f38995ab
DM
424 if (ref($writer)) {
425 print $writer $input if defined $input;
426 close $writer;
427 }
e143e9d8
DM
428
429 my $select = new IO::Select;
f38995ab 430 $select->add($reader) if ref($reader);
e143e9d8
DM
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) {
776fbfa8 452 if ($outfunc || $logfunc) {
e143e9d8
DM
453 eval {
454 $outlog .= $buf;
455 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
456 my $line = $1;
776fbfa8
DM
457 &$outfunc($line) if $outfunc;
458 &$logfunc($line) if $logfunc;
e143e9d8
DM
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) {
776fbfa8 472 if ($errfunc || $logfunc) {
e143e9d8
DM
473 eval {
474 $errlog .= $buf;
475 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
476 my $line = $1;
776fbfa8
DM
477 &$errfunc($line) if $errfunc;
478 &$logfunc($line) if $logfunc;
e143e9d8
DM
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;
776fbfa8
DM
496 &$logfunc($outlog) if $logfunc && $outlog;
497
e143e9d8 498 &$errfunc($errlog) if $errfunc && $errlog;
776fbfa8 499 &$logfunc($errlog) if $logfunc && $errlog;
e143e9d8
DM
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";
7e826928
TL
507 } elsif ($exitcode = ($? >> 8)) {
508 if (!($exitcode == 24 && ($cmdstr =~ m|^(\S+/)?rsync\s|))) {
1c50a24a
DM
509 if ($errmsg && $laststderr) {
510 my $lerr = $laststderr;
511 $laststderr = undef;
512 die "$lerr\n";
513 }
7e826928 514 die "exit code $exitcode\n";
e143e9d8 515 }
e143e9d8
DM
516 }
517
518 alarm(0);
519 };
520
521 my $err = $@;
522
523 alarm(0);
524
4630cb95
DM
525 if ($errmsg && $laststderr) {
526 &$errfunc(undef); # flush laststderr
527 }
e143e9d8
DM
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) {
adbc988d 541 $err =~ s/^usermod:\s*// if $cmdstr =~ m|^(\S+/)?usermod\s|;
e143e9d8 542 die "$errmsg: $err";
7e826928 543 } elsif(!$noerr) {
e143e9d8
DM
544 die "command '$cmdstr' failed: $err";
545 }
546 }
1c50a24a 547
7e826928 548 return $exitcode;
e143e9d8
DM
549}
550
551sub split_list {
552 my $listtxt = shift || '';
553
d2b0374d
DM
554 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
555
556 $listtxt =~ s/[,;]/ /g;
e143e9d8
DM
557 $listtxt =~ s/^\s+//;
558
559 my @data = split (/\s+/, $listtxt);
560
561 return @data;
562}
563
564sub 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}"
576sub template_replace {
577 my ($tmpl, $data) = @_;
578
3250f5c7
DM
579 return $tmpl if !$tmpl;
580
e143e9d8
DM
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
589sub 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
599sub 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
910d57b0
DM
644my $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' ],
5a5ca434
DM
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 ],
910d57b0
DM
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],
9934cd0b 674 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
910d57b0 675 #'th' => [],
c10cc112 676 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
910d57b0
DM
677};
678
679my $kvmkeymaparray = [];
680foreach my $lc (keys %$keymaphash) {
681 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
682}
683
e143e9d8 684sub kvmkeymaps {
910d57b0
DM
685 return $keymaphash;
686}
687
688sub kvmkeymaplist {
689 return $kvmkeymaparray;
e143e9d8
DM
690}
691
692sub extract_param {
693 my ($param, $key) = @_;
694
695 my $res = $param->{$key};
696 delete $param->{$key};
697
698 return $res;
699}
700
eb7047f6 701# Note: we use this to wait until vncterm/spiceterm is ready
ec6d95b4
DM
702sub wait_for_vnc_port {
703 my ($port, $timeout) = @_;
704
705 $timeout = 5 if !$timeout;
eb7047f6
DM
706 my $sleeptime = 0;
707 my $starttime = [gettimeofday];
708 my $elapsed;
ec6d95b4 709
eb7047f6 710 while (($elapsed = tv_interval($starttime)) < $timeout) {
ec6d95b4
DM
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 }
eb7047f6
DM
722 $sleeptime += 100000 if $sleeptime < 1000000;
723 usleep($sleeptime);
ec6d95b4
DM
724 }
725
726 return undef;
727}
728
59b3f563 729sub next_unused_port {
46775218 730 my ($range_start, $range_end, $family) = @_;
59b3f563
DM
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";
e143e9d8 738
59b3f563 739 my $code = sub {
e143e9d8 740
59b3f563
DM
741 my $expiretime = 5;
742 my $ctime = time();
e143e9d8 743
59b3f563
DM
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 }
e143e9d8 755 }
59b3f563
DM
756
757 my $newport;
758
759 for (my $p = $range_start; $p < $range_end; $p++) {
760 next if $ports->{$p}; # reserved
761
00dc9d0f 762 my $sock = IO::Socket::IP->new(Listen => 5,
00dc9d0f
WB
763 LocalPort => $p,
764 ReuseAddr => 1,
46775218 765 Family => $family,
e43b3a0f
WB
766 Proto => 0,
767 GetAddrInfoFlags => 0);
59b3f563
DM
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);
e143e9d8 783
59b3f563
DM
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
795sub next_migrate_port {
46775218
WB
796 my ($family) = @_;
797 return next_unused_port(60000, 60050, $family);
59b3f563
DM
798}
799
800sub next_vnc_port {
46775218
WB
801 my ($family) = @_;
802 return next_unused_port(5900, 6000, $family);
59b3f563 803}
e143e9d8 804
2f13cbb5 805sub next_spice_port {
46775218
WB
806 my ($family) = @_;
807 return next_unused_port(61000, 61099, $family);
2f13cbb5
DM
808}
809
e143e9d8
DM
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"
97c8c857 813# So fork() before using Filesys::Df
e143e9d8
DM
814sub df {
815 my ($path, $timeout) = @_;
816
e143e9d8
DM
817 my $res = {
818 total => 0,
819 used => 0,
820 avail => 0,
821 };
822
97c8c857
WB
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);
e143e9d8 840 }
97c8c857
WB
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);
e143e9d8 853 };
e143e9d8 854 warn $@ if $@;
97c8c857
WB
855 $pipe->close();
856 kill('KILL', $child);
857 waitpid($child, 0);
e143e9d8
DM
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
866sub upid_encode {
867 my $d = shift;
868
19cec230
DM
869 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
870 # more that 8 characters for pstart
e143e9d8
DM
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
876sub upid_decode {
877 my ($upid, $noerr) = @_;
878
879 my $res;
880 my $filename;
881
882 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
19cec230
DM
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]+):$/) {
e143e9d8 885 $res->{node} = $1;
3702f038
DM
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);
e143e9d8
DM
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
904sub 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";
2b8e0f12 919 chown $wwwid, -1, $outfh;
e143e9d8
DM
920
921 return $outfh;
922};
923
924sub 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;
cc9121d3 930 my $maxlen = 4096;
e143e9d8
DM
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
951sub 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
959sub decode_text {
960 my ($data) = @_;
961
962 return Encode::decode("utf8", uri_unescape($data));
963}
964
815b2aba
DM
965sub decode_utf8_parameters {
966 my ($param) = @_;
967
34ebb226 968 foreach my $p (qw(comment description firstname lastname)) {
815b2aba
DM
969 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
970 }
971
972 return $param;
973}
974
a413a515
DM
975sub random_ether_addr {
976
46a11c00
DM
977 my ($seconds, $microseconds) = gettimeofday;
978
979 my $rand = Digest::SHA::sha1_hex($$, rand(), $seconds, $microseconds);
a413a515 980
85d5625a 981 # clear multicast, set local id
de9a267f 982 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
a413a515 983
85d5625a 984 return sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
a413a515 985}
e143e9d8 986
762e3223
DM
987sub shellquote {
988 my $str = shift;
989
7514b23a 990 return String::ShellQuote::shell_quote($str);
762e3223
DM
991}
992
65e1d3fc
DM
993sub 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
e38bcd35 1006# split an shell argument string into an array,
f9125663
DM
1007sub split_args {
1008 my ($str) = @_;
1009
e38bcd35 1010 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
f9125663
DM
1011}
1012
804b1041 1013sub dump_logfile {
eb7e5538 1014 my ($filename, $start, $limit, $filter) = @_;
804b1041
DM
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;
eb7e5538
DM
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 }
804b1041
DM
1049 }
1050
1051 close($fh);
1052
6de95a66
DM
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
1063sub dump_journal {
19e95cd0 1064 my ($start, $limit, $since, $until) = @_;
6de95a66
DM
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'];
19e95cd0
TL
1082
1083 push @$cmd, '--since', $since if $since;
1084 push @$cmd, '--until', $until if $until;
6de95a66
DM
1085 run_command($cmd, outfunc => $parser);
1086
804b1041
DM
1087 # HACK: ExtJS store.guaranteeRange() does not like empty array
1088 # so we add a line
1089 if (!$count) {
1090 $count++;
1091 push @$lines, { n => $count, t => "no content"};
1092 }
1093
1094 return ($count, $lines);
1095}
1096
7eb283fb
DM
1097sub dir_glob_regex {
1098 my ($dir, $regex) = @_;
1099
1100 my $dh = IO::Dir->new ($dir);
1101 return wantarray ? () : undef if !$dh;
1102
1103 while (defined(my $tmp = $dh->read)) {
1104 if (my @res = $tmp =~ m/^($regex)$/) {
1105 $dh->close;
1106 return wantarray ? @res : $tmp;
1107 }
1108 }
1109 $dh->close;
1110
1111 return wantarray ? () : undef;
1112}
1113
1114sub dir_glob_foreach {
1115 my ($dir, $regex, $func) = @_;
1116
1117 my $dh = IO::Dir->new ($dir);
1118 if (defined $dh) {
1119 while (defined(my $tmp = $dh->read)) {
1120 if (my @res = $tmp =~ m/^($regex)$/) {
1121 &$func (@res);
1122 }
1123 }
1124 }
1125}
1126
a345b9d5
DM
1127sub assert_if_modified {
1128 my ($digest1, $digest2) = @_;
1129
1130 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
212fc0b7 1131 die "detected modified configuration - file changed by other user? Try again.\n";
a345b9d5
DM
1132 }
1133}
1134
2d3bca34
DM
1135# Digest for short strings
1136# like FNV32a, but we only return 31 bits (positive numbers)
1137sub fnv31a {
1138 my ($string) = @_;
1139
1140 my $hval = 0x811c9dc5;
1141
1142 foreach my $c (unpack('C*', $string)) {
1143 $hval ^= $c;
1144 $hval += (
1145 (($hval << 1) ) +
1146 (($hval << 4) ) +
1147 (($hval << 7) ) +
1148 (($hval << 8) ) +
1149 (($hval << 24) ) );
1150 $hval = $hval & 0xffffffff;
1151 }
1152 return $hval & 0x7fffffff;
1153}
1154
1155sub fnv31a_hex { return sprintf("%X", fnv31a(@_)); }
1156
8df6b794
WB
1157sub unpack_sockaddr_in46 {
1158 my ($sin) = @_;
1159 my $family = Socket::sockaddr_family($sin);
1160 my ($port, $host) = ($family == AF_INET6 ? Socket::unpack_sockaddr_in6($sin)
1161 : Socket::unpack_sockaddr_in($sin));
1162 return ($family, $port, $host);
1163}
1164
a0b6ef52
WB
1165sub getaddrinfo_all {
1166 my ($hostname, @opts) = @_;
a956854f 1167 my %hints = ( flags => AI_V4MAPPED | AI_ALL,
a0b6ef52 1168 @opts );
a956854f 1169 my ($err, @res) = Socket::getaddrinfo($hostname, '0', \%hints);
a0b6ef52
WB
1170 die "failed to get address info for: $hostname: $err\n" if $err;
1171 return @res;
1172}
a956854f 1173
a0b6ef52
WB
1174sub get_host_address_family {
1175 my ($hostname, $socktype) = @_;
1176 my @res = getaddrinfo_all($hostname, socktype => $socktype);
1177 return $res[0]->{family};
a956854f
WB
1178}
1179
b2613777
WB
1180# Parses any sane kind of host, or host+port pair:
1181# The port is always optional and thus may be undef.
1182sub parse_host_and_port {
1183 my ($address) = @_;
1184 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1185 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1186 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1187 {
1188 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1189 }
1190 return; # nothing
1191}
1192
817c6be0 1193sub unshare($) {
952fd95e 1194 my ($flags) = @_;
817c6be0 1195 return 0 == syscall(272, $flags);
952fd95e
WB
1196}
1197
891b224a
WB
1198sub setns($$) {
1199 my ($fileno, $nstype) = @_;
1200 return 0 == syscall(308, $fileno, $nstype);
1201}
1202
44acb12c
WB
1203sub syncfs($) {
1204 my ($fileno) = @_;
1205 return 0 == syscall(306, $fileno);
1206}
1207
1208sub sync_mountpoint {
1209 my ($path) = @_;
1210 sysopen my $fd, $path, O_PATH or die "failed to open $path: $!\n";
1211 my $result = syncfs(fileno($fd));
1212 close($fd);
1213 return $result;
1214}
1215
e143e9d8 12161;