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