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