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