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