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