]> git.proxmox.com Git - pve-common.git/blame - src/PVE/Tools.pm
tools: add extract_sensitive_params
[pve-common.git] / src / PVE / Tools.pm
CommitLineData
e143e9d8
DM
1package PVE::Tools;
2
3use strict;
c36f332e 4use warnings;
7e1ee743 5use POSIX qw(EINTR EEXIST EOPNOTSUPP);
00dc9d0f 6use IO::Socket::IP;
a0ecb159
WB
7use Socket qw(AF_INET AF_INET6 AI_ALL AI_V4MAPPED AI_CANONNAME SOCK_DGRAM
8 IPPROTO_TCP);
e143e9d8
DM
9use IO::Select;
10use File::Basename;
11use File::Path qw(make_path);
97c8c857
WB
12use Filesys::Df (); # don't overwrite our df()
13use IO::Pipe;
e143e9d8 14use IO::File;
7eb283fb 15use IO::Dir;
21c56a96 16use IO::Handle;
e143e9d8
DM
17use IPC::Open3;
18use Fcntl qw(:DEFAULT :flock);
19use base 'Exporter';
20use URI::Escape;
21use Encode;
568ba6a4 22use Digest::SHA;
f2c72fc3 23use JSON;
e38bcd35 24use Text::ParseWords;
7514b23a 25use String::ShellQuote;
c38cea65 26use Time::HiRes qw(usleep gettimeofday tv_interval alarm);
d9f86d0d 27use Scalar::Util 'weaken';
b18826ce
SI
28use Date::Format qw(time2str);
29
c8e94d4b 30use PVE::Syscall;
e143e9d8 31
57eeea0c
DM
32# avoid warning when parsing long hex values with hex()
33no warnings 'portable'; # Support for 64-bit ints required
34
e143e9d8 35our @EXPORT_OK = qw(
602ec0cd
DM
36$IPV6RE
37$IPV4RE
813a5c0d 38lock_file
493004a2 39lock_file_full
813a5c0d
DC
40run_command
41file_set_contents
e143e9d8
DM
42file_get_contents
43file_read_firstline
7eb283fb
DM
44dir_glob_regex
45dir_glob_foreach
e143e9d8
DM
46split_list
47template_replace
48safe_print
49trim
50extract_param
40682a69 51extract_sensitive_params
23e0e0d7 52file_copy
ce007e99 53get_host_arch
c0647765
WB
54O_PATH
55O_TMPFILE
1b0bc6c0
WB
56AT_EMPTY_PATH
57AT_FDCWD
58CLONE_NEWNS
59CLONE_NEWUTS
60CLONE_NEWIPC
61CLONE_NEWUSER
62CLONE_NEWPID
63CLONE_NEWNET
e143e9d8
DM
64);
65
66my $pvelogdir = "/var/log/pve";
67my $pvetaskdir = "$pvelogdir/tasks";
68
69mkdir $pvelogdir;
70mkdir $pvetaskdir;
71
cd9bd252 72my $IPV4OCTET = "(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])";
602ec0cd
DM
73our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)";
74my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})";
75my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))";
76
77our $IPV6RE = "(?:" .
78 "(?:(?:" . "(?:$IPV6H16:){6})$IPV6LS32)|" .
79 "(?:(?:" . "::(?:$IPV6H16:){5})$IPV6LS32)|" .
80 "(?:(?:(?:" . "$IPV6H16)?::(?:$IPV6H16:){4})$IPV6LS32)|" .
81 "(?:(?:(?:(?:$IPV6H16:){0,1}$IPV6H16)?::(?:$IPV6H16:){3})$IPV6LS32)|" .
82 "(?:(?:(?:(?:$IPV6H16:){0,2}$IPV6H16)?::(?:$IPV6H16:){2})$IPV6LS32)|" .
83 "(?:(?:(?:(?:$IPV6H16:){0,3}$IPV6H16)?::(?:$IPV6H16:){1})$IPV6LS32)|" .
84 "(?:(?:(?:(?:$IPV6H16:){0,4}$IPV6H16)?::" . ")$IPV6LS32)|" .
85 "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" . ")$IPV6H16)|" .
86 "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" . ")))";
87
176b1186
WB
88our $IPRE = "(?:$IPV4RE|$IPV6RE)";
89
be8f0477 90use constant {CLONE_NEWNS => 0x00020000,
952fd95e
WB
91 CLONE_NEWUTS => 0x04000000,
92 CLONE_NEWIPC => 0x08000000,
93 CLONE_NEWUSER => 0x10000000,
94 CLONE_NEWPID => 0x20000000,
be8f0477 95 CLONE_NEWNET => 0x40000000};
952fd95e 96
26598a51 97use constant {O_PATH => 0x00200000,
b260d4e3 98 O_CLOEXEC => 0x00080000,
26598a51 99 O_TMPFILE => 0x00410000}; # This includes O_DIRECTORY
44acb12c 100
1b0bc6c0
WB
101use constant {AT_EMPTY_PATH => 0x1000,
102 AT_FDCWD => -100};
6cf6b404 103
0f0990f1
DM
104sub run_with_timeout {
105 my ($timeout, $code, @param) = @_;
e143e9d8 106
0f0990f1 107 die "got timeout\n" if $timeout <= 0;
e143e9d8 108
c38cea65 109 my $prev_alarm = alarm 0; # suspend outer alarm early
0f0990f1
DM
110
111 my $sigcount = 0;
e143e9d8
DM
112
113 my $res;
114
e143e9d8 115 eval {
0f0990f1
DM
116 local $SIG{ALRM} = sub { $sigcount++; die "got timeout\n"; };
117 local $SIG{PIPE} = sub { $sigcount++; die "broken pipe\n" };
118 local $SIG{__DIE__}; # see SA bug 4631
e143e9d8 119
c38cea65 120 alarm($timeout);
e143e9d8 121
c38cea65 122 eval { $res = &$code(@param); };
0f0990f1
DM
123
124 alarm(0); # avoid race conditions
c38cea65
WB
125
126 die $@ if $@;
0f0990f1
DM
127 };
128
129 my $err = $@;
130
c38cea65 131 alarm $prev_alarm;
0f0990f1 132
c38cea65 133 # this shouldn't happen anymore?
0f0990f1
DM
134 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
135
136 die $err if $err;
137
138 return $res;
139}
e143e9d8 140
0f0990f1 141# flock: we use one file handle per process, so lock file
d9f86d0d
WB
142# can be nested multiple times and succeeds for the same process.
143#
144# Since this is the only way we lock now and we don't have the old
145# 'lock(); code(); unlock();' pattern anymore we do not actually need to
146# count how deep we're nesting. Therefore this hash now stores a weak reference
147# to a boolean telling us whether we already have a lock.
0f0990f1
DM
148
149my $lock_handles = {};
150
493004a2
DM
151sub lock_file_full {
152 my ($filename, $timeout, $shared, $code, @param) = @_;
0f0990f1
DM
153
154 $timeout = 10 if !$timeout;
155
493004a2
DM
156 my $mode = $shared ? LOCK_SH : LOCK_EX;
157
d9f86d0d 158 my $lockhash = ($lock_handles->{$$} //= {});
e143e9d8 159
d9f86d0d
WB
160 # Returns a locked file handle.
161 my $get_locked_file = sub {
162 my $fh = IO::File->new(">>$filename")
163 or die "can't open file - $!\n";
164
165 if (!flock($fh, $mode|LOCK_NB)) {
91bae4c0 166 print STDERR "trying to acquire lock...\n";
b5d12b08
DM
167 my $success;
168 while(1) {
d9f86d0d 169 $success = flock($fh, $mode);
b5d12b08
DM
170 # try again on EINTR (see bug #273)
171 if ($success || ($! != EINTR)) {
172 last;
173 }
174 }
d9f86d0d
WB
175 if (!$success) {
176 print STDERR " failed\n";
177 die "can't acquire lock '$filename' - $!\n";
178 }
179 print STDERR " OK\n";
180 }
181
182 return $fh;
e143e9d8
DM
183 };
184
0f0990f1 185 my $res;
d9f86d0d
WB
186 my $checkptr = $lockhash->{$filename};
187 my $check = 0; # This must not go out of scope before running the code.
188 my $local_fh; # This must stay local
189 if (!$checkptr || !$$checkptr) {
190 # We cannot create a weak reference in a single atomic step, so we first
191 # create a false-value, then create a reference to it, then weaken it,
192 # and after successfully locking the file we change the boolean value.
193 #
194 # The reason for this is that if an outer SIGALRM throws an exception
195 # between creating the reference and weakening it, a subsequent call to
196 # lock_file_full() will see a leftover full reference to a valid
197 # variable. This variable must be 0 in order for said call to attempt to
198 # lock the file anew.
199 #
200 # An externally triggered exception elsewhere in the code will cause the
201 # weak reference to become 'undef', and since the file handle is only
202 # stored in the local scope in $local_fh, the file will be closed by
203 # perl's cleanup routines as well.
204 #
205 # This still assumes that an IO::File handle can properly deal with such
206 # exceptions thrown during its own destruction, but that's up to perls
207 # guts now.
208 $lockhash->{$filename} = \$check;
209 weaken $lockhash->{$filename};
210 $local_fh = eval { run_with_timeout($timeout, $get_locked_file) };
211 if ($@) {
212 $@ = "can't lock file '$filename' - $@";
213 return undef;
f127adab 214 }
d9f86d0d 215 $check = 1;
e143e9d8 216 }
d9f86d0d
WB
217 $res = eval { &$code(@param); };
218 return undef if $@;
e143e9d8
DM
219 return $res;
220}
221
493004a2
DM
222
223sub lock_file {
224 my ($filename, $timeout, $code, @param) = @_;
225
226 return lock_file_full($filename, $timeout, 0, $code, @param);
227}
228
e143e9d8
DM
229sub file_set_contents {
230 my ($filename, $data, $perm) = @_;
231
232 $perm = 0644 if !defined($perm);
233
234 my $tmpname = "$filename.tmp.$$";
235
236 eval {
ce338f4f
WB
237 my ($fh, $tries) = (undef, 0);
238 while (!$fh && $tries++ < 3) {
239 $fh = IO::File->new($tmpname, O_WRONLY|O_CREAT|O_EXCL, $perm);
240 if (!$fh && $! == EEXIST) {
241 unlink($tmpname) or die "unable to delete old temp file: $!\n";
242 }
243 }
e143e9d8
DM
244 die "unable to open file '$tmpname' - $!\n" if !$fh;
245 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
246 die "closing file '$tmpname' failed - $!\n" unless close $fh;
247 };
248 my $err = $@;
249
250 if ($err) {
251 unlink $tmpname;
252 die $err;
253 }
254
255 if (!rename($tmpname, $filename)) {
256 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
257 unlink $tmpname;
813a5c0d 258 die $msg;
e143e9d8
DM
259 }
260}
261
262sub file_get_contents {
263 my ($filename, $max) = @_;
264
265 my $fh = IO::File->new($filename, "r") ||
266 die "can't open '$filename' - $!\n";
267
034a8181 268 my $content = safe_read_from($fh, $max, 0, $filename);
e143e9d8
DM
269
270 close $fh;
271
272 return $content;
273}
274
23e0e0d7
WL
275sub file_copy {
276 my ($filename, $dst, $max, $perm) = @_;
277
278 file_set_contents ($dst, file_get_contents($filename, $max), $perm);
279}
280
e143e9d8
DM
281sub file_read_firstline {
282 my ($filename) = @_;
283
284 my $fh = IO::File->new ($filename, "r");
285 return undef if !$fh;
286 my $res = <$fh>;
88955a2e 287 chomp $res if $res;
e143e9d8
DM
288 $fh->close;
289 return $res;
290}
291
292sub safe_read_from {
034a8181 293 my ($fh, $max, $oneline, $filename) = @_;
e143e9d8 294
8fb28ab9
FG
295 # pmxcfs file size limit
296 $max = 512*1024 if !$max;
e143e9d8 297
034a8181
DM
298 my $subject = defined($filename) ? "file '$filename'" : 'input';
299
e143e9d8
DM
300 my $br = 0;
301 my $input = '';
302 my $count;
303 while ($count = sysread($fh, $input, 8192, $br)) {
304 $br += $count;
034a8181 305 die "$subject too long - aborting\n" if $br > $max;
e143e9d8
DM
306 if ($oneline && $input =~ m/^(.*)\n/) {
307 $input = $1;
308 last;
309 }
813a5c0d 310 }
034a8181 311 die "unable to read $subject - $!\n" if !defined($count);
e143e9d8
DM
312
313 return $input;
314}
315
bd9c3a36
WB
316# The $cmd parameter can be:
317# -) a string
318# This is generally executed by passing it to the shell with the -c option.
319# However, it can be executed in one of two ways, depending on whether
320# there's a pipe involved:
321# *) with pipe: passed explicitly to bash -c, prefixed with:
322# set -o pipefail &&
323# *) without a pipe: passed to perl's open3 which uses 'sh -c'
324# (Note that this may result in two different syntax requirements!)
325# FIXME?
326# -) an array of arguments (strings)
327# Will be executed without interference from a shell. (Parameters are passed
328# as is, no escape sequences of strings will be touched.)
fcdc0cfc
WB
329# -) an array of arrays
330# Each array represents a command, and each command's output is piped into
331# the following command's standard input.
332# For this a shell command string is created with pipe symbols between each
333# command.
334# Each command is a list of strings meant to end up in the final command
335# unchanged. In order to achieve this, every argument is shell-quoted.
336# Quoting can be disabled for a particular argument by turning it into a
337# reference, this allows inserting arbitrary shell options.
338# For instance: the $cmd [ [ 'echo', 'hello', \'>/dev/null' ] ] will not
339# produce any output, while the $cmd [ [ 'echo', 'hello', '>/dev/null' ] ]
340# will literally print: hello >/dev/null
e143e9d8
DM
341sub run_command {
342 my ($cmd, %param) = @_;
343
344 my $old_umask;
ded47a61 345 my $cmdstr;
e143e9d8 346
fcdc0cfc
WB
347 if (my $ref = ref($cmd)) {
348 if (ref($cmd->[0])) {
349 $cmdstr = 'set -o pipefail && ';
350 my $pipe = '';
351 foreach my $command (@$cmd) {
352 # concatenate quoted parameters
353 # strings which are passed by reference are NOT shell quoted
354 $cmdstr .= $pipe . join(' ', map { ref($_) ? $$_ : shellquote($_) } @$command);
355 $pipe = ' | ';
356 }
1a0c0103 357 $cmd = [ '/bin/bash', '-c', "$cmdstr" ];
fcdc0cfc
WB
358 } else {
359 $cmdstr = cmd2string($cmd);
360 }
361 } else {
ded47a61 362 $cmdstr = $cmd;
22d4efe6 363 if ($cmd =~ m/\|/) {
e0cabd2c
DM
364 # see 'man bash' for option pipefail
365 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
366 } else {
367 $cmd = [ $cmd ];
368 }
ded47a61 369 }
e143e9d8
DM
370
371 my $errmsg;
372 my $laststderr;
373 my $timeout;
374 my $oldtimeout;
375 my $pid;
38d9aa12 376 my $exitcode = -1;
e143e9d8 377
4630cb95
DM
378 my $outfunc;
379 my $errfunc;
380 my $logfunc;
381 my $input;
382 my $output;
a417477c 383 my $afterfork;
7e826928 384 my $noerr;
0f3f314e 385 my $keeplocale;
ed61b9d6 386 my $quiet;
4630cb95 387
e143e9d8 388 eval {
e143e9d8
DM
389
390 foreach my $p (keys %param) {
391 if ($p eq 'timeout') {
392 $timeout = $param{$p};
393 } elsif ($p eq 'umask') {
eb9e24df 394 $old_umask = umask($param{$p});
e143e9d8
DM
395 } elsif ($p eq 'errmsg') {
396 $errmsg = $param{$p};
e143e9d8
DM
397 } elsif ($p eq 'input') {
398 $input = $param{$p};
1c50a24a
DM
399 } elsif ($p eq 'output') {
400 $output = $param{$p};
e143e9d8
DM
401 } elsif ($p eq 'outfunc') {
402 $outfunc = $param{$p};
403 } elsif ($p eq 'errfunc') {
404 $errfunc = $param{$p};
776fbfa8
DM
405 } elsif ($p eq 'logfunc') {
406 $logfunc = $param{$p};
a417477c
DM
407 } elsif ($p eq 'afterfork') {
408 $afterfork = $param{$p};
7e826928
TL
409 } elsif ($p eq 'noerr') {
410 $noerr = $param{$p};
0f3f314e
DC
411 } elsif ($p eq 'keeplocale') {
412 $keeplocale = $param{$p};
ed61b9d6
TL
413 } elsif ($p eq 'quiet') {
414 $quiet = $param{$p};
e143e9d8
DM
415 } else {
416 die "got unknown parameter '$p' for run_command\n";
417 }
418 }
419
4630cb95
DM
420 if ($errmsg) {
421 my $origerrfunc = $errfunc;
422 $errfunc = sub {
423 if ($laststderr) {
424 if ($origerrfunc) {
425 &$origerrfunc("$laststderr\n");
426 } else {
427 print STDERR "$laststderr\n" if $laststderr;
428 }
429 }
813a5c0d 430 $laststderr = shift;
4630cb95
DM
431 };
432 }
433
1c50a24a
DM
434 my $reader = $output && $output =~ m/^>&/ ? $output : IO::File->new();
435 my $writer = $input && $input =~ m/^<&/ ? $input : IO::File->new();
436 my $error = IO::File->new();
437
e143e9d8
DM
438 my $orig_pid = $$;
439
440 eval {
0f3f314e 441 local $ENV{LC_ALL} = 'C' if !$keeplocale;
e143e9d8
DM
442
443 # suppress LVM warnings like: "File descriptor 3 left open";
444 local $ENV{LVM_SUPPRESS_FD_WARNINGS} = "1";
445
446 $pid = open3($writer, $reader, $error, @$cmd) || die $!;
f38995ab
DM
447
448 # if we pipe fron STDIN, open3 closes STDIN, so we we
449 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
450 # as soon as we open a new file.
451 # to avoid that we open /dev/null
452 if (!ref($writer) && !defined(fileno(STDIN))) {
453 POSIX::close(0);
454 open(STDIN, "</dev/null");
455 }
e143e9d8
DM
456 };
457
458 my $err = $@;
459
460 # catch exec errors
461 if ($orig_pid != $$) {
462 warn "ERROR: $err";
813a5c0d
DC
463 POSIX::_exit (1);
464 kill ('KILL', $$);
e143e9d8
DM
465 }
466
467 die $err if $err;
468
469 local $SIG{ALRM} = sub { die "got timeout\n"; } if $timeout;
470 $oldtimeout = alarm($timeout) if $timeout;
471
a417477c
DM
472 &$afterfork() if $afterfork;
473
f38995ab
DM
474 if (ref($writer)) {
475 print $writer $input if defined $input;
476 close $writer;
477 }
e143e9d8
DM
478
479 my $select = new IO::Select;
f38995ab 480 $select->add($reader) if ref($reader);
e143e9d8
DM
481 $select->add($error);
482
483 my $outlog = '';
484 my $errlog = '';
485
486 my $starttime = time();
487
488 while ($select->count) {
489 my @handles = $select->can_read(1);
490
491 foreach my $h (@handles) {
492 my $buf = '';
493 my $count = sysread ($h, $buf, 4096);
494 if (!defined ($count)) {
495 my $err = $!;
496 kill (9, $pid);
497 waitpid ($pid, 0);
498 die $err;
499 }
500 $select->remove ($h) if !$count;
501 if ($h eq $reader) {
776fbfa8 502 if ($outfunc || $logfunc) {
e143e9d8 503 eval {
ba104d67 504 while ($buf =~ s/^([^\010\r\n]*)(?:\n|(?:\010)+|\r\n?)//) {
cb9db10c
DC
505 my $line = $outlog . $1;
506 $outlog = '';
776fbfa8
DM
507 &$outfunc($line) if $outfunc;
508 &$logfunc($line) if $logfunc;
e143e9d8 509 }
cb9db10c 510 $outlog .= $buf;
e143e9d8
DM
511 };
512 my $err = $@;
513 if ($err) {
514 kill (9, $pid);
515 waitpid ($pid, 0);
516 die $err;
517 }
ed61b9d6 518 } elsif (!$quiet) {
e143e9d8
DM
519 print $buf;
520 *STDOUT->flush();
521 }
522 } elsif ($h eq $error) {
776fbfa8 523 if ($errfunc || $logfunc) {
e143e9d8 524 eval {
ba104d67 525 while ($buf =~ s/^([^\010\r\n]*)(?:\n|(?:\010)+|\r\n?)//) {
cb9db10c
DC
526 my $line = $errlog . $1;
527 $errlog = '';
776fbfa8
DM
528 &$errfunc($line) if $errfunc;
529 &$logfunc($line) if $logfunc;
e143e9d8 530 }
cb9db10c 531 $errlog .= $buf;
e143e9d8
DM
532 };
533 my $err = $@;
534 if ($err) {
535 kill (9, $pid);
536 waitpid ($pid, 0);
537 die $err;
538 }
ed61b9d6 539 } elsif (!$quiet) {
e143e9d8
DM
540 print STDERR $buf;
541 *STDERR->flush();
542 }
543 }
544 }
545 }
546
547 &$outfunc($outlog) if $outfunc && $outlog;
776fbfa8
DM
548 &$logfunc($outlog) if $logfunc && $outlog;
549
e143e9d8 550 &$errfunc($errlog) if $errfunc && $errlog;
776fbfa8 551 &$logfunc($errlog) if $logfunc && $errlog;
e143e9d8
DM
552
553 waitpid ($pid, 0);
813a5c0d 554
e143e9d8
DM
555 if ($? == -1) {
556 die "failed to execute\n";
557 } elsif (my $sig = ($? & 127)) {
558 die "got signal $sig\n";
7e826928
TL
559 } elsif ($exitcode = ($? >> 8)) {
560 if (!($exitcode == 24 && ($cmdstr =~ m|^(\S+/)?rsync\s|))) {
1c50a24a
DM
561 if ($errmsg && $laststderr) {
562 my $lerr = $laststderr;
563 $laststderr = undef;
564 die "$lerr\n";
565 }
7e826928 566 die "exit code $exitcode\n";
e143e9d8 567 }
e143e9d8
DM
568 }
569
570 alarm(0);
571 };
572
573 my $err = $@;
574
575 alarm(0);
576
4630cb95
DM
577 if ($errmsg && $laststderr) {
578 &$errfunc(undef); # flush laststderr
579 }
e143e9d8
DM
580
581 umask ($old_umask) if defined($old_umask);
582
583 alarm($oldtimeout) if $oldtimeout;
584
585 if ($err) {
586 if ($pid && ($err eq "got timeout\n")) {
587 kill (9, $pid);
588 waitpid ($pid, 0);
589 die "command '$cmdstr' failed: $err";
590 }
591
592 if ($errmsg) {
adbc988d 593 $err =~ s/^usermod:\s*// if $cmdstr =~ m|^(\S+/)?usermod\s|;
e143e9d8 594 die "$errmsg: $err";
7e826928 595 } elsif(!$noerr) {
e143e9d8
DM
596 die "command '$cmdstr' failed: $err";
597 }
598 }
1c50a24a 599
7e826928 600 return $exitcode;
e143e9d8
DM
601}
602
2d38b8a1
TL
603# Run a command with a tcp socket as standard input.
604sub pipe_socket_to_command {
605 my ($cmd, $ip, $port) = @_;
606
607 my $params = {
608 Listen => 1,
609 ReuseAddr => 1,
610 Proto => &Socket::IPPROTO_TCP,
611 GetAddrInfoFlags => 0,
612 LocalAddr => $ip,
613 LocalPort => $port,
614 };
615 my $socket = IO::Socket::IP->new(%$params) or die "failed to open socket: $!\n";
616
617 print "$ip\n$port\n"; # tell remote where to connect
618 *STDOUT->flush();
619
620 alarm 0;
621 local $SIG{ALRM} = sub { die "timed out waiting for client\n" };
622 alarm 30;
623 my $client = $socket->accept; # Wait for a client
624 alarm 0;
625 close($socket);
626
627 # We want that the command talks over the TCP socket and takes
628 # ownership of it, so that when it closes it the connection is
629 # terminated, so we need to be able to close the socket. So we
630 # can't really use PVE::Tools::run_command().
631 my $pid = fork() // die "fork failed: $!\n";
632 if (!$pid) {
633 POSIX::dup2(fileno($client), 0);
634 POSIX::dup2(fileno($client), 1);
635 close($client);
636 exec {$cmd->[0]} @$cmd or do {
637 warn "exec failed: $!\n";
638 POSIX::_exit(1);
639 };
640 }
641
642 close($client);
643 if (waitpid($pid, 0) != $pid) {
644 kill(15 => $pid); # if we got interrupted terminate the child
645 my $count = 0;
646 while (waitpid($pid, POSIX::WNOHANG) != $pid) {
647 usleep(100000);
648 $count++;
649 kill(9 => $pid), last if $count > 300; # 30 second timeout
650 }
651 }
652 if (my $sig = ($? & 127)) {
653 die "got signal $sig\n";
654 } elsif (my $exitcode = ($? >> 8)) {
655 die "exit code $exitcode\n";
656 }
657
658 return undef;
659}
660
e143e9d8 661sub split_list {
0a3de87e 662 my $listtxt = shift // '';
e143e9d8 663
d2b0374d 664 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
813a5c0d 665
d2b0374d 666 $listtxt =~ s/[,;]/ /g;
e143e9d8
DM
667 $listtxt =~ s/^\s+//;
668
669 my @data = split (/\s+/, $listtxt);
670
671 return @data;
672}
673
674sub trim {
675 my $txt = shift;
676
677 return $txt if !defined($txt);
678
679 $txt =~ s/^\s+//;
680 $txt =~ s/\s+$//;
813a5c0d 681
e143e9d8
DM
682 return $txt;
683}
684
685# simple uri templates like "/vms/{vmid}"
686sub template_replace {
687 my ($tmpl, $data) = @_;
688
3250f5c7 689 return $tmpl if !$tmpl;
813a5c0d 690
e143e9d8 691 my $res = '';
14410e5f 692 while ($tmpl =~ m/([^{]+)?(\{([^}]+)\})?/g) {
e143e9d8
DM
693 $res .= $1 if $1;
694 $res .= ($data->{$3} || '-') if $2;
695 }
696 return $res;
697}
698
699sub safe_print {
700 my ($filename, $fh, $data) = @_;
701
702 return if !$data;
703
704 my $res = print $fh $data;
705
706 die "write to '$filename' failed\n" if !$res;
707}
708
709sub debmirrors {
710
711 return {
712 'at' => 'ftp.at.debian.org',
713 'au' => 'ftp.au.debian.org',
714 'be' => 'ftp.be.debian.org',
715 'bg' => 'ftp.bg.debian.org',
716 'br' => 'ftp.br.debian.org',
717 'ca' => 'ftp.ca.debian.org',
718 'ch' => 'ftp.ch.debian.org',
719 'cl' => 'ftp.cl.debian.org',
720 'cz' => 'ftp.cz.debian.org',
721 'de' => 'ftp.de.debian.org',
722 'dk' => 'ftp.dk.debian.org',
723 'ee' => 'ftp.ee.debian.org',
724 'es' => 'ftp.es.debian.org',
725 'fi' => 'ftp.fi.debian.org',
726 'fr' => 'ftp.fr.debian.org',
727 'gr' => 'ftp.gr.debian.org',
728 'hk' => 'ftp.hk.debian.org',
729 'hr' => 'ftp.hr.debian.org',
730 'hu' => 'ftp.hu.debian.org',
731 'ie' => 'ftp.ie.debian.org',
732 'is' => 'ftp.is.debian.org',
733 'it' => 'ftp.it.debian.org',
734 'jp' => 'ftp.jp.debian.org',
735 'kr' => 'ftp.kr.debian.org',
736 'mx' => 'ftp.mx.debian.org',
737 'nl' => 'ftp.nl.debian.org',
738 'no' => 'ftp.no.debian.org',
739 'nz' => 'ftp.nz.debian.org',
740 'pl' => 'ftp.pl.debian.org',
741 'pt' => 'ftp.pt.debian.org',
742 'ro' => 'ftp.ro.debian.org',
743 'ru' => 'ftp.ru.debian.org',
744 'se' => 'ftp.se.debian.org',
745 'si' => 'ftp.si.debian.org',
746 'sk' => 'ftp.sk.debian.org',
747 'tr' => 'ftp.tr.debian.org',
748 'tw' => 'ftp.tw.debian.org',
749 'gb' => 'ftp.uk.debian.org',
750 'us' => 'ftp.us.debian.org',
751 };
752}
753
910d57b0
DM
754my $keymaphash = {
755 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
756 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
813a5c0d 757 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
5a5ca434
DM
758 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
759 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
910d57b0
DM
760 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
761 #'et' => [], # Ethopia or Estonia ??
762 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
763 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
764 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
765 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
766 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
767 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
768 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
769 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
770 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
771 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
772 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
773 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
774 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
775 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
776 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
777 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
813a5c0d 778 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
910d57b0
DM
779 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
780 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
781 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
fb3a1b29 782 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # don't know?
910d57b0 783 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
9934cd0b 784 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
910d57b0 785 #'th' => [],
c10cc112 786 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
910d57b0
DM
787};
788
789my $kvmkeymaparray = [];
0a7de820 790foreach my $lc (sort keys %$keymaphash) {
910d57b0
DM
791 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
792}
793
e143e9d8 794sub kvmkeymaps {
910d57b0
DM
795 return $keymaphash;
796}
797
798sub kvmkeymaplist {
799 return $kvmkeymaparray;
e143e9d8
DM
800}
801
802sub extract_param {
803 my ($param, $key) = @_;
804
805 my $res = $param->{$key};
806 delete $param->{$key};
807
808 return $res;
809}
810
40682a69
DC
811sub extract_sensitive_params :prototype($$$) {
812 my ($param, $sensitive_list, $delete_list) = @_;
813
814 my $sensitive;
815
816 my %delete = map { $_ => 1 } ($delete_list || [])->@*;
817
818 # always extract sensitive keys, so they don't get written to the www-data readable scfg
819 for my $opt (@$sensitive_list) {
820 # First handle deletions as explicitly setting `undef`, afterwards new values may override
821 # it.
822 if (exists($delete{$opt})) {
823 $sensitive->{$opt} = undef;
824 }
825
826 if (defined(my $value = extract_param($param, $opt))) {
827 $sensitive->{$opt} = $value;
828 }
829 }
830
831 return $sensitive;
832}
833
eb7047f6 834# Note: we use this to wait until vncterm/spiceterm is ready
ec6d95b4 835sub wait_for_vnc_port {
590b924e 836 my ($port, $family, $timeout) = @_;
ec6d95b4
DM
837
838 $timeout = 5 if !$timeout;
eb7047f6
DM
839 my $sleeptime = 0;
840 my $starttime = [gettimeofday];
841 my $elapsed;
ec6d95b4 842
590b924e
TL
843 my $cmd = ['/bin/ss', '-Htln', "sport = :$port"];
844 push @$cmd, $family == AF_INET6 ? '-6' : '-4' if defined($family);
845
9a41a7b7 846 my $found;
eb7047f6 847 while (($elapsed = tv_interval($starttime)) < $timeout) {
9a41a7b7 848 # -Htln = don't print header, tcp, listening sockets only, numeric ports
590b924e 849 run_command($cmd, outfunc => sub {
9a41a7b7
TL
850 my $line = shift;
851 if ($line =~ m/^LISTEN\s+\d+\s+\d+\s+\S+:(\d+)\s/) {
852 $found = 1 if ($port == $1);
ec6d95b4 853 }
9a41a7b7
TL
854 });
855 return 1 if $found;
eb7047f6
DM
856 $sleeptime += 100000 if $sleeptime < 1000000;
857 usleep($sleeptime);
ec6d95b4
DM
858 }
859
8fd0d634 860 die "Timeout while waiting for port '$port' to get ready!\n";
ec6d95b4
DM
861}
862
59b3f563 863sub next_unused_port {
c14960cc 864 my ($range_start, $range_end, $family, $address) = @_;
59b3f563
DM
865
866 # We use a file to register allocated ports.
867 # Those registrations expires after $expiretime.
868 # We use this to avoid race conditions between
869 # allocation and use of ports.
870
871 my $filename = "/var/tmp/pve-reserved-ports";
e143e9d8 872
59b3f563 873 my $code = sub {
e143e9d8 874
59b3f563
DM
875 my $expiretime = 5;
876 my $ctime = time();
e143e9d8 877
59b3f563
DM
878 my $ports = {};
879
880 if (my $fh = IO::File->new ($filename, "r")) {
881 while (my $line = <$fh>) {
882 if ($line =~ m/^(\d+)\s(\d+)$/) {
883 my ($port, $timestamp) = ($1, $2);
884 if (($timestamp + $expiretime) > $ctime) {
885 $ports->{$port} = $timestamp; # not expired
813a5c0d 886 }
59b3f563
DM
887 }
888 }
e143e9d8 889 }
813a5c0d 890
59b3f563 891 my $newport;
c14960cc
WB
892 my %sockargs = (Listen => 5,
893 ReuseAddr => 1,
894 Family => $family,
a0ecb159 895 Proto => IPPROTO_TCP,
c14960cc
WB
896 GetAddrInfoFlags => 0);
897 $sockargs{LocalAddr} = $address if defined($address);
59b3f563
DM
898
899 for (my $p = $range_start; $p < $range_end; $p++) {
900 next if $ports->{$p}; # reserved
901
c14960cc
WB
902 $sockargs{LocalPort} = $p;
903 my $sock = IO::Socket::IP->new(%sockargs);
59b3f563
DM
904
905 if ($sock) {
906 close($sock);
907 $newport = $p;
908 $ports->{$p} = $ctime;
909 last;
910 }
911 }
813a5c0d 912
59b3f563
DM
913 my $data = "";
914 foreach my $p (keys %$ports) {
915 $data .= "$p $ports->{$p}\n";
916 }
813a5c0d 917
59b3f563 918 file_set_contents($filename, $data);
e143e9d8 919
59b3f563
DM
920 return $newport;
921 };
922
3c476ed5 923 my $p = lock_file('/var/lock/pve-ports.lck', 10, $code);
59b3f563 924 die $@ if $@;
813a5c0d 925
59b3f563
DM
926 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
927
928 return $p;
929}
930
931sub next_migrate_port {
c14960cc
WB
932 my ($family, $address) = @_;
933 return next_unused_port(60000, 60050, $family, $address);
59b3f563
DM
934}
935
936sub next_vnc_port {
c14960cc
WB
937 my ($family, $address) = @_;
938 return next_unused_port(5900, 6000, $family, $address);
59b3f563 939}
e143e9d8 940
30aeac2e
DC
941sub spice_port_range {
942 return (61000, 61999);
943}
944
2f13cbb5 945sub next_spice_port {
c14960cc 946 my ($family, $address) = @_;
30aeac2e 947 return next_unused_port(spice_port_range(), $family, $address);
2f13cbb5
DM
948}
949
893ec6f2
WB
950sub must_stringify {
951 my ($value) = @_;
952 eval { $value = "$value" };
953 return "error turning value into a string: $@" if $@;
954 return $value;
955}
956
72fba911
EK
957# sigkill after $timeout a $sub running in a fork if it can't write a pipe
958# the $sub has to return a single scalar
959sub run_fork_with_timeout {
960 my ($timeout, $sub) = @_;
961
962 my $res;
963 my $error;
964 my $pipe_out = IO::Pipe->new();
72fba911
EK
965
966 # disable pending alarms, save their remaining time
967 my $prev_alarm = alarm 0;
968
eead1cca 969 # avoid leaving a zombie if the parent gets interrupted
72fba911 970 my $sig_received;
72fba911
EK
971
972 my $child = fork();
973 if (!defined($child)) {
974 die "fork failed: $!\n";
975 return $res;
976 }
977
978 if (!$child) {
979 $pipe_out->writer();
72fba911
EK
980
981 eval {
982 $res = $sub->();
f2c72fc3 983 print {$pipe_out} encode_json({ result => $res });
72fba911
EK
984 $pipe_out->flush();
985 };
986 if (my $err = $@) {
893ec6f2 987 print {$pipe_out} encode_json({ error => must_stringify($err) });
f2c72fc3 988 $pipe_out->flush();
72fba911
EK
989 POSIX::_exit(1);
990 }
991 POSIX::_exit(0);
992 }
993
2e353dfb
DC
994 local $SIG{INT} = sub { $sig_received++; };
995 local $SIG{TERM} = sub {
996 $error //= "interrupted by unexpected signal\n";
997 kill('TERM', $child);
998 };
999
72fba911 1000 $pipe_out->reader();
72fba911
EK
1001
1002 my $readvalues = sub {
1003 local $/ = undef;
2e353dfb 1004 my $child_res = decode_json(readline_nointr($pipe_out));
f2c72fc3
TL
1005 $res = $child_res->{result};
1006 $error = $child_res->{error};
72fba911
EK
1007 };
1008 eval {
a2d049af
WB
1009 if (defined($timeout)) {
1010 run_with_timeout($timeout, $readvalues);
1011 } else {
1012 $readvalues->();
1013 }
72fba911
EK
1014 };
1015 warn $@ if $@;
1016 $pipe_out->close();
72fba911
EK
1017 kill('KILL', $child);
1018 waitpid($child, 0);
1019
1020 alarm $prev_alarm;
1021 die "interrupted by unexpected signal\n" if $sig_received;
1022
1023 die $error if $error;
1024 return $res;
1025}
1026
a2d049af
WB
1027sub run_fork {
1028 my ($code) = @_;
1029 return run_fork_with_timeout(undef, $code);
1030}
1031
813a5c0d 1032# NOTE: NFS syscall can't be interrupted, so alarm does
e143e9d8
DM
1033# not work to provide timeouts.
1034# from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
97c8c857 1035# So fork() before using Filesys::Df
e143e9d8
DM
1036sub df {
1037 my ($path, $timeout) = @_;
1038
4fdc9659 1039 my $df = sub { return Filesys::Df::df($path, 1) };
97c8c857 1040
4fdc9659
TL
1041 my $res = eval { run_fork_with_timeout($timeout, $df) } // {};
1042 warn $@ if $@;
97c8c857 1043
8bc99fda
TL
1044 # untaint, but be flexible: PB usage can result in scientific notation
1045 my ($blocks, $used, $bavail) = map { defined($_) ? (/^([\d\.e\-+]+)$/) : 0 }
fd58bb2b
DC
1046 $res->@{qw(blocks used bavail)};
1047
4fdc9659 1048 return {
fd58bb2b
DC
1049 total => $blocks,
1050 used => $used,
1051 avail => $bavail,
e143e9d8 1052 };
e143e9d8
DM
1053}
1054
62635f92
DM
1055sub du {
1056 my ($path, $timeout) = @_;
1057
1058 my $size;
1059
1060 $timeout //= 10;
1061
1062 my $parser = sub {
1063 my $line = shift;
1064
1065 if ($line =~ m/^(\d+)\s+total$/) {
1066 $size = $1;
1067 }
1068 };
1069
1070 run_command(['du', '-scb', $path], outfunc => $parser, timeout => $timeout);
1071
1072 return $size;
1073}
1074
e143e9d8
DM
1075# UPID helper
1076# We use this to uniquely identify a process.
813a5c0d 1077# An 'Unique Process ID' has the following format:
e143e9d8
DM
1078# "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
1079
1080sub upid_encode {
1081 my $d = shift;
1082
19cec230
DM
1083 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
1084 # more that 8 characters for pstart
813a5c0d
DC
1085 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid},
1086 $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id},
e143e9d8
DM
1087 $d->{user});
1088}
1089
1090sub upid_decode {
1091 my ($upid, $noerr) = @_;
1092
1093 my $res;
1094 my $filename;
1095
1096 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
19cec230
DM
1097 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
1098 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 1099 $res->{node} = $1;
3702f038
DM
1100 $res->{pid} = hex($3);
1101 $res->{pstart} = hex($4);
1102 $res->{starttime} = hex($5);
1103 $res->{type} = $6;
1104 $res->{id} = $7;
1105 $res->{user} = $8;
1106
1107 my $subdir = substr($5, 7, 8);
e143e9d8
DM
1108 $filename = "$pvetaskdir/$subdir/$upid";
1109
1110 } else {
1111 return undef if $noerr;
1112 die "unable to parse worker upid '$upid'\n";
1113 }
1114
1115 return wantarray ? ($res, $filename) : $res;
1116}
1117
1118sub upid_open {
1119 my ($upid) = @_;
1120
813a5c0d 1121 my ($task, $filename) = upid_decode($upid);
e143e9d8
DM
1122
1123 my $dirname = dirname($filename);
1124 make_path($dirname);
1125
1126 my $wwwid = getpwnam('www-data') ||
1127 die "getpwnam failed";
1128
1129 my $perm = 0640;
813a5c0d 1130
e143e9d8
DM
1131 my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) ||
1132 die "unable to create output file '$filename' - $!\n";
2b8e0f12 1133 chown $wwwid, -1, $outfh;
e143e9d8
DM
1134
1135 return $outfh;
1136};
1137
1138sub upid_read_status {
1139 my ($upid) = @_;
1140
1141 my ($task, $filename) = upid_decode($upid);
1142 my $fh = IO::File->new($filename, "r");
1143 return "unable to open file - $!" if !$fh;
cc9121d3 1144 my $maxlen = 4096;
e143e9d8
DM
1145 sysseek($fh, -$maxlen, 2);
1146 my $readbuf = '';
1147 my $br = sysread($fh, $readbuf, $maxlen);
1148 close($fh);
1149 if ($br) {
1150 return "unable to extract last line"
1151 if $readbuf !~ m/\n?(.+)$/;
1152 my $line = $1;
1153 if ($line =~ m/^TASK OK$/) {
1154 return 'OK';
1155 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
1156 return $1;
1157 } else {
1158 return "unexpected status";
1159 }
1160 }
1161 return "unable to read tail (got $br bytes)";
1162}
1163
813a5c0d 1164# useful functions to store comments in config files
e143e9d8
DM
1165sub encode_text {
1166 my ($text) = @_;
1167
1168 # all control and hi-bit characters, and ':'
1169 my $unsafe = "^\x20-\x39\x3b-\x7e";
1170 return uri_escape(Encode::encode("utf8", $text), $unsafe);
1171}
1172
1173sub decode_text {
1174 my ($data) = @_;
1175
1176 return Encode::decode("utf8", uri_unescape($data));
1177}
1178
6d46baf6
DM
1179# depreciated - do not use!
1180# we now decode all parameters by default
815b2aba
DM
1181sub decode_utf8_parameters {
1182 my ($param) = @_;
1183
34ebb226 1184 foreach my $p (qw(comment description firstname lastname)) {
815b2aba
DM
1185 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
1186 }
1187
1188 return $param;
1189}
1190
a413a515 1191sub random_ether_addr {
12392173 1192 my ($prefix) = @_;
a413a515 1193
46a11c00
DM
1194 my ($seconds, $microseconds) = gettimeofday;
1195
d743b69c 1196 my $rand = Digest::SHA::sha1($$, rand(), $seconds, $microseconds);
a413a515 1197
85d5625a 1198 # clear multicast, set local id
de9a267f 1199 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
a413a515 1200
12392173
WB
1201 my $addr = sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
1202 if (defined($prefix)) {
1203 $addr = uc($prefix) . substr($addr, length($prefix));
1204 }
1205 return $addr;
a413a515 1206}
e143e9d8 1207
762e3223
DM
1208sub shellquote {
1209 my $str = shift;
1210
7514b23a 1211 return String::ShellQuote::shell_quote($str);
762e3223
DM
1212}
1213
65e1d3fc
DM
1214sub cmd2string {
1215 my ($cmd) = @_;
1216
1217 die "no arguments" if !$cmd;
1218
1219 return $cmd if !ref($cmd);
1220
1221 my @qa = ();
1222 foreach my $arg (@$cmd) { push @qa, shellquote($arg); }
1223
1224 return join (' ', @qa);
1225}
1226
e38bcd35 1227# split an shell argument string into an array,
f9125663
DM
1228sub split_args {
1229 my ($str) = @_;
1230
e38bcd35 1231 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
f9125663
DM
1232}
1233
804b1041 1234sub dump_logfile {
eb7e5538 1235 my ($filename, $start, $limit, $filter) = @_;
804b1041
DM
1236
1237 my $lines = [];
1238 my $count = 0;
1239
1240 my $fh = IO::File->new($filename, "r");
813a5c0d 1241 if (!$fh) {
804b1041
DM
1242 $count++;
1243 push @$lines, { n => $count, t => "unable to open file - $!"};
1244 return ($count, $lines);
1245 }
1246
1247 $start = 0 if !$start;
1248 $limit = 50 if !$limit;
1249
1250 my $line;
eb7e5538
DM
1251
1252 if ($filter) {
1253 # duplicate code, so that we do not slow down normal path
1254 while (defined($line = <$fh>)) {
1255 next if $line !~ m/$filter/;
1256 next if $count++ < $start;
1257 next if $limit <= 0;
1258 chomp $line;
1259 push @$lines, { n => $count, t => $line};
1260 $limit--;
1261 }
1262 } else {
1263 while (defined($line = <$fh>)) {
1264 next if $count++ < $start;
1265 next if $limit <= 0;
1266 chomp $line;
1267 push @$lines, { n => $count, t => $line};
1268 $limit--;
1269 }
804b1041
DM
1270 }
1271
1272 close($fh);
1273
6de95a66
DM
1274 # HACK: ExtJS store.guaranteeRange() does not like empty array
1275 # so we add a line
1276 if (!$count) {
1277 $count++;
1278 push @$lines, { n => $count, t => "no content"};
1279 }
1280
1281 return ($count, $lines);
1282}
1283
1284sub dump_journal {
ccf60d3b 1285 my ($start, $limit, $since, $until, $service) = @_;
6de95a66
DM
1286
1287 my $lines = [];
1288 my $count = 0;
813a5c0d 1289
6de95a66
DM
1290 $start = 0 if !$start;
1291 $limit = 50 if !$limit;
1292
1293 my $parser = sub {
1294 my $line = shift;
1295
1296 return if $count++ < $start;
1297 return if $limit <= 0;
1298 push @$lines, { n => int($count), t => $line};
1299 $limit--;
1300 };
1301
1302 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
19e95cd0 1303
ccf60d3b 1304 push @$cmd, '--unit', $service if $service;
19e95cd0
TL
1305 push @$cmd, '--since', $since if $since;
1306 push @$cmd, '--until', $until if $until;
6de95a66
DM
1307 run_command($cmd, outfunc => $parser);
1308
804b1041
DM
1309 # HACK: ExtJS store.guaranteeRange() does not like empty array
1310 # so we add a line
1311 if (!$count) {
1312 $count++;
1313 push @$lines, { n => $count, t => "no content"};
1314 }
1315
1316 return ($count, $lines);
1317}
1318
7eb283fb
DM
1319sub dir_glob_regex {
1320 my ($dir, $regex) = @_;
1321
1322 my $dh = IO::Dir->new ($dir);
1323 return wantarray ? () : undef if !$dh;
813a5c0d
DC
1324
1325 while (defined(my $tmp = $dh->read)) {
7eb283fb
DM
1326 if (my @res = $tmp =~ m/^($regex)$/) {
1327 $dh->close;
1328 return wantarray ? @res : $tmp;
1329 }
1330 }
1331 $dh->close;
1332
1333 return wantarray ? () : undef;
1334}
1335
1336sub dir_glob_foreach {
1337 my ($dir, $regex, $func) = @_;
1338
1339 my $dh = IO::Dir->new ($dir);
1340 if (defined $dh) {
1341 while (defined(my $tmp = $dh->read)) {
1342 if (my @res = $tmp =~ m/^($regex)$/) {
1343 &$func (@res);
1344 }
1345 }
813a5c0d 1346 }
7eb283fb
DM
1347}
1348
a345b9d5
DM
1349sub assert_if_modified {
1350 my ($digest1, $digest2) = @_;
1351
1352 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
212fc0b7 1353 die "detected modified configuration - file changed by other user? Try again.\n";
a345b9d5
DM
1354 }
1355}
1356
2d3bca34
DM
1357# Digest for short strings
1358# like FNV32a, but we only return 31 bits (positive numbers)
1359sub fnv31a {
1360 my ($string) = @_;
1361
1362 my $hval = 0x811c9dc5;
1363
1364 foreach my $c (unpack('C*', $string)) {
1365 $hval ^= $c;
1366 $hval += (
1367 (($hval << 1) ) +
1368 (($hval << 4) ) +
1369 (($hval << 7) ) +
1370 (($hval << 8) ) +
1371 (($hval << 24) ) );
1372 $hval = $hval & 0xffffffff;
1373 }
1374 return $hval & 0x7fffffff;
1375}
1376
1377sub fnv31a_hex { return sprintf("%X", fnv31a(@_)); }
1378
8df6b794
WB
1379sub unpack_sockaddr_in46 {
1380 my ($sin) = @_;
1381 my $family = Socket::sockaddr_family($sin);
1382 my ($port, $host) = ($family == AF_INET6 ? Socket::unpack_sockaddr_in6($sin)
1383 : Socket::unpack_sockaddr_in($sin));
1384 return ($family, $port, $host);
1385}
1386
a0b6ef52
WB
1387sub getaddrinfo_all {
1388 my ($hostname, @opts) = @_;
a956854f 1389 my %hints = ( flags => AI_V4MAPPED | AI_ALL,
a0b6ef52 1390 @opts );
a956854f 1391 my ($err, @res) = Socket::getaddrinfo($hostname, '0', \%hints);
a0b6ef52
WB
1392 die "failed to get address info for: $hostname: $err\n" if $err;
1393 return @res;
1394}
a956854f 1395
a0b6ef52
WB
1396sub get_host_address_family {
1397 my ($hostname, $socktype) = @_;
1398 my @res = getaddrinfo_all($hostname, socktype => $socktype);
1399 return $res[0]->{family};
a956854f
WB
1400}
1401
d3c8f0c1
EK
1402# get the fully qualified domain name of a host
1403# same logic as hostname(1): The FQDN is the name getaddrinfo(3) returns,
1404# given a nodename as a parameter
1405sub get_fqdn {
1406 my ($nodename) = @_;
1407
1408 my $hints = {
1409 flags => AI_CANONNAME,
1410 socktype => SOCK_DGRAM
1411 };
1412
1413 my ($err, @addrs) = Socket::getaddrinfo($nodename, undef, $hints);
1414
1415 die "getaddrinfo: $err" if $err;
1416
1417 return $addrs[0]->{canonname};
1418}
1419
b2613777
WB
1420# Parses any sane kind of host, or host+port pair:
1421# The port is always optional and thus may be undef.
1422sub parse_host_and_port {
1423 my ($address) = @_;
1424 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1425 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1426 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1427 {
1428 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1429 }
1430 return; # nothing
1431}
1432
0c078e66
SI
1433sub setresuid($$$) {
1434 my ($ruid, $euid, $suid) = @_;
1435 return 0 == syscall(PVE::Syscall::setresuid, $ruid, $euid, $suid);
1436}
1437
817c6be0 1438sub unshare($) {
952fd95e 1439 my ($flags) = @_;
c8e94d4b 1440 return 0 == syscall(PVE::Syscall::unshare, $flags);
952fd95e
WB
1441}
1442
891b224a
WB
1443sub setns($$) {
1444 my ($fileno, $nstype) = @_;
c8e94d4b 1445 return 0 == syscall(PVE::Syscall::setns, $fileno, $nstype);
891b224a
WB
1446}
1447
44acb12c
WB
1448sub syncfs($) {
1449 my ($fileno) = @_;
c8e94d4b 1450 return 0 == syscall(PVE::Syscall::syncfs, $fileno);
44acb12c
WB
1451}
1452
cee0e23a
TL
1453sub fsync($) {
1454 my ($fileno) = @_;
1455 return 0 == syscall(PVE::Syscall::fsync, $fileno);
1456}
1457
44acb12c
WB
1458sub sync_mountpoint {
1459 my ($path) = @_;
b260d4e3 1460 sysopen my $fd, $path, O_RDONLY|O_CLOEXEC or die "failed to open $path: $!\n";
09d47f9d
TL
1461 my $syncfs_err;
1462 if (!syncfs(fileno($fd))) {
1463 $syncfs_err = "$!";
1464 }
44acb12c 1465 close($fd);
09d47f9d 1466 die "syncfs '$path' failed - $syncfs_err\n" if defined $syncfs_err;
44acb12c
WB
1467}
1468
b61a47db
TL
1469# support sending multi-part mail messages with a text and or a HTML part
1470# mailto may be a single email string or an array of receivers
1471sub sendmail {
1472 my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_;
c9c6d910 1473 my $mail_re = qr/[^-a-zA-Z0-9+._@]/;
b61a47db 1474
5a873e6d 1475 $mailto = [ $mailto ] if !ref($mailto);
b61a47db 1476
a7886364
TL
1477 for my $to (@$mailto) {
1478 die "illegal character in mailto address\n" if $to =~ $mail_re;
b61a47db 1479 }
c9c6d910 1480
b61a47db
TL
1481 my $rcvrtxt = join (', ', @$mailto);
1482
1483 $mailfrom = $mailfrom || "root";
a7886364 1484 die "illegal character in mailfrom address\n" if $mailfrom =~ $mail_re;
c9c6d910 1485
a24d91ea 1486 $author = $author // 'Proxmox VE';
b61a47db 1487
216a3f4f 1488 open (MAIL, "|-", "sendmail", "-B", "8BITMIME", "-f", $mailfrom, "--", @$mailto) ||
b61a47db
TL
1489 die "unable to open 'sendmail' - $!";
1490
b18826ce
SI
1491 my $date = time2str('%a, %d %b %Y %H:%M:%S %z', time());
1492
1493 my $is_multipart = $text && $html;
1494
b61a47db
TL
1495 # multipart spec see https://www.ietf.org/rfc/rfc1521.txt
1496 my $boundary = "----_=_NextPart_001_".int(time).$$;
1497
b18826ce
SI
1498 if ($subject =~ /[^[:ascii:]]/) {
1499 $subject = Encode::encode('MIME-Header', $subject);
1500 }
b61a47db 1501
b18826ce
SI
1502 if ($subject =~ /[^[:ascii:]]/ || $is_multipart) {
1503 print MAIL "MIME-Version: 1.0\n";
1504 }
1505 print MAIL "From: $author <$mailfrom>\n";
1506 print MAIL "To: $rcvrtxt\n";
1507 print MAIL "Date: $date\n";
1508 print MAIL "Subject: $subject\n";
1509
1510 if ($is_multipart) {
1511 print MAIL "Content-Type: multipart/alternative;\n";
1512 print MAIL "\tboundary=\"$boundary\"\n";
1513 print MAIL "\n";
1514 print MAIL "This is a multi-part message in MIME format.\n\n";
1515 print MAIL "--$boundary\n";
1516 }
b61a47db 1517
5a873e6d 1518 if (defined($text)) {
b61a47db 1519 print MAIL "Content-Type: text/plain;\n";
b18826ce 1520 print MAIL "\tcharset=\"UTF-8\"\n";
b61a47db
TL
1521 print MAIL "Content-Transfer-Encoding: 8bit\n";
1522 print MAIL "\n";
1523
1524 # avoid 'remove extra line breaks' issue (MS Outlook)
1525 my $fill = ' ';
1526 $text =~ s/^/$fill/gm;
1527
1528 print MAIL $text;
1529
b18826ce 1530 print MAIL "\n--$boundary\n" if $is_multipart;
b61a47db
TL
1531 }
1532
5a873e6d 1533 if (defined($html)) {
b61a47db 1534 print MAIL "Content-Type: text/html;\n";
b18826ce 1535 print MAIL "\tcharset=\"UTF-8\"\n";
b61a47db
TL
1536 print MAIL "Content-Transfer-Encoding: 8bit\n";
1537 print MAIL "\n";
1538
1539 print MAIL $html;
1540
b18826ce 1541 print MAIL "\n--$boundary--\n" if $is_multipart;
b61a47db
TL
1542 }
1543
1544 close(MAIL);
b61a47db
TL
1545}
1546
26598a51
WB
1547sub tempfile {
1548 my ($perm, %opts) = @_;
1549
1550 # default permissions are stricter than with file_set_contents
1551 $perm = 0600 if !defined($perm);
1552
f0cfc20e 1553 my $dir = $opts{dir} // '/run';
26598a51
WB
1554 my $mode = $opts{mode} // O_RDWR;
1555 $mode |= O_EXCL if !$opts{allow_links};
1556
7e1ee743
WB
1557 my $fh = IO::File->new($dir, $mode | O_TMPFILE, $perm);
1558 if (!$fh && $! == EOPNOTSUPP) {
77b2b96f 1559 $dir = '/tmp' if !defined($opts{dir});
7e1ee743
WB
1560 $dir .= "/.tmpfile.$$";
1561 $fh = IO::File->new($dir, $mode | O_CREAT | O_EXCL, $perm);
1562 unlink($dir) if $fh;
1563 }
1564 die "failed to create tempfile: $!\n" if !$fh;
26598a51
WB
1565 return $fh;
1566}
1567
1568sub tempfile_contents {
1569 my ($data, $perm, %opts) = @_;
1570
1571 my $fh = tempfile($perm, %opts);
1572 eval {
1573 die "unable to write to tempfile: $!\n" if !print {$fh} $data;
1574 die "unable to flush to tempfile: $!\n" if !defined($fh->flush());
1575 };
1576 if (my $err = $@) {
1577 close $fh;
1578 die $err;
1579 }
1580
1581 return ("/proc/$$/fd/".$fh->fileno, $fh);
1582}
1583
48df47a4
FG
1584sub validate_ssh_public_keys {
1585 my ($raw) = @_;
1586 my @lines = split(/\n/, $raw);
1587
1588 foreach my $line (@lines) {
1589 next if $line =~ m/^\s*$/;
1590 eval {
1591 my ($filename, $handle) = tempfile_contents($line);
1592 run_command(["ssh-keygen", "-l", "-f", $filename],
1593 outfunc => sub {}, errfunc => sub {});
1594 };
1595 die "SSH public key validation error\n" if $@;
1596 }
1597}
1598
21c56a96
WB
1599sub openat($$$;$) {
1600 my ($dirfd, $pathname, $flags, $mode) = @_;
c8e94d4b 1601 my $fd = syscall(PVE::Syscall::openat, $dirfd, $pathname, $flags, $mode//0);
21c56a96
WB
1602 return undef if $fd < 0;
1603 # sysopen() doesn't deal with numeric file descriptors apparently
1604 # so we need to convert to a mode string for IO::Handle->new_from_fd
1605 my $flagstr = ($flags & O_RDWR) ? 'rw' : ($flags & O_WRONLY) ? 'w' : 'r';
1606 my $handle = IO::Handle->new_from_fd($fd, $flagstr);
1607 return $handle if $handle;
1608 my $err = $!; # save error before closing the raw fd
c8e94d4b 1609 syscall(PVE::Syscall::close, $fd); # close
21c56a96
WB
1610 $! = $err;
1611 return undef;
1612}
1613
1614sub mkdirat($$$) {
1615 my ($dirfd, $name, $mode) = @_;
c8e94d4b 1616 return syscall(PVE::Syscall::mkdirat, $dirfd, $name, $mode) == 0;
21c56a96
WB
1617}
1618
6cf6b404
FG
1619sub fchownat($$$$$) {
1620 my ($dirfd, $pathname, $owner, $group, $flags) = @_;
1621 return syscall(PVE::Syscall::fchownat, $dirfd, $pathname, $owner, $group, $flags) == 0;
1622}
1623
9867ff7a
DM
1624my $salt_starter = time();
1625
1626sub encrypt_pw {
1627 my ($pw) = @_;
1628
1629 $salt_starter++;
1630 my $salt = substr(Digest::SHA::sha1_base64(time() + $salt_starter + $$), 0, 8);
1631
1632 # crypt does not want '+' in salt (see 'man crypt')
1633 $salt =~ s/\+/X/g;
1634
1635 return crypt(encode("utf8", $pw), "\$5\$$salt\$");
1636}
1637
8e677e74 1638# intended usage: convert_size($val, "kb" => "gb")
95386daf
DC
1639# we round up to the next integer by default
1640# E.g. `convert_size(1023, "b" => "kb")` returns 1
8e677e74 1641# use $no_round_up to switch this off, above example would then return 0
95386daf
DC
1642# this is also true for converting down e.g. 0.0005 gb to mb returns 1
1643# (0 if $no_round_up is true)
1644# allowed formats for value:
1645# 1234
1646# 1234.
1647# 1234.1234
1648# .1234
8e677e74
TL
1649sub convert_size {
1650 my ($value, $from, $to, $no_round_up) = @_;
1651
1652 my $units = {
1653 b => 0,
1654 kb => 1,
1655 mb => 2,
1656 gb => 3,
1657 tb => 4,
1658 pb => 5,
1659 };
1660
95386daf
DC
1661 die "no value given"
1662 if !defined($value) || $value eq "";
1663
1664 $from = lc($from // ''); $to = lc($to // '');
8e677e74 1665 die "unknown 'from' and/or 'to' units ($from => $to)"
95386daf 1666 if !defined($units->{$from}) || !defined($units->{$to});
8e677e74 1667
95386daf
DC
1668 die "value '$value' is not a valid, positive number"
1669 if $value !~ m/^(?:[0-9]+\.?[0-9]*|[0-9]*\.[0-9]+)$/;
8e677e74 1670
95386daf
DC
1671 my $shift_amount = ($units->{$from} - $units->{$to}) * 10;
1672
1673 $value *= 2**$shift_amount;
1674 $value++ if !$no_round_up && ($value - int($value)) > 0.0;
8e677e74 1675
95386daf 1676 return int($value);
8e677e74
TL
1677}
1678
e03a8365
DC
1679# uninterruptible readline
1680# retries on EINTR
1681sub readline_nointr {
1682 my ($fh) = @_;
1683 my $line;
1684 while (1) {
1685 $line = <$fh>;
1686 last if defined($line) || ($! != EINTR);
1687 }
1688 return $line;
1689}
1690
ce007e99 1691my $host_arch;
b8faece3 1692sub get_host_arch {
ce007e99
SR
1693 $host_arch = (POSIX::uname())[4] if !$host_arch;
1694 return $host_arch;
732b693f
DM
1695}
1696
243c4e58
WB
1697# Devices are: [ (12 bits minor) (12 bits major) (8 bits minor) ]
1698sub dev_t_major($) {
1699 my ($dev_t) = @_;
1700 return (int($dev_t) & 0xfff00) >> 8;
1701}
1702
1703sub dev_t_minor($) {
1704 my ($dev_t) = @_;
1705 $dev_t = int($dev_t);
1706 return (($dev_t >> 12) & 0xfff00) | ($dev_t & 0xff);
1707}
1708
a59544e7
SR
1709# Given an array of array refs [ \[a b c], \[a b b], \[e b a] ]
1710# Returns the intersection of elements as a single array [a b]
1711sub array_intersect {
1712 my ($arrays) = @_;
1713
3982313e
TL
1714 if (!ref($arrays->[0])) {
1715 $arrays = [ grep { ref($_) eq 'ARRAY' } @_ ];
1716 }
1717
38586028
TL
1718 return [] if scalar(@$arrays) == 0;
1719 return $arrays->[0] if scalar(@$arrays) == 1;
a59544e7 1720
4c28a8bc
TL
1721 my $array_unique = sub {
1722 my %seen = ();
1723 return grep { ! $seen{ $_ }++ } @_;
1724 };
1725
38586028
TL
1726 # base idea is to get all unique members from the first array, then
1727 # check the common elements with the next (uniquely made) one, only keep
1728 # those. Repeat for every array and at the end we only have those left
1729 # which exist in all arrays
1730 my $return_arr = [ $array_unique->(@{$arrays->[0]}) ];
a59544e7
SR
1731 for my $i (1 .. $#$arrays) {
1732 my %count = ();
38586028 1733 # $return_arr is already unique, explicit at before the loop, implicit below.
4c28a8bc 1734 foreach my $element (@$return_arr, $array_unique->(@{$arrays->[$i]})) {
a59544e7
SR
1735 $count{$element}++;
1736 }
1737 $return_arr = [];
1738 foreach my $element (keys %count) {
1739 push @$return_arr, $element if $count{$element} > 1;
1740 }
26a68cf6 1741 last if scalar(@$return_arr) == 0; # empty intersection, early exit
a59544e7
SR
1742 }
1743
1744 return $return_arr;
1745}
1746
76c5fee8
WB
1747sub open_tree($$$) {
1748 my ($dfd, $pathname, $flags) = @_;
1749 return PVE::Syscall::file_handle_result(syscall(
1750 &PVE::Syscall::open_tree,
1751 $dfd,
1752 $pathname,
1753 $flags,
1754 ));
1755}
1756
1757sub move_mount($$$$$) {
1758 my ($from_dirfd, $from_pathname, $to_dirfd, $to_pathname, $flags) = @_;
1759 return 0 == syscall(
1760 &PVE::Syscall::move_mount,
1761 $from_dirfd,
1762 $from_pathname,
1763 $to_dirfd,
1764 $to_pathname,
1765 $flags,
1766 );
1767}
1768
1769sub fsopen($$) {
1770 my ($fsname, $flags) = @_;
1771 return PVE::Syscall::file_handle_result(syscall(&PVE::Syscall::fsopen, $fsname, $flags));
1772}
1773
1774sub fsmount($$$) {
1775 my ($fd, $flags, $mount_attrs) = @_;
1776 return PVE::Syscall::file_handle_result(syscall(
1777 &PVE::Syscall::fsmount,
1778 $fd,
1779 $flags,
1780 $mount_attrs,
1781 ));
1782}
1783
1784sub fspick($$$) {
1785 my ($dirfd, $pathname, $flags) = @_;
1786 return PVE::Syscall::file_handle_result(syscall(
1787 &PVE::Syscall::fspick,
1788 $dirfd,
1789 $pathname,
1790 $flags,
1791 ));
1792}
1793
1794sub fsconfig($$$$$) {
1795 my ($fd, $command, $key, $value, $aux) = @_;
1796 return 0 == syscall(&PVE::Syscall::fsconfig, $fd, $command, $key, $value, $aux);
1797}
1798
1799# "raw" mount, old api, not for generic use (as it does not invoke any helpers).
1800# use for lower level stuff such as bind/remount/... or simple tmpfs mounts
1801sub mount($$$$$) {
1802 my ($source, $target, $filesystemtype, $mountflags, $data) = @_;
1803 return 0 == syscall(
1804 &PVE::Syscall::mount,
1805 $source,
1806 $target,
1807 $filesystemtype,
1808 $mountflags,
1809 $data,
1810 );
1811}
a59544e7 1812
890d25d9
FE
1813sub safe_compare {
1814 my ($left, $right, $cmp) = @_;
1815
1816 return 0 if !defined($left) && !defined($right);
1817 return -1 if !defined($left);
1818 return 1 if !defined($right);
1819 return $cmp->($left, $right);
1820}
1821
e143e9d8 18221;