]> git.proxmox.com Git - pve-common.git/blame - src/PVE/Tools.pm
Fix #1188: tempfile: use /run by default
[pve-common.git] / src / PVE / Tools.pm
CommitLineData
e143e9d8
DM
1package PVE::Tools;
2
3use strict;
c36f332e 4use warnings;
ce338f4f 5use POSIX qw(EINTR EEXIST);
00dc9d0f 6use IO::Socket::IP;
a956854f 7use Socket qw(AF_INET AF_INET6 AI_ALL AI_V4MAPPED);
e143e9d8
DM
8use IO::Select;
9use File::Basename;
10use File::Path qw(make_path);
97c8c857
WB
11use Filesys::Df (); # don't overwrite our df()
12use IO::Pipe;
e143e9d8 13use IO::File;
7eb283fb 14use IO::Dir;
21c56a96 15use IO::Handle;
e143e9d8
DM
16use IPC::Open3;
17use Fcntl qw(:DEFAULT :flock);
18use base 'Exporter';
19use URI::Escape;
20use Encode;
568ba6a4 21use Digest::SHA;
e38bcd35 22use Text::ParseWords;
7514b23a 23use String::ShellQuote;
c38cea65 24use Time::HiRes qw(usleep gettimeofday tv_interval alarm);
0b9cf991
WB
25use Net::DBus qw(dbus_uint32 dbus_uint64);
26use Net::DBus::Callback;
27use Net::DBus::Reactor;
e143e9d8 28
57eeea0c
DM
29# avoid warning when parsing long hex values with hex()
30no warnings 'portable'; # Support for 64-bit ints required
31
e143e9d8 32our @EXPORT_OK = qw(
602ec0cd
DM
33$IPV6RE
34$IPV4RE
e143e9d8 35lock_file
493004a2 36lock_file_full
e143e9d8
DM
37run_command
38file_set_contents
39file_get_contents
40file_read_firstline
7eb283fb
DM
41dir_glob_regex
42dir_glob_foreach
e143e9d8
DM
43split_list
44template_replace
45safe_print
46trim
47extract_param
23e0e0d7 48file_copy
c0647765
WB
49O_PATH
50O_TMPFILE
e143e9d8
DM
51);
52
53my $pvelogdir = "/var/log/pve";
54my $pvetaskdir = "$pvelogdir/tasks";
55
56mkdir $pvelogdir;
57mkdir $pvetaskdir;
58
cd9bd252 59my $IPV4OCTET = "(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])";
602ec0cd
DM
60our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)";
61my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})";
62my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))";
63
64our $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
176b1186
WB
75our $IPRE = "(?:$IPV4RE|$IPV6RE)";
76
be8f0477 77use constant {CLONE_NEWNS => 0x00020000,
952fd95e
WB
78 CLONE_NEWUTS => 0x04000000,
79 CLONE_NEWIPC => 0x08000000,
80 CLONE_NEWUSER => 0x10000000,
81 CLONE_NEWPID => 0x20000000,
be8f0477 82 CLONE_NEWNET => 0x40000000};
952fd95e 83
26598a51
WB
84use constant {O_PATH => 0x00200000,
85 O_TMPFILE => 0x00410000}; # This includes O_DIRECTORY
44acb12c 86
0f0990f1
DM
87sub run_with_timeout {
88 my ($timeout, $code, @param) = @_;
e143e9d8 89
0f0990f1 90 die "got timeout\n" if $timeout <= 0;
e143e9d8 91
c38cea65 92 my $prev_alarm = alarm 0; # suspend outer alarm early
0f0990f1
DM
93
94 my $sigcount = 0;
e143e9d8
DM
95
96 my $res;
97
e143e9d8 98 eval {
0f0990f1
DM
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
e143e9d8 102
c38cea65 103 alarm($timeout);
e143e9d8 104
c38cea65 105 eval { $res = &$code(@param); };
0f0990f1
DM
106
107 alarm(0); # avoid race conditions
c38cea65
WB
108
109 die $@ if $@;
0f0990f1
DM
110 };
111
112 my $err = $@;
113
c38cea65 114 alarm $prev_alarm;
0f0990f1 115
c38cea65 116 # this shouldn't happen anymore?
0f0990f1
DM
117 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
118
119 die $err if $err;
120
121 return $res;
122}
e143e9d8 123
0f0990f1
DM
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
127my $lock_handles = {};
128
493004a2
DM
129sub lock_file_full {
130 my ($filename, $timeout, $shared, $code, @param) = @_;
0f0990f1
DM
131
132 $timeout = 10 if !$timeout;
133
493004a2
DM
134 my $mode = $shared ? LOCK_SH : LOCK_EX;
135
0f0990f1 136 my $lock_func = sub {
e143e9d8 137 if (!$lock_handles->{$$}->{$filename}) {
f127adab
FG
138 my $fh = new IO::File(">>$filename") ||
139 die "can't open file - $!\n";
140 $lock_handles->{$$}->{$filename} = { fh => $fh, refcount => 0};
e143e9d8
DM
141 }
142
f127adab 143 if (!flock($lock_handles->{$$}->{$filename}->{fh}, $mode|LOCK_NB)) {
b148e99f 144 print STDERR "trying to acquire lock...";
b5d12b08
DM
145 my $success;
146 while(1) {
f127adab 147 $success = flock($lock_handles->{$$}->{$filename}->{fh}, $mode);
b5d12b08
DM
148 # try again on EINTR (see bug #273)
149 if ($success || ($! != EINTR)) {
150 last;
151 }
152 }
153 if (!$success) {
e143e9d8 154 print STDERR " failed\n";
b148e99f 155 die "can't acquire lock '$filename' - $!\n";
e143e9d8
DM
156 }
157 print STDERR " OK\n";
158 }
f127adab 159 $lock_handles->{$$}->{$filename}->{refcount}++;
e143e9d8
DM
160 };
161
0f0990f1 162 my $res;
e143e9d8 163
0f0990f1
DM
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 }
e143e9d8 172
f127adab
FG
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 }
e143e9d8
DM
179 }
180
181 if ($err) {
182 $@ = $err;
183 return undef;
184 }
185
186 $@ = undef;
187
188 return $res;
189}
190
493004a2
DM
191
192sub lock_file {
193 my ($filename, $timeout, $code, @param) = @_;
194
195 return lock_file_full($filename, $timeout, 0, $code, @param);
196}
197
e143e9d8
DM
198sub file_set_contents {
199 my ($filename, $data, $perm) = @_;
200
201 $perm = 0644 if !defined($perm);
202
203 my $tmpname = "$filename.tmp.$$";
204
205 eval {
ce338f4f
WB
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 }
e143e9d8
DM
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
231sub 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
23e0e0d7
WL
244sub file_copy {
245 my ($filename, $dst, $max, $perm) = @_;
246
247 file_set_contents ($dst, file_get_contents($filename, $max), $perm);
248}
249
e143e9d8
DM
250sub file_read_firstline {
251 my ($filename) = @_;
252
253 my $fh = IO::File->new ($filename, "r");
254 return undef if !$fh;
255 my $res = <$fh>;
88955a2e 256 chomp $res if $res;
e143e9d8
DM
257 $fh->close;
258 return $res;
259}
260
261sub 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
bd9c3a36
WB
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.)
fcdc0cfc
WB
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
e143e9d8
DM
307sub run_command {
308 my ($cmd, %param) = @_;
309
310 my $old_umask;
ded47a61 311 my $cmdstr;
e143e9d8 312
fcdc0cfc
WB
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 }
1a0c0103 323 $cmd = [ '/bin/bash', '-c', "$cmdstr" ];
fcdc0cfc
WB
324 } else {
325 $cmdstr = cmd2string($cmd);
326 }
327 } else {
ded47a61 328 $cmdstr = $cmd;
22d4efe6 329 if ($cmd =~ m/\|/) {
e0cabd2c
DM
330 # see 'man bash' for option pipefail
331 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
332 } else {
333 $cmd = [ $cmd ];
334 }
ded47a61 335 }
e143e9d8
DM
336
337 my $errmsg;
338 my $laststderr;
339 my $timeout;
340 my $oldtimeout;
341 my $pid;
7e826928 342 my $exitcode;
e143e9d8 343
4630cb95
DM
344 my $outfunc;
345 my $errfunc;
346 my $logfunc;
347 my $input;
348 my $output;
a417477c 349 my $afterfork;
7e826928 350 my $noerr;
4630cb95 351
e143e9d8 352 eval {
e143e9d8
DM
353
354 foreach my $p (keys %param) {
355 if ($p eq 'timeout') {
356 $timeout = $param{$p};
357 } elsif ($p eq 'umask') {
eb9e24df 358 $old_umask = umask($param{$p});
e143e9d8
DM
359 } elsif ($p eq 'errmsg') {
360 $errmsg = $param{$p};
e143e9d8
DM
361 } elsif ($p eq 'input') {
362 $input = $param{$p};
1c50a24a
DM
363 } elsif ($p eq 'output') {
364 $output = $param{$p};
e143e9d8
DM
365 } elsif ($p eq 'outfunc') {
366 $outfunc = $param{$p};
367 } elsif ($p eq 'errfunc') {
368 $errfunc = $param{$p};
776fbfa8
DM
369 } elsif ($p eq 'logfunc') {
370 $logfunc = $param{$p};
a417477c
DM
371 } elsif ($p eq 'afterfork') {
372 $afterfork = $param{$p};
7e826928
TL
373 } elsif ($p eq 'noerr') {
374 $noerr = $param{$p};
e143e9d8
DM
375 } else {
376 die "got unknown parameter '$p' for run_command\n";
377 }
378 }
379
4630cb95
DM
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
1c50a24a
DM
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
e143e9d8
DM
398 # try to avoid locale related issues/warnings
399 my $lang = $param{lang} || 'C';
400
401 my $orig_pid = $$;
402
403 eval {
329351e2 404 local $ENV{LC_ALL} = $lang;
e143e9d8
DM
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 $!;
f38995ab
DM
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 }
e143e9d8
DM
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
a417477c
DM
435 &$afterfork() if $afterfork;
436
f38995ab
DM
437 if (ref($writer)) {
438 print $writer $input if defined $input;
439 close $writer;
440 }
e143e9d8
DM
441
442 my $select = new IO::Select;
f38995ab 443 $select->add($reader) if ref($reader);
e143e9d8
DM
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) {
776fbfa8 465 if ($outfunc || $logfunc) {
e143e9d8
DM
466 eval {
467 $outlog .= $buf;
468 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
469 my $line = $1;
776fbfa8
DM
470 &$outfunc($line) if $outfunc;
471 &$logfunc($line) if $logfunc;
e143e9d8
DM
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) {
776fbfa8 485 if ($errfunc || $logfunc) {
e143e9d8
DM
486 eval {
487 $errlog .= $buf;
488 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
489 my $line = $1;
776fbfa8
DM
490 &$errfunc($line) if $errfunc;
491 &$logfunc($line) if $logfunc;
e143e9d8
DM
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;
776fbfa8
DM
509 &$logfunc($outlog) if $logfunc && $outlog;
510
e143e9d8 511 &$errfunc($errlog) if $errfunc && $errlog;
776fbfa8 512 &$logfunc($errlog) if $logfunc && $errlog;
e143e9d8
DM
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";
7e826928
TL
520 } elsif ($exitcode = ($? >> 8)) {
521 if (!($exitcode == 24 && ($cmdstr =~ m|^(\S+/)?rsync\s|))) {
1c50a24a
DM
522 if ($errmsg && $laststderr) {
523 my $lerr = $laststderr;
524 $laststderr = undef;
525 die "$lerr\n";
526 }
7e826928 527 die "exit code $exitcode\n";
e143e9d8 528 }
e143e9d8
DM
529 }
530
531 alarm(0);
532 };
533
534 my $err = $@;
535
536 alarm(0);
537
4630cb95
DM
538 if ($errmsg && $laststderr) {
539 &$errfunc(undef); # flush laststderr
540 }
e143e9d8
DM
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) {
adbc988d 554 $err =~ s/^usermod:\s*// if $cmdstr =~ m|^(\S+/)?usermod\s|;
e143e9d8 555 die "$errmsg: $err";
7e826928 556 } elsif(!$noerr) {
e143e9d8
DM
557 die "command '$cmdstr' failed: $err";
558 }
559 }
1c50a24a 560
7e826928 561 return $exitcode;
e143e9d8
DM
562}
563
564sub split_list {
565 my $listtxt = shift || '';
566
d2b0374d
DM
567 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
568
569 $listtxt =~ s/[,;]/ /g;
e143e9d8
DM
570 $listtxt =~ s/^\s+//;
571
572 my @data = split (/\s+/, $listtxt);
573
574 return @data;
575}
576
577sub 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}"
589sub template_replace {
590 my ($tmpl, $data) = @_;
591
3250f5c7
DM
592 return $tmpl if !$tmpl;
593
e143e9d8
DM
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
602sub 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
612sub 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
910d57b0
DM
657my $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' ],
5a5ca434
DM
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 ],
910d57b0
DM
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],
9934cd0b 687 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
910d57b0 688 #'th' => [],
c10cc112 689 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
910d57b0
DM
690};
691
692my $kvmkeymaparray = [];
0a7de820 693foreach my $lc (sort keys %$keymaphash) {
910d57b0
DM
694 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
695}
696
e143e9d8 697sub kvmkeymaps {
910d57b0
DM
698 return $keymaphash;
699}
700
701sub kvmkeymaplist {
702 return $kvmkeymaparray;
e143e9d8
DM
703}
704
705sub extract_param {
706 my ($param, $key) = @_;
707
708 my $res = $param->{$key};
709 delete $param->{$key};
710
711 return $res;
712}
713
eb7047f6 714# Note: we use this to wait until vncterm/spiceterm is ready
ec6d95b4
DM
715sub wait_for_vnc_port {
716 my ($port, $timeout) = @_;
717
718 $timeout = 5 if !$timeout;
eb7047f6
DM
719 my $sleeptime = 0;
720 my $starttime = [gettimeofday];
721 my $elapsed;
ec6d95b4 722
eb7047f6 723 while (($elapsed = tv_interval($starttime)) < $timeout) {
ec6d95b4
DM
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 }
eb7047f6
DM
735 $sleeptime += 100000 if $sleeptime < 1000000;
736 usleep($sleeptime);
ec6d95b4
DM
737 }
738
739 return undef;
740}
741
59b3f563 742sub next_unused_port {
46775218 743 my ($range_start, $range_end, $family) = @_;
59b3f563
DM
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";
e143e9d8 751
59b3f563 752 my $code = sub {
e143e9d8 753
59b3f563
DM
754 my $expiretime = 5;
755 my $ctime = time();
e143e9d8 756
59b3f563
DM
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 }
e143e9d8 768 }
59b3f563
DM
769
770 my $newport;
771
772 for (my $p = $range_start; $p < $range_end; $p++) {
773 next if $ports->{$p}; # reserved
774
00dc9d0f 775 my $sock = IO::Socket::IP->new(Listen => 5,
00dc9d0f
WB
776 LocalPort => $p,
777 ReuseAddr => 1,
46775218 778 Family => $family,
e43b3a0f
WB
779 Proto => 0,
780 GetAddrInfoFlags => 0);
59b3f563
DM
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);
e143e9d8 796
59b3f563
DM
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
808sub next_migrate_port {
46775218
WB
809 my ($family) = @_;
810 return next_unused_port(60000, 60050, $family);
59b3f563
DM
811}
812
813sub next_vnc_port {
46775218
WB
814 my ($family) = @_;
815 return next_unused_port(5900, 6000, $family);
59b3f563 816}
e143e9d8 817
2f13cbb5 818sub next_spice_port {
46775218
WB
819 my ($family) = @_;
820 return next_unused_port(61000, 61099, $family);
2f13cbb5
DM
821}
822
e143e9d8
DM
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"
97c8c857 826# So fork() before using Filesys::Df
e143e9d8
DM
827sub df {
828 my ($path, $timeout) = @_;
829
e143e9d8
DM
830 my $res = {
831 total => 0,
832 used => 0,
833 avail => 0,
834 };
835
97c8c857
WB
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);
e143e9d8 853 }
97c8c857
WB
854 POSIX::_exit(0);
855 }
856
857 $pipe->reader();
858
859 my $readvalues = sub {
28705ff6
WB
860 $res->{total} = int((<$pipe> =~ /^(\d*)$/)[0]);
861 $res->{used} = int((<$pipe> =~ /^(\d*)$/)[0]);
862 $res->{avail} = int((<$pipe> =~ /^(\d*)$/)[0]);
97c8c857
WB
863 };
864 eval {
865 run_with_timeout($timeout, $readvalues);
e143e9d8 866 };
e143e9d8 867 warn $@ if $@;
97c8c857
WB
868 $pipe->close();
869 kill('KILL', $child);
870 waitpid($child, 0);
e143e9d8
DM
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
879sub upid_encode {
880 my $d = shift;
881
19cec230
DM
882 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
883 # more that 8 characters for pstart
e143e9d8
DM
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
889sub upid_decode {
890 my ($upid, $noerr) = @_;
891
892 my $res;
893 my $filename;
894
895 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
19cec230
DM
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]+):$/) {
e143e9d8 898 $res->{node} = $1;
3702f038
DM
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);
e143e9d8
DM
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
917sub 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";
2b8e0f12 932 chown $wwwid, -1, $outfh;
e143e9d8
DM
933
934 return $outfh;
935};
936
937sub 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;
cc9121d3 943 my $maxlen = 4096;
e143e9d8
DM
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
964sub 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
972sub decode_text {
973 my ($data) = @_;
974
975 return Encode::decode("utf8", uri_unescape($data));
976}
977
815b2aba
DM
978sub decode_utf8_parameters {
979 my ($param) = @_;
980
34ebb226 981 foreach my $p (qw(comment description firstname lastname)) {
815b2aba
DM
982 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
983 }
984
985 return $param;
986}
987
a413a515 988sub random_ether_addr {
12392173 989 my ($prefix) = @_;
a413a515 990
46a11c00
DM
991 my ($seconds, $microseconds) = gettimeofday;
992
d743b69c 993 my $rand = Digest::SHA::sha1($$, rand(), $seconds, $microseconds);
a413a515 994
85d5625a 995 # clear multicast, set local id
de9a267f 996 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
a413a515 997
12392173
WB
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;
a413a515 1003}
e143e9d8 1004
762e3223
DM
1005sub shellquote {
1006 my $str = shift;
1007
7514b23a 1008 return String::ShellQuote::shell_quote($str);
762e3223
DM
1009}
1010
65e1d3fc
DM
1011sub 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
e38bcd35 1024# split an shell argument string into an array,
f9125663
DM
1025sub split_args {
1026 my ($str) = @_;
1027
e38bcd35 1028 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
f9125663
DM
1029}
1030
804b1041 1031sub dump_logfile {
eb7e5538 1032 my ($filename, $start, $limit, $filter) = @_;
804b1041
DM
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;
eb7e5538
DM
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 }
804b1041
DM
1067 }
1068
1069 close($fh);
1070
6de95a66
DM
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
1081sub dump_journal {
19e95cd0 1082 my ($start, $limit, $since, $until) = @_;
6de95a66
DM
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'];
19e95cd0
TL
1100
1101 push @$cmd, '--since', $since if $since;
1102 push @$cmd, '--until', $until if $until;
6de95a66
DM
1103 run_command($cmd, outfunc => $parser);
1104
804b1041
DM
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
7eb283fb
DM
1115sub 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
1132sub 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
a345b9d5
DM
1145sub assert_if_modified {
1146 my ($digest1, $digest2) = @_;
1147
1148 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
212fc0b7 1149 die "detected modified configuration - file changed by other user? Try again.\n";
a345b9d5
DM
1150 }
1151}
1152
2d3bca34
DM
1153# Digest for short strings
1154# like FNV32a, but we only return 31 bits (positive numbers)
1155sub 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
1173sub fnv31a_hex { return sprintf("%X", fnv31a(@_)); }
1174
8df6b794
WB
1175sub 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
a0b6ef52
WB
1183sub getaddrinfo_all {
1184 my ($hostname, @opts) = @_;
a956854f 1185 my %hints = ( flags => AI_V4MAPPED | AI_ALL,
a0b6ef52 1186 @opts );
a956854f 1187 my ($err, @res) = Socket::getaddrinfo($hostname, '0', \%hints);
a0b6ef52
WB
1188 die "failed to get address info for: $hostname: $err\n" if $err;
1189 return @res;
1190}
a956854f 1191
a0b6ef52
WB
1192sub get_host_address_family {
1193 my ($hostname, $socktype) = @_;
1194 my @res = getaddrinfo_all($hostname, socktype => $socktype);
1195 return $res[0]->{family};
a956854f
WB
1196}
1197
b2613777
WB
1198# Parses any sane kind of host, or host+port pair:
1199# The port is always optional and thus may be undef.
1200sub 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
817c6be0 1211sub unshare($) {
952fd95e 1212 my ($flags) = @_;
817c6be0 1213 return 0 == syscall(272, $flags);
952fd95e
WB
1214}
1215
891b224a
WB
1216sub setns($$) {
1217 my ($fileno, $nstype) = @_;
1218 return 0 == syscall(308, $fileno, $nstype);
1219}
1220
44acb12c
WB
1221sub syncfs($) {
1222 my ($fileno) = @_;
1223 return 0 == syscall(306, $fileno);
1224}
1225
1226sub 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
b61a47db
TL
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
1236sub sendmail {
1237 my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_;
c9c6d910 1238 my $mail_re = qr/[^-a-zA-Z0-9+._@]/;
b61a47db 1239
5a873e6d 1240 $mailto = [ $mailto ] if !ref($mailto);
b61a47db 1241
c9c6d910
FG
1242 foreach (@$mailto) {
1243 die "illegal character in mailto address\n"
1244 if ($_ =~ $mail_re);
b61a47db 1245 }
c9c6d910 1246
b61a47db
TL
1247 my $rcvrtxt = join (', ', @$mailto);
1248
1249 $mailfrom = $mailfrom || "root";
c9c6d910
FG
1250 die "illegal character in mailfrom address\n"
1251 if $mailfrom =~ $mail_re;
1252
5a873e6d 1253 $author = $author || 'Proxmox VE';
b61a47db 1254
c9c6d910 1255 open (MAIL, "|-", "sendmail", "-B", "8BITMIME", "-f", $mailfrom, @$mailto) ||
b61a47db
TL
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
5a873e6d 1272 if (defined($text)) {
b61a47db
TL
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
5a873e6d 1287 if (defined($html)) {
b61a47db
TL
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);
b61a47db
TL
1299}
1300
26598a51
WB
1301sub tempfile {
1302 my ($perm, %opts) = @_;
1303
1304 # default permissions are stricter than with file_set_contents
1305 $perm = 0600 if !defined($perm);
1306
f0cfc20e 1307 my $dir = $opts{dir} // '/run';
26598a51
WB
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
1316sub 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
48df47a4
FG
1332sub 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
21c56a96
WB
1347sub 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
1362sub mkdirat($$$) {
1363 my ($dirfd, $name, $mode) = @_;
1364 return syscall(258, $dirfd, $name, $mode) == 0;
1365}
1366
0b9cf991
WB
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.
1373sub 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
e143e9d8 14381;