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