]> git.proxmox.com Git - pve-access-control.git/blob - PVE/RPCEnvironment.pm
untaint path
[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::Exception qw(raise raise_perm_exc);
11 use PVE::SafeSyslog;
12 use PVE::Tools;
13 use PVE::INotify;
14 use PVE::Cluster;
15 use PVE::ProcFSTools;
16 use PVE::AccessControl;
17 use Cwd 'abs_path';
18 use CGI;
19
20 # we use this singleton class to pass RPC related environment values
21
22 my $pve_env;
23
24 # save $SIG{CHLD} handler implementation.
25 # simply set $SIG{CHLD} = $worker_reaper;
26 # and register forked processes with &$register_worker(pid)
27 # Note: using $SIG{CHLD} = 'IGNORE' or $SIG{CHLD} = sub { wait (); } or ...
28 # has serious side effects, because perls built in system() and open()
29 # functions can't get the correct exit status of a child. So we cant use
30 # that (also see perlipc)
31
32 my $WORKER_PIDS;
33
34 my $log_task_result = sub {
35 my ($upid, $user, $status) = @_;
36
37 my $msg = 'successful';
38 my $pri = 'info';
39 if ($status != 0) {
40 my $ec = $status >> 8;
41 my $ic = $status & 255;
42 $msg = $ec ? "failed ($ec)" : "interrupted ($ic)";
43 $pri = 'err';
44 }
45 my $tlist = active_workers($upid);
46 PVE::Cluster::broadcast_tasklist($tlist);
47 my $task;
48 foreach my $t (@$tlist) {
49 if ($t->{upid} eq $upid) {
50 $task = $t;
51 last;
52 }
53 }
54 if ($task && $task->{status}) {
55 $msg = $task->{status};
56 }
57 PVE::Cluster::log_msg($pri, $user, "end task $upid $msg");
58 };
59
60 my $worker_reaper = sub {
61 local $!; local $?;
62 foreach my $pid (keys %$WORKER_PIDS) {
63 my $waitpid = waitpid ($pid, WNOHANG);
64 if (defined($waitpid) && ($waitpid == $pid)) {
65 my $info = $WORKER_PIDS->{$pid};
66 if ($info && $info->{upid} && $info->{user}) {
67 &$log_task_result($info->{upid}, $info->{user}, $?);
68 }
69 delete ($WORKER_PIDS->{$pid});
70 }
71 }
72 };
73
74 my $register_worker = sub {
75 my ($pid, $user, $upid) = @_;
76
77 return if !$pid;
78
79 # do not register if already finished
80 my $waitpid = waitpid ($pid, WNOHANG);
81 if (defined($waitpid) && ($waitpid == $pid)) {
82 delete ($WORKER_PIDS->{$pid});
83 return;
84 }
85
86 $WORKER_PIDS->{$pid} = {
87 user => $user,
88 upid => $upid,
89 };
90 };
91
92 # ACL cache
93
94 my $compile_acl_path = sub {
95 my ($self, $user, $path) = @_;
96
97 my $cfg = $self->{user_cfg};
98
99 return undef if !$cfg->{roles};
100
101 die "internal error" if $user eq 'root@pam';
102
103 my $cache = $self->{aclcache};
104 $cache->{$user} = {} if !$cache->{$user};
105 my $data = $cache->{$user};
106
107 if (!$data->{poolroles}) {
108 $data->{poolroles} = {};
109
110 foreach my $pool (keys %{$cfg->{pools}}) {
111 my $d = $cfg->{pools}->{$pool};
112 my @ra = PVE::AccessControl::roles($cfg, $user, "/pool/$pool"); # pool roles
113 next if !scalar(@ra);
114 foreach my $vmid (keys %{$d->{vms}}) {
115 for my $role (@ra) {
116 $data->{poolroles}->{"/vms/$vmid"}->{$role} = 1;
117 }
118 }
119 foreach my $storeid (keys %{$d->{storage}}) {
120 for my $role (@ra) {
121 $data->{poolroles}->{"/storage/$storeid"}->{$role} = 1;
122 }
123 }
124 }
125 }
126
127 my @ra = PVE::AccessControl::roles($cfg, $user, $path);
128
129 # apply roles inherited from pools
130 # Note: assume we do not want to propagate those privs
131 if ($data->{poolroles}->{$path}) {
132 if (!($ra[0] && $ra[0] eq 'NoAccess')) {
133 if ($data->{poolroles}->{$path}->{NoAccess}) {
134 @ra = ('NoAccess');
135 } else {
136 foreach my $role (keys %{$data->{poolroles}->{$path}}) {
137 push @ra, $role;
138 }
139 }
140 }
141 }
142
143 $data->{roles}->{$path} = [ @ra ];
144
145 my $privs = {};
146 foreach my $role (@ra) {
147 if (my $privset = $cfg->{roles}->{$role}) {
148 foreach my $p (keys %$privset) {
149 $privs->{$p} = 1;
150 }
151 }
152 }
153 $data->{privs}->{$path} = $privs;
154
155 return $privs;
156 };
157
158 sub roles {
159 my ($self, $user, $path) = @_;
160
161 if ($user eq 'root@pam') { # root can do anything
162 return ('Administrator');
163 }
164
165 $user = PVE::AccessControl::verify_username($user, 1);
166 return () if !$user;
167
168 my $cache = $self->{aclcache};
169 $cache->{$user} = {} if !$cache->{$user};
170
171 my $acl = $cache->{$user};
172
173 my $roles = $acl->{roles}->{$path};
174 return @$roles if $roles;
175
176 &$compile_acl_path($self, $user, $path);
177 $roles = $acl->{roles}->{$path} || [];
178 return @$roles;
179 }
180
181 sub permissions {
182 my ($self, $user, $path) = @_;
183
184 if ($user eq 'root@pam') { # root can do anything
185 my $cfg = $self->{user_cfg};
186 return $cfg->{roles}->{'Administrator'};
187 }
188
189 $user = PVE::AccessControl::verify_username($user, 1);
190 return {} if !$user;
191
192 my $cache = $self->{aclcache};
193 $cache->{$user} = {} if !$cache->{$user};
194
195 my $acl = $cache->{$user};
196
197 my $perm = $acl->{privs}->{$path};
198 return $perm if $perm;
199
200 return &$compile_acl_path($self, $user, $path);
201 }
202
203 sub check {
204 my ($self, $user, $path, $privs, $noerr) = @_;
205
206 my $perm = $self->permissions($user, $path);
207
208 foreach my $priv (@$privs) {
209 PVE::AccessControl::verify_privname($priv);
210 if (!$perm->{$priv}) {
211 return undef if $noerr;
212 raise_perm_exc("$path, $priv");
213 }
214 };
215
216 return 1;
217 };
218
219 sub check_any {
220 my ($self, $user, $path, $privs, $noerr) = @_;
221
222 my $perm = $self->permissions($user, $path);
223
224 my $found = 0;
225 foreach my $priv (@$privs) {
226 PVE::AccessControl::verify_privname($priv);
227 if ($perm->{$priv}) {
228 $found = 1;
229 last;
230 }
231 };
232
233 return 1 if $found;
234
235 return undef if $noerr;
236
237 raise_perm_exc("$path, " . join("|", @$privs));
238 };
239
240 sub check_full {
241 my ($self, $username, $path, $privs, $any, $noerr) = @_;
242 if ($any) {
243 return $self->check_any($username, $path, $privs, $noerr);
244 } else {
245 return $self->check($username, $path, $privs, $noerr);
246 }
247 }
248
249 sub check_user_enabled {
250 my ($self, $user, $noerr) = @_;
251
252 my $cfg = $self->{user_cfg};
253 return PVE::AccessControl::check_user_enabled($cfg, $user, $noerr);
254 }
255
256 sub check_user_exist {
257 my ($self, $user, $noerr) = @_;
258
259 my $cfg = $self->{user_cfg};
260 return PVE::AccessControl::check_user_exist($cfg, $user, $noerr);
261 }
262
263 sub check_pool_exist {
264 my ($self, $pool, $noerr) = @_;
265
266 my $cfg = $self->{user_cfg};
267
268 return 1 if $cfg->{pools}->{$pool};
269
270 return undef if $noerr;
271
272 raise_perm_exc("pool '$pool' does not exist");
273 }
274
275 sub check_vm_perm {
276 my ($self, $user, $vmid, $pool, $privs, $any, $noerr) = @_;
277
278 my $cfg = $self->{user_cfg};
279
280 if ($pool) {
281 return if $self->check_full($user, "/pool/$pool", $privs, $any, 1);
282 }
283 return $self->check_full($user, "/vms/$vmid", $privs, $any, $noerr);
284 };
285
286 sub check_volume_access {
287 my ($self, $user, $storecfg, $vmid, $volid) = @_;
288
289 # test if we have read access to volid
290
291 my $path;
292 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
293 if ($sid) {
294 my ($ownervm, $vtype);
295 ($path, $ownervm, $vtype) = PVE::Storage::path($storecfg, $volid);
296 if ($vtype eq 'iso' || $vtype eq 'vztmpl') {
297 # we simply allow access
298 } elsif (!$ownervm || ($ownervm != $vmid)) {
299 # allow if we are Datastore administrator
300 $self->check($user, "/storage/$sid", ['Datastore.Allocate']);
301 }
302 } else {
303 die "Only root can pass arbitrary filesystem paths."
304 if $user ne 'root@pam';
305
306 $path = abs_path($volid);
307 if ($path =~ m|^(/.+)$|) {
308 $path = $1; # untaint any path
309 }
310 }
311 return $path;
312 }
313
314 sub is_group_member {
315 my ($self, $group, $user) = @_;
316
317 my $cfg = $self->{user_cfg};
318
319 return 0 if !$cfg->{groups}->{$group};
320
321 return defined($cfg->{groups}->{$group}->{users}->{$user});
322 }
323
324 sub filter_groups {
325 my ($self, $user, $privs, $any) = @_;
326
327 my $cfg = $self->{user_cfg};
328
329 my $groups = {};
330 foreach my $group (keys %{$cfg->{groups}}) {
331 my $path = "/access/groups/$group";
332 if ($self->check_full($user, $path, $privs, $any, 1)) {
333 $groups->{$group} = $cfg->{groups}->{$group};
334 }
335 }
336
337 return $groups;
338 }
339
340 sub group_member_join {
341 my ($self, $grouplist) = @_;
342
343 my $users = {};
344
345 my $cfg = $self->{user_cfg};
346 foreach my $group (@$grouplist) {
347 my $data = $cfg->{groups}->{$group};
348 next if !$data;
349 foreach my $user (keys %{$data->{users}}) {
350 $users->{$user} = 1;
351 }
352 }
353
354 return $users;
355 }
356
357 sub check_perm_modify {
358 my ($self, $username, $path, $noerr) = @_;
359
360 return $self->check($username, '/access', [ 'Permissions.Modify' ], $noerr) if !$path;
361
362 my $testperms = [ 'Permissions.Modify' ];
363 if ($path =~ m|^/storage/.+$|) {
364 push @$testperms, 'Datastore.Allocate';
365 } elsif ($path =~ m|^/vms/.+$|) {
366 push @$testperms, 'VM.Allocate';
367 } elsif ($path =~ m|^/pool/.+$|) {
368 push @$testperms, 'Pool.Allocate';
369 }
370
371 return $self->check_any($username, $path, $testperms, $noerr);
372 }
373
374 sub exec_api2_perm_check {
375 my ($self, $check, $username, $param, $noerr) = @_;
376
377 # syslog("info", "CHECK " . join(', ', @$check));
378
379 my $ind = 0;
380 my $test = $check->[$ind++];
381 die "no permission test specified" if !$test;
382
383 if ($test eq 'and') {
384 while (my $subcheck = $check->[$ind++]) {
385 $self->exec_api2_perm_check($subcheck, $username, $param);
386 }
387 return 1;
388 } elsif ($test eq 'or') {
389 while (my $subcheck = $check->[$ind++]) {
390 return 1 if $self->exec_api2_perm_check($subcheck, $username, $param, 1);
391 }
392 return 0 if $noerr;
393 raise_perm_exc();
394 } elsif ($test eq 'perm') {
395 my ($t, $tmplpath, $privs, %options) = @$check;
396 my $any = $options{any};
397 die "missing parameters" if !($tmplpath && $privs);
398 my $require_param = $options{require_param};
399 if ($require_param && !defined($param->{$require_param})) {
400 return 0 if $noerr;
401 raise_perm_exc();
402 }
403 my $path = PVE::Tools::template_replace($tmplpath, $param);
404 $path = PVE::AccessControl::normalize_path($path);
405 return $self->check_full($username, $path, $privs, $any, $noerr);
406 } elsif ($test eq 'userid-group') {
407 my $userid = $param->{userid};
408 my ($t, $privs, %options) = @$check;
409 return 0 if !$options{groups_param} && !$self->check_user_exist($userid, $noerr);
410 if (!$self->check_any($username, "/access/groups", $privs, 1)) {
411 my $groups = $self->filter_groups($username, $privs, 1);
412 if ($options{groups_param}) {
413 my @group_param = PVE::Tools::split_list($param->{groups});
414 raise_perm_exc("/access/groups, " . join("|", @$privs)) if !scalar(@group_param);
415 foreach my $pg (@group_param) {
416 raise_perm_exc("/access/groups/$pg, " . join("|", @$privs))
417 if !$groups->{$pg};
418 }
419 } else {
420 my $allowed_users = $self->group_member_join([keys %$groups]);
421 if (!$allowed_users->{$userid}) {
422 return 0 if $noerr;
423 raise_perm_exc();
424 }
425 }
426 }
427 return 1;
428 } elsif ($test eq 'userid-param') {
429 my ($userid, undef, $realm) = PVE::AccessControl::verify_username($param->{userid});
430 my ($t, $subtest) = @$check;
431 die "missing parameters" if !$subtest;
432 if ($subtest eq 'self') {
433 return 0 if !$self->check_user_exist($userid, $noerr);
434 return 1 if $username eq $userid;
435 return 0 if $noerr;
436 raise_perm_exc();
437 } elsif ($subtest eq 'Realm.AllocateUser') {
438 my $path = "/access/realm/$realm";
439 return $self->check($username, $path, ['Realm.AllocateUser'], $noerr);
440 } else {
441 die "unknown userid-param test";
442 }
443 } elsif ($test eq 'perm-modify') {
444 my ($t, $tmplpath) = @$check;
445 my $path = PVE::Tools::template_replace($tmplpath, $param);
446 $path = PVE::AccessControl::normalize_path($path);
447 return $self->check_perm_modify($username, $path, $noerr);
448 } else {
449 die "unknown permission test";
450 }
451 };
452
453 sub check_api2_permissions {
454 my ($self, $perm, $username, $param) = @_;
455
456 return 1 if !$username && $perm->{user} eq 'world';
457
458 raise_perm_exc("user != null") if !$username;
459
460 return 1 if $username eq 'root@pam';
461
462 raise_perm_exc('user != root@pam') if !$perm;
463
464 return 1 if $perm->{user} && $perm->{user} eq 'all';
465
466 return $self->exec_api2_perm_check($perm->{check}, $username, $param)
467 if $perm->{check};
468
469 raise_perm_exc();
470 }
471
472 # initialize environment - must be called once at program startup
473 sub init {
474 my ($class, $type, %params) = @_;
475
476 $class = ref($class) || $class;
477
478 die "already initialized" if $pve_env;
479
480 die "unknown environment type" if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
481
482 $SIG{CHLD} = $worker_reaper;
483
484 # environment types
485 # cli ... command started fron command line
486 # pub ... access from public server (apache)
487 # priv ... access from private server (pvedaemon)
488 # ha ... access from HA resource manager agent (rgmanager)
489
490 my $self = {
491 user_cfg => {},
492 aclcache => {},
493 aclversion => undef,
494 type => $type,
495 };
496
497 bless $self, $class;
498
499 foreach my $p (keys %params) {
500 if ($p eq 'atfork') {
501 $self->{$p} = $params{$p};
502 } else {
503 die "unknown option '$p'";
504 }
505 }
506
507 $pve_env = $self;
508
509 my ($sysname, $nodename) = POSIX::uname();
510
511 $nodename =~ s/\..*$//; # strip domain part, if any
512
513 $self->{nodename} = $nodename;
514
515 return $self;
516 };
517
518 # get the singleton
519 sub get {
520
521 die "not initialized" if !$pve_env;
522
523 return $pve_env;
524 }
525
526 sub parse_params {
527 my ($self, $enable_upload) = @_;
528
529 if ($self->{request_rec}) {
530 my $cgi;
531 if ($enable_upload) {
532 $cgi = CGI->new($self->{request_rec});
533 } else {
534 # disable upload using empty upload_hook
535 $cgi = CGI->new($self->{request_rec}, sub {}, undef, 0);
536 }
537 $self->{cgi} = $cgi;
538 my $params = $cgi->Vars();
539 return PVE::Tools::decode_utf8_parameters($params);
540 } elsif ($self->{params}) {
541 return $self->{params};
542 } else {
543 die "no parameters registered";
544 }
545 }
546
547 sub get_upload_info {
548 my ($self, $param) = @_;
549
550 my $cgi = $self->{cgi};
551 die "CGI not initialized" if !$cgi;
552
553 my $pd = $cgi->param($param);
554 die "unable to get cgi parameter info\n" if !$pd;
555 my $info = $cgi->uploadInfo($pd);
556 die "unable to get cgi upload info\n" if !$info;
557
558 my $res = { %$info };
559
560 my $tmpfilename = $cgi->tmpFileName($pd);
561 die "unable to get cgi upload file name\n" if !$tmpfilename;
562 $res->{tmpfilename} = $tmpfilename;
563
564 #my $hndl = $cgi->upload($param);
565 #die "unable to get cgi upload handle\n" if !$hndl;
566 #$res->{handle} = $hndl->handle;
567
568 return $res;
569 }
570
571 # init_request - must be called before each RPC request
572 sub init_request {
573 my ($self, %params) = @_;
574
575 PVE::Cluster::cfs_update();
576
577 $self->{result_attributes} = {};
578
579 my $userconfig; # we use this for regression tests
580 foreach my $p (keys %params) {
581 if ($p eq 'userconfig') {
582 $userconfig = $params{$p};
583 } elsif ($p eq 'request_rec') {
584 # pass Apache2::RequestRec
585 $self->{request_rec} = $params{$p};
586 } elsif ($p eq 'params') {
587 $self->{params} = $params{$p};
588 } else {
589 die "unknown parameter '$p'";
590 }
591 }
592
593 eval {
594 $self->{aclcache} = {};
595 if ($userconfig) {
596 my $ucdata = PVE::Tools::file_get_contents($userconfig);
597 my $cfg = PVE::AccessControl::parse_user_config($userconfig, $ucdata);
598 $self->{user_cfg} = $cfg;
599 #print Dumper($cfg);
600 } else {
601 my $ucvers = PVE::Cluster::cfs_file_version('user.cfg');
602 if (!$self->{aclcache} || !defined($self->{aclversion}) ||
603 !defined($ucvers) || ($ucvers ne $self->{aclversion})) {
604 $self->{aclversion} = $ucvers;
605 my $cfg = PVE::Cluster::cfs_read_file('user.cfg');
606 $self->{user_cfg} = $cfg;
607 }
608 }
609 };
610 if (my $err = $@) {
611 $self->{user_cfg} = {};
612 die "Unable to load access control list: $err";
613 }
614 }
615
616 sub set_client_ip {
617 my ($self, $ip) = @_;
618
619 $self->{client_ip} = $ip;
620 }
621
622 sub get_client_ip {
623 my ($self) = @_;
624
625 return $self->{client_ip};
626 }
627
628 sub set_result_attrib {
629 my ($self, $key, $value) = @_;
630
631 $self->{result_attributes}->{$key} = $value;
632 }
633
634 sub get_result_attrib {
635 my ($self, $key) = @_;
636
637 return $self->{result_attributes}->{$key};
638 }
639
640 sub set_language {
641 my ($self, $lang) = @_;
642
643 # fixme: initialize I18N
644
645 $self->{language} = $lang;
646 }
647
648 sub get_language {
649 my ($self) = @_;
650
651 return $self->{language};
652 }
653
654 sub set_user {
655 my ($self, $user) = @_;
656
657 # fixme: get ACLs
658
659 $self->{user} = $user;
660 }
661
662 sub get_user {
663 my ($self) = @_;
664
665 die "user name not set\n" if !$self->{user};
666
667 return $self->{user};
668 }
669
670 # read/update list of active workers
671 # we move all finished tasks to the archive index,
672 # but keep aktive and most recent task in the active file.
673 # $nocheck ... consider $new_upid still running (avoid that
674 # we try to read the reult to early.
675 sub active_workers {
676 my ($new_upid, $nocheck) = @_;
677
678 my $lkfn = "/var/log/pve/tasks/.active.lock";
679
680 my $timeout = 10;
681
682 my $code = sub {
683
684 my $tasklist = PVE::INotify::read_file('active');
685
686 my @ta;
687 my $tlist = [];
688 my $thash = {}; # only list task once
689
690 my $check_task = sub {
691 my ($task, $running) = @_;
692
693 if ($running || PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart})) {
694 push @$tlist, $task;
695 } else {
696 delete $task->{pid};
697 push @ta, $task;
698 }
699 delete $task->{pstart};
700 };
701
702 foreach my $task (@$tasklist) {
703 my $upid = $task->{upid};
704 next if $thash->{$upid};
705 $thash->{$upid} = $task;
706 &$check_task($task);
707 }
708
709 if ($new_upid && !(my $task = $thash->{$new_upid})) {
710 $task = PVE::Tools::upid_decode($new_upid);
711 $task->{upid} = $new_upid;
712 $thash->{$new_upid} = $task;
713 &$check_task($task, $nocheck);
714 }
715
716
717 @ta = sort { $b->{starttime} cmp $a->{starttime} } @ta;
718
719 my $save = defined($new_upid);
720
721 foreach my $task (@ta) {
722 next if $task->{endtime};
723 $task->{endtime} = time();
724 $task->{status} = PVE::Tools::upid_read_status($task->{upid});
725 $save = 1;
726 }
727
728 my $archive = '';
729 my @arlist = ();
730 foreach my $task (@ta) {
731 if (!$task->{saved}) {
732 $archive .= sprintf("$task->{upid} %08X $task->{status}\n", $task->{endtime});
733 $save = 1;
734 push @arlist, $task;
735 $task->{saved} = 1;
736 }
737 }
738
739 if ($archive) {
740 my $size = 0;
741 my $filename = "/var/log/pve/tasks/index";
742 eval {
743 my $fh = IO::File->new($filename, '>>', 0644) ||
744 die "unable to open file '$filename' - $!\n";
745 PVE::Tools::safe_print($filename, $fh, $archive);
746 $size = -s $fh;
747 close($fh) ||
748 die "unable to close file '$filename' - $!\n";
749 };
750 my $err = $@;
751 if ($err) {
752 syslog('err', $err);
753 foreach my $task (@arlist) { # mark as not saved
754 $task->{saved} = 0;
755 }
756 }
757 my $maxsize = 50000; # about 1000 entries
758 if ($size > $maxsize) {
759 rename($filename, "$filename.1");
760 }
761 }
762
763 # we try to reduce the amount of data
764 # list all running tasks and task and a few others
765 # try to limit to 25 tasks
766 my $ctime = time();
767 my $max = 25 - scalar(@$tlist);
768 foreach my $task (@ta) {
769 last if $max <= 0;
770 push @$tlist, $task;
771 $max--;
772 }
773
774 PVE::INotify::write_file('active', $tlist) if $save;
775
776 return $tlist;
777 };
778
779 my $res = PVE::Tools::lock_file($lkfn, $timeout, $code);
780 die $@ if $@;
781
782 return $res;
783 }
784
785 my $kill_process_group = sub {
786 my ($pid, $pstart) = @_;
787
788 # send kill to process group (negative pid)
789 my $kpid = -$pid;
790
791 # always send signal to all pgrp members
792 kill(15, $kpid); # send TERM signal
793
794 # give max 5 seconds to shut down
795 for (my $i = 0; $i < 5; $i++) {
796 return if !PVE::ProcFSTools::check_process_running($pid, $pstart);
797 sleep (1);
798 }
799
800 # to be sure
801 kill(9, $kpid);
802 };
803
804 sub check_worker {
805 my ($upid, $killit) = @_;
806
807 my $task = PVE::Tools::upid_decode($upid);
808
809 my $running = PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart});
810
811 return 0 if !$running;
812
813 if ($killit) {
814 &$kill_process_group($task->{pid});
815 return 0;
816 }
817
818 return 1;
819 }
820
821 # start long running workers
822 # STDIN is redirected to /dev/null
823 # STDOUT,STDERR are redirected to the filename returned by upid_decode
824 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
825 sub fork_worker {
826 my ($self, $dtype, $id, $user, $function, $background) = @_;
827
828 $dtype = 'unknown' if !defined ($dtype);
829 $id = '' if !defined ($id);
830
831 $user = 'root@pve' if !defined ($user);
832
833 my $sync = ($self->{type} eq 'cli' && !$background) ? 1 : 0;
834
835 local $SIG{INT} =
836 local $SIG{QUIT} =
837 local $SIG{PIPE} =
838 local $SIG{TERM} = 'IGNORE';
839
840 my $starttime = time ();
841
842 my @psync = POSIX::pipe();
843 my @csync = POSIX::pipe();
844
845 my $node = $self->{nodename};
846
847 my $cpid = fork();
848 die "unable to fork worker - $!" if !defined($cpid);
849
850 my $workerpuid = $cpid ? $cpid : $$;
851
852 my $pstart = PVE::ProcFSTools::read_proc_starttime($workerpuid) ||
853 die "unable to read process start time";
854
855 my $upid = PVE::Tools::upid_encode ({
856 node => $node, pid => $workerpuid, pstart => $pstart,
857 starttime => $starttime, type => $dtype, id => $id, user => $user });
858
859 my $outfh;
860
861 if (!$cpid) { # child
862
863 $0 = "task $upid";
864
865 $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = sub { die "received interrupt\n"; };
866
867 $SIG{CHLD} = $SIG{PIPE} = 'DEFAULT';
868
869 # set sess/process group - we want to be able to kill the
870 # whole process group
871 POSIX::setsid();
872
873 POSIX::close ($psync[0]);
874 POSIX::close ($csync[1]);
875
876 $outfh = $sync ? $psync[1] : undef;
877
878 eval {
879 PVE::INotify::inotify_close();
880
881 if (my $atfork = $self->{atfork}) {
882 &$atfork();
883 }
884
885 # same algorythm as used inside SA
886 # STDIN = /dev/null
887 my $fd = fileno (STDIN);
888
889 if (!$sync) {
890 close STDIN;
891 POSIX::close(0) if $fd != 0;
892
893 die "unable to redirect STDIN - $!"
894 if !open(STDIN, "</dev/null");
895
896 $outfh = PVE::Tools::upid_open($upid);
897 }
898
899
900 # redirect STDOUT
901 $fd = fileno(STDOUT);
902 close STDOUT;
903 POSIX::close (1) if $fd != 1;
904
905 die "unable to redirect STDOUT - $!"
906 if !open(STDOUT, ">&", $outfh);
907
908 STDOUT->autoflush (1);
909
910 # redirect STDERR to STDOUT
911 $fd = fileno (STDERR);
912 close STDERR;
913 POSIX::close(2) if $fd != 2;
914
915 die "unable to redirect STDERR - $!"
916 if !open(STDERR, ">&1");
917
918 STDERR->autoflush(1);
919 };
920 if (my $err = $@) {
921 my $msg = "ERROR: $err";
922 POSIX::write($psync[1], $msg, length ($msg));
923 POSIX::close($psync[1]);
924 POSIX::_exit(1);
925 kill(-9, $$);
926 }
927
928 # sync with parent (signal that we are ready)
929 if ($sync) {
930 print "$upid\n";
931 } else {
932 POSIX::write($psync[1], $upid, length ($upid));
933 POSIX::close($psync[1]);
934 }
935
936 my $readbuf = '';
937 # sync with parent (wait until parent is ready)
938 POSIX::read($csync[0], $readbuf, 4096);
939 die "parent setup error\n" if $readbuf ne 'OK';
940
941 if ($self->{type} eq 'ha') {
942 print "task started by HA resource agent\n";
943 }
944 eval { &$function($upid); };
945 my $err = $@;
946 if ($err) {
947 chomp $err;
948 $err =~ s/\n/ /mg;
949 syslog('err', $err);
950 print STDERR "TASK ERROR: $err\n";
951 POSIX::_exit(-1);
952 } else {
953 print STDERR "TASK OK\n";
954 POSIX::_exit(0);
955 }
956 kill(-9, $$);
957 }
958
959 # parent
960
961 POSIX::close ($psync[1]);
962 POSIX::close ($csync[0]);
963
964 my $readbuf = '';
965 # sync with child (wait until child starts)
966 POSIX::read($psync[0], $readbuf, 4096);
967
968 if (!$sync) {
969 POSIX::close($psync[0]);
970 &$register_worker($cpid, $user, $upid);
971 } else {
972 chomp $readbuf;
973 }
974
975 eval {
976 die "got no worker upid - start worker failed\n" if !$readbuf;
977
978 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
979 die "starting worker failed: $1\n";
980 }
981
982 if ($readbuf ne $upid) {
983 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
984 }
985
986 if ($sync) {
987 $outfh = PVE::Tools::upid_open($upid);
988 }
989 };
990 my $err = $@;
991
992 if (!$err) {
993 my $msg = 'OK';
994 POSIX::write($csync[1], $msg, length ($msg));
995 POSIX::close($csync[1]);
996
997 } else {
998 POSIX::close($csync[1]);
999 kill(-9, $cpid); # make sure it gets killed
1000 die $err;
1001 }
1002
1003 PVE::Cluster::log_msg('info', $user, "starting task $upid");
1004
1005 my $tlist = active_workers($upid, $sync);
1006 PVE::Cluster::broadcast_tasklist($tlist);
1007
1008 my $res = 0;
1009
1010 if ($sync) {
1011 my $count;
1012 my $outbuf = '';
1013 my $int_count = 0;
1014 eval {
1015 local $SIG{INT} = local $SIG{QUIT} = local $SIG{TERM} = sub {
1016 # always send signal to all pgrp members
1017 my $kpid = -$cpid;
1018 if ($int_count < 3) {
1019 kill(15, $kpid); # send TERM signal
1020 } else {
1021 kill(9, $kpid); # send KILL signal
1022 }
1023 $int_count++;
1024 };
1025 local $SIG{PIPE} = sub { die "broken pipe\n"; };
1026
1027 my $select = new IO::Select;
1028 my $fh = IO::Handle->new_from_fd($psync[0], 'r');
1029 $select->add($fh);
1030
1031 while ($select->count) {
1032 my @handles = $select->can_read(1);
1033 if (scalar(@handles)) {
1034 my $count = sysread ($handles[0], $readbuf, 4096);
1035 if (!defined ($count)) {
1036 my $err = $!;
1037 die "sync pipe read error: $err\n";
1038 }
1039 last if $count == 0; # eof
1040
1041 $outbuf .= $readbuf;
1042 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
1043 my $line = $1;
1044 my $data = $2;
1045 if ($data =~ m/^TASK OK$/) {
1046 # skip
1047 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
1048 print STDERR "$1\n";
1049 } else {
1050 print $line;
1051 }
1052 if ($outfh) {
1053 print $outfh $line;
1054 $outfh->flush();
1055 }
1056 }
1057 } else {
1058 # some commands daemonize without closing stdout
1059 last if !PVE::ProcFSTools::check_process_running($cpid);
1060 }
1061 }
1062 };
1063 my $err = $@;
1064
1065 POSIX::close($psync[0]);
1066
1067 if ($outbuf) { # just to be sure
1068 print $outbuf;
1069 if ($outfh) {
1070 print $outfh $outbuf;
1071 }
1072 }
1073
1074 if ($err) {
1075 $err =~ s/\n/ /mg;
1076 print STDERR "$err\n";
1077 if ($outfh) {
1078 print $outfh "TASK ERROR: $err\n";
1079 }
1080 }
1081
1082 &$kill_process_group($cpid, $pstart); # make sure it gets killed
1083
1084 close($outfh);
1085
1086 waitpid($cpid, 0);
1087 $res = $?;
1088 &$log_task_result($upid, $user, $res);
1089 }
1090
1091 return wantarray ? ($upid, $res) : $upid;
1092 }
1093
1094 1;