]>
git.proxmox.com Git - pve-access-control.git/blob - PVE/RPCEnvironment.pm
0df71dca594099544d2cdc5961c31831927947ff
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_path = sub {
94 my ($self, $user, $path) = @_;
96 my $cfg = $self->{user_cfg
};
98 return undef if !$cfg->{roles
};
100 die "internal error" if $user eq 'root@pam';
102 my $cache = $self->{aclcache
};
103 $cache->{$user} = {} if !$cache->{$user};
104 my $data = $cache->{$user};
106 if (!$data->{poolroles
}) {
107 $data->{poolroles
} = {};
109 foreach my $poolpath (keys %{$cfg->{pools
}}) {
110 my $d = $cfg->{pools
}->{$poolpath};
111 my @ra = PVE
::AccessControl
::roles
($cfg, $user, "/pool$poolpath"); # pool roles
112 next if !scalar(@ra);
113 foreach my $vmid (keys %{$d->{vms
}}) {
115 $data->{poolroles
}->{"/vms/$vmid"}->{$role} = 1;
118 foreach my $storeid (keys %{$d->{storage
}}) {
120 $data->{poolroles
}->{"/storage/$storeid"}->{$role} = 1;
126 my @ra = PVE
::AccessControl
::roles
($cfg, $user, $path);
128 # apply roles inherited from pools
129 # Note: assume we do not want to propagate those privs
130 if ($data->{poolroles
}->{$path}) {
131 if (!($ra[0] && $ra[0] eq 'NoAccess')) {
132 if ($data->{poolroles
}->{$path}->{NoAccess
}) {
135 foreach my $role (keys %{$data->{poolroles
}->{$path}}) {
142 $data->{roles
}->{$path} = [ @ra ];
145 foreach my $role (@ra) {
146 if (my $privset = $cfg->{roles
}->{$role}) {
147 foreach my $p (keys %$privset) {
152 $data->{privs
}->{$path} = $privs;
158 my ($self, $user, $path) = @_;
160 if ($user eq 'root@pam') { # root can do anything
161 return ('Administrator');
164 $user = PVE
::AccessControl
::verify_username
($user, 1);
167 my $cache = $self->{aclcache
};
168 $cache->{$user} = {} if !$cache->{$user};
170 my $acl = $cache->{$user};
172 my $roles = $acl->{roles
}->{$path};
173 return @$roles if $roles;
175 &$compile_acl_path($self, $user, $path);
176 $roles = $acl->{roles
}->{$path} || [];
181 my ($self, $user, $path) = @_;
183 if ($user eq 'root@pam') { # root can do anything
184 my $cfg = $self->{user_cfg
};
185 return $cfg->{roles
}->{'Administrator'};
188 $user = PVE
::AccessControl
::verify_username
($user, 1);
191 my $cache = $self->{aclcache
};
192 $cache->{$user} = {} if !$cache->{$user};
194 my $acl = $cache->{$user};
196 my $perm = $acl->{privs
}->{$path};
197 return $perm if $perm;
199 return &$compile_acl_path($self, $user, $path);
203 my ($self, $user, $path, $privs, $noerr) = @_;
205 my $perm = $self->permissions($user, $path);
207 foreach my $priv (@$privs) {
208 PVE
::AccessControl
::verify_privname
($priv);
209 if (!$perm->{$priv}) {
210 return undef if $noerr;
211 raise_perm_exc
("$path, $priv");
219 my ($self, $user, $path, $privs, $noerr) = @_;
221 my $perm = $self->permissions($user, $path);
224 foreach my $priv (@$privs) {
225 PVE
::AccessControl
::verify_privname
($priv);
226 if ($perm->{$priv}) {
234 return undef if $noerr;
236 raise_perm_exc
("$path, " . join("|", @$privs));
239 sub check_user_enabled
{
240 my ($self, $user, $noerr) = @_;
242 my $cfg = $self->{user_cfg
};
243 return PVE
::AccessControl
::check_user_enabled
($cfg, $user, $noerr);
246 sub check_user_exist
{
247 my ($self, $user, $noerr) = @_;
249 my $cfg = $self->{user_cfg
};
250 return PVE
::AccessControl
::check_user_exist
($cfg, $user, $noerr);
253 sub is_group_member
{
254 my ($self, $group, $user) = @_;
256 my $cfg = $self->{user_cfg
};
258 return 0 if !$cfg->{groups
}->{$group};
260 return defined($cfg->{groups
}->{$group}->{users
}->{$user});
264 my ($self, $user, $privs, $any) = @_;
266 my $cfg = $self->{user_cfg
};
269 foreach my $group (keys %{$cfg->{groups
}}) {
270 my $path = "/access/groups/$group";
272 if ($self->check_any($user, $path, $privs, 1)) {
273 $groups->{$group} = $cfg->{groups
}->{$group};
276 if ($self->check($user, $path, $privs, 1)) {
277 $groups->{$group} = $cfg->{groups
}->{$group};
285 sub group_member_join
{
286 my ($self, $grouplist) = @_;
290 my $cfg = $self->{user_cfg
};
291 foreach my $group (@$grouplist) {
292 my $data = $cfg->{groups
}->{$group};
294 foreach my $user (keys %{$data->{users
}}) {
302 sub exec_api2_perm_check
{
303 my ($self, $check, $username, $param, $noerr) = @_;
305 # syslog("info", "CHECK " . join(', ', @$check));
308 my $test = $check->[$ind++];
309 die "no permission test specified" if !$test;
311 if ($test eq 'and') {
312 while (my $subcheck = $check->[$ind++]) {
313 $self->exec_api2_perm_check($subcheck, $username, $param);
316 } elsif ($test eq 'or') {
317 while (my $subcheck = $check->[$ind++]) {
318 return 1 if $self->exec_api2_perm_check($subcheck, $username, $param, 1);
322 } elsif ($test eq 'perm') {
323 my ($t, $tmplpath, $privs, %options) = @$check;
324 my $any = $options{any
};
325 die "missing parameters" if !($tmplpath && $privs);
326 my $path = PVE
::Tools
::template_replace
($tmplpath, $param);
328 return $self->check_any($username, $path, $privs, $noerr);
330 return $self->check($username, $path, $privs, $noerr);
332 } elsif ($test eq 'userid-group') {
333 my $userid = $param->{userid
};
334 my ($t, $privs, %options) = @$check;
335 return if !$options{groups_param
} && !$self->check_user_exist($userid, $noerr);
336 if (!$self->check_any($username, "/access", $privs, 1)) {
337 my $groups = $self->filter_groups($username, $privs, 1);
338 if ($options{groups_param
}) {
339 my @group_param = PVE
::Tools
::split_list
($param->{groups
});
340 raise_perm_exc
("/access, " . join("|", @$privs)) if !scalar(@group_param);
341 foreach my $pg (@group_param) {
342 raise_perm_exc
("/access/groups/$pg, " . join("|", @$privs))
346 my $allowed_users = $self->group_member_join([keys %$groups]);
347 if (!$allowed_users->{$userid}) {
354 } elsif ($test eq 'userid-param') {
355 my $userid = $param->{userid
};
356 return if !$self->check_user_exist($userid, $noerr);
357 my ($t, $subtest) = @$check;
358 die "missing parameters" if !$subtest;
359 if ($subtest eq 'self') {
360 return 1 if $username eq 'userid';
364 die "unknown userid-param test";
367 die "unknown permission test";
371 sub check_api2_permissions
{
372 my ($self, $perm, $username, $param) = @_;
374 return 1 if !$username && $perm->{user
} eq 'world';
376 raise_perm_exc
("user != null") if !$username;
378 return 1 if $username eq 'root@pam';
380 raise_perm_exc
('user != root@pam') if !$perm;
382 return 1 if $perm->{user
} && $perm->{user
} eq 'all';
384 return $self->exec_api2_perm_check($perm->{check
}, $username, $param)
390 # initialize environment - must be called once at program startup
392 my ($class, $type, %params) = @_;
394 $class = ref($class) || $class;
396 die "already initialized" if $pve_env;
398 die "unknown environment type" if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
400 $SIG{CHLD
} = $worker_reaper;
403 # cli ... command started fron command line
404 # pub ... access from public server (apache)
405 # priv ... access from private server (pvedaemon)
406 # ha ... access from HA resource manager agent (rgmanager)
417 foreach my $p (keys %params) {
418 if ($p eq 'atfork') {
419 $self->{$p} = $params{$p};
421 die "unknown option '$p'";
427 my ($sysname, $nodename) = POSIX
::uname
();
429 $nodename =~ s/\..*$//; # strip domain part, if any
431 $self->{nodename
} = $nodename;
439 die "not initialized" if !$pve_env;
445 my ($self, $enable_upload) = @_;
447 if ($self->{request_rec
}) {
449 if ($enable_upload) {
450 $cgi = CGI-
>new($self->{request_rec
});
452 # disable upload using empty upload_hook
453 $cgi = CGI-
>new($self->{request_rec
}, sub {}, undef, 0);
456 my $params = $cgi->Vars();
457 return PVE
::Tools
::decode_utf8_parameters
($params);
458 } elsif ($self->{params
}) {
459 return $self->{params
};
461 die "no parameters registered";
465 sub get_upload_info
{
466 my ($self, $param) = @_;
468 my $cgi = $self->{cgi
};
469 die "CGI not initialized" if !$cgi;
471 my $pd = $cgi->param($param);
472 die "unable to get cgi parameter info\n" if !$pd;
473 my $info = $cgi->uploadInfo($pd);
474 die "unable to get cgi upload info\n" if !$info;
476 my $res = { %$info };
478 my $tmpfilename = $cgi->tmpFileName($pd);
479 die "unable to get cgi upload file name\n" if !$tmpfilename;
480 $res->{tmpfilename
} = $tmpfilename;
482 #my $hndl = $cgi->upload($param);
483 #die "unable to get cgi upload handle\n" if !$hndl;
484 #$res->{handle} = $hndl->handle;
489 # init_request - must be called before each RPC request
491 my ($self, %params) = @_;
493 PVE
::Cluster
::cfs_update
();
495 $self->{result_attributes
} = {};
497 my $userconfig; # we use this for regression tests
498 foreach my $p (keys %params) {
499 if ($p eq 'userconfig') {
500 $userconfig = $params{$p};
501 } elsif ($p eq 'request_rec') {
502 # pass Apache2::RequestRec
503 $self->{request_rec
} = $params{$p};
504 } elsif ($p eq 'params') {
505 $self->{params
} = $params{$p};
507 die "unknown parameter '$p'";
512 $self->{aclcache
} = {};
514 my $ucdata = PVE
::Tools
::file_get_contents
($userconfig);
515 my $cfg = PVE
::AccessControl
::parse_user_config
($userconfig, $ucdata);
516 $self->{user_cfg
} = $cfg;
519 my $ucvers = PVE
::Cluster
::cfs_file_version
('user.cfg');
520 if (!$self->{aclcache
} || !defined($self->{aclversion
}) ||
521 !defined($ucvers) || ($ucvers ne $self->{aclversion
})) {
522 $self->{aclversion
} = $ucvers;
523 my $cfg = PVE
::Cluster
::cfs_read_file
('user.cfg');
524 $self->{user_cfg
} = $cfg;
529 $self->{user_cfg
} = {};
530 die "Unable to load access control list: $err";
535 my ($self, $ip) = @_;
537 $self->{client_ip
} = $ip;
543 return $self->{client_ip
};
546 sub set_result_attrib
{
547 my ($self, $key, $value) = @_;
549 $self->{result_attributes
}->{$key} = $value;
552 sub get_result_attrib
{
553 my ($self, $key) = @_;
555 return $self->{result_attributes
}->{$key};
559 my ($self, $lang) = @_;
561 # fixme: initialize I18N
563 $self->{language
} = $lang;
569 return $self->{language
};
573 my ($self, $user) = @_;
577 $self->{user
} = $user;
583 die "user name not set\n" if !$self->{user
};
585 return $self->{user
};
588 # read/update list of active workers
589 # we move all finished tasks to the archive index,
590 # but keep aktive and most recent task in the active file.
591 # $nocheck ... consider $new_upid still running (avoid that
592 # we try to read the reult to early.
594 my ($new_upid, $nocheck) = @_;
596 my $lkfn = "/var/log/pve/tasks/.active.lock";
602 my $tasklist = PVE
::INotify
::read_file
('active');
606 my $thash = {}; # only list task once
608 my $check_task = sub {
609 my ($task, $running) = @_;
611 if ($running || PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
})) {
617 delete $task->{pstart
};
620 foreach my $task (@$tasklist) {
621 my $upid = $task->{upid
};
622 next if $thash->{$upid};
623 $thash->{$upid} = $task;
627 if ($new_upid && !(my $task = $thash->{$new_upid})) {
628 $task = PVE
::Tools
::upid_decode
($new_upid);
629 $task->{upid
} = $new_upid;
630 $thash->{$new_upid} = $task;
631 &$check_task($task, $nocheck);
635 @ta = sort { $b->{starttime
} cmp $a->{starttime
} } @ta;
637 my $save = defined($new_upid);
639 foreach my $task (@ta) {
640 next if $task->{endtime
};
641 $task->{endtime
} = time();
642 $task->{status
} = PVE
::Tools
::upid_read_status
($task->{upid
});
648 foreach my $task (@ta) {
649 if (!$task->{saved
}) {
650 $archive .= sprintf("$task->{upid} %08X $task->{status}\n", $task->{endtime
});
659 my $filename = "/var/log/pve/tasks/index";
661 my $fh = IO
::File-
>new($filename, '>>', 0644) ||
662 die "unable to open file '$filename' - $!\n";
663 PVE
::Tools
::safe_print
($filename, $fh, $archive);
666 die "unable to close file '$filename' - $!\n";
671 foreach my $task (@arlist) { # mark as not saved
675 my $maxsize = 50000; # about 1000 entries
676 if ($size > $maxsize) {
677 rename($filename, "$filename.1");
681 # we try to reduce the amount of data
682 # list all running tasks and task and a few others
683 # try to limit to 25 tasks
685 my $max = 25 - scalar(@$tlist);
686 foreach my $task (@ta) {
692 PVE
::INotify
::write_file
('active', $tlist) if $save;
697 my $res = PVE
::Tools
::lock_file
($lkfn, $timeout, $code);
703 my $kill_process_group = sub {
704 my ($pid, $pstart) = @_;
706 # send kill to process group (negative pid)
709 # always send signal to all pgrp members
710 kill(15, $kpid); # send TERM signal
712 # give max 5 seconds to shut down
713 for (my $i = 0; $i < 5; $i++) {
714 return if !PVE
::ProcFSTools
::check_process_running
($pid, $pstart);
723 my ($upid, $killit) = @_;
725 my $task = PVE
::Tools
::upid_decode
($upid);
727 my $running = PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
});
729 return 0 if !$running;
732 &$kill_process_group($task->{pid
});
739 # start long running workers
740 # STDIN is redirected to /dev/null
741 # STDOUT,STDERR are redirected to the filename returned by upid_decode
742 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
744 my ($self, $dtype, $id, $user, $function) = @_;
746 $dtype = 'unknown' if !defined ($dtype);
747 $id = '' if !defined ($id);
749 $user = 'root@pve' if !defined ($user);
751 my $sync = $self->{type
} eq 'cli' ?
1 : 0;
756 local $SIG{TERM
} = 'IGNORE';
758 my $starttime = time ();
760 my @psync = POSIX
::pipe();
761 my @csync = POSIX
::pipe();
763 my $node = $self->{nodename
};
766 die "unable to fork worker - $!" if !defined($cpid);
768 my $workerpuid = $cpid ?
$cpid : $$;
770 my $pstart = PVE
::ProcFSTools
::read_proc_starttime
($workerpuid) ||
771 die "unable to read process start time";
773 my $upid = PVE
::Tools
::upid_encode
({
774 node
=> $node, pid
=> $workerpuid, pstart
=> $pstart,
775 starttime
=> $starttime, type
=> $dtype, id
=> $id, user
=> $user });
779 if (!$cpid) { # child
783 $SIG{INT
} = $SIG{QUIT
} = $SIG{TERM
} = sub { die "received interrupt\n"; };
785 $SIG{CHLD
} = $SIG{PIPE
} = 'DEFAULT';
787 # set sess/process group - we want to be able to kill the
788 # whole process group
791 POSIX
::close ($psync[0]);
792 POSIX
::close ($csync[1]);
794 $outfh = $sync ?
$psync[1] : undef;
797 PVE
::INotify
::inotify_close
();
799 if (my $atfork = $self->{atfork
}) {
803 # same algorythm as used inside SA
805 my $fd = fileno (STDIN
);
809 POSIX
::close(0) if $fd != 0;
811 die "unable to redirect STDIN - $!"
812 if !open(STDIN
, "</dev/null");
814 $outfh = PVE
::Tools
::upid_open
($upid);
819 $fd = fileno(STDOUT
);
821 POSIX
::close (1) if $fd != 1;
823 die "unable to redirect STDOUT - $!"
824 if !open(STDOUT
, ">&", $outfh);
826 STDOUT-
>autoflush (1);
828 # redirect STDERR to STDOUT
829 $fd = fileno (STDERR
);
831 POSIX
::close(2) if $fd != 2;
833 die "unable to redirect STDERR - $!"
834 if !open(STDERR
, ">&1");
836 STDERR-
>autoflush(1);
839 my $msg = "ERROR: $err";
840 POSIX
::write($psync[1], $msg, length ($msg));
841 POSIX
::close($psync[1]);
846 # sync with parent (signal that we are ready)
850 POSIX
::write($psync[1], $upid, length ($upid));
851 POSIX
::close($psync[1]);
855 # sync with parent (wait until parent is ready)
856 POSIX
::read($csync[0], $readbuf, 4096);
857 die "parent setup error\n" if $readbuf ne 'OK';
859 if ($self->{type
} eq 'ha') {
860 print "task started by HA resource agent\n";
862 eval { &$function($upid); };
868 print STDERR
"TASK ERROR: $err\n";
871 print STDERR
"TASK OK\n";
879 POSIX
::close ($psync[1]);
880 POSIX
::close ($csync[0]);
883 # sync with child (wait until child starts)
884 POSIX
::read($psync[0], $readbuf, 4096);
887 POSIX
::close($psync[0]);
888 &$register_worker($cpid, $user, $upid);
894 die "got no worker upid - start worker failed\n" if !$readbuf;
896 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
897 die "starting worker failed: $1\n";
900 if ($readbuf ne $upid) {
901 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
905 $outfh = PVE
::Tools
::upid_open
($upid);
912 POSIX
::write($csync[1], $msg, length ($msg));
913 POSIX
::close($csync[1]);
916 POSIX
::close($csync[1]);
917 kill(-9, $cpid); # make sure it gets killed
921 PVE
::Cluster
::log_msg
('info', $user, "starting task $upid");
923 my $tlist = active_workers
($upid, $sync);
924 PVE
::Cluster
::broadcast_tasklist
($tlist);
933 local $SIG{INT
} = local $SIG{QUIT
} = local $SIG{TERM
} = sub {
934 # always send signal to all pgrp members
936 if ($int_count < 3) {
937 kill(15, $kpid); # send TERM signal
939 kill(9, $kpid); # send KILL signal
943 local $SIG{PIPE
} = sub { die "broken pipe\n"; };
945 my $select = new IO
::Select
;
946 my $fh = IO
::Handle-
>new_from_fd($psync[0], 'r');
949 while ($select->count) {
950 my @handles = $select->can_read(1);
951 if (scalar(@handles)) {
952 my $count = sysread ($handles[0], $readbuf, 4096);
953 if (!defined ($count)) {
955 die "sync pipe read error: $err\n";
957 last if $count == 0; # eof
960 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
963 if ($data =~ m/^TASK OK$/) {
965 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
976 # some commands daemonize without closing stdout
977 last if !PVE
::ProcFSTools
::check_process_running
($cpid);
983 POSIX
::close($psync[0]);
985 if ($outbuf) { # just to be sure
988 print $outfh $outbuf;
994 print STDERR
"$err\n";
996 print $outfh "TASK ERROR: $err\n";
1000 &$kill_process_group($cpid, $pstart); # make sure it gets killed
1006 &$log_task_result($upid, $user, $res);
1009 return wantarray ?
($upid, $res) : $upid;