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