]>
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; |
189f0321 | 7 | use Socket qw(AF_INET AF_INET6 AI_ALL AI_V4MAPPED AI_CANONNAME SOCK_DGRAM IPPROTO_TCP); |
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; |
f2c72fc3 | 22 | use JSON; |
e38bcd35 | 23 | use Text::ParseWords; |
7514b23a | 24 | use String::ShellQuote; |
c38cea65 | 25 | use Time::HiRes qw(usleep gettimeofday tv_interval alarm); |
d9f86d0d | 26 | use Scalar::Util 'weaken'; |
b18826ce SI |
27 | use Date::Format qw(time2str); |
28 | ||
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 | |
40682a69 | 50 | extract_sensitive_params |
23e0e0d7 | 51 | file_copy |
ce007e99 | 52 | get_host_arch |
c0647765 WB |
53 | O_PATH |
54 | O_TMPFILE | |
1b0bc6c0 WB |
55 | AT_EMPTY_PATH |
56 | AT_FDCWD | |
57 | CLONE_NEWNS | |
58 | CLONE_NEWUTS | |
59 | CLONE_NEWIPC | |
60 | CLONE_NEWUSER | |
61 | CLONE_NEWPID | |
62 | CLONE_NEWNET | |
e143e9d8 DM |
63 | ); |
64 | ||
65 | my $pvelogdir = "/var/log/pve"; | |
66 | my $pvetaskdir = "$pvelogdir/tasks"; | |
67 | ||
68 | mkdir $pvelogdir; | |
69 | mkdir $pvetaskdir; | |
70 | ||
cd9bd252 | 71 | my $IPV4OCTET = "(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])"; |
602ec0cd DM |
72 | our $IPV4RE = "(?:(?:$IPV4OCTET\\.){3}$IPV4OCTET)"; |
73 | my $IPV6H16 = "(?:[0-9a-fA-F]{1,4})"; | |
74 | my $IPV6LS32 = "(?:(?:$IPV4RE|$IPV6H16:$IPV6H16))"; | |
75 | ||
76 | our $IPV6RE = "(?:" . | |
77 | "(?:(?:" . "(?:$IPV6H16:){6})$IPV6LS32)|" . | |
78 | "(?:(?:" . "::(?:$IPV6H16:){5})$IPV6LS32)|" . | |
79 | "(?:(?:(?:" . "$IPV6H16)?::(?:$IPV6H16:){4})$IPV6LS32)|" . | |
80 | "(?:(?:(?:(?:$IPV6H16:){0,1}$IPV6H16)?::(?:$IPV6H16:){3})$IPV6LS32)|" . | |
81 | "(?:(?:(?:(?:$IPV6H16:){0,2}$IPV6H16)?::(?:$IPV6H16:){2})$IPV6LS32)|" . | |
82 | "(?:(?:(?:(?:$IPV6H16:){0,3}$IPV6H16)?::(?:$IPV6H16:){1})$IPV6LS32)|" . | |
83 | "(?:(?:(?:(?:$IPV6H16:){0,4}$IPV6H16)?::" . ")$IPV6LS32)|" . | |
84 | "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" . ")$IPV6H16)|" . | |
85 | "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" . ")))"; | |
86 | ||
176b1186 WB |
87 | our $IPRE = "(?:$IPV4RE|$IPV6RE)"; |
88 | ||
4c4bd104 FE |
89 | our $EMAIL_USER_RE = qr/[\w\+\-\~]+(\.[\w\+\-\~]+)*/; |
90 | our $EMAIL_RE = qr/$EMAIL_USER_RE@[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]+)*/; | |
91 | ||
be8f0477 | 92 | use constant {CLONE_NEWNS => 0x00020000, |
952fd95e WB |
93 | CLONE_NEWUTS => 0x04000000, |
94 | CLONE_NEWIPC => 0x08000000, | |
95 | CLONE_NEWUSER => 0x10000000, | |
96 | CLONE_NEWPID => 0x20000000, | |
be8f0477 | 97 | CLONE_NEWNET => 0x40000000}; |
952fd95e | 98 | |
26598a51 | 99 | use constant {O_PATH => 0x00200000, |
b260d4e3 | 100 | O_CLOEXEC => 0x00080000, |
26598a51 | 101 | O_TMPFILE => 0x00410000}; # This includes O_DIRECTORY |
44acb12c | 102 | |
1b0bc6c0 WB |
103 | use constant {AT_EMPTY_PATH => 0x1000, |
104 | AT_FDCWD => -100}; | |
6cf6b404 | 105 | |
0f0990f1 DM |
106 | sub run_with_timeout { |
107 | my ($timeout, $code, @param) = @_; | |
e143e9d8 | 108 | |
0f0990f1 | 109 | die "got timeout\n" if $timeout <= 0; |
e143e9d8 | 110 | |
c38cea65 | 111 | my $prev_alarm = alarm 0; # suspend outer alarm early |
0f0990f1 DM |
112 | |
113 | my $sigcount = 0; | |
e143e9d8 DM |
114 | |
115 | my $res; | |
116 | ||
e143e9d8 | 117 | eval { |
0f0990f1 DM |
118 | local $SIG{ALRM} = sub { $sigcount++; die "got timeout\n"; }; |
119 | local $SIG{PIPE} = sub { $sigcount++; die "broken pipe\n" }; | |
120 | local $SIG{__DIE__}; # see SA bug 4631 | |
e143e9d8 | 121 | |
c38cea65 | 122 | alarm($timeout); |
e143e9d8 | 123 | |
c38cea65 | 124 | eval { $res = &$code(@param); }; |
0f0990f1 DM |
125 | |
126 | alarm(0); # avoid race conditions | |
c38cea65 WB |
127 | |
128 | die $@ if $@; | |
0f0990f1 DM |
129 | }; |
130 | ||
131 | my $err = $@; | |
132 | ||
c38cea65 | 133 | alarm $prev_alarm; |
0f0990f1 | 134 | |
c38cea65 | 135 | # this shouldn't happen anymore? |
0f0990f1 DM |
136 | die "unknown error" if $sigcount && !$err; # seems to happen sometimes |
137 | ||
138 | die $err if $err; | |
139 | ||
140 | return $res; | |
141 | } | |
e143e9d8 | 142 | |
0f0990f1 | 143 | # flock: we use one file handle per process, so lock file |
d9f86d0d WB |
144 | # can be nested multiple times and succeeds for the same process. |
145 | # | |
146 | # Since this is the only way we lock now and we don't have the old | |
147 | # 'lock(); code(); unlock();' pattern anymore we do not actually need to | |
148 | # count how deep we're nesting. Therefore this hash now stores a weak reference | |
149 | # to a boolean telling us whether we already have a lock. | |
0f0990f1 DM |
150 | |
151 | my $lock_handles = {}; | |
152 | ||
493004a2 DM |
153 | sub lock_file_full { |
154 | my ($filename, $timeout, $shared, $code, @param) = @_; | |
0f0990f1 DM |
155 | |
156 | $timeout = 10 if !$timeout; | |
157 | ||
493004a2 DM |
158 | my $mode = $shared ? LOCK_SH : LOCK_EX; |
159 | ||
d9f86d0d | 160 | my $lockhash = ($lock_handles->{$$} //= {}); |
e143e9d8 | 161 | |
d9f86d0d WB |
162 | # Returns a locked file handle. |
163 | my $get_locked_file = sub { | |
164 | my $fh = IO::File->new(">>$filename") | |
165 | or die "can't open file - $!\n"; | |
166 | ||
167 | if (!flock($fh, $mode|LOCK_NB)) { | |
91bae4c0 | 168 | print STDERR "trying to acquire lock...\n"; |
b5d12b08 DM |
169 | my $success; |
170 | while(1) { | |
d9f86d0d | 171 | $success = flock($fh, $mode); |
b5d12b08 DM |
172 | # try again on EINTR (see bug #273) |
173 | if ($success || ($! != EINTR)) { | |
174 | last; | |
175 | } | |
176 | } | |
d9f86d0d WB |
177 | if (!$success) { |
178 | print STDERR " failed\n"; | |
179 | die "can't acquire lock '$filename' - $!\n"; | |
180 | } | |
181 | print STDERR " OK\n"; | |
182 | } | |
183 | ||
184 | return $fh; | |
e143e9d8 DM |
185 | }; |
186 | ||
0f0990f1 | 187 | my $res; |
d9f86d0d WB |
188 | my $checkptr = $lockhash->{$filename}; |
189 | my $check = 0; # This must not go out of scope before running the code. | |
190 | my $local_fh; # This must stay local | |
191 | if (!$checkptr || !$$checkptr) { | |
192 | # We cannot create a weak reference in a single atomic step, so we first | |
193 | # create a false-value, then create a reference to it, then weaken it, | |
194 | # and after successfully locking the file we change the boolean value. | |
195 | # | |
196 | # The reason for this is that if an outer SIGALRM throws an exception | |
197 | # between creating the reference and weakening it, a subsequent call to | |
198 | # lock_file_full() will see a leftover full reference to a valid | |
199 | # variable. This variable must be 0 in order for said call to attempt to | |
200 | # lock the file anew. | |
201 | # | |
202 | # An externally triggered exception elsewhere in the code will cause the | |
203 | # weak reference to become 'undef', and since the file handle is only | |
204 | # stored in the local scope in $local_fh, the file will be closed by | |
205 | # perl's cleanup routines as well. | |
206 | # | |
207 | # This still assumes that an IO::File handle can properly deal with such | |
208 | # exceptions thrown during its own destruction, but that's up to perls | |
209 | # guts now. | |
210 | $lockhash->{$filename} = \$check; | |
211 | weaken $lockhash->{$filename}; | |
212 | $local_fh = eval { run_with_timeout($timeout, $get_locked_file) }; | |
213 | if ($@) { | |
214 | $@ = "can't lock file '$filename' - $@"; | |
215 | return undef; | |
f127adab | 216 | } |
d9f86d0d | 217 | $check = 1; |
e143e9d8 | 218 | } |
d9f86d0d WB |
219 | $res = eval { &$code(@param); }; |
220 | return undef if $@; | |
e143e9d8 DM |
221 | return $res; |
222 | } | |
223 | ||
493004a2 DM |
224 | |
225 | sub lock_file { | |
226 | my ($filename, $timeout, $code, @param) = @_; | |
227 | ||
228 | return lock_file_full($filename, $timeout, 0, $code, @param); | |
229 | } | |
230 | ||
e143e9d8 DM |
231 | sub file_set_contents { |
232 | my ($filename, $data, $perm) = @_; | |
233 | ||
234 | $perm = 0644 if !defined($perm); | |
235 | ||
236 | my $tmpname = "$filename.tmp.$$"; | |
237 | ||
238 | eval { | |
ce338f4f WB |
239 | my ($fh, $tries) = (undef, 0); |
240 | while (!$fh && $tries++ < 3) { | |
241 | $fh = IO::File->new($tmpname, O_WRONLY|O_CREAT|O_EXCL, $perm); | |
242 | if (!$fh && $! == EEXIST) { | |
243 | unlink($tmpname) or die "unable to delete old temp file: $!\n"; | |
244 | } | |
245 | } | |
e143e9d8 DM |
246 | die "unable to open file '$tmpname' - $!\n" if !$fh; |
247 | die "unable to write '$tmpname' - $!\n" unless print $fh $data; | |
248 | die "closing file '$tmpname' failed - $!\n" unless close $fh; | |
249 | }; | |
250 | my $err = $@; | |
251 | ||
252 | if ($err) { | |
253 | unlink $tmpname; | |
254 | die $err; | |
255 | } | |
256 | ||
257 | if (!rename($tmpname, $filename)) { | |
258 | my $msg = "close (rename) atomic file '$filename' failed: $!\n"; | |
259 | unlink $tmpname; | |
813a5c0d | 260 | die $msg; |
e143e9d8 DM |
261 | } |
262 | } | |
263 | ||
264 | sub file_get_contents { | |
265 | my ($filename, $max) = @_; | |
266 | ||
267 | my $fh = IO::File->new($filename, "r") || | |
268 | die "can't open '$filename' - $!\n"; | |
269 | ||
034a8181 | 270 | my $content = safe_read_from($fh, $max, 0, $filename); |
e143e9d8 DM |
271 | |
272 | close $fh; | |
273 | ||
274 | return $content; | |
275 | } | |
276 | ||
23e0e0d7 WL |
277 | sub file_copy { |
278 | my ($filename, $dst, $max, $perm) = @_; | |
279 | ||
280 | file_set_contents ($dst, file_get_contents($filename, $max), $perm); | |
281 | } | |
282 | ||
e143e9d8 DM |
283 | sub file_read_firstline { |
284 | my ($filename) = @_; | |
285 | ||
286 | my $fh = IO::File->new ($filename, "r"); | |
287 | return undef if !$fh; | |
288 | my $res = <$fh>; | |
88955a2e | 289 | chomp $res if $res; |
e143e9d8 DM |
290 | $fh->close; |
291 | return $res; | |
292 | } | |
293 | ||
294 | sub safe_read_from { | |
034a8181 | 295 | my ($fh, $max, $oneline, $filename) = @_; |
e143e9d8 | 296 | |
8fb28ab9 FG |
297 | # pmxcfs file size limit |
298 | $max = 512*1024 if !$max; | |
e143e9d8 | 299 | |
034a8181 DM |
300 | my $subject = defined($filename) ? "file '$filename'" : 'input'; |
301 | ||
e143e9d8 DM |
302 | my $br = 0; |
303 | my $input = ''; | |
304 | my $count; | |
305 | while ($count = sysread($fh, $input, 8192, $br)) { | |
306 | $br += $count; | |
034a8181 | 307 | die "$subject too long - aborting\n" if $br > $max; |
e143e9d8 DM |
308 | if ($oneline && $input =~ m/^(.*)\n/) { |
309 | $input = $1; | |
310 | last; | |
311 | } | |
813a5c0d | 312 | } |
034a8181 | 313 | die "unable to read $subject - $!\n" if !defined($count); |
e143e9d8 DM |
314 | |
315 | return $input; | |
316 | } | |
317 | ||
bd9c3a36 WB |
318 | # The $cmd parameter can be: |
319 | # -) a string | |
320 | # This is generally executed by passing it to the shell with the -c option. | |
321 | # However, it can be executed in one of two ways, depending on whether | |
322 | # there's a pipe involved: | |
323 | # *) with pipe: passed explicitly to bash -c, prefixed with: | |
324 | # set -o pipefail && | |
325 | # *) without a pipe: passed to perl's open3 which uses 'sh -c' | |
326 | # (Note that this may result in two different syntax requirements!) | |
327 | # FIXME? | |
328 | # -) an array of arguments (strings) | |
329 | # Will be executed without interference from a shell. (Parameters are passed | |
330 | # as is, no escape sequences of strings will be touched.) | |
fcdc0cfc WB |
331 | # -) an array of arrays |
332 | # Each array represents a command, and each command's output is piped into | |
333 | # the following command's standard input. | |
334 | # For this a shell command string is created with pipe symbols between each | |
335 | # command. | |
336 | # Each command is a list of strings meant to end up in the final command | |
337 | # unchanged. In order to achieve this, every argument is shell-quoted. | |
338 | # Quoting can be disabled for a particular argument by turning it into a | |
339 | # reference, this allows inserting arbitrary shell options. | |
340 | # For instance: the $cmd [ [ 'echo', 'hello', \'>/dev/null' ] ] will not | |
341 | # produce any output, while the $cmd [ [ 'echo', 'hello', '>/dev/null' ] ] | |
342 | # will literally print: hello >/dev/null | |
e143e9d8 DM |
343 | sub run_command { |
344 | my ($cmd, %param) = @_; | |
345 | ||
346 | my $old_umask; | |
ded47a61 | 347 | my $cmdstr; |
e143e9d8 | 348 | |
fcdc0cfc WB |
349 | if (my $ref = ref($cmd)) { |
350 | if (ref($cmd->[0])) { | |
351 | $cmdstr = 'set -o pipefail && '; | |
352 | my $pipe = ''; | |
353 | foreach my $command (@$cmd) { | |
354 | # concatenate quoted parameters | |
355 | # strings which are passed by reference are NOT shell quoted | |
356 | $cmdstr .= $pipe . join(' ', map { ref($_) ? $$_ : shellquote($_) } @$command); | |
357 | $pipe = ' | '; | |
358 | } | |
1a0c0103 | 359 | $cmd = [ '/bin/bash', '-c', "$cmdstr" ]; |
fcdc0cfc WB |
360 | } else { |
361 | $cmdstr = cmd2string($cmd); | |
362 | } | |
363 | } else { | |
ded47a61 | 364 | $cmdstr = $cmd; |
22d4efe6 | 365 | if ($cmd =~ m/\|/) { |
e0cabd2c DM |
366 | # see 'man bash' for option pipefail |
367 | $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ]; | |
368 | } else { | |
369 | $cmd = [ $cmd ]; | |
370 | } | |
ded47a61 | 371 | } |
e143e9d8 DM |
372 | |
373 | my $errmsg; | |
374 | my $laststderr; | |
375 | my $timeout; | |
376 | my $oldtimeout; | |
377 | my $pid; | |
38d9aa12 | 378 | my $exitcode = -1; |
e143e9d8 | 379 | |
4630cb95 DM |
380 | my $outfunc; |
381 | my $errfunc; | |
382 | my $logfunc; | |
383 | my $input; | |
384 | my $output; | |
a417477c | 385 | my $afterfork; |
7e826928 | 386 | my $noerr; |
0f3f314e | 387 | my $keeplocale; |
ed61b9d6 | 388 | my $quiet; |
4630cb95 | 389 | |
e143e9d8 | 390 | eval { |
e143e9d8 DM |
391 | |
392 | foreach my $p (keys %param) { | |
393 | if ($p eq 'timeout') { | |
394 | $timeout = $param{$p}; | |
395 | } elsif ($p eq 'umask') { | |
eb9e24df | 396 | $old_umask = umask($param{$p}); |
e143e9d8 DM |
397 | } elsif ($p eq 'errmsg') { |
398 | $errmsg = $param{$p}; | |
e143e9d8 DM |
399 | } elsif ($p eq 'input') { |
400 | $input = $param{$p}; | |
1c50a24a DM |
401 | } elsif ($p eq 'output') { |
402 | $output = $param{$p}; | |
e143e9d8 DM |
403 | } elsif ($p eq 'outfunc') { |
404 | $outfunc = $param{$p}; | |
405 | } elsif ($p eq 'errfunc') { | |
406 | $errfunc = $param{$p}; | |
776fbfa8 DM |
407 | } elsif ($p eq 'logfunc') { |
408 | $logfunc = $param{$p}; | |
a417477c DM |
409 | } elsif ($p eq 'afterfork') { |
410 | $afterfork = $param{$p}; | |
7e826928 TL |
411 | } elsif ($p eq 'noerr') { |
412 | $noerr = $param{$p}; | |
0f3f314e DC |
413 | } elsif ($p eq 'keeplocale') { |
414 | $keeplocale = $param{$p}; | |
ed61b9d6 TL |
415 | } elsif ($p eq 'quiet') { |
416 | $quiet = $param{$p}; | |
e143e9d8 DM |
417 | } else { |
418 | die "got unknown parameter '$p' for run_command\n"; | |
419 | } | |
420 | } | |
421 | ||
4630cb95 DM |
422 | if ($errmsg) { |
423 | my $origerrfunc = $errfunc; | |
424 | $errfunc = sub { | |
425 | if ($laststderr) { | |
426 | if ($origerrfunc) { | |
427 | &$origerrfunc("$laststderr\n"); | |
428 | } else { | |
429 | print STDERR "$laststderr\n" if $laststderr; | |
430 | } | |
431 | } | |
813a5c0d | 432 | $laststderr = shift; |
4630cb95 DM |
433 | }; |
434 | } | |
435 | ||
1c50a24a DM |
436 | my $reader = $output && $output =~ m/^>&/ ? $output : IO::File->new(); |
437 | my $writer = $input && $input =~ m/^<&/ ? $input : IO::File->new(); | |
438 | my $error = IO::File->new(); | |
439 | ||
e143e9d8 DM |
440 | my $orig_pid = $$; |
441 | ||
442 | eval { | |
0f3f314e | 443 | local $ENV{LC_ALL} = 'C' if !$keeplocale; |
e143e9d8 DM |
444 | |
445 | # suppress LVM warnings like: "File descriptor 3 left open"; | |
446 | local $ENV{LVM_SUPPRESS_FD_WARNINGS} = "1"; | |
447 | ||
448 | $pid = open3($writer, $reader, $error, @$cmd) || die $!; | |
f38995ab DM |
449 | |
450 | # if we pipe fron STDIN, open3 closes STDIN, so we we | |
451 | # a perl warning "Filehandle STDIN reopened as GENXYZ .. " | |
452 | # as soon as we open a new file. | |
453 | # to avoid that we open /dev/null | |
454 | if (!ref($writer) && !defined(fileno(STDIN))) { | |
455 | POSIX::close(0); | |
456 | open(STDIN, "</dev/null"); | |
457 | } | |
e143e9d8 DM |
458 | }; |
459 | ||
460 | my $err = $@; | |
461 | ||
462 | # catch exec errors | |
463 | if ($orig_pid != $$) { | |
464 | warn "ERROR: $err"; | |
813a5c0d DC |
465 | POSIX::_exit (1); |
466 | kill ('KILL', $$); | |
e143e9d8 DM |
467 | } |
468 | ||
469 | die $err if $err; | |
470 | ||
471 | local $SIG{ALRM} = sub { die "got timeout\n"; } if $timeout; | |
472 | $oldtimeout = alarm($timeout) if $timeout; | |
473 | ||
a417477c DM |
474 | &$afterfork() if $afterfork; |
475 | ||
f38995ab DM |
476 | if (ref($writer)) { |
477 | print $writer $input if defined $input; | |
478 | close $writer; | |
479 | } | |
e143e9d8 DM |
480 | |
481 | my $select = new IO::Select; | |
f38995ab | 482 | $select->add($reader) if ref($reader); |
e143e9d8 DM |
483 | $select->add($error); |
484 | ||
485 | my $outlog = ''; | |
486 | my $errlog = ''; | |
487 | ||
488 | my $starttime = time(); | |
489 | ||
490 | while ($select->count) { | |
491 | my @handles = $select->can_read(1); | |
492 | ||
493 | foreach my $h (@handles) { | |
494 | my $buf = ''; | |
495 | my $count = sysread ($h, $buf, 4096); | |
496 | if (!defined ($count)) { | |
497 | my $err = $!; | |
498 | kill (9, $pid); | |
499 | waitpid ($pid, 0); | |
500 | die $err; | |
501 | } | |
502 | $select->remove ($h) if !$count; | |
503 | if ($h eq $reader) { | |
776fbfa8 | 504 | if ($outfunc || $logfunc) { |
e143e9d8 | 505 | eval { |
ba104d67 | 506 | while ($buf =~ s/^([^\010\r\n]*)(?:\n|(?:\010)+|\r\n?)//) { |
cb9db10c DC |
507 | my $line = $outlog . $1; |
508 | $outlog = ''; | |
776fbfa8 DM |
509 | &$outfunc($line) if $outfunc; |
510 | &$logfunc($line) if $logfunc; | |
e143e9d8 | 511 | } |
cb9db10c | 512 | $outlog .= $buf; |
e143e9d8 DM |
513 | }; |
514 | my $err = $@; | |
515 | if ($err) { | |
516 | kill (9, $pid); | |
517 | waitpid ($pid, 0); | |
518 | die $err; | |
519 | } | |
ed61b9d6 | 520 | } elsif (!$quiet) { |
e143e9d8 DM |
521 | print $buf; |
522 | *STDOUT->flush(); | |
523 | } | |
524 | } elsif ($h eq $error) { | |
776fbfa8 | 525 | if ($errfunc || $logfunc) { |
e143e9d8 | 526 | eval { |
ba104d67 | 527 | while ($buf =~ s/^([^\010\r\n]*)(?:\n|(?:\010)+|\r\n?)//) { |
cb9db10c DC |
528 | my $line = $errlog . $1; |
529 | $errlog = ''; | |
776fbfa8 DM |
530 | &$errfunc($line) if $errfunc; |
531 | &$logfunc($line) if $logfunc; | |
e143e9d8 | 532 | } |
cb9db10c | 533 | $errlog .= $buf; |
e143e9d8 DM |
534 | }; |
535 | my $err = $@; | |
536 | if ($err) { | |
537 | kill (9, $pid); | |
538 | waitpid ($pid, 0); | |
539 | die $err; | |
540 | } | |
ed61b9d6 | 541 | } elsif (!$quiet) { |
e143e9d8 DM |
542 | print STDERR $buf; |
543 | *STDERR->flush(); | |
544 | } | |
545 | } | |
546 | } | |
547 | } | |
548 | ||
549 | &$outfunc($outlog) if $outfunc && $outlog; | |
776fbfa8 DM |
550 | &$logfunc($outlog) if $logfunc && $outlog; |
551 | ||
e143e9d8 | 552 | &$errfunc($errlog) if $errfunc && $errlog; |
776fbfa8 | 553 | &$logfunc($errlog) if $logfunc && $errlog; |
e143e9d8 DM |
554 | |
555 | waitpid ($pid, 0); | |
813a5c0d | 556 | |
e143e9d8 DM |
557 | if ($? == -1) { |
558 | die "failed to execute\n"; | |
559 | } elsif (my $sig = ($? & 127)) { | |
560 | die "got signal $sig\n"; | |
7e826928 TL |
561 | } elsif ($exitcode = ($? >> 8)) { |
562 | if (!($exitcode == 24 && ($cmdstr =~ m|^(\S+/)?rsync\s|))) { | |
1c50a24a DM |
563 | if ($errmsg && $laststderr) { |
564 | my $lerr = $laststderr; | |
565 | $laststderr = undef; | |
566 | die "$lerr\n"; | |
567 | } | |
7e826928 | 568 | die "exit code $exitcode\n"; |
e143e9d8 | 569 | } |
e143e9d8 DM |
570 | } |
571 | ||
572 | alarm(0); | |
573 | }; | |
574 | ||
575 | my $err = $@; | |
576 | ||
577 | alarm(0); | |
578 | ||
4630cb95 DM |
579 | if ($errmsg && $laststderr) { |
580 | &$errfunc(undef); # flush laststderr | |
581 | } | |
e143e9d8 DM |
582 | |
583 | umask ($old_umask) if defined($old_umask); | |
584 | ||
585 | alarm($oldtimeout) if $oldtimeout; | |
586 | ||
587 | if ($err) { | |
588 | if ($pid && ($err eq "got timeout\n")) { | |
589 | kill (9, $pid); | |
590 | waitpid ($pid, 0); | |
591 | die "command '$cmdstr' failed: $err"; | |
592 | } | |
593 | ||
594 | if ($errmsg) { | |
adbc988d | 595 | $err =~ s/^usermod:\s*// if $cmdstr =~ m|^(\S+/)?usermod\s|; |
e143e9d8 | 596 | die "$errmsg: $err"; |
7e826928 | 597 | } elsif(!$noerr) { |
e143e9d8 DM |
598 | die "command '$cmdstr' failed: $err"; |
599 | } | |
600 | } | |
1c50a24a | 601 | |
7e826928 | 602 | return $exitcode; |
e143e9d8 DM |
603 | } |
604 | ||
2d38b8a1 TL |
605 | # Run a command with a tcp socket as standard input. |
606 | sub pipe_socket_to_command { | |
607 | my ($cmd, $ip, $port) = @_; | |
608 | ||
609 | my $params = { | |
610 | Listen => 1, | |
611 | ReuseAddr => 1, | |
612 | Proto => &Socket::IPPROTO_TCP, | |
613 | GetAddrInfoFlags => 0, | |
614 | LocalAddr => $ip, | |
615 | LocalPort => $port, | |
616 | }; | |
617 | my $socket = IO::Socket::IP->new(%$params) or die "failed to open socket: $!\n"; | |
618 | ||
619 | print "$ip\n$port\n"; # tell remote where to connect | |
620 | *STDOUT->flush(); | |
621 | ||
622 | alarm 0; | |
623 | local $SIG{ALRM} = sub { die "timed out waiting for client\n" }; | |
624 | alarm 30; | |
625 | my $client = $socket->accept; # Wait for a client | |
626 | alarm 0; | |
627 | close($socket); | |
628 | ||
629 | # We want that the command talks over the TCP socket and takes | |
630 | # ownership of it, so that when it closes it the connection is | |
631 | # terminated, so we need to be able to close the socket. So we | |
632 | # can't really use PVE::Tools::run_command(). | |
633 | my $pid = fork() // die "fork failed: $!\n"; | |
634 | if (!$pid) { | |
635 | POSIX::dup2(fileno($client), 0); | |
636 | POSIX::dup2(fileno($client), 1); | |
637 | close($client); | |
638 | exec {$cmd->[0]} @$cmd or do { | |
639 | warn "exec failed: $!\n"; | |
640 | POSIX::_exit(1); | |
641 | }; | |
642 | } | |
643 | ||
644 | close($client); | |
645 | if (waitpid($pid, 0) != $pid) { | |
646 | kill(15 => $pid); # if we got interrupted terminate the child | |
647 | my $count = 0; | |
648 | while (waitpid($pid, POSIX::WNOHANG) != $pid) { | |
649 | usleep(100000); | |
650 | $count++; | |
651 | kill(9 => $pid), last if $count > 300; # 30 second timeout | |
652 | } | |
653 | } | |
654 | if (my $sig = ($? & 127)) { | |
655 | die "got signal $sig\n"; | |
656 | } elsif (my $exitcode = ($? >> 8)) { | |
657 | die "exit code $exitcode\n"; | |
658 | } | |
659 | ||
660 | return undef; | |
661 | } | |
662 | ||
e143e9d8 | 663 | sub split_list { |
0a3de87e | 664 | my $listtxt = shift // ''; |
e143e9d8 | 665 | |
d2b0374d | 666 | return split (/\0/, $listtxt) if $listtxt =~ m/\0/; |
813a5c0d | 667 | |
d2b0374d | 668 | $listtxt =~ s/[,;]/ /g; |
e143e9d8 DM |
669 | $listtxt =~ s/^\s+//; |
670 | ||
671 | my @data = split (/\s+/, $listtxt); | |
672 | ||
673 | return @data; | |
674 | } | |
675 | ||
676 | sub trim { | |
677 | my $txt = shift; | |
678 | ||
679 | return $txt if !defined($txt); | |
680 | ||
681 | $txt =~ s/^\s+//; | |
682 | $txt =~ s/\s+$//; | |
813a5c0d | 683 | |
e143e9d8 DM |
684 | return $txt; |
685 | } | |
686 | ||
687 | # simple uri templates like "/vms/{vmid}" | |
688 | sub template_replace { | |
689 | my ($tmpl, $data) = @_; | |
690 | ||
3250f5c7 | 691 | return $tmpl if !$tmpl; |
813a5c0d | 692 | |
e143e9d8 | 693 | my $res = ''; |
14410e5f | 694 | while ($tmpl =~ m/([^{]+)?(\{([^}]+)\})?/g) { |
e143e9d8 DM |
695 | $res .= $1 if $1; |
696 | $res .= ($data->{$3} || '-') if $2; | |
697 | } | |
698 | return $res; | |
699 | } | |
700 | ||
701 | sub safe_print { | |
702 | my ($filename, $fh, $data) = @_; | |
703 | ||
704 | return if !$data; | |
705 | ||
706 | my $res = print $fh $data; | |
707 | ||
708 | die "write to '$filename' failed\n" if !$res; | |
709 | } | |
710 | ||
711 | sub debmirrors { | |
712 | ||
713 | return { | |
714 | 'at' => 'ftp.at.debian.org', | |
715 | 'au' => 'ftp.au.debian.org', | |
716 | 'be' => 'ftp.be.debian.org', | |
717 | 'bg' => 'ftp.bg.debian.org', | |
718 | 'br' => 'ftp.br.debian.org', | |
719 | 'ca' => 'ftp.ca.debian.org', | |
720 | 'ch' => 'ftp.ch.debian.org', | |
721 | 'cl' => 'ftp.cl.debian.org', | |
722 | 'cz' => 'ftp.cz.debian.org', | |
723 | 'de' => 'ftp.de.debian.org', | |
724 | 'dk' => 'ftp.dk.debian.org', | |
725 | 'ee' => 'ftp.ee.debian.org', | |
726 | 'es' => 'ftp.es.debian.org', | |
727 | 'fi' => 'ftp.fi.debian.org', | |
728 | 'fr' => 'ftp.fr.debian.org', | |
729 | 'gr' => 'ftp.gr.debian.org', | |
730 | 'hk' => 'ftp.hk.debian.org', | |
731 | 'hr' => 'ftp.hr.debian.org', | |
732 | 'hu' => 'ftp.hu.debian.org', | |
733 | 'ie' => 'ftp.ie.debian.org', | |
734 | 'is' => 'ftp.is.debian.org', | |
735 | 'it' => 'ftp.it.debian.org', | |
736 | 'jp' => 'ftp.jp.debian.org', | |
737 | 'kr' => 'ftp.kr.debian.org', | |
738 | 'mx' => 'ftp.mx.debian.org', | |
739 | 'nl' => 'ftp.nl.debian.org', | |
740 | 'no' => 'ftp.no.debian.org', | |
741 | 'nz' => 'ftp.nz.debian.org', | |
742 | 'pl' => 'ftp.pl.debian.org', | |
743 | 'pt' => 'ftp.pt.debian.org', | |
744 | 'ro' => 'ftp.ro.debian.org', | |
745 | 'ru' => 'ftp.ru.debian.org', | |
746 | 'se' => 'ftp.se.debian.org', | |
747 | 'si' => 'ftp.si.debian.org', | |
748 | 'sk' => 'ftp.sk.debian.org', | |
749 | 'tr' => 'ftp.tr.debian.org', | |
750 | 'tw' => 'ftp.tw.debian.org', | |
751 | 'gb' => 'ftp.uk.debian.org', | |
752 | 'us' => 'ftp.us.debian.org', | |
753 | }; | |
754 | } | |
755 | ||
910d57b0 DM |
756 | my $keymaphash = { |
757 | 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'], | |
758 | 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ], | |
813a5c0d | 759 | 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ], |
5a5ca434 DM |
760 | 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', undef], |
761 | 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', undef ], | |
910d57b0 DM |
762 | 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'], |
763 | #'et' => [], # Ethopia or Estonia ?? | |
764 | 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'], | |
765 | #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'], | |
766 | 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'], | |
767 | 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'], | |
768 | 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'], | |
769 | 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'], | |
770 | #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2? | |
771 | 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef], | |
772 | 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'], | |
773 | 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'], | |
774 | 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef], | |
775 | 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'], | |
776 | #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7? | |
777 | 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'], | |
778 | 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef], | |
779 | #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?], | |
813a5c0d | 780 | 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'], |
910d57b0 DM |
781 | 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef], |
782 | 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'], | |
783 | 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'], | |
fb3a1b29 | 784 | #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # don't know? |
910d57b0 | 785 | 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef], |
9934cd0b | 786 | 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'], |
910d57b0 | 787 | #'th' => [], |
c10cc112 | 788 | 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef], |
910d57b0 DM |
789 | }; |
790 | ||
791 | my $kvmkeymaparray = []; | |
0a7de820 | 792 | foreach my $lc (sort keys %$keymaphash) { |
910d57b0 DM |
793 | push @$kvmkeymaparray, $keymaphash->{$lc}->[1]; |
794 | } | |
795 | ||
e143e9d8 | 796 | sub kvmkeymaps { |
910d57b0 DM |
797 | return $keymaphash; |
798 | } | |
799 | ||
800 | sub kvmkeymaplist { | |
801 | return $kvmkeymaparray; | |
e143e9d8 DM |
802 | } |
803 | ||
804 | sub extract_param { | |
805 | my ($param, $key) = @_; | |
806 | ||
807 | my $res = $param->{$key}; | |
808 | delete $param->{$key}; | |
809 | ||
810 | return $res; | |
811 | } | |
812 | ||
9d52694b | 813 | # For extracting sensitive keys (e.g. password), to avoid writing them to www-data owned configs |
40682a69 DC |
814 | sub extract_sensitive_params :prototype($$$) { |
815 | my ($param, $sensitive_list, $delete_list) = @_; | |
816 | ||
40682a69 DC |
817 | my %delete = map { $_ => 1 } ($delete_list || [])->@*; |
818 | ||
9d52694b | 819 | my $sensitive = {}; |
40682a69 | 820 | for my $opt (@$sensitive_list) { |
9d52694b TL |
821 | # handle deletions as explicitly setting `undef`, so subs which only have $param but not |
822 | # $delete_list available can recognize them. Afterwards new values may override. | |
40682a69 DC |
823 | if (exists($delete{$opt})) { |
824 | $sensitive->{$opt} = undef; | |
825 | } | |
826 | ||
827 | if (defined(my $value = extract_param($param, $opt))) { | |
828 | $sensitive->{$opt} = $value; | |
829 | } | |
830 | } | |
831 | ||
832 | return $sensitive; | |
833 | } | |
834 | ||
eb7047f6 | 835 | # Note: we use this to wait until vncterm/spiceterm is ready |
ec6d95b4 | 836 | sub wait_for_vnc_port { |
590b924e | 837 | my ($port, $family, $timeout) = @_; |
ec6d95b4 DM |
838 | |
839 | $timeout = 5 if !$timeout; | |
eb7047f6 DM |
840 | my $sleeptime = 0; |
841 | my $starttime = [gettimeofday]; | |
842 | my $elapsed; | |
ec6d95b4 | 843 | |
590b924e TL |
844 | my $cmd = ['/bin/ss', '-Htln', "sport = :$port"]; |
845 | push @$cmd, $family == AF_INET6 ? '-6' : '-4' if defined($family); | |
846 | ||
9a41a7b7 | 847 | my $found; |
eb7047f6 | 848 | while (($elapsed = tv_interval($starttime)) < $timeout) { |
9a41a7b7 | 849 | # -Htln = don't print header, tcp, listening sockets only, numeric ports |
590b924e | 850 | run_command($cmd, outfunc => sub { |
9a41a7b7 TL |
851 | my $line = shift; |
852 | if ($line =~ m/^LISTEN\s+\d+\s+\d+\s+\S+:(\d+)\s/) { | |
853 | $found = 1 if ($port == $1); | |
ec6d95b4 | 854 | } |
9a41a7b7 TL |
855 | }); |
856 | return 1 if $found; | |
eb7047f6 DM |
857 | $sleeptime += 100000 if $sleeptime < 1000000; |
858 | usleep($sleeptime); | |
ec6d95b4 DM |
859 | } |
860 | ||
8fd0d634 | 861 | die "Timeout while waiting for port '$port' to get ready!\n"; |
ec6d95b4 DM |
862 | } |
863 | ||
59b3f563 | 864 | sub next_unused_port { |
c14960cc | 865 | my ($range_start, $range_end, $family, $address) = @_; |
59b3f563 DM |
866 | |
867 | # We use a file to register allocated ports. | |
868 | # Those registrations expires after $expiretime. | |
869 | # We use this to avoid race conditions between | |
870 | # allocation and use of ports. | |
871 | ||
872 | my $filename = "/var/tmp/pve-reserved-ports"; | |
e143e9d8 | 873 | |
59b3f563 | 874 | my $code = sub { |
e143e9d8 | 875 | |
59b3f563 DM |
876 | my $expiretime = 5; |
877 | my $ctime = time(); | |
e143e9d8 | 878 | |
59b3f563 DM |
879 | my $ports = {}; |
880 | ||
881 | if (my $fh = IO::File->new ($filename, "r")) { | |
882 | while (my $line = <$fh>) { | |
883 | if ($line =~ m/^(\d+)\s(\d+)$/) { | |
884 | my ($port, $timestamp) = ($1, $2); | |
885 | if (($timestamp + $expiretime) > $ctime) { | |
886 | $ports->{$port} = $timestamp; # not expired | |
813a5c0d | 887 | } |
59b3f563 DM |
888 | } |
889 | } | |
e143e9d8 | 890 | } |
813a5c0d | 891 | |
59b3f563 | 892 | my $newport; |
c14960cc WB |
893 | my %sockargs = (Listen => 5, |
894 | ReuseAddr => 1, | |
895 | Family => $family, | |
a0ecb159 | 896 | Proto => IPPROTO_TCP, |
c14960cc WB |
897 | GetAddrInfoFlags => 0); |
898 | $sockargs{LocalAddr} = $address if defined($address); | |
59b3f563 DM |
899 | |
900 | for (my $p = $range_start; $p < $range_end; $p++) { | |
901 | next if $ports->{$p}; # reserved | |
902 | ||
c14960cc WB |
903 | $sockargs{LocalPort} = $p; |
904 | my $sock = IO::Socket::IP->new(%sockargs); | |
59b3f563 DM |
905 | |
906 | if ($sock) { | |
907 | close($sock); | |
908 | $newport = $p; | |
909 | $ports->{$p} = $ctime; | |
910 | last; | |
911 | } | |
912 | } | |
813a5c0d | 913 | |
59b3f563 DM |
914 | my $data = ""; |
915 | foreach my $p (keys %$ports) { | |
916 | $data .= "$p $ports->{$p}\n"; | |
917 | } | |
813a5c0d | 918 | |
59b3f563 | 919 | file_set_contents($filename, $data); |
e143e9d8 | 920 | |
59b3f563 DM |
921 | return $newport; |
922 | }; | |
923 | ||
3c476ed5 | 924 | my $p = lock_file('/var/lock/pve-ports.lck', 10, $code); |
59b3f563 | 925 | die $@ if $@; |
813a5c0d | 926 | |
59b3f563 DM |
927 | die "unable to find free port (${range_start}-${range_end})\n" if !$p; |
928 | ||
929 | return $p; | |
930 | } | |
931 | ||
932 | sub next_migrate_port { | |
c14960cc WB |
933 | my ($family, $address) = @_; |
934 | return next_unused_port(60000, 60050, $family, $address); | |
59b3f563 DM |
935 | } |
936 | ||
937 | sub next_vnc_port { | |
c14960cc WB |
938 | my ($family, $address) = @_; |
939 | return next_unused_port(5900, 6000, $family, $address); | |
59b3f563 | 940 | } |
e143e9d8 | 941 | |
30aeac2e DC |
942 | sub spice_port_range { |
943 | return (61000, 61999); | |
944 | } | |
945 | ||
2f13cbb5 | 946 | sub next_spice_port { |
c14960cc | 947 | my ($family, $address) = @_; |
30aeac2e | 948 | return next_unused_port(spice_port_range(), $family, $address); |
2f13cbb5 DM |
949 | } |
950 | ||
893ec6f2 WB |
951 | sub must_stringify { |
952 | my ($value) = @_; | |
953 | eval { $value = "$value" }; | |
954 | return "error turning value into a string: $@" if $@; | |
955 | return $value; | |
956 | } | |
957 | ||
72fba911 EK |
958 | # sigkill after $timeout a $sub running in a fork if it can't write a pipe |
959 | # the $sub has to return a single scalar | |
960 | sub run_fork_with_timeout { | |
961 | my ($timeout, $sub) = @_; | |
962 | ||
963 | my $res; | |
964 | my $error; | |
965 | my $pipe_out = IO::Pipe->new(); | |
72fba911 EK |
966 | |
967 | # disable pending alarms, save their remaining time | |
968 | my $prev_alarm = alarm 0; | |
969 | ||
eead1cca | 970 | # avoid leaving a zombie if the parent gets interrupted |
72fba911 | 971 | my $sig_received; |
72fba911 EK |
972 | |
973 | my $child = fork(); | |
974 | if (!defined($child)) { | |
975 | die "fork failed: $!\n"; | |
976 | return $res; | |
977 | } | |
978 | ||
979 | if (!$child) { | |
980 | $pipe_out->writer(); | |
72fba911 EK |
981 | |
982 | eval { | |
983 | $res = $sub->(); | |
f2c72fc3 | 984 | print {$pipe_out} encode_json({ result => $res }); |
72fba911 EK |
985 | $pipe_out->flush(); |
986 | }; | |
987 | if (my $err = $@) { | |
893ec6f2 | 988 | print {$pipe_out} encode_json({ error => must_stringify($err) }); |
f2c72fc3 | 989 | $pipe_out->flush(); |
72fba911 EK |
990 | POSIX::_exit(1); |
991 | } | |
992 | POSIX::_exit(0); | |
993 | } | |
994 | ||
2e353dfb DC |
995 | local $SIG{INT} = sub { $sig_received++; }; |
996 | local $SIG{TERM} = sub { | |
997 | $error //= "interrupted by unexpected signal\n"; | |
998 | kill('TERM', $child); | |
999 | }; | |
1000 | ||
72fba911 | 1001 | $pipe_out->reader(); |
72fba911 EK |
1002 | |
1003 | my $readvalues = sub { | |
1004 | local $/ = undef; | |
2e353dfb | 1005 | my $child_res = decode_json(readline_nointr($pipe_out)); |
f2c72fc3 TL |
1006 | $res = $child_res->{result}; |
1007 | $error = $child_res->{error}; | |
72fba911 EK |
1008 | }; |
1009 | eval { | |
a2d049af WB |
1010 | if (defined($timeout)) { |
1011 | run_with_timeout($timeout, $readvalues); | |
1012 | } else { | |
1013 | $readvalues->(); | |
1014 | } | |
72fba911 EK |
1015 | }; |
1016 | warn $@ if $@; | |
1017 | $pipe_out->close(); | |
72fba911 EK |
1018 | kill('KILL', $child); |
1019 | waitpid($child, 0); | |
1020 | ||
1021 | alarm $prev_alarm; | |
1022 | die "interrupted by unexpected signal\n" if $sig_received; | |
1023 | ||
1024 | die $error if $error; | |
1025 | return $res; | |
1026 | } | |
1027 | ||
a2d049af WB |
1028 | sub run_fork { |
1029 | my ($code) = @_; | |
1030 | return run_fork_with_timeout(undef, $code); | |
1031 | } | |
1032 | ||
813a5c0d | 1033 | # NOTE: NFS syscall can't be interrupted, so alarm does |
e143e9d8 DM |
1034 | # not work to provide timeouts. |
1035 | # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation" | |
97c8c857 | 1036 | # So fork() before using Filesys::Df |
e143e9d8 DM |
1037 | sub df { |
1038 | my ($path, $timeout) = @_; | |
1039 | ||
4fdc9659 | 1040 | my $df = sub { return Filesys::Df::df($path, 1) }; |
97c8c857 | 1041 | |
4fdc9659 TL |
1042 | my $res = eval { run_fork_with_timeout($timeout, $df) } // {}; |
1043 | warn $@ if $@; | |
97c8c857 | 1044 | |
8bc99fda TL |
1045 | # untaint, but be flexible: PB usage can result in scientific notation |
1046 | my ($blocks, $used, $bavail) = map { defined($_) ? (/^([\d\.e\-+]+)$/) : 0 } | |
fd58bb2b DC |
1047 | $res->@{qw(blocks used bavail)}; |
1048 | ||
4fdc9659 | 1049 | return { |
fd58bb2b DC |
1050 | total => $blocks, |
1051 | used => $used, | |
1052 | avail => $bavail, | |
e143e9d8 | 1053 | }; |
e143e9d8 DM |
1054 | } |
1055 | ||
62635f92 DM |
1056 | sub du { |
1057 | my ($path, $timeout) = @_; | |
1058 | ||
1059 | my $size; | |
1060 | ||
1061 | $timeout //= 10; | |
1062 | ||
1063 | my $parser = sub { | |
1064 | my $line = shift; | |
1065 | ||
1066 | if ($line =~ m/^(\d+)\s+total$/) { | |
1067 | $size = $1; | |
1068 | } | |
1069 | }; | |
1070 | ||
1071 | run_command(['du', '-scb', $path], outfunc => $parser, timeout => $timeout); | |
1072 | ||
1073 | return $size; | |
1074 | } | |
1075 | ||
e143e9d8 DM |
1076 | # UPID helper |
1077 | # We use this to uniquely identify a process. | |
813a5c0d | 1078 | # An 'Unique Process ID' has the following format: |
e143e9d8 DM |
1079 | # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user" |
1080 | ||
1081 | sub upid_encode { | |
1082 | my $d = shift; | |
1083 | ||
19cec230 DM |
1084 | # Note: pstart can be > 32bit if uptime > 497 days, so this can result in |
1085 | # more that 8 characters for pstart | |
813a5c0d DC |
1086 | return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid}, |
1087 | $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id}, | |
e143e9d8 DM |
1088 | $d->{user}); |
1089 | } | |
1090 | ||
1091 | sub upid_decode { | |
1092 | my ($upid, $noerr) = @_; | |
1093 | ||
1094 | my $res; | |
1095 | my $filename; | |
1096 | ||
1097 | # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user" | |
19cec230 DM |
1098 | # Note: allow up to 9 characters for pstart (work until 20 years uptime) |
1099 | 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 | 1100 | $res->{node} = $1; |
3702f038 DM |
1101 | $res->{pid} = hex($3); |
1102 | $res->{pstart} = hex($4); | |
1103 | $res->{starttime} = hex($5); | |
1104 | $res->{type} = $6; | |
1105 | $res->{id} = $7; | |
1106 | $res->{user} = $8; | |
1107 | ||
1108 | my $subdir = substr($5, 7, 8); | |
e143e9d8 DM |
1109 | $filename = "$pvetaskdir/$subdir/$upid"; |
1110 | ||
1111 | } else { | |
1112 | return undef if $noerr; | |
1113 | die "unable to parse worker upid '$upid'\n"; | |
1114 | } | |
1115 | ||
1116 | return wantarray ? ($res, $filename) : $res; | |
1117 | } | |
1118 | ||
1119 | sub upid_open { | |
1120 | my ($upid) = @_; | |
1121 | ||
813a5c0d | 1122 | my ($task, $filename) = upid_decode($upid); |
e143e9d8 DM |
1123 | |
1124 | my $dirname = dirname($filename); | |
1125 | make_path($dirname); | |
1126 | ||
1127 | my $wwwid = getpwnam('www-data') || | |
1128 | die "getpwnam failed"; | |
1129 | ||
1130 | my $perm = 0640; | |
813a5c0d | 1131 | |
e143e9d8 DM |
1132 | my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) || |
1133 | die "unable to create output file '$filename' - $!\n"; | |
2b8e0f12 | 1134 | chown $wwwid, -1, $outfh; |
e143e9d8 DM |
1135 | |
1136 | return $outfh; | |
1137 | }; | |
1138 | ||
1139 | sub upid_read_status { | |
1140 | my ($upid) = @_; | |
1141 | ||
1142 | my ($task, $filename) = upid_decode($upid); | |
1143 | my $fh = IO::File->new($filename, "r"); | |
1144 | return "unable to open file - $!" if !$fh; | |
cc9121d3 | 1145 | my $maxlen = 4096; |
e143e9d8 DM |
1146 | sysseek($fh, -$maxlen, 2); |
1147 | my $readbuf = ''; | |
1148 | my $br = sysread($fh, $readbuf, $maxlen); | |
1149 | close($fh); | |
1150 | if ($br) { | |
1151 | return "unable to extract last line" | |
1152 | if $readbuf !~ m/\n?(.+)$/; | |
1153 | my $line = $1; | |
1154 | if ($line =~ m/^TASK OK$/) { | |
1155 | return 'OK'; | |
1156 | } elsif ($line =~ m/^TASK ERROR: (.+)$/) { | |
1157 | return $1; | |
ff79ee65 FE |
1158 | } elsif ($line =~ m/^TASK (WARNINGS: \d+)$/) { |
1159 | return $1; | |
e143e9d8 DM |
1160 | } else { |
1161 | return "unexpected status"; | |
1162 | } | |
1163 | } | |
1164 | return "unable to read tail (got $br bytes)"; | |
1165 | } | |
1166 | ||
813a5c0d | 1167 | # useful functions to store comments in config files |
e143e9d8 DM |
1168 | sub encode_text { |
1169 | my ($text) = @_; | |
1170 | ||
1171 | # all control and hi-bit characters, and ':' | |
1172 | my $unsafe = "^\x20-\x39\x3b-\x7e"; | |
1173 | return uri_escape(Encode::encode("utf8", $text), $unsafe); | |
1174 | } | |
1175 | ||
1176 | sub decode_text { | |
1177 | my ($data) = @_; | |
1178 | ||
1179 | return Encode::decode("utf8", uri_unescape($data)); | |
1180 | } | |
1181 | ||
6d46baf6 DM |
1182 | # depreciated - do not use! |
1183 | # we now decode all parameters by default | |
815b2aba DM |
1184 | sub decode_utf8_parameters { |
1185 | my ($param) = @_; | |
1186 | ||
34ebb226 | 1187 | foreach my $p (qw(comment description firstname lastname)) { |
815b2aba DM |
1188 | $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p}; |
1189 | } | |
1190 | ||
1191 | return $param; | |
1192 | } | |
1193 | ||
a413a515 | 1194 | sub random_ether_addr { |
12392173 | 1195 | my ($prefix) = @_; |
a413a515 | 1196 | |
46a11c00 DM |
1197 | my ($seconds, $microseconds) = gettimeofday; |
1198 | ||
d743b69c | 1199 | my $rand = Digest::SHA::sha1($$, rand(), $seconds, $microseconds); |
a413a515 | 1200 | |
85d5625a | 1201 | # clear multicast, set local id |
de9a267f | 1202 | vec($rand, 0, 8) = (vec($rand, 0, 8) & 0xfe) | 2; |
a413a515 | 1203 | |
12392173 WB |
1204 | my $addr = sprintf("%02X:%02X:%02X:%02X:%02X:%02X", unpack("C6", $rand)); |
1205 | if (defined($prefix)) { | |
1206 | $addr = uc($prefix) . substr($addr, length($prefix)); | |
1207 | } | |
1208 | return $addr; | |
a413a515 | 1209 | } |
e143e9d8 | 1210 | |
762e3223 DM |
1211 | sub shellquote { |
1212 | my $str = shift; | |
1213 | ||
7514b23a | 1214 | return String::ShellQuote::shell_quote($str); |
762e3223 DM |
1215 | } |
1216 | ||
65e1d3fc DM |
1217 | sub cmd2string { |
1218 | my ($cmd) = @_; | |
1219 | ||
1220 | die "no arguments" if !$cmd; | |
1221 | ||
1222 | return $cmd if !ref($cmd); | |
1223 | ||
1224 | my @qa = (); | |
1225 | foreach my $arg (@$cmd) { push @qa, shellquote($arg); } | |
1226 | ||
1227 | return join (' ', @qa); | |
1228 | } | |
1229 | ||
e38bcd35 | 1230 | # split an shell argument string into an array, |
f9125663 DM |
1231 | sub split_args { |
1232 | my ($str) = @_; | |
1233 | ||
e38bcd35 | 1234 | return $str ? [ Text::ParseWords::shellwords($str) ] : []; |
f9125663 DM |
1235 | } |
1236 | ||
804b1041 | 1237 | sub dump_logfile { |
eb7e5538 | 1238 | my ($filename, $start, $limit, $filter) = @_; |
804b1041 DM |
1239 | |
1240 | my $lines = []; | |
1241 | my $count = 0; | |
1242 | ||
1243 | my $fh = IO::File->new($filename, "r"); | |
813a5c0d | 1244 | if (!$fh) { |
804b1041 DM |
1245 | $count++; |
1246 | push @$lines, { n => $count, t => "unable to open file - $!"}; | |
1247 | return ($count, $lines); | |
1248 | } | |
1249 | ||
1250 | $start = 0 if !$start; | |
1251 | $limit = 50 if !$limit; | |
1252 | ||
1253 | my $line; | |
eb7e5538 DM |
1254 | |
1255 | if ($filter) { | |
1256 | # duplicate code, so that we do not slow down normal path | |
1257 | while (defined($line = <$fh>)) { | |
1258 | next if $line !~ m/$filter/; | |
1259 | next if $count++ < $start; | |
1260 | next if $limit <= 0; | |
1261 | chomp $line; | |
1262 | push @$lines, { n => $count, t => $line}; | |
1263 | $limit--; | |
1264 | } | |
1265 | } else { | |
1266 | while (defined($line = <$fh>)) { | |
1267 | next if $count++ < $start; | |
1268 | next if $limit <= 0; | |
1269 | chomp $line; | |
1270 | push @$lines, { n => $count, t => $line}; | |
1271 | $limit--; | |
1272 | } | |
804b1041 DM |
1273 | } |
1274 | ||
1275 | close($fh); | |
1276 | ||
6de95a66 DM |
1277 | # HACK: ExtJS store.guaranteeRange() does not like empty array |
1278 | # so we add a line | |
1279 | if (!$count) { | |
1280 | $count++; | |
1281 | push @$lines, { n => $count, t => "no content"}; | |
1282 | } | |
1283 | ||
1284 | return ($count, $lines); | |
1285 | } | |
1286 | ||
1287 | sub dump_journal { | |
ccf60d3b | 1288 | my ($start, $limit, $since, $until, $service) = @_; |
6de95a66 DM |
1289 | |
1290 | my $lines = []; | |
1291 | my $count = 0; | |
813a5c0d | 1292 | |
6de95a66 DM |
1293 | $start = 0 if !$start; |
1294 | $limit = 50 if !$limit; | |
1295 | ||
1296 | my $parser = sub { | |
1297 | my $line = shift; | |
1298 | ||
1299 | return if $count++ < $start; | |
1300 | return if $limit <= 0; | |
1301 | push @$lines, { n => int($count), t => $line}; | |
1302 | $limit--; | |
1303 | }; | |
1304 | ||
1305 | my $cmd = ['journalctl', '-o', 'short', '--no-pager']; | |
19e95cd0 | 1306 | |
ccf60d3b | 1307 | push @$cmd, '--unit', $service if $service; |
19e95cd0 TL |
1308 | push @$cmd, '--since', $since if $since; |
1309 | push @$cmd, '--until', $until if $until; | |
6de95a66 DM |
1310 | run_command($cmd, outfunc => $parser); |
1311 | ||
804b1041 DM |
1312 | # HACK: ExtJS store.guaranteeRange() does not like empty array |
1313 | # so we add a line | |
1314 | if (!$count) { | |
1315 | $count++; | |
1316 | push @$lines, { n => $count, t => "no content"}; | |
1317 | } | |
1318 | ||
1319 | return ($count, $lines); | |
1320 | } | |
1321 | ||
7eb283fb DM |
1322 | sub dir_glob_regex { |
1323 | my ($dir, $regex) = @_; | |
1324 | ||
1325 | my $dh = IO::Dir->new ($dir); | |
1326 | return wantarray ? () : undef if !$dh; | |
813a5c0d DC |
1327 | |
1328 | while (defined(my $tmp = $dh->read)) { | |
7eb283fb DM |
1329 | if (my @res = $tmp =~ m/^($regex)$/) { |
1330 | $dh->close; | |
1331 | return wantarray ? @res : $tmp; | |
1332 | } | |
1333 | } | |
1334 | $dh->close; | |
1335 | ||
1336 | return wantarray ? () : undef; | |
1337 | } | |
1338 | ||
1339 | sub dir_glob_foreach { | |
1340 | my ($dir, $regex, $func) = @_; | |
1341 | ||
1342 | my $dh = IO::Dir->new ($dir); | |
1343 | if (defined $dh) { | |
1344 | while (defined(my $tmp = $dh->read)) { | |
1345 | if (my @res = $tmp =~ m/^($regex)$/) { | |
1346 | &$func (@res); | |
1347 | } | |
1348 | } | |
813a5c0d | 1349 | } |
7eb283fb DM |
1350 | } |
1351 | ||
a345b9d5 DM |
1352 | sub assert_if_modified { |
1353 | my ($digest1, $digest2) = @_; | |
1354 | ||
1355 | if ($digest1 && $digest2 && ($digest1 ne $digest2)) { | |
212fc0b7 | 1356 | die "detected modified configuration - file changed by other user? Try again.\n"; |
a345b9d5 DM |
1357 | } |
1358 | } | |
1359 | ||
2d3bca34 DM |
1360 | # Digest for short strings |
1361 | # like FNV32a, but we only return 31 bits (positive numbers) | |
1362 | sub fnv31a { | |
1363 | my ($string) = @_; | |
1364 | ||
1365 | my $hval = 0x811c9dc5; | |
1366 | ||
1367 | foreach my $c (unpack('C*', $string)) { | |
1368 | $hval ^= $c; | |
1369 | $hval += ( | |
1370 | (($hval << 1) ) + | |
1371 | (($hval << 4) ) + | |
1372 | (($hval << 7) ) + | |
1373 | (($hval << 8) ) + | |
1374 | (($hval << 24) ) ); | |
1375 | $hval = $hval & 0xffffffff; | |
1376 | } | |
1377 | return $hval & 0x7fffffff; | |
1378 | } | |
1379 | ||
1380 | sub fnv31a_hex { return sprintf("%X", fnv31a(@_)); } | |
1381 | ||
8df6b794 WB |
1382 | sub unpack_sockaddr_in46 { |
1383 | my ($sin) = @_; | |
1384 | my $family = Socket::sockaddr_family($sin); | |
1385 | my ($port, $host) = ($family == AF_INET6 ? Socket::unpack_sockaddr_in6($sin) | |
1386 | : Socket::unpack_sockaddr_in($sin)); | |
1387 | return ($family, $port, $host); | |
1388 | } | |
1389 | ||
a0b6ef52 WB |
1390 | sub getaddrinfo_all { |
1391 | my ($hostname, @opts) = @_; | |
7a2e8ca1 TL |
1392 | my %hints = ( |
1393 | flags => AI_V4MAPPED | AI_ALL, | |
1394 | @opts, | |
1395 | ); | |
a956854f | 1396 | my ($err, @res) = Socket::getaddrinfo($hostname, '0', \%hints); |
a0b6ef52 WB |
1397 | die "failed to get address info for: $hostname: $err\n" if $err; |
1398 | return @res; | |
1399 | } | |
a956854f | 1400 | |
a0b6ef52 WB |
1401 | sub get_host_address_family { |
1402 | my ($hostname, $socktype) = @_; | |
1403 | my @res = getaddrinfo_all($hostname, socktype => $socktype); | |
1404 | return $res[0]->{family}; | |
a956854f WB |
1405 | } |
1406 | ||
d3c8f0c1 EK |
1407 | # get the fully qualified domain name of a host |
1408 | # same logic as hostname(1): The FQDN is the name getaddrinfo(3) returns, | |
1409 | # given a nodename as a parameter | |
1410 | sub get_fqdn { | |
1411 | my ($nodename) = @_; | |
1412 | ||
1413 | my $hints = { | |
1414 | flags => AI_CANONNAME, | |
1415 | socktype => SOCK_DGRAM | |
1416 | }; | |
1417 | ||
1418 | my ($err, @addrs) = Socket::getaddrinfo($nodename, undef, $hints); | |
1419 | ||
1420 | die "getaddrinfo: $err" if $err; | |
1421 | ||
1422 | return $addrs[0]->{canonname}; | |
1423 | } | |
1424 | ||
b2613777 WB |
1425 | # Parses any sane kind of host, or host+port pair: |
1426 | # The port is always optional and thus may be undef. | |
1427 | sub parse_host_and_port { | |
1428 | my ($address) = @_; | |
1429 | if ($address =~ /^($IPV4RE|[[:alnum:]\-.]+)(?::(\d+))?$/ || # ipv4 or host with optional ':port' | |
1430 | $address =~ /^\[($IPV6RE|$IPV4RE|[[:alnum:]\-.]+)\](?::(\d+))?$/ || # anything in brackets with optional ':port' | |
1431 | $address =~ /^($IPV6RE)(?:\.(\d+))?$/) # ipv6 with optional port separated by dot | |
1432 | { | |
1433 | return ($1, $2, 1); # end with 1 to support simple if(parse...) tests | |
1434 | } | |
1435 | return; # nothing | |
1436 | } | |
1437 | ||
0c078e66 SI |
1438 | sub setresuid($$$) { |
1439 | my ($ruid, $euid, $suid) = @_; | |
1440 | return 0 == syscall(PVE::Syscall::setresuid, $ruid, $euid, $suid); | |
1441 | } | |
1442 | ||
817c6be0 | 1443 | sub unshare($) { |
952fd95e | 1444 | my ($flags) = @_; |
c8e94d4b | 1445 | return 0 == syscall(PVE::Syscall::unshare, $flags); |
952fd95e WB |
1446 | } |
1447 | ||
891b224a WB |
1448 | sub setns($$) { |
1449 | my ($fileno, $nstype) = @_; | |
c8e94d4b | 1450 | return 0 == syscall(PVE::Syscall::setns, $fileno, $nstype); |
891b224a WB |
1451 | } |
1452 | ||
44acb12c WB |
1453 | sub syncfs($) { |
1454 | my ($fileno) = @_; | |
c8e94d4b | 1455 | return 0 == syscall(PVE::Syscall::syncfs, $fileno); |
44acb12c WB |
1456 | } |
1457 | ||
cee0e23a TL |
1458 | sub fsync($) { |
1459 | my ($fileno) = @_; | |
1460 | return 0 == syscall(PVE::Syscall::fsync, $fileno); | |
1461 | } | |
1462 | ||
44acb12c WB |
1463 | sub sync_mountpoint { |
1464 | my ($path) = @_; | |
b260d4e3 | 1465 | sysopen my $fd, $path, O_RDONLY|O_CLOEXEC or die "failed to open $path: $!\n"; |
09d47f9d TL |
1466 | my $syncfs_err; |
1467 | if (!syncfs(fileno($fd))) { | |
1468 | $syncfs_err = "$!"; | |
1469 | } | |
44acb12c | 1470 | close($fd); |
09d47f9d | 1471 | die "syncfs '$path' failed - $syncfs_err\n" if defined $syncfs_err; |
44acb12c WB |
1472 | } |
1473 | ||
b61a47db TL |
1474 | # support sending multi-part mail messages with a text and or a HTML part |
1475 | # mailto may be a single email string or an array of receivers | |
1476 | sub sendmail { | |
1477 | my ($mailto, $subject, $text, $html, $mailfrom, $author) = @_; | |
1478 | ||
5a873e6d | 1479 | $mailto = [ $mailto ] if !ref($mailto); |
b61a47db | 1480 | |
4c4bd104 | 1481 | my $mailto_quoted = []; |
a7886364 | 1482 | for my $to (@$mailto) { |
4c4bd104 FE |
1483 | die "mailto does not look like a valid email address or username\n" |
1484 | if $to !~ /^$EMAIL_RE$/ && $to !~ /^$EMAIL_USER_RE$/; | |
1485 | push @$mailto_quoted, shellquote($to); | |
b61a47db | 1486 | } |
c9c6d910 | 1487 | |
b61a47db TL |
1488 | my $rcvrtxt = join (', ', @$mailto); |
1489 | ||
1490 | $mailfrom = $mailfrom || "root"; | |
4c4bd104 FE |
1491 | die "mailfrom does not look like a valid email address or username\n" |
1492 | if $mailfrom !~ /^$EMAIL_RE$/ && $mailfrom !~ /^$EMAIL_USER_RE$/; | |
1493 | my $mailfrom_quoted = shellquote($mailfrom); | |
c9c6d910 | 1494 | |
a24d91ea | 1495 | $author = $author // 'Proxmox VE'; |
b61a47db | 1496 | |
4c4bd104 FE |
1497 | open (MAIL, "|-", "sendmail", "-B", "8BITMIME", "-f", $mailfrom_quoted, |
1498 | "--", @$mailto_quoted) || die "unable to open 'sendmail' - $!"; | |
b61a47db | 1499 | |
b18826ce SI |
1500 | my $date = time2str('%a, %d %b %Y %H:%M:%S %z', time()); |
1501 | ||
1502 | my $is_multipart = $text && $html; | |
1503 | ||
b61a47db TL |
1504 | # multipart spec see https://www.ietf.org/rfc/rfc1521.txt |
1505 | my $boundary = "----_=_NextPart_001_".int(time).$$; | |
1506 | ||
b18826ce SI |
1507 | if ($subject =~ /[^[:ascii:]]/) { |
1508 | $subject = Encode::encode('MIME-Header', $subject); | |
1509 | } | |
b61a47db | 1510 | |
b18826ce SI |
1511 | if ($subject =~ /[^[:ascii:]]/ || $is_multipart) { |
1512 | print MAIL "MIME-Version: 1.0\n"; | |
1513 | } | |
1514 | print MAIL "From: $author <$mailfrom>\n"; | |
1515 | print MAIL "To: $rcvrtxt\n"; | |
1516 | print MAIL "Date: $date\n"; | |
1517 | print MAIL "Subject: $subject\n"; | |
1518 | ||
1519 | if ($is_multipart) { | |
1520 | print MAIL "Content-Type: multipart/alternative;\n"; | |
1521 | print MAIL "\tboundary=\"$boundary\"\n"; | |
1522 | print MAIL "\n"; | |
1523 | print MAIL "This is a multi-part message in MIME format.\n\n"; | |
1524 | print MAIL "--$boundary\n"; | |
1525 | } | |
b61a47db | 1526 | |
5a873e6d | 1527 | if (defined($text)) { |
b61a47db | 1528 | print MAIL "Content-Type: text/plain;\n"; |
b18826ce | 1529 | print MAIL "\tcharset=\"UTF-8\"\n"; |
b61a47db TL |
1530 | print MAIL "Content-Transfer-Encoding: 8bit\n"; |
1531 | print MAIL "\n"; | |
1532 | ||
1533 | # avoid 'remove extra line breaks' issue (MS Outlook) | |
1534 | my $fill = ' '; | |
1535 | $text =~ s/^/$fill/gm; | |
1536 | ||
1537 | print MAIL $text; | |
1538 | ||
b18826ce | 1539 | print MAIL "\n--$boundary\n" if $is_multipart; |
b61a47db TL |
1540 | } |
1541 | ||
5a873e6d | 1542 | if (defined($html)) { |
b61a47db | 1543 | print MAIL "Content-Type: text/html;\n"; |
b18826ce | 1544 | print MAIL "\tcharset=\"UTF-8\"\n"; |
b61a47db TL |
1545 | print MAIL "Content-Transfer-Encoding: 8bit\n"; |
1546 | print MAIL "\n"; | |
1547 | ||
1548 | print MAIL $html; | |
1549 | ||
b18826ce | 1550 | print MAIL "\n--$boundary--\n" if $is_multipart; |
b61a47db TL |
1551 | } |
1552 | ||
1553 | close(MAIL); | |
b61a47db TL |
1554 | } |
1555 | ||
26598a51 WB |
1556 | sub tempfile { |
1557 | my ($perm, %opts) = @_; | |
1558 | ||
1559 | # default permissions are stricter than with file_set_contents | |
1560 | $perm = 0600 if !defined($perm); | |
1561 | ||
f0cfc20e | 1562 | my $dir = $opts{dir} // '/run'; |
26598a51 WB |
1563 | my $mode = $opts{mode} // O_RDWR; |
1564 | $mode |= O_EXCL if !$opts{allow_links}; | |
1565 | ||
7e1ee743 WB |
1566 | my $fh = IO::File->new($dir, $mode | O_TMPFILE, $perm); |
1567 | if (!$fh && $! == EOPNOTSUPP) { | |
77b2b96f | 1568 | $dir = '/tmp' if !defined($opts{dir}); |
7e1ee743 WB |
1569 | $dir .= "/.tmpfile.$$"; |
1570 | $fh = IO::File->new($dir, $mode | O_CREAT | O_EXCL, $perm); | |
1571 | unlink($dir) if $fh; | |
1572 | } | |
1573 | die "failed to create tempfile: $!\n" if !$fh; | |
26598a51 WB |
1574 | return $fh; |
1575 | } | |
1576 | ||
1577 | sub tempfile_contents { | |
1578 | my ($data, $perm, %opts) = @_; | |
1579 | ||
1580 | my $fh = tempfile($perm, %opts); | |
1581 | eval { | |
1582 | die "unable to write to tempfile: $!\n" if !print {$fh} $data; | |
1583 | die "unable to flush to tempfile: $!\n" if !defined($fh->flush()); | |
1584 | }; | |
1585 | if (my $err = $@) { | |
1586 | close $fh; | |
1587 | die $err; | |
1588 | } | |
1589 | ||
1590 | return ("/proc/$$/fd/".$fh->fileno, $fh); | |
1591 | } | |
1592 | ||
48df47a4 FG |
1593 | sub validate_ssh_public_keys { |
1594 | my ($raw) = @_; | |
1595 | my @lines = split(/\n/, $raw); | |
1596 | ||
1597 | foreach my $line (@lines) { | |
1598 | next if $line =~ m/^\s*$/; | |
1599 | eval { | |
1600 | my ($filename, $handle) = tempfile_contents($line); | |
1601 | run_command(["ssh-keygen", "-l", "-f", $filename], | |
1602 | outfunc => sub {}, errfunc => sub {}); | |
1603 | }; | |
1604 | die "SSH public key validation error\n" if $@; | |
1605 | } | |
1606 | } | |
1607 | ||
21c56a96 WB |
1608 | sub openat($$$;$) { |
1609 | my ($dirfd, $pathname, $flags, $mode) = @_; | |
c8e94d4b | 1610 | my $fd = syscall(PVE::Syscall::openat, $dirfd, $pathname, $flags, $mode//0); |
21c56a96 WB |
1611 | return undef if $fd < 0; |
1612 | # sysopen() doesn't deal with numeric file descriptors apparently | |
1613 | # so we need to convert to a mode string for IO::Handle->new_from_fd | |
1614 | my $flagstr = ($flags & O_RDWR) ? 'rw' : ($flags & O_WRONLY) ? 'w' : 'r'; | |
1615 | my $handle = IO::Handle->new_from_fd($fd, $flagstr); | |
1616 | return $handle if $handle; | |
1617 | my $err = $!; # save error before closing the raw fd | |
c8e94d4b | 1618 | syscall(PVE::Syscall::close, $fd); # close |
21c56a96 WB |
1619 | $! = $err; |
1620 | return undef; | |
1621 | } | |
1622 | ||
1623 | sub mkdirat($$$) { | |
1624 | my ($dirfd, $name, $mode) = @_; | |
c8e94d4b | 1625 | return syscall(PVE::Syscall::mkdirat, $dirfd, $name, $mode) == 0; |
21c56a96 WB |
1626 | } |
1627 | ||
6cf6b404 FG |
1628 | sub fchownat($$$$$) { |
1629 | my ($dirfd, $pathname, $owner, $group, $flags) = @_; | |
1630 | return syscall(PVE::Syscall::fchownat, $dirfd, $pathname, $owner, $group, $flags) == 0; | |
1631 | } | |
1632 | ||
9867ff7a DM |
1633 | my $salt_starter = time(); |
1634 | ||
1635 | sub encrypt_pw { | |
1636 | my ($pw) = @_; | |
1637 | ||
1638 | $salt_starter++; | |
1639 | my $salt = substr(Digest::SHA::sha1_base64(time() + $salt_starter + $$), 0, 8); | |
1640 | ||
1641 | # crypt does not want '+' in salt (see 'man crypt') | |
1642 | $salt =~ s/\+/X/g; | |
1643 | ||
1644 | return crypt(encode("utf8", $pw), "\$5\$$salt\$"); | |
1645 | } | |
1646 | ||
8e677e74 | 1647 | # intended usage: convert_size($val, "kb" => "gb") |
95386daf DC |
1648 | # we round up to the next integer by default |
1649 | # E.g. `convert_size(1023, "b" => "kb")` returns 1 | |
8e677e74 | 1650 | # use $no_round_up to switch this off, above example would then return 0 |
95386daf DC |
1651 | # this is also true for converting down e.g. 0.0005 gb to mb returns 1 |
1652 | # (0 if $no_round_up is true) | |
1653 | # allowed formats for value: | |
1654 | # 1234 | |
1655 | # 1234. | |
1656 | # 1234.1234 | |
1657 | # .1234 | |
8e677e74 TL |
1658 | sub convert_size { |
1659 | my ($value, $from, $to, $no_round_up) = @_; | |
1660 | ||
1661 | my $units = { | |
1662 | b => 0, | |
1663 | kb => 1, | |
1664 | mb => 2, | |
1665 | gb => 3, | |
1666 | tb => 4, | |
1667 | pb => 5, | |
1668 | }; | |
1669 | ||
95386daf DC |
1670 | die "no value given" |
1671 | if !defined($value) || $value eq ""; | |
1672 | ||
1673 | $from = lc($from // ''); $to = lc($to // ''); | |
8e677e74 | 1674 | die "unknown 'from' and/or 'to' units ($from => $to)" |
95386daf | 1675 | if !defined($units->{$from}) || !defined($units->{$to}); |
8e677e74 | 1676 | |
95386daf DC |
1677 | die "value '$value' is not a valid, positive number" |
1678 | if $value !~ m/^(?:[0-9]+\.?[0-9]*|[0-9]*\.[0-9]+)$/; | |
8e677e74 | 1679 | |
95386daf DC |
1680 | my $shift_amount = ($units->{$from} - $units->{$to}) * 10; |
1681 | ||
1682 | $value *= 2**$shift_amount; | |
1683 | $value++ if !$no_round_up && ($value - int($value)) > 0.0; | |
8e677e74 | 1684 | |
95386daf | 1685 | return int($value); |
8e677e74 TL |
1686 | } |
1687 | ||
e03a8365 DC |
1688 | # uninterruptible readline |
1689 | # retries on EINTR | |
1690 | sub readline_nointr { | |
1691 | my ($fh) = @_; | |
1692 | my $line; | |
1693 | while (1) { | |
1694 | $line = <$fh>; | |
1695 | last if defined($line) || ($! != EINTR); | |
1696 | } | |
1697 | return $line; | |
1698 | } | |
1699 | ||
ce007e99 | 1700 | my $host_arch; |
b8faece3 | 1701 | sub get_host_arch { |
ce007e99 SR |
1702 | $host_arch = (POSIX::uname())[4] if !$host_arch; |
1703 | return $host_arch; | |
732b693f DM |
1704 | } |
1705 | ||
243c4e58 WB |
1706 | # Devices are: [ (12 bits minor) (12 bits major) (8 bits minor) ] |
1707 | sub dev_t_major($) { | |
1708 | my ($dev_t) = @_; | |
1709 | return (int($dev_t) & 0xfff00) >> 8; | |
1710 | } | |
1711 | ||
1712 | sub dev_t_minor($) { | |
1713 | my ($dev_t) = @_; | |
1714 | $dev_t = int($dev_t); | |
1715 | return (($dev_t >> 12) & 0xfff00) | ($dev_t & 0xff); | |
1716 | } | |
1717 | ||
a59544e7 SR |
1718 | # Given an array of array refs [ \[a b c], \[a b b], \[e b a] ] |
1719 | # Returns the intersection of elements as a single array [a b] | |
1720 | sub array_intersect { | |
1721 | my ($arrays) = @_; | |
1722 | ||
3982313e TL |
1723 | if (!ref($arrays->[0])) { |
1724 | $arrays = [ grep { ref($_) eq 'ARRAY' } @_ ]; | |
1725 | } | |
1726 | ||
38586028 TL |
1727 | return [] if scalar(@$arrays) == 0; |
1728 | return $arrays->[0] if scalar(@$arrays) == 1; | |
a59544e7 | 1729 | |
4c28a8bc TL |
1730 | my $array_unique = sub { |
1731 | my %seen = (); | |
1732 | return grep { ! $seen{ $_ }++ } @_; | |
1733 | }; | |
1734 | ||
38586028 TL |
1735 | # base idea is to get all unique members from the first array, then |
1736 | # check the common elements with the next (uniquely made) one, only keep | |
1737 | # those. Repeat for every array and at the end we only have those left | |
1738 | # which exist in all arrays | |
1739 | my $return_arr = [ $array_unique->(@{$arrays->[0]}) ]; | |
a59544e7 SR |
1740 | for my $i (1 .. $#$arrays) { |
1741 | my %count = (); | |
38586028 | 1742 | # $return_arr is already unique, explicit at before the loop, implicit below. |
4c28a8bc | 1743 | foreach my $element (@$return_arr, $array_unique->(@{$arrays->[$i]})) { |
a59544e7 SR |
1744 | $count{$element}++; |
1745 | } | |
1746 | $return_arr = []; | |
1747 | foreach my $element (keys %count) { | |
1748 | push @$return_arr, $element if $count{$element} > 1; | |
1749 | } | |
26a68cf6 | 1750 | last if scalar(@$return_arr) == 0; # empty intersection, early exit |
a59544e7 SR |
1751 | } |
1752 | ||
1753 | return $return_arr; | |
1754 | } | |
1755 | ||
76c5fee8 WB |
1756 | sub open_tree($$$) { |
1757 | my ($dfd, $pathname, $flags) = @_; | |
1758 | return PVE::Syscall::file_handle_result(syscall( | |
1759 | &PVE::Syscall::open_tree, | |
1760 | $dfd, | |
1761 | $pathname, | |
1762 | $flags, | |
1763 | )); | |
1764 | } | |
1765 | ||
1766 | sub move_mount($$$$$) { | |
1767 | my ($from_dirfd, $from_pathname, $to_dirfd, $to_pathname, $flags) = @_; | |
1768 | return 0 == syscall( | |
1769 | &PVE::Syscall::move_mount, | |
1770 | $from_dirfd, | |
1771 | $from_pathname, | |
1772 | $to_dirfd, | |
1773 | $to_pathname, | |
1774 | $flags, | |
1775 | ); | |
1776 | } | |
1777 | ||
1778 | sub fsopen($$) { | |
1779 | my ($fsname, $flags) = @_; | |
1780 | return PVE::Syscall::file_handle_result(syscall(&PVE::Syscall::fsopen, $fsname, $flags)); | |
1781 | } | |
1782 | ||
1783 | sub fsmount($$$) { | |
1784 | my ($fd, $flags, $mount_attrs) = @_; | |
1785 | return PVE::Syscall::file_handle_result(syscall( | |
1786 | &PVE::Syscall::fsmount, | |
1787 | $fd, | |
1788 | $flags, | |
1789 | $mount_attrs, | |
1790 | )); | |
1791 | } | |
1792 | ||
1793 | sub fspick($$$) { | |
1794 | my ($dirfd, $pathname, $flags) = @_; | |
1795 | return PVE::Syscall::file_handle_result(syscall( | |
1796 | &PVE::Syscall::fspick, | |
1797 | $dirfd, | |
1798 | $pathname, | |
1799 | $flags, | |
1800 | )); | |
1801 | } | |
1802 | ||
1803 | sub fsconfig($$$$$) { | |
1804 | my ($fd, $command, $key, $value, $aux) = @_; | |
1805 | return 0 == syscall(&PVE::Syscall::fsconfig, $fd, $command, $key, $value, $aux); | |
1806 | } | |
1807 | ||
1808 | # "raw" mount, old api, not for generic use (as it does not invoke any helpers). | |
1809 | # use for lower level stuff such as bind/remount/... or simple tmpfs mounts | |
1810 | sub mount($$$$$) { | |
1811 | my ($source, $target, $filesystemtype, $mountflags, $data) = @_; | |
1812 | return 0 == syscall( | |
1813 | &PVE::Syscall::mount, | |
1814 | $source, | |
1815 | $target, | |
1816 | $filesystemtype, | |
1817 | $mountflags, | |
1818 | $data, | |
1819 | ); | |
1820 | } | |
a59544e7 | 1821 | |
890d25d9 FE |
1822 | sub safe_compare { |
1823 | my ($left, $right, $cmp) = @_; | |
1824 | ||
1825 | return 0 if !defined($left) && !defined($right); | |
1826 | return -1 if !defined($left); | |
1827 | return 1 if !defined($right); | |
1828 | return $cmp->($left, $right); | |
1829 | } | |
1830 | ||
a3327ea6 | 1831 | |
60fb1c26 TL |
1832 | # opts is a hash ref with the following known properties |
1833 | # hash_required - if 1, at least one checksum has to be specified otherwise an error will be thrown | |
1834 | # http_proxy | |
1835 | # https_proxy | |
1836 | # verify_certificates - if 0 (false) we tell wget to ignore untrusted TLS certs. Default to true | |
1837 | # md5sum|sha(1|224|256|384|512)sum - the respective expected checksum string | |
a3327ea6 LS |
1838 | sub download_file_from_url { |
1839 | my ($dest, $url, $opts) = @_; | |
1840 | ||
60fb1c26 | 1841 | my ($checksum_algorithm, $checksum_expected); |
a3327ea6 LS |
1842 | for ('sha512', 'sha384', 'sha256', 'sha224', 'sha1', 'md5') { |
1843 | if (defined($opts->{"${_}sum"})) { | |
60fb1c26 TL |
1844 | $checksum_algorithm = $_; |
1845 | $checksum_expected = $opts->{"${_}sum"}; | |
a3327ea6 LS |
1846 | last; |
1847 | } | |
1848 | } | |
60fb1c26 | 1849 | die "checksum required but not specified\n" if ($opts->{hash_required} && !$checksum_algorithm); |
a3327ea6 | 1850 | |
60fb1c26 | 1851 | print "downloading $url to $dest\n"; |
a3327ea6 | 1852 | |
60fb1c26 TL |
1853 | my $tmpdest = "$dest.tmp.$$"; |
1854 | eval { | |
1855 | if (-f $dest && $checksum_algorithm) { | |
1856 | print "calculating checksum of existing file..."; | |
1857 | my $checksum_got = get_file_hash($checksum_algorithm, $dest); | |
a3327ea6 | 1858 | |
60fb1c26 TL |
1859 | if (lc($checksum_got) eq lc($checksum_expected)) { |
1860 | print "OK, got correct file already, no need to download\n"; | |
1861 | return; | |
1862 | } else { | |
1863 | # we could re-download, but may not be safe so just abort for now.. | |
1864 | die "mismatch (got '$checksum_got' != expect '$checksum_expected'), aborting\n"; | |
a3327ea6 | 1865 | } |
60fb1c26 | 1866 | } |
a3327ea6 | 1867 | |
3a946485 TL |
1868 | local $SIG{INT} = sub { |
1869 | unlink $tmpdest or warn "could not cleanup temporary file: $!"; | |
1870 | die "got interrupted by signal\n"; | |
1871 | }; | |
1872 | ||
60fb1c26 | 1873 | { # limit the scope of the ENV change |
a3327ea6 LS |
1874 | local %ENV; |
1875 | if ($opts->{http_proxy}) { | |
1876 | $ENV{http_proxy} = $opts->{http_proxy}; | |
1877 | } | |
1878 | if ($opts->{https_proxy}) { | |
1879 | $ENV{https_proxy} = $opts->{https_proxy}; | |
1880 | } | |
1881 | ||
60fb1c26 | 1882 | my $cmd = ['wget', '--progress=dot:giga', '-O', $tmpdest, $url]; |
a3327ea6 | 1883 | |
60fb1c26 TL |
1884 | if (!($opts->{verify_certificates} // 1)) { # default to true |
1885 | push @$cmd, '--no-check-certificate'; | |
a3327ea6 LS |
1886 | } |
1887 | ||
60fb1c26 TL |
1888 | run_command($cmd, errmsg => "download failed"); |
1889 | } | |
1890 | ||
1891 | if ($checksum_algorithm) { | |
1892 | print "calculating checksum..."; | |
a3327ea6 | 1893 | |
60fb1c26 | 1894 | my $checksum_got = get_file_hash($checksum_algorithm, $tmpdest); |
a3327ea6 | 1895 | |
60fb1c26 TL |
1896 | if (lc($checksum_got) eq lc($checksum_expected)) { |
1897 | print "OK, checksum verified\n"; | |
a3327ea6 | 1898 | } else { |
60fb1c26 | 1899 | die "ERRROR, checksum mismatch: got '$checksum_got' != expect '$checksum_expected'\n"; |
a3327ea6 | 1900 | } |
a3327ea6 LS |
1901 | } |
1902 | ||
60fb1c26 | 1903 | rename($tmpdest, $dest) or die "unable to rename temporary file: $!\n"; |
a3327ea6 | 1904 | }; |
60fb1c26 TL |
1905 | if (my $err = $@) { |
1906 | unlink $tmpdest or warn "could not cleanup temporary file: $!"; | |
1907 | die $err; | |
1908 | } | |
a3327ea6 | 1909 | |
60fb1c26 | 1910 | print "download of '$url' to '$dest' finished\n"; |
a3327ea6 LS |
1911 | } |
1912 | ||
60fb1c26 TL |
1913 | sub get_file_hash { |
1914 | my ($algorithm, $filename) = @_; | |
a3327ea6 LS |
1915 | |
1916 | my $algorithm_map = { | |
1917 | 'md5' => sub { Digest::MD5->new }, | |
1918 | 'sha1' => sub { Digest::SHA->new(1) }, | |
1919 | 'sha224' => sub { Digest::SHA->new(224) }, | |
1920 | 'sha256' => sub { Digest::SHA->new(256) }, | |
1921 | 'sha384' => sub { Digest::SHA->new(384) }, | |
1922 | 'sha512' => sub { Digest::SHA->new(512) }, | |
1923 | }; | |
1924 | ||
1925 | my $digester = $algorithm_map->{$algorithm}->() or die "unknown algorithm '$algorithm'\n"; | |
1926 | ||
1927 | open(my $fh, '<', $filename) or die "unable to open '$filename': $!\n"; | |
1928 | binmode($fh); | |
1929 | ||
1930 | my $digest = $digester->addfile($fh)->hexdigest; | |
1931 | ||
60fb1c26 | 1932 | return lc($digest); |
a3327ea6 LS |
1933 | } |
1934 | ||
e143e9d8 | 1935 | 1; |