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