]>
git.proxmox.com Git - pve-access-control.git/blob - PVE/RPCEnvironment.pm
0b8147e4cc1ad285670b434e8e38a0cb5a2d2653
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 check_perm_modify
{
303 my ($self, $username, $path, $noerr) = @_;
305 return $self->check($username, '/access', [ 'Permissions.Modify' ], $noerr) if !$path;
307 my $testperms = [ 'Permissions.Modify' ];
308 if ($path =~ m
|^/storage/.+$|) {
309 push @$testperms, 'Datastore.Allocate';
310 } elsif ($path =~ m
|^/vms/.+$|) {
311 push @$testperms, 'VM.Allocate';
314 return $self->check_any($username, $path, $testperms, $noerr);
317 sub exec_api2_perm_check
{
318 my ($self, $check, $username, $param, $noerr) = @_;
320 # syslog("info", "CHECK " . join(', ', @$check));
323 my $test = $check->[$ind++];
324 die "no permission test specified" if !$test;
326 if ($test eq 'and') {
327 while (my $subcheck = $check->[$ind++]) {
328 $self->exec_api2_perm_check($subcheck, $username, $param);
331 } elsif ($test eq 'or') {
332 while (my $subcheck = $check->[$ind++]) {
333 return 1 if $self->exec_api2_perm_check($subcheck, $username, $param, 1);
337 } elsif ($test eq 'perm') {
338 my ($t, $tmplpath, $privs, %options) = @$check;
339 my $any = $options{any
};
340 die "missing parameters" if !($tmplpath && $privs);
341 my $path = PVE
::Tools
::template_replace
($tmplpath, $param);
342 $path = PVE
::AccessControl
::normalize_path
($path);
344 return $self->check_any($username, $path, $privs, $noerr);
346 return $self->check($username, $path, $privs, $noerr);
348 } elsif ($test eq 'userid-group') {
349 my $userid = $param->{userid
};
350 my ($t, $privs, %options) = @$check;
351 return if !$options{groups_param
} && !$self->check_user_exist($userid, $noerr);
352 if (!$self->check_any($username, "/access", $privs, 1)) {
353 my $groups = $self->filter_groups($username, $privs, 1);
354 if ($options{groups_param
}) {
355 my @group_param = PVE
::Tools
::split_list
($param->{groups
});
356 raise_perm_exc
("/access, " . join("|", @$privs)) if !scalar(@group_param);
357 foreach my $pg (@group_param) {
358 raise_perm_exc
("/access/groups/$pg, " . join("|", @$privs))
362 my $allowed_users = $self->group_member_join([keys %$groups]);
363 if (!$allowed_users->{$userid}) {
370 } elsif ($test eq 'userid-param') {
371 my $userid = $param->{userid
};
372 return if !$self->check_user_exist($userid, $noerr);
373 my ($t, $subtest) = @$check;
374 die "missing parameters" if !$subtest;
375 if ($subtest eq 'self') {
376 return 1 if $username eq 'userid';
380 die "unknown userid-param test";
382 } elsif ($test eq 'perm-modify') {
383 my ($t, $tmplpath) = @$check;
384 my $path = PVE
::Tools
::template_replace
($tmplpath, $param);
385 $path = PVE
::AccessControl
::normalize_path
($path);
386 return $self->check_perm_modify($username, $path, $noerr);
388 die "unknown permission test";
392 sub check_api2_permissions
{
393 my ($self, $perm, $username, $param) = @_;
395 return 1 if !$username && $perm->{user
} eq 'world';
397 raise_perm_exc
("user != null") if !$username;
399 return 1 if $username eq 'root@pam';
401 raise_perm_exc
('user != root@pam') if !$perm;
403 return 1 if $perm->{user
} && $perm->{user
} eq 'all';
405 return $self->exec_api2_perm_check($perm->{check
}, $username, $param)
411 # initialize environment - must be called once at program startup
413 my ($class, $type, %params) = @_;
415 $class = ref($class) || $class;
417 die "already initialized" if $pve_env;
419 die "unknown environment type" if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
421 $SIG{CHLD
} = $worker_reaper;
424 # cli ... command started fron command line
425 # pub ... access from public server (apache)
426 # priv ... access from private server (pvedaemon)
427 # ha ... access from HA resource manager agent (rgmanager)
438 foreach my $p (keys %params) {
439 if ($p eq 'atfork') {
440 $self->{$p} = $params{$p};
442 die "unknown option '$p'";
448 my ($sysname, $nodename) = POSIX
::uname
();
450 $nodename =~ s/\..*$//; # strip domain part, if any
452 $self->{nodename
} = $nodename;
460 die "not initialized" if !$pve_env;
466 my ($self, $enable_upload) = @_;
468 if ($self->{request_rec
}) {
470 if ($enable_upload) {
471 $cgi = CGI-
>new($self->{request_rec
});
473 # disable upload using empty upload_hook
474 $cgi = CGI-
>new($self->{request_rec
}, sub {}, undef, 0);
477 my $params = $cgi->Vars();
478 return PVE
::Tools
::decode_utf8_parameters
($params);
479 } elsif ($self->{params
}) {
480 return $self->{params
};
482 die "no parameters registered";
486 sub get_upload_info
{
487 my ($self, $param) = @_;
489 my $cgi = $self->{cgi
};
490 die "CGI not initialized" if !$cgi;
492 my $pd = $cgi->param($param);
493 die "unable to get cgi parameter info\n" if !$pd;
494 my $info = $cgi->uploadInfo($pd);
495 die "unable to get cgi upload info\n" if !$info;
497 my $res = { %$info };
499 my $tmpfilename = $cgi->tmpFileName($pd);
500 die "unable to get cgi upload file name\n" if !$tmpfilename;
501 $res->{tmpfilename
} = $tmpfilename;
503 #my $hndl = $cgi->upload($param);
504 #die "unable to get cgi upload handle\n" if !$hndl;
505 #$res->{handle} = $hndl->handle;
510 # init_request - must be called before each RPC request
512 my ($self, %params) = @_;
514 PVE
::Cluster
::cfs_update
();
516 $self->{result_attributes
} = {};
518 my $userconfig; # we use this for regression tests
519 foreach my $p (keys %params) {
520 if ($p eq 'userconfig') {
521 $userconfig = $params{$p};
522 } elsif ($p eq 'request_rec') {
523 # pass Apache2::RequestRec
524 $self->{request_rec
} = $params{$p};
525 } elsif ($p eq 'params') {
526 $self->{params
} = $params{$p};
528 die "unknown parameter '$p'";
533 $self->{aclcache
} = {};
535 my $ucdata = PVE
::Tools
::file_get_contents
($userconfig);
536 my $cfg = PVE
::AccessControl
::parse_user_config
($userconfig, $ucdata);
537 $self->{user_cfg
} = $cfg;
540 my $ucvers = PVE
::Cluster
::cfs_file_version
('user.cfg');
541 if (!$self->{aclcache
} || !defined($self->{aclversion
}) ||
542 !defined($ucvers) || ($ucvers ne $self->{aclversion
})) {
543 $self->{aclversion
} = $ucvers;
544 my $cfg = PVE
::Cluster
::cfs_read_file
('user.cfg');
545 $self->{user_cfg
} = $cfg;
550 $self->{user_cfg
} = {};
551 die "Unable to load access control list: $err";
556 my ($self, $ip) = @_;
558 $self->{client_ip
} = $ip;
564 return $self->{client_ip
};
567 sub set_result_attrib
{
568 my ($self, $key, $value) = @_;
570 $self->{result_attributes
}->{$key} = $value;
573 sub get_result_attrib
{
574 my ($self, $key) = @_;
576 return $self->{result_attributes
}->{$key};
580 my ($self, $lang) = @_;
582 # fixme: initialize I18N
584 $self->{language
} = $lang;
590 return $self->{language
};
594 my ($self, $user) = @_;
598 $self->{user
} = $user;
604 die "user name not set\n" if !$self->{user
};
606 return $self->{user
};
609 # read/update list of active workers
610 # we move all finished tasks to the archive index,
611 # but keep aktive and most recent task in the active file.
612 # $nocheck ... consider $new_upid still running (avoid that
613 # we try to read the reult to early.
615 my ($new_upid, $nocheck) = @_;
617 my $lkfn = "/var/log/pve/tasks/.active.lock";
623 my $tasklist = PVE
::INotify
::read_file
('active');
627 my $thash = {}; # only list task once
629 my $check_task = sub {
630 my ($task, $running) = @_;
632 if ($running || PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
})) {
638 delete $task->{pstart
};
641 foreach my $task (@$tasklist) {
642 my $upid = $task->{upid
};
643 next if $thash->{$upid};
644 $thash->{$upid} = $task;
648 if ($new_upid && !(my $task = $thash->{$new_upid})) {
649 $task = PVE
::Tools
::upid_decode
($new_upid);
650 $task->{upid
} = $new_upid;
651 $thash->{$new_upid} = $task;
652 &$check_task($task, $nocheck);
656 @ta = sort { $b->{starttime
} cmp $a->{starttime
} } @ta;
658 my $save = defined($new_upid);
660 foreach my $task (@ta) {
661 next if $task->{endtime
};
662 $task->{endtime
} = time();
663 $task->{status
} = PVE
::Tools
::upid_read_status
($task->{upid
});
669 foreach my $task (@ta) {
670 if (!$task->{saved
}) {
671 $archive .= sprintf("$task->{upid} %08X $task->{status}\n", $task->{endtime
});
680 my $filename = "/var/log/pve/tasks/index";
682 my $fh = IO
::File-
>new($filename, '>>', 0644) ||
683 die "unable to open file '$filename' - $!\n";
684 PVE
::Tools
::safe_print
($filename, $fh, $archive);
687 die "unable to close file '$filename' - $!\n";
692 foreach my $task (@arlist) { # mark as not saved
696 my $maxsize = 50000; # about 1000 entries
697 if ($size > $maxsize) {
698 rename($filename, "$filename.1");
702 # we try to reduce the amount of data
703 # list all running tasks and task and a few others
704 # try to limit to 25 tasks
706 my $max = 25 - scalar(@$tlist);
707 foreach my $task (@ta) {
713 PVE
::INotify
::write_file
('active', $tlist) if $save;
718 my $res = PVE
::Tools
::lock_file
($lkfn, $timeout, $code);
724 my $kill_process_group = sub {
725 my ($pid, $pstart) = @_;
727 # send kill to process group (negative pid)
730 # always send signal to all pgrp members
731 kill(15, $kpid); # send TERM signal
733 # give max 5 seconds to shut down
734 for (my $i = 0; $i < 5; $i++) {
735 return if !PVE
::ProcFSTools
::check_process_running
($pid, $pstart);
744 my ($upid, $killit) = @_;
746 my $task = PVE
::Tools
::upid_decode
($upid);
748 my $running = PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
});
750 return 0 if !$running;
753 &$kill_process_group($task->{pid
});
760 # start long running workers
761 # STDIN is redirected to /dev/null
762 # STDOUT,STDERR are redirected to the filename returned by upid_decode
763 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
765 my ($self, $dtype, $id, $user, $function) = @_;
767 $dtype = 'unknown' if !defined ($dtype);
768 $id = '' if !defined ($id);
770 $user = 'root@pve' if !defined ($user);
772 my $sync = $self->{type
} eq 'cli' ?
1 : 0;
777 local $SIG{TERM
} = 'IGNORE';
779 my $starttime = time ();
781 my @psync = POSIX
::pipe();
782 my @csync = POSIX
::pipe();
784 my $node = $self->{nodename
};
787 die "unable to fork worker - $!" if !defined($cpid);
789 my $workerpuid = $cpid ?
$cpid : $$;
791 my $pstart = PVE
::ProcFSTools
::read_proc_starttime
($workerpuid) ||
792 die "unable to read process start time";
794 my $upid = PVE
::Tools
::upid_encode
({
795 node
=> $node, pid
=> $workerpuid, pstart
=> $pstart,
796 starttime
=> $starttime, type
=> $dtype, id
=> $id, user
=> $user });
800 if (!$cpid) { # child
804 $SIG{INT
} = $SIG{QUIT
} = $SIG{TERM
} = sub { die "received interrupt\n"; };
806 $SIG{CHLD
} = $SIG{PIPE
} = 'DEFAULT';
808 # set sess/process group - we want to be able to kill the
809 # whole process group
812 POSIX
::close ($psync[0]);
813 POSIX
::close ($csync[1]);
815 $outfh = $sync ?
$psync[1] : undef;
818 PVE
::INotify
::inotify_close
();
820 if (my $atfork = $self->{atfork
}) {
824 # same algorythm as used inside SA
826 my $fd = fileno (STDIN
);
830 POSIX
::close(0) if $fd != 0;
832 die "unable to redirect STDIN - $!"
833 if !open(STDIN
, "</dev/null");
835 $outfh = PVE
::Tools
::upid_open
($upid);
840 $fd = fileno(STDOUT
);
842 POSIX
::close (1) if $fd != 1;
844 die "unable to redirect STDOUT - $!"
845 if !open(STDOUT
, ">&", $outfh);
847 STDOUT-
>autoflush (1);
849 # redirect STDERR to STDOUT
850 $fd = fileno (STDERR
);
852 POSIX
::close(2) if $fd != 2;
854 die "unable to redirect STDERR - $!"
855 if !open(STDERR
, ">&1");
857 STDERR-
>autoflush(1);
860 my $msg = "ERROR: $err";
861 POSIX
::write($psync[1], $msg, length ($msg));
862 POSIX
::close($psync[1]);
867 # sync with parent (signal that we are ready)
871 POSIX
::write($psync[1], $upid, length ($upid));
872 POSIX
::close($psync[1]);
876 # sync with parent (wait until parent is ready)
877 POSIX
::read($csync[0], $readbuf, 4096);
878 die "parent setup error\n" if $readbuf ne 'OK';
880 if ($self->{type
} eq 'ha') {
881 print "task started by HA resource agent\n";
883 eval { &$function($upid); };
889 print STDERR
"TASK ERROR: $err\n";
892 print STDERR
"TASK OK\n";
900 POSIX
::close ($psync[1]);
901 POSIX
::close ($csync[0]);
904 # sync with child (wait until child starts)
905 POSIX
::read($psync[0], $readbuf, 4096);
908 POSIX
::close($psync[0]);
909 &$register_worker($cpid, $user, $upid);
915 die "got no worker upid - start worker failed\n" if !$readbuf;
917 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
918 die "starting worker failed: $1\n";
921 if ($readbuf ne $upid) {
922 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
926 $outfh = PVE
::Tools
::upid_open
($upid);
933 POSIX
::write($csync[1], $msg, length ($msg));
934 POSIX
::close($csync[1]);
937 POSIX
::close($csync[1]);
938 kill(-9, $cpid); # make sure it gets killed
942 PVE
::Cluster
::log_msg
('info', $user, "starting task $upid");
944 my $tlist = active_workers
($upid, $sync);
945 PVE
::Cluster
::broadcast_tasklist
($tlist);
954 local $SIG{INT
} = local $SIG{QUIT
} = local $SIG{TERM
} = sub {
955 # always send signal to all pgrp members
957 if ($int_count < 3) {
958 kill(15, $kpid); # send TERM signal
960 kill(9, $kpid); # send KILL signal
964 local $SIG{PIPE
} = sub { die "broken pipe\n"; };
966 my $select = new IO
::Select
;
967 my $fh = IO
::Handle-
>new_from_fd($psync[0], 'r');
970 while ($select->count) {
971 my @handles = $select->can_read(1);
972 if (scalar(@handles)) {
973 my $count = sysread ($handles[0], $readbuf, 4096);
974 if (!defined ($count)) {
976 die "sync pipe read error: $err\n";
978 last if $count == 0; # eof
981 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
984 if ($data =~ m/^TASK OK$/) {
986 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
997 # some commands daemonize without closing stdout
998 last if !PVE
::ProcFSTools
::check_process_running
($cpid);
1004 POSIX
::close($psync[0]);
1006 if ($outbuf) { # just to be sure
1009 print $outfh $outbuf;
1015 print STDERR
"$err\n";
1017 print $outfh "TASK ERROR: $err\n";
1021 &$kill_process_group($cpid, $pstart); # make sure it gets killed
1027 &$log_task_result($upid, $user, $res);
1030 return wantarray ?
($upid, $res) : $upid;