]> git.proxmox.com Git - pve-common.git/blame - src/PVE/Tools.pm
Use double hyphens when prefixing command options in the documentation
[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
2d38b8a1
TL
583# Run a command with a tcp socket as standard input.
584sub pipe_socket_to_command {
585 my ($cmd, $ip, $port) = @_;
586
587 my $params = {
588 Listen => 1,
589 ReuseAddr => 1,
590 Proto => &Socket::IPPROTO_TCP,
591 GetAddrInfoFlags => 0,
592 LocalAddr => $ip,
593 LocalPort => $port,
594 };
595 my $socket = IO::Socket::IP->new(%$params) or die "failed to open socket: $!\n";
596
597 print "$ip\n$port\n"; # tell remote where to connect
598 *STDOUT->flush();
599
600 alarm 0;
601 local $SIG{ALRM} = sub { die "timed out waiting for client\n" };
602 alarm 30;
603 my $client = $socket->accept; # Wait for a client
604 alarm 0;
605 close($socket);
606
607 # We want that the command talks over the TCP socket and takes
608 # ownership of it, so that when it closes it the connection is
609 # terminated, so we need to be able to close the socket. So we
610 # can't really use PVE::Tools::run_command().
611 my $pid = fork() // die "fork failed: $!\n";
612 if (!$pid) {
613 POSIX::dup2(fileno($client), 0);
614 POSIX::dup2(fileno($client), 1);
615 close($client);
616 exec {$cmd->[0]} @$cmd or do {
617 warn "exec failed: $!\n";
618 POSIX::_exit(1);
619 };
620 }
621
622 close($client);
623 if (waitpid($pid, 0) != $pid) {
624 kill(15 => $pid); # if we got interrupted terminate the child
625 my $count = 0;
626 while (waitpid($pid, POSIX::WNOHANG) != $pid) {
627 usleep(100000);
628 $count++;
629 kill(9 => $pid), last if $count > 300; # 30 second timeout
630 }
631 }
632 if (my $sig = ($? & 127)) {
633 die "got signal $sig\n";
634 } elsif (my $exitcode = ($? >> 8)) {
635 die "exit code $exitcode\n";
636 }
637
638 return undef;
639}
640
e143e9d8
DM
641sub split_list {
642 my $listtxt = shift || '';
643
d2b0374d 644 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
813a5c0d 645
d2b0374d 646 $listtxt =~ s/[,;]/ /g;
e143e9d8
DM
647 $listtxt =~ s/^\s+//;
648
649 my @data = split (/\s+/, $listtxt);
650
651 return @data;
652}
653
654sub trim {
655 my $txt = shift;
656
657 return $txt if !defined($txt);
658
659 $txt =~ s/^\s+//;
660 $txt =~ s/\s+$//;
813a5c0d 661
e143e9d8
DM
662 return $txt;
663}
664
665# simple uri templates like "/vms/{vmid}"
666sub template_replace {
667 my ($tmpl, $data) = @_;
668
3250f5c7 669 return $tmpl if !$tmpl;
813a5c0d 670
e143e9d8
DM
671 my $res = '';
672 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
673 $res .= $1 if $1;
674 $res .= ($data->{$3} || '-') if $2;
675 }
676 return $res;
677}
678
679sub safe_print {
680 my ($filename, $fh, $data) = @_;
681
682 return if !$data;
683
684 my $res = print $fh $data;
685
686 die "write to '$filename' failed\n" if !$res;
687}
688
689sub debmirrors {
690
691 return {
692 'at' => 'ftp.at.debian.org',
693 'au' => 'ftp.au.debian.org',
694 'be' => 'ftp.be.debian.org',
695 'bg' => 'ftp.bg.debian.org',
696 'br' => 'ftp.br.debian.org',
697 'ca' => 'ftp.ca.debian.org',
698 'ch' => 'ftp.ch.debian.org',
699 'cl' => 'ftp.cl.debian.org',
700 'cz' => 'ftp.cz.debian.org',
701 'de' => 'ftp.de.debian.org',
702 'dk' => 'ftp.dk.debian.org',
703 'ee' => 'ftp.ee.debian.org',
704 'es' => 'ftp.es.debian.org',
705 'fi' => 'ftp.fi.debian.org',
706 'fr' => 'ftp.fr.debian.org',
707 'gr' => 'ftp.gr.debian.org',
708 'hk' => 'ftp.hk.debian.org',
709 'hr' => 'ftp.hr.debian.org',
710 'hu' => 'ftp.hu.debian.org',
711 'ie' => 'ftp.ie.debian.org',
712 'is' => 'ftp.is.debian.org',
713 'it' => 'ftp.it.debian.org',
714 'jp' => 'ftp.jp.debian.org',
715 'kr' => 'ftp.kr.debian.org',
716 'mx' => 'ftp.mx.debian.org',
717 'nl' => 'ftp.nl.debian.org',
718 'no' => 'ftp.no.debian.org',
719 'nz' => 'ftp.nz.debian.org',
720 'pl' => 'ftp.pl.debian.org',
721 'pt' => 'ftp.pt.debian.org',
722 'ro' => 'ftp.ro.debian.org',
723 'ru' => 'ftp.ru.debian.org',
724 'se' => 'ftp.se.debian.org',
725 'si' => 'ftp.si.debian.org',
726 'sk' => 'ftp.sk.debian.org',
727 'tr' => 'ftp.tr.debian.org',
728 'tw' => 'ftp.tw.debian.org',
729 'gb' => 'ftp.uk.debian.org',
730 'us' => 'ftp.us.debian.org',
731 };
732}
733
910d57b0
DM
734my $keymaphash = {
735 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
736 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
813a5c0d 737 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
5a5ca434
DM
738 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef],
739 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ],
910d57b0
DM
740 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
741 #'et' => [], # Ethopia or Estonia ??
742 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
743 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
744 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
745 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
746 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
747 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
748 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
749 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
750 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
751 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
752 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
753 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
754 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
755 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
756 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
757 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
813a5c0d 758 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
910d57b0
DM
759 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
760 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
761 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
762 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
763 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
9934cd0b 764 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
910d57b0 765 #'th' => [],
c10cc112 766 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
910d57b0
DM
767};
768
769my $kvmkeymaparray = [];
0a7de820 770foreach my $lc (sort keys %$keymaphash) {
910d57b0
DM
771 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
772}
773
e143e9d8 774sub kvmkeymaps {
910d57b0
DM
775 return $keymaphash;
776}
777
778sub kvmkeymaplist {
779 return $kvmkeymaparray;
e143e9d8
DM
780}
781
782sub extract_param {
783 my ($param, $key) = @_;
784
785 my $res = $param->{$key};
786 delete $param->{$key};
787
788 return $res;
789}
790
eb7047f6 791# Note: we use this to wait until vncterm/spiceterm is ready
ec6d95b4
DM
792sub wait_for_vnc_port {
793 my ($port, $timeout) = @_;
794
795 $timeout = 5 if !$timeout;
eb7047f6
DM
796 my $sleeptime = 0;
797 my $starttime = [gettimeofday];
798 my $elapsed;
ec6d95b4 799
9a41a7b7 800 my $found;
eb7047f6 801 while (($elapsed = tv_interval($starttime)) < $timeout) {
9a41a7b7
TL
802 # -Htln = don't print header, tcp, listening sockets only, numeric ports
803 run_command(['/bin/ss', '-Htln', "sport = :$port"], outfunc => sub {
804 my $line = shift;
805 if ($line =~ m/^LISTEN\s+\d+\s+\d+\s+\S+:(\d+)\s/) {
806 $found = 1 if ($port == $1);
ec6d95b4 807 }
9a41a7b7
TL
808 });
809 return 1 if $found;
eb7047f6
DM
810 $sleeptime += 100000 if $sleeptime < 1000000;
811 usleep($sleeptime);
ec6d95b4
DM
812 }
813
814 return undef;
815}
816
59b3f563 817sub next_unused_port {
c14960cc 818 my ($range_start, $range_end, $family, $address) = @_;
59b3f563
DM
819
820 # We use a file to register allocated ports.
821 # Those registrations expires after $expiretime.
822 # We use this to avoid race conditions between
823 # allocation and use of ports.
824
825 my $filename = "/var/tmp/pve-reserved-ports";
e143e9d8 826
59b3f563 827 my $code = sub {
e143e9d8 828
59b3f563
DM
829 my $expiretime = 5;
830 my $ctime = time();
e143e9d8 831
59b3f563
DM
832 my $ports = {};
833
834 if (my $fh = IO::File->new ($filename, "r")) {
835 while (my $line = <$fh>) {
836 if ($line =~ m/^(\d+)\s(\d+)$/) {
837 my ($port, $timestamp) = ($1, $2);
838 if (($timestamp + $expiretime) > $ctime) {
839 $ports->{$port} = $timestamp; # not expired
813a5c0d 840 }
59b3f563
DM
841 }
842 }
e143e9d8 843 }
813a5c0d 844
59b3f563 845 my $newport;
c14960cc
WB
846 my %sockargs = (Listen => 5,
847 ReuseAddr => 1,
848 Family => $family,
a0ecb159 849 Proto => IPPROTO_TCP,
c14960cc
WB
850 GetAddrInfoFlags => 0);
851 $sockargs{LocalAddr} = $address if defined($address);
59b3f563
DM
852
853 for (my $p = $range_start; $p < $range_end; $p++) {
854 next if $ports->{$p}; # reserved
855
c14960cc
WB
856 $sockargs{LocalPort} = $p;
857 my $sock = IO::Socket::IP->new(%sockargs);
59b3f563
DM
858
859 if ($sock) {
860 close($sock);
861 $newport = $p;
862 $ports->{$p} = $ctime;
863 last;
864 }
865 }
813a5c0d 866
59b3f563
DM
867 my $data = "";
868 foreach my $p (keys %$ports) {
869 $data .= "$p $ports->{$p}\n";
870 }
813a5c0d 871
59b3f563 872 file_set_contents($filename, $data);
e143e9d8 873
59b3f563
DM
874 return $newport;
875 };
876
3c476ed5 877 my $p = lock_file('/var/lock/pve-ports.lck', 10, $code);
59b3f563 878 die $@ if $@;
813a5c0d 879
59b3f563
DM
880 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
881
882 return $p;
883}
884
885sub next_migrate_port {
c14960cc
WB
886 my ($family, $address) = @_;
887 return next_unused_port(60000, 60050, $family, $address);
59b3f563
DM
888}
889
890sub next_vnc_port {
c14960cc
WB
891 my ($family, $address) = @_;
892 return next_unused_port(5900, 6000, $family, $address);
59b3f563 893}
e143e9d8 894
2f13cbb5 895sub next_spice_port {
c14960cc
WB
896 my ($family, $address) = @_;
897 return next_unused_port(61000, 61099, $family, $address);
2f13cbb5
DM
898}
899
72fba911
EK
900# sigkill after $timeout a $sub running in a fork if it can't write a pipe
901# the $sub has to return a single scalar
902sub run_fork_with_timeout {
903 my ($timeout, $sub) = @_;
904
905 my $res;
906 my $error;
907 my $pipe_out = IO::Pipe->new();
908 my $pipe_err = IO::Pipe->new();
909
910 # disable pending alarms, save their remaining time
911 my $prev_alarm = alarm 0;
912
eead1cca 913 # avoid leaving a zombie if the parent gets interrupted
72fba911 914 my $sig_received;
eead1cca 915 local $SIG{INT} = sub { $sig_received++; };
72fba911
EK
916
917 my $child = fork();
918 if (!defined($child)) {
919 die "fork failed: $!\n";
920 return $res;
921 }
922
923 if (!$child) {
924 $pipe_out->writer();
925 $pipe_err->writer();
926
927 eval {
928 $res = $sub->();
929 print {$pipe_out} "$res";
930 $pipe_out->flush();
931 };
932 if (my $err = $@) {
933 print {$pipe_err} "$err";
934 $pipe_err->flush();
935 POSIX::_exit(1);
936 }
937 POSIX::_exit(0);
938 }
939
940 $pipe_out->reader();
941 $pipe_err->reader();
942
943 my $readvalues = sub {
944 local $/ = undef;
945 $res = <$pipe_out>;
946 $error = <$pipe_err>;
947 };
948 eval {
949 run_with_timeout($timeout, $readvalues);
950 };
951 warn $@ if $@;
952 $pipe_out->close();
953 $pipe_err->close();
954 kill('KILL', $child);
955 waitpid($child, 0);
956
957 alarm $prev_alarm;
958 die "interrupted by unexpected signal\n" if $sig_received;
959
960 die $error if $error;
961 return $res;
962}
963
813a5c0d 964# NOTE: NFS syscall can't be interrupted, so alarm does
e143e9d8
DM
965# not work to provide timeouts.
966# from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
97c8c857 967# So fork() before using Filesys::Df
e143e9d8
DM
968sub df {
969 my ($path, $timeout) = @_;
970
e143e9d8
DM
971 my $res = {
972 total => 0,
973 used => 0,
974 avail => 0,
975 };
976
97c8c857
WB
977 my $pipe = IO::Pipe->new();
978 my $child = fork();
979 if (!defined($child)) {
980 warn "fork failed: $!\n";
981 return $res;
982 }
983
984 if (!$child) {
985 $pipe->writer();
986 eval {
987 my $df = Filesys::Df::df($path, 1);
988 print {$pipe} "$df->{blocks}\n$df->{used}\n$df->{bavail}\n";
989 $pipe->close();
990 };
991 if (my $err = $@) {
992 warn $err;
993 POSIX::_exit(1);
e143e9d8 994 }
97c8c857
WB
995 POSIX::_exit(0);
996 }
997
998 $pipe->reader();
999
1000 my $readvalues = sub {
28705ff6
WB
1001 $res->{total} = int((<$pipe> =~ /^(\d*)$/)[0]);
1002 $res->{used} = int((<$pipe> =~ /^(\d*)$/)[0]);
1003 $res->{avail} = int((<$pipe> =~ /^(\d*)$/)[0]);
97c8c857
WB
1004 };
1005 eval {
1006 run_with_timeout($timeout, $readvalues);
e143e9d8 1007 };
e143e9d8 1008 warn $@ if $@;
97c8c857
WB
1009 $pipe->close();
1010 kill('KILL', $child);
1011 waitpid($child, 0);
e143e9d8
DM
1012 return $res;
1013}
1014
1015# UPID helper
1016# We use this to uniquely identify a process.
813a5c0d 1017# An 'Unique Process ID' has the following format:
e143e9d8
DM
1018# "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
1019
1020sub upid_encode {
1021 my $d = shift;
1022
19cec230
DM
1023 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
1024 # more that 8 characters for pstart
813a5c0d
DC
1025 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid},
1026 $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id},
e143e9d8
DM
1027 $d->{user});
1028}
1029
1030sub upid_decode {
1031 my ($upid, $noerr) = @_;
1032
1033 my $res;
1034 my $filename;
1035
1036 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
19cec230
DM
1037 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
1038 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 1039 $res->{node} = $1;
3702f038
DM
1040 $res->{pid} = hex($3);
1041 $res->{pstart} = hex($4);
1042 $res->{starttime} = hex($5);
1043 $res->{type} = $6;
1044 $res->{id} = $7;
1045 $res->{user} = $8;
1046
1047 my $subdir = substr($5, 7, 8);
e143e9d8
DM
1048 $filename = "$pvetaskdir/$subdir/$upid";
1049
1050 } else {
1051 return undef if $noerr;
1052 die "unable to parse worker upid '$upid'\n";
1053 }
1054
1055 return wantarray ? ($res, $filename) : $res;
1056}
1057
1058sub upid_open {
1059 my ($upid) = @_;
1060
813a5c0d 1061 my ($task, $filename) = upid_decode($upid);
e143e9d8
DM
1062
1063 my $dirname = dirname($filename);
1064 make_path($dirname);
1065
1066 my $wwwid = getpwnam('www-data') ||
1067 die "getpwnam failed";
1068
1069 my $perm = 0640;
813a5c0d 1070
e143e9d8
DM
1071 my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) ||
1072 die "unable to create output file '$filename' - $!\n";
2b8e0f12 1073 chown $wwwid, -1, $outfh;
e143e9d8
DM
1074
1075 return $outfh;
1076};
1077
1078sub upid_read_status {
1079 my ($upid) = @_;
1080
1081 my ($task, $filename) = upid_decode($upid);
1082 my $fh = IO::File->new($filename, "r");
1083 return "unable to open file - $!" if !$fh;
cc9121d3 1084 my $maxlen = 4096;
e143e9d8
DM
1085 sysseek($fh, -$maxlen, 2);
1086 my $readbuf = '';
1087 my $br = sysread($fh, $readbuf, $maxlen);
1088 close($fh);
1089 if ($br) {
1090 return "unable to extract last line"
1091 if $readbuf !~ m/\n?(.+)$/;
1092 my $line = $1;
1093 if ($line =~ m/^TASK OK$/) {
1094 return 'OK';
1095 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
1096 return $1;
1097 } else {
1098 return "unexpected status";
1099 }
1100 }
1101 return "unable to read tail (got $br bytes)";
1102}
1103
813a5c0d 1104# useful functions to store comments in config files
e143e9d8
DM
1105sub encode_text {
1106 my ($text) = @_;
1107
1108 # all control and hi-bit characters, and ':'
1109 my $unsafe = "^\x20-\x39\x3b-\x7e";
1110 return uri_escape(Encode::encode("utf8", $text), $unsafe);
1111}
1112
1113sub decode_text {
1114 my ($data) = @_;
1115
1116 return Encode::decode("utf8", uri_unescape($data));
1117}
1118
6d46baf6
DM
1119# depreciated - do not use!
1120# we now decode all parameters by default
815b2aba
DM
1121sub decode_utf8_parameters {
1122 my ($param) = @_;
1123
34ebb226 1124 foreach my $p (qw(comment description firstname lastname)) {
815b2aba
DM
1125 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
1126 }
1127
1128 return $param;
1129}
1130
a413a515 1131sub random_ether_addr {
12392173 1132 my ($prefix) = @_;
a413a515 1133
46a11c00
DM
1134 my ($seconds, $microseconds) = gettimeofday;
1135
d743b69c 1136 my $rand = Digest::SHA::sha1($$, rand(), $seconds, $microseconds);
a413a515 1137
85d5625a 1138 # clear multicast, set local id
de9a267f 1139 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
a413a515 1140
12392173
WB
1141 my $addr = sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
1142 if (defined($prefix)) {
1143 $addr = uc($prefix) . substr($addr, length($prefix));
1144 }
1145 return $addr;
a413a515 1146}
e143e9d8 1147
762e3223
DM
1148sub shellquote {
1149 my $str = shift;
1150
7514b23a 1151 return String::ShellQuote::shell_quote($str);
762e3223
DM
1152}
1153
65e1d3fc
DM
1154sub cmd2string {
1155 my ($cmd) = @_;
1156
1157 die "no arguments" if !$cmd;
1158
1159 return $cmd if !ref($cmd);
1160
1161 my @qa = ();
1162 foreach my $arg (@$cmd) { push @qa, shellquote($arg); }
1163
1164 return join (' ', @qa);
1165}
1166
e38bcd35 1167# split an shell argument string into an array,
f9125663
DM
1168sub split_args {
1169 my ($str) = @_;
1170
e38bcd35 1171 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
f9125663
DM
1172}
1173
804b1041 1174sub dump_logfile {
eb7e5538 1175 my ($filename, $start, $limit, $filter) = @_;
804b1041
DM
1176
1177 my $lines = [];
1178 my $count = 0;
1179
1180 my $fh = IO::File->new($filename, "r");
813a5c0d 1181 if (!$fh) {
804b1041
DM
1182 $count++;
1183 push @$lines, { n => $count, t => "unable to open file - $!"};
1184 return ($count, $lines);
1185 }
1186
1187 $start = 0 if !$start;
1188 $limit = 50 if !$limit;
1189
1190 my $line;
eb7e5538
DM
1191
1192 if ($filter) {
1193 # duplicate code, so that we do not slow down normal path
1194 while (defined($line = <$fh>)) {
1195 next if $line !~ m/$filter/;
1196 next if $count++ < $start;
1197 next if $limit <= 0;
1198 chomp $line;
1199 push @$lines, { n => $count, t => $line};
1200 $limit--;
1201 }
1202 } else {
1203 while (defined($line = <$fh>)) {
1204 next if $count++ < $start;
1205 next if $limit <= 0;
1206 chomp $line;
1207 push @$lines, { n => $count, t => $line};
1208 $limit--;
1209 }
804b1041
DM
1210 }
1211
1212 close($fh);
1213
6de95a66
DM
1214 # HACK: ExtJS store.guaranteeRange() does not like empty array
1215 # so we add a line
1216 if (!$count) {
1217 $count++;
1218 push @$lines, { n => $count, t => "no content"};
1219 }
1220
1221 return ($count, $lines);
1222}
1223
1224sub dump_journal {
ccf60d3b 1225 my ($start, $limit, $since, $until, $service) = @_;
6de95a66
DM
1226
1227 my $lines = [];
1228 my $count = 0;
813a5c0d 1229
6de95a66
DM
1230 $start = 0 if !$start;
1231 $limit = 50 if !$limit;
1232
1233 my $parser = sub {
1234 my $line = shift;
1235
1236 return if $count++ < $start;
1237 return if $limit <= 0;
1238 push @$lines, { n => int($count), t => $line};
1239 $limit--;
1240 };
1241
1242 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
19e95cd0 1243
ccf60d3b 1244 push @$cmd, '--unit', $service if $service;
19e95cd0
TL
1245 push @$cmd, '--since', $since if $since;
1246 push @$cmd, '--until', $until if $until;
6de95a66
DM
1247 run_command($cmd, outfunc => $parser);
1248
804b1041
DM
1249 # HACK: ExtJS store.guaranteeRange() does not like empty array
1250 # so we add a line
1251 if (!$count) {
1252 $count++;
1253 push @$lines, { n => $count, t => "no content"};
1254 }
1255
1256 return ($count, $lines);
1257}
1258
7eb283fb
DM
1259sub dir_glob_regex {
1260 my ($dir, $regex) = @_;
1261
1262 my $dh = IO::Dir->new ($dir);
1263 return wantarray ? () : undef if !$dh;
813a5c0d
DC
1264
1265 while (defined(my $tmp = $dh->read)) {
7eb283fb
DM
1266 if (my @res = $tmp =~ m/^($regex)$/) {
1267 $dh->close;
1268 return wantarray ? @res : $tmp;
1269 }
1270 }
1271 $dh->close;
1272
1273 return wantarray ? () : undef;
1274}
1275
1276sub dir_glob_foreach {
1277 my ($dir, $regex, $func) = @_;
1278
1279 my $dh = IO::Dir->new ($dir);
1280 if (defined $dh) {
1281 while (defined(my $tmp = $dh->read)) {
1282 if (my @res = $tmp =~ m/^($regex)$/) {
1283 &$func (@res);
1284 }
1285 }
813a5c0d 1286 }
7eb283fb
DM
1287}
1288
a345b9d5
DM
1289sub assert_if_modified {
1290 my ($digest1, $digest2) = @_;
1291
1292 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
212fc0b7 1293 die "detected modified configuration - file changed by other user? Try again.\n";
a345b9d5
DM
1294 }
1295}
1296
2d3bca34
DM
1297# Digest for short strings
1298# like FNV32a, but we only return 31 bits (positive numbers)
1299sub fnv31a {
1300 my ($string) = @_;
1301
1302 my $hval = 0x811c9dc5;
1303
1304 foreach my $c (unpack('C*', $string)) {
1305 $hval ^= $c;
1306 $hval += (
1307 (($hval << 1) ) +
1308 (($hval << 4) ) +
1309 (($hval << 7) ) +
1310 (($hval << 8) ) +
1311 (($hval << 24) ) );
1312 $hval = $hval & 0xffffffff;
1313 }
1314 return $hval & 0x7fffffff;
1315}
1316
1317sub fnv31a_hex { return sprintf("%X", fnv31a(@_)); }
1318
8df6b794
WB
1319sub unpack_sockaddr_in46 {
1320 my ($sin) = @_;
1321 my $family = Socket::sockaddr_family($sin);
1322 my ($port, $host) = ($family == AF_INET6 ? Socket::unpack_sockaddr_in6($sin)
1323 : Socket::unpack_sockaddr_in($sin));
1324 return ($family, $port, $host);
1325}
1326
a0b6ef52
WB
1327sub getaddrinfo_all {
1328 my ($hostname, @opts) = @_;
a956854f 1329 my %hints = ( flags => AI_V4MAPPED | AI_ALL,
a0b6ef52 1330 @opts );
a956854f 1331 my ($err, @res) = Socket::getaddrinfo($hostname, '0', \%hints);
a0b6ef52
WB
1332 die "failed to get address info for: $hostname: $err\n" if $err;
1333 return @res;
1334}
a956854f 1335
a0b6ef52
WB
1336sub get_host_address_family {
1337 my ($hostname, $socktype) = @_;
1338 my @res = getaddrinfo_all($hostname, socktype => $socktype);
1339 return $res[0]->{family};
a956854f
WB
1340}
1341
d3c8f0c1
EK
1342# get the fully qualified domain name of a host
1343# same logic as hostname(1): The FQDN is the name getaddrinfo(3) returns,
1344# given a nodename as a parameter
1345sub get_fqdn {
1346 my ($nodename) = @_;
1347
1348 my $hints = {
1349 flags => AI_CANONNAME,
1350 socktype => SOCK_DGRAM
1351 };
1352
1353 my ($err, @addrs) = Socket::getaddrinfo($nodename, undef, $hints);
1354
1355 die "getaddrinfo: $err" if $err;
1356
1357 return $addrs[0]->{canonname};
1358}
1359
b2613777
WB
1360# Parses any sane kind of host, or host+port pair:
1361# The port is always optional and thus may be undef.
1362sub parse_host_and_port {
1363 my ($address) = @_;
1364 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1365 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1366 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1367 {
1368 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1369 }
1370 return; # nothing
1371}
1372
817c6be0 1373sub unshare($) {
952fd95e 1374 my ($flags) = @_;
c8e94d4b 1375 return 0 == syscall(PVE::Syscall::unshare, $flags);
952fd95e
WB
1376}
1377
891b224a
WB
1378sub setns($$) {
1379 my ($fileno, $nstype) = @_;
c8e94d4b 1380 return 0 == syscall(PVE::Syscall::setns, $fileno, $nstype);
891b224a
WB
1381}
1382
44acb12c
WB
1383sub syncfs($) {
1384 my ($fileno) = @_;
c8e94d4b 1385 return 0 == syscall(PVE::Syscall::syncfs, $fileno);
44acb12c
WB
1386}
1387
1388sub sync_mountpoint {
1389 my ($path) = @_;
1390 sysopen my $fd, $path, O_PATH or die "failed to open $path: $!\n";
1391 my $result = syncfs(fileno($fd));
1392 close($fd);
1393 return $result;
1394}
1395
b61a47db
TL
1396# support sending multi-part mail messages with a text and or a HTML part
1397# mailto may be a single email string or an array of receivers
1398sub sendmail {
1399 my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_;
c9c6d910 1400 my $mail_re = qr/[^-a-zA-Z0-9+._@]/;
b61a47db 1401
5a873e6d 1402 $mailto = [ $mailto ] if !ref($mailto);
b61a47db 1403
c9c6d910
FG
1404 foreach (@$mailto) {
1405 die "illegal character in mailto address\n"
1406 if ($_ =~ $mail_re);
b61a47db 1407 }
c9c6d910 1408
b61a47db
TL
1409 my $rcvrtxt = join (', ', @$mailto);
1410
1411 $mailfrom = $mailfrom || "root";
c9c6d910
FG
1412 die "illegal character in mailfrom address\n"
1413 if $mailfrom =~ $mail_re;
1414
5a873e6d 1415 $author = $author || 'Proxmox VE';
b61a47db 1416
c9c6d910 1417 open (MAIL, "|-", "sendmail", "-B", "8BITMIME", "-f", $mailfrom, @$mailto) ||
b61a47db
TL
1418 die "unable to open 'sendmail' - $!";
1419
1420 # multipart spec see https://www.ietf.org/rfc/rfc1521.txt
1421 my $boundary = "----_=_NextPart_001_".int(time).$$;
1422
1423 print MAIL "Content-Type: multipart/alternative;\n";
1424 print MAIL "\tboundary=\"$boundary\"\n";
1425 print MAIL "MIME-Version: 1.0\n";
1426
1427 print MAIL "FROM: $author <$mailfrom>\n";
1428 print MAIL "TO: $rcvrtxt\n";
1429 print MAIL "SUBJECT: $subject\n";
1430 print MAIL "\n";
1431 print MAIL "This is a multi-part message in MIME format.\n\n";
1432 print MAIL "--$boundary\n";
1433
5a873e6d 1434 if (defined($text)) {
b61a47db
TL
1435 print MAIL "Content-Type: text/plain;\n";
1436 print MAIL "\tcharset=\"UTF8\"\n";
1437 print MAIL "Content-Transfer-Encoding: 8bit\n";
1438 print MAIL "\n";
1439
1440 # avoid 'remove extra line breaks' issue (MS Outlook)
1441 my $fill = ' ';
1442 $text =~ s/^/$fill/gm;
1443
1444 print MAIL $text;
1445
1446 print MAIL "\n--$boundary\n";
1447 }
1448
5a873e6d 1449 if (defined($html)) {
b61a47db
TL
1450 print MAIL "Content-Type: text/html;\n";
1451 print MAIL "\tcharset=\"UTF8\"\n";
1452 print MAIL "Content-Transfer-Encoding: 8bit\n";
1453 print MAIL "\n";
1454
1455 print MAIL $html;
1456
1457 print MAIL "\n--$boundary--\n";
1458 }
1459
1460 close(MAIL);
b61a47db
TL
1461}
1462
26598a51
WB
1463sub tempfile {
1464 my ($perm, %opts) = @_;
1465
1466 # default permissions are stricter than with file_set_contents
1467 $perm = 0600 if !defined($perm);
1468
f0cfc20e 1469 my $dir = $opts{dir} // '/run';
26598a51
WB
1470 my $mode = $opts{mode} // O_RDWR;
1471 $mode |= O_EXCL if !$opts{allow_links};
1472
7e1ee743
WB
1473 my $fh = IO::File->new($dir, $mode | O_TMPFILE, $perm);
1474 if (!$fh && $! == EOPNOTSUPP) {
77b2b96f 1475 $dir = '/tmp' if !defined($opts{dir});
7e1ee743
WB
1476 $dir .= "/.tmpfile.$$";
1477 $fh = IO::File->new($dir, $mode | O_CREAT | O_EXCL, $perm);
1478 unlink($dir) if $fh;
1479 }
1480 die "failed to create tempfile: $!\n" if !$fh;
26598a51
WB
1481 return $fh;
1482}
1483
1484sub tempfile_contents {
1485 my ($data, $perm, %opts) = @_;
1486
1487 my $fh = tempfile($perm, %opts);
1488 eval {
1489 die "unable to write to tempfile: $!\n" if !print {$fh} $data;
1490 die "unable to flush to tempfile: $!\n" if !defined($fh->flush());
1491 };
1492 if (my $err = $@) {
1493 close $fh;
1494 die $err;
1495 }
1496
1497 return ("/proc/$$/fd/".$fh->fileno, $fh);
1498}
1499
48df47a4
FG
1500sub validate_ssh_public_keys {
1501 my ($raw) = @_;
1502 my @lines = split(/\n/, $raw);
1503
1504 foreach my $line (@lines) {
1505 next if $line =~ m/^\s*$/;
1506 eval {
1507 my ($filename, $handle) = tempfile_contents($line);
1508 run_command(["ssh-keygen", "-l", "-f", $filename],
1509 outfunc => sub {}, errfunc => sub {});
1510 };
1511 die "SSH public key validation error\n" if $@;
1512 }
1513}
1514
21c56a96
WB
1515sub openat($$$;$) {
1516 my ($dirfd, $pathname, $flags, $mode) = @_;
c8e94d4b 1517 my $fd = syscall(PVE::Syscall::openat, $dirfd, $pathname, $flags, $mode//0);
21c56a96
WB
1518 return undef if $fd < 0;
1519 # sysopen() doesn't deal with numeric file descriptors apparently
1520 # so we need to convert to a mode string for IO::Handle->new_from_fd
1521 my $flagstr = ($flags & O_RDWR) ? 'rw' : ($flags & O_WRONLY) ? 'w' : 'r';
1522 my $handle = IO::Handle->new_from_fd($fd, $flagstr);
1523 return $handle if $handle;
1524 my $err = $!; # save error before closing the raw fd
c8e94d4b 1525 syscall(PVE::Syscall::close, $fd); # close
21c56a96
WB
1526 $! = $err;
1527 return undef;
1528}
1529
1530sub mkdirat($$$) {
1531 my ($dirfd, $name, $mode) = @_;
c8e94d4b 1532 return syscall(PVE::Syscall::mkdirat, $dirfd, $name, $mode) == 0;
21c56a96
WB
1533}
1534
0b9cf991
WB
1535# NOTE: This calls the dbus main loop and must not be used when another dbus
1536# main loop is being used as we need to wait for the JobRemoved signal.
1537# Polling the job status instead doesn't work because this doesn't give us the
1538# distinction between success and failure.
1539#
1540# Note that the description is mandatory for security reasons.
1541sub enter_systemd_scope {
1542 my ($unit, $description, %extra) = @_;
1543 die "missing description\n" if !defined($description);
1544
1545 my $timeout = delete $extra{timeout};
1546
1547 $unit .= '.scope';
1548 my $properties = [ [PIDs => [dbus_uint32($$)]] ];
1549
1550 foreach my $key (keys %extra) {
1551 if ($key eq 'Slice' || $key eq 'KillMode') {
1552 push @$properties, [$key, $extra{$key}];
1553 } elsif ($key eq 'CPUShares') {
1554 push @$properties, [$key, dbus_uint64($extra{$key})];
1555 } elsif ($key eq 'CPUQuota') {
1556 push @$properties, ['CPUQuotaPerSecUSec',
1557 dbus_uint64($extra{$key} * 10000)];
1558 } else {
1559 die "Don't know how to encode $key for systemd scope\n";
1560 }
1561 }
1562
1563 my $job;
1564 my $done = 0;
1565
1566 my $bus = Net::DBus->system();
1567 my $reactor = Net::DBus::Reactor->main();
1568
1569 my $service = $bus->get_service('org.freedesktop.systemd1');
1570 my $if = $service->get_object('/org/freedesktop/systemd1', 'org.freedesktop.systemd1.Manager');
1571 # Connect to the JobRemoved signal since we want to wait for it to finish
1572 my $sigid;
1573 my $timer;
1574 my $cleanup = sub {
1575 my ($no_shutdown) = @_;
1576 $if->disconnect_from_signal('JobRemoved', $sigid) if defined($if);
1577 $if = undef;
1578 $sigid = undef;
1579 $reactor->remove_timeout($timer) if defined($timer);
1580 $timer = undef;
1581 return if $no_shutdown;
1582 $reactor->shutdown();
1583 };
1584
1585 $sigid = $if->connect_to_signal('JobRemoved', sub {
1586 my ($id, $removed_job, $signaled_unit, $result) = @_;
1587 return if $signaled_unit ne $unit || $removed_job ne $job;
1588 $cleanup->(0);
1589 die "systemd job failed\n" if $result ne 'done';
1590 $done = 1;
1591 });
1592
1593 my $on_timeout = sub {
1594 $cleanup->(0);
1595 die "systemd job timed out\n";
1596 };
1597
1598 $timer = $reactor->add_timeout($timeout * 1000, Net::DBus::Callback->new(method => $on_timeout))
1599 if defined($timeout);
1600 $job = $if->StartTransientUnit($unit, 'fail', $properties, []);
1601 $reactor->run();
1602 $cleanup->(1);
1603 die "systemd job never completed\n" if !$done;
1604}
1605
9867ff7a
DM
1606my $salt_starter = time();
1607
1608sub encrypt_pw {
1609 my ($pw) = @_;
1610
1611 $salt_starter++;
1612 my $salt = substr(Digest::SHA::sha1_base64(time() + $salt_starter + $$), 0, 8);
1613
1614 # crypt does not want '+' in salt (see 'man crypt')
1615 $salt =~ s/\+/X/g;
1616
1617 return crypt(encode("utf8", $pw), "\$5\$$salt\$");
1618}
1619
8e677e74
TL
1620# intended usage: convert_size($val, "kb" => "gb")
1621# on reduction (converting to a bigger unit) we round up by default if
1622# information got lost. E.g. `convert_size(1023, "b" => "kb")` returns 1
1623# use $no_round_up to switch this off, above example would then return 0
1624sub convert_size {
1625 my ($value, $from, $to, $no_round_up) = @_;
1626
1627 my $units = {
1628 b => 0,
1629 kb => 1,
1630 mb => 2,
1631 gb => 3,
1632 tb => 4,
1633 pb => 5,
1634 };
1635
1636 $from = lc($from); $to = lc($to);
1637 die "unknown 'from' and/or 'to' units ($from => $to)"
1638 if !(defined($units->{$from}) && defined($units->{$to}));
1639
1640 my $shift_amount = $units->{$from} - $units->{$to};
1641
1642 if ($shift_amount > 0) {
1643 $value <<= ($shift_amount * 10);
1644 } elsif ($shift_amount < 0) {
1645 my $remainder = ($value & (1 << abs($shift_amount)*10) - 1);
1646 $value >>= abs($shift_amount) * 10;
1647 $value++ if $remainder && !$no_round_up;
1648 }
1649
1650 return $value;
1651}
1652
e143e9d8 16531;