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