]>
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_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 foreach my $role (keys %{$data->{poolroles
}->{$path}}) {
138 $data->{roles
}->{$path} = [ @ra ];
141 foreach my $role (@ra) {
142 if (my $privset = $cfg->{roles
}->{$role}) {
143 foreach my $p (keys %$privset) {
148 $data->{privs
}->{$path} = $privs;
154 my ($self, $user, $path) = @_;
156 if ($user eq 'root@pam') { # root can do anything
157 return ('Administrator');
160 $user = PVE
::AccessControl
::verify_username
($user, 1);
163 my $cache = $self->{aclcache
};
164 $cache->{$user} = {} if !$cache->{$user};
166 my $acl = $cache->{$user};
168 my $roles = $acl->{roles
}->{$path};
169 return @$roles if $roles;
171 &$compile_acl_path($self, $user, $path);
172 $roles = $acl->{roles
}->{$path} || [];
177 my ($self, $user, $path) = @_;
179 if ($user eq 'root@pam') { # root can do anything
180 my $cfg = $self->{user_cfg
};
181 return $cfg->{roles
}->{'Administrator'};
184 $user = PVE
::AccessControl
::verify_username
($user, 1);
187 my $cache = $self->{aclcache
};
188 $cache->{$user} = {} if !$cache->{$user};
190 my $acl = $cache->{$user};
192 my $perm = $acl->{privs
}->{$path};
193 return $perm if $perm;
195 return &$compile_acl_path($self, $user, $path);
199 my ($self, $user, $path, $privs, $noerr) = @_;
201 my $perm = $self->permissions($user, $path);
203 foreach my $priv (@$privs) {
204 PVE
::AccessControl
::verify_privname
($priv);
205 if (!$perm->{$priv}) {
206 return undef if $noerr;
207 raise_perm_exc
("$path, $priv");
215 my ($self, $user, $path, $privs, $noerr) = @_;
217 my $perm = $self->permissions($user, $path);
218 syslog
("info", "check_any $user $path " . join(" ", keys %$perm));
220 foreach my $priv (@$privs) {
221 PVE
::AccessControl
::verify_privname
($priv);
222 if ($perm->{$priv}) {
230 return undef if $noerr;
232 raise_perm_exc
("$path, " . join("|", @$privs));
235 sub check_user_enabled
{
236 my ($self, $user, $noerr) = @_;
238 my $cfg = $self->{user_cfg
};
239 return PVE
::AccessControl
::check_user_enabled
($cfg, $user, $noerr);
242 sub check_user_exist
{
243 my ($self, $user, $noerr) = @_;
245 my $cfg = $self->{user_cfg
};
246 return PVE
::AccessControl
::check_user_exist
($cfg, $user, $noerr);
249 sub is_group_member
{
250 my ($self, $group, $user) = @_;
252 my $cfg = $self->{user_cfg
};
254 return 0 if !$cfg->{groups
}->{$group};
256 return defined($cfg->{groups
}->{$group}->{users
}->{$user});
260 my ($self, $user, $privs, $any) = @_;
262 my $cfg = $self->{user_cfg
};
265 foreach my $group (keys %{$cfg->{groups
}}) {
266 my $path = "/access/groups/$group";
268 if ($self->check_any($user, $path, $privs, 1)) {
269 $groups->{$group} = $cfg->{groups
}->{$group};
272 if ($self->check($user, $path, $privs, 1)) {
273 $groups->{$group} = $cfg->{groups
}->{$group};
281 sub group_member_join
{
282 my ($self, $grouplist) = @_;
286 my $cfg = $self->{user_cfg
};
287 foreach my $group (@$grouplist) {
288 my $data = $cfg->{groups
}->{$group};
290 foreach my $user (keys %{$data->{users
}}) {
298 sub exec_api2_perm_check
{
299 my ($self, $check, $username, $param, $noerr) = @_;
301 # syslog("info", "CHECK " . join(', ', @$check));
304 my $test = $check->[$ind++];
305 die "no permission test specified" if !$test;
307 if ($test eq 'and') {
308 while (my $subcheck = $check->[$ind++]) {
309 $self->exec_api2_perm_check($subcheck, $username, $param);
312 } elsif ($test eq 'or') {
313 while (my $subcheck = $check->[$ind++]) {
314 return 1 if $self->exec_api2_perm_check($subcheck, $username, $param, 1);
318 } elsif ($test eq 'perm') {
319 my ($t, $tmplpath, $privs, %options) = @$check;
320 my $any = $options{any
};
321 die "missing parameters" if !($tmplpath && $privs);
322 my $path = PVE
::Tools
::template_replace
($tmplpath, $param);
324 return $self->check_any($username, $path, $privs, $noerr);
326 return $self->check($username, $path, $privs, $noerr);
328 } elsif ($test eq 'userid-group') {
329 my $userid = $param->{userid
};
330 my ($t, $privs, %options) = @$check;
331 return if !$options{groups_param
} && !$self->check_user_exist($userid, $noerr);
332 if (!$self->check_any($username, "/access", $privs, 1)) {
333 my $groups = $self->filter_groups($username, $privs, 1);
334 if ($options{groups_param
}) {
335 my @group_param = PVE
::Tools
::split_list
($param->{groups
});
336 raise_perm_exc
("/access, " . join("|", @$privs)) if !scalar(@group_param);
337 foreach my $pg (@group_param) {
338 raise_perm_exc
("/access/groups/$pg, " . join("|", @$privs))
342 my $allowed_users = $self->group_member_join([keys %$groups]);
343 if (!$allowed_users->{$userid}) {
350 } elsif ($test eq 'userid-param') {
351 my $userid = $param->{userid
};
352 return if !$self->check_user_exist($userid, $noerr);
353 my ($t, $subtest) = @$check;
354 die "missing parameters" if !$subtest;
355 if ($subtest eq 'self') {
356 return 1 if $username eq 'userid';
360 die "unknown userid-param test";
363 die "unknown permission test";
367 sub check_api2_permissions
{
368 my ($self, $perm, $username, $param) = @_;
370 return 1 if !$username && $perm->{user
} eq 'world';
372 raise_perm_exc
("user != null") if !$username;
374 return 1 if $username eq 'root@pam';
376 raise_perm_exc
('user != root@pam') if !$perm;
378 return 1 if $perm->{user
} && $perm->{user
} eq 'all';
380 return $self->exec_api2_perm_check($perm->{check
}, $username, $param)
386 # initialize environment - must be called once at program startup
388 my ($class, $type, %params) = @_;
390 $class = ref($class) || $class;
392 die "already initialized" if $pve_env;
394 die "unknown environment type" if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
396 $SIG{CHLD
} = $worker_reaper;
399 # cli ... command started fron command line
400 # pub ... access from public server (apache)
401 # priv ... access from private server (pvedaemon)
402 # ha ... access from HA resource manager agent (rgmanager)
413 foreach my $p (keys %params) {
414 if ($p eq 'atfork') {
415 $self->{$p} = $params{$p};
417 die "unknown option '$p'";
423 my ($sysname, $nodename) = POSIX
::uname
();
425 $nodename =~ s/\..*$//; # strip domain part, if any
427 $self->{nodename
} = $nodename;
435 die "not initialized" if !$pve_env;
441 my ($self, $enable_upload) = @_;
443 if ($self->{request_rec
}) {
445 if ($enable_upload) {
446 $cgi = CGI-
>new($self->{request_rec
});
448 # disable upload using empty upload_hook
449 $cgi = CGI-
>new($self->{request_rec
}, sub {}, undef, 0);
452 my $params = $cgi->Vars();
453 return PVE
::Tools
::decode_utf8_parameters
($params);
454 } elsif ($self->{params
}) {
455 return $self->{params
};
457 die "no parameters registered";
461 sub get_upload_info
{
462 my ($self, $param) = @_;
464 my $cgi = $self->{cgi
};
465 die "CGI not initialized" if !$cgi;
467 my $pd = $cgi->param($param);
468 die "unable to get cgi parameter info\n" if !$pd;
469 my $info = $cgi->uploadInfo($pd);
470 die "unable to get cgi upload info\n" if !$info;
472 my $res = { %$info };
474 my $tmpfilename = $cgi->tmpFileName($pd);
475 die "unable to get cgi upload file name\n" if !$tmpfilename;
476 $res->{tmpfilename
} = $tmpfilename;
478 #my $hndl = $cgi->upload($param);
479 #die "unable to get cgi upload handle\n" if !$hndl;
480 #$res->{handle} = $hndl->handle;
485 # init_request - must be called before each RPC request
487 my ($self, %params) = @_;
489 PVE
::Cluster
::cfs_update
();
491 $self->{result_attributes
} = {};
493 my $userconfig; # we use this for regression tests
494 foreach my $p (keys %params) {
495 if ($p eq 'userconfig') {
496 $userconfig = $params{$p};
497 } elsif ($p eq 'request_rec') {
498 # pass Apache2::RequestRec
499 $self->{request_rec
} = $params{$p};
500 } elsif ($p eq 'params') {
501 $self->{params
} = $params{$p};
503 die "unknown parameter '$p'";
508 $self->{aclcache
} = {};
510 my $ucdata = PVE
::Tools
::file_get_contents
($userconfig);
511 my $cfg = PVE
::AccessControl
::parse_user_config
($userconfig, $ucdata);
512 $self->{user_cfg
} = $cfg;
515 my $ucvers = PVE
::Cluster
::cfs_file_version
('user.cfg');
516 if (!$self->{aclcache
} || !defined($self->{aclversion
}) ||
517 !defined($ucvers) || ($ucvers ne $self->{aclversion
})) {
518 $self->{aclversion
} = $ucvers;
519 my $cfg = PVE
::Cluster
::cfs_read_file
('user.cfg');
520 $self->{user_cfg
} = $cfg;
525 $self->{user_cfg
} = {};
526 die "Unable to load access control list: $err";
531 my ($self, $ip) = @_;
533 $self->{client_ip
} = $ip;
539 return $self->{client_ip
};
542 sub set_result_attrib
{
543 my ($self, $key, $value) = @_;
545 $self->{result_attributes
}->{$key} = $value;
548 sub get_result_attrib
{
549 my ($self, $key) = @_;
551 return $self->{result_attributes
}->{$key};
555 my ($self, $lang) = @_;
557 # fixme: initialize I18N
559 $self->{language
} = $lang;
565 return $self->{language
};
569 my ($self, $user) = @_;
573 $self->{user
} = $user;
579 die "user name not set\n" if !$self->{user
};
581 return $self->{user
};
584 # read/update list of active workers
585 # we move all finished tasks to the archive index,
586 # but keep aktive and most recent task in the active file.
587 # $nocheck ... consider $new_upid still running (avoid that
588 # we try to read the reult to early.
590 my ($new_upid, $nocheck) = @_;
592 my $lkfn = "/var/log/pve/tasks/.active.lock";
598 my $tasklist = PVE
::INotify
::read_file
('active');
602 my $thash = {}; # only list task once
604 my $check_task = sub {
605 my ($task, $running) = @_;
607 if ($running || PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
})) {
613 delete $task->{pstart
};
616 foreach my $task (@$tasklist) {
617 my $upid = $task->{upid
};
618 next if $thash->{$upid};
619 $thash->{$upid} = $task;
623 if ($new_upid && !(my $task = $thash->{$new_upid})) {
624 $task = PVE
::Tools
::upid_decode
($new_upid);
625 $task->{upid
} = $new_upid;
626 $thash->{$new_upid} = $task;
627 &$check_task($task, $nocheck);
631 @ta = sort { $b->{starttime
} cmp $a->{starttime
} } @ta;
633 my $save = defined($new_upid);
635 foreach my $task (@ta) {
636 next if $task->{endtime
};
637 $task->{endtime
} = time();
638 $task->{status
} = PVE
::Tools
::upid_read_status
($task->{upid
});
644 foreach my $task (@ta) {
645 if (!$task->{saved
}) {
646 $archive .= sprintf("$task->{upid} %08X $task->{status}\n", $task->{endtime
});
655 my $filename = "/var/log/pve/tasks/index";
657 my $fh = IO
::File-
>new($filename, '>>', 0644) ||
658 die "unable to open file '$filename' - $!\n";
659 PVE
::Tools
::safe_print
($filename, $fh, $archive);
662 die "unable to close file '$filename' - $!\n";
667 foreach my $task (@arlist) { # mark as not saved
671 my $maxsize = 50000; # about 1000 entries
672 if ($size > $maxsize) {
673 rename($filename, "$filename.1");
677 # we try to reduce the amount of data
678 # list all running tasks and task and a few others
679 # try to limit to 25 tasks
681 my $max = 25 - scalar(@$tlist);
682 foreach my $task (@ta) {
688 PVE
::INotify
::write_file
('active', $tlist) if $save;
693 my $res = PVE
::Tools
::lock_file
($lkfn, $timeout, $code);
699 my $kill_process_group = sub {
700 my ($pid, $pstart) = @_;
702 # send kill to process group (negative pid)
705 # always send signal to all pgrp members
706 kill(15, $kpid); # send TERM signal
708 # give max 5 seconds to shut down
709 for (my $i = 0; $i < 5; $i++) {
710 return if !PVE
::ProcFSTools
::check_process_running
($pid, $pstart);
719 my ($upid, $killit) = @_;
721 my $task = PVE
::Tools
::upid_decode
($upid);
723 my $running = PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
});
725 return 0 if !$running;
728 &$kill_process_group($task->{pid
});
735 # start long running workers
736 # STDIN is redirected to /dev/null
737 # STDOUT,STDERR are redirected to the filename returned by upid_decode
738 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
740 my ($self, $dtype, $id, $user, $function) = @_;
742 $dtype = 'unknown' if !defined ($dtype);
743 $id = '' if !defined ($id);
745 $user = 'root@pve' if !defined ($user);
747 my $sync = $self->{type
} eq 'cli' ?
1 : 0;
752 local $SIG{TERM
} = 'IGNORE';
754 my $starttime = time ();
756 my @psync = POSIX
::pipe();
757 my @csync = POSIX
::pipe();
759 my $node = $self->{nodename
};
762 die "unable to fork worker - $!" if !defined($cpid);
764 my $workerpuid = $cpid ?
$cpid : $$;
766 my $pstart = PVE
::ProcFSTools
::read_proc_starttime
($workerpuid) ||
767 die "unable to read process start time";
769 my $upid = PVE
::Tools
::upid_encode
({
770 node
=> $node, pid
=> $workerpuid, pstart
=> $pstart,
771 starttime
=> $starttime, type
=> $dtype, id
=> $id, user
=> $user });
775 if (!$cpid) { # child
779 $SIG{INT
} = $SIG{QUIT
} = $SIG{TERM
} = sub { die "received interrupt\n"; };
781 $SIG{CHLD
} = $SIG{PIPE
} = 'DEFAULT';
783 # set sess/process group - we want to be able to kill the
784 # whole process group
787 POSIX
::close ($psync[0]);
788 POSIX
::close ($csync[1]);
790 $outfh = $sync ?
$psync[1] : undef;
793 PVE
::INotify
::inotify_close
();
795 if (my $atfork = $self->{atfork
}) {
799 # same algorythm as used inside SA
801 my $fd = fileno (STDIN
);
805 POSIX
::close(0) if $fd != 0;
807 die "unable to redirect STDIN - $!"
808 if !open(STDIN
, "</dev/null");
810 $outfh = PVE
::Tools
::upid_open
($upid);
815 $fd = fileno(STDOUT
);
817 POSIX
::close (1) if $fd != 1;
819 die "unable to redirect STDOUT - $!"
820 if !open(STDOUT
, ">&", $outfh);
822 STDOUT-
>autoflush (1);
824 # redirect STDERR to STDOUT
825 $fd = fileno (STDERR
);
827 POSIX
::close(2) if $fd != 2;
829 die "unable to redirect STDERR - $!"
830 if !open(STDERR
, ">&1");
832 STDERR-
>autoflush(1);
835 my $msg = "ERROR: $err";
836 POSIX
::write($psync[1], $msg, length ($msg));
837 POSIX
::close($psync[1]);
842 # sync with parent (signal that we are ready)
846 POSIX
::write($psync[1], $upid, length ($upid));
847 POSIX
::close($psync[1]);
851 # sync with parent (wait until parent is ready)
852 POSIX
::read($csync[0], $readbuf, 4096);
853 die "parent setup error\n" if $readbuf ne 'OK';
855 if ($self->{type
} eq 'ha') {
856 print "task started by HA resource agent\n";
858 eval { &$function($upid); };
864 print STDERR
"TASK ERROR: $err\n";
867 print STDERR
"TASK OK\n";
875 POSIX
::close ($psync[1]);
876 POSIX
::close ($csync[0]);
879 # sync with child (wait until child starts)
880 POSIX
::read($psync[0], $readbuf, 4096);
883 POSIX
::close($psync[0]);
884 &$register_worker($cpid, $user, $upid);
890 die "got no worker upid - start worker failed\n" if !$readbuf;
892 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
893 die "starting worker failed: $1\n";
896 if ($readbuf ne $upid) {
897 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
901 $outfh = PVE
::Tools
::upid_open
($upid);
908 POSIX
::write($csync[1], $msg, length ($msg));
909 POSIX
::close($csync[1]);
912 POSIX
::close($csync[1]);
913 kill(-9, $cpid); # make sure it gets killed
917 PVE
::Cluster
::log_msg
('info', $user, "starting task $upid");
919 my $tlist = active_workers
($upid, $sync);
920 PVE
::Cluster
::broadcast_tasklist
($tlist);
929 local $SIG{INT
} = local $SIG{QUIT
} = local $SIG{TERM
} = sub {
930 # always send signal to all pgrp members
932 if ($int_count < 3) {
933 kill(15, $kpid); # send TERM signal
935 kill(9, $kpid); # send KILL signal
939 local $SIG{PIPE
} = sub { die "broken pipe\n"; };
941 my $select = new IO
::Select
;
942 my $fh = IO
::Handle-
>new_from_fd($psync[0], 'r');
945 while ($select->count) {
946 my @handles = $select->can_read(1);
947 if (scalar(@handles)) {
948 my $count = sysread ($handles[0], $readbuf, 4096);
949 if (!defined ($count)) {
951 die "sync pipe read error: $err\n";
953 last if $count == 0; # eof
956 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
959 if ($data =~ m/^TASK OK$/) {
961 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
972 # some commands daemonize without closing stdout
973 last if !PVE
::ProcFSTools
::check_process_running
($cpid);
979 POSIX
::close($psync[0]);
981 if ($outbuf) { # just to be sure
984 print $outfh $outbuf;
990 print STDERR
"$err\n";
992 print $outfh "TASK ERROR: $err\n";
996 &$kill_process_group($cpid, $pstart); # make sure it gets killed
1002 &$log_task_result($upid, $user, $res);
1005 return wantarray ?
($upid, $res) : $upid;