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