]>
git.proxmox.com Git - pve-access-control.git/blob - PVE/RPCEnvironment.pm
1 package PVE
::RPCEnvironment
;
5 use POSIX
qw(:sys_wait_h EINTR);
10 use PVE
::Exception
qw(raise raise_perm_exc);
16 use PVE
::AccessControl
;
19 # we use this singleton class to pass RPC related environment values
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)
33 my $log_task_result = sub {
34 my ($upid, $user, $status) = @_;
36 my $msg = 'successful';
39 my $ec = $status >> 8;
40 my $ic = $status & 255;
41 $msg = $ec ?
"failed ($ec)" : "interrupted ($ic)";
44 my $tlist = active_workers
($upid);
45 PVE
::Cluster
::broadcast_tasklist
($tlist);
47 foreach my $t (@$tlist) {
48 if ($t->{upid
} eq $upid) {
53 if ($task && $task->{status
}) {
54 $msg = $task->{status
};
56 PVE
::Cluster
::log_msg
($pri, $user, "end task $upid $msg");
59 my $worker_reaper = sub {
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
}, $?);
68 delete ($WORKER_PIDS->{$pid});
73 my $register_worker = sub {
74 my ($pid, $user, $upid) = @_;
78 # do not register if already finished
79 my $waitpid = waitpid ($pid, WNOHANG
);
80 if (defined($waitpid) && ($waitpid == $pid)) {
81 delete ($WORKER_PIDS->{$pid});
85 $WORKER_PIDS->{$pid} = {
93 my $compile_acl = sub {
94 my ($self, $user) = @_;
97 my $cfg = $self->{user_cfg
};
99 return undef if !$cfg->{roles
};
101 if ($user eq 'root@pam') { # root can do anything
102 return {'/' => $cfg->{roles
}->{'Administrator'}};
105 foreach my $path (sort keys %{$cfg->{acl
}}) {
106 my @ra = PVE
::AccessControl
::roles
($cfg, $user, $path);
109 foreach my $role (@ra) {
110 if (my $privset = $cfg->{roles
}->{$role}) {
111 foreach my $p (keys %$privset) {
117 $res->{$path} = $privs;
124 my ($self, $user, $path) = @_;
126 $user = PVE
::AccessControl
::verify_username
($user, 1);
129 my $cache = $self->{aclcache
};
131 my $acl = $cache->{$user};
134 if (!($acl = &$compile_acl($self, $user))) {
137 $cache->{$user} = $acl;
142 if (!($perm = $acl->{$path})) {
144 foreach my $p (sort keys %$acl) {
145 my $final = ($path eq $p);
147 next if !(($p eq '/') || $final || ($path =~ m
|^$p/|));
151 $acl->{$path} = $perm;
158 my ($self, $user, $path, $privs, $noerr) = @_;
160 my $perm = $self->permissions($user, $path);
162 foreach my $priv (@$privs) {
163 PVE
::AccessControl
::verify_privname
($priv);
164 if (!$perm->{$priv}) {
165 return undef if $noerr;
166 raise_perm_exc
("$path, $priv");
174 my ($self, $user, $path, $privs, $noerr) = @_;
176 my $perm = $self->permissions($user, $path);
179 foreach my $priv (@$privs) {
180 PVE
::AccessControl
::verify_privname
($priv);
181 if ($perm->{$priv}) {
189 return undef if $noerr;
191 raise_perm_exc
("$path, " . join("|", @$privs));
194 sub check_user_enabled
{
195 my ($self, $user, $noerr) = @_;
197 my $cfg = $self->{user_cfg
};
198 return PVE
::AccessControl
::check_user_enabled
($cfg, $user, $noerr);
201 sub check_user_exist
{
202 my ($self, $user, $noerr) = @_;
204 my $cfg = $self->{user_cfg
};
205 return PVE
::AccessControl
::check_user_exist
($cfg, $user, $noerr);
208 sub is_group_member
{
209 my ($self, $group, $user) = @_;
211 my $cfg = $self->{user_cfg
};
213 return 0 if !$cfg->{groups
}->{$group};
215 return defined($cfg->{groups
}->{$group}->{users
}->{$user});
219 my ($self, $user, $privs, $any) = @_;
221 my $cfg = $self->{user_cfg
};
224 foreach my $group (keys %{$cfg->{groups
}}) {
225 my $path = "/access/groups/$group";
227 if ($self->check_any($user, $path, $privs, 1)) {
228 $groups->{$group} = $cfg->{groups
}->{$group};
231 if ($self->check($user, $path, $privs, 1)) {
232 $groups->{$group} = $cfg->{groups
}->{$group};
240 sub group_member_join
{
241 my ($self, $grouplist) = @_;
245 my $cfg = $self->{user_cfg
};
246 foreach my $group (@$grouplist) {
247 my $data = $cfg->{groups
}->{$group};
249 foreach my $user (keys %{$data->{users
}}) {
257 # initialize environment - must be called once at program startup
259 my ($class, $type, %params) = @_;
261 $class = ref($class) || $class;
263 die "already initialized" if $pve_env;
265 die "unknown environment type" if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
267 $SIG{CHLD
} = $worker_reaper;
270 # cli ... command started fron command line
271 # pub ... access from public server (apache)
272 # priv ... access from private server (pvedaemon)
273 # ha ... access from HA resource manager agent (rgmanager)
284 foreach my $p (keys %params) {
285 if ($p eq 'atfork') {
286 $self->{$p} = $params{$p};
288 die "unknown option '$p'";
294 my ($sysname, $nodename) = POSIX
::uname
();
296 $nodename =~ s/\..*$//; # strip domain part, if any
298 $self->{nodename
} = $nodename;
306 die "not initialized" if !$pve_env;
312 my ($self, $enable_upload) = @_;
314 if ($self->{request_rec
}) {
316 if ($enable_upload) {
317 $cgi = CGI-
>new($self->{request_rec
});
319 # disable upload using empty upload_hook
320 $cgi = CGI-
>new($self->{request_rec
}, sub {}, undef, 0);
323 my $params = $cgi->Vars();
324 return PVE
::Tools
::decode_utf8_parameters
($params);
325 } elsif ($self->{params
}) {
326 return $self->{params
};
328 die "no parameters registered";
332 sub get_upload_info
{
333 my ($self, $param) = @_;
335 my $cgi = $self->{cgi
};
336 die "CGI not initialized" if !$cgi;
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;
343 my $res = { %$info };
345 my $tmpfilename = $cgi->tmpFileName($pd);
346 die "unable to get cgi upload file name\n" if !$tmpfilename;
347 $res->{tmpfilename
} = $tmpfilename;
349 #my $hndl = $cgi->upload($param);
350 #die "unable to get cgi upload handle\n" if !$hndl;
351 #$res->{handle} = $hndl->handle;
356 # init_request - must be called before each RPC request
358 my ($self, %params) = @_;
360 PVE
::Cluster
::cfs_update
();
362 $self->{result_attributes
} = {};
364 my $userconfig; # we use this for regression tests
365 foreach my $p (keys %params) {
366 if ($p eq 'userconfig') {
367 $userconfig = $params{$p};
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};
374 die "unknown parameter '$p'";
379 $self->{aclcache
} = {};
381 my $ucdata = PVE
::Tools
::file_get_contents
($userconfig);
382 my $cfg = PVE
::AccessControl
::parse_user_config
($userconfig, $ucdata);
383 $self->{user_cfg
} = $cfg;
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;
395 $self->{user_cfg
} = {};
396 die "Unable to load access control list: $err";
401 my ($self, $ip) = @_;
403 $self->{client_ip
} = $ip;
409 return $self->{client_ip
};
412 sub set_result_attrib
{
413 my ($self, $key, $value) = @_;
415 $self->{result_attributes
}->{$key} = $value;
418 sub get_result_attrib
{
419 my ($self, $key) = @_;
421 return $self->{result_attributes
}->{$key};
425 my ($self, $lang) = @_;
427 # fixme: initialize I18N
429 $self->{language
} = $lang;
435 return $self->{language
};
439 my ($self, $user) = @_;
443 $self->{user
} = $user;
449 die "user name not set\n" if !$self->{user
};
451 return $self->{user
};
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.
457 # $nocheck ... consider $new_upid still running (avoid that
458 # we try to read the reult to early.
460 my ($new_upid, $nocheck) = @_;
462 my $lkfn = "/var/log/pve/tasks/.active.lock";
468 my $tasklist = PVE
::INotify
::read_file
('active');
472 my $thash = {}; # only list task once
474 my $check_task = sub {
475 my ($task, $running) = @_;
477 if ($running || PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
})) {
483 delete $task->{pstart
};
486 foreach my $task (@$tasklist) {
487 my $upid = $task->{upid
};
488 next if $thash->{$upid};
489 $thash->{$upid} = $task;
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;
497 &$check_task($task, $nocheck);
501 @ta = sort { $b->{starttime
} cmp $a->{starttime
} } @ta;
503 my $save = defined($new_upid);
505 foreach my $task (@ta) {
506 next if $task->{endtime
};
507 $task->{endtime
} = time();
508 $task->{status
} = PVE
::Tools
::upid_read_status
($task->{upid
});
514 foreach my $task (@ta) {
515 if (!$task->{saved
}) {
516 $archive .= sprintf("$task->{upid} %08X $task->{status}\n", $task->{endtime
});
525 my $filename = "/var/log/pve/tasks/index";
527 my $fh = IO
::File-
>new($filename, '>>', 0644) ||
528 die "unable to open file '$filename' - $!\n";
529 PVE
::Tools
::safe_print
($filename, $fh, $archive);
532 die "unable to close file '$filename' - $!\n";
537 foreach my $task (@arlist) { # mark as not saved
541 my $maxsize = 50000; # about 1000 entries
542 if ($size > $maxsize) {
543 rename($filename, "$filename.1");
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
551 my $max = 25 - scalar(@$tlist);
552 foreach my $task (@ta) {
558 PVE
::INotify
::write_file
('active', $tlist) if $save;
563 my $res = PVE
::Tools
::lock_file
($lkfn, $timeout, $code);
569 my $kill_process_group = sub {
570 my ($pid, $pstart) = @_;
572 # send kill to process group (negative pid)
575 # always send signal to all pgrp members
576 kill(15, $kpid); # send TERM signal
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);
589 my ($upid, $killit) = @_;
591 my $task = PVE
::Tools
::upid_decode
($upid);
593 my $running = PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
});
595 return 0 if !$running;
598 &$kill_process_group($task->{pid
});
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')
610 my ($self, $dtype, $id, $user, $function) = @_;
612 $dtype = 'unknown' if !defined ($dtype);
613 $id = '' if !defined ($id);
615 $user = 'root@pve' if !defined ($user);
617 my $sync = $self->{type
} eq 'cli' ?
1 : 0;
622 local $SIG{TERM
} = 'IGNORE';
624 my $starttime = time ();
626 my @psync = POSIX
::pipe();
627 my @csync = POSIX
::pipe();
629 my $node = $self->{nodename
};
632 die "unable to fork worker - $!" if !defined($cpid);
634 my $workerpuid = $cpid ?
$cpid : $$;
636 my $pstart = PVE
::ProcFSTools
::read_proc_starttime
($workerpuid) ||
637 die "unable to read process start time";
639 my $upid = PVE
::Tools
::upid_encode
({
640 node
=> $node, pid
=> $workerpuid, pstart
=> $pstart,
641 starttime
=> $starttime, type
=> $dtype, id
=> $id, user
=> $user });
645 if (!$cpid) { # child
649 $SIG{INT
} = $SIG{QUIT
} = $SIG{TERM
} = sub { die "received interrupt\n"; };
651 $SIG{CHLD
} = $SIG{PIPE
} = 'DEFAULT';
653 # set sess/process group - we want to be able to kill the
654 # whole process group
657 POSIX
::close ($psync[0]);
658 POSIX
::close ($csync[1]);
660 $outfh = $sync ?
$psync[1] : undef;
663 PVE
::INotify
::inotify_close
();
665 if (my $atfork = $self->{atfork
}) {
669 # same algorythm as used inside SA
671 my $fd = fileno (STDIN
);
675 POSIX
::close(0) if $fd != 0;
677 die "unable to redirect STDIN - $!"
678 if !open(STDIN
, "</dev/null");
680 $outfh = PVE
::Tools
::upid_open
($upid);
685 $fd = fileno(STDOUT
);
687 POSIX
::close (1) if $fd != 1;
689 die "unable to redirect STDOUT - $!"
690 if !open(STDOUT
, ">&", $outfh);
692 STDOUT-
>autoflush (1);
694 # redirect STDERR to STDOUT
695 $fd = fileno (STDERR
);
697 POSIX
::close(2) if $fd != 2;
699 die "unable to redirect STDERR - $!"
700 if !open(STDERR
, ">&1");
702 STDERR-
>autoflush(1);
705 my $msg = "ERROR: $err";
706 POSIX
::write($psync[1], $msg, length ($msg));
707 POSIX
::close($psync[1]);
712 # sync with parent (signal that we are ready)
716 POSIX
::write($psync[1], $upid, length ($upid));
717 POSIX
::close($psync[1]);
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';
725 if ($self->{type
} eq 'ha') {
726 print "task started by HA resource agent\n";
728 eval { &$function($upid); };
734 print STDERR
"TASK ERROR: $err\n";
737 print STDERR
"TASK OK\n";
745 POSIX
::close ($psync[1]);
746 POSIX
::close ($csync[0]);
749 # sync with child (wait until child starts)
750 POSIX
::read($psync[0], $readbuf, 4096);
753 POSIX
::close($psync[0]);
754 &$register_worker($cpid, $user, $upid);
760 die "got no worker upid - start worker failed\n" if !$readbuf;
762 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
763 die "starting worker failed: $1\n";
766 if ($readbuf ne $upid) {
767 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
771 $outfh = PVE
::Tools
::upid_open
($upid);
778 POSIX
::write($csync[1], $msg, length ($msg));
779 POSIX
::close($csync[1]);
782 POSIX
::close($csync[1]);
783 kill(-9, $cpid); # make sure it gets killed
787 PVE
::Cluster
::log_msg
('info', $user, "starting task $upid");
789 my $tlist = active_workers
($upid, $sync);
790 PVE
::Cluster
::broadcast_tasklist
($tlist);
799 local $SIG{INT
} = local $SIG{QUIT
} = local $SIG{TERM
} = sub {
800 # always send signal to all pgrp members
802 if ($int_count < 3) {
803 kill(15, $kpid); # send TERM signal
805 kill(9, $kpid); # send KILL signal
809 local $SIG{PIPE
} = sub { die "broken pipe\n"; };
811 my $select = new IO
::Select
;
812 my $fh = IO
::Handle-
>new_from_fd($psync[0], 'r');
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)) {
821 die "sync pipe read error: $err\n";
823 last if $count == 0; # eof
826 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
829 if ($data =~ m/^TASK OK$/) {
831 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
842 # some commands daemonize without closing stdout
843 last if !PVE
::ProcFSTools
::check_process_running
($cpid);
849 POSIX
::close($psync[0]);
851 if ($outbuf) { # just to be sure
854 print $outfh $outbuf;
860 print STDERR
"$err\n";
862 print $outfh "TASK ERROR: $err\n";
866 &$kill_process_group($cpid, $pstart); # make sure it gets killed
872 &$log_task_result($upid, $user, $res);
875 return wantarray ?
($upid, $res) : $upid;