]> git.proxmox.com Git - pve-access-control.git/blob - PVE/RPCEnvironment.pm
45cc84d665c765e46b30fdc71f1ffb9472812166
[pve-access-control.git] / PVE / RPCEnvironment.pm
1 package PVE::RPCEnvironment;
2
3 use strict;
4 use warnings;
5 use POSIX qw(:sys_wait_h EINTR);
6 use IO::Handle;
7 use IO::File;
8 use IO::Select;
9 use Fcntl qw(:flock);
10 use PVE::SafeSyslog;
11 use PVE::Tools;
12 use PVE::INotify;
13 use PVE::Cluster;
14 use PVE::ProcFSTools;
15 use PVE::AccessControl;
16 use CGI;
17
18 # we use this singleton class to pass RPC related environment values
19
20 my $pve_env;
21
22 # save $SIG{CHLD} handler implementation.
23 # simply set $SIG{CHLD} = $worker_reaper;
24 # and register forked processes with &$register_worker(pid)
25 # Note: using $SIG{CHLD} = 'IGNORE' or $SIG{CHLD} = sub { wait (); } or ...
26 # has serious side effects, because perls built in system() and open()
27 # functions can't get the correct exit status of a child. So we cant use
28 # that (also see perlipc)
29
30 my $WORKER_PIDS;
31
32 my $log_task_result = sub {
33 my ($upid, $user, $status) = @_;
34
35 my $msg = 'successful';
36 my $pri = 'info';
37 if ($status != 0) {
38 my $ec = $status >> 8;
39 my $ic = $status & 255;
40 $msg = $ec ? "failed ($ec)" : "interrupted ($ic)";
41 $pri = 'err';
42 }
43 my $tlist = active_workers($upid);
44 PVE::Cluster::broadcast_tasklist($tlist);
45 my $task;
46 foreach my $t (@$tlist) {
47 if ($t->{upid} eq $upid) {
48 $task = $t;
49 last;
50 }
51 }
52 if ($task && $task->{status}) {
53 $msg = $task->{status};
54 }
55 PVE::Cluster::log_msg($pri, $user, "end task $upid $msg");
56 };
57
58 my $worker_reaper = sub {
59 local $!; local $?;
60 foreach my $pid (keys %$WORKER_PIDS) {
61 my $waitpid = waitpid ($pid, WNOHANG);
62 if (defined($waitpid) && ($waitpid == $pid)) {
63 my $info = $WORKER_PIDS->{$pid};
64 if ($info && $info->{upid} && $info->{user}) {
65 &$log_task_result($info->{upid}, $info->{user}, $?);
66 }
67 delete ($WORKER_PIDS->{$pid});
68 }
69 }
70 };
71
72 my $register_worker = sub {
73 my ($pid, $user, $upid) = @_;
74
75 return if !$pid;
76
77 # do not register if already finished
78 my $waitpid = waitpid ($pid, WNOHANG);
79 if (defined($waitpid) && ($waitpid == $pid)) {
80 delete ($WORKER_PIDS->{$pid});
81 return;
82 }
83
84 $WORKER_PIDS->{$pid} = {
85 user => $user,
86 upid => $upid,
87 };
88 };
89
90 # ACL cache
91
92 my $compile_acl = sub {
93 my ($self, $user) = @_;
94
95 my $res = {};
96 my $cfg = $self->{user_cfg};
97
98 return undef if !$cfg->{roles};
99
100 if ($user eq 'root@pam') { # root can do anything
101 return {'/' => $cfg->{roles}->{'Administrator'}};
102 }
103
104 foreach my $path (sort keys %{$cfg->{acl}}) {
105 my @ra = PVE::AccessControl::roles($cfg, $user, $path);
106
107 my $privs = {};
108 foreach my $role (@ra) {
109 if (my $privset = $cfg->{roles}->{$role}) {
110 foreach my $p (keys %$privset) {
111 $privs->{$p} = 1;
112 }
113 }
114 }
115
116 $res->{$path} = $privs;
117 }
118
119 return $res;
120 };
121
122 sub permissions {
123 my ($self, $user, $path) = @_;
124
125 $user = PVE::AccessControl::verify_username($user, 1);
126 return {} if !$user;
127
128 my $cache = $self->{aclcache};
129
130 my $acl = $cache->{$user};
131
132 if (!$acl) {
133 if (!($acl = &$compile_acl($self, $user))) {
134 return {};
135 }
136 $cache->{$user} = $acl;
137 }
138
139 my $perm;
140
141 if (!($perm = $acl->{$path})) {
142 $perm = {};
143 foreach my $p (sort keys %$acl) {
144 my $final = ($path eq $p);
145
146 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
147
148 $perm = $acl->{$p};
149 }
150 $acl->{$path} = $perm;
151 }
152
153 return $perm;
154 }
155
156 sub check {
157 my ($self, $user, $path, $privs) = @_;
158
159 my $perm = $self->permissions($user, $path);
160
161 foreach my $priv (@$privs) {
162 return undef if !$perm->{$priv};
163 };
164
165 return 1;
166 };
167
168 sub user_enabled {
169 my ($self, $user) = @_;
170
171 my $cfg = $self->{user_cfg};
172 return PVE::AccessControl::user_enabled($cfg, $user);
173 }
174
175 # initialize environment - must be called once at program startup
176 sub init {
177 my ($class, $type, %params) = @_;
178
179 $class = ref($class) || $class;
180
181 die "already initialized" if $pve_env;
182
183 die "unknown environment type" if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
184
185 $SIG{CHLD} = $worker_reaper;
186
187 # environment types
188 # cli ... command started fron command line
189 # pub ... access from public server (apache)
190 # priv ... access from private server (pvedaemon)
191 # ha ... access from HA resource manager agent (rgmanager)
192
193 my $self = {
194 user_cfg => {},
195 aclcache => {},
196 aclversion => undef,
197 type => $type,
198 };
199
200 bless $self, $class;
201
202 foreach my $p (keys %params) {
203 if ($p eq 'atfork') {
204 $self->{$p} = $params{$p};
205 } else {
206 die "unknown option '$p'";
207 }
208 }
209
210 $pve_env = $self;
211
212 my ($sysname, $nodename) = POSIX::uname();
213
214 $nodename =~ s/\..*$//; # strip domain part, if any
215
216 $self->{nodename} = $nodename;
217
218 return $self;
219 };
220
221 # get the singleton
222 sub get {
223
224 die "not initialized" if !$pve_env;
225
226 return $pve_env;
227 }
228
229 sub parse_params {
230 my ($self, $enable_upload) = @_;
231
232 if ($self->{request_rec}) {
233 my $cgi;
234 if ($enable_upload) {
235 $cgi = CGI->new($self->{request_rec});
236 } else {
237 # disable upload using empty upload_hook
238 $cgi = CGI->new($self->{request_rec}, sub {}, undef, 0);
239 }
240 $self->{cgi} = $cgi;
241 my $params = $cgi->Vars();
242 return $params;
243 } elsif ($self->{params}) {
244 return $self->{params};
245 } else {
246 die "no parameters registered";
247 }
248 }
249
250 sub get_upload_info {
251 my ($self, $param) = @_;
252
253 my $cgi = $self->{cgi};
254 die "CGI not initialized" if !$cgi;
255
256 my $pd = $cgi->param($param);
257 die "unable to get cgi parameter info\n" if !$pd;
258 my $info = $cgi->uploadInfo($pd);
259 die "unable to get cgi upload info\n" if !$info;
260
261 my $res = { %$info };
262
263 my $tmpfilename = $cgi->tmpFileName($pd);
264 die "unable to get cgi upload file name\n" if !$tmpfilename;
265 $res->{tmpfilename} = $tmpfilename;
266
267 #my $hndl = $cgi->upload($param);
268 #die "unable to get cgi upload handle\n" if !$hndl;
269 #$res->{handle} = $hndl->handle;
270
271 return $res;
272 }
273
274 # init_request - must be called before each RPC request
275 sub init_request {
276 my ($self, %params) = @_;
277
278 PVE::Cluster::cfs_update();
279
280 $self->{result_count} = undef;
281 $self->{result_changes} = undef;
282
283 my $userconfig; # we use this for regression tests
284 foreach my $p (keys %params) {
285 if ($p eq 'userconfig') {
286 $userconfig = $params{$p};
287 } elsif ($p eq 'request_rec') {
288 # pass Apache2::RequestRec
289 $self->{request_rec} = $params{$p};
290 } elsif ($p eq 'params') {
291 $self->{params} = $params{$p};
292 } else {
293 die "unknown parameter '$p'";
294 }
295 }
296
297 eval {
298 $self->{aclcache} = {};
299 if ($userconfig) {
300 my $ucdata = PVE::Tools::file_get_contents($userconfig);
301 my $cfg = PVE::AccessControl::parse_user_config($userconfig, $ucdata);
302 $self->{user_cfg} = $cfg;
303 } else {
304 my $ucvers = PVE::Cluster::cfs_file_version('user.cfg');
305 if (!$self->{aclcache} || !defined($self->{aclversion}) ||
306 !defined($ucvers) || ($ucvers ne $self->{aclversion})) {
307 $self->{aclversion} = $ucvers;
308 my $cfg = PVE::Cluster::cfs_read_file('user.cfg');
309 $self->{user_cfg} = $cfg;
310 }
311 }
312 };
313 if (my $err = $@) {
314 $self->{user_cfg} = {};
315 die "Unable to load access control list: $err";
316 }
317 }
318
319 sub set_client_ip {
320 my ($self, $ip) = @_;
321
322 $self->{client_ip} = $ip;
323 }
324
325 sub get_client_ip {
326 my ($self) = @_;
327
328 return $self->{client_ip};
329 }
330
331 sub set_result_count {
332 my ($self, $count) = @_;
333
334 $self->{result_count} = $count;
335 }
336
337 sub get_result_count {
338 my ($self) = @_;
339
340 return $self->{result_count};
341 }
342
343 sub set_result_changes {
344 my ($self, $diff) = @_;
345
346 $self->{result_changes} = $diff;
347 }
348
349 sub get_result_changes {
350 my ($self) = @_;
351
352 return $self->{result_changes};
353 }
354
355 sub set_language {
356 my ($self, $lang) = @_;
357
358 # fixme: initialize I18N
359
360 $self->{language} = $lang;
361 }
362
363 sub get_language {
364 my ($self) = @_;
365
366 return $self->{language};
367 }
368
369 sub set_user {
370 my ($self, $user) = @_;
371
372 # fixme: get ACLs
373
374 $self->{user} = $user;
375 }
376
377 sub get_user {
378 my ($self) = @_;
379
380 die "user name not set\n" if !$self->{user};
381
382 return $self->{user};
383 }
384
385 # read/update list of active workers
386 # we move all finished tasks to the archive index,
387 # but keep aktive and most recent task in the active file.
388 # $nocheck ... consider $new_upid still running (avoid that
389 # we try to read the reult to early.
390 sub active_workers {
391 my ($new_upid, $nocheck) = @_;
392
393 my $lkfn = "/var/log/pve/tasks/.active.lock";
394
395 my $timeout = 10;
396
397 my $code = sub {
398
399 my $tasklist = PVE::INotify::read_file('active');
400
401 my @ta;
402 my $tlist = [];
403 my $thash = {}; # only list task once
404
405 my $check_task = sub {
406 my ($task, $running) = @_;
407
408 if ($running || PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart})) {
409 push @$tlist, $task;
410 } else {
411 delete $task->{pid};
412 push @ta, $task;
413 }
414 delete $task->{pstart};
415 };
416
417 foreach my $task (@$tasklist) {
418 my $upid = $task->{upid};
419 next if $thash->{$upid};
420 $thash->{$upid} = $task;
421 &$check_task($task);
422 }
423
424 if ($new_upid && !(my $task = $thash->{$new_upid})) {
425 $task = PVE::Tools::upid_decode($new_upid);
426 $task->{upid} = $new_upid;
427 $thash->{$new_upid} = $task;
428 &$check_task($task, $nocheck);
429 }
430
431
432 @ta = sort { $b->{starttime} cmp $a->{starttime} } @ta;
433
434 my $save = defined($new_upid);
435
436 foreach my $task (@ta) {
437 next if $task->{endtime};
438 $task->{endtime} = time();
439 $task->{status} = PVE::Tools::upid_read_status($task->{upid});
440 $save = 1;
441 }
442
443 my $archive = '';
444 my @arlist = ();
445 foreach my $task (@ta) {
446 if (!$task->{saved}) {
447 $archive .= sprintf("$task->{upid} %08X $task->{status}\n", $task->{endtime});
448 $save = 1;
449 push @arlist, $task;
450 $task->{saved} = 1;
451 }
452 }
453
454 if ($archive) {
455 my $size = 0;
456 my $filename = "/var/log/pve/tasks/index";
457 eval {
458 my $fh = IO::File->new($filename, '>>', 0644) ||
459 die "unable to open file '$filename' - $!\n";
460 PVE::Tools::safe_print($filename, $fh, $archive);
461 $size = -s $fh;
462 close($fh) ||
463 die "unable to close file '$filename' - $!\n";
464 };
465 my $err = $@;
466 if ($err) {
467 syslog('err', $err);
468 foreach my $task (@arlist) { # mark as not saved
469 $task->{saved} = 0;
470 }
471 }
472 my $maxsize = 50000; # about 1000 entries
473 if ($size > $maxsize) {
474 rename($filename, "$filename.1");
475 }
476 }
477
478 # we try to reduce the amount of data
479 # list all running tasks and task and a few others
480 # try to limit to 25 tasks
481 my $ctime = time();
482 my $max = 25 - scalar(@$tlist);
483 foreach my $task (@ta) {
484 last if $max <= 0;
485 push @$tlist, $task;
486 $max--;
487 }
488
489 PVE::INotify::write_file('active', $tlist) if $save;
490
491 return $tlist;
492 };
493
494 my $res = PVE::Tools::lock_file($lkfn, $timeout, $code);
495 die $@ if $@;
496
497 return $res;
498 }
499
500 my $kill_process_group = sub {
501 my ($pid, $pstart) = @_;
502
503 # send kill to process group (negative pid)
504 my $kpid = -$pid;
505
506 # always send signal to all pgrp members
507 kill(15, $kpid); # send TERM signal
508
509 # give max 5 seconds to shut down
510 for (my $i = 0; $i < 5; $i++) {
511 return if !PVE::ProcFSTools::check_process_running($pid, $pstart);
512 sleep (1);
513 }
514
515 # to be sure
516 kill(9, $kpid);
517 };
518
519 sub check_worker {
520 my ($upid, $killit) = @_;
521
522 my $task = PVE::Tools::upid_decode($upid);
523
524 my $running = PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart});
525
526 return 0 if !$running;
527
528 if ($killit) {
529 &$kill_process_group($task->{pid});
530 return 0;
531 }
532
533 return 1;
534 }
535
536 # start long running workers
537 # STDIN is redirected to /dev/null
538 # STDOUT,STDERR are redirected to the filename returned by upid_decode
539 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
540 sub fork_worker {
541 my ($self, $dtype, $id, $user, $function) = @_;
542
543 $dtype = 'unknown' if !defined ($dtype);
544 $id = '' if !defined ($id);
545
546 $user = 'root@pve' if !defined ($user);
547
548 my $sync = $self->{type} eq 'cli' ? 1 : 0;
549
550 local $SIG{INT} =
551 local $SIG{QUIT} =
552 local $SIG{PIPE} =
553 local $SIG{TERM} = 'IGNORE';
554
555 my $starttime = time ();
556
557 my @psync = POSIX::pipe();
558 my @csync = POSIX::pipe();
559
560 my $node = $self->{nodename};
561
562 my $cpid = fork();
563 die "unable to fork worker - $!" if !defined($cpid);
564
565 my $workerpuid = $cpid ? $cpid : $$;
566
567 my $pstart = PVE::ProcFSTools::read_proc_starttime($workerpuid) ||
568 die "unable to read process start time";
569
570 my $upid = PVE::Tools::upid_encode ({
571 node => $node, pid => $workerpuid, pstart => $pstart,
572 starttime => $starttime, type => $dtype, id => $id, user => $user });
573
574 my $outfh;
575
576 if (!$cpid) { # child
577
578 $0 = "task $upid";
579
580 $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = sub { die "received interrupt\n"; };
581
582 $SIG{CHLD} = $SIG{PIPE} = 'DEFAULT';
583
584 # set sess/process group - we want to be able to kill the
585 # whole process group
586 POSIX::setsid();
587
588 POSIX::close ($psync[0]);
589 POSIX::close ($csync[1]);
590
591 $outfh = $sync ? $psync[1] : undef;
592
593 eval {
594 PVE::INotify::inotify_close();
595
596 if (my $atfork = $self->{atfork}) {
597 &$atfork();
598 }
599
600 # same algorythm as used inside SA
601 # STDIN = /dev/null
602 my $fd = fileno (STDIN);
603
604 if (!$sync) {
605 close STDIN;
606 POSIX::close(0) if $fd != 0;
607
608 die "unable to redirect STDIN - $!"
609 if !open(STDIN, "</dev/null");
610
611 $outfh = PVE::Tools::upid_open($upid);
612 }
613
614
615 # redirect STDOUT
616 $fd = fileno(STDOUT);
617 close STDOUT;
618 POSIX::close (1) if $fd != 1;
619
620 die "unable to redirect STDOUT - $!"
621 if !open(STDOUT, ">&", $outfh);
622
623 STDOUT->autoflush (1);
624
625 # redirect STDERR to STDOUT
626 $fd = fileno (STDERR);
627 close STDERR;
628 POSIX::close(2) if $fd != 2;
629
630 die "unable to redirect STDERR - $!"
631 if !open(STDERR, ">&1");
632
633 STDERR->autoflush(1);
634 };
635 if (my $err = $@) {
636 my $msg = "ERROR: $err";
637 POSIX::write($psync[1], $msg, length ($msg));
638 POSIX::close($psync[1]);
639 POSIX::_exit(1);
640 kill(-9, $$);
641 }
642
643 # sync with parent (signal that we are ready)
644 if ($sync) {
645 print "$upid\n";
646 } else {
647 POSIX::write($psync[1], $upid, length ($upid));
648 POSIX::close($psync[1]);
649 }
650
651 my $readbuf = '';
652 # sync with parent (wait until parent is ready)
653 POSIX::read($csync[0], $readbuf, 4096);
654 die "parent setup error\n" if $readbuf ne 'OK';
655
656 if ($self->{type} eq 'ha') {
657 print "task started by HA resource agent\n";
658 }
659 eval { &$function($upid); };
660 my $err = $@;
661 if ($err) {
662 chomp $err;
663 $err =~ s/\n/ /mg;
664 syslog('err', $err);
665 print STDERR "TASK ERROR: $err\n";
666 POSIX::_exit(-1);
667 } else {
668 print STDERR "TASK OK\n";
669 POSIX::_exit(0);
670 }
671 kill(-9, $$);
672 }
673
674 # parent
675
676 POSIX::close ($psync[1]);
677 POSIX::close ($csync[0]);
678
679 my $readbuf = '';
680 # sync with child (wait until child starts)
681 POSIX::read($psync[0], $readbuf, 4096);
682
683 if (!$sync) {
684 POSIX::close($psync[0]);
685 &$register_worker($cpid, $user, $upid);
686 } else {
687 chomp $readbuf;
688 }
689
690 eval {
691 die "got no worker upid - start worker failed\n" if !$readbuf;
692
693 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
694 die "starting worker failed: $1\n";
695 }
696
697 if ($readbuf ne $upid) {
698 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
699 }
700
701 if ($sync) {
702 $outfh = PVE::Tools::upid_open($upid);
703 }
704 };
705 my $err = $@;
706
707 if (!$err) {
708 my $msg = 'OK';
709 POSIX::write($csync[1], $msg, length ($msg));
710 POSIX::close($csync[1]);
711
712 } else {
713 POSIX::close($csync[1]);
714 kill(-9, $cpid); # make sure it gets killed
715 die $err;
716 }
717
718 PVE::Cluster::log_msg('info', $user, "starting task $upid");
719
720 my $tlist = active_workers($upid, $sync);
721 PVE::Cluster::broadcast_tasklist($tlist);
722
723 my $res = 0;
724
725 if ($sync) {
726 my $count;
727 my $outbuf = '';
728 my $int_count = 0;
729 eval {
730 local $SIG{INT} = local $SIG{QUIT} = local $SIG{TERM} = sub {
731 # always send signal to all pgrp members
732 my $kpid = -$cpid;
733 if ($int_count < 3) {
734 kill(15, $kpid); # send TERM signal
735 } else {
736 kill(9, $kpid); # send KILL signal
737 }
738 $int_count++;
739 };
740 local $SIG{PIPE} = sub { die "broken pipe\n"; };
741
742 my $select = new IO::Select;
743 my $fh = IO::Handle->new_from_fd($psync[0], 'r');
744 $select->add($fh);
745
746 while ($select->count) {
747 my @handles = $select->can_read(1);
748 if (scalar(@handles)) {
749 my $count = sysread ($handles[0], $readbuf, 4096);
750 if (!defined ($count)) {
751 my $err = $!;
752 die "sync pipe read error: $err\n";
753 }
754 last if $count == 0; # eof
755
756 $outbuf .= $readbuf;
757 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
758 my $line = $1;
759 my $data = $2;
760 if ($data =~ m/^TASK OK$/) {
761 # skip
762 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
763 print STDERR "$1\n";
764 } else {
765 print $line;
766 }
767 if ($outfh) {
768 print $outfh $line;
769 $outfh->flush();
770 }
771 }
772 } else {
773 # some commands daemonize without closing stdout
774 last if !PVE::ProcFSTools::check_process_running($cpid);
775 }
776 }
777 };
778 my $err = $@;
779
780 POSIX::close($psync[0]);
781
782 if ($outbuf) { # just to be sure
783 print $outbuf;
784 if ($outfh) {
785 print $outfh $outbuf;
786 }
787 }
788
789 if ($err) {
790 $err =~ s/\n/ /mg;
791 print STDERR "$err\n";
792 if ($outfh) {
793 print $outfh "TASK ERROR: $err\n";
794 }
795 }
796
797 &$kill_process_group($cpid, $pstart); # make sure it gets killed
798
799 close($outfh);
800
801 waitpid($cpid, 0);
802 $res = $?;
803 &$log_task_result($upid, $user, $res);
804 }
805
806 return wantarray ? ($upid, $res) : $upid;
807 }
808
809 1;