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