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