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