5 use POSIX
qw(EINTR EEXIST EOPNOTSUPP);
7 use Socket
qw(AF_INET AF_INET6 AI_ALL AI_V4MAPPED);
10 use File
::Path
qw(make_path);
11 use Filesys
::Df
(); # don't overwrite our df()
17 use Fcntl
qw(:DEFAULT :flock);
23 use String
::ShellQuote
;
24 use Time
::HiRes
qw(usleep gettimeofday tv_interval alarm);
25 use Net
::DBus
qw(dbus_uint32 dbus_uint64);
26 use Net
::DBus
::Callback
;
27 use Net
::DBus
::Reactor
;
29 # avoid warning when parsing long hex values with hex()
30 no warnings
'portable'; # Support for 64-bit ints required
53 my $pvelogdir = "/var/log/pve";
54 my $pvetaskdir = "$pvelogdir/tasks";
59 my $IPV4OCTET = "(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])";
60 our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)";
61 my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})";
62 my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))";
65 "(?:(?:" . "(?:$IPV6H16:){6})$IPV6LS32)|" .
66 "(?:(?:" . "::(?:$IPV6H16:){5})$IPV6LS32)|" .
67 "(?:(?:(?:" . "$IPV6H16)?::(?:$IPV6H16:){4})$IPV6LS32)|" .
68 "(?:(?:(?:(?:$IPV6H16:){0,1}$IPV6H16)?::(?:$IPV6H16:){3})$IPV6LS32)|" .
69 "(?:(?:(?:(?:$IPV6H16:){0,2}$IPV6H16)?::(?:$IPV6H16:){2})$IPV6LS32)|" .
70 "(?:(?:(?:(?:$IPV6H16:){0,3}$IPV6H16)?::(?:$IPV6H16:){1})$IPV6LS32)|" .
71 "(?:(?:(?:(?:$IPV6H16:){0,4}$IPV6H16)?::" . ")$IPV6LS32)|" .
72 "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" . ")$IPV6H16)|" .
73 "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" . ")))";
75 our $IPRE = "(?:$IPV4RE|$IPV6RE)";
77 use constant {CLONE_NEWNS
=> 0x00020000,
78 CLONE_NEWUTS
=> 0x04000000,
79 CLONE_NEWIPC
=> 0x08000000,
80 CLONE_NEWUSER
=> 0x10000000,
81 CLONE_NEWPID
=> 0x20000000,
82 CLONE_NEWNET
=> 0x40000000};
84 use constant {O_PATH
=> 0x00200000,
85 O_TMPFILE
=> 0x00410000}; # This includes O_DIRECTORY
87 sub run_with_timeout
{
88 my ($timeout, $code, @param) = @_;
90 die "got timeout\n" if $timeout <= 0;
92 my $prev_alarm = alarm 0; # suspend outer alarm early
99 local $SIG{ALRM
} = sub { $sigcount++; die "got timeout\n"; };
100 local $SIG{PIPE
} = sub { $sigcount++; die "broken pipe\n" };
101 local $SIG{__DIE__
}; # see SA bug 4631
105 eval { $res = &$code(@param); };
107 alarm(0); # avoid race conditions
116 # this shouldn't happen anymore?
117 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
124 # flock: we use one file handle per process, so lock file
125 # can be called multiple times and succeeds for the same process.
127 my $lock_handles = {};
130 my ($filename, $timeout, $shared, $code, @param) = @_;
132 $timeout = 10 if !$timeout;
134 my $mode = $shared ? LOCK_SH
: LOCK_EX
;
136 my $lock_func = sub {
137 if (!$lock_handles->{$$}->{$filename}) {
138 my $fh = new IO
::File
(">>$filename") ||
139 die "can't open file - $!\n";
140 $lock_handles->{$$}->{$filename} = { fh
=> $fh, refcount
=> 0};
143 if (!flock($lock_handles->{$$}->{$filename}->{fh
}, $mode|LOCK_NB
)) {
144 print STDERR
"trying to acquire lock...";
147 $success = flock($lock_handles->{$$}->{$filename}->{fh
}, $mode);
148 # try again on EINTR (see bug #273)
149 if ($success || ($! != EINTR
)) {
154 print STDERR
" failed\n";
155 die "can't acquire lock '$filename' - $!\n";
157 print STDERR
" OK\n";
159 $lock_handles->{$$}->{$filename}->{refcount
}++;
164 eval { run_with_timeout
($timeout, $lock_func); };
167 $err = "can't lock file '$filename' - $err";
169 eval { $res = &$code(@param) };
173 if (my $fh = $lock_handles->{$$}->{$filename}->{fh
}) {
174 my $refcount = --$lock_handles->{$$}->{$filename}->{refcount
};
175 if ($refcount <= 0) {
176 $lock_handles->{$$}->{$filename} = undef;
193 my ($filename, $timeout, $code, @param) = @_;
195 return lock_file_full
($filename, $timeout, 0, $code, @param);
198 sub file_set_contents
{
199 my ($filename, $data, $perm) = @_;
201 $perm = 0644 if !defined($perm);
203 my $tmpname = "$filename.tmp.$$";
206 my ($fh, $tries) = (undef, 0);
207 while (!$fh && $tries++ < 3) {
208 $fh = IO
::File-
>new($tmpname, O_WRONLY
|O_CREAT
|O_EXCL
, $perm);
209 if (!$fh && $! == EEXIST
) {
210 unlink($tmpname) or die "unable to delete old temp file: $!\n";
213 die "unable to open file '$tmpname' - $!\n" if !$fh;
214 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
215 die "closing file '$tmpname' failed - $!\n" unless close $fh;
224 if (!rename($tmpname, $filename)) {
225 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
231 sub file_get_contents
{
232 my ($filename, $max) = @_;
234 my $fh = IO
::File-
>new($filename, "r") ||
235 die "can't open '$filename' - $!\n";
237 my $content = safe_read_from
($fh, $max, 0, $filename);
245 my ($filename, $dst, $max, $perm) = @_;
247 file_set_contents
($dst, file_get_contents
($filename, $max), $perm);
250 sub file_read_firstline
{
253 my $fh = IO
::File-
>new ($filename, "r");
254 return undef if !$fh;
262 my ($fh, $max, $oneline, $filename) = @_;
264 $max = 32768 if !$max;
266 my $subject = defined($filename) ?
"file '$filename'" : 'input';
271 while ($count = sysread($fh, $input, 8192, $br)) {
273 die "$subject too long - aborting\n" if $br > $max;
274 if ($oneline && $input =~ m/^(.*)\n/) {
279 die "unable to read $subject - $!\n" if !defined($count);
284 # The $cmd parameter can be:
286 # This is generally executed by passing it to the shell with the -c option.
287 # However, it can be executed in one of two ways, depending on whether
288 # there's a pipe involved:
289 # *) with pipe: passed explicitly to bash -c, prefixed with:
291 # *) without a pipe: passed to perl's open3 which uses 'sh -c'
292 # (Note that this may result in two different syntax requirements!)
294 # -) an array of arguments (strings)
295 # Will be executed without interference from a shell. (Parameters are passed
296 # as is, no escape sequences of strings will be touched.)
297 # -) an array of arrays
298 # Each array represents a command, and each command's output is piped into
299 # the following command's standard input.
300 # For this a shell command string is created with pipe symbols between each
302 # Each command is a list of strings meant to end up in the final command
303 # unchanged. In order to achieve this, every argument is shell-quoted.
304 # Quoting can be disabled for a particular argument by turning it into a
305 # reference, this allows inserting arbitrary shell options.
306 # For instance: the $cmd [ [ 'echo', 'hello', \'>/dev/null' ] ] will not
307 # produce any output, while the $cmd [ [ 'echo', 'hello', '>/dev/null' ] ]
308 # will literally print: hello >/dev/null
310 my ($cmd, %param) = @_;
315 if (my $ref = ref($cmd)) {
316 if (ref($cmd->[0])) {
317 $cmdstr = 'set -o pipefail && ';
319 foreach my $command (@$cmd) {
320 # concatenate quoted parameters
321 # strings which are passed by reference are NOT shell quoted
322 $cmdstr .= $pipe . join(' ', map { ref($_) ?
$$_ : shellquote
($_) } @$command);
325 $cmd = [ '/bin/bash', '-c', "$cmdstr" ];
327 $cmdstr = cmd2string
($cmd);
332 # see 'man bash' for option pipefail
333 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
356 foreach my $p (keys %param) {
357 if ($p eq 'timeout') {
358 $timeout = $param{$p};
359 } elsif ($p eq 'umask') {
360 $old_umask = umask($param{$p});
361 } elsif ($p eq 'errmsg') {
362 $errmsg = $param{$p};
363 } elsif ($p eq 'input') {
365 } elsif ($p eq 'output') {
366 $output = $param{$p};
367 } elsif ($p eq 'outfunc') {
368 $outfunc = $param{$p};
369 } elsif ($p eq 'errfunc') {
370 $errfunc = $param{$p};
371 } elsif ($p eq 'logfunc') {
372 $logfunc = $param{$p};
373 } elsif ($p eq 'afterfork') {
374 $afterfork = $param{$p};
375 } elsif ($p eq 'noerr') {
378 die "got unknown parameter '$p' for run_command\n";
383 my $origerrfunc = $errfunc;
387 &$origerrfunc("$laststderr\n");
389 print STDERR
"$laststderr\n" if $laststderr;
396 my $reader = $output && $output =~ m/^>&/ ?
$output : IO
::File-
>new();
397 my $writer = $input && $input =~ m/^<&/ ?
$input : IO
::File-
>new();
398 my $error = IO
::File-
>new();
400 # try to avoid locale related issues/warnings
401 my $lang = $param{lang
} || 'C';
406 local $ENV{LC_ALL
} = $lang;
408 # suppress LVM warnings like: "File descriptor 3 left open";
409 local $ENV{LVM_SUPPRESS_FD_WARNINGS
} = "1";
411 $pid = open3
($writer, $reader, $error, @$cmd) || die $!;
413 # if we pipe fron STDIN, open3 closes STDIN, so we we
414 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
415 # as soon as we open a new file.
416 # to avoid that we open /dev/null
417 if (!ref($writer) && !defined(fileno(STDIN
))) {
419 open(STDIN
, "</dev/null");
426 if ($orig_pid != $$) {
434 local $SIG{ALRM
} = sub { die "got timeout\n"; } if $timeout;
435 $oldtimeout = alarm($timeout) if $timeout;
437 &$afterfork() if $afterfork;
440 print $writer $input if defined $input;
444 my $select = new IO
::Select
;
445 $select->add($reader) if ref($reader);
446 $select->add($error);
451 my $starttime = time();
453 while ($select->count) {
454 my @handles = $select->can_read(1);
456 foreach my $h (@handles) {
458 my $count = sysread ($h, $buf, 4096);
459 if (!defined ($count)) {
465 $select->remove ($h) if !$count;
467 if ($outfunc || $logfunc) {
470 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
472 &$outfunc($line) if $outfunc;
473 &$logfunc($line) if $logfunc;
486 } elsif ($h eq $error) {
487 if ($errfunc || $logfunc) {
490 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
492 &$errfunc($line) if $errfunc;
493 &$logfunc($line) if $logfunc;
510 &$outfunc($outlog) if $outfunc && $outlog;
511 &$logfunc($outlog) if $logfunc && $outlog;
513 &$errfunc($errlog) if $errfunc && $errlog;
514 &$logfunc($errlog) if $logfunc && $errlog;
519 die "failed to execute\n";
520 } elsif (my $sig = ($? & 127)) {
521 die "got signal $sig\n";
522 } elsif ($exitcode = ($? >> 8)) {
523 if (!($exitcode == 24 && ($cmdstr =~ m
|^(\S
+/)?rsync\s
|))) {
524 if ($errmsg && $laststderr) {
525 my $lerr = $laststderr;
529 die "exit code $exitcode\n";
540 if ($errmsg && $laststderr) {
541 &$errfunc(undef); # flush laststderr
544 umask ($old_umask) if defined($old_umask);
546 alarm($oldtimeout) if $oldtimeout;
549 if ($pid && ($err eq "got timeout\n")) {
552 die "command '$cmdstr' failed: $err";
556 $err =~ s/^usermod:\s*// if $cmdstr =~ m
|^(\S
+/)?usermod\s
|;
559 die "command '$cmdstr' failed: $err";
567 my $listtxt = shift || '';
569 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
571 $listtxt =~ s/[,;]/ /g;
572 $listtxt =~ s/^\s+//;
574 my @data = split (/\s+/, $listtxt);
582 return $txt if !defined($txt);
590 # simple uri templates like "/vms/{vmid}"
591 sub template_replace
{
592 my ($tmpl, $data) = @_;
594 return $tmpl if !$tmpl;
597 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
599 $res .= ($data->{$3} || '-') if $2;
605 my ($filename, $fh, $data) = @_;
609 my $res = print $fh $data;
611 die "write to '$filename' failed\n" if !$res;
617 'at' => 'ftp.at.debian.org',
618 'au' => 'ftp.au.debian.org',
619 'be' => 'ftp.be.debian.org',
620 'bg' => 'ftp.bg.debian.org',
621 'br' => 'ftp.br.debian.org',
622 'ca' => 'ftp.ca.debian.org',
623 'ch' => 'ftp.ch.debian.org',
624 'cl' => 'ftp.cl.debian.org',
625 'cz' => 'ftp.cz.debian.org',
626 'de' => 'ftp.de.debian.org',
627 'dk' => 'ftp.dk.debian.org',
628 'ee' => 'ftp.ee.debian.org',
629 'es' => 'ftp.es.debian.org',
630 'fi' => 'ftp.fi.debian.org',
631 'fr' => 'ftp.fr.debian.org',
632 'gr' => 'ftp.gr.debian.org',
633 'hk' => 'ftp.hk.debian.org',
634 'hr' => 'ftp.hr.debian.org',
635 'hu' => 'ftp.hu.debian.org',
636 'ie' => 'ftp.ie.debian.org',
637 'is' => 'ftp.is.debian.org',
638 'it' => 'ftp.it.debian.org',
639 'jp' => 'ftp.jp.debian.org',
640 'kr' => 'ftp.kr.debian.org',
641 'mx' => 'ftp.mx.debian.org',
642 'nl' => 'ftp.nl.debian.org',
643 'no' => 'ftp.no.debian.org',
644 'nz' => 'ftp.nz.debian.org',
645 'pl' => 'ftp.pl.debian.org',
646 'pt' => 'ftp.pt.debian.org',
647 'ro' => 'ftp.ro.debian.org',
648 'ru' => 'ftp.ru.debian.org',
649 'se' => 'ftp.se.debian.org',
650 'si' => 'ftp.si.debian.org',
651 'sk' => 'ftp.sk.debian.org',
652 'tr' => 'ftp.tr.debian.org',
653 'tw' => 'ftp.tw.debian.org',
654 'gb' => 'ftp.uk.debian.org',
655 'us' => 'ftp.us.debian.org',
660 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
661 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
662 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
663 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
664 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
665 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
666 #'et' => [], # Ethopia or Estonia ??
667 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
668 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
669 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
670 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
671 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
672 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
673 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
674 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
675 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
676 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
677 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
678 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
679 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
680 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
681 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
682 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
683 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
684 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
685 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
686 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
687 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
688 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
689 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
691 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
694 my $kvmkeymaparray = [];
695 foreach my $lc (sort keys %$keymaphash) {
696 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
704 return $kvmkeymaparray;
708 my ($param, $key) = @_;
710 my $res = $param->{$key};
711 delete $param->{$key};
716 # Note: we use this to wait until vncterm/spiceterm is ready
717 sub wait_for_vnc_port
{
718 my ($port, $timeout) = @_;
720 $timeout = 5 if !$timeout;
722 my $starttime = [gettimeofday
];
725 while (($elapsed = tv_interval
($starttime)) < $timeout) {
726 if (my $fh = IO
::File-
>new ("/proc/net/tcp", "r")) {
727 while (defined (my $line = <$fh>)) {
728 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
729 if ($port == hex($2)) {
737 $sleeptime += 100000 if $sleeptime < 1000000;
744 sub next_unused_port
{
745 my ($range_start, $range_end, $family) = @_;
747 # We use a file to register allocated ports.
748 # Those registrations expires after $expiretime.
749 # We use this to avoid race conditions between
750 # allocation and use of ports.
752 my $filename = "/var/tmp/pve-reserved-ports";
761 if (my $fh = IO
::File-
>new ($filename, "r")) {
762 while (my $line = <$fh>) {
763 if ($line =~ m/^(\d+)\s(\d+)$/) {
764 my ($port, $timestamp) = ($1, $2);
765 if (($timestamp + $expiretime) > $ctime) {
766 $ports->{$port} = $timestamp; # not expired
774 for (my $p = $range_start; $p < $range_end; $p++) {
775 next if $ports->{$p}; # reserved
777 my $sock = IO
::Socket
::IP-
>new(Listen
=> 5,
782 GetAddrInfoFlags
=> 0);
787 $ports->{$p} = $ctime;
793 foreach my $p (keys %$ports) {
794 $data .= "$p $ports->{$p}\n";
797 file_set_contents
($filename, $data);
802 my $p = lock_file
($filename, 10, $code);
805 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
810 sub next_migrate_port
{
812 return next_unused_port
(60000, 60050, $family);
817 return next_unused_port
(5900, 6000, $family);
820 sub next_spice_port
{
822 return next_unused_port
(61000, 61099, $family);
825 # NOTE: NFS syscall can't be interrupted, so alarm does
826 # not work to provide timeouts.
827 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
828 # So fork() before using Filesys::Df
830 my ($path, $timeout) = @_;
838 my $pipe = IO
::Pipe-
>new();
840 if (!defined($child)) {
841 warn "fork failed: $!\n";
848 my $df = Filesys
::Df
::df
($path, 1);
849 print {$pipe} "$df->{blocks}\n$df->{used}\n$df->{bavail}\n";
861 my $readvalues = sub {
862 $res->{total
} = int((<$pipe> =~ /^(\d*)$/)[0]);
863 $res->{used
} = int((<$pipe> =~ /^(\d*)$/)[0]);
864 $res->{avail
} = int((<$pipe> =~ /^(\d*)$/)[0]);
867 run_with_timeout
($timeout, $readvalues);
871 kill('KILL', $child);
877 # We use this to uniquely identify a process.
878 # An 'Unique Process ID' has the following format:
879 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
884 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
885 # more that 8 characters for pstart
886 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node
}, $d->{pid
},
887 $d->{pstart
}, $d->{starttime
}, $d->{type
}, $d->{id
},
892 my ($upid, $noerr) = @_;
897 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
898 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
899 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]+):$/) {
901 $res->{pid
} = hex($3);
902 $res->{pstart
} = hex($4);
903 $res->{starttime
} = hex($5);
908 my $subdir = substr($5, 7, 8);
909 $filename = "$pvetaskdir/$subdir/$upid";
912 return undef if $noerr;
913 die "unable to parse worker upid '$upid'\n";
916 return wantarray ?
($res, $filename) : $res;
922 my ($task, $filename) = upid_decode
($upid);
924 my $dirname = dirname
($filename);
927 my $wwwid = getpwnam('www-data') ||
928 die "getpwnam failed";
932 my $outfh = IO
::File-
>new ($filename, O_WRONLY
|O_CREAT
|O_EXCL
, $perm) ||
933 die "unable to create output file '$filename' - $!\n";
934 chown $wwwid, -1, $outfh;
939 sub upid_read_status
{
942 my ($task, $filename) = upid_decode
($upid);
943 my $fh = IO
::File-
>new($filename, "r");
944 return "unable to open file - $!" if !$fh;
946 sysseek($fh, -$maxlen, 2);
948 my $br = sysread($fh, $readbuf, $maxlen);
951 return "unable to extract last line"
952 if $readbuf !~ m/\n?(.+)$/;
954 if ($line =~ m/^TASK OK$/) {
956 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
959 return "unexpected status";
962 return "unable to read tail (got $br bytes)";
965 # useful functions to store comments in config files
969 # all control and hi-bit characters, and ':'
970 my $unsafe = "^\x20-\x39\x3b-\x7e";
971 return uri_escape
(Encode
::encode
("utf8", $text), $unsafe);
977 return Encode
::decode
("utf8", uri_unescape
($data));
980 sub decode_utf8_parameters
{
983 foreach my $p (qw(comment description firstname lastname)) {
984 $param->{$p} = decode
('utf8', $param->{$p}) if $param->{$p};
990 sub random_ether_addr
{
993 my ($seconds, $microseconds) = gettimeofday
;
995 my $rand = Digest
::SHA
::sha1
($$, rand(), $seconds, $microseconds);
997 # clear multicast, set local id
998 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
1000 my $addr = sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
1001 if (defined($prefix)) {
1002 $addr = uc($prefix) . substr($addr, length($prefix));
1010 return String
::ShellQuote
::shell_quote
($str);
1016 die "no arguments" if !$cmd;
1018 return $cmd if !ref($cmd);
1021 foreach my $arg (@$cmd) { push @qa, shellquote
($arg); }
1023 return join (' ', @qa);
1026 # split an shell argument string into an array,
1030 return $str ?
[ Text
::ParseWords
::shellwords
($str) ] : [];
1034 my ($filename, $start, $limit, $filter) = @_;
1039 my $fh = IO
::File-
>new($filename, "r");
1042 push @$lines, { n
=> $count, t
=> "unable to open file - $!"};
1043 return ($count, $lines);
1046 $start = 0 if !$start;
1047 $limit = 50 if !$limit;
1052 # duplicate code, so that we do not slow down normal path
1053 while (defined($line = <$fh>)) {
1054 next if $line !~ m/$filter/;
1055 next if $count++ < $start;
1056 next if $limit <= 0;
1058 push @$lines, { n
=> $count, t
=> $line};
1062 while (defined($line = <$fh>)) {
1063 next if $count++ < $start;
1064 next if $limit <= 0;
1066 push @$lines, { n
=> $count, t
=> $line};
1073 # HACK: ExtJS store.guaranteeRange() does not like empty array
1077 push @$lines, { n
=> $count, t
=> "no content"};
1080 return ($count, $lines);
1084 my ($start, $limit, $since, $until) = @_;
1089 $start = 0 if !$start;
1090 $limit = 50 if !$limit;
1095 return if $count++ < $start;
1096 return if $limit <= 0;
1097 push @$lines, { n
=> int($count), t
=> $line};
1101 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1103 push @$cmd, '--since', $since if $since;
1104 push @$cmd, '--until', $until if $until;
1105 run_command
($cmd, outfunc
=> $parser);
1107 # HACK: ExtJS store.guaranteeRange() does not like empty array
1111 push @$lines, { n
=> $count, t
=> "no content"};
1114 return ($count, $lines);
1117 sub dir_glob_regex
{
1118 my ($dir, $regex) = @_;
1120 my $dh = IO
::Dir-
>new ($dir);
1121 return wantarray ?
() : undef if !$dh;
1123 while (defined(my $tmp = $dh->read)) {
1124 if (my @res = $tmp =~ m/^($regex)$/) {
1126 return wantarray ?
@res : $tmp;
1131 return wantarray ?
() : undef;
1134 sub dir_glob_foreach
{
1135 my ($dir, $regex, $func) = @_;
1137 my $dh = IO
::Dir-
>new ($dir);
1139 while (defined(my $tmp = $dh->read)) {
1140 if (my @res = $tmp =~ m/^($regex)$/) {
1147 sub assert_if_modified
{
1148 my ($digest1, $digest2) = @_;
1150 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1151 die "detected modified configuration - file changed by other user? Try again.\n";
1155 # Digest for short strings
1156 # like FNV32a, but we only return 31 bits (positive numbers)
1160 my $hval = 0x811c9dc5;
1162 foreach my $c (unpack('C*', $string)) {
1170 $hval = $hval & 0xffffffff;
1172 return $hval & 0x7fffffff;
1175 sub fnv31a_hex
{ return sprintf("%X", fnv31a
(@_)); }
1177 sub unpack_sockaddr_in46
{
1179 my $family = Socket
::sockaddr_family
($sin);
1180 my ($port, $host) = ($family == AF_INET6 ? Socket
::unpack_sockaddr_in6
($sin)
1181 : Socket
::unpack_sockaddr_in
($sin));
1182 return ($family, $port, $host);
1185 sub getaddrinfo_all
{
1186 my ($hostname, @opts) = @_;
1187 my %hints = ( flags
=> AI_V4MAPPED
| AI_ALL
,
1189 my ($err, @res) = Socket
::getaddrinfo
($hostname, '0', \
%hints);
1190 die "failed to get address info for: $hostname: $err\n" if $err;
1194 sub get_host_address_family
{
1195 my ($hostname, $socktype) = @_;
1196 my @res = getaddrinfo_all
($hostname, socktype
=> $socktype);
1197 return $res[0]->{family
};
1200 # Parses any sane kind of host, or host+port pair:
1201 # The port is always optional and thus may be undef.
1202 sub parse_host_and_port
{
1204 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1205 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1206 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1208 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1215 return 0 == syscall(272, $flags);
1219 my ($fileno, $nstype) = @_;
1220 return 0 == syscall(308, $fileno, $nstype);
1225 return 0 == syscall(306, $fileno);
1228 sub sync_mountpoint
{
1230 sysopen my $fd, $path, O_PATH
or die "failed to open $path: $!\n";
1231 my $result = syncfs
(fileno($fd));
1236 # support sending multi-part mail messages with a text and or a HTML part
1237 # mailto may be a single email string or an array of receivers
1239 my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_;
1240 my $mail_re = qr/[^-a-zA-Z0-9+._@]/;
1242 $mailto = [ $mailto ] if !ref($mailto);
1244 foreach (@$mailto) {
1245 die "illegal character in mailto address\n"
1246 if ($_ =~ $mail_re);
1249 my $rcvrtxt = join (', ', @$mailto);
1251 $mailfrom = $mailfrom || "root";
1252 die "illegal character in mailfrom address\n"
1253 if $mailfrom =~ $mail_re;
1255 $author = $author || 'Proxmox VE';
1257 open (MAIL
, "|-", "sendmail", "-B", "8BITMIME", "-f", $mailfrom, @$mailto) ||
1258 die "unable to open 'sendmail' - $!";
1260 # multipart spec see https://www.ietf.org/rfc/rfc1521.txt
1261 my $boundary = "----_=_NextPart_001_".int(time).$$;
1263 print MAIL
"Content-Type: multipart/alternative;\n";
1264 print MAIL
"\tboundary=\"$boundary\"\n";
1265 print MAIL "MIME-Version
: 1.0\n";
1267 print MAIL "FROM
: $author <$mailfrom>\n";
1268 print MAIL "TO
: $rcvrtxt\n";
1269 print MAIL "SUBJECT
: $subject\n";
1271 print MAIL "This
is a multi-part message
in MIME format
.\n\n";
1272 print MAIL "--$boundary\n";
1274 if (defined($text)) {
1275 print MAIL "Content-Type
: text
/plain
;\n";
1276 print MAIL "\tcharset
=\"UTF8
\"\n";
1277 print MAIL "Content-Transfer-Encoding
: 8bit
\n";
1280 # avoid 'remove extra line breaks' issue (MS Outlook)
1282 $text =~ s/^/$fill/gm;
1286 print MAIL "\n--$boundary\n";
1289 if (defined($html)) {
1290 print MAIL "Content-Type
: text
/html
;\n";
1291 print MAIL "\tcharset
=\"UTF8
\"\n";
1292 print MAIL "Content-Transfer-Encoding
: 8bit
\n";
1297 print MAIL "\n--$boundary--\n";
1304 my ($perm, %opts) = @_;
1306 # default permissions are stricter than with file_set_contents
1307 $perm = 0600 if !defined($perm);
1309 my $dir = $opts{dir} // '/run';
1310 my $mode = $opts{mode} // O_RDWR;
1311 $mode |= O_EXCL if !$opts{allow_links};
1313 my $fh = IO::File->new($dir, $mode | O_TMPFILE, $perm);
1314 if (!$fh && $! == EOPNOTSUPP) {
1315 $dir = '/tmp' if !defined($opts{dir});
1316 $dir .= "/.tmpfile
.$$";
1317 $fh = IO::File->new($dir, $mode | O_CREAT | O_EXCL, $perm);
1318 unlink($dir) if $fh;
1320 die "failed to create tempfile
: $!\n" if !$fh;
1324 sub tempfile_contents {
1325 my ($data, $perm, %opts) = @_;
1327 my $fh = tempfile($perm, %opts);
1329 die "unable to
write to tempfile
: $!\n" if !print {$fh} $data;
1330 die "unable to flush to tempfile
: $!\n" if !defined($fh->flush());
1337 return ("/proc/$$/fd/".$fh->fileno, $fh);
1340 sub validate_ssh_public_keys {
1342 my @lines = split(/\n/, $raw);
1344 foreach my $line (@lines) {
1345 next if $line =~ m/^\s*$/;
1347 my ($filename, $handle) = tempfile_contents($line);
1348 run_command(["ssh-keygen
", "-l
", "-f
", $filename],
1349 outfunc => sub {}, errfunc => sub {});
1351 die "SSH public key validation error
\n" if $@;
1356 my ($dirfd, $pathname, $flags, $mode) = @_;
1357 my $fd = syscall(257, $dirfd, $pathname, $flags, $mode//0);
1358 return undef if $fd < 0;
1359 # sysopen() doesn't deal with numeric file descriptors apparently
1360 # so we need to convert to a mode string for IO::Handle->new_from_fd
1361 my $flagstr = ($flags & O_RDWR) ? 'rw' : ($flags & O_WRONLY) ? 'w' : 'r';
1362 my $handle = IO::Handle->new_from_fd($fd, $flagstr);
1363 return $handle if $handle;
1364 my $err = $!; # save error before closing the raw fd
1365 syscall(3, $fd); # close
1371 my ($dirfd, $name, $mode) = @_;
1372 return syscall(258, $dirfd, $name, $mode) == 0;
1375 # NOTE: This calls the dbus main loop and must not be used when another dbus
1376 # main loop is being used as we need to wait for the JobRemoved signal.
1377 # Polling the job status instead doesn't work because this doesn't give us the
1378 # distinction between success and failure.
1380 # Note that the description is mandatory for security reasons.
1381 sub enter_systemd_scope {
1382 my ($unit, $description, %extra) = @_;
1383 die "missing description
\n" if !defined($description);
1385 my $timeout = delete $extra{timeout};
1388 my $properties = [ [PIDs => [dbus_uint32($$)]] ];
1390 foreach my $key (keys %extra) {
1391 if ($key eq 'Slice' || $key eq 'KillMode') {
1392 push @$properties, [$key, $extra{$key}];
1393 } elsif ($key eq 'CPUShares') {
1394 push @$properties, [$key, dbus_uint64($extra{$key})];
1395 } elsif ($key eq 'CPUQuota') {
1396 push @$properties, ['CPUQuotaPerSecUSec',
1397 dbus_uint64($extra{$key} * 10000)];
1399 die "Don
't know how to encode $key for systemd scope\n";
1406 my $bus = Net::DBus->system();
1407 my $reactor = Net::DBus::Reactor->main();
1409 my $service = $bus->get_service('org
.freedesktop
.systemd1
');
1410 my $if = $service->get_object('/org/freedesktop
/systemd1
', 'org
.freedesktop
.systemd1
.Manager
');
1411 # Connect to the JobRemoved signal since we want to wait for it to finish
1415 my ($no_shutdown) = @_;
1416 $if->disconnect_from_signal('JobRemoved
', $sigid) if defined($if);
1419 $reactor->remove_timeout($timer) if defined($timer);
1421 return if $no_shutdown;
1422 $reactor->shutdown();
1425 $sigid = $if->connect_to_signal('JobRemoved
', sub {
1426 my ($id, $removed_job, $signaled_unit, $result) = @_;
1427 return if $signaled_unit ne $unit || $removed_job ne $job;
1429 die "systemd job failed\n" if $result ne 'done
';
1433 my $on_timeout = sub {
1435 die "systemd job timed out\n";
1438 $timer = $reactor->add_timeout($timeout * 1000, Net::DBus::Callback->new(method => $on_timeout))
1439 if defined($timeout);
1440 $job = $if->StartTransientUnit($unit, 'fail
', $properties, []);
1443 die "systemd job never completed\n" if !$done;