]>
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 sub exec_api2_perm_check
{
258 my ($self, $check, $username, $param, $noerr) = @_;
260 # syslog("info", "CHECK " . join(', ', @$check));
263 my $test = $check->[$ind++];
264 die "no permission test specified" if !$test;
266 if ($test eq 'and') {
267 while (my $subcheck = $check->[$ind++]) {
268 $self->exec_api2_perm_check($subcheck, $username, $param);
271 } elsif ($test eq 'or') {
272 while (my $subcheck = $check->[$ind++]) {
273 return 1 if $self->exec_api2_perm_check($subcheck, $username, $param, 1);
277 } elsif ($test eq 'perm') {
278 my ($t, $tmplpath, $privs, %options) = @$check;
279 my $any = $options{any
};
280 die "missing parameters" if !($tmplpath && $privs);
281 my $path = PVE
::Tools
::template_replace
($tmplpath, $param);
283 return $self->check_any($username, $path, $privs, $noerr);
285 return $self->check($username, $path, $privs, $noerr);
287 } elsif ($test eq 'userid-group') {
288 my $userid = $param->{userid
};
289 my ($t, $privs, %options) = @$check;
290 return if !$options{groups_param
} && !$self->check_user_exist($userid, $noerr);
291 if (!$self->check_any($username, "/access", $privs, 1)) {
292 my $groups = $self->filter_groups($username, $privs, 1);
293 if ($options{groups_param
}) {
294 my @group_param = PVE
::Tools
::split_list
($param->{groups
});
295 raise_perm_exc
("/access, " . join("|", @$privs)) if !scalar(@group_param);
296 foreach my $pg (@group_param) {
297 raise_perm_exc
("/access/groups/$pg, " . join("|", @$privs))
301 my $allowed_users = $self->group_member_join([keys %$groups]);
302 if (!$allowed_users->{$userid}) {
309 } elsif ($test eq 'userid-param') {
310 my $userid = $param->{userid
};
311 return if !$self->check_user_exist($userid, $noerr);
312 my ($t, $subtest) = @$check;
313 die "missing parameters" if !$subtest;
314 if ($subtest eq 'self') {
315 return 1 if $username eq 'userid';
319 die "unknown userid-param test";
322 die "unknown permission test";
326 sub check_api2_permissions
{
327 my ($self, $perm, $username, $param) = @_;
329 return 1 if !$username && $perm->{user
} eq 'world';
331 raise_perm_exc
("user != null") if !$username;
333 return 1 if $username eq 'root@pam';
335 raise_perm_exc
('user != root@pam') if !$perm;
337 return 1 if $perm->{user
} && $perm->{user
} eq 'all';
339 return $self->exec_api2_perm_check($perm->{check
}, $username, $param)
345 # initialize environment - must be called once at program startup
347 my ($class, $type, %params) = @_;
349 $class = ref($class) || $class;
351 die "already initialized" if $pve_env;
353 die "unknown environment type" if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
355 $SIG{CHLD
} = $worker_reaper;
358 # cli ... command started fron command line
359 # pub ... access from public server (apache)
360 # priv ... access from private server (pvedaemon)
361 # ha ... access from HA resource manager agent (rgmanager)
372 foreach my $p (keys %params) {
373 if ($p eq 'atfork') {
374 $self->{$p} = $params{$p};
376 die "unknown option '$p'";
382 my ($sysname, $nodename) = POSIX
::uname
();
384 $nodename =~ s/\..*$//; # strip domain part, if any
386 $self->{nodename
} = $nodename;
394 die "not initialized" if !$pve_env;
400 my ($self, $enable_upload) = @_;
402 if ($self->{request_rec
}) {
404 if ($enable_upload) {
405 $cgi = CGI-
>new($self->{request_rec
});
407 # disable upload using empty upload_hook
408 $cgi = CGI-
>new($self->{request_rec
}, sub {}, undef, 0);
411 my $params = $cgi->Vars();
412 return PVE
::Tools
::decode_utf8_parameters
($params);
413 } elsif ($self->{params
}) {
414 return $self->{params
};
416 die "no parameters registered";
420 sub get_upload_info
{
421 my ($self, $param) = @_;
423 my $cgi = $self->{cgi
};
424 die "CGI not initialized" if !$cgi;
426 my $pd = $cgi->param($param);
427 die "unable to get cgi parameter info\n" if !$pd;
428 my $info = $cgi->uploadInfo($pd);
429 die "unable to get cgi upload info\n" if !$info;
431 my $res = { %$info };
433 my $tmpfilename = $cgi->tmpFileName($pd);
434 die "unable to get cgi upload file name\n" if !$tmpfilename;
435 $res->{tmpfilename
} = $tmpfilename;
437 #my $hndl = $cgi->upload($param);
438 #die "unable to get cgi upload handle\n" if !$hndl;
439 #$res->{handle} = $hndl->handle;
444 # init_request - must be called before each RPC request
446 my ($self, %params) = @_;
448 PVE
::Cluster
::cfs_update
();
450 $self->{result_attributes
} = {};
452 my $userconfig; # we use this for regression tests
453 foreach my $p (keys %params) {
454 if ($p eq 'userconfig') {
455 $userconfig = $params{$p};
456 } elsif ($p eq 'request_rec') {
457 # pass Apache2::RequestRec
458 $self->{request_rec
} = $params{$p};
459 } elsif ($p eq 'params') {
460 $self->{params
} = $params{$p};
462 die "unknown parameter '$p'";
467 $self->{aclcache
} = {};
469 my $ucdata = PVE
::Tools
::file_get_contents
($userconfig);
470 my $cfg = PVE
::AccessControl
::parse_user_config
($userconfig, $ucdata);
471 $self->{user_cfg
} = $cfg;
473 my $ucvers = PVE
::Cluster
::cfs_file_version
('user.cfg');
474 if (!$self->{aclcache
} || !defined($self->{aclversion
}) ||
475 !defined($ucvers) || ($ucvers ne $self->{aclversion
})) {
476 $self->{aclversion
} = $ucvers;
477 my $cfg = PVE
::Cluster
::cfs_read_file
('user.cfg');
478 $self->{user_cfg
} = $cfg;
483 $self->{user_cfg
} = {};
484 die "Unable to load access control list: $err";
489 my ($self, $ip) = @_;
491 $self->{client_ip
} = $ip;
497 return $self->{client_ip
};
500 sub set_result_attrib
{
501 my ($self, $key, $value) = @_;
503 $self->{result_attributes
}->{$key} = $value;
506 sub get_result_attrib
{
507 my ($self, $key) = @_;
509 return $self->{result_attributes
}->{$key};
513 my ($self, $lang) = @_;
515 # fixme: initialize I18N
517 $self->{language
} = $lang;
523 return $self->{language
};
527 my ($self, $user) = @_;
531 $self->{user
} = $user;
537 die "user name not set\n" if !$self->{user
};
539 return $self->{user
};
542 # read/update list of active workers
543 # we move all finished tasks to the archive index,
544 # but keep aktive and most recent task in the active file.
545 # $nocheck ... consider $new_upid still running (avoid that
546 # we try to read the reult to early.
548 my ($new_upid, $nocheck) = @_;
550 my $lkfn = "/var/log/pve/tasks/.active.lock";
556 my $tasklist = PVE
::INotify
::read_file
('active');
560 my $thash = {}; # only list task once
562 my $check_task = sub {
563 my ($task, $running) = @_;
565 if ($running || PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
})) {
571 delete $task->{pstart
};
574 foreach my $task (@$tasklist) {
575 my $upid = $task->{upid
};
576 next if $thash->{$upid};
577 $thash->{$upid} = $task;
581 if ($new_upid && !(my $task = $thash->{$new_upid})) {
582 $task = PVE
::Tools
::upid_decode
($new_upid);
583 $task->{upid
} = $new_upid;
584 $thash->{$new_upid} = $task;
585 &$check_task($task, $nocheck);
589 @ta = sort { $b->{starttime
} cmp $a->{starttime
} } @ta;
591 my $save = defined($new_upid);
593 foreach my $task (@ta) {
594 next if $task->{endtime
};
595 $task->{endtime
} = time();
596 $task->{status
} = PVE
::Tools
::upid_read_status
($task->{upid
});
602 foreach my $task (@ta) {
603 if (!$task->{saved
}) {
604 $archive .= sprintf("$task->{upid} %08X $task->{status}\n", $task->{endtime
});
613 my $filename = "/var/log/pve/tasks/index";
615 my $fh = IO
::File-
>new($filename, '>>', 0644) ||
616 die "unable to open file '$filename' - $!\n";
617 PVE
::Tools
::safe_print
($filename, $fh, $archive);
620 die "unable to close file '$filename' - $!\n";
625 foreach my $task (@arlist) { # mark as not saved
629 my $maxsize = 50000; # about 1000 entries
630 if ($size > $maxsize) {
631 rename($filename, "$filename.1");
635 # we try to reduce the amount of data
636 # list all running tasks and task and a few others
637 # try to limit to 25 tasks
639 my $max = 25 - scalar(@$tlist);
640 foreach my $task (@ta) {
646 PVE
::INotify
::write_file
('active', $tlist) if $save;
651 my $res = PVE
::Tools
::lock_file
($lkfn, $timeout, $code);
657 my $kill_process_group = sub {
658 my ($pid, $pstart) = @_;
660 # send kill to process group (negative pid)
663 # always send signal to all pgrp members
664 kill(15, $kpid); # send TERM signal
666 # give max 5 seconds to shut down
667 for (my $i = 0; $i < 5; $i++) {
668 return if !PVE
::ProcFSTools
::check_process_running
($pid, $pstart);
677 my ($upid, $killit) = @_;
679 my $task = PVE
::Tools
::upid_decode
($upid);
681 my $running = PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
});
683 return 0 if !$running;
686 &$kill_process_group($task->{pid
});
693 # start long running workers
694 # STDIN is redirected to /dev/null
695 # STDOUT,STDERR are redirected to the filename returned by upid_decode
696 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
698 my ($self, $dtype, $id, $user, $function) = @_;
700 $dtype = 'unknown' if !defined ($dtype);
701 $id = '' if !defined ($id);
703 $user = 'root@pve' if !defined ($user);
705 my $sync = $self->{type
} eq 'cli' ?
1 : 0;
710 local $SIG{TERM
} = 'IGNORE';
712 my $starttime = time ();
714 my @psync = POSIX
::pipe();
715 my @csync = POSIX
::pipe();
717 my $node = $self->{nodename
};
720 die "unable to fork worker - $!" if !defined($cpid);
722 my $workerpuid = $cpid ?
$cpid : $$;
724 my $pstart = PVE
::ProcFSTools
::read_proc_starttime
($workerpuid) ||
725 die "unable to read process start time";
727 my $upid = PVE
::Tools
::upid_encode
({
728 node
=> $node, pid
=> $workerpuid, pstart
=> $pstart,
729 starttime
=> $starttime, type
=> $dtype, id
=> $id, user
=> $user });
733 if (!$cpid) { # child
737 $SIG{INT
} = $SIG{QUIT
} = $SIG{TERM
} = sub { die "received interrupt\n"; };
739 $SIG{CHLD
} = $SIG{PIPE
} = 'DEFAULT';
741 # set sess/process group - we want to be able to kill the
742 # whole process group
745 POSIX
::close ($psync[0]);
746 POSIX
::close ($csync[1]);
748 $outfh = $sync ?
$psync[1] : undef;
751 PVE
::INotify
::inotify_close
();
753 if (my $atfork = $self->{atfork
}) {
757 # same algorythm as used inside SA
759 my $fd = fileno (STDIN
);
763 POSIX
::close(0) if $fd != 0;
765 die "unable to redirect STDIN - $!"
766 if !open(STDIN
, "</dev/null");
768 $outfh = PVE
::Tools
::upid_open
($upid);
773 $fd = fileno(STDOUT
);
775 POSIX
::close (1) if $fd != 1;
777 die "unable to redirect STDOUT - $!"
778 if !open(STDOUT
, ">&", $outfh);
780 STDOUT-
>autoflush (1);
782 # redirect STDERR to STDOUT
783 $fd = fileno (STDERR
);
785 POSIX
::close(2) if $fd != 2;
787 die "unable to redirect STDERR - $!"
788 if !open(STDERR
, ">&1");
790 STDERR-
>autoflush(1);
793 my $msg = "ERROR: $err";
794 POSIX
::write($psync[1], $msg, length ($msg));
795 POSIX
::close($psync[1]);
800 # sync with parent (signal that we are ready)
804 POSIX
::write($psync[1], $upid, length ($upid));
805 POSIX
::close($psync[1]);
809 # sync with parent (wait until parent is ready)
810 POSIX
::read($csync[0], $readbuf, 4096);
811 die "parent setup error\n" if $readbuf ne 'OK';
813 if ($self->{type
} eq 'ha') {
814 print "task started by HA resource agent\n";
816 eval { &$function($upid); };
822 print STDERR
"TASK ERROR: $err\n";
825 print STDERR
"TASK OK\n";
833 POSIX
::close ($psync[1]);
834 POSIX
::close ($csync[0]);
837 # sync with child (wait until child starts)
838 POSIX
::read($psync[0], $readbuf, 4096);
841 POSIX
::close($psync[0]);
842 &$register_worker($cpid, $user, $upid);
848 die "got no worker upid - start worker failed\n" if !$readbuf;
850 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
851 die "starting worker failed: $1\n";
854 if ($readbuf ne $upid) {
855 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
859 $outfh = PVE
::Tools
::upid_open
($upid);
866 POSIX
::write($csync[1], $msg, length ($msg));
867 POSIX
::close($csync[1]);
870 POSIX
::close($csync[1]);
871 kill(-9, $cpid); # make sure it gets killed
875 PVE
::Cluster
::log_msg
('info', $user, "starting task $upid");
877 my $tlist = active_workers
($upid, $sync);
878 PVE
::Cluster
::broadcast_tasklist
($tlist);
887 local $SIG{INT
} = local $SIG{QUIT
} = local $SIG{TERM
} = sub {
888 # always send signal to all pgrp members
890 if ($int_count < 3) {
891 kill(15, $kpid); # send TERM signal
893 kill(9, $kpid); # send KILL signal
897 local $SIG{PIPE
} = sub { die "broken pipe\n"; };
899 my $select = new IO
::Select
;
900 my $fh = IO
::Handle-
>new_from_fd($psync[0], 'r');
903 while ($select->count) {
904 my @handles = $select->can_read(1);
905 if (scalar(@handles)) {
906 my $count = sysread ($handles[0], $readbuf, 4096);
907 if (!defined ($count)) {
909 die "sync pipe read error: $err\n";
911 last if $count == 0; # eof
914 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
917 if ($data =~ m/^TASK OK$/) {
919 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
930 # some commands daemonize without closing stdout
931 last if !PVE
::ProcFSTools
::check_process_running
($cpid);
937 POSIX
::close($psync[0]);
939 if ($outbuf) { # just to be sure
942 print $outfh $outbuf;
948 print STDERR
"$err\n";
950 print $outfh "TASK ERROR: $err\n";
954 &$kill_process_group($cpid, $pstart); # make sure it gets killed
960 &$log_task_result($upid, $user, $res);
963 return wantarray ?
($upid, $res) : $upid;