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