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