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