]> git.proxmox.com Git - pve-common.git/blob - src/PVE/Tools.pm
use more reliable checks in wait_for_vnc_port
[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 Text::ParseWords;
24 use String::ShellQuote;
25 use Time::HiRes qw(usleep gettimeofday tv_interval alarm);
26 use Net::DBus qw(dbus_uint32 dbus_uint64);
27 use Net::DBus::Callback;
28 use Net::DBus::Reactor;
29 use Scalar::Util 'weaken';
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 file_copy
52 O_PATH
53 O_TMPFILE
54 );
55
56 my $pvelogdir = "/var/log/pve";
57 my $pvetaskdir = "$pvelogdir/tasks";
58
59 mkdir $pvelogdir;
60 mkdir $pvetaskdir;
61
62 my $IPV4OCTET = "(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])";
63 our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)";
64 my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})";
65 my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))";
66
67 our $IPV6RE = "(?:" .
68 "(?:(?:" . "(?:$IPV6H16:){6})$IPV6LS32)|" .
69 "(?:(?:" . "::(?:$IPV6H16:){5})$IPV6LS32)|" .
70 "(?:(?:(?:" . "$IPV6H16)?::(?:$IPV6H16:){4})$IPV6LS32)|" .
71 "(?:(?:(?:(?:$IPV6H16:){0,1}$IPV6H16)?::(?:$IPV6H16:){3})$IPV6LS32)|" .
72 "(?:(?:(?:(?:$IPV6H16:){0,2}$IPV6H16)?::(?:$IPV6H16:){2})$IPV6LS32)|" .
73 "(?:(?:(?:(?:$IPV6H16:){0,3}$IPV6H16)?::(?:$IPV6H16:){1})$IPV6LS32)|" .
74 "(?:(?:(?:(?:$IPV6H16:){0,4}$IPV6H16)?::" . ")$IPV6LS32)|" .
75 "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" . ")$IPV6H16)|" .
76 "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" . ")))";
77
78 our $IPRE = "(?:$IPV4RE|$IPV6RE)";
79
80 use constant {CLONE_NEWNS => 0x00020000,
81 CLONE_NEWUTS => 0x04000000,
82 CLONE_NEWIPC => 0x08000000,
83 CLONE_NEWUSER => 0x10000000,
84 CLONE_NEWPID => 0x20000000,
85 CLONE_NEWNET => 0x40000000};
86
87 use constant {O_PATH => 0x00200000,
88 O_TMPFILE => 0x00410000}; # This includes O_DIRECTORY
89
90 sub run_with_timeout {
91 my ($timeout, $code, @param) = @_;
92
93 die "got timeout\n" if $timeout <= 0;
94
95 my $prev_alarm = alarm 0; # suspend outer alarm early
96
97 my $sigcount = 0;
98
99 my $res;
100
101 eval {
102 local $SIG{ALRM} = sub { $sigcount++; die "got timeout\n"; };
103 local $SIG{PIPE} = sub { $sigcount++; die "broken pipe\n" };
104 local $SIG{__DIE__}; # see SA bug 4631
105
106 alarm($timeout);
107
108 eval { $res = &$code(@param); };
109
110 alarm(0); # avoid race conditions
111
112 die $@ if $@;
113 };
114
115 my $err = $@;
116
117 alarm $prev_alarm;
118
119 # this shouldn't happen anymore?
120 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
121
122 die $err if $err;
123
124 return $res;
125 }
126
127 # flock: we use one file handle per process, so lock file
128 # can be nested multiple times and succeeds for the same process.
129 #
130 # Since this is the only way we lock now and we don't have the old
131 # 'lock(); code(); unlock();' pattern anymore we do not actually need to
132 # count how deep we're nesting. Therefore this hash now stores a weak reference
133 # to a boolean telling us whether we already have a lock.
134
135 my $lock_handles = {};
136
137 sub lock_file_full {
138 my ($filename, $timeout, $shared, $code, @param) = @_;
139
140 $timeout = 10 if !$timeout;
141
142 my $mode = $shared ? LOCK_SH : LOCK_EX;
143
144 my $lockhash = ($lock_handles->{$$} //= {});
145
146 # Returns a locked file handle.
147 my $get_locked_file = sub {
148 my $fh = IO::File->new(">>$filename")
149 or die "can't open file - $!\n";
150
151 if (!flock($fh, $mode|LOCK_NB)) {
152 print STDERR "trying to acquire lock...";
153 my $success;
154 while(1) {
155 $success = flock($fh, $mode);
156 # try again on EINTR (see bug #273)
157 if ($success || ($! != EINTR)) {
158 last;
159 }
160 }
161 if (!$success) {
162 print STDERR " failed\n";
163 die "can't acquire lock '$filename' - $!\n";
164 }
165 print STDERR " OK\n";
166 }
167
168 return $fh;
169 };
170
171 my $res;
172 my $checkptr = $lockhash->{$filename};
173 my $check = 0; # This must not go out of scope before running the code.
174 my $local_fh; # This must stay local
175 if (!$checkptr || !$$checkptr) {
176 # We cannot create a weak reference in a single atomic step, so we first
177 # create a false-value, then create a reference to it, then weaken it,
178 # and after successfully locking the file we change the boolean value.
179 #
180 # The reason for this is that if an outer SIGALRM throws an exception
181 # between creating the reference and weakening it, a subsequent call to
182 # lock_file_full() will see a leftover full reference to a valid
183 # variable. This variable must be 0 in order for said call to attempt to
184 # lock the file anew.
185 #
186 # An externally triggered exception elsewhere in the code will cause the
187 # weak reference to become 'undef', and since the file handle is only
188 # stored in the local scope in $local_fh, the file will be closed by
189 # perl's cleanup routines as well.
190 #
191 # This still assumes that an IO::File handle can properly deal with such
192 # exceptions thrown during its own destruction, but that's up to perls
193 # guts now.
194 $lockhash->{$filename} = \$check;
195 weaken $lockhash->{$filename};
196 $local_fh = eval { run_with_timeout($timeout, $get_locked_file) };
197 if ($@) {
198 $@ = "can't lock file '$filename' - $@";
199 return undef;
200 }
201 $check = 1;
202 }
203 $res = eval { &$code(@param); };
204 return undef if $@;
205 return $res;
206 }
207
208
209 sub lock_file {
210 my ($filename, $timeout, $code, @param) = @_;
211
212 return lock_file_full($filename, $timeout, 0, $code, @param);
213 }
214
215 sub file_set_contents {
216 my ($filename, $data, $perm) = @_;
217
218 $perm = 0644 if !defined($perm);
219
220 my $tmpname = "$filename.tmp.$$";
221
222 eval {
223 my ($fh, $tries) = (undef, 0);
224 while (!$fh && $tries++ < 3) {
225 $fh = IO::File->new($tmpname, O_WRONLY|O_CREAT|O_EXCL, $perm);
226 if (!$fh && $! == EEXIST) {
227 unlink($tmpname) or die "unable to delete old temp file: $!\n";
228 }
229 }
230 die "unable to open file '$tmpname' - $!\n" if !$fh;
231 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
232 die "closing file '$tmpname' failed - $!\n" unless close $fh;
233 };
234 my $err = $@;
235
236 if ($err) {
237 unlink $tmpname;
238 die $err;
239 }
240
241 if (!rename($tmpname, $filename)) {
242 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
243 unlink $tmpname;
244 die $msg;
245 }
246 }
247
248 sub file_get_contents {
249 my ($filename, $max) = @_;
250
251 my $fh = IO::File->new($filename, "r") ||
252 die "can't open '$filename' - $!\n";
253
254 my $content = safe_read_from($fh, $max, 0, $filename);
255
256 close $fh;
257
258 return $content;
259 }
260
261 sub file_copy {
262 my ($filename, $dst, $max, $perm) = @_;
263
264 file_set_contents ($dst, file_get_contents($filename, $max), $perm);
265 }
266
267 sub file_read_firstline {
268 my ($filename) = @_;
269
270 my $fh = IO::File->new ($filename, "r");
271 return undef if !$fh;
272 my $res = <$fh>;
273 chomp $res if $res;
274 $fh->close;
275 return $res;
276 }
277
278 sub safe_read_from {
279 my ($fh, $max, $oneline, $filename) = @_;
280
281 $max = 32768 if !$max;
282
283 my $subject = defined($filename) ? "file '$filename'" : 'input';
284
285 my $br = 0;
286 my $input = '';
287 my $count;
288 while ($count = sysread($fh, $input, 8192, $br)) {
289 $br += $count;
290 die "$subject too long - aborting\n" if $br > $max;
291 if ($oneline && $input =~ m/^(.*)\n/) {
292 $input = $1;
293 last;
294 }
295 }
296 die "unable to read $subject - $!\n" if !defined($count);
297
298 return $input;
299 }
300
301 # The $cmd parameter can be:
302 # -) a string
303 # This is generally executed by passing it to the shell with the -c option.
304 # However, it can be executed in one of two ways, depending on whether
305 # there's a pipe involved:
306 # *) with pipe: passed explicitly to bash -c, prefixed with:
307 # set -o pipefail &&
308 # *) without a pipe: passed to perl's open3 which uses 'sh -c'
309 # (Note that this may result in two different syntax requirements!)
310 # FIXME?
311 # -) an array of arguments (strings)
312 # Will be executed without interference from a shell. (Parameters are passed
313 # as is, no escape sequences of strings will be touched.)
314 # -) an array of arrays
315 # Each array represents a command, and each command's output is piped into
316 # the following command's standard input.
317 # For this a shell command string is created with pipe symbols between each
318 # command.
319 # Each command is a list of strings meant to end up in the final command
320 # unchanged. In order to achieve this, every argument is shell-quoted.
321 # Quoting can be disabled for a particular argument by turning it into a
322 # reference, this allows inserting arbitrary shell options.
323 # For instance: the $cmd [ [ 'echo', 'hello', \'>/dev/null' ] ] will not
324 # produce any output, while the $cmd [ [ 'echo', 'hello', '>/dev/null' ] ]
325 # will literally print: hello >/dev/null
326 sub run_command {
327 my ($cmd, %param) = @_;
328
329 my $old_umask;
330 my $cmdstr;
331
332 if (my $ref = ref($cmd)) {
333 if (ref($cmd->[0])) {
334 $cmdstr = 'set -o pipefail && ';
335 my $pipe = '';
336 foreach my $command (@$cmd) {
337 # concatenate quoted parameters
338 # strings which are passed by reference are NOT shell quoted
339 $cmdstr .= $pipe . join(' ', map { ref($_) ? $$_ : shellquote($_) } @$command);
340 $pipe = ' | ';
341 }
342 $cmd = [ '/bin/bash', '-c', "$cmdstr" ];
343 } else {
344 $cmdstr = cmd2string($cmd);
345 }
346 } else {
347 $cmdstr = $cmd;
348 if ($cmd =~ m/\|/) {
349 # see 'man bash' for option pipefail
350 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
351 } else {
352 $cmd = [ $cmd ];
353 }
354 }
355
356 my $errmsg;
357 my $laststderr;
358 my $timeout;
359 my $oldtimeout;
360 my $pid;
361 my $exitcode = -1;
362
363 my $outfunc;
364 my $errfunc;
365 my $logfunc;
366 my $input;
367 my $output;
368 my $afterfork;
369 my $noerr;
370 my $keeplocale;
371
372 eval {
373
374 foreach my $p (keys %param) {
375 if ($p eq 'timeout') {
376 $timeout = $param{$p};
377 } elsif ($p eq 'umask') {
378 $old_umask = umask($param{$p});
379 } elsif ($p eq 'errmsg') {
380 $errmsg = $param{$p};
381 } elsif ($p eq 'input') {
382 $input = $param{$p};
383 } elsif ($p eq 'output') {
384 $output = $param{$p};
385 } elsif ($p eq 'outfunc') {
386 $outfunc = $param{$p};
387 } elsif ($p eq 'errfunc') {
388 $errfunc = $param{$p};
389 } elsif ($p eq 'logfunc') {
390 $logfunc = $param{$p};
391 } elsif ($p eq 'afterfork') {
392 $afterfork = $param{$p};
393 } elsif ($p eq 'noerr') {
394 $noerr = $param{$p};
395 } elsif ($p eq 'keeplocale') {
396 $keeplocale = $param{$p};
397 } else {
398 die "got unknown parameter '$p' for run_command\n";
399 }
400 }
401
402 if ($errmsg) {
403 my $origerrfunc = $errfunc;
404 $errfunc = sub {
405 if ($laststderr) {
406 if ($origerrfunc) {
407 &$origerrfunc("$laststderr\n");
408 } else {
409 print STDERR "$laststderr\n" if $laststderr;
410 }
411 }
412 $laststderr = shift;
413 };
414 }
415
416 my $reader = $output && $output =~ m/^>&/ ? $output : IO::File->new();
417 my $writer = $input && $input =~ m/^<&/ ? $input : IO::File->new();
418 my $error = IO::File->new();
419
420 my $orig_pid = $$;
421
422 eval {
423 local $ENV{LC_ALL} = 'C' if !$keeplocale;
424
425 # suppress LVM warnings like: "File descriptor 3 left open";
426 local $ENV{LVM_SUPPRESS_FD_WARNINGS} = "1";
427
428 $pid = open3($writer, $reader, $error, @$cmd) || die $!;
429
430 # if we pipe fron STDIN, open3 closes STDIN, so we we
431 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
432 # as soon as we open a new file.
433 # to avoid that we open /dev/null
434 if (!ref($writer) && !defined(fileno(STDIN))) {
435 POSIX::close(0);
436 open(STDIN, "</dev/null");
437 }
438 };
439
440 my $err = $@;
441
442 # catch exec errors
443 if ($orig_pid != $$) {
444 warn "ERROR: $err";
445 POSIX::_exit (1);
446 kill ('KILL', $$);
447 }
448
449 die $err if $err;
450
451 local $SIG{ALRM} = sub { die "got timeout\n"; } if $timeout;
452 $oldtimeout = alarm($timeout) if $timeout;
453
454 &$afterfork() if $afterfork;
455
456 if (ref($writer)) {
457 print $writer $input if defined $input;
458 close $writer;
459 }
460
461 my $select = new IO::Select;
462 $select->add($reader) if ref($reader);
463 $select->add($error);
464
465 my $outlog = '';
466 my $errlog = '';
467
468 my $starttime = time();
469
470 while ($select->count) {
471 my @handles = $select->can_read(1);
472
473 foreach my $h (@handles) {
474 my $buf = '';
475 my $count = sysread ($h, $buf, 4096);
476 if (!defined ($count)) {
477 my $err = $!;
478 kill (9, $pid);
479 waitpid ($pid, 0);
480 die $err;
481 }
482 $select->remove ($h) if !$count;
483 if ($h eq $reader) {
484 if ($outfunc || $logfunc) {
485 eval {
486 $outlog .= $buf;
487 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
488 my $line = $1;
489 &$outfunc($line) if $outfunc;
490 &$logfunc($line) if $logfunc;
491 }
492 };
493 my $err = $@;
494 if ($err) {
495 kill (9, $pid);
496 waitpid ($pid, 0);
497 die $err;
498 }
499 } else {
500 print $buf;
501 *STDOUT->flush();
502 }
503 } elsif ($h eq $error) {
504 if ($errfunc || $logfunc) {
505 eval {
506 $errlog .= $buf;
507 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
508 my $line = $1;
509 &$errfunc($line) if $errfunc;
510 &$logfunc($line) if $logfunc;
511 }
512 };
513 my $err = $@;
514 if ($err) {
515 kill (9, $pid);
516 waitpid ($pid, 0);
517 die $err;
518 }
519 } else {
520 print STDERR $buf;
521 *STDERR->flush();
522 }
523 }
524 }
525 }
526
527 &$outfunc($outlog) if $outfunc && $outlog;
528 &$logfunc($outlog) if $logfunc && $outlog;
529
530 &$errfunc($errlog) if $errfunc && $errlog;
531 &$logfunc($errlog) if $logfunc && $errlog;
532
533 waitpid ($pid, 0);
534
535 if ($? == -1) {
536 die "failed to execute\n";
537 } elsif (my $sig = ($? & 127)) {
538 die "got signal $sig\n";
539 } elsif ($exitcode = ($? >> 8)) {
540 if (!($exitcode == 24 && ($cmdstr =~ m|^(\S+/)?rsync\s|))) {
541 if ($errmsg && $laststderr) {
542 my $lerr = $laststderr;
543 $laststderr = undef;
544 die "$lerr\n";
545 }
546 die "exit code $exitcode\n";
547 }
548 }
549
550 alarm(0);
551 };
552
553 my $err = $@;
554
555 alarm(0);
556
557 if ($errmsg && $laststderr) {
558 &$errfunc(undef); # flush laststderr
559 }
560
561 umask ($old_umask) if defined($old_umask);
562
563 alarm($oldtimeout) if $oldtimeout;
564
565 if ($err) {
566 if ($pid && ($err eq "got timeout\n")) {
567 kill (9, $pid);
568 waitpid ($pid, 0);
569 die "command '$cmdstr' failed: $err";
570 }
571
572 if ($errmsg) {
573 $err =~ s/^usermod:\s*// if $cmdstr =~ m|^(\S+/)?usermod\s|;
574 die "$errmsg: $err";
575 } elsif(!$noerr) {
576 die "command '$cmdstr' failed: $err";
577 }
578 }
579
580 return $exitcode;
581 }
582
583 sub split_list {
584 my $listtxt = shift || '';
585
586 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
587
588 $listtxt =~ s/[,;]/ /g;
589 $listtxt =~ s/^\s+//;
590
591 my @data = split (/\s+/, $listtxt);
592
593 return @data;
594 }
595
596 sub trim {
597 my $txt = shift;
598
599 return $txt if !defined($txt);
600
601 $txt =~ s/^\s+//;
602 $txt =~ s/\s+$//;
603
604 return $txt;
605 }
606
607 # simple uri templates like "/vms/{vmid}"
608 sub template_replace {
609 my ($tmpl, $data) = @_;
610
611 return $tmpl if !$tmpl;
612
613 my $res = '';
614 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
615 $res .= $1 if $1;
616 $res .= ($data->{$3} || '-') if $2;
617 }
618 return $res;
619 }
620
621 sub safe_print {
622 my ($filename, $fh, $data) = @_;
623
624 return if !$data;
625
626 my $res = print $fh $data;
627
628 die "write to '$filename' failed\n" if !$res;
629 }
630
631 sub debmirrors {
632
633 return {
634 'at' => 'ftp.at.debian.org',
635 'au' => 'ftp.au.debian.org',
636 'be' => 'ftp.be.debian.org',
637 'bg' => 'ftp.bg.debian.org',
638 'br' => 'ftp.br.debian.org',
639 'ca' => 'ftp.ca.debian.org',
640 'ch' => 'ftp.ch.debian.org',
641 'cl' => 'ftp.cl.debian.org',
642 'cz' => 'ftp.cz.debian.org',
643 'de' => 'ftp.de.debian.org',
644 'dk' => 'ftp.dk.debian.org',
645 'ee' => 'ftp.ee.debian.org',
646 'es' => 'ftp.es.debian.org',
647 'fi' => 'ftp.fi.debian.org',
648 'fr' => 'ftp.fr.debian.org',
649 'gr' => 'ftp.gr.debian.org',
650 'hk' => 'ftp.hk.debian.org',
651 'hr' => 'ftp.hr.debian.org',
652 'hu' => 'ftp.hu.debian.org',
653 'ie' => 'ftp.ie.debian.org',
654 'is' => 'ftp.is.debian.org',
655 'it' => 'ftp.it.debian.org',
656 'jp' => 'ftp.jp.debian.org',
657 'kr' => 'ftp.kr.debian.org',
658 'mx' => 'ftp.mx.debian.org',
659 'nl' => 'ftp.nl.debian.org',
660 'no' => 'ftp.no.debian.org',
661 'nz' => 'ftp.nz.debian.org',
662 'pl' => 'ftp.pl.debian.org',
663 'pt' => 'ftp.pt.debian.org',
664 'ro' => 'ftp.ro.debian.org',
665 'ru' => 'ftp.ru.debian.org',
666 'se' => 'ftp.se.debian.org',
667 'si' => 'ftp.si.debian.org',
668 'sk' => 'ftp.sk.debian.org',
669 'tr' => 'ftp.tr.debian.org',
670 'tw' => 'ftp.tw.debian.org',
671 'gb' => 'ftp.uk.debian.org',
672 'us' => 'ftp.us.debian.org',
673 };
674 }
675
676 my $keymaphash = {
677 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
678 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
679 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
680 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
681 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
682 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
683 #'et' => [], # Ethopia or Estonia ??
684 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
685 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
686 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
687 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
688 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
689 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
690 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
691 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
692 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
693 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
694 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
695 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
696 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
697 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
698 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
699 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
700 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
701 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
702 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
703 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
704 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
705 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
706 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
707 #'th' => [],
708 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
709 };
710
711 my $kvmkeymaparray = [];
712 foreach my $lc (sort keys %$keymaphash) {
713 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
714 }
715
716 sub kvmkeymaps {
717 return $keymaphash;
718 }
719
720 sub kvmkeymaplist {
721 return $kvmkeymaparray;
722 }
723
724 sub extract_param {
725 my ($param, $key) = @_;
726
727 my $res = $param->{$key};
728 delete $param->{$key};
729
730 return $res;
731 }
732
733 # Note: we use this to wait until vncterm/spiceterm is ready
734 sub wait_for_vnc_port {
735 my ($port, $timeout) = @_;
736
737 $timeout = 5 if !$timeout;
738 my $sleeptime = 0;
739 my $starttime = [gettimeofday];
740 my $elapsed;
741
742 my $found;
743 while (($elapsed = tv_interval($starttime)) < $timeout) {
744 # -Htln = don't print header, tcp, listening sockets only, numeric ports
745 run_command(['/bin/ss', '-Htln', "sport = :$port"], outfunc => sub {
746 my $line = shift;
747 if ($line =~ m/^LISTEN\s+\d+\s+\d+\s+\S+:(\d+)\s/) {
748 $found = 1 if ($port == $1);
749 }
750 });
751 return 1 if $found;
752 $sleeptime += 100000 if $sleeptime < 1000000;
753 usleep($sleeptime);
754 }
755
756 return undef;
757 }
758
759 sub next_unused_port {
760 my ($range_start, $range_end, $family, $address) = @_;
761
762 # We use a file to register allocated ports.
763 # Those registrations expires after $expiretime.
764 # We use this to avoid race conditions between
765 # allocation and use of ports.
766
767 my $filename = "/var/tmp/pve-reserved-ports";
768
769 my $code = sub {
770
771 my $expiretime = 5;
772 my $ctime = time();
773
774 my $ports = {};
775
776 if (my $fh = IO::File->new ($filename, "r")) {
777 while (my $line = <$fh>) {
778 if ($line =~ m/^(\d+)\s(\d+)$/) {
779 my ($port, $timestamp) = ($1, $2);
780 if (($timestamp + $expiretime) > $ctime) {
781 $ports->{$port} = $timestamp; # not expired
782 }
783 }
784 }
785 }
786
787 my $newport;
788 my %sockargs = (Listen => 5,
789 ReuseAddr => 1,
790 Family => $family,
791 Proto => IPPROTO_TCP,
792 GetAddrInfoFlags => 0);
793 $sockargs{LocalAddr} = $address if defined($address);
794
795 for (my $p = $range_start; $p < $range_end; $p++) {
796 next if $ports->{$p}; # reserved
797
798 $sockargs{LocalPort} = $p;
799 my $sock = IO::Socket::IP->new(%sockargs);
800
801 if ($sock) {
802 close($sock);
803 $newport = $p;
804 $ports->{$p} = $ctime;
805 last;
806 }
807 }
808
809 my $data = "";
810 foreach my $p (keys %$ports) {
811 $data .= "$p $ports->{$p}\n";
812 }
813
814 file_set_contents($filename, $data);
815
816 return $newport;
817 };
818
819 my $p = lock_file('/var/lock/pve-ports.lck', 10, $code);
820 die $@ if $@;
821
822 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
823
824 return $p;
825 }
826
827 sub next_migrate_port {
828 my ($family, $address) = @_;
829 return next_unused_port(60000, 60050, $family, $address);
830 }
831
832 sub next_vnc_port {
833 my ($family, $address) = @_;
834 return next_unused_port(5900, 6000, $family, $address);
835 }
836
837 sub next_spice_port {
838 my ($family, $address) = @_;
839 return next_unused_port(61000, 61099, $family, $address);
840 }
841
842 # NOTE: NFS syscall can't be interrupted, so alarm does
843 # not work to provide timeouts.
844 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
845 # So fork() before using Filesys::Df
846 sub df {
847 my ($path, $timeout) = @_;
848
849 my $res = {
850 total => 0,
851 used => 0,
852 avail => 0,
853 };
854
855 my $pipe = IO::Pipe->new();
856 my $child = fork();
857 if (!defined($child)) {
858 warn "fork failed: $!\n";
859 return $res;
860 }
861
862 if (!$child) {
863 $pipe->writer();
864 eval {
865 my $df = Filesys::Df::df($path, 1);
866 print {$pipe} "$df->{blocks}\n$df->{used}\n$df->{bavail}\n";
867 $pipe->close();
868 };
869 if (my $err = $@) {
870 warn $err;
871 POSIX::_exit(1);
872 }
873 POSIX::_exit(0);
874 }
875
876 $pipe->reader();
877
878 my $readvalues = sub {
879 $res->{total} = int((<$pipe> =~ /^(\d*)$/)[0]);
880 $res->{used} = int((<$pipe> =~ /^(\d*)$/)[0]);
881 $res->{avail} = int((<$pipe> =~ /^(\d*)$/)[0]);
882 };
883 eval {
884 run_with_timeout($timeout, $readvalues);
885 };
886 warn $@ if $@;
887 $pipe->close();
888 kill('KILL', $child);
889 waitpid($child, 0);
890 return $res;
891 }
892
893 # UPID helper
894 # We use this to uniquely identify a process.
895 # An 'Unique Process ID' has the following format:
896 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
897
898 sub upid_encode {
899 my $d = shift;
900
901 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
902 # more that 8 characters for pstart
903 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid},
904 $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id},
905 $d->{user});
906 }
907
908 sub upid_decode {
909 my ($upid, $noerr) = @_;
910
911 my $res;
912 my $filename;
913
914 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
915 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
916 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]+):$/) {
917 $res->{node} = $1;
918 $res->{pid} = hex($3);
919 $res->{pstart} = hex($4);
920 $res->{starttime} = hex($5);
921 $res->{type} = $6;
922 $res->{id} = $7;
923 $res->{user} = $8;
924
925 my $subdir = substr($5, 7, 8);
926 $filename = "$pvetaskdir/$subdir/$upid";
927
928 } else {
929 return undef if $noerr;
930 die "unable to parse worker upid '$upid'\n";
931 }
932
933 return wantarray ? ($res, $filename) : $res;
934 }
935
936 sub upid_open {
937 my ($upid) = @_;
938
939 my ($task, $filename) = upid_decode($upid);
940
941 my $dirname = dirname($filename);
942 make_path($dirname);
943
944 my $wwwid = getpwnam('www-data') ||
945 die "getpwnam failed";
946
947 my $perm = 0640;
948
949 my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) ||
950 die "unable to create output file '$filename' - $!\n";
951 chown $wwwid, -1, $outfh;
952
953 return $outfh;
954 };
955
956 sub upid_read_status {
957 my ($upid) = @_;
958
959 my ($task, $filename) = upid_decode($upid);
960 my $fh = IO::File->new($filename, "r");
961 return "unable to open file - $!" if !$fh;
962 my $maxlen = 4096;
963 sysseek($fh, -$maxlen, 2);
964 my $readbuf = '';
965 my $br = sysread($fh, $readbuf, $maxlen);
966 close($fh);
967 if ($br) {
968 return "unable to extract last line"
969 if $readbuf !~ m/\n?(.+)$/;
970 my $line = $1;
971 if ($line =~ m/^TASK OK$/) {
972 return 'OK';
973 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
974 return $1;
975 } else {
976 return "unexpected status";
977 }
978 }
979 return "unable to read tail (got $br bytes)";
980 }
981
982 # useful functions to store comments in config files
983 sub encode_text {
984 my ($text) = @_;
985
986 # all control and hi-bit characters, and ':'
987 my $unsafe = "^\x20-\x39\x3b-\x7e";
988 return uri_escape(Encode::encode("utf8", $text), $unsafe);
989 }
990
991 sub decode_text {
992 my ($data) = @_;
993
994 return Encode::decode("utf8", uri_unescape($data));
995 }
996
997 # depreciated - do not use!
998 # we now decode all parameters by default
999 sub decode_utf8_parameters {
1000 my ($param) = @_;
1001
1002 foreach my $p (qw(comment description firstname lastname)) {
1003 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
1004 }
1005
1006 return $param;
1007 }
1008
1009 sub random_ether_addr {
1010 my ($prefix) = @_;
1011
1012 my ($seconds, $microseconds) = gettimeofday;
1013
1014 my $rand = Digest::SHA::sha1($$, rand(), $seconds, $microseconds);
1015
1016 # clear multicast, set local id
1017 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
1018
1019 my $addr = sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
1020 if (defined($prefix)) {
1021 $addr = uc($prefix) . substr($addr, length($prefix));
1022 }
1023 return $addr;
1024 }
1025
1026 sub shellquote {
1027 my $str = shift;
1028
1029 return String::ShellQuote::shell_quote($str);
1030 }
1031
1032 sub cmd2string {
1033 my ($cmd) = @_;
1034
1035 die "no arguments" if !$cmd;
1036
1037 return $cmd if !ref($cmd);
1038
1039 my @qa = ();
1040 foreach my $arg (@$cmd) { push @qa, shellquote($arg); }
1041
1042 return join (' ', @qa);
1043 }
1044
1045 # split an shell argument string into an array,
1046 sub split_args {
1047 my ($str) = @_;
1048
1049 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
1050 }
1051
1052 sub dump_logfile {
1053 my ($filename, $start, $limit, $filter) = @_;
1054
1055 my $lines = [];
1056 my $count = 0;
1057
1058 my $fh = IO::File->new($filename, "r");
1059 if (!$fh) {
1060 $count++;
1061 push @$lines, { n => $count, t => "unable to open file - $!"};
1062 return ($count, $lines);
1063 }
1064
1065 $start = 0 if !$start;
1066 $limit = 50 if !$limit;
1067
1068 my $line;
1069
1070 if ($filter) {
1071 # duplicate code, so that we do not slow down normal path
1072 while (defined($line = <$fh>)) {
1073 next if $line !~ m/$filter/;
1074 next if $count++ < $start;
1075 next if $limit <= 0;
1076 chomp $line;
1077 push @$lines, { n => $count, t => $line};
1078 $limit--;
1079 }
1080 } else {
1081 while (defined($line = <$fh>)) {
1082 next if $count++ < $start;
1083 next if $limit <= 0;
1084 chomp $line;
1085 push @$lines, { n => $count, t => $line};
1086 $limit--;
1087 }
1088 }
1089
1090 close($fh);
1091
1092 # HACK: ExtJS store.guaranteeRange() does not like empty array
1093 # so we add a line
1094 if (!$count) {
1095 $count++;
1096 push @$lines, { n => $count, t => "no content"};
1097 }
1098
1099 return ($count, $lines);
1100 }
1101
1102 sub dump_journal {
1103 my ($start, $limit, $since, $until, $service) = @_;
1104
1105 my $lines = [];
1106 my $count = 0;
1107
1108 $start = 0 if !$start;
1109 $limit = 50 if !$limit;
1110
1111 my $parser = sub {
1112 my $line = shift;
1113
1114 return if $count++ < $start;
1115 return if $limit <= 0;
1116 push @$lines, { n => int($count), t => $line};
1117 $limit--;
1118 };
1119
1120 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1121
1122 push @$cmd, '--unit', $service if $service;
1123 push @$cmd, '--since', $since if $since;
1124 push @$cmd, '--until', $until if $until;
1125 run_command($cmd, outfunc => $parser);
1126
1127 # HACK: ExtJS store.guaranteeRange() does not like empty array
1128 # so we add a line
1129 if (!$count) {
1130 $count++;
1131 push @$lines, { n => $count, t => "no content"};
1132 }
1133
1134 return ($count, $lines);
1135 }
1136
1137 sub dir_glob_regex {
1138 my ($dir, $regex) = @_;
1139
1140 my $dh = IO::Dir->new ($dir);
1141 return wantarray ? () : undef if !$dh;
1142
1143 while (defined(my $tmp = $dh->read)) {
1144 if (my @res = $tmp =~ m/^($regex)$/) {
1145 $dh->close;
1146 return wantarray ? @res : $tmp;
1147 }
1148 }
1149 $dh->close;
1150
1151 return wantarray ? () : undef;
1152 }
1153
1154 sub dir_glob_foreach {
1155 my ($dir, $regex, $func) = @_;
1156
1157 my $dh = IO::Dir->new ($dir);
1158 if (defined $dh) {
1159 while (defined(my $tmp = $dh->read)) {
1160 if (my @res = $tmp =~ m/^($regex)$/) {
1161 &$func (@res);
1162 }
1163 }
1164 }
1165 }
1166
1167 sub assert_if_modified {
1168 my ($digest1, $digest2) = @_;
1169
1170 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1171 die "detected modified configuration - file changed by other user? Try again.\n";
1172 }
1173 }
1174
1175 # Digest for short strings
1176 # like FNV32a, but we only return 31 bits (positive numbers)
1177 sub fnv31a {
1178 my ($string) = @_;
1179
1180 my $hval = 0x811c9dc5;
1181
1182 foreach my $c (unpack('C*', $string)) {
1183 $hval ^= $c;
1184 $hval += (
1185 (($hval << 1) ) +
1186 (($hval << 4) ) +
1187 (($hval << 7) ) +
1188 (($hval << 8) ) +
1189 (($hval << 24) ) );
1190 $hval = $hval & 0xffffffff;
1191 }
1192 return $hval & 0x7fffffff;
1193 }
1194
1195 sub fnv31a_hex { return sprintf("%X", fnv31a(@_)); }
1196
1197 sub unpack_sockaddr_in46 {
1198 my ($sin) = @_;
1199 my $family = Socket::sockaddr_family($sin);
1200 my ($port, $host) = ($family == AF_INET6 ? Socket::unpack_sockaddr_in6($sin)
1201 : Socket::unpack_sockaddr_in($sin));
1202 return ($family, $port, $host);
1203 }
1204
1205 sub getaddrinfo_all {
1206 my ($hostname, @opts) = @_;
1207 my %hints = ( flags => AI_V4MAPPED | AI_ALL,
1208 @opts );
1209 my ($err, @res) = Socket::getaddrinfo($hostname, '0', \%hints);
1210 die "failed to get address info for: $hostname: $err\n" if $err;
1211 return @res;
1212 }
1213
1214 sub get_host_address_family {
1215 my ($hostname, $socktype) = @_;
1216 my @res = getaddrinfo_all($hostname, socktype => $socktype);
1217 return $res[0]->{family};
1218 }
1219
1220 # get the fully qualified domain name of a host
1221 # same logic as hostname(1): The FQDN is the name getaddrinfo(3) returns,
1222 # given a nodename as a parameter
1223 sub get_fqdn {
1224 my ($nodename) = @_;
1225
1226 my $hints = {
1227 flags => AI_CANONNAME,
1228 socktype => SOCK_DGRAM
1229 };
1230
1231 my ($err, @addrs) = Socket::getaddrinfo($nodename, undef, $hints);
1232
1233 die "getaddrinfo: $err" if $err;
1234
1235 return $addrs[0]->{canonname};
1236 }
1237
1238 # Parses any sane kind of host, or host+port pair:
1239 # The port is always optional and thus may be undef.
1240 sub parse_host_and_port {
1241 my ($address) = @_;
1242 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1243 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1244 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1245 {
1246 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1247 }
1248 return; # nothing
1249 }
1250
1251 sub unshare($) {
1252 my ($flags) = @_;
1253 return 0 == syscall(PVE::Syscall::unshare, $flags);
1254 }
1255
1256 sub setns($$) {
1257 my ($fileno, $nstype) = @_;
1258 return 0 == syscall(PVE::Syscall::setns, $fileno, $nstype);
1259 }
1260
1261 sub syncfs($) {
1262 my ($fileno) = @_;
1263 return 0 == syscall(PVE::Syscall::syncfs, $fileno);
1264 }
1265
1266 sub sync_mountpoint {
1267 my ($path) = @_;
1268 sysopen my $fd, $path, O_PATH or die "failed to open $path: $!\n";
1269 my $result = syncfs(fileno($fd));
1270 close($fd);
1271 return $result;
1272 }
1273
1274 # support sending multi-part mail messages with a text and or a HTML part
1275 # mailto may be a single email string or an array of receivers
1276 sub sendmail {
1277 my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_;
1278 my $mail_re = qr/[^-a-zA-Z0-9+._@]/;
1279
1280 $mailto = [ $mailto ] if !ref($mailto);
1281
1282 foreach (@$mailto) {
1283 die "illegal character in mailto address\n"
1284 if ($_ =~ $mail_re);
1285 }
1286
1287 my $rcvrtxt = join (', ', @$mailto);
1288
1289 $mailfrom = $mailfrom || "root";
1290 die "illegal character in mailfrom address\n"
1291 if $mailfrom =~ $mail_re;
1292
1293 $author = $author || 'Proxmox VE';
1294
1295 open (MAIL, "|-", "sendmail", "-B", "8BITMIME", "-f", $mailfrom, @$mailto) ||
1296 die "unable to open 'sendmail' - $!";
1297
1298 # multipart spec see https://www.ietf.org/rfc/rfc1521.txt
1299 my $boundary = "----_=_NextPart_001_".int(time).$$;
1300
1301 print MAIL "Content-Type: multipart/alternative;\n";
1302 print MAIL "\tboundary=\"$boundary\"\n";
1303 print MAIL "MIME-Version: 1.0\n";
1304
1305 print MAIL "FROM: $author <$mailfrom>\n";
1306 print MAIL "TO: $rcvrtxt\n";
1307 print MAIL "SUBJECT: $subject\n";
1308 print MAIL "\n";
1309 print MAIL "This is a multi-part message in MIME format.\n\n";
1310 print MAIL "--$boundary\n";
1311
1312 if (defined($text)) {
1313 print MAIL "Content-Type: text/plain;\n";
1314 print MAIL "\tcharset=\"UTF8\"\n";
1315 print MAIL "Content-Transfer-Encoding: 8bit\n";
1316 print MAIL "\n";
1317
1318 # avoid 'remove extra line breaks' issue (MS Outlook)
1319 my $fill = ' ';
1320 $text =~ s/^/$fill/gm;
1321
1322 print MAIL $text;
1323
1324 print MAIL "\n--$boundary\n";
1325 }
1326
1327 if (defined($html)) {
1328 print MAIL "Content-Type: text/html;\n";
1329 print MAIL "\tcharset=\"UTF8\"\n";
1330 print MAIL "Content-Transfer-Encoding: 8bit\n";
1331 print MAIL "\n";
1332
1333 print MAIL $html;
1334
1335 print MAIL "\n--$boundary--\n";
1336 }
1337
1338 close(MAIL);
1339 }
1340
1341 sub tempfile {
1342 my ($perm, %opts) = @_;
1343
1344 # default permissions are stricter than with file_set_contents
1345 $perm = 0600 if !defined($perm);
1346
1347 my $dir = $opts{dir} // '/run';
1348 my $mode = $opts{mode} // O_RDWR;
1349 $mode |= O_EXCL if !$opts{allow_links};
1350
1351 my $fh = IO::File->new($dir, $mode | O_TMPFILE, $perm);
1352 if (!$fh && $! == EOPNOTSUPP) {
1353 $dir = '/tmp' if !defined($opts{dir});
1354 $dir .= "/.tmpfile.$$";
1355 $fh = IO::File->new($dir, $mode | O_CREAT | O_EXCL, $perm);
1356 unlink($dir) if $fh;
1357 }
1358 die "failed to create tempfile: $!\n" if !$fh;
1359 return $fh;
1360 }
1361
1362 sub tempfile_contents {
1363 my ($data, $perm, %opts) = @_;
1364
1365 my $fh = tempfile($perm, %opts);
1366 eval {
1367 die "unable to write to tempfile: $!\n" if !print {$fh} $data;
1368 die "unable to flush to tempfile: $!\n" if !defined($fh->flush());
1369 };
1370 if (my $err = $@) {
1371 close $fh;
1372 die $err;
1373 }
1374
1375 return ("/proc/$$/fd/".$fh->fileno, $fh);
1376 }
1377
1378 sub validate_ssh_public_keys {
1379 my ($raw) = @_;
1380 my @lines = split(/\n/, $raw);
1381
1382 foreach my $line (@lines) {
1383 next if $line =~ m/^\s*$/;
1384 eval {
1385 my ($filename, $handle) = tempfile_contents($line);
1386 run_command(["ssh-keygen", "-l", "-f", $filename],
1387 outfunc => sub {}, errfunc => sub {});
1388 };
1389 die "SSH public key validation error\n" if $@;
1390 }
1391 }
1392
1393 sub openat($$$;$) {
1394 my ($dirfd, $pathname, $flags, $mode) = @_;
1395 my $fd = syscall(PVE::Syscall::openat, $dirfd, $pathname, $flags, $mode//0);
1396 return undef if $fd < 0;
1397 # sysopen() doesn't deal with numeric file descriptors apparently
1398 # so we need to convert to a mode string for IO::Handle->new_from_fd
1399 my $flagstr = ($flags & O_RDWR) ? 'rw' : ($flags & O_WRONLY) ? 'w' : 'r';
1400 my $handle = IO::Handle->new_from_fd($fd, $flagstr);
1401 return $handle if $handle;
1402 my $err = $!; # save error before closing the raw fd
1403 syscall(PVE::Syscall::close, $fd); # close
1404 $! = $err;
1405 return undef;
1406 }
1407
1408 sub mkdirat($$$) {
1409 my ($dirfd, $name, $mode) = @_;
1410 return syscall(PVE::Syscall::mkdirat, $dirfd, $name, $mode) == 0;
1411 }
1412
1413 # NOTE: This calls the dbus main loop and must not be used when another dbus
1414 # main loop is being used as we need to wait for the JobRemoved signal.
1415 # Polling the job status instead doesn't work because this doesn't give us the
1416 # distinction between success and failure.
1417 #
1418 # Note that the description is mandatory for security reasons.
1419 sub enter_systemd_scope {
1420 my ($unit, $description, %extra) = @_;
1421 die "missing description\n" if !defined($description);
1422
1423 my $timeout = delete $extra{timeout};
1424
1425 $unit .= '.scope';
1426 my $properties = [ [PIDs => [dbus_uint32($$)]] ];
1427
1428 foreach my $key (keys %extra) {
1429 if ($key eq 'Slice' || $key eq 'KillMode') {
1430 push @$properties, [$key, $extra{$key}];
1431 } elsif ($key eq 'CPUShares') {
1432 push @$properties, [$key, dbus_uint64($extra{$key})];
1433 } elsif ($key eq 'CPUQuota') {
1434 push @$properties, ['CPUQuotaPerSecUSec',
1435 dbus_uint64($extra{$key} * 10000)];
1436 } else {
1437 die "Don't know how to encode $key for systemd scope\n";
1438 }
1439 }
1440
1441 my $job;
1442 my $done = 0;
1443
1444 my $bus = Net::DBus->system();
1445 my $reactor = Net::DBus::Reactor->main();
1446
1447 my $service = $bus->get_service('org.freedesktop.systemd1');
1448 my $if = $service->get_object('/org/freedesktop/systemd1', 'org.freedesktop.systemd1.Manager');
1449 # Connect to the JobRemoved signal since we want to wait for it to finish
1450 my $sigid;
1451 my $timer;
1452 my $cleanup = sub {
1453 my ($no_shutdown) = @_;
1454 $if->disconnect_from_signal('JobRemoved', $sigid) if defined($if);
1455 $if = undef;
1456 $sigid = undef;
1457 $reactor->remove_timeout($timer) if defined($timer);
1458 $timer = undef;
1459 return if $no_shutdown;
1460 $reactor->shutdown();
1461 };
1462
1463 $sigid = $if->connect_to_signal('JobRemoved', sub {
1464 my ($id, $removed_job, $signaled_unit, $result) = @_;
1465 return if $signaled_unit ne $unit || $removed_job ne $job;
1466 $cleanup->(0);
1467 die "systemd job failed\n" if $result ne 'done';
1468 $done = 1;
1469 });
1470
1471 my $on_timeout = sub {
1472 $cleanup->(0);
1473 die "systemd job timed out\n";
1474 };
1475
1476 $timer = $reactor->add_timeout($timeout * 1000, Net::DBus::Callback->new(method => $on_timeout))
1477 if defined($timeout);
1478 $job = $if->StartTransientUnit($unit, 'fail', $properties, []);
1479 $reactor->run();
1480 $cleanup->(1);
1481 die "systemd job never completed\n" if !$done;
1482 }
1483
1484 my $salt_starter = time();
1485
1486 sub encrypt_pw {
1487 my ($pw) = @_;
1488
1489 $salt_starter++;
1490 my $salt = substr(Digest::SHA::sha1_base64(time() + $salt_starter + $$), 0, 8);
1491
1492 # crypt does not want '+' in salt (see 'man crypt')
1493 $salt =~ s/\+/X/g;
1494
1495 return crypt(encode("utf8", $pw), "\$5\$$salt\$");
1496 }
1497
1498 1;