]> git.proxmox.com Git - pve-common.git/blame - src/PVE/Tools.pm
bump version to 4.0-71
[pve-common.git] / src / PVE / Tools.pm
CommitLineData
e143e9d8
DM
1package PVE::Tools;
2
3use strict;
c36f332e 4use warnings;
b5d12b08 5use POSIX qw(EINTR);
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 {
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
225sub 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
23e0e0d7
WL
238sub file_copy {
239 my ($filename, $dst, $max, $perm) = @_;
240
241 file_set_contents ($dst, file_get_contents($filename, $max), $perm);
242}
243
e143e9d8
DM
244sub file_read_firstline {
245 my ($filename) = @_;
246
247 my $fh = IO::File->new ($filename, "r");
248 return undef if !$fh;
249 my $res = <$fh>;
88955a2e 250 chomp $res if $res;
e143e9d8
DM
251 $fh->close;
252 return $res;
253}
254
255sub 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
bd9c3a36
WB
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.)
fcdc0cfc
WB
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
e143e9d8
DM
301sub run_command {
302 my ($cmd, %param) = @_;
303
304 my $old_umask;
ded47a61 305 my $cmdstr;
e143e9d8 306
fcdc0cfc
WB
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 }
1a0c0103 317 $cmd = [ '/bin/bash', '-c', "$cmdstr" ];
fcdc0cfc
WB
318 } else {
319 $cmdstr = cmd2string($cmd);
320 }
321 } else {
ded47a61 322 $cmdstr = $cmd;
22d4efe6 323 if ($cmd =~ m/\|/) {
e0cabd2c
DM
324 # see 'man bash' for option pipefail
325 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
326 } else {
327 $cmd = [ $cmd ];
328 }
ded47a61 329 }
e143e9d8
DM
330
331 my $errmsg;
332 my $laststderr;
333 my $timeout;
334 my $oldtimeout;
335 my $pid;
7e826928 336 my $exitcode;
e143e9d8 337
4630cb95
DM
338 my $outfunc;
339 my $errfunc;
340 my $logfunc;
341 my $input;
342 my $output;
a417477c 343 my $afterfork;
7e826928 344 my $noerr;
4630cb95 345
e143e9d8 346 eval {
e143e9d8
DM
347
348 foreach my $p (keys %param) {
349 if ($p eq 'timeout') {
350 $timeout = $param{$p};
351 } elsif ($p eq 'umask') {
eb9e24df 352 $old_umask = umask($param{$p});
e143e9d8
DM
353 } elsif ($p eq 'errmsg') {
354 $errmsg = $param{$p};
e143e9d8
DM
355 } elsif ($p eq 'input') {
356 $input = $param{$p};
1c50a24a
DM
357 } elsif ($p eq 'output') {
358 $output = $param{$p};
e143e9d8
DM
359 } elsif ($p eq 'outfunc') {
360 $outfunc = $param{$p};
361 } elsif ($p eq 'errfunc') {
362 $errfunc = $param{$p};
776fbfa8
DM
363 } elsif ($p eq 'logfunc') {
364 $logfunc = $param{$p};
a417477c
DM
365 } elsif ($p eq 'afterfork') {
366 $afterfork = $param{$p};
7e826928
TL
367 } elsif ($p eq 'noerr') {
368 $noerr = $param{$p};
e143e9d8
DM
369 } else {
370 die "got unknown parameter '$p' for run_command\n";
371 }
372 }
373
4630cb95
DM
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
1c50a24a
DM
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
e143e9d8
DM
392 # try to avoid locale related issues/warnings
393 my $lang = $param{lang} || 'C';
394
395 my $orig_pid = $$;
396
397 eval {
329351e2 398 local $ENV{LC_ALL} = $lang;
e143e9d8
DM
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 $!;
f38995ab
DM
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 }
e143e9d8
DM
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
a417477c
DM
429 &$afterfork() if $afterfork;
430
f38995ab
DM
431 if (ref($writer)) {
432 print $writer $input if defined $input;
433 close $writer;
434 }
e143e9d8
DM
435
436 my $select = new IO::Select;
f38995ab 437 $select->add($reader) if ref($reader);
e143e9d8
DM
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) {
776fbfa8 459 if ($outfunc || $logfunc) {
e143e9d8
DM
460 eval {
461 $outlog .= $buf;
462 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
463 my $line = $1;
776fbfa8
DM
464 &$outfunc($line) if $outfunc;
465 &$logfunc($line) if $logfunc;
e143e9d8
DM
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) {
776fbfa8 479 if ($errfunc || $logfunc) {
e143e9d8
DM
480 eval {
481 $errlog .= $buf;
482 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
483 my $line = $1;
776fbfa8
DM
484 &$errfunc($line) if $errfunc;
485 &$logfunc($line) if $logfunc;
e143e9d8
DM
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;
776fbfa8
DM
503 &$logfunc($outlog) if $logfunc && $outlog;
504
e143e9d8 505 &$errfunc($errlog) if $errfunc && $errlog;
776fbfa8 506 &$logfunc($errlog) if $logfunc && $errlog;
e143e9d8
DM
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";
7e826928
TL
514 } elsif ($exitcode = ($? >> 8)) {
515 if (!($exitcode == 24 && ($cmdstr =~ m|^(\S+/)?rsync\s|))) {
1c50a24a
DM
516 if ($errmsg && $laststderr) {
517 my $lerr = $laststderr;
518 $laststderr = undef;
519 die "$lerr\n";
520 }
7e826928 521 die "exit code $exitcode\n";
e143e9d8 522 }
e143e9d8
DM
523 }
524
525 alarm(0);
526 };
527
528 my $err = $@;
529
530 alarm(0);
531
4630cb95
DM
532 if ($errmsg && $laststderr) {
533 &$errfunc(undef); # flush laststderr
534 }
e143e9d8
DM
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) {
adbc988d 548 $err =~ s/^usermod:\s*// if $cmdstr =~ m|^(\S+/)?usermod\s|;
e143e9d8 549 die "$errmsg: $err";
7e826928 550 } elsif(!$noerr) {
e143e9d8
DM
551 die "command '$cmdstr' failed: $err";
552 }
553 }
1c50a24a 554
7e826928 555 return $exitcode;
e143e9d8
DM
556}
557
558sub split_list {
559 my $listtxt = shift || '';
560
d2b0374d
DM
561 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
562
563 $listtxt =~ s/[,;]/ /g;
e143e9d8
DM
564 $listtxt =~ s/^\s+//;
565
566 my @data = split (/\s+/, $listtxt);
567
568 return @data;
569}
570
571sub 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}"
583sub template_replace {
584 my ($tmpl, $data) = @_;
585
3250f5c7
DM
586 return $tmpl if !$tmpl;
587
e143e9d8
DM
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
596sub 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
606sub 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
910d57b0
DM
651my $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' ],
5a5ca434
DM
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 ],
910d57b0
DM
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],
9934cd0b 681 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
910d57b0 682 #'th' => [],
c10cc112 683 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
910d57b0
DM
684};
685
686my $kvmkeymaparray = [];
0a7de820 687foreach my $lc (sort keys %$keymaphash) {
910d57b0
DM
688 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
689}
690
e143e9d8 691sub kvmkeymaps {
910d57b0
DM
692 return $keymaphash;
693}
694
695sub kvmkeymaplist {
696 return $kvmkeymaparray;
e143e9d8
DM
697}
698
699sub extract_param {
700 my ($param, $key) = @_;
701
702 my $res = $param->{$key};
703 delete $param->{$key};
704
705 return $res;
706}
707
eb7047f6 708# Note: we use this to wait until vncterm/spiceterm is ready
ec6d95b4
DM
709sub wait_for_vnc_port {
710 my ($port, $timeout) = @_;
711
712 $timeout = 5 if !$timeout;
eb7047f6
DM
713 my $sleeptime = 0;
714 my $starttime = [gettimeofday];
715 my $elapsed;
ec6d95b4 716
eb7047f6 717 while (($elapsed = tv_interval($starttime)) < $timeout) {
ec6d95b4
DM
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 }
eb7047f6
DM
729 $sleeptime += 100000 if $sleeptime < 1000000;
730 usleep($sleeptime);
ec6d95b4
DM
731 }
732
733 return undef;
734}
735
59b3f563 736sub next_unused_port {
46775218 737 my ($range_start, $range_end, $family) = @_;
59b3f563
DM
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";
e143e9d8 745
59b3f563 746 my $code = sub {
e143e9d8 747
59b3f563
DM
748 my $expiretime = 5;
749 my $ctime = time();
e143e9d8 750
59b3f563
DM
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 }
e143e9d8 762 }
59b3f563
DM
763
764 my $newport;
765
766 for (my $p = $range_start; $p < $range_end; $p++) {
767 next if $ports->{$p}; # reserved
768
00dc9d0f 769 my $sock = IO::Socket::IP->new(Listen => 5,
00dc9d0f
WB
770 LocalPort => $p,
771 ReuseAddr => 1,
46775218 772 Family => $family,
e43b3a0f
WB
773 Proto => 0,
774 GetAddrInfoFlags => 0);
59b3f563
DM
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);
e143e9d8 790
59b3f563
DM
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
802sub next_migrate_port {
46775218
WB
803 my ($family) = @_;
804 return next_unused_port(60000, 60050, $family);
59b3f563
DM
805}
806
807sub next_vnc_port {
46775218
WB
808 my ($family) = @_;
809 return next_unused_port(5900, 6000, $family);
59b3f563 810}
e143e9d8 811
2f13cbb5 812sub next_spice_port {
46775218
WB
813 my ($family) = @_;
814 return next_unused_port(61000, 61099, $family);
2f13cbb5
DM
815}
816
e143e9d8
DM
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"
97c8c857 820# So fork() before using Filesys::Df
e143e9d8
DM
821sub df {
822 my ($path, $timeout) = @_;
823
e143e9d8
DM
824 my $res = {
825 total => 0,
826 used => 0,
827 avail => 0,
828 };
829
97c8c857
WB
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);
e143e9d8 847 }
97c8c857
WB
848 POSIX::_exit(0);
849 }
850
851 $pipe->reader();
852
853 my $readvalues = sub {
28705ff6
WB
854 $res->{total} = int((<$pipe> =~ /^(\d*)$/)[0]);
855 $res->{used} = int((<$pipe> =~ /^(\d*)$/)[0]);
856 $res->{avail} = int((<$pipe> =~ /^(\d*)$/)[0]);
97c8c857
WB
857 };
858 eval {
859 run_with_timeout($timeout, $readvalues);
e143e9d8 860 };
e143e9d8 861 warn $@ if $@;
97c8c857
WB
862 $pipe->close();
863 kill('KILL', $child);
864 waitpid($child, 0);
e143e9d8
DM
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
873sub upid_encode {
874 my $d = shift;
875
19cec230
DM
876 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
877 # more that 8 characters for pstart
e143e9d8
DM
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
883sub upid_decode {
884 my ($upid, $noerr) = @_;
885
886 my $res;
887 my $filename;
888
889 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
19cec230
DM
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]+):$/) {
e143e9d8 892 $res->{node} = $1;
3702f038
DM
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);
e143e9d8
DM
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
911sub 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";
2b8e0f12 926 chown $wwwid, -1, $outfh;
e143e9d8
DM
927
928 return $outfh;
929};
930
931sub 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;
cc9121d3 937 my $maxlen = 4096;
e143e9d8
DM
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
958sub 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
966sub decode_text {
967 my ($data) = @_;
968
969 return Encode::decode("utf8", uri_unescape($data));
970}
971
815b2aba
DM
972sub decode_utf8_parameters {
973 my ($param) = @_;
974
34ebb226 975 foreach my $p (qw(comment description firstname lastname)) {
815b2aba
DM
976 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
977 }
978
979 return $param;
980}
981
a413a515
DM
982sub random_ether_addr {
983
46a11c00
DM
984 my ($seconds, $microseconds) = gettimeofday;
985
d743b69c 986 my $rand = Digest::SHA::sha1($$, rand(), $seconds, $microseconds);
a413a515 987
85d5625a 988 # clear multicast, set local id
de9a267f 989 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
a413a515 990
85d5625a 991 return sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
a413a515 992}
e143e9d8 993
762e3223
DM
994sub shellquote {
995 my $str = shift;
996
7514b23a 997 return String::ShellQuote::shell_quote($str);
762e3223
DM
998}
999
65e1d3fc
DM
1000sub cmd2string {
1001 my ($cmd) = @_;
1002
1003 die "no arguments" if !$cmd;
1004
1005 return $cmd if !ref($cmd);
1006
1007 my @qa = ();
1008 foreach my $arg (@$cmd) { push @qa, shellquote($arg); }
1009
1010 return join (' ', @qa);
1011}
1012
e38bcd35 1013# split an shell argument string into an array,
f9125663
DM
1014sub split_args {
1015 my ($str) = @_;
1016
e38bcd35 1017 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
f9125663
DM
1018}
1019
804b1041 1020sub dump_logfile {
eb7e5538 1021 my ($filename, $start, $limit, $filter) = @_;
804b1041
DM
1022
1023 my $lines = [];
1024 my $count = 0;
1025
1026 my $fh = IO::File->new($filename, "r");
1027 if (!$fh) {
1028 $count++;
1029 push @$lines, { n => $count, t => "unable to open file - $!"};
1030 return ($count, $lines);
1031 }
1032
1033 $start = 0 if !$start;
1034 $limit = 50 if !$limit;
1035
1036 my $line;
eb7e5538
DM
1037
1038 if ($filter) {
1039 # duplicate code, so that we do not slow down normal path
1040 while (defined($line = <$fh>)) {
1041 next if $line !~ m/$filter/;
1042 next if $count++ < $start;
1043 next if $limit <= 0;
1044 chomp $line;
1045 push @$lines, { n => $count, t => $line};
1046 $limit--;
1047 }
1048 } else {
1049 while (defined($line = <$fh>)) {
1050 next if $count++ < $start;
1051 next if $limit <= 0;
1052 chomp $line;
1053 push @$lines, { n => $count, t => $line};
1054 $limit--;
1055 }
804b1041
DM
1056 }
1057
1058 close($fh);
1059
6de95a66
DM
1060 # HACK: ExtJS store.guaranteeRange() does not like empty array
1061 # so we add a line
1062 if (!$count) {
1063 $count++;
1064 push @$lines, { n => $count, t => "no content"};
1065 }
1066
1067 return ($count, $lines);
1068}
1069
1070sub dump_journal {
19e95cd0 1071 my ($start, $limit, $since, $until) = @_;
6de95a66
DM
1072
1073 my $lines = [];
1074 my $count = 0;
1075
1076 $start = 0 if !$start;
1077 $limit = 50 if !$limit;
1078
1079 my $parser = sub {
1080 my $line = shift;
1081
1082 return if $count++ < $start;
1083 return if $limit <= 0;
1084 push @$lines, { n => int($count), t => $line};
1085 $limit--;
1086 };
1087
1088 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
19e95cd0
TL
1089
1090 push @$cmd, '--since', $since if $since;
1091 push @$cmd, '--until', $until if $until;
6de95a66
DM
1092 run_command($cmd, outfunc => $parser);
1093
804b1041
DM
1094 # HACK: ExtJS store.guaranteeRange() does not like empty array
1095 # so we add a line
1096 if (!$count) {
1097 $count++;
1098 push @$lines, { n => $count, t => "no content"};
1099 }
1100
1101 return ($count, $lines);
1102}
1103
7eb283fb
DM
1104sub dir_glob_regex {
1105 my ($dir, $regex) = @_;
1106
1107 my $dh = IO::Dir->new ($dir);
1108 return wantarray ? () : undef if !$dh;
1109
1110 while (defined(my $tmp = $dh->read)) {
1111 if (my @res = $tmp =~ m/^($regex)$/) {
1112 $dh->close;
1113 return wantarray ? @res : $tmp;
1114 }
1115 }
1116 $dh->close;
1117
1118 return wantarray ? () : undef;
1119}
1120
1121sub dir_glob_foreach {
1122 my ($dir, $regex, $func) = @_;
1123
1124 my $dh = IO::Dir->new ($dir);
1125 if (defined $dh) {
1126 while (defined(my $tmp = $dh->read)) {
1127 if (my @res = $tmp =~ m/^($regex)$/) {
1128 &$func (@res);
1129 }
1130 }
1131 }
1132}
1133
a345b9d5
DM
1134sub assert_if_modified {
1135 my ($digest1, $digest2) = @_;
1136
1137 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
212fc0b7 1138 die "detected modified configuration - file changed by other user? Try again.\n";
a345b9d5
DM
1139 }
1140}
1141
2d3bca34
DM
1142# Digest for short strings
1143# like FNV32a, but we only return 31 bits (positive numbers)
1144sub fnv31a {
1145 my ($string) = @_;
1146
1147 my $hval = 0x811c9dc5;
1148
1149 foreach my $c (unpack('C*', $string)) {
1150 $hval ^= $c;
1151 $hval += (
1152 (($hval << 1) ) +
1153 (($hval << 4) ) +
1154 (($hval << 7) ) +
1155 (($hval << 8) ) +
1156 (($hval << 24) ) );
1157 $hval = $hval & 0xffffffff;
1158 }
1159 return $hval & 0x7fffffff;
1160}
1161
1162sub fnv31a_hex { return sprintf("%X", fnv31a(@_)); }
1163
8df6b794
WB
1164sub unpack_sockaddr_in46 {
1165 my ($sin) = @_;
1166 my $family = Socket::sockaddr_family($sin);
1167 my ($port, $host) = ($family == AF_INET6 ? Socket::unpack_sockaddr_in6($sin)
1168 : Socket::unpack_sockaddr_in($sin));
1169 return ($family, $port, $host);
1170}
1171
a0b6ef52
WB
1172sub getaddrinfo_all {
1173 my ($hostname, @opts) = @_;
a956854f 1174 my %hints = ( flags => AI_V4MAPPED | AI_ALL,
a0b6ef52 1175 @opts );
a956854f 1176 my ($err, @res) = Socket::getaddrinfo($hostname, '0', \%hints);
a0b6ef52
WB
1177 die "failed to get address info for: $hostname: $err\n" if $err;
1178 return @res;
1179}
a956854f 1180
a0b6ef52
WB
1181sub get_host_address_family {
1182 my ($hostname, $socktype) = @_;
1183 my @res = getaddrinfo_all($hostname, socktype => $socktype);
1184 return $res[0]->{family};
a956854f
WB
1185}
1186
b2613777
WB
1187# Parses any sane kind of host, or host+port pair:
1188# The port is always optional and thus may be undef.
1189sub parse_host_and_port {
1190 my ($address) = @_;
1191 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1192 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1193 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1194 {
1195 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1196 }
1197 return; # nothing
1198}
1199
817c6be0 1200sub unshare($) {
952fd95e 1201 my ($flags) = @_;
817c6be0 1202 return 0 == syscall(272, $flags);
952fd95e
WB
1203}
1204
891b224a
WB
1205sub setns($$) {
1206 my ($fileno, $nstype) = @_;
1207 return 0 == syscall(308, $fileno, $nstype);
1208}
1209
44acb12c
WB
1210sub syncfs($) {
1211 my ($fileno) = @_;
1212 return 0 == syscall(306, $fileno);
1213}
1214
1215sub sync_mountpoint {
1216 my ($path) = @_;
1217 sysopen my $fd, $path, O_PATH or die "failed to open $path: $!\n";
1218 my $result = syncfs(fileno($fd));
1219 close($fd);
1220 return $result;
1221}
1222
b61a47db
TL
1223# support sending multi-part mail messages with a text and or a HTML part
1224# mailto may be a single email string or an array of receivers
1225sub sendmail {
1226 my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_;
c9c6d910 1227 my $mail_re = qr/[^-a-zA-Z0-9+._@]/;
b61a47db 1228
5a873e6d 1229 $mailto = [ $mailto ] if !ref($mailto);
b61a47db 1230
c9c6d910
FG
1231 foreach (@$mailto) {
1232 die "illegal character in mailto address\n"
1233 if ($_ =~ $mail_re);
b61a47db 1234 }
c9c6d910 1235
b61a47db
TL
1236 my $rcvrtxt = join (', ', @$mailto);
1237
1238 $mailfrom = $mailfrom || "root";
c9c6d910
FG
1239 die "illegal character in mailfrom address\n"
1240 if $mailfrom =~ $mail_re;
1241
5a873e6d 1242 $author = $author || 'Proxmox VE';
b61a47db 1243
c9c6d910 1244 open (MAIL, "|-", "sendmail", "-B", "8BITMIME", "-f", $mailfrom, @$mailto) ||
b61a47db
TL
1245 die "unable to open 'sendmail' - $!";
1246
1247 # multipart spec see https://www.ietf.org/rfc/rfc1521.txt
1248 my $boundary = "----_=_NextPart_001_".int(time).$$;
1249
1250 print MAIL "Content-Type: multipart/alternative;\n";
1251 print MAIL "\tboundary=\"$boundary\"\n";
1252 print MAIL "MIME-Version: 1.0\n";
1253
1254 print MAIL "FROM: $author <$mailfrom>\n";
1255 print MAIL "TO: $rcvrtxt\n";
1256 print MAIL "SUBJECT: $subject\n";
1257 print MAIL "\n";
1258 print MAIL "This is a multi-part message in MIME format.\n\n";
1259 print MAIL "--$boundary\n";
1260
5a873e6d 1261 if (defined($text)) {
b61a47db
TL
1262 print MAIL "Content-Type: text/plain;\n";
1263 print MAIL "\tcharset=\"UTF8\"\n";
1264 print MAIL "Content-Transfer-Encoding: 8bit\n";
1265 print MAIL "\n";
1266
1267 # avoid 'remove extra line breaks' issue (MS Outlook)
1268 my $fill = ' ';
1269 $text =~ s/^/$fill/gm;
1270
1271 print MAIL $text;
1272
1273 print MAIL "\n--$boundary\n";
1274 }
1275
5a873e6d 1276 if (defined($html)) {
b61a47db
TL
1277 print MAIL "Content-Type: text/html;\n";
1278 print MAIL "\tcharset=\"UTF8\"\n";
1279 print MAIL "Content-Transfer-Encoding: 8bit\n";
1280 print MAIL "\n";
1281
1282 print MAIL $html;
1283
1284 print MAIL "\n--$boundary--\n";
1285 }
1286
1287 close(MAIL);
b61a47db
TL
1288}
1289
26598a51
WB
1290sub tempfile {
1291 my ($perm, %opts) = @_;
1292
1293 # default permissions are stricter than with file_set_contents
1294 $perm = 0600 if !defined($perm);
1295
1296 my $dir = $opts{dir} // '/tmp';
1297 my $mode = $opts{mode} // O_RDWR;
1298 $mode |= O_EXCL if !$opts{allow_links};
1299
1300 my $fh = IO::File->new($dir, $mode | O_TMPFILE, $perm)
1301 or die "failed to create tempfile: $!\n";
1302 return $fh;
1303}
1304
1305sub tempfile_contents {
1306 my ($data, $perm, %opts) = @_;
1307
1308 my $fh = tempfile($perm, %opts);
1309 eval {
1310 die "unable to write to tempfile: $!\n" if !print {$fh} $data;
1311 die "unable to flush to tempfile: $!\n" if !defined($fh->flush());
1312 };
1313 if (my $err = $@) {
1314 close $fh;
1315 die $err;
1316 }
1317
1318 return ("/proc/$$/fd/".$fh->fileno, $fh);
1319}
1320
48df47a4
FG
1321sub validate_ssh_public_keys {
1322 my ($raw) = @_;
1323 my @lines = split(/\n/, $raw);
1324
1325 foreach my $line (@lines) {
1326 next if $line =~ m/^\s*$/;
1327 eval {
1328 my ($filename, $handle) = tempfile_contents($line);
1329 run_command(["ssh-keygen", "-l", "-f", $filename],
1330 outfunc => sub {}, errfunc => sub {});
1331 };
1332 die "SSH public key validation error\n" if $@;
1333 }
1334}
1335
21c56a96
WB
1336sub openat($$$;$) {
1337 my ($dirfd, $pathname, $flags, $mode) = @_;
1338 my $fd = syscall(257, $dirfd, $pathname, $flags, $mode//0);
1339 return undef if $fd < 0;
1340 # sysopen() doesn't deal with numeric file descriptors apparently
1341 # so we need to convert to a mode string for IO::Handle->new_from_fd
1342 my $flagstr = ($flags & O_RDWR) ? 'rw' : ($flags & O_WRONLY) ? 'w' : 'r';
1343 my $handle = IO::Handle->new_from_fd($fd, $flagstr);
1344 return $handle if $handle;
1345 my $err = $!; # save error before closing the raw fd
1346 syscall(3, $fd); # close
1347 $! = $err;
1348 return undef;
1349}
1350
1351sub mkdirat($$$) {
1352 my ($dirfd, $name, $mode) = @_;
1353 return syscall(258, $dirfd, $name, $mode) == 0;
1354}
1355
0b9cf991
WB
1356# NOTE: This calls the dbus main loop and must not be used when another dbus
1357# main loop is being used as we need to wait for the JobRemoved signal.
1358# Polling the job status instead doesn't work because this doesn't give us the
1359# distinction between success and failure.
1360#
1361# Note that the description is mandatory for security reasons.
1362sub enter_systemd_scope {
1363 my ($unit, $description, %extra) = @_;
1364 die "missing description\n" if !defined($description);
1365
1366 my $timeout = delete $extra{timeout};
1367
1368 $unit .= '.scope';
1369 my $properties = [ [PIDs => [dbus_uint32($$)]] ];
1370
1371 foreach my $key (keys %extra) {
1372 if ($key eq 'Slice' || $key eq 'KillMode') {
1373 push @$properties, [$key, $extra{$key}];
1374 } elsif ($key eq 'CPUShares') {
1375 push @$properties, [$key, dbus_uint64($extra{$key})];
1376 } elsif ($key eq 'CPUQuota') {
1377 push @$properties, ['CPUQuotaPerSecUSec',
1378 dbus_uint64($extra{$key} * 10000)];
1379 } else {
1380 die "Don't know how to encode $key for systemd scope\n";
1381 }
1382 }
1383
1384 my $job;
1385 my $done = 0;
1386
1387 my $bus = Net::DBus->system();
1388 my $reactor = Net::DBus::Reactor->main();
1389
1390 my $service = $bus->get_service('org.freedesktop.systemd1');
1391 my $if = $service->get_object('/org/freedesktop/systemd1', 'org.freedesktop.systemd1.Manager');
1392 # Connect to the JobRemoved signal since we want to wait for it to finish
1393 my $sigid;
1394 my $timer;
1395 my $cleanup = sub {
1396 my ($no_shutdown) = @_;
1397 $if->disconnect_from_signal('JobRemoved', $sigid) if defined($if);
1398 $if = undef;
1399 $sigid = undef;
1400 $reactor->remove_timeout($timer) if defined($timer);
1401 $timer = undef;
1402 return if $no_shutdown;
1403 $reactor->shutdown();
1404 };
1405
1406 $sigid = $if->connect_to_signal('JobRemoved', sub {
1407 my ($id, $removed_job, $signaled_unit, $result) = @_;
1408 return if $signaled_unit ne $unit || $removed_job ne $job;
1409 $cleanup->(0);
1410 die "systemd job failed\n" if $result ne 'done';
1411 $done = 1;
1412 });
1413
1414 my $on_timeout = sub {
1415 $cleanup->(0);
1416 die "systemd job timed out\n";
1417 };
1418
1419 $timer = $reactor->add_timeout($timeout * 1000, Net::DBus::Callback->new(method => $on_timeout))
1420 if defined($timeout);
1421 $job = $if->StartTransientUnit($unit, 'fail', $properties, []);
1422 $reactor->run();
1423 $cleanup->(1);
1424 die "systemd job never completed\n" if !$done;
1425}
1426
e143e9d8 14271;