]> git.proxmox.com Git - pve-common.git/blob - src/PVE/Tools.pm
30322b2888246a8b6ae1c139f370582de936db7e
[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, $address) = @_;
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 my %sockargs = (Listen => 5,
790 ReuseAddr => 1,
791 Family => $family,
792 Proto => 0,
793 GetAddrInfoFlags => 0);
794 $sockargs{LocalAddr} = $address if defined($address);
795
796 for (my $p = $range_start; $p < $range_end; $p++) {
797 next if $ports->{$p}; # reserved
798
799 $sockargs{LocalPort} = $p;
800 my $sock = IO::Socket::IP->new(%sockargs);
801
802 if ($sock) {
803 close($sock);
804 $newport = $p;
805 $ports->{$p} = $ctime;
806 last;
807 }
808 }
809
810 my $data = "";
811 foreach my $p (keys %$ports) {
812 $data .= "$p $ports->{$p}\n";
813 }
814
815 file_set_contents($filename, $data);
816
817 return $newport;
818 };
819
820 my $p = lock_file('/var/lock/pve-ports.lck', 10, $code);
821 die $@ if $@;
822
823 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
824
825 return $p;
826 }
827
828 sub next_migrate_port {
829 my ($family, $address) = @_;
830 return next_unused_port(60000, 60050, $family, $address);
831 }
832
833 sub next_vnc_port {
834 my ($family, $address) = @_;
835 return next_unused_port(5900, 6000, $family, $address);
836 }
837
838 sub next_spice_port {
839 my ($family, $address) = @_;
840 return next_unused_port(61000, 61099, $family, $address);
841 }
842
843 # NOTE: NFS syscall can't be interrupted, so alarm does
844 # not work to provide timeouts.
845 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
846 # So fork() before using Filesys::Df
847 sub df {
848 my ($path, $timeout) = @_;
849
850 my $res = {
851 total => 0,
852 used => 0,
853 avail => 0,
854 };
855
856 my $pipe = IO::Pipe->new();
857 my $child = fork();
858 if (!defined($child)) {
859 warn "fork failed: $!\n";
860 return $res;
861 }
862
863 if (!$child) {
864 $pipe->writer();
865 eval {
866 my $df = Filesys::Df::df($path, 1);
867 print {$pipe} "$df->{blocks}\n$df->{used}\n$df->{bavail}\n";
868 $pipe->close();
869 };
870 if (my $err = $@) {
871 warn $err;
872 POSIX::_exit(1);
873 }
874 POSIX::_exit(0);
875 }
876
877 $pipe->reader();
878
879 my $readvalues = sub {
880 $res->{total} = int((<$pipe> =~ /^(\d*)$/)[0]);
881 $res->{used} = int((<$pipe> =~ /^(\d*)$/)[0]);
882 $res->{avail} = int((<$pipe> =~ /^(\d*)$/)[0]);
883 };
884 eval {
885 run_with_timeout($timeout, $readvalues);
886 };
887 warn $@ if $@;
888 $pipe->close();
889 kill('KILL', $child);
890 waitpid($child, 0);
891 return $res;
892 }
893
894 # UPID helper
895 # We use this to uniquely identify a process.
896 # An 'Unique Process ID' has the following format:
897 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
898
899 sub upid_encode {
900 my $d = shift;
901
902 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
903 # more that 8 characters for pstart
904 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid},
905 $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id},
906 $d->{user});
907 }
908
909 sub upid_decode {
910 my ($upid, $noerr) = @_;
911
912 my $res;
913 my $filename;
914
915 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
916 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
917 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]+):$/) {
918 $res->{node} = $1;
919 $res->{pid} = hex($3);
920 $res->{pstart} = hex($4);
921 $res->{starttime} = hex($5);
922 $res->{type} = $6;
923 $res->{id} = $7;
924 $res->{user} = $8;
925
926 my $subdir = substr($5, 7, 8);
927 $filename = "$pvetaskdir/$subdir/$upid";
928
929 } else {
930 return undef if $noerr;
931 die "unable to parse worker upid '$upid'\n";
932 }
933
934 return wantarray ? ($res, $filename) : $res;
935 }
936
937 sub upid_open {
938 my ($upid) = @_;
939
940 my ($task, $filename) = upid_decode($upid);
941
942 my $dirname = dirname($filename);
943 make_path($dirname);
944
945 my $wwwid = getpwnam('www-data') ||
946 die "getpwnam failed";
947
948 my $perm = 0640;
949
950 my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) ||
951 die "unable to create output file '$filename' - $!\n";
952 chown $wwwid, -1, $outfh;
953
954 return $outfh;
955 };
956
957 sub upid_read_status {
958 my ($upid) = @_;
959
960 my ($task, $filename) = upid_decode($upid);
961 my $fh = IO::File->new($filename, "r");
962 return "unable to open file - $!" if !$fh;
963 my $maxlen = 4096;
964 sysseek($fh, -$maxlen, 2);
965 my $readbuf = '';
966 my $br = sysread($fh, $readbuf, $maxlen);
967 close($fh);
968 if ($br) {
969 return "unable to extract last line"
970 if $readbuf !~ m/\n?(.+)$/;
971 my $line = $1;
972 if ($line =~ m/^TASK OK$/) {
973 return 'OK';
974 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
975 return $1;
976 } else {
977 return "unexpected status";
978 }
979 }
980 return "unable to read tail (got $br bytes)";
981 }
982
983 # useful functions to store comments in config files
984 sub encode_text {
985 my ($text) = @_;
986
987 # all control and hi-bit characters, and ':'
988 my $unsafe = "^\x20-\x39\x3b-\x7e";
989 return uri_escape(Encode::encode("utf8", $text), $unsafe);
990 }
991
992 sub decode_text {
993 my ($data) = @_;
994
995 return Encode::decode("utf8", uri_unescape($data));
996 }
997
998 # depreciated - do not use!
999 # we now decode all parameters by default
1000 sub decode_utf8_parameters {
1001 my ($param) = @_;
1002
1003 foreach my $p (qw(comment description firstname lastname)) {
1004 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
1005 }
1006
1007 return $param;
1008 }
1009
1010 sub random_ether_addr {
1011 my ($prefix) = @_;
1012
1013 my ($seconds, $microseconds) = gettimeofday;
1014
1015 my $rand = Digest::SHA::sha1($$, rand(), $seconds, $microseconds);
1016
1017 # clear multicast, set local id
1018 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
1019
1020 my $addr = sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
1021 if (defined($prefix)) {
1022 $addr = uc($prefix) . substr($addr, length($prefix));
1023 }
1024 return $addr;
1025 }
1026
1027 sub shellquote {
1028 my $str = shift;
1029
1030 return String::ShellQuote::shell_quote($str);
1031 }
1032
1033 sub cmd2string {
1034 my ($cmd) = @_;
1035
1036 die "no arguments" if !$cmd;
1037
1038 return $cmd if !ref($cmd);
1039
1040 my @qa = ();
1041 foreach my $arg (@$cmd) { push @qa, shellquote($arg); }
1042
1043 return join (' ', @qa);
1044 }
1045
1046 # split an shell argument string into an array,
1047 sub split_args {
1048 my ($str) = @_;
1049
1050 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
1051 }
1052
1053 sub dump_logfile {
1054 my ($filename, $start, $limit, $filter) = @_;
1055
1056 my $lines = [];
1057 my $count = 0;
1058
1059 my $fh = IO::File->new($filename, "r");
1060 if (!$fh) {
1061 $count++;
1062 push @$lines, { n => $count, t => "unable to open file - $!"};
1063 return ($count, $lines);
1064 }
1065
1066 $start = 0 if !$start;
1067 $limit = 50 if !$limit;
1068
1069 my $line;
1070
1071 if ($filter) {
1072 # duplicate code, so that we do not slow down normal path
1073 while (defined($line = <$fh>)) {
1074 next if $line !~ m/$filter/;
1075 next if $count++ < $start;
1076 next if $limit <= 0;
1077 chomp $line;
1078 push @$lines, { n => $count, t => $line};
1079 $limit--;
1080 }
1081 } else {
1082 while (defined($line = <$fh>)) {
1083 next if $count++ < $start;
1084 next if $limit <= 0;
1085 chomp $line;
1086 push @$lines, { n => $count, t => $line};
1087 $limit--;
1088 }
1089 }
1090
1091 close($fh);
1092
1093 # HACK: ExtJS store.guaranteeRange() does not like empty array
1094 # so we add a line
1095 if (!$count) {
1096 $count++;
1097 push @$lines, { n => $count, t => "no content"};
1098 }
1099
1100 return ($count, $lines);
1101 }
1102
1103 sub dump_journal {
1104 my ($start, $limit, $since, $until, $service) = @_;
1105
1106 my $lines = [];
1107 my $count = 0;
1108
1109 $start = 0 if !$start;
1110 $limit = 50 if !$limit;
1111
1112 my $parser = sub {
1113 my $line = shift;
1114
1115 return if $count++ < $start;
1116 return if $limit <= 0;
1117 push @$lines, { n => int($count), t => $line};
1118 $limit--;
1119 };
1120
1121 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
1122
1123 push @$cmd, '--unit', $service if $service;
1124 push @$cmd, '--since', $since if $since;
1125 push @$cmd, '--until', $until if $until;
1126 run_command($cmd, outfunc => $parser);
1127
1128 # HACK: ExtJS store.guaranteeRange() does not like empty array
1129 # so we add a line
1130 if (!$count) {
1131 $count++;
1132 push @$lines, { n => $count, t => "no content"};
1133 }
1134
1135 return ($count, $lines);
1136 }
1137
1138 sub dir_glob_regex {
1139 my ($dir, $regex) = @_;
1140
1141 my $dh = IO::Dir->new ($dir);
1142 return wantarray ? () : undef if !$dh;
1143
1144 while (defined(my $tmp = $dh->read)) {
1145 if (my @res = $tmp =~ m/^($regex)$/) {
1146 $dh->close;
1147 return wantarray ? @res : $tmp;
1148 }
1149 }
1150 $dh->close;
1151
1152 return wantarray ? () : undef;
1153 }
1154
1155 sub dir_glob_foreach {
1156 my ($dir, $regex, $func) = @_;
1157
1158 my $dh = IO::Dir->new ($dir);
1159 if (defined $dh) {
1160 while (defined(my $tmp = $dh->read)) {
1161 if (my @res = $tmp =~ m/^($regex)$/) {
1162 &$func (@res);
1163 }
1164 }
1165 }
1166 }
1167
1168 sub assert_if_modified {
1169 my ($digest1, $digest2) = @_;
1170
1171 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
1172 die "detected modified configuration - file changed by other user? Try again.\n";
1173 }
1174 }
1175
1176 # Digest for short strings
1177 # like FNV32a, but we only return 31 bits (positive numbers)
1178 sub fnv31a {
1179 my ($string) = @_;
1180
1181 my $hval = 0x811c9dc5;
1182
1183 foreach my $c (unpack('C*', $string)) {
1184 $hval ^= $c;
1185 $hval += (
1186 (($hval << 1) ) +
1187 (($hval << 4) ) +
1188 (($hval << 7) ) +
1189 (($hval << 8) ) +
1190 (($hval << 24) ) );
1191 $hval = $hval & 0xffffffff;
1192 }
1193 return $hval & 0x7fffffff;
1194 }
1195
1196 sub fnv31a_hex { return sprintf("%X", fnv31a(@_)); }
1197
1198 sub unpack_sockaddr_in46 {
1199 my ($sin) = @_;
1200 my $family = Socket::sockaddr_family($sin);
1201 my ($port, $host) = ($family == AF_INET6 ? Socket::unpack_sockaddr_in6($sin)
1202 : Socket::unpack_sockaddr_in($sin));
1203 return ($family, $port, $host);
1204 }
1205
1206 sub getaddrinfo_all {
1207 my ($hostname, @opts) = @_;
1208 my %hints = ( flags => AI_V4MAPPED | AI_ALL,
1209 @opts );
1210 my ($err, @res) = Socket::getaddrinfo($hostname, '0', \%hints);
1211 die "failed to get address info for: $hostname: $err\n" if $err;
1212 return @res;
1213 }
1214
1215 sub get_host_address_family {
1216 my ($hostname, $socktype) = @_;
1217 my @res = getaddrinfo_all($hostname, socktype => $socktype);
1218 return $res[0]->{family};
1219 }
1220
1221 # get the fully qualified domain name of a host
1222 # same logic as hostname(1): The FQDN is the name getaddrinfo(3) returns,
1223 # given a nodename as a parameter
1224 sub get_fqdn {
1225 my ($nodename) = @_;
1226
1227 my $hints = {
1228 flags => AI_CANONNAME,
1229 socktype => SOCK_DGRAM
1230 };
1231
1232 my ($err, @addrs) = Socket::getaddrinfo($nodename, undef, $hints);
1233
1234 die "getaddrinfo: $err" if $err;
1235
1236 return $addrs[0]->{canonname};
1237 }
1238
1239 # Parses any sane kind of host, or host+port pair:
1240 # The port is always optional and thus may be undef.
1241 sub parse_host_and_port {
1242 my ($address) = @_;
1243 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1244 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1245 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1246 {
1247 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1248 }
1249 return; # nothing
1250 }
1251
1252 sub unshare($) {
1253 my ($flags) = @_;
1254 return 0 == syscall(PVE::Syscall::unshare, $flags);
1255 }
1256
1257 sub setns($$) {
1258 my ($fileno, $nstype) = @_;
1259 return 0 == syscall(PVE::Syscall::setns, $fileno, $nstype);
1260 }
1261
1262 sub syncfs($) {
1263 my ($fileno) = @_;
1264 return 0 == syscall(PVE::Syscall::syncfs, $fileno);
1265 }
1266
1267 sub sync_mountpoint {
1268 my ($path) = @_;
1269 sysopen my $fd, $path, O_PATH or die "failed to open $path: $!\n";
1270 my $result = syncfs(fileno($fd));
1271 close($fd);
1272 return $result;
1273 }
1274
1275 # support sending multi-part mail messages with a text and or a HTML part
1276 # mailto may be a single email string or an array of receivers
1277 sub sendmail {
1278 my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_;
1279 my $mail_re = qr/[^-a-zA-Z0-9+._@]/;
1280
1281 $mailto = [ $mailto ] if !ref($mailto);
1282
1283 foreach (@$mailto) {
1284 die "illegal character in mailto address\n"
1285 if ($_ =~ $mail_re);
1286 }
1287
1288 my $rcvrtxt = join (', ', @$mailto);
1289
1290 $mailfrom = $mailfrom || "root";
1291 die "illegal character in mailfrom address\n"
1292 if $mailfrom =~ $mail_re;
1293
1294 $author = $author || 'Proxmox VE';
1295
1296 open (MAIL, "|-", "sendmail", "-B", "8BITMIME", "-f", $mailfrom, @$mailto) ||
1297 die "unable to open 'sendmail' - $!";
1298
1299 # multipart spec see https://www.ietf.org/rfc/rfc1521.txt
1300 my $boundary = "----_=_NextPart_001_".int(time).$$;
1301
1302 print MAIL "Content-Type: multipart/alternative;\n";
1303 print MAIL "\tboundary=\"$boundary\"\n";
1304 print MAIL "MIME-Version: 1.0\n";
1305
1306 print MAIL "FROM: $author <$mailfrom>\n";
1307 print MAIL "TO: $rcvrtxt\n";
1308 print MAIL "SUBJECT: $subject\n";
1309 print MAIL "\n";
1310 print MAIL "This is a multi-part message in MIME format.\n\n";
1311 print MAIL "--$boundary\n";
1312
1313 if (defined($text)) {
1314 print MAIL "Content-Type: text/plain;\n";
1315 print MAIL "\tcharset=\"UTF8\"\n";
1316 print MAIL "Content-Transfer-Encoding: 8bit\n";
1317 print MAIL "\n";
1318
1319 # avoid 'remove extra line breaks' issue (MS Outlook)
1320 my $fill = ' ';
1321 $text =~ s/^/$fill/gm;
1322
1323 print MAIL $text;
1324
1325 print MAIL "\n--$boundary\n";
1326 }
1327
1328 if (defined($html)) {
1329 print MAIL "Content-Type: text/html;\n";
1330 print MAIL "\tcharset=\"UTF8\"\n";
1331 print MAIL "Content-Transfer-Encoding: 8bit\n";
1332 print MAIL "\n";
1333
1334 print MAIL $html;
1335
1336 print MAIL "\n--$boundary--\n";
1337 }
1338
1339 close(MAIL);
1340 }
1341
1342 sub tempfile {
1343 my ($perm, %opts) = @_;
1344
1345 # default permissions are stricter than with file_set_contents
1346 $perm = 0600 if !defined($perm);
1347
1348 my $dir = $opts{dir} // '/run';
1349 my $mode = $opts{mode} // O_RDWR;
1350 $mode |= O_EXCL if !$opts{allow_links};
1351
1352 my $fh = IO::File->new($dir, $mode | O_TMPFILE, $perm);
1353 if (!$fh && $! == EOPNOTSUPP) {
1354 $dir = '/tmp' if !defined($opts{dir});
1355 $dir .= "/.tmpfile.$$";
1356 $fh = IO::File->new($dir, $mode | O_CREAT | O_EXCL, $perm);
1357 unlink($dir) if $fh;
1358 }
1359 die "failed to create tempfile: $!\n" if !$fh;
1360 return $fh;
1361 }
1362
1363 sub tempfile_contents {
1364 my ($data, $perm, %opts) = @_;
1365
1366 my $fh = tempfile($perm, %opts);
1367 eval {
1368 die "unable to write to tempfile: $!\n" if !print {$fh} $data;
1369 die "unable to flush to tempfile: $!\n" if !defined($fh->flush());
1370 };
1371 if (my $err = $@) {
1372 close $fh;
1373 die $err;
1374 }
1375
1376 return ("/proc/$$/fd/".$fh->fileno, $fh);
1377 }
1378
1379 sub validate_ssh_public_keys {
1380 my ($raw) = @_;
1381 my @lines = split(/\n/, $raw);
1382
1383 foreach my $line (@lines) {
1384 next if $line =~ m/^\s*$/;
1385 eval {
1386 my ($filename, $handle) = tempfile_contents($line);
1387 run_command(["ssh-keygen", "-l", "-f", $filename],
1388 outfunc => sub {}, errfunc => sub {});
1389 };
1390 die "SSH public key validation error\n" if $@;
1391 }
1392 }
1393
1394 sub openat($$$;$) {
1395 my ($dirfd, $pathname, $flags, $mode) = @_;
1396 my $fd = syscall(PVE::Syscall::openat, $dirfd, $pathname, $flags, $mode//0);
1397 return undef if $fd < 0;
1398 # sysopen() doesn't deal with numeric file descriptors apparently
1399 # so we need to convert to a mode string for IO::Handle->new_from_fd
1400 my $flagstr = ($flags & O_RDWR) ? 'rw' : ($flags & O_WRONLY) ? 'w' : 'r';
1401 my $handle = IO::Handle->new_from_fd($fd, $flagstr);
1402 return $handle if $handle;
1403 my $err = $!; # save error before closing the raw fd
1404 syscall(PVE::Syscall::close, $fd); # close
1405 $! = $err;
1406 return undef;
1407 }
1408
1409 sub mkdirat($$$) {
1410 my ($dirfd, $name, $mode) = @_;
1411 return syscall(PVE::Syscall::mkdirat, $dirfd, $name, $mode) == 0;
1412 }
1413
1414 # NOTE: This calls the dbus main loop and must not be used when another dbus
1415 # main loop is being used as we need to wait for the JobRemoved signal.
1416 # Polling the job status instead doesn't work because this doesn't give us the
1417 # distinction between success and failure.
1418 #
1419 # Note that the description is mandatory for security reasons.
1420 sub enter_systemd_scope {
1421 my ($unit, $description, %extra) = @_;
1422 die "missing description\n" if !defined($description);
1423
1424 my $timeout = delete $extra{timeout};
1425
1426 $unit .= '.scope';
1427 my $properties = [ [PIDs => [dbus_uint32($$)]] ];
1428
1429 foreach my $key (keys %extra) {
1430 if ($key eq 'Slice' || $key eq 'KillMode') {
1431 push @$properties, [$key, $extra{$key}];
1432 } elsif ($key eq 'CPUShares') {
1433 push @$properties, [$key, dbus_uint64($extra{$key})];
1434 } elsif ($key eq 'CPUQuota') {
1435 push @$properties, ['CPUQuotaPerSecUSec',
1436 dbus_uint64($extra{$key} * 10000)];
1437 } else {
1438 die "Don't know how to encode $key for systemd scope\n";
1439 }
1440 }
1441
1442 my $job;
1443 my $done = 0;
1444
1445 my $bus = Net::DBus->system();
1446 my $reactor = Net::DBus::Reactor->main();
1447
1448 my $service = $bus->get_service('org.freedesktop.systemd1');
1449 my $if = $service->get_object('/org/freedesktop/systemd1', 'org.freedesktop.systemd1.Manager');
1450 # Connect to the JobRemoved signal since we want to wait for it to finish
1451 my $sigid;
1452 my $timer;
1453 my $cleanup = sub {
1454 my ($no_shutdown) = @_;
1455 $if->disconnect_from_signal('JobRemoved', $sigid) if defined($if);
1456 $if = undef;
1457 $sigid = undef;
1458 $reactor->remove_timeout($timer) if defined($timer);
1459 $timer = undef;
1460 return if $no_shutdown;
1461 $reactor->shutdown();
1462 };
1463
1464 $sigid = $if->connect_to_signal('JobRemoved', sub {
1465 my ($id, $removed_job, $signaled_unit, $result) = @_;
1466 return if $signaled_unit ne $unit || $removed_job ne $job;
1467 $cleanup->(0);
1468 die "systemd job failed\n" if $result ne 'done';
1469 $done = 1;
1470 });
1471
1472 my $on_timeout = sub {
1473 $cleanup->(0);
1474 die "systemd job timed out\n";
1475 };
1476
1477 $timer = $reactor->add_timeout($timeout * 1000, Net::DBus::Callback->new(method => $on_timeout))
1478 if defined($timeout);
1479 $job = $if->StartTransientUnit($unit, 'fail', $properties, []);
1480 $reactor->run();
1481 $cleanup->(1);
1482 die "systemd job never completed\n" if !$done;
1483 }
1484
1485 my $salt_starter = time();
1486
1487 sub encrypt_pw {
1488 my ($pw) = @_;
1489
1490 $salt_starter++;
1491 my $salt = substr(Digest::SHA::sha1_base64(time() + $salt_starter + $$), 0, 8);
1492
1493 # crypt does not want '+' in salt (see 'man crypt')
1494 $salt =~ s/\+/X/g;
1495
1496 return crypt(encode("utf8", $pw), "\$5\$$salt\$");
1497 }
1498
1499 1;