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