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