use 'mv' to make targets atomic
[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)$/;
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
192 my $self = {
193 user_cfg => {},
194 aclcache => {},
195 aclversion => undef,
196 type => $type,
197 };
198
199 bless $self, $class;
200
201 foreach my $p (keys %params) {
202 if ($p eq 'atfork') {
203 $self->{$p} = $params{$p};
204 } else {
205 die "unknown option '$p'";
206 }
207 }
208
209 $pve_env = $self;
210
211 my ($sysname, $nodename) = POSIX::uname();
212
213 $nodename =~ s/\..*$//; # strip domain part, if any
214
215 $self->{nodename} = $nodename;
216
217 return $self;
218 };
219
220 # get the singleton
221 sub get {
222
223 die "not initialized" if !$pve_env;
224
225 return $pve_env;
226 }
227
228 sub parse_params {
229 my ($self, $enable_upload) = @_;
230
231 if ($self->{request_rec}) {
232 my $cgi;
233 if ($enable_upload) {
234 $cgi = CGI->new($self->{request_rec});
235 } else {
236 # disable upload using empty upload_hook
237 $cgi = CGI->new($self->{request_rec}, sub {}, undef, 0);
238 }
239 $self->{cgi} = $cgi;
240 my $params = $cgi->Vars();
241 return $params;
242 } elsif ($self->{params}) {
243 return $self->{params};
244 } else {
245 die "no parameters registered";
246 }
247 }
248
249 sub get_upload_info {
250 my ($self, $param) = @_;
251
252 my $cgi = $self->{cgi};
253 die "CGI not initialized" if !$cgi;
254
255 my $pd = $cgi->param($param);
256 die "unable to get cgi parameter info\n" if !$pd;
257 my $info = $cgi->uploadInfo($pd);
258 die "unable to get cgi upload info\n" if !$info;
259
260 my $res = { %$info };
261
262 my $tmpfilename = $cgi->tmpFileName($pd);
263 die "unable to get cgi upload file name\n" if !$tmpfilename;
264 $res->{tmpfilename} = $tmpfilename;
265
266 #my $hndl = $cgi->upload($param);
267 #die "unable to get cgi upload handle\n" if !$hndl;
268 #$res->{handle} = $hndl->handle;
269
270 return $res;
271 }
272
273 # init_request - must be called before each RPC request
274 sub init_request {
275 my ($self, %params) = @_;
276
277 PVE::Cluster::cfs_update();
278
279 my $userconfig; # we use this for regression tests
280 foreach my $p (keys %params) {
281 if ($p eq 'userconfig') {
282 $userconfig = $params{$p};
283 } elsif ($p eq 'request_rec') {
284 # pass Apache2::RequestRec
285 $self->{request_rec} = $params{$p};
286 } elsif ($p eq 'params') {
287 $self->{params} = $params{$p};
288 } else {
289 die "unknown parameter '$p'";
290 }
291 }
292
293 eval {
294 $self->{aclcache} = {};
295 if ($userconfig) {
296 my $ucdata = PVE::Tools::file_get_contents($userconfig);
297 my $cfg = PVE::AccessControl::parse_user_config($userconfig, $ucdata);
298 $self->{user_cfg} = $cfg;
299 } else {
300 my $ucvers = PVE::Cluster::cfs_file_version('user.cfg');
301 if (!$self->{aclcache} || !defined($self->{aclversion}) ||
302 !defined($ucvers) || ($ucvers ne $self->{aclversion})) {
303 $self->{aclversion} = $ucvers;
304 my $cfg = PVE::Cluster::cfs_read_file('user.cfg');
305 $self->{user_cfg} = $cfg;
306 }
307 }
308 };
309 if (my $err = $@) {
310 $self->{user_cfg} = {};
311 die "Unable to load access control list: $err";
312 }
313 }
314
315 sub set_client_ip {
316 my ($self, $ip) = @_;
317
318 $self->{client_ip} = $ip;
319 }
320
321 sub get_client_ip {
322 my ($self) = @_;
323
324 return $self->{client_ip};
325 }
326
327 sub set_result_count {
328 my ($self, $count) = @_;
329
330 $self->{result_count} = $count;
331 }
332
333 sub get_result_count {
334 my ($self) = @_;
335
336 return $self->{result_count};
337 }
338
339 sub set_language {
340 my ($self, $lang) = @_;
341
342 # fixme: initialize I18N
343
344 $self->{language} = $lang;
345 }
346
347 sub get_language {
348 my ($self) = @_;
349
350 return $self->{language};
351 }
352
353 sub set_user {
354 my ($self, $user) = @_;
355
356 # fixme: get ACLs
357
358 $self->{user} = $user;
359 }
360
361 sub get_user {
362 my ($self) = @_;
363
364 die "user name not set\n" if !$self->{user};
365
366 return $self->{user};
367 }
368
369 # read/update list of active workers
370 # we move all finished tasks to the archive index,
371 # but keep aktive and most recent task in the active file.
372 # $nocheck ... consider $new_upid still running (avoid that
373 # we try to read the reult to early.
374 sub active_workers {
375 my ($new_upid, $nocheck) = @_;
376
377 my $lkfn = "/var/log/pve/tasks/.active.lock";
378
379 my $timeout = 10;
380
381 my $code = sub {
382
383 my $tasklist = PVE::INotify::read_file('active');
384
385 my @ta;
386 my $tlist = [];
387 my $thash = {}; # only list task once
388
389 my $check_task = sub {
390 my ($task, $running) = @_;
391
392 if ($running || PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart})) {
393 push @$tlist, $task;
394 } else {
395 delete $task->{pid};
396 push @ta, $task;
397 }
398 delete $task->{pstart};
399 };
400
401 foreach my $task (@$tasklist) {
402 my $upid = $task->{upid};
403 next if $thash->{$upid};
404 $thash->{$upid} = $task;
405 &$check_task($task);
406 }
407
408 if ($new_upid && !(my $task = $thash->{$new_upid})) {
409 $task = PVE::Tools::upid_decode($new_upid);
410 $task->{upid} = $new_upid;
411 $thash->{$new_upid} = $task;
412 &$check_task($task, $nocheck);
413 }
414
415
416 @ta = sort { $b->{starttime} cmp $a->{starttime} } @ta;
417
418 my $save = defined($new_upid);
419
420 foreach my $task (@ta) {
421 next if $task->{endtime};
422 $task->{endtime} = time();
423 $task->{status} = PVE::Tools::upid_read_status($task->{upid});
424 $save = 1;
425 }
426
427 my $archive = '';
428 my @arlist = ();
429 foreach my $task (@ta) {
430 if (!$task->{saved}) {
431 $archive .= sprintf("$task->{upid} %08X $task->{status}\n", $task->{endtime});
432 $save = 1;
433 push @arlist, $task;
434 $task->{saved} = 1;
435 }
436 }
437
438 if ($archive) {
439 my $size = 0;
440 my $filename = "/var/log/pve/tasks/index";
441 eval {
442 my $fh = IO::File->new($filename, '>>', 0644) ||
443 die "unable to open file '$filename' - $!\n";
444 PVE::Tools::safe_print($filename, $fh, $archive);
445 $size = -s $fh;
446 close($fh) ||
447 die "unable to close file '$filename' - $!\n";
448 };
449 my $err = $@;
450 if ($err) {
451 syslog('err', $err);
452 foreach my $task (@arlist) { # mark as not saved
453 $task->{saved} = 0;
454 }
455 }
456 my $maxsize = 50000; # about 1000 entries
457 if ($size > $maxsize) {
458 rename($filename, "$filename.1");
459 }
460 }
461
462 # we try to reduce the amount of data
463 # list all running tasks and task and a few others
464 # try to limit to 25 tasks
465 my $ctime = time();
466 my $max = 25 - scalar(@$tlist);
467 foreach my $task (@ta) {
468 last if $max <= 0;
469 push @$tlist, $task;
470 $max--;
471 }
472
473 PVE::INotify::write_file('active', $tlist) if $save;
474
475 return $tlist;
476 };
477
478 my $res = PVE::Tools::lock_file($lkfn, $timeout, $code);
479 die $@ if $@;
480
481 return $res;
482 }
483
484 my $kill_process_group = sub {
485 my ($pid, $pstart) = @_;
486
487 # send kill to process group (negative pid)
488 my $kpid = -$pid;
489
490 # always send signal to all pgrp members
491 kill(15, $kpid); # send TERM signal
492
493 # give max 5 seconds to shut down
494 for (my $i = 0; $i < 5; $i++) {
495 return if !PVE::ProcFSTools::check_process_running($pid, $pstart);
496 sleep (1);
497 }
498
499 # to be sure
500 kill(9, $kpid);
501 };
502
503 sub check_worker {
504 my ($upid, $killit) = @_;
505
506 my $task = PVE::Tools::upid_decode($upid);
507
508 my $running = PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart});
509
510 return 0 if !$running;
511
512 if ($killit) {
513 &$kill_process_group($task->{pid});
514 return 0;
515 }
516
517 return 1;
518 }
519
520 # start long running workers
521 # STDIN is redirected to /dev/null
522 # STDOUT,STDERR are redirected to the filename returned by upid_decode
523 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
524 sub fork_worker {
525 my ($self, $dtype, $id, $user, $function) = @_;
526
527 $dtype = 'unknown' if !defined ($dtype);
528 $id = '' if !defined ($id);
529
530 $user = 'root@pve' if !defined ($user);
531
532 my $sync = $self->{type} eq 'cli' ? 1 : 0;
533
534 local $SIG{INT} =
535 local $SIG{QUIT} =
536 local $SIG{PIPE} =
537 local $SIG{TERM} = 'IGNORE';
538
539 my $starttime = time ();
540
541 my @psync = POSIX::pipe();
542 my @csync = POSIX::pipe();
543
544 my $node = $self->{nodename};
545
546 my $cpid = fork();
547 die "unable to fork worker - $!" if !defined($cpid);
548
549 my $workerpuid = $cpid ? $cpid : $$;
550
551 my $pstart = PVE::ProcFSTools::read_proc_starttime($workerpuid) ||
552 die "unable to read process start time";
553
554 my $upid = PVE::Tools::upid_encode ({
555 node => $node, pid => $workerpuid, pstart => $pstart,
556 starttime => $starttime, type => $dtype, id => $id, user => $user });
557
558 my $outfh;
559
560 if (!$cpid) { # child
561
562 $0 = "task $upid";
563
564 $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = sub { die "received interrupt\n"; };
565
566 $SIG{CHLD} = $SIG{PIPE} = 'DEFAULT';
567
568 # set sess/process group - we want to be able to kill the
569 # whole process group
570 POSIX::setsid();
571
572 POSIX::close ($psync[0]);
573 POSIX::close ($csync[1]);
574
575 $outfh = $sync ? $psync[1] : undef;
576
577 eval {
578 PVE::INotify::inotify_close();
579
580 if (my $atfork = $self->{atfork}) {
581 &$atfork();
582 }
583
584 # same algorythm as used inside SA
585 # STDIN = /dev/null
586 my $fd = fileno (STDIN);
587
588 if (!$sync) {
589 close STDIN;
590 POSIX::close(0) if $fd != 0;
591
592 die "unable to redirect STDIN - $!"
593 if !open(STDIN, "</dev/null");
594
595 $outfh = PVE::Tools::upid_open($upid);
596 }
597
598
599 # redirect STDOUT
600 $fd = fileno(STDOUT);
601 close STDOUT;
602 POSIX::close (1) if $fd != 1;
603
604 die "unable to redirect STDOUT - $!"
605 if !open(STDOUT, ">&", $outfh);
606
607 STDOUT->autoflush (1);
608
609 # redirect STDERR to STDOUT
610 $fd = fileno (STDERR);
611 close STDERR;
612 POSIX::close(2) if $fd != 2;
613
614 die "unable to redirect STDERR - $!"
615 if !open(STDERR, ">&1");
616
617 STDERR->autoflush(1);
618 };
619 if (my $err = $@) {
620 my $msg = "ERROR: $err";
621 POSIX::write($psync[1], $msg, length ($msg));
622 POSIX::close($psync[1]);
623 POSIX::_exit(1);
624 kill(-9, $$);
625 }
626
627 # sync with parent (signal that we are ready)
628 if ($sync) {
629 print "$upid\n";
630 } else {
631 POSIX::write($psync[1], $upid, length ($upid));
632 POSIX::close($psync[1]);
633 }
634
635 my $readbuf = '';
636 # sync with parent (wait until parent is ready)
637 POSIX::read($csync[0], $readbuf, 4096);
638 die "parent setup error\n" if $readbuf ne 'OK';
639
640 eval { &$function($upid); };
641 my $err = $@;
642 if ($err) {
643 chomp $err;
644 $err =~ s/\n/ /mg;
645 syslog('err', $err);
646 print STDERR "TASK ERROR: $err\n";
647 POSIX::_exit(-1);
648 } else {
649 print STDERR "TASK OK\n";
650 POSIX::_exit(0);
651 }
652 kill(-9, $$);
653 }
654
655 # parent
656
657 POSIX::close ($psync[1]);
658 POSIX::close ($csync[0]);
659
660 my $readbuf = '';
661 # sync with child (wait until child starts)
662 POSIX::read($psync[0], $readbuf, 4096);
663
664 if (!$sync) {
665 POSIX::close($psync[0]);
666 &$register_worker($cpid, $user, $upid);
667 } else {
668 chomp $readbuf;
669 }
670
671 eval {
672 die "got no worker upid - start worker failed\n" if !$readbuf;
673
674 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
675 die "starting worker failed: $1\n";
676 }
677
678 if ($readbuf ne $upid) {
679 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
680 }
681
682 if ($sync) {
683 $outfh = PVE::Tools::upid_open($upid);
684 }
685 };
686 my $err = $@;
687
688 if (!$err) {
689 my $msg = 'OK';
690 POSIX::write($csync[1], $msg, length ($msg));
691 POSIX::close($csync[1]);
692
693 } else {
694 POSIX::close($csync[1]);
695 kill(-9, $cpid); # make sure it gets killed
696 die $err;
697 }
698
699 PVE::Cluster::log_msg('info', $user, "starting task $upid");
700
701 my $tlist = active_workers($upid, $sync);
702 PVE::Cluster::broadcast_tasklist($tlist);
703
704 my $res = 0;
705
706 if ($sync) {
707 my $count;
708 my $outbuf = '';
709 my $int_count = 0;
710 eval {
711 local $SIG{INT} = local $SIG{QUIT} = local $SIG{TERM} = sub {
712 # always send signal to all pgrp members
713 my $kpid = -$cpid;
714 if ($int_count < 3) {
715 kill(15, $kpid); # send TERM signal
716 } else {
717 kill(9, $kpid); # send KILL signal
718 }
719 $int_count++;
720 };
721 local $SIG{PIPE} = sub { die "broken pipe\n"; };
722
723 my $select = new IO::Select;
724 my $fh = IO::Handle->new_from_fd($psync[0], 'r');
725 $select->add($fh);
726
727 while ($select->count) {
728 my @handles = $select->can_read(1);
729 if (scalar(@handles)) {
730 my $count = sysread ($handles[0], $readbuf, 4096);
731 if (!defined ($count)) {
732 my $err = $!;
733 die "sync pipe read error: $err\n";
734 }
735 last if $count == 0; # eof
736
737 $outbuf .= $readbuf;
738 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
739 my $line = $1;
740 my $data = $2;
741 if ($data =~ m/^TASK OK$/) {
742 # skip
743 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
744 print STDERR "$1\n";
745 } else {
746 print $line;
747 }
748 if ($outfh) {
749 print $outfh $line;
750 $outfh->flush();
751 }
752 }
753 } else {
754 # some commands daemonize without closing stdout
755 last if !PVE::ProcFSTools::check_process_running($cpid);
756 }
757 }
758 };
759 my $err = $@;
760
761 POSIX::close($psync[0]);
762
763 if ($outbuf) { # just to be sure
764 print $outbuf;
765 if ($outfh) {
766 print $outfh $outbuf;
767 }
768 }
769
770 if ($err) {
771 $err =~ s/\n/ /mg;
772 print STDERR "$err\n";
773 if ($outfh) {
774 print $outfh "TASK ERROR: $err\n";
775 }
776 }
777
778 &$kill_process_group($cpid, $pstart); # make sure it gets killed
779
780 close($outfh);
781
782 waitpid($cpid, 0);
783 $res = $?;
784 &$log_task_result($upid, $user, $res);
785 }
786
787 return wantarray ? ($upid, $res) : $upid;
788 }
789
790 1;