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