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