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