]> git.proxmox.com Git - pve-access-control.git/blame - PVE/RPCEnvironment.pm
fix access control
[pve-access-control.git] / PVE / RPCEnvironment.pm
CommitLineData
2c3a6c0a
DM
1package PVE::RPCEnvironment;
2
3use strict;
4use warnings;
8d6e045f 5use POSIX qw(:sys_wait_h EINTR);
b28410fc 6use IO::Handle;
2c3a6c0a 7use IO::File;
b28410fc 8use IO::Select;
2c3a6c0a 9use Fcntl qw(:flock);
37d45deb 10use PVE::Exception qw(raise raise_perm_exc);
2c3a6c0a
DM
11use PVE::SafeSyslog;
12use PVE::Tools;
13use PVE::INotify;
14use PVE::Cluster;
15use PVE::ProcFSTools;
16use PVE::AccessControl;
7b24102d 17use CGI;
2c3a6c0a
DM
18
19# we use this singleton class to pass RPC related environment values
20
21my $pve_env;
22
23# save $SIG{CHLD} handler implementation.
24# simply set $SIG{CHLD} = $worker_reaper;
25# and register forked processes with &$register_worker(pid)
26# Note: using $SIG{CHLD} = 'IGNORE' or $SIG{CHLD} = sub { wait (); } or ...
27# has serious side effects, because perls built in system() and open()
28# functions can't get the correct exit status of a child. So we cant use
29# that (also see perlipc)
30
31my $WORKER_PIDS;
32
33my $log_task_result = sub {
34 my ($upid, $user, $status) = @_;
35
36 my $msg = 'successful';
37 my $pri = 'info';
38 if ($status != 0) {
39 my $ec = $status >> 8;
40 my $ic = $status & 255;
41 $msg = $ec ? "failed ($ec)" : "interrupted ($ic)";
42 $pri = 'err';
43 }
44 my $tlist = active_workers($upid);
45 PVE::Cluster::broadcast_tasklist($tlist);
46 my $task;
47 foreach my $t (@$tlist) {
48 if ($t->{upid} eq $upid) {
49 $task = $t;
50 last;
51 }
52 }
53 if ($task && $task->{status}) {
54 $msg = $task->{status};
55 }
56 PVE::Cluster::log_msg($pri, $user, "end task $upid $msg");
57};
58
59my $worker_reaper = sub {
60 local $!; local $?;
61 foreach my $pid (keys %$WORKER_PIDS) {
62 my $waitpid = waitpid ($pid, WNOHANG);
63 if (defined($waitpid) && ($waitpid == $pid)) {
64 my $info = $WORKER_PIDS->{$pid};
65 if ($info && $info->{upid} && $info->{user}) {
66 &$log_task_result($info->{upid}, $info->{user}, $?);
67 }
68 delete ($WORKER_PIDS->{$pid});
69 }
70 }
71};
72
73my $register_worker = sub {
74 my ($pid, $user, $upid) = @_;
75
76 return if !$pid;
77
78 # do not register if already finished
79 my $waitpid = waitpid ($pid, WNOHANG);
80 if (defined($waitpid) && ($waitpid == $pid)) {
81 delete ($WORKER_PIDS->{$pid});
82 return;
83 }
84
85 $WORKER_PIDS->{$pid} = {
86 user => $user,
87 upid => $upid,
88 };
89};
90
91# ACL cache
92
93my $compile_acl = sub {
94 my ($self, $user) = @_;
95
96 my $res = {};
97 my $cfg = $self->{user_cfg};
98
99 return undef if !$cfg->{roles};
100
101 if ($user eq 'root@pam') { # root can do anything
102 return {'/' => $cfg->{roles}->{'Administrator'}};
103 }
104
105 foreach my $path (sort keys %{$cfg->{acl}}) {
106 my @ra = PVE::AccessControl::roles($cfg, $user, $path);
107
108 my $privs = {};
109 foreach my $role (@ra) {
110 if (my $privset = $cfg->{roles}->{$role}) {
111 foreach my $p (keys %$privset) {
112 $privs->{$p} = 1;
113 }
114 }
115 }
116
117 $res->{$path} = $privs;
118 }
119
120 return $res;
121};
122
123sub permissions {
124 my ($self, $user, $path) = @_;
125
126 $user = PVE::AccessControl::verify_username($user, 1);
127 return {} if !$user;
128
129 my $cache = $self->{aclcache};
130
131 my $acl = $cache->{$user};
132
133 if (!$acl) {
134 if (!($acl = &$compile_acl($self, $user))) {
135 return {};
136 }
137 $cache->{$user} = $acl;
138 }
139
140 my $perm;
141
142 if (!($perm = $acl->{$path})) {
143 $perm = {};
144 foreach my $p (sort keys %$acl) {
145 my $final = ($path eq $p);
146
147 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
148
149 $perm = $acl->{$p};
150 }
151 $acl->{$path} = $perm;
152 }
153
154 return $perm;
155}
156
157sub check {
37d45deb 158 my ($self, $user, $path, $privs, $noerr) = @_;
2c3a6c0a
DM
159
160 my $perm = $self->permissions($user, $path);
161
162 foreach my $priv (@$privs) {
37d45deb
DM
163 PVE::AccessControl::verify_privname($priv);
164 if (!$perm->{$priv}) {
165 return undef if $noerr;
166 raise_perm_exc("$path, $priv");
167 }
2c3a6c0a
DM
168 };
169
170 return 1;
171};
172
37d45deb
DM
173sub check_any {
174 my ($self, $user, $path, $privs, $noerr) = @_;
175
176 my $perm = $self->permissions($user, $path);
177
178 my $found = 0;
179 foreach my $priv (@$privs) {
180 PVE::AccessControl::verify_privname($priv);
181 if ($perm->{$priv}) {
182 $found = 1;
183 last;
184 }
185 };
186
187 return 1 if $found;
188
189 return undef if $noerr;
190
191 raise_perm_exc("$path, " . join("|", @$privs));
192};
193
7070c1ae
DM
194sub check_user_enabled {
195 my ($self, $user, $noerr) = @_;
2c3a6c0a
DM
196
197 my $cfg = $self->{user_cfg};
7070c1ae 198 return PVE::AccessControl::check_user_enabled($cfg, $user, $noerr);
2c3a6c0a
DM
199}
200
37d45deb
DM
201sub check_user_exist {
202 my ($self, $user, $noerr) = @_;
203
204 my $cfg = $self->{user_cfg};
205 return PVE::AccessControl::check_user_exist($cfg, $user, $noerr);
206}
207
208sub is_group_member {
209 my ($self, $group, $user) = @_;
210
211 my $cfg = $self->{user_cfg};
212
213 return 0 if !$cfg->{groups}->{$group};
214
215 return defined($cfg->{groups}->{$group}->{users}->{$user});
216}
217
218sub filter_groups {
b9180ed2 219 my ($self, $user, $privs, $any) = @_;
37d45deb
DM
220
221 my $cfg = $self->{user_cfg};
222
223 my $groups = {};
224 foreach my $group (keys %{$cfg->{groups}}) {
b9180ed2 225 my $path = "/access/groups/$group";
37d45deb 226 if ($any) {
b9180ed2 227 if ($self->check_any($user, $path, $privs, 1)) {
37d45deb
DM
228 $groups->{$group} = $cfg->{groups}->{$group};
229 }
230 } else {
b9180ed2 231 if ($self->check($user, $path, $privs, 1)) {
37d45deb
DM
232 $groups->{$group} = $cfg->{groups}->{$group};
233 }
234 }
235 }
236
237 return $groups;
238}
239
240sub group_member_join {
241 my ($self, $grouplist) = @_;
242
243 my $users = {};
244
245 my $cfg = $self->{user_cfg};
246 foreach my $group (@$grouplist) {
247 my $data = $cfg->{groups}->{$group};
248 next if !$data;
249 foreach my $user (keys %{$data->{users}}) {
250 $users->{$user} = 1;
251 }
252 }
253
254 return $users;
255}
256
2c3a6c0a
DM
257# initialize environment - must be called once at program startup
258sub init {
259 my ($class, $type, %params) = @_;
260
261 $class = ref($class) || $class;
262
263 die "already initialized" if $pve_env;
264
e42eedbc 265 die "unknown environment type" if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
2c3a6c0a
DM
266
267 $SIG{CHLD} = $worker_reaper;
268
269 # environment types
270 # cli ... command started fron command line
271 # pub ... access from public server (apache)
272 # priv ... access from private server (pvedaemon)
e42eedbc 273 # ha ... access from HA resource manager agent (rgmanager)
2c3a6c0a
DM
274
275 my $self = {
276 user_cfg => {},
277 aclcache => {},
278 aclversion => undef,
279 type => $type,
280 };
281
282 bless $self, $class;
283
284 foreach my $p (keys %params) {
285 if ($p eq 'atfork') {
286 $self->{$p} = $params{$p};
287 } else {
288 die "unknown option '$p'";
289 }
290 }
291
292 $pve_env = $self;
293
294 my ($sysname, $nodename) = POSIX::uname();
295
296 $nodename =~ s/\..*$//; # strip domain part, if any
297
298 $self->{nodename} = $nodename;
299
300 return $self;
301};
302
303# get the singleton
304sub get {
305
306 die "not initialized" if !$pve_env;
307
308 return $pve_env;
309}
310
7b24102d
DM
311sub parse_params {
312 my ($self, $enable_upload) = @_;
313
314 if ($self->{request_rec}) {
315 my $cgi;
316 if ($enable_upload) {
317 $cgi = CGI->new($self->{request_rec});
318 } else {
319 # disable upload using empty upload_hook
320 $cgi = CGI->new($self->{request_rec}, sub {}, undef, 0);
321 }
322 $self->{cgi} = $cgi;
323 my $params = $cgi->Vars();
76c377c1 324 return PVE::Tools::decode_utf8_parameters($params);
7b24102d
DM
325 } elsif ($self->{params}) {
326 return $self->{params};
327 } else {
328 die "no parameters registered";
329 }
330}
331
332sub get_upload_info {
333 my ($self, $param) = @_;
334
335 my $cgi = $self->{cgi};
336 die "CGI not initialized" if !$cgi;
337
338 my $pd = $cgi->param($param);
339 die "unable to get cgi parameter info\n" if !$pd;
340 my $info = $cgi->uploadInfo($pd);
341 die "unable to get cgi upload info\n" if !$info;
342
343 my $res = { %$info };
344
345 my $tmpfilename = $cgi->tmpFileName($pd);
346 die "unable to get cgi upload file name\n" if !$tmpfilename;
347 $res->{tmpfilename} = $tmpfilename;
348
349 #my $hndl = $cgi->upload($param);
350 #die "unable to get cgi upload handle\n" if !$hndl;
351 #$res->{handle} = $hndl->handle;
352
353 return $res;
354}
355
2c3a6c0a
DM
356# init_request - must be called before each RPC request
357sub init_request {
358 my ($self, %params) = @_;
359
360 PVE::Cluster::cfs_update();
361
be6ea723 362 $self->{result_attributes} = {};
272fe9ff 363
2c3a6c0a
DM
364 my $userconfig; # we use this for regression tests
365 foreach my $p (keys %params) {
366 if ($p eq 'userconfig') {
367 $userconfig = $params{$p};
7b24102d
DM
368 } elsif ($p eq 'request_rec') {
369 # pass Apache2::RequestRec
370 $self->{request_rec} = $params{$p};
371 } elsif ($p eq 'params') {
372 $self->{params} = $params{$p};
2c3a6c0a
DM
373 } else {
374 die "unknown parameter '$p'";
375 }
376 }
377
378 eval {
379 $self->{aclcache} = {};
380 if ($userconfig) {
381 my $ucdata = PVE::Tools::file_get_contents($userconfig);
382 my $cfg = PVE::AccessControl::parse_user_config($userconfig, $ucdata);
383 $self->{user_cfg} = $cfg;
384 } else {
385 my $ucvers = PVE::Cluster::cfs_file_version('user.cfg');
386 if (!$self->{aclcache} || !defined($self->{aclversion}) ||
387 !defined($ucvers) || ($ucvers ne $self->{aclversion})) {
388 $self->{aclversion} = $ucvers;
389 my $cfg = PVE::Cluster::cfs_read_file('user.cfg');
390 $self->{user_cfg} = $cfg;
391 }
392 }
393 };
394 if (my $err = $@) {
395 $self->{user_cfg} = {};
396 die "Unable to load access control list: $err";
397 }
398}
399
400sub set_client_ip {
401 my ($self, $ip) = @_;
402
403 $self->{client_ip} = $ip;
404}
405
406sub get_client_ip {
407 my ($self) = @_;
408
409 return $self->{client_ip};
410}
411
be6ea723
DM
412sub set_result_attrib {
413 my ($self, $key, $value) = @_;
2c3a6c0a 414
be6ea723 415 $self->{result_attributes}->{$key} = $value;
2c3a6c0a
DM
416}
417
be6ea723
DM
418sub get_result_attrib {
419 my ($self, $key) = @_;
272fe9ff 420
be6ea723 421 return $self->{result_attributes}->{$key};
272fe9ff
DM
422}
423
2c3a6c0a
DM
424sub set_language {
425 my ($self, $lang) = @_;
426
427 # fixme: initialize I18N
428
429 $self->{language} = $lang;
430}
431
432sub get_language {
433 my ($self) = @_;
434
435 return $self->{language};
436}
437
438sub set_user {
439 my ($self, $user) = @_;
440
441 # fixme: get ACLs
442
443 $self->{user} = $user;
444}
445
446sub get_user {
447 my ($self) = @_;
448
449 die "user name not set\n" if !$self->{user};
450
451 return $self->{user};
452}
453
454# read/update list of active workers
455# we move all finished tasks to the archive index,
456# but keep aktive and most recent task in the active file.
5bf71a96
DM
457# $nocheck ... consider $new_upid still running (avoid that
458# we try to read the reult to early.
2c3a6c0a 459sub active_workers {
5bf71a96 460 my ($new_upid, $nocheck) = @_;
2c3a6c0a
DM
461
462 my $lkfn = "/var/log/pve/tasks/.active.lock";
463
464 my $timeout = 10;
465
466 my $code = sub {
467
468 my $tasklist = PVE::INotify::read_file('active');
469
470 my @ta;
471 my $tlist = [];
472 my $thash = {}; # only list task once
473
474 my $check_task = sub {
d33d0735 475 my ($task, $running) = @_;
2c3a6c0a 476
d33d0735 477 if ($running || PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart})) {
2c3a6c0a
DM
478 push @$tlist, $task;
479 } else {
480 delete $task->{pid};
481 push @ta, $task;
482 }
483 delete $task->{pstart};
484 };
485
486 foreach my $task (@$tasklist) {
487 my $upid = $task->{upid};
488 next if $thash->{$upid};
489 $thash->{$upid} = $task;
490 &$check_task($task);
491 }
492
493 if ($new_upid && !(my $task = $thash->{$new_upid})) {
494 $task = PVE::Tools::upid_decode($new_upid);
495 $task->{upid} = $new_upid;
496 $thash->{$new_upid} = $task;
d33d0735 497 &$check_task($task, $nocheck);
2c3a6c0a
DM
498 }
499
500
501 @ta = sort { $b->{starttime} cmp $a->{starttime} } @ta;
502
503 my $save = defined($new_upid);
504
505 foreach my $task (@ta) {
506 next if $task->{endtime};
507 $task->{endtime} = time();
508 $task->{status} = PVE::Tools::upid_read_status($task->{upid});
509 $save = 1;
510 }
511
512 my $archive = '';
513 my @arlist = ();
514 foreach my $task (@ta) {
515 if (!$task->{saved}) {
516 $archive .= sprintf("$task->{upid} %08X $task->{status}\n", $task->{endtime});
517 $save = 1;
518 push @arlist, $task;
519 $task->{saved} = 1;
520 }
521 }
522
523 if ($archive) {
524 my $size = 0;
525 my $filename = "/var/log/pve/tasks/index";
526 eval {
527 my $fh = IO::File->new($filename, '>>', 0644) ||
528 die "unable to open file '$filename' - $!\n";
529 PVE::Tools::safe_print($filename, $fh, $archive);
530 $size = -s $fh;
531 close($fh) ||
532 die "unable to close file '$filename' - $!\n";
533 };
534 my $err = $@;
535 if ($err) {
536 syslog('err', $err);
537 foreach my $task (@arlist) { # mark as not saved
538 $task->{saved} = 0;
539 }
540 }
541 my $maxsize = 50000; # about 1000 entries
542 if ($size > $maxsize) {
543 rename($filename, "$filename.1");
544 }
545 }
546
547 # we try to reduce the amount of data
548 # list all running tasks and task and a few others
549 # try to limit to 25 tasks
550 my $ctime = time();
551 my $max = 25 - scalar(@$tlist);
552 foreach my $task (@ta) {
553 last if $max <= 0;
554 push @$tlist, $task;
555 $max--;
556 }
557
558 PVE::INotify::write_file('active', $tlist) if $save;
559
560 return $tlist;
561 };
562
563 my $res = PVE::Tools::lock_file($lkfn, $timeout, $code);
564 die $@ if $@;
565
566 return $res;
567}
568
b9e47e57
DM
569my $kill_process_group = sub {
570 my ($pid, $pstart) = @_;
571
572 # send kill to process group (negative pid)
573 my $kpid = -$pid;
574
575 # always send signal to all pgrp members
576 kill(15, $kpid); # send TERM signal
577
578 # give max 5 seconds to shut down
579 for (my $i = 0; $i < 5; $i++) {
580 return if !PVE::ProcFSTools::check_process_running($pid, $pstart);
581 sleep (1);
582 }
583
584 # to be sure
585 kill(9, $kpid);
586};
587
588sub check_worker {
589 my ($upid, $killit) = @_;
590
591 my $task = PVE::Tools::upid_decode($upid);
592
593 my $running = PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart});
594
595 return 0 if !$running;
596
597 if ($killit) {
598 &$kill_process_group($task->{pid});
599 return 0;
600 }
601
602 return 1;
603}
604
2c3a6c0a
DM
605# start long running workers
606# STDIN is redirected to /dev/null
607# STDOUT,STDERR are redirected to the filename returned by upid_decode
608# NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
609sub fork_worker {
610 my ($self, $dtype, $id, $user, $function) = @_;
611
612 $dtype = 'unknown' if !defined ($dtype);
613 $id = '' if !defined ($id);
614
615 $user = 'root@pve' if !defined ($user);
616
617 my $sync = $self->{type} eq 'cli' ? 1 : 0;
618
619 local $SIG{INT} =
620 local $SIG{QUIT} =
621 local $SIG{PIPE} =
622 local $SIG{TERM} = 'IGNORE';
623
624 my $starttime = time ();
625
626 my @psync = POSIX::pipe();
627 my @csync = POSIX::pipe();
628
629 my $node = $self->{nodename};
630
631 my $cpid = fork();
632 die "unable to fork worker - $!" if !defined($cpid);
633
634 my $workerpuid = $cpid ? $cpid : $$;
635
636 my $pstart = PVE::ProcFSTools::read_proc_starttime($workerpuid) ||
637 die "unable to read process start time";
638
639 my $upid = PVE::Tools::upid_encode ({
640 node => $node, pid => $workerpuid, pstart => $pstart,
641 starttime => $starttime, type => $dtype, id => $id, user => $user });
642
643 my $outfh;
644
645 if (!$cpid) { # child
646
647 $0 = "task $upid";
648
649 $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = sub { die "received interrupt\n"; };
650
651 $SIG{CHLD} = $SIG{PIPE} = 'DEFAULT';
652
653 # set sess/process group - we want to be able to kill the
654 # whole process group
655 POSIX::setsid();
656
657 POSIX::close ($psync[0]);
658 POSIX::close ($csync[1]);
659
660 $outfh = $sync ? $psync[1] : undef;
661
662 eval {
663 PVE::INotify::inotify_close();
664
665 if (my $atfork = $self->{atfork}) {
666 &$atfork();
667 }
668
669 # same algorythm as used inside SA
670 # STDIN = /dev/null
671 my $fd = fileno (STDIN);
2c3a6c0a 672
5a941ebe
DM
673 if (!$sync) {
674 close STDIN;
675 POSIX::close(0) if $fd != 0;
676
677 die "unable to redirect STDIN - $!"
678 if !open(STDIN, "</dev/null");
679
680 $outfh = PVE::Tools::upid_open($upid);
681 }
2c3a6c0a 682
2c3a6c0a
DM
683
684 # redirect STDOUT
685 $fd = fileno(STDOUT);
686 close STDOUT;
687 POSIX::close (1) if $fd != 1;
688
689 die "unable to redirect STDOUT - $!"
690 if !open(STDOUT, ">&", $outfh);
691
692 STDOUT->autoflush (1);
693
694 # redirect STDERR to STDOUT
695 $fd = fileno (STDERR);
696 close STDERR;
697 POSIX::close(2) if $fd != 2;
698
699 die "unable to redirect STDERR - $!"
700 if !open(STDERR, ">&1");
701
702 STDERR->autoflush(1);
703 };
704 if (my $err = $@) {
705 my $msg = "ERROR: $err";
706 POSIX::write($psync[1], $msg, length ($msg));
707 POSIX::close($psync[1]);
708 POSIX::_exit(1);
b9e47e57 709 kill(-9, $$);
2c3a6c0a
DM
710 }
711
f6f2d51f 712 # sync with parent (signal that we are ready)
2c3a6c0a
DM
713 if ($sync) {
714 print "$upid\n";
715 } else {
716 POSIX::write($psync[1], $upid, length ($upid));
717 POSIX::close($psync[1]);
718 }
719
720 my $readbuf = '';
721 # sync with parent (wait until parent is ready)
722 POSIX::read($csync[0], $readbuf, 4096);
723 die "parent setup error\n" if $readbuf ne 'OK';
724
e42eedbc
DM
725 if ($self->{type} eq 'ha') {
726 print "task started by HA resource agent\n";
727 }
2c3a6c0a
DM
728 eval { &$function($upid); };
729 my $err = $@;
730 if ($err) {
731 chomp $err;
732 $err =~ s/\n/ /mg;
733 syslog('err', $err);
734 print STDERR "TASK ERROR: $err\n";
735 POSIX::_exit(-1);
736 } else {
737 print STDERR "TASK OK\n";
b9e47e57 738 POSIX::_exit(0);
2c3a6c0a 739 }
b9e47e57 740 kill(-9, $$);
2c3a6c0a
DM
741 }
742
743 # parent
744
745 POSIX::close ($psync[1]);
746 POSIX::close ($csync[0]);
747
748 my $readbuf = '';
749 # sync with child (wait until child starts)
750 POSIX::read($psync[0], $readbuf, 4096);
751
752 if (!$sync) {
753 POSIX::close($psync[0]);
754 &$register_worker($cpid, $user, $upid);
755 } else {
756 chomp $readbuf;
757 }
758
759 eval {
760 die "got no worker upid - start worker failed\n" if !$readbuf;
761
762 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
763 die "starting worker failed: $1\n";
764 }
765
766 if ($readbuf ne $upid) {
767 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
768 }
769
770 if ($sync) {
771 $outfh = PVE::Tools::upid_open($upid);
772 }
773 };
774 my $err = $@;
775
776 if (!$err) {
777 my $msg = 'OK';
778 POSIX::write($csync[1], $msg, length ($msg));
779 POSIX::close($csync[1]);
780
781 } else {
782 POSIX::close($csync[1]);
b9e47e57 783 kill(-9, $cpid); # make sure it gets killed
2c3a6c0a
DM
784 die $err;
785 }
786
787 PVE::Cluster::log_msg('info', $user, "starting task $upid");
788
5bf71a96 789 my $tlist = active_workers($upid, $sync);
2c3a6c0a
DM
790 PVE::Cluster::broadcast_tasklist($tlist);
791
792 my $res = 0;
793
794 if ($sync) {
795 my $count;
796 my $outbuf = '';
8d6e045f 797 my $int_count = 0;
2c3a6c0a 798 eval {
8d6e045f 799 local $SIG{INT} = local $SIG{QUIT} = local $SIG{TERM} = sub {
527b2e7a
DM
800 # always send signal to all pgrp members
801 my $kpid = -$cpid;
8d6e045f 802 if ($int_count < 3) {
527b2e7a 803 kill(15, $kpid); # send TERM signal
8d6e045f 804 } else {
527b2e7a 805 kill(9, $kpid); # send KILL signal
8d6e045f
DM
806 }
807 $int_count++;
808 };
2c3a6c0a 809 local $SIG{PIPE} = sub { die "broken pipe\n"; };
b28410fc
DM
810
811 my $select = new IO::Select;
812 my $fh = IO::Handle->new_from_fd($psync[0], 'r');
813 $select->add($fh);
814
815 while ($select->count) {
816 my @handles = $select->can_read(1);
817 if (scalar(@handles)) {
818 my $count = sysread ($handles[0], $readbuf, 4096);
819 if (!defined ($count)) {
820 my $err = $!;
821 die "sync pipe read error: $err\n";
2c3a6c0a 822 }
b28410fc
DM
823 last if $count == 0; # eof
824
825 $outbuf .= $readbuf;
826 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
827 my $line = $1;
828 my $data = $2;
829 if ($data =~ m/^TASK OK$/) {
830 # skip
831 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
832 print STDERR "$1\n";
833 } else {
834 print $line;
835 }
836 if ($outfh) {
837 print $outfh $line;
838 $outfh->flush();
839 }
2c3a6c0a 840 }
b28410fc
DM
841 } else {
842 # some commands daemonize without closing stdout
843 last if !PVE::ProcFSTools::check_process_running($cpid);
2c3a6c0a
DM
844 }
845 }
846 };
847 my $err = $@;
848
849 POSIX::close($psync[0]);
850
851 if ($outbuf) { # just to be sure
852 print $outbuf;
853 if ($outfh) {
854 print $outfh $outbuf;
855 }
856 }
857
858 if ($err) {
859 $err =~ s/\n/ /mg;
860 print STDERR "$err\n";
861 if ($outfh) {
862 print $outfh "TASK ERROR: $err\n";
863 }
2c3a6c0a
DM
864 }
865
b9e47e57
DM
866 &$kill_process_group($cpid, $pstart); # make sure it gets killed
867
2c3a6c0a
DM
868 close($outfh);
869
b9e47e57 870 waitpid($cpid, 0);
2c3a6c0a
DM
871 $res = $?;
872 &$log_task_result($upid, $user, $res);
873 }
874
875 return wantarray ? ($upid, $res) : $upid;
876}
877
8781;