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