]> git.proxmox.com Git - pve-common.git/blame - src/PVE/Tools.pm
bump version to 5.0-14
[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
eb7047f6 742 while (($elapsed = tv_interval($starttime)) < $timeout) {
ec6d95b4
DM
743 if (my $fh = IO::File->new ("/proc/net/tcp", "r")) {
744 while (defined (my $line = <$fh>)) {
745 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
746 if ($port == hex($2)) {
747 close($fh);
748 return 1;
749 }
750 }
751 }
752 close($fh);
753 }
eb7047f6
DM
754 $sleeptime += 100000 if $sleeptime < 1000000;
755 usleep($sleeptime);
ec6d95b4
DM
756 }
757
758 return undef;
759}
760
59b3f563 761sub next_unused_port {
c14960cc 762 my ($range_start, $range_end, $family, $address) = @_;
59b3f563
DM
763
764 # We use a file to register allocated ports.
765 # Those registrations expires after $expiretime.
766 # We use this to avoid race conditions between
767 # allocation and use of ports.
768
769 my $filename = "/var/tmp/pve-reserved-ports";
e143e9d8 770
59b3f563 771 my $code = sub {
e143e9d8 772
59b3f563
DM
773 my $expiretime = 5;
774 my $ctime = time();
e143e9d8 775
59b3f563
DM
776 my $ports = {};
777
778 if (my $fh = IO::File->new ($filename, "r")) {
779 while (my $line = <$fh>) {
780 if ($line =~ m/^(\d+)\s(\d+)$/) {
781 my ($port, $timestamp) = ($1, $2);
782 if (($timestamp + $expiretime) > $ctime) {
783 $ports->{$port} = $timestamp; # not expired
813a5c0d 784 }
59b3f563
DM
785 }
786 }
e143e9d8 787 }
813a5c0d 788
59b3f563 789 my $newport;
c14960cc
WB
790 my %sockargs = (Listen => 5,
791 ReuseAddr => 1,
792 Family => $family,
a0ecb159 793 Proto => IPPROTO_TCP,
c14960cc
WB
794 GetAddrInfoFlags => 0);
795 $sockargs{LocalAddr} = $address if defined($address);
59b3f563
DM
796
797 for (my $p = $range_start; $p < $range_end; $p++) {
798 next if $ports->{$p}; # reserved
799
c14960cc
WB
800 $sockargs{LocalPort} = $p;
801 my $sock = IO::Socket::IP->new(%sockargs);
59b3f563
DM
802
803 if ($sock) {
804 close($sock);
805 $newport = $p;
806 $ports->{$p} = $ctime;
807 last;
808 }
809 }
813a5c0d 810
59b3f563
DM
811 my $data = "";
812 foreach my $p (keys %$ports) {
813 $data .= "$p $ports->{$p}\n";
814 }
813a5c0d 815
59b3f563 816 file_set_contents($filename, $data);
e143e9d8 817
59b3f563
DM
818 return $newport;
819 };
820
3c476ed5 821 my $p = lock_file('/var/lock/pve-ports.lck', 10, $code);
59b3f563 822 die $@ if $@;
813a5c0d 823
59b3f563
DM
824 die "unable to find free port (${range_start}-${range_end})\n" if !$p;
825
826 return $p;
827}
828
829sub next_migrate_port {
c14960cc
WB
830 my ($family, $address) = @_;
831 return next_unused_port(60000, 60050, $family, $address);
59b3f563
DM
832}
833
834sub next_vnc_port {
c14960cc
WB
835 my ($family, $address) = @_;
836 return next_unused_port(5900, 6000, $family, $address);
59b3f563 837}
e143e9d8 838
2f13cbb5 839sub next_spice_port {
c14960cc
WB
840 my ($family, $address) = @_;
841 return next_unused_port(61000, 61099, $family, $address);
2f13cbb5
DM
842}
843
813a5c0d 844# NOTE: NFS syscall can't be interrupted, so alarm does
e143e9d8
DM
845# not work to provide timeouts.
846# from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
97c8c857 847# So fork() before using Filesys::Df
e143e9d8
DM
848sub df {
849 my ($path, $timeout) = @_;
850
e143e9d8
DM
851 my $res = {
852 total => 0,
853 used => 0,
854 avail => 0,
855 };
856
97c8c857
WB
857 my $pipe = IO::Pipe->new();
858 my $child = fork();
859 if (!defined($child)) {
860 warn "fork failed: $!\n";
861 return $res;
862 }
863
864 if (!$child) {
865 $pipe->writer();
866 eval {
867 my $df = Filesys::Df::df($path, 1);
868 print {$pipe} "$df->{blocks}\n$df->{used}\n$df->{bavail}\n";
869 $pipe->close();
870 };
871 if (my $err = $@) {
872 warn $err;
873 POSIX::_exit(1);
e143e9d8 874 }
97c8c857
WB
875 POSIX::_exit(0);
876 }
877
878 $pipe->reader();
879
880 my $readvalues = sub {
28705ff6
WB
881 $res->{total} = int((<$pipe> =~ /^(\d*)$/)[0]);
882 $res->{used} = int((<$pipe> =~ /^(\d*)$/)[0]);
883 $res->{avail} = int((<$pipe> =~ /^(\d*)$/)[0]);
97c8c857
WB
884 };
885 eval {
886 run_with_timeout($timeout, $readvalues);
e143e9d8 887 };
e143e9d8 888 warn $@ if $@;
97c8c857
WB
889 $pipe->close();
890 kill('KILL', $child);
891 waitpid($child, 0);
e143e9d8
DM
892 return $res;
893}
894
895# UPID helper
896# We use this to uniquely identify a process.
813a5c0d 897# An 'Unique Process ID' has the following format:
e143e9d8
DM
898# "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
899
900sub upid_encode {
901 my $d = shift;
902
19cec230
DM
903 # Note: pstart can be > 32bit if uptime > 497 days, so this can result in
904 # more that 8 characters for pstart
813a5c0d
DC
905 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid},
906 $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id},
e143e9d8
DM
907 $d->{user});
908}
909
910sub upid_decode {
911 my ($upid, $noerr) = @_;
912
913 my $res;
914 my $filename;
915
916 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
19cec230
DM
917 # Note: allow up to 9 characters for pstart (work until 20 years uptime)
918 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 919 $res->{node} = $1;
3702f038
DM
920 $res->{pid} = hex($3);
921 $res->{pstart} = hex($4);
922 $res->{starttime} = hex($5);
923 $res->{type} = $6;
924 $res->{id} = $7;
925 $res->{user} = $8;
926
927 my $subdir = substr($5, 7, 8);
e143e9d8
DM
928 $filename = "$pvetaskdir/$subdir/$upid";
929
930 } else {
931 return undef if $noerr;
932 die "unable to parse worker upid '$upid'\n";
933 }
934
935 return wantarray ? ($res, $filename) : $res;
936}
937
938sub upid_open {
939 my ($upid) = @_;
940
813a5c0d 941 my ($task, $filename) = upid_decode($upid);
e143e9d8
DM
942
943 my $dirname = dirname($filename);
944 make_path($dirname);
945
946 my $wwwid = getpwnam('www-data') ||
947 die "getpwnam failed";
948
949 my $perm = 0640;
813a5c0d 950
e143e9d8
DM
951 my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) ||
952 die "unable to create output file '$filename' - $!\n";
2b8e0f12 953 chown $wwwid, -1, $outfh;
e143e9d8
DM
954
955 return $outfh;
956};
957
958sub upid_read_status {
959 my ($upid) = @_;
960
961 my ($task, $filename) = upid_decode($upid);
962 my $fh = IO::File->new($filename, "r");
963 return "unable to open file - $!" if !$fh;
cc9121d3 964 my $maxlen = 4096;
e143e9d8
DM
965 sysseek($fh, -$maxlen, 2);
966 my $readbuf = '';
967 my $br = sysread($fh, $readbuf, $maxlen);
968 close($fh);
969 if ($br) {
970 return "unable to extract last line"
971 if $readbuf !~ m/\n?(.+)$/;
972 my $line = $1;
973 if ($line =~ m/^TASK OK$/) {
974 return 'OK';
975 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
976 return $1;
977 } else {
978 return "unexpected status";
979 }
980 }
981 return "unable to read tail (got $br bytes)";
982}
983
813a5c0d 984# useful functions to store comments in config files
e143e9d8
DM
985sub encode_text {
986 my ($text) = @_;
987
988 # all control and hi-bit characters, and ':'
989 my $unsafe = "^\x20-\x39\x3b-\x7e";
990 return uri_escape(Encode::encode("utf8", $text), $unsafe);
991}
992
993sub decode_text {
994 my ($data) = @_;
995
996 return Encode::decode("utf8", uri_unescape($data));
997}
998
6d46baf6
DM
999# depreciated - do not use!
1000# we now decode all parameters by default
815b2aba
DM
1001sub decode_utf8_parameters {
1002 my ($param) = @_;
1003
34ebb226 1004 foreach my $p (qw(comment description firstname lastname)) {
815b2aba
DM
1005 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
1006 }
1007
1008 return $param;
1009}
1010
a413a515 1011sub random_ether_addr {
12392173 1012 my ($prefix) = @_;
a413a515 1013
46a11c00
DM
1014 my ($seconds, $microseconds) = gettimeofday;
1015
d743b69c 1016 my $rand = Digest::SHA::sha1($$, rand(), $seconds, $microseconds);
a413a515 1017
85d5625a 1018 # clear multicast, set local id
de9a267f 1019 vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2;
a413a515 1020
12392173
WB
1021 my $addr = sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand));
1022 if (defined($prefix)) {
1023 $addr = uc($prefix) . substr($addr, length($prefix));
1024 }
1025 return $addr;
a413a515 1026}
e143e9d8 1027
762e3223
DM
1028sub shellquote {
1029 my $str = shift;
1030
7514b23a 1031 return String::ShellQuote::shell_quote($str);
762e3223
DM
1032}
1033
65e1d3fc
DM
1034sub cmd2string {
1035 my ($cmd) = @_;
1036
1037 die "no arguments" if !$cmd;
1038
1039 return $cmd if !ref($cmd);
1040
1041 my @qa = ();
1042 foreach my $arg (@$cmd) { push @qa, shellquote($arg); }
1043
1044 return join (' ', @qa);
1045}
1046
e38bcd35 1047# split an shell argument string into an array,
f9125663
DM
1048sub split_args {
1049 my ($str) = @_;
1050
e38bcd35 1051 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
f9125663
DM
1052}
1053
804b1041 1054sub dump_logfile {
eb7e5538 1055 my ($filename, $start, $limit, $filter) = @_;
804b1041
DM
1056
1057 my $lines = [];
1058 my $count = 0;
1059
1060 my $fh = IO::File->new($filename, "r");
813a5c0d 1061 if (!$fh) {
804b1041
DM
1062 $count++;
1063 push @$lines, { n => $count, t => "unable to open file - $!"};
1064 return ($count, $lines);
1065 }
1066
1067 $start = 0 if !$start;
1068 $limit = 50 if !$limit;
1069
1070 my $line;
eb7e5538
DM
1071
1072 if ($filter) {
1073 # duplicate code, so that we do not slow down normal path
1074 while (defined($line = <$fh>)) {
1075 next if $line !~ m/$filter/;
1076 next if $count++ < $start;
1077 next if $limit <= 0;
1078 chomp $line;
1079 push @$lines, { n => $count, t => $line};
1080 $limit--;
1081 }
1082 } else {
1083 while (defined($line = <$fh>)) {
1084 next if $count++ < $start;
1085 next if $limit <= 0;
1086 chomp $line;
1087 push @$lines, { n => $count, t => $line};
1088 $limit--;
1089 }
804b1041
DM
1090 }
1091
1092 close($fh);
1093
6de95a66
DM
1094 # HACK: ExtJS store.guaranteeRange() does not like empty array
1095 # so we add a line
1096 if (!$count) {
1097 $count++;
1098 push @$lines, { n => $count, t => "no content"};
1099 }
1100
1101 return ($count, $lines);
1102}
1103
1104sub dump_journal {
ccf60d3b 1105 my ($start, $limit, $since, $until, $service) = @_;
6de95a66
DM
1106
1107 my $lines = [];
1108 my $count = 0;
813a5c0d 1109
6de95a66
DM
1110 $start = 0 if !$start;
1111 $limit = 50 if !$limit;
1112
1113 my $parser = sub {
1114 my $line = shift;
1115
1116 return if $count++ < $start;
1117 return if $limit <= 0;
1118 push @$lines, { n => int($count), t => $line};
1119 $limit--;
1120 };
1121
1122 my $cmd = ['journalctl', '-o', 'short', '--no-pager'];
19e95cd0 1123
ccf60d3b 1124 push @$cmd, '--unit', $service if $service;
19e95cd0
TL
1125 push @$cmd, '--since', $since if $since;
1126 push @$cmd, '--until', $until if $until;
6de95a66
DM
1127 run_command($cmd, outfunc => $parser);
1128
804b1041
DM
1129 # HACK: ExtJS store.guaranteeRange() does not like empty array
1130 # so we add a line
1131 if (!$count) {
1132 $count++;
1133 push @$lines, { n => $count, t => "no content"};
1134 }
1135
1136 return ($count, $lines);
1137}
1138
7eb283fb
DM
1139sub dir_glob_regex {
1140 my ($dir, $regex) = @_;
1141
1142 my $dh = IO::Dir->new ($dir);
1143 return wantarray ? () : undef if !$dh;
813a5c0d
DC
1144
1145 while (defined(my $tmp = $dh->read)) {
7eb283fb
DM
1146 if (my @res = $tmp =~ m/^($regex)$/) {
1147 $dh->close;
1148 return wantarray ? @res : $tmp;
1149 }
1150 }
1151 $dh->close;
1152
1153 return wantarray ? () : undef;
1154}
1155
1156sub dir_glob_foreach {
1157 my ($dir, $regex, $func) = @_;
1158
1159 my $dh = IO::Dir->new ($dir);
1160 if (defined $dh) {
1161 while (defined(my $tmp = $dh->read)) {
1162 if (my @res = $tmp =~ m/^($regex)$/) {
1163 &$func (@res);
1164 }
1165 }
813a5c0d 1166 }
7eb283fb
DM
1167}
1168
a345b9d5
DM
1169sub assert_if_modified {
1170 my ($digest1, $digest2) = @_;
1171
1172 if ($digest1 && $digest2 && ($digest1 ne $digest2)) {
212fc0b7 1173 die "detected modified configuration - file changed by other user? Try again.\n";
a345b9d5
DM
1174 }
1175}
1176
2d3bca34
DM
1177# Digest for short strings
1178# like FNV32a, but we only return 31 bits (positive numbers)
1179sub fnv31a {
1180 my ($string) = @_;
1181
1182 my $hval = 0x811c9dc5;
1183
1184 foreach my $c (unpack('C*', $string)) {
1185 $hval ^= $c;
1186 $hval += (
1187 (($hval << 1) ) +
1188 (($hval << 4) ) +
1189 (($hval << 7) ) +
1190 (($hval << 8) ) +
1191 (($hval << 24) ) );
1192 $hval = $hval & 0xffffffff;
1193 }
1194 return $hval & 0x7fffffff;
1195}
1196
1197sub fnv31a_hex { return sprintf("%X", fnv31a(@_)); }
1198
8df6b794
WB
1199sub unpack_sockaddr_in46 {
1200 my ($sin) = @_;
1201 my $family = Socket::sockaddr_family($sin);
1202 my ($port, $host) = ($family == AF_INET6 ? Socket::unpack_sockaddr_in6($sin)
1203 : Socket::unpack_sockaddr_in($sin));
1204 return ($family, $port, $host);
1205}
1206
a0b6ef52
WB
1207sub getaddrinfo_all {
1208 my ($hostname, @opts) = @_;
a956854f 1209 my %hints = ( flags => AI_V4MAPPED | AI_ALL,
a0b6ef52 1210 @opts );
a956854f 1211 my ($err, @res) = Socket::getaddrinfo($hostname, '0', \%hints);
a0b6ef52
WB
1212 die "failed to get address info for: $hostname: $err\n" if $err;
1213 return @res;
1214}
a956854f 1215
a0b6ef52
WB
1216sub get_host_address_family {
1217 my ($hostname, $socktype) = @_;
1218 my @res = getaddrinfo_all($hostname, socktype => $socktype);
1219 return $res[0]->{family};
a956854f
WB
1220}
1221
d3c8f0c1
EK
1222# get the fully qualified domain name of a host
1223# same logic as hostname(1): The FQDN is the name getaddrinfo(3) returns,
1224# given a nodename as a parameter
1225sub get_fqdn {
1226 my ($nodename) = @_;
1227
1228 my $hints = {
1229 flags => AI_CANONNAME,
1230 socktype => SOCK_DGRAM
1231 };
1232
1233 my ($err, @addrs) = Socket::getaddrinfo($nodename, undef, $hints);
1234
1235 die "getaddrinfo: $err" if $err;
1236
1237 return $addrs[0]->{canonname};
1238}
1239
b2613777
WB
1240# Parses any sane kind of host, or host+port pair:
1241# The port is always optional and thus may be undef.
1242sub parse_host_and_port {
1243 my ($address) = @_;
1244 if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port'
1245 $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port'
1246 $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot
1247 {
1248 return ($1, $2, 1); # end with 1 to support simple if(parse...) tests
1249 }
1250 return; # nothing
1251}
1252
817c6be0 1253sub unshare($) {
952fd95e 1254 my ($flags) = @_;
c8e94d4b 1255 return 0 == syscall(PVE::Syscall::unshare, $flags);
952fd95e
WB
1256}
1257
891b224a
WB
1258sub setns($$) {
1259 my ($fileno, $nstype) = @_;
c8e94d4b 1260 return 0 == syscall(PVE::Syscall::setns, $fileno, $nstype);
891b224a
WB
1261}
1262
44acb12c
WB
1263sub syncfs($) {
1264 my ($fileno) = @_;
c8e94d4b 1265 return 0 == syscall(PVE::Syscall::syncfs, $fileno);
44acb12c
WB
1266}
1267
1268sub sync_mountpoint {
1269 my ($path) = @_;
1270 sysopen my $fd, $path, O_PATH or die "failed to open $path: $!\n";
1271 my $result = syncfs(fileno($fd));
1272 close($fd);
1273 return $result;
1274}
1275
b61a47db
TL
1276# support sending multi-part mail messages with a text and or a HTML part
1277# mailto may be a single email string or an array of receivers
1278sub sendmail {
1279 my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_;
c9c6d910 1280 my $mail_re = qr/[^-a-zA-Z0-9+._@]/;
b61a47db 1281
5a873e6d 1282 $mailto = [ $mailto ] if !ref($mailto);
b61a47db 1283
c9c6d910
FG
1284 foreach (@$mailto) {
1285 die "illegal character in mailto address\n"
1286 if ($_ =~ $mail_re);
b61a47db 1287 }
c9c6d910 1288
b61a47db
TL
1289 my $rcvrtxt = join (', ', @$mailto);
1290
1291 $mailfrom = $mailfrom || "root";
c9c6d910
FG
1292 die "illegal character in mailfrom address\n"
1293 if $mailfrom =~ $mail_re;
1294
5a873e6d 1295 $author = $author || 'Proxmox VE';
b61a47db 1296
c9c6d910 1297 open (MAIL, "|-", "sendmail", "-B", "8BITMIME", "-f", $mailfrom, @$mailto) ||
b61a47db
TL
1298 die "unable to open 'sendmail' - $!";
1299
1300 # multipart spec see https://www.ietf.org/rfc/rfc1521.txt
1301 my $boundary = "----_=_NextPart_001_".int(time).$$;
1302
1303 print MAIL "Content-Type: multipart/alternative;\n";
1304 print MAIL "\tboundary=\"$boundary\"\n";
1305 print MAIL "MIME-Version: 1.0\n";
1306
1307 print MAIL "FROM: $author <$mailfrom>\n";
1308 print MAIL "TO: $rcvrtxt\n";
1309 print MAIL "SUBJECT: $subject\n";
1310 print MAIL "\n";
1311 print MAIL "This is a multi-part message in MIME format.\n\n";
1312 print MAIL "--$boundary\n";
1313
5a873e6d 1314 if (defined($text)) {
b61a47db
TL
1315 print MAIL "Content-Type: text/plain;\n";
1316 print MAIL "\tcharset=\"UTF8\"\n";
1317 print MAIL "Content-Transfer-Encoding: 8bit\n";
1318 print MAIL "\n";
1319
1320 # avoid 'remove extra line breaks' issue (MS Outlook)
1321 my $fill = ' ';
1322 $text =~ s/^/$fill/gm;
1323
1324 print MAIL $text;
1325
1326 print MAIL "\n--$boundary\n";
1327 }
1328
5a873e6d 1329 if (defined($html)) {
b61a47db
TL
1330 print MAIL "Content-Type: text/html;\n";
1331 print MAIL "\tcharset=\"UTF8\"\n";
1332 print MAIL "Content-Transfer-Encoding: 8bit\n";
1333 print MAIL "\n";
1334
1335 print MAIL $html;
1336
1337 print MAIL "\n--$boundary--\n";
1338 }
1339
1340 close(MAIL);
b61a47db
TL
1341}
1342
26598a51
WB
1343sub tempfile {
1344 my ($perm, %opts) = @_;
1345
1346 # default permissions are stricter than with file_set_contents
1347 $perm = 0600 if !defined($perm);
1348
f0cfc20e 1349 my $dir = $opts{dir} // '/run';
26598a51
WB
1350 my $mode = $opts{mode} // O_RDWR;
1351 $mode |= O_EXCL if !$opts{allow_links};
1352
7e1ee743
WB
1353 my $fh = IO::File->new($dir, $mode | O_TMPFILE, $perm);
1354 if (!$fh && $! == EOPNOTSUPP) {
77b2b96f 1355 $dir = '/tmp' if !defined($opts{dir});
7e1ee743
WB
1356 $dir .= "/.tmpfile.$$";
1357 $fh = IO::File->new($dir, $mode | O_CREAT | O_EXCL, $perm);
1358 unlink($dir) if $fh;
1359 }
1360 die "failed to create tempfile: $!\n" if !$fh;
26598a51
WB
1361 return $fh;
1362}
1363
1364sub tempfile_contents {
1365 my ($data, $perm, %opts) = @_;
1366
1367 my $fh = tempfile($perm, %opts);
1368 eval {
1369 die "unable to write to tempfile: $!\n" if !print {$fh} $data;
1370 die "unable to flush to tempfile: $!\n" if !defined($fh->flush());
1371 };
1372 if (my $err = $@) {
1373 close $fh;
1374 die $err;
1375 }
1376
1377 return ("/proc/$$/fd/".$fh->fileno, $fh);
1378}
1379
48df47a4
FG
1380sub validate_ssh_public_keys {
1381 my ($raw) = @_;
1382 my @lines = split(/\n/, $raw);
1383
1384 foreach my $line (@lines) {
1385 next if $line =~ m/^\s*$/;
1386 eval {
1387 my ($filename, $handle) = tempfile_contents($line);
1388 run_command(["ssh-keygen", "-l", "-f", $filename],
1389 outfunc => sub {}, errfunc => sub {});
1390 };
1391 die "SSH public key validation error\n" if $@;
1392 }
1393}
1394
21c56a96
WB
1395sub openat($$$;$) {
1396 my ($dirfd, $pathname, $flags, $mode) = @_;
c8e94d4b 1397 my $fd = syscall(PVE::Syscall::openat, $dirfd, $pathname, $flags, $mode//0);
21c56a96
WB
1398 return undef if $fd < 0;
1399 # sysopen() doesn't deal with numeric file descriptors apparently
1400 # so we need to convert to a mode string for IO::Handle->new_from_fd
1401 my $flagstr = ($flags & O_RDWR) ? 'rw' : ($flags & O_WRONLY) ? 'w' : 'r';
1402 my $handle = IO::Handle->new_from_fd($fd, $flagstr);
1403 return $handle if $handle;
1404 my $err = $!; # save error before closing the raw fd
c8e94d4b 1405 syscall(PVE::Syscall::close, $fd); # close
21c56a96
WB
1406 $! = $err;
1407 return undef;
1408}
1409
1410sub mkdirat($$$) {
1411 my ($dirfd, $name, $mode) = @_;
c8e94d4b 1412 return syscall(PVE::Syscall::mkdirat, $dirfd, $name, $mode) == 0;
21c56a96
WB
1413}
1414
0b9cf991
WB
1415# NOTE: This calls the dbus main loop and must not be used when another dbus
1416# main loop is being used as we need to wait for the JobRemoved signal.
1417# Polling the job status instead doesn't work because this doesn't give us the
1418# distinction between success and failure.
1419#
1420# Note that the description is mandatory for security reasons.
1421sub enter_systemd_scope {
1422 my ($unit, $description, %extra) = @_;
1423 die "missing description\n" if !defined($description);
1424
1425 my $timeout = delete $extra{timeout};
1426
1427 $unit .= '.scope';
1428 my $properties = [ [PIDs => [dbus_uint32($$)]] ];
1429
1430 foreach my $key (keys %extra) {
1431 if ($key eq 'Slice' || $key eq 'KillMode') {
1432 push @$properties, [$key, $extra{$key}];
1433 } elsif ($key eq 'CPUShares') {
1434 push @$properties, [$key, dbus_uint64($extra{$key})];
1435 } elsif ($key eq 'CPUQuota') {
1436 push @$properties, ['CPUQuotaPerSecUSec',
1437 dbus_uint64($extra{$key} * 10000)];
1438 } else {
1439 die "Don't know how to encode $key for systemd scope\n";
1440 }
1441 }
1442
1443 my $job;
1444 my $done = 0;
1445
1446 my $bus = Net::DBus->system();
1447 my $reactor = Net::DBus::Reactor->main();
1448
1449 my $service = $bus->get_service('org.freedesktop.systemd1');
1450 my $if = $service->get_object('/org/freedesktop/systemd1', 'org.freedesktop.systemd1.Manager');
1451 # Connect to the JobRemoved signal since we want to wait for it to finish
1452 my $sigid;
1453 my $timer;
1454 my $cleanup = sub {
1455 my ($no_shutdown) = @_;
1456 $if->disconnect_from_signal('JobRemoved', $sigid) if defined($if);
1457 $if = undef;
1458 $sigid = undef;
1459 $reactor->remove_timeout($timer) if defined($timer);
1460 $timer = undef;
1461 return if $no_shutdown;
1462 $reactor->shutdown();
1463 };
1464
1465 $sigid = $if->connect_to_signal('JobRemoved', sub {
1466 my ($id, $removed_job, $signaled_unit, $result) = @_;
1467 return if $signaled_unit ne $unit || $removed_job ne $job;
1468 $cleanup->(0);
1469 die "systemd job failed\n" if $result ne 'done';
1470 $done = 1;
1471 });
1472
1473 my $on_timeout = sub {
1474 $cleanup->(0);
1475 die "systemd job timed out\n";
1476 };
1477
1478 $timer = $reactor->add_timeout($timeout * 1000, Net::DBus::Callback->new(method => $on_timeout))
1479 if defined($timeout);
1480 $job = $if->StartTransientUnit($unit, 'fail', $properties, []);
1481 $reactor->run();
1482 $cleanup->(1);
1483 die "systemd job never completed\n" if !$done;
1484}
1485
9867ff7a
DM
1486my $salt_starter = time();
1487
1488sub encrypt_pw {
1489 my ($pw) = @_;
1490
1491 $salt_starter++;
1492 my $salt = substr(Digest::SHA::sha1_base64(time() + $salt_starter + $$), 0, 8);
1493
1494 # crypt does not want '+' in salt (see 'man crypt')
1495 $salt =~ s/\+/X/g;
1496
1497 return crypt(encode("utf8", $pw), "\$5\$$salt\$");
1498}
1499
e143e9d8 15001;