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