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