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