27b4361f7f11c9a6d76d3a48b0a9a465bc86c074
[pve-common.git] / data / PVE / Tools.pm
1 package PVE::Tools;
2
3 use strict;
4 use POSIX;
5 use IO::Socket::INET;
6 use IO::Select;
7 use File::Basename;
8 use File::Path qw(make_path);
9 use IO::File;
10 use IO::Dir;
11 use IPC::Open3;
12 use Fcntl qw(:DEFAULT :flock);
13 use base 'Exporter';
14 use URI::Escape;
15 use Encode;
16 use Digest::SHA;
17 use Text::ParseWords;
18 use String::ShellQuote;
19
20 our @EXPORT_OK = qw(
21 lock_file
22 run_command
23 file_set_contents
24 file_get_contents
25 file_read_firstline
26 dir_glob_regex
27 dir_glob_foreach
28 split_list
29 template_replace
30 safe_print
31 trim
32 extract_param
33 );
34
35 my $pvelogdir = "/var/log/pve";
36 my $pvetaskdir = "$pvelogdir/tasks";
37
38 mkdir $pvelogdir;
39 mkdir $pvetaskdir;
40
41 sub run_with_timeout {
42 my ($timeout, $code, @param) = @_;
43
44 die "got timeout\n" if $timeout <= 0;
45
46 my $prev_alarm;
47
48 my $sigcount = 0;
49
50 my $res;
51
52 local $SIG{ALRM} = sub { $sigcount++; }; # catch alarm outside eval
53
54 eval {
55 local $SIG{ALRM} = sub { $sigcount++; die "got timeout\n"; };
56 local $SIG{PIPE} = sub { $sigcount++; die "broken pipe\n" };
57 local $SIG{__DIE__}; # see SA bug 4631
58
59 $prev_alarm = alarm($timeout);
60
61 $res = &$code(@param);
62
63 alarm(0); # avoid race conditions
64 };
65
66 my $err = $@;
67
68 alarm($prev_alarm) if defined($prev_alarm);
69
70 die "unknown error" if $sigcount && !$err; # seems to happen sometimes
71
72 die $err if $err;
73
74 return $res;
75 }
76
77 # flock: we use one file handle per process, so lock file
78 # can be called multiple times and succeeds for the same process.
79
80 my $lock_handles = {};
81
82 sub lock_file {
83 my ($filename, $timeout, $code, @param) = @_;
84
85 $timeout = 10 if !$timeout;
86
87 my $lock_func = sub {
88 if (!$lock_handles->{$$}->{$filename}) {
89 $lock_handles->{$$}->{$filename} = new IO::File (">>$filename") ||
90 die "can't open file - $!\n";
91 }
92
93 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX|LOCK_NB)) {
94 print STDERR "trying to aquire lock...";
95 if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX)) {
96 print STDERR " failed\n";
97 die "can't aquire lock - $!\n";
98 }
99 print STDERR " OK\n";
100 }
101 };
102
103 my $res;
104
105 eval { run_with_timeout($timeout, $lock_func); };
106 my $err = $@;
107 if ($err) {
108 $err = "can't lock file '$filename' - $err";
109 } else {
110 eval { $res = &$code(@param) };
111 $err = $@;
112 }
113
114 if ($lock_handles->{$$}->{$filename}) {
115 my $fh = $lock_handles->{$$}->{$filename};
116 $lock_handles->{$$}->{$filename} = undef;
117 close ($fh);
118 }
119
120 if ($err) {
121 $@ = $err;
122 return undef;
123 }
124
125 $@ = undef;
126
127 return $res;
128 }
129
130 sub file_set_contents {
131 my ($filename, $data, $perm) = @_;
132
133 $perm = 0644 if !defined($perm);
134
135 my $tmpname = "$filename.tmp.$$";
136
137 eval {
138 my $fh = IO::File->new($tmpname, O_WRONLY|O_CREAT, $perm);
139 die "unable to open file '$tmpname' - $!\n" if !$fh;
140 die "unable to write '$tmpname' - $!\n" unless print $fh $data;
141 die "closing file '$tmpname' failed - $!\n" unless close $fh;
142 };
143 my $err = $@;
144
145 if ($err) {
146 unlink $tmpname;
147 die $err;
148 }
149
150 if (!rename($tmpname, $filename)) {
151 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
152 unlink $tmpname;
153 die $msg;
154 }
155 }
156
157 sub file_get_contents {
158 my ($filename, $max) = @_;
159
160 my $fh = IO::File->new($filename, "r") ||
161 die "can't open '$filename' - $!\n";
162
163 my $content = safe_read_from($fh, $max);
164
165 close $fh;
166
167 return $content;
168 }
169
170 sub file_read_firstline {
171 my ($filename) = @_;
172
173 my $fh = IO::File->new ($filename, "r");
174 return undef if !$fh;
175 my $res = <$fh>;
176 chomp $res if $res;
177 $fh->close;
178 return $res;
179 }
180
181 sub safe_read_from {
182 my ($fh, $max, $oneline) = @_;
183
184 $max = 32768 if !$max;
185
186 my $br = 0;
187 my $input = '';
188 my $count;
189 while ($count = sysread($fh, $input, 8192, $br)) {
190 $br += $count;
191 die "input too long - aborting\n" if $br > $max;
192 if ($oneline && $input =~ m/^(.*)\n/) {
193 $input = $1;
194 last;
195 }
196 }
197 die "unable to read input - $!\n" if !defined($count);
198
199 return $input;
200 }
201
202 sub run_command {
203 my ($cmd, %param) = @_;
204
205 my $old_umask;
206 my $cmdstr;
207
208 if (!ref($cmd)) {
209 $cmdstr = $cmd;
210 if ($cmd =~ m/|/) {
211 # see 'man bash' for option pipefail
212 $cmd = [ '/bin/bash', '-c', "set -o pipefail && $cmd" ];
213 } else {
214 $cmd = [ $cmd ];
215 }
216 } else {
217 $cmdstr = cmd2string($cmd);
218 }
219
220 my $errmsg;
221 my $laststderr;
222 my $timeout;
223 my $oldtimeout;
224 my $pid;
225
226 my $outfunc;
227 my $errfunc;
228 my $logfunc;
229 my $input;
230 my $output;
231
232 eval {
233
234 foreach my $p (keys %param) {
235 if ($p eq 'timeout') {
236 $timeout = $param{$p};
237 } elsif ($p eq 'umask') {
238 $old_umask = umask($param{$p});
239 } elsif ($p eq 'errmsg') {
240 $errmsg = $param{$p};
241 } elsif ($p eq 'input') {
242 $input = $param{$p};
243 } elsif ($p eq 'output') {
244 $output = $param{$p};
245 } elsif ($p eq 'outfunc') {
246 $outfunc = $param{$p};
247 } elsif ($p eq 'errfunc') {
248 $errfunc = $param{$p};
249 } elsif ($p eq 'logfunc') {
250 $logfunc = $param{$p};
251 } else {
252 die "got unknown parameter '$p' for run_command\n";
253 }
254 }
255
256 if ($errmsg) {
257 my $origerrfunc = $errfunc;
258 $errfunc = sub {
259 if ($laststderr) {
260 if ($origerrfunc) {
261 &$origerrfunc("$laststderr\n");
262 } else {
263 print STDERR "$laststderr\n" if $laststderr;
264 }
265 }
266 $laststderr = shift;
267 };
268 }
269
270 my $reader = $output && $output =~ m/^>&/ ? $output : IO::File->new();
271 my $writer = $input && $input =~ m/^<&/ ? $input : IO::File->new();
272 my $error = IO::File->new();
273
274 # try to avoid locale related issues/warnings
275 my $lang = $param{lang} || 'C';
276
277 my $orig_pid = $$;
278
279 eval {
280 local $ENV{LC_ALL} = $lang;
281
282 # suppress LVM warnings like: "File descriptor 3 left open";
283 local $ENV{LVM_SUPPRESS_FD_WARNINGS} = "1";
284
285 $pid = open3($writer, $reader, $error, @$cmd) || die $!;
286
287 # if we pipe fron STDIN, open3 closes STDIN, so we we
288 # a perl warning "Filehandle STDIN reopened as GENXYZ .. "
289 # as soon as we open a new file.
290 # to avoid that we open /dev/null
291 if (!ref($writer) && !defined(fileno(STDIN))) {
292 POSIX::close(0);
293 open(STDIN, "</dev/null");
294 }
295 };
296
297 my $err = $@;
298
299 # catch exec errors
300 if ($orig_pid != $$) {
301 warn "ERROR: $err";
302 POSIX::_exit (1);
303 kill ('KILL', $$);
304 }
305
306 die $err if $err;
307
308 local $SIG{ALRM} = sub { die "got timeout\n"; } if $timeout;
309 $oldtimeout = alarm($timeout) if $timeout;
310
311 if (ref($writer)) {
312 print $writer $input if defined $input;
313 close $writer;
314 }
315
316 my $select = new IO::Select;
317 $select->add($reader) if ref($reader);
318 $select->add($error);
319
320 my $outlog = '';
321 my $errlog = '';
322
323 my $starttime = time();
324
325 while ($select->count) {
326 my @handles = $select->can_read(1);
327
328 foreach my $h (@handles) {
329 my $buf = '';
330 my $count = sysread ($h, $buf, 4096);
331 if (!defined ($count)) {
332 my $err = $!;
333 kill (9, $pid);
334 waitpid ($pid, 0);
335 die $err;
336 }
337 $select->remove ($h) if !$count;
338 if ($h eq $reader) {
339 if ($outfunc || $logfunc) {
340 eval {
341 $outlog .= $buf;
342 while ($outlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
343 my $line = $1;
344 &$outfunc($line) if $outfunc;
345 &$logfunc($line) if $logfunc;
346 }
347 };
348 my $err = $@;
349 if ($err) {
350 kill (9, $pid);
351 waitpid ($pid, 0);
352 die $err;
353 }
354 } else {
355 print $buf;
356 *STDOUT->flush();
357 }
358 } elsif ($h eq $error) {
359 if ($errfunc || $logfunc) {
360 eval {
361 $errlog .= $buf;
362 while ($errlog =~ s/^([^\010\r\n]*)(\r|\n|(\010)+|\r\n)//s) {
363 my $line = $1;
364 &$errfunc($line) if $errfunc;
365 &$logfunc($line) if $logfunc;
366 }
367 };
368 my $err = $@;
369 if ($err) {
370 kill (9, $pid);
371 waitpid ($pid, 0);
372 die $err;
373 }
374 } else {
375 print STDERR $buf;
376 *STDERR->flush();
377 }
378 }
379 }
380 }
381
382 &$outfunc($outlog) if $outfunc && $outlog;
383 &$logfunc($outlog) if $logfunc && $outlog;
384
385 &$errfunc($errlog) if $errfunc && $errlog;
386 &$logfunc($errlog) if $logfunc && $errlog;
387
388 waitpid ($pid, 0);
389
390 if ($? == -1) {
391 die "failed to execute\n";
392 } elsif (my $sig = ($? & 127)) {
393 die "got signal $sig\n";
394 } elsif (my $ec = ($? >> 8)) {
395 if (!($ec == 24 && ($cmdstr =~ m|^(\S+/)?rsync\s|))) {
396 if ($errmsg && $laststderr) {
397 my $lerr = $laststderr;
398 $laststderr = undef;
399 die "$lerr\n";
400 }
401 die "exit code $ec\n";
402 }
403 }
404
405 alarm(0);
406 };
407
408 my $err = $@;
409
410 alarm(0);
411
412 if ($errmsg && $laststderr) {
413 &$errfunc(undef); # flush laststderr
414 }
415
416 umask ($old_umask) if defined($old_umask);
417
418 alarm($oldtimeout) if $oldtimeout;
419
420 if ($err) {
421 if ($pid && ($err eq "got timeout\n")) {
422 kill (9, $pid);
423 waitpid ($pid, 0);
424 die "command '$cmdstr' failed: $err";
425 }
426
427 if ($errmsg) {
428 $err =~ s/^usermod:\s*// if $cmdstr =~ m|^(\S+/)?usermod\s|;
429 die "$errmsg: $err";
430 } else {
431 die "command '$cmdstr' failed: $err";
432 }
433 }
434
435 return undef;
436 }
437
438 sub split_list {
439 my $listtxt = shift || '';
440
441 return split (/\0/, $listtxt) if $listtxt =~ m/\0/;
442
443 $listtxt =~ s/[,;]/ /g;
444 $listtxt =~ s/^\s+//;
445
446 my @data = split (/\s+/, $listtxt);
447
448 return @data;
449 }
450
451 sub trim {
452 my $txt = shift;
453
454 return $txt if !defined($txt);
455
456 $txt =~ s/^\s+//;
457 $txt =~ s/\s+$//;
458
459 return $txt;
460 }
461
462 # simple uri templates like "/vms/{vmid}"
463 sub template_replace {
464 my ($tmpl, $data) = @_;
465
466 return $tmpl if !$tmpl;
467
468 my $res = '';
469 while ($tmpl =~ m/([^{]+)?({([^}]+)})?/g) {
470 $res .= $1 if $1;
471 $res .= ($data->{$3} || '-') if $2;
472 }
473 return $res;
474 }
475
476 sub safe_print {
477 my ($filename, $fh, $data) = @_;
478
479 return if !$data;
480
481 my $res = print $fh $data;
482
483 die "write to '$filename' failed\n" if !$res;
484 }
485
486 sub debmirrors {
487
488 return {
489 'at' => 'ftp.at.debian.org',
490 'au' => 'ftp.au.debian.org',
491 'be' => 'ftp.be.debian.org',
492 'bg' => 'ftp.bg.debian.org',
493 'br' => 'ftp.br.debian.org',
494 'ca' => 'ftp.ca.debian.org',
495 'ch' => 'ftp.ch.debian.org',
496 'cl' => 'ftp.cl.debian.org',
497 'cz' => 'ftp.cz.debian.org',
498 'de' => 'ftp.de.debian.org',
499 'dk' => 'ftp.dk.debian.org',
500 'ee' => 'ftp.ee.debian.org',
501 'es' => 'ftp.es.debian.org',
502 'fi' => 'ftp.fi.debian.org',
503 'fr' => 'ftp.fr.debian.org',
504 'gr' => 'ftp.gr.debian.org',
505 'hk' => 'ftp.hk.debian.org',
506 'hr' => 'ftp.hr.debian.org',
507 'hu' => 'ftp.hu.debian.org',
508 'ie' => 'ftp.ie.debian.org',
509 'is' => 'ftp.is.debian.org',
510 'it' => 'ftp.it.debian.org',
511 'jp' => 'ftp.jp.debian.org',
512 'kr' => 'ftp.kr.debian.org',
513 'mx' => 'ftp.mx.debian.org',
514 'nl' => 'ftp.nl.debian.org',
515 'no' => 'ftp.no.debian.org',
516 'nz' => 'ftp.nz.debian.org',
517 'pl' => 'ftp.pl.debian.org',
518 'pt' => 'ftp.pt.debian.org',
519 'ro' => 'ftp.ro.debian.org',
520 'ru' => 'ftp.ru.debian.org',
521 'se' => 'ftp.se.debian.org',
522 'si' => 'ftp.si.debian.org',
523 'sk' => 'ftp.sk.debian.org',
524 'tr' => 'ftp.tr.debian.org',
525 'tw' => 'ftp.tw.debian.org',
526 'gb' => 'ftp.uk.debian.org',
527 'us' => 'ftp.us.debian.org',
528 };
529 }
530
531 my $keymaphash = {
532 'dk' => ['Danish', 'da', 'qwerty/dk-latin1.kmap.gz', 'dk', 'nodeadkeys'],
533 'de' => ['German', 'de', 'qwertz/de-latin1-nodeadkeys.kmap.gz', 'de', 'nodeadkeys' ],
534 'de-ch' => ['Swiss-German', 'de-ch', 'qwertz/sg-latin1.kmap.gz', 'ch', 'de_nodeadkeys' ],
535 'en-gb' => ['United Kingdom', 'en-gb', 'qwerty/uk.kmap.gz' , 'gb', 'intl' ],
536 'en-us' => ['U.S. English', 'en-us', 'qwerty/us-latin1.kmap.gz', 'us', 'intl' ],
537 'es' => ['Spanish', 'es', 'qwerty/es.kmap.gz', 'es', 'nodeadkeys'],
538 #'et' => [], # Ethopia or Estonia ??
539 'fi' => ['Finnish', 'fi', 'qwerty/fi-latin1.kmap.gz', 'fi', 'nodeadkeys'],
540 #'fo' => ['Faroe Islands', 'fo', ???, 'fo', 'nodeadkeys'],
541 'fr' => ['French', 'fr', 'azerty/fr-latin1.kmap.gz', 'fr', 'nodeadkeys'],
542 'fr-be' => ['Belgium-French', 'fr-be', 'azerty/be2-latin1.kmap.gz', 'be', 'nodeadkeys'],
543 'fr-ca' => ['Canada-French', 'fr-ca', 'qwerty/cf.kmap.gz', 'ca', 'fr-legacy'],
544 'fr-ch' => ['Swiss-French', 'fr-ch', 'qwertz/fr_CH-latin1.kmap.gz', 'ch', 'fr_nodeadkeys'],
545 #'hr' => ['Croatia', 'hr', 'qwertz/croat.kmap.gz', 'hr', ??], # latin2?
546 'hu' => ['Hungarian', 'hu', 'qwertz/hu.kmap.gz', 'hu', undef],
547 'is' => ['Icelandic', 'is', 'qwerty/is-latin1.kmap.gz', 'is', 'nodeadkeys'],
548 'it' => ['Italian', 'it', 'qwerty/it2.kmap.gz', 'it', 'nodeadkeys'],
549 'jp' => ['Japanese', 'ja', 'qwerty/jp106.kmap.gz', 'jp', undef],
550 'lt' => ['Lithuanian', 'lt', 'qwerty/lt.kmap.gz', 'lt', 'std'],
551 #'lv' => ['Latvian', 'lv', 'qwerty/lv-latin4.kmap.gz', 'lv', ??], # latin4 or latin7?
552 'mk' => ['Macedonian', 'mk', 'qwerty/mk.kmap.gz', 'mk', 'nodeadkeys'],
553 'nl' => ['Dutch', 'nl', 'qwerty/nl.kmap.gz', 'nl', undef],
554 #'nl-be' => ['Belgium-Dutch', 'nl-be', ?, ?, ?],
555 'no' => ['Norwegian', 'no', 'qwerty/no-latin1.kmap.gz', 'no', 'nodeadkeys'],
556 'pl' => ['Polish', 'pl', 'qwerty/pl.kmap.gz', 'pl', undef],
557 'pt' => ['Portuguese', 'pt', 'qwerty/pt-latin1.kmap.gz', 'pt', 'nodeadkeys'],
558 'pt-br' => ['Brazil-Portuguese', 'pt-br', 'qwerty/br-latin1.kmap.gz', 'br', 'nodeadkeys'],
559 #'ru' => ['Russian', 'ru', 'qwerty/ru.kmap.gz', 'ru', undef], # dont know?
560 'si' => ['Slovenian', 'sl', 'qwertz/slovene.kmap.gz', 'si', undef],
561 'se' => ['Swedish', 'sv', 'qwerty/se-latin1.kmap.gz', 'se', 'nodeadkeys'],
562 #'th' => [],
563 'tr' => ['Turkish', 'tr', 'qwerty/trq.kmap.gz', 'tr', undef],
564 };
565
566 my $kvmkeymaparray = [];
567 foreach my $lc (keys %$keymaphash) {
568 push @$kvmkeymaparray, $keymaphash->{$lc}->[1];
569 }
570
571 sub kvmkeymaps {
572 return $keymaphash;
573 }
574
575 sub kvmkeymaplist {
576 return $kvmkeymaparray;
577 }
578
579 sub extract_param {
580 my ($param, $key) = @_;
581
582 my $res = $param->{$key};
583 delete $param->{$key};
584
585 return $res;
586 }
587
588 # Note: we use this to wait until vncterm is ready
589 sub wait_for_vnc_port {
590 my ($port, $timeout) = @_;
591
592 $timeout = 5 if !$timeout;
593
594 for (my $i = 0; $i < $timeout; $i++) {
595 if (my $fh = IO::File->new ("/proc/net/tcp", "r")) {
596 while (defined (my $line = <$fh>)) {
597 if ($line =~ m/^\s*\d+:\s+([0-9A-Fa-f]{8}):([0-9A-Fa-f]{4})\s/) {
598 if ($port == hex($2)) {
599 close($fh);
600 return 1;
601 }
602 }
603 }
604 close($fh);
605 }
606 sleep(1);
607 }
608
609 return undef;
610 }
611
612 sub next_vnc_port {
613
614 for (my $p = 5900; $p < 6000; $p++) {
615
616 my $sock = IO::Socket::INET->new (Listen => 5,
617 LocalAddr => 'localhost',
618 LocalPort => $p,
619 ReuseAddr => 1,
620 Proto => 0);
621
622 if ($sock) {
623 close ($sock);
624 return $p;
625 }
626 }
627
628 die "unable to find free vnc port";
629 };
630
631 # NOTE: NFS syscall can't be interrupted, so alarm does
632 # not work to provide timeouts.
633 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
634 # So the spawn external 'df' process instead of using
635 # Filesys::Df (which uses statfs syscall)
636 sub df {
637 my ($path, $timeout) = @_;
638
639 my $cmd = [ 'df', '-P', '-B', '1', $path];
640
641 my $res = {
642 total => 0,
643 used => 0,
644 avail => 0,
645 };
646
647 my $parser = sub {
648 my $line = shift;
649 if (my ($fsid, $total, $used, $avail) = $line =~
650 m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
651 $res = {
652 total => $total,
653 used => $used,
654 avail => $avail,
655 };
656 }
657 };
658 eval { run_command($cmd, timeout => $timeout, outfunc => $parser); };
659 warn $@ if $@;
660
661 return $res;
662 }
663
664 # UPID helper
665 # We use this to uniquely identify a process.
666 # An 'Unique Process ID' has the following format:
667 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
668
669 sub upid_encode {
670 my $d = shift;
671
672 return sprintf("UPID:%s:%08X:%08X:%08X:%s:%s:%s:", $d->{node}, $d->{pid},
673 $d->{pstart}, $d->{starttime}, $d->{type}, $d->{id},
674 $d->{user});
675 }
676
677 sub upid_decode {
678 my ($upid, $noerr) = @_;
679
680 my $res;
681 my $filename;
682
683 # "UPID:$node:$pid:$pstart:$startime:$dtype:$id:$user"
684 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}):([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/) {
685 $res->{node} = $1;
686 $res->{pid} = hex($3);
687 $res->{pstart} = hex($4);
688 $res->{starttime} = hex($5);
689 $res->{type} = $6;
690 $res->{id} = $7;
691 $res->{user} = $8;
692
693 my $subdir = substr($5, 7, 8);
694 $filename = "$pvetaskdir/$subdir/$upid";
695
696 } else {
697 return undef if $noerr;
698 die "unable to parse worker upid '$upid'\n";
699 }
700
701 return wantarray ? ($res, $filename) : $res;
702 }
703
704 sub upid_open {
705 my ($upid) = @_;
706
707 my ($task, $filename) = upid_decode($upid);
708
709 my $dirname = dirname($filename);
710 make_path($dirname);
711
712 my $wwwid = getpwnam('www-data') ||
713 die "getpwnam failed";
714
715 my $perm = 0640;
716
717 my $outfh = IO::File->new ($filename, O_WRONLY|O_CREAT|O_EXCL, $perm) ||
718 die "unable to create output file '$filename' - $!\n";
719 chown $wwwid, -1, $outfh;
720
721 return $outfh;
722 };
723
724 sub upid_read_status {
725 my ($upid) = @_;
726
727 my ($task, $filename) = upid_decode($upid);
728 my $fh = IO::File->new($filename, "r");
729 return "unable to open file - $!" if !$fh;
730 my $maxlen = 1024;
731 sysseek($fh, -$maxlen, 2);
732 my $readbuf = '';
733 my $br = sysread($fh, $readbuf, $maxlen);
734 close($fh);
735 if ($br) {
736 return "unable to extract last line"
737 if $readbuf !~ m/\n?(.+)$/;
738 my $line = $1;
739 if ($line =~ m/^TASK OK$/) {
740 return 'OK';
741 } elsif ($line =~ m/^TASK ERROR: (.+)$/) {
742 return $1;
743 } else {
744 return "unexpected status";
745 }
746 }
747 return "unable to read tail (got $br bytes)";
748 }
749
750 # useful functions to store comments in config files
751 sub encode_text {
752 my ($text) = @_;
753
754 # all control and hi-bit characters, and ':'
755 my $unsafe = "^\x20-\x39\x3b-\x7e";
756 return uri_escape(Encode::encode("utf8", $text), $unsafe);
757 }
758
759 sub decode_text {
760 my ($data) = @_;
761
762 return Encode::decode("utf8", uri_unescape($data));
763 }
764
765 sub decode_utf8_parameters {
766 my ($param) = @_;
767
768 foreach my $p (qw(comment description firstname lastname)) {
769 $param->{$p} = decode('utf8', $param->{$p}) if $param->{$p};
770 }
771
772 return $param;
773 }
774
775 sub random_ether_addr {
776
777 my $rand = Digest::SHA::sha1_hex(rand(), time());
778
779 my $mac = '';
780 for (my $i = 0; $i < 6; $i++) {
781 my $ss = hex(substr($rand, $i*2, 2));
782 if (!$i) {
783 $ss &= 0xfe; # clear multicast
784 $ss |= 2; # set local id
785 }
786 $ss = sprintf("%02X", $ss);
787
788 if (!$i) {
789 $mac .= "$ss";
790 } else {
791 $mac .= ":$ss";
792 }
793 }
794
795 return $mac;
796 }
797
798 sub shellquote {
799 my $str = shift;
800
801 return String::ShellQuote::shell_quote($str);
802 }
803
804 sub cmd2string {
805 my ($cmd) = @_;
806
807 die "no arguments" if !$cmd;
808
809 return $cmd if !ref($cmd);
810
811 my @qa = ();
812 foreach my $arg (@$cmd) { push @qa, shellquote($arg); }
813
814 return join (' ', @qa);
815 }
816
817 # split an shell argument string into an array,
818 sub split_args {
819 my ($str) = @_;
820
821 return $str ? [ Text::ParseWords::shellwords($str) ] : [];
822 }
823
824 sub dump_logfile {
825 my ($filename, $start, $limit) = @_;
826
827 my $lines = [];
828 my $count = 0;
829
830 my $fh = IO::File->new($filename, "r");
831 if (!$fh) {
832 $count++;
833 push @$lines, { n => $count, t => "unable to open file - $!"};
834 return ($count, $lines);
835 }
836
837 $start = 0 if !$start;
838 $limit = 50 if !$limit;
839
840 my $line;
841 while (defined($line = <$fh>)) {
842 next if $count++ < $start;
843 next if $limit <= 0;
844 chomp $line;
845 push @$lines, { n => $count, t => $line};
846 $limit--;
847 }
848
849 close($fh);
850
851 # HACK: ExtJS store.guaranteeRange() does not like empty array
852 # so we add a line
853 if (!$count) {
854 $count++;
855 push @$lines, { n => $count, t => "no content"};
856 }
857
858 return ($count, $lines);
859 }
860
861 sub dir_glob_regex {
862 my ($dir, $regex) = @_;
863
864 my $dh = IO::Dir->new ($dir);
865 return wantarray ? () : undef if !$dh;
866
867 while (defined(my $tmp = $dh->read)) {
868 if (my @res = $tmp =~ m/^($regex)$/) {
869 $dh->close;
870 return wantarray ? @res : $tmp;
871 }
872 }
873 $dh->close;
874
875 return wantarray ? () : undef;
876 }
877
878 sub dir_glob_foreach {
879 my ($dir, $regex, $func) = @_;
880
881 my $dh = IO::Dir->new ($dir);
882 if (defined $dh) {
883 while (defined(my $tmp = $dh->read)) {
884 if (my @res = $tmp =~ m/^($regex)$/) {
885 &$func (@res);
886 }
887 }
888 }
889 }
890
891 1;