Group.pm.in 44.3 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2005-2019 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23 24 25 26 27 28 29 30 31 32 33 34
#
package Group;

use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
@EXPORT = qw ( );

use libdb;
use libtestbed;
35
use EmulabConstants;
36
use emutil;
37
use User;
38 39 40 41
use English;
use Data::Dumper;
use File::Basename;
use overload ('""' => 'Stringify');
42
use vars qw($MEMBERLIST_FLAGS_UIDSONLY $MEMBERLIST_FLAGS_ALLUSERS
Russ Fish's avatar
Russ Fish committed
43
	    $MEMBERLIST_FLAGS_GETTRUST $MEMBERLIST_FLAGS_EXCLUDE_LEADER);
44 45

# Configure variables
46 47 48 49
my $TB		  = "@prefix@";
my $BOSSNODE      = "@BOSSNODE@";
my $CONTROL	  = "@USERNODE@";
my $TBOPS         = "@TBOPSEMAIL@";
50
my $TBAPPROVAL    = "@TBAPPROVALEMAIL@";
51 52 53 54
my $TBAUDIT       = "@TBAUDITEMAIL@";
my $TBBASE        = "@TBBASE@";
my $TBWWW         = "@TBWWW@";
my $MIN_UNIX_GID  = @MIN_UNIX_GID@;
55 56 57

# Cache of instances to avoid regenerating them.
my %groups    = ();
58
BEGIN { use emutil; emutil::AddCache(\%groups); }
59 60
my $debug      = 0;

61
# MemberList flags.
Russ Fish's avatar
Russ Fish committed
62 63 64 65
$MEMBERLIST_FLAGS_UIDSONLY	 = 0x01;
$MEMBERLIST_FLAGS_ALLUSERS	 = 0x02;
$MEMBERLIST_FLAGS_GETTRUST	 = 0x04;
$MEMBERLIST_FLAGS_EXCLUDE_LEADER = 0x08;
66

67 68 69 70 71 72 73 74 75 76 77 78 79
# Little helper and debug function.
sub mysystem($)
{
    my ($command) = @_;

    print STDERR "Running '$command'\n"
	if ($debug);
    return system($command);
}

#
# Lookup by idx.
#
80
sub Lookup($$;$)
81
{
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    my ($class, $arg1, $arg2) = @_;
    my $gid_idx;

    #
    # A single arg is either an index or a "pid,gid" or "pid/gid" string.
    #
    if (!defined($arg2)) {
	if ($arg1 =~ /^(\d*)$/) {
	    $gid_idx = $1;
	}
	elsif ($arg1 =~ /^([-\w]*),([-\w]*)$/ ||
	       $arg1 =~ /^([-\w]*)\/([-\w]*)$/) {
	    $arg1 = $1;
	    $arg2 = $2;
	}
	else {
	    return undef;
	}
    }
    elsif (! (($arg1 =~ /^[-\w]*$/) && ($arg2 =~ /^[-\w]*$/))) {
	return undef;
    }

    #
    # Two args means pid/gid lookup instead of gid_idx.
    #
    if (defined($arg2)) {
	my $groups_result =
	    DBQueryWarn("select gid_idx from groups ".
			"where pid='$arg1' and gid='$arg2'");

	return undef
	    if (! $groups_result || !$groups_result->numrows);

	($gid_idx) = $groups_result->fetchrow_array();
    }
118 119 120 121 122 123

    # Look in cache first
    return $groups{"$gid_idx"}
        if (exists($groups{"$gid_idx"}));
    
    my $query_result =
124
	DBQueryWarn("select * from groups where gid_idx='$gid_idx'");
125 126 127 128

    return undef
	if (!$query_result || !$query_result->numrows);

129 130 131
    my $self           = {};
    $self->{'GROUP'}   = $query_result->fetchrow_hashref();
    $self->{'PROJECT'} = undef;
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146

    bless($self, $class);
    
    # Add to cache. 
    $groups{"$gid_idx"} = $self;
    
    return $self;
}
# accessors
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'GROUP'}->{$_[1]}); }
sub pid($)	        { return field($_[0], "pid"); }
sub gid($)	        { return field($_[0], "gid"); }
sub pid_idx($)          { return field($_[0], "pid_idx"); }
sub gid_idx($)          { return field($_[0], "gid_idx"); }
sub leader($)           { return field($_[0], "leader"); }
147
sub leader_idx($)       { return field($_[0], "leader_idx"); }
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
sub created($)          { return field($_[0], "created"); }
sub description($)      { return field($_[0], "description"); }
sub unix_gid($)         { return field($_[0], "unix_gid"); }
sub unix_name($)        { return field($_[0], "unix_name"); }
sub expt_count($)       { return field($_[0], "expt_count"); }
sub expt_last($)        { return field($_[0], "expt_last"); }
sub wikiname($)         { return field($_[0], "wikiname"); }
sub mailman_password($) { return field($_[0], "mailman_password"); }

#
# Lookup given pid/gid. For backwards compat.
#
sub LookupByPidGid($$$)
{
    my ($class, $pid, $gid) = @_;

164
    return Group->Lookup($pid, $gid);
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
}

#
# Refresh a class instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

    return -1
	if (! ref($self));

    my $gid_idx = $self->gid_idx();
    
    my $query_result =
	DBQueryWarn("select * from groups where gid_idx=$gid_idx");

    return -1
	if (!$query_result || !$query_result->numrows);

    $self->{'GROUP'} = $query_result->fetchrow_hashref();

    return 0;
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $pid     = $self->pid();
    my $gid     = $self->gid();
    my $gid_idx = $self->gid_idx();
    my $pid_idx = $self->pid_idx();

    return "[Group: $pid/$gid, IDX: $pid_idx/$gid_idx]";
}

#
# Perform some updates ...
#
sub Update($$)
{
    my ($self, $argref) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $gid_idx = $self->gid_idx();

    my $query = "update groups set ".
	join(",", map("$_='" . $argref->{$_} . "'", keys(%{$argref})));

    $query .= " where gid_idx='$gid_idx'";

    return -1
	if (! DBQueryWarn($query));

    return Refresh($self);
}

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
#
# Class function to create new group and return object.
#
sub Create($$$$$$)
{
    my ($class, $project, $gid, $leader, $description, $unix_name) = @_;
    my $pid;
    my $pid_idx;
    
    #
    # Check that we can guarantee uniqueness of the unix group name.
    # 
    my $query_result =
	DBQueryFatal("select gid from groups ".
		     "where unix_name='$unix_name'");

    if ($query_result->numrows) {
	print "*** Could not form a unique Unix group name: $unix_name!\n";
	return undef;
    }

    # Every group gets a new unique index.
    my $gid_idx = TBGetUniqueIndex('next_gid');

    # If project is not defined, then creating initial project group.
    if (! $project) {
	$pid = $gid;
	$pid_idx = $gid_idx;
    }
    else {
	$pid = $project->pid();
	$pid_idx = $project->pid_idx();
    }

    #
    # Get me an unused unix gid. 
    #
    my $unix_gid;

    #
    # Start here, and keep going if the one picked from the DB just
    # happens to be in use (in the group file). Actually happens!
    #
    my $min_gid = $MIN_UNIX_GID;
    
    while (! defined($unix_gid)) {
	#
	# Get me an unused unix id. Nice query, eh? Basically, find
	# unused numbers by looking at existing numbers plus one, and
278 279 280 281
	# check to see if that number is taken. The point is to look
	# for holes since the space is only 16 bits, but this is really
	# ineffecient! Not really a problem with smallish number of groups
	# but terrible for 1000s!
282 283 284 285 286
	#
	$query_result =
	    DBQueryWarn("select g.unix_gid + 1 as start from groups as g ".
			"left outer join groups as r on ".
			"  g.unix_gid + 1 = r.unix_gid ".
287
			"where g.unix_gid>=$min_gid and ".
288 289 290 291 292 293
			"      g.unix_gid<50000 and ".
			"      r.unix_gid is null limit 1");

	return undef
	    if (! $query_result);

294 295
	my $unused;

296
	if (! $query_result->numrows) {
297 298 299 300
	    $unused = $min_gid;
	}
	else {
	    ($unused) = $query_result->fetchrow_array();
301 302 303 304 305
	}

	if (getgrgid($unused)) {
	    # Keep going.
	    $min_gid++;
306 307 308 309
	    if ($min_gid >= 50000) {
		print "*** WARNING: Could not find an unused unix_gid!\n";
		return undef;
	    }
310 311 312 313 314 315 316
	}
	else {
	    # Break out of loop.
	    $unix_gid = $unused;
	}
    }

317 318 319 320 321 322 323
    # And a UUID (universally unique identifier).
    my $uuid = NewUUID();
    if (!defined($uuid)) {
	print "*** WARNING: Could not generate a UUID!\n";
	return undef;
    }

324 325 326 327 328 329 330
    if (!DBQueryWarn("insert into groups set ".
		     " pid='$pid', gid='$gid', ".
		     " leader='" . $leader->uid() . "'," .
		     " leader_idx='" . $leader->uid_idx() . "'," .
		     " created=now(), ".
		     " description='$description', ".
		     " unix_name='$unix_name', ".
331
		     " gid_uuid='$uuid', ".
332 333 334 335 336 337
		     " gid_idx=$gid_idx, ".
		     " pid_idx=$pid_idx, ".
		     " unix_gid=$unix_gid")) {
	return undef;
    }

338 339 340
    if (! DBQueryWarn("insert into group_stats ".
		      "  (pid, gid, gid_idx, pid_idx, gid_uuid) ".
		      "values ('$pid','$gid',$gid_idx,$pid_idx,'$uuid')")) {
341 342 343 344 345 346 347 348 349 350 351
	DBQueryFatal("delete from groups where gid_idx='$gid_idx'");
	return undef;
    }
    my $newgroup = Group->Lookup($gid_idx);
    return undef
	if (! $newgroup);

    return $newgroup;
}

#
352
# Delete a group. This will eventually change to group archival.
353 354 355 356 357 358 359 360 361 362 363
#
sub Delete($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $gid_idx = $self->gid_idx();

364 365 366 367 368 369 370 371
    # Order matters, groups table should be last so we can repeat if failure.
    my @tables = ("group_policies", "group_stats", "groups");

    foreach my $table (@tables) {
	return -1
	    if (!DBQueryWarn("delete from $table where gid_idx='$gid_idx'"));
    }
    
372 373 374
    return 0;
}

375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
#
# Worker class method to edit group membership.
# Makes two passes, first checking consistency, then updating the DB.
#
sub EditGroup($$$$)
{
    my ($class, $group, $this_user, $argref, $usrerr_ref) = @_;

    my %mods;
    my $noreport;

    #
    # The default group membership cannot be changed, but the trust levels can.
    #
    my $defaultgroup = $group->IsProjectGroup();

    #
    # See if user is allowed to add non-members to group.
    # 
    my $grabusers = 0;
    if ($group->AccessCheck($this_user, TB_PROJECT_GROUPGRABUSERS())) {
	$grabusers = 1;
    }

    #
    # See if user is allowed to bestow group_root upon members of group.
    # 
    my $bestowgrouproot = 0;
    if ($group->AccessCheck($this_user, TB_PROJECT_BESTOWGROUPROOT())) {
	$bestowgrouproot = 1;
    }

    #
    # Grab the user list for the group. Provide a button selection of people
    # that can be removed. The group leader cannot be removed!
    # Do not include members that have not been approved
    # to main group either! This will force them to go through the approval
    # page first.
    #
    my @curmembers;
415 416 417
    if ($group->MemberList(\@curmembers, 
			   $MEMBERLIST_FLAGS_GETTRUST |
			   $MEMBERLIST_FLAGS_EXCLUDE_LEADER)) {
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
	$$usrerr_ref = "Error: Could not get member list for $group";
	return undef;
    }

    #
    # Grab the user list from the project. These are the people who can be
    # added. Do not include people in the above list, obviously! Do not
    # include members that have not been approved to main group either! This
    # will force them to go through the approval page first.
    #
    my @nonmembers;
    if ($group->NonMemberList(\@nonmembers)) {
	$$usrerr_ref = "Error: Could not get nonmember list for $group";
	return undef;
    }

    #
    # First pass does checks. Second pass does the real thing. 
    #
    my $g_pid = $group->pid();
    my $g_gid = $group->gid();
    my $target_user;
    my $target_idx;
    my $target_uid;
    my $oldtrust;
    my $newtrust;
    my $foo;
    my $bar;
    my $cmd;
    my $cmd_out;

    #
    # Go through the list of current members. For each one, check to see if
    # the checkbox for that person was checked. If not, delete the person
    # from the group membership. Otherwise, look to see if the trust level
    # has been changed.
    #
    if ($#curmembers>=0) {
	foreach $target_user (@curmembers) {
	    $target_uid = $target_user->uid();
	    $target_idx = $target_user->uid_idx();
	    $oldtrust   = $target_user->GetTempData();
	    $foo        = "change_$target_idx";

	    #
	    # Is member to be deleted?
	    # 
	    if (!$defaultgroup && !exists($argref->{$foo})) {
		# Yes.
		next;
	    }

	    #
	    # There should be a corresponding trust variable in the POST vars.
	    # Note that we construct the variable name and indirect to it.
	    #
	    $foo      = "U${target_idx}\$\$trust";
	    if (!exists($argref->{$foo}) || $argref->{$foo} eq "") {
		$$usrerr_ref = "Error: finding trust(1) for $target_uid";
		return undef;
	    }
	    $newtrust = $argref->{$foo};

	    if ($newtrust ne $Group::MemberShip::TRUSTSTRING_USER &&
		$newtrust ne $Group::MemberShip::TRUSTSTRING_LOCALROOT &&
		$newtrust ne $Group::MemberShip::TRUSTSTRING_GROUPROOT) {
		$$usrerr_ref = "Error: Invalid trust $newtrust for $target_uid";
		return undef;
	    }

	    #
	    # If the user is attempting to bestow group_root on a user who 
	    # did not previously have group_root, check to see if the operation is
	    # permitted.
	    #
	    if ($newtrust ne $oldtrust &&
		$newtrust eq $Group::MemberShip::TRUSTSTRING_GROUPROOT && 
		!$bestowgrouproot) {
		$$usrerr_ref = "Group: You do not have permission to bestow".
		    " group root trust to users in $g_pid/$g_gid!";
	    }

	    $group->Group::MemberShip::CheckTrustConsistency($target_user, 
							     $newtrust, 1);
	}
    }

    #
    # Go through the list of non members. For each one, check to see if
    # the checkbox for that person was checked. If so, add the person
    # to the group membership, with the trust level specified.
    # Only do this if user has permission to grab users. 
    #

    if ($grabusers && !$defaultgroup && $#nonmembers>=0) {
	foreach $target_user (@nonmembers) {
	    $target_uid = $target_user->uid();
	    $target_idx = $target_user->uid_idx();
516
	    $foo        = "add_$target_idx";
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631

	    if (exists($argref->{$foo}) && $argref->{$foo} eq "permit"){
		#
		# There should be a corresponding trust variable in the POST vars.
		# Note that we construct the variable name and indirect to it.
		#
		$bar = "U${target_idx}\$\$trust";
		if (!exists($argref->{$bar}) || $argref->{$bar} eq "") {
		    $$usrerr_ref = "Error: finding trust(2) for $target_uid";
		    return undef;
		}
		$newtrust = $argref->{$bar};

		if ($newtrust ne $Group::MemberShip::TRUSTSTRING_USER &&
		    $newtrust ne $Group::MemberShip::TRUSTSTRING_LOCALROOT &&
		    $newtrust ne $Group::MemberShip::TRUSTSTRING_GROUPROOT) {
		    $$usrerr_ref = "Error: " .
			"Invalid trust $newtrust for $target_uid";
		    return undef;
		}

		if ($newtrust eq $Group::MemberShip::TRUSTSTRING_GROUPROOT
		    && !$bestowgrouproot) {
		    $$usrerr_ref = "Error: You do not have permission to".
			" bestow group root trust to users in $g_pid/$g_gid!";
		    return undef;
		}
		$group->Group::MemberShip::CheckTrustConsistency($target_user,
								 $newtrust, 1);
	    }
	}
    }

    #
    # Now do the second pass, which makes the changes. 
    #

    ### STARTBUSY("Applying group membership changes");

    #
    # Go through the list of current members. For each one, check to see if
    # the checkbox for that person was checked. If not, delete the person
    # from the group membership. Otherwise, look to see if the trust level
    # has been changed.
    #
    if ($#curmembers>=0) {
	foreach $target_user (@curmembers) {
	    $target_uid = $target_user->uid();
	    $target_idx = $target_user->uid_idx();
	    $oldtrust   = $target_user->GetTempData();
	    $foo        = "change_$target_idx";

	    if (!$defaultgroup && !exists($argref->{$foo})) {
		$cmd = "modgroups -r $g_pid:$g_gid $target_uid";
		##print $cmd . "\n";
		$cmd_out = `$cmd`;
		if ($?) {
		    $$usrerr_ref = "Error: " . $cmd_out;
		    return undef;
		}
	    }
	    #
	    # There should be a corresponding trust variable in the POST vars.
	    # Note that we construct the variable name and indirect to it.
	    #
	    $foo      = "U${target_idx}\$\$trust";
	    $newtrust = $argref->{$foo};

	    if ($oldtrust ne $newtrust) {
		$cmd = "modgroups -m $g_pid:$g_gid:$newtrust $target_uid";
		##print $cmd . "\n";
		$cmd_out = `$cmd`;
		if ($?) {		
		    $$usrerr_ref = "Error: " . $cmd_out;
		    return undef;
		}
	    }
	}
    }

    #
    # Go through the list of non members. For each one, check to see if
    # the checkbox for that person was checked. If so, add the person
    # to the group membership, with the trust level specified.
    #

    if ($grabusers && !$defaultgroup && $#nonmembers>=0) {
	foreach $target_user (@nonmembers) {
	    $target_uid = $target_user->uid();
	    $target_idx = $target_user->uid_idx();
	    $foo        = "add_$target_idx";    

	    if (exists($argref->{$foo}) && $argref->{$foo} eq "permit"){
		#
		# There should be a corresponding trust variable in the POST vars.
		# Note that we construct the variable name and indirect to it.
		#
		$bar      = "U${target_idx}\$\$trust";
		$newtrust = $argref->{$bar};

		$cmd = "modgroups -a $g_pid:$g_gid:$newtrust $target_uid";
		##print $cmd . "\n";
		$cmd_out = `$cmd`;
		if ($?) {
		    $$usrerr_ref = "Error: " . $cmd_out;
		    return undef;
		}

	    }
	}
    }

    return 1;
}

632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
#
# Generic function to look up some table values given a set of desired
# fields and some conditions. Pretty simple, not widely useful, but it
# helps to avoid spreading queries around then we need to. 
#
sub TableLookUp($$$;$)
{
    my ($self, $table, $fields, $conditions) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));
    
    my $gid_idx = $self->gid_idx();

    if (defined($conditions) && "$conditions" ne "") {
	$conditions = "and ($conditions)";
    }
    else {
	$conditions = "";
    }

    return DBQueryWarn("select distinct $fields from $table ".
		       "where gid_idx='$gid_idx' $conditions");
}

#
# Ditto for update.
#
sub TableUpdate($$$;$)
{
    my ($self, $table, $sets, $conditions) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    if (ref($sets) eq "HASH") {
	$sets = join(",", map("$_='" . $sets->{$_} . "'", keys(%{$sets})));
    }
    my $gid_idx = $self->gid_idx();

    if (defined($conditions) && "$conditions" ne "") {
	$conditions = "and ($conditions)";
    }
    else {
	$conditions = "";
    }

    return 0
	if (DBQueryWarn("update $table set $sets ".
			"where gid_idx='$gid_idx' $conditions"));
    return -1;
}

687 688 689 690 691 692 693 694 695 696
#
# The basis of access permissions; what is the users trust level in the group.
#
sub Trust($$)
{
    my ($self, $user) = @_;
    
    #
    # User must be active to be trusted.
    #
697
    return PROJMEMBERTRUST_NONE()
698 699 700 701 702 703 704 705 706 707
	if ($user->status() ne USERSTATUS_ACTIVE());

    #
    # Must be a member of the group.
    #
    my $membership = $self->LookupUser($user);

    #
    # No membership is the same as no trust. True? Maybe an error instead?
    #
708
    return PROJMEMBERTRUST_NONE()
709 710 711 712 713
	if (!defined($membership));
    
    return TBTrustConvert($membership->trust());
}

714 715 716 717 718 719
#
# Check permissions.
#
sub AccessCheck($$$)
{
    my ($self, $user, $access_type) = @_;
720 721
    my $mintrust;
    
722
    # Must be a real reference. 
723
    return 0
724 725
	if (! ref($self));

726 727 728 729
    my $pid = $self->pid();
    my $gid = $self->gid();
    my $uid = $user->uid();

730 731
    if ($access_type < TB_PROJECT_MIN() ||
	$access_type > TB_PROJECT_MAX()) {
732 733 734
	print "*** Invalid access type: $access_type!\n";
	return 0;
    }
735 736
    # Admins do whatever they want. Treat leadgroup special though since
    # the user has to actually be a member of the project, not just an admin.
737
    return 1
738
	if ($user->IsAdmin() && $access_type != TB_PROJECT_LEADGROUP());
739

740 741
    if ($access_type == TB_PROJECT_READINFO()) {
	$mintrust = PROJMEMBERTRUST_USER();
742
    }
743 744
    elsif ($access_type == TB_PROJECT_MAKEGROUP() ||
	   $access_type == TB_PROJECT_DELGROUP()) {
745 746 747 748 749 750 751 752 753
	#
	# Project leader can always do this
	#
	if ($access_type == TB_PROJECT_DELGROUP()) {
	    my $project = $self->GetProject();
	    my $leader  = $self->GetLeader();
	    return 1
		if ($user->SameUser($leader));
	}
754
	$mintrust = PROJMEMBERTRUST_GROUPROOT();
755
    }
756
    elsif ($access_type == TB_PROJECT_LEADGROUP()) {
757 758 759
	#
	# Allow mere user (in default group) to lead a subgroup.
	# 
760
	$mintrust = PROJMEMBERTRUST_USER();
761
    }
762 763
    elsif ($access_type == TB_PROJECT_MAKEOSID() ||
	   $access_type == TB_PROJECT_MAKEIMAGEID() ||
764 765
	   $access_type == TB_PROJECT_CREATEEXPT() ||
	   $access_type == TB_PROJECT_CREATELEASE()) {
766
	$mintrust = PROJMEMBERTRUST_LOCALROOT();
767
    }
768 769
    elsif ($access_type == TB_PROJECT_ADDUSER() ||
	   $access_type == TB_PROJECT_EDITGROUP()) {
770 771 772 773
	#
	# If user is project_root or group_root in default group, 
	# allow them to add/edit/remove users in any group.
	#
774
	if (TBMinTrust($self->Trust($user), PROJMEMBERTRUST_GROUPROOT())) {
775 776 777 778 779 780
	    return 1;
	}
	#
	# Otherwise, editing a group requires group_root 
	# in that group.
	#	
781
	$mintrust = PROJMEMBERTRUST_GROUPROOT();
782
    }
783
    elsif ($access_type == TB_PROJECT_BESTOWGROUPROOT()) {
784 785 786 787
	#
	# If user is project_root, 
	# allow them to bestow group_root in any group.
	#
788
	if (TBMinTrust($self->Trust($user), PROJMEMBERTRUST_PROJROOT())) {
789 790 791
	    return 1;
	}

792
	if ($gid eq $pid)  {
793 794 795 796 797 798 799 800 801 802 803 804
	    #
	    # Only project_root can bestow group_root in default group, 
	    # and we already established that they are not project_root,
	    # so fail.
	    #
	    return 0;
	}
	else {
	    #
	    # Non-default group.
	    # group_root in default group may bestow group_root.
	    #
805
	    if (TBMinTrust($self->Trust($user), PROJMEMBERTRUST_GROUPROOT())) {
806 807 808 809 810 811 812
		return 1;
	    }

	    #
	    # group_root in the group in question may also bestow
	    # group_root.
	    #
813
	    $mintrust = PROJMEMBERTRUST_GROUPROOT();
814 815
	}
    }
816
    elsif ($access_type == TB_PROJECT_GROUPGRABUSERS()) {
817 818 819 820
	#
	# Only project_root or group_root in default group
	# may grab (involuntarily add) users into groups.
	#
821 822 823
	if (! $self->IsProjectGroup()) {
	    return $self->GetProject()->AccessCheck($user, $access_type);
	}
824
	$mintrust = PROJMEMBERTRUST_GROUPROOT();
825
    }
826
    elsif ($access_type == TB_PROJECT_DELUSER()) {
827
	$mintrust = PROJMEMBERTRUST_GROUPROOT();
828
    }
829 830 831 832 833
    else {
	print "*** Invalid access type: $access_type!\n";
	return 0;
    }
    return TBMinTrust($self->Trust($user), $mintrust);
834 835
}

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
#
# Change the leader for a group.
#
sub ChangeLeader($$)
{
    my ($self, $leader) = @_;

    # Must be a real reference. 
    return -1
	if (! (ref($self) && ref($leader)));

    my %args = ();
    $args{'leader'}     = $leader->uid();
    $args{'leader_idx'} = $leader->uid_idx();
    return $self->Update(\%args);
}

853 854 855 856 857 858 859 860 861 862 863
#
# Add a user to the group
#
sub AddMemberShip($$;$)
{
    my ($self, $user, $trust) = @_;

    # Must be a real reference. 
    return -1
	if (! (ref($self) && ref($user)));

864 865 866 867 868 869
    my $membership = $self->LookupUser($user);

    if (defined($membership)) {
	print "*** AddMemberShip: $user is already a member of $self!\n";
	return -1;
    }
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
    return Group::MemberShip->NewMemberShip($self, $user, $trust);
}

#
# Remove a user from a group
#
sub DeleteMemberShip($$)
{
    my ($self, $user) = @_;

    # Must be a real reference. 
    return -1
	if (! (ref($self) && ref($user)));

    return Group::MemberShip->DeleteMemberShip($self, $user);
}

887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
#
# Send email notification of user joining a group.
#
sub SendJoinEmail($$)
{
    my ($self, $user) = @_;
    # Must be a real reference. 
    return -1
	if (! (ref($self) && ref($user)));

    #
    # Grab user info.
    #
    my $usr_email   = $user->email();
    my $usr_URL     = $user->URL();
    my $usr_addr    = $user->addr();
    my $usr_addr2   = $user->addr2();
    my $usr_city    = $user->city();
    my $usr_state   = $user->state();
    my $usr_zip	    = $user->zip();
    my $usr_country = $user->country();
    my $usr_name    = $user->name();
    my $usr_phone   = $user->phone();
    my $usr_title   = $user->title();
    my $usr_affil   = $user->affil();
    my $uid_idx     = $user->uid_idx();
    my $uid         = $user->uid();
914 915
    my $wanted_sslcert = (defined($user->initial_passphrase()) ?
			  "Yes" : "No");
916 917 918 919 920 921 922 923 924

    # And leader info
    my $leader      = $self->GetLeader();
    my $leader_name = $leader->name();
    my $leader_email= $leader->email();
    my $leader_uid  = $leader->uid();
    my $allleaders  = $self->LeaderMailList();
    my $pid         = $self->pid();
    my $gid         = $self->gid();
925 926 927 928 929 930

    $usr_addr2 = ""
	if (!defined($usr_addr2));
    $usr_URL = ""
	if (!defined($usr_URL));

931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
    my $project = $self->GetProject();
    my $from    = "$usr_name '$uid' <$usr_email>";
    my $message =
	"$usr_name is trying to join your group $gid in project $pid.".
	"\n".
	"\n".
	"Contact Info:\n".
	"Name:            $usr_name\n".
	"Login ID:        $uid\n".
	"Email:           $usr_email\n".
	"Affiliation:     $usr_affil\n".
	"Address 1:       $usr_addr\n".
	"Address 2:       $usr_addr2\n".
	"City:            $usr_city\n".
	"State:           $usr_state\n".
	"ZIP/Postal Code: $usr_zip\n".
	"Country:         $usr_country\n";

949 950
    if ($project->isAPT() || $project->isCloud() ||
	$project->isPNet() || $project->isPowder()) {
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
	my $url = $project->wwwBase() . "/approveuser.php?uid=$uid&pid=$pid";
	    
	$message .=
	    "\n".
	    "You can approve or reject this user:\n\n".
	    "Approve:  ${url}&action=approve\n".
	    "or\n".
	    "Deny:     ${url}&action=deny\n".
	    "\n".
	    "Thanks\n";
	$from = $project->ApprovalEmailAddress();
    }
    else {
	$message .= 
	    "Phone:           $usr_phone\n".
	    "User URL:        $usr_URL\n".
	    "Job Title:       $usr_title\n".
	    "SSL Cert:        $wanted_sslcert\n".
	    "\n".
	    "Please return to $TBWWW,\n".
	    "log in, select the 'New User Approval' page, and enter your\n".
	    "decision regarding ${usr_name}'s membership in your project.\n".
	    "\n".
	    "Thanks,\n".
	    "Testbed Operations\n";
    }
    $project->SendEmail("$leader_name '$leader_uid' <$leader_email>",
			"$uid $pid Project Join Request",
			$message, $from, "CC: $allleaders");
980 981 982 983

    return 0;
}

984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
#
# Send email notifying of initial approval testbed approval in a group.
#
sub SendApprovalEmail($$$)
{
    my ($self, $this_user, $target_user) = @_;

    # Must be a real reference. 
    return -1
	if (! (ref($self) && ref($this_user) && ref($target_user)));

    my $usr_email   = $target_user->email();
    my $usr_name    = $target_user->name();
    my $usr_uid     = $target_user->uid();
    my $this_name   = $this_user->name();
    my $this_email  = $this_user->email();
    my $pid         = $self->pid();
    my $gid         = $self->gid();
    my $allleaders  = $self->LeaderMailList();
    my $membership  = $self->LookupUser($target_user);
1004
    my $project     = $self->GetProject();
1005 1006 1007 1008 1009

    return -1
	if (!defined($membership));

    my $trust = $membership->trust();
1010 1011 1012
    my $message = "This message is to notify you that you have been approved\n".
	"as a member of ";
    my $subject = "Membership Approved in '$pid/$gid'";
1013

1014 1015
    if ($project->isAPT() || $project->isCloud() ||
	$project->isPNet() || $project->isPowder()) {
1016 1017 1018 1019
	my $helpurl  = $project->Brand()->UsersGroupURL();
	
	$message .= "project $pid.\n\n";
	$message .= "Please be sure to join the Help Forum at $helpurl";
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
	$subject  = "Membership Approved in Project $pid";
    }
    else {
	$message .= "$pid/$gid with '$trust' permission.";
    }
    $project->AnonSendEmail("$usr_name '$usr_uid' <$usr_email>",
			    $subject,
			    "$message\n".
			    "\n".
			    "Thanks\n",
			    $project->ApprovalEmailAddress(),
			    "CC: $allleaders\n".
			    "Bcc: $TBAUDIT");
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075

    return 0;
}

sub SendTrustChangeEmail($$$)
{
    my ($self, $this_user, $target_user) = @_;

    # Must be a real reference. 
    return -1
	if (! (ref($self) && ref($this_user) && ref($target_user)));

    my $usr_email   = $target_user->email();
    my $usr_name    = $target_user->name();
    my $usr_uid     = $target_user->uid();
    my $this_name   = $this_user->name();
    my $this_email  = $this_user->email();
    my $pid         = $self->pid();
    my $gid         = $self->gid();
    my $allleaders  = $self->LeaderMailList();
    my $membership  = $self->LookupUser($target_user);

    return -1
	if (!defined($membership));

    my $trust = $membership->trust();

    SENDMAIL("$usr_name '$usr_uid' <$usr_email>",
             "Membership Change in '$pid/$gid' ",
	     "\n".
	     "This message is to notify you that your permission in $pid/$gid".
	     "\n".
	     "has been changed to '$trust'\n".
             "\n\n".
             "Thanks,\n".
             "Testbed Operations\n",
             "$this_name <$this_email>",
	     "CC: $allleaders\n".
	     "Bcc: $TBAUDIT");

    return 0;
}

1076 1077 1078 1079 1080 1081 1082
#
# Lookup user membership in this group
#
sub LookupUser($$)
{
    my ($self, $user) = @_;

1083 1084 1085 1086
    # Must be a real reference. 
    return undef
	if (! (ref($self) && ref($user)));

1087 1088 1089
    return Group::MemberShip->LookupUser($self, $user);
}

1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
#
# Is this group the default project group. Returns boolean.
#
sub IsProjectGroup($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return 0
	if (! ref($self));

    return $self->pid_idx() == $self->gid_idx();
}

#
# Return (and cache) the project for a group.
#
sub GetProject($)
{
    my ($self) = @_;
Mike Hibler's avatar
Mike Hibler committed
1110
    require Project;
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173

    # Must be a real reference. 
    return undef
	if (! ref($self));

    return $self->{'PROJECT'}
        if (defined($self->{'PROJECT'}));

    $self->{'PROJECT'} = Project->Lookup($self->pid_idx());
    return $self->{'PROJECT'};
}

#
# Is the user the group leader.
#
sub IsLeader($$)
{
    my ($self, $user) = @_;

    # Must be a real reference. 
    return 0
	if (! (ref($self) && ref($user)));

    return $self->leader_idx() == $user->uid_idx();
}

#
# Return user object for leader.
#
sub GetLeader($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return undef
	if (! ref($self));

    return User->Lookup($self->leader_idx());
}

#
# Return a list of leaders (proj/group roots) in the format of an
# email address list.
#
sub LeaderMailList($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return undef
	if (! ref($self));

    my $gid_idx   = $self->gid_idx();
    my $projroot  = $Group::MemberShip::TRUSTSTRING_PROJROOT;
    my $grouproot = $Group::MemberShip::TRUSTSTRING_GROUPROOT;
    my $mailstr   = "";
    
    my $query_result =
	DBQueryFatal("select distinct usr_name,u.uid,usr_email ".
		     "  from users as u ".
		     "left join group_membership as gm on ".
		     "     gm.uid_idx=u.uid_idx ".
		     "where gid_idx='$gid_idx' and ".
1174
		     "      (trust='$projroot' or trust='$grouproot')");
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184

    while (my ($name,$uid,$email) = $query_result->fetchrow_array()) {
	$mailstr .= ", "
	    if ($mailstr ne "");

	$mailstr .= '"' . $name . " (". $uid . ")\" <". $email . ">";
    }
    return $mailstr;
}

1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
#
# Return list of members in this group, by specific trust.
#
sub MemberList($$;$$)
{
    my ($self, $prval, $flags, $desired_trust) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    $flags = 0
	if (!defined($flags));

    my $gid_idx    = $self->gid_idx();
    my $pid_idx    = $self->pid_idx();
    my @result     = ();
    my $uids_only  = ($flags & $MEMBERLIST_FLAGS_UIDSONLY ? 1 : 0);
1203
    my $gettrust   = ($flags & $MEMBERLIST_FLAGS_GETTRUST ? 1 : 0);
Russ Fish's avatar
Russ Fish committed
1204
    my $exclude_leader = ($flags & $MEMBERLIST_FLAGS_EXCLUDE_LEADER ? 1 : 0);
1205 1206
    my $trust_clause;

1207 1208 1209 1210 1211 1212 1213
    my $leader	    = $self->GetLeader();
    my $leader_idx;
    # There will be no leader during approveproject/Destroy.
    if (defined($leader)) {
	$leader_idx = $leader->uid_idx();
    }

1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
    if (defined($desired_trust)) {
	$trust_clause = "and trust='$desired_trust'"
    }
    elsif ($flags & $MEMBERLIST_FLAGS_ALLUSERS) {
	$trust_clause = "";
    }
    else {
	$trust_clause = "and trust!='none'"
    }

    my $query_result =
1225
	DBQueryWarn("select distinct m.uid_idx,m.uid,m.trust ".
1226 1227 1228 1229 1230 1231
		    "   from group_membership as m ".
		    "where m.pid_idx='$pid_idx' and ".
		    "      m.gid_idx='$gid_idx' $trust_clause");

    return -1
	if (!$query_result);
1232

1233 1234
    while (my ($uid_idx, $uid, $trust) = $query_result->fetchrow_array()) {

1235
	if ($exclude_leader && defined($leader) && $leader_idx == $uid_idx) {
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
	    next;
	}
	
	if ($uids_only) {
	    push(@result, $uid);
	    next;
	}
	
	my $user = User->Lookup($uid_idx);
	if (!defined($user)) {
	    print "Group::Memberlist: Could not map $uid_idx to object\n";
	    return undef;
	}
	if ($gettrust) {
	    # So caller can get this with GetTempData.
	    $user->SetTempData($trust);
	}
	push(@result, $user);
    }
    @$prval = @result;
    return 0;
}

#
# Grab the user list from the project. These are the people who can be
# added. Do not include people in the above list, obviously! Do not
# include members that have not been approved to main group either! This
# will force them to go through the approval page first.
#
sub NonMemberList($$;$)
{
    my ($self, $prval, $flags) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    $flags = 0
	if (!defined($flags));

    my $gid_idx    = $self->gid_idx();
    my $pid_idx    = $self->pid_idx();
    my @result     = ();
    my $uids_only  = ($flags & $MEMBERLIST_FLAGS_UIDSONLY ? 1 : 0);

    my $query_result =
	DBQueryFatal("select m.uid_idx from group_membership as m ".
		     "left join group_membership as a on ".
		     "     a.uid_idx=m.uid_idx and ".
		     "     a.pid_idx=m.pid_idx and a.gid_idx='$gid_idx' ".
		     "where m.pid_idx='$pid_idx' and ".
		     "      m.gid_idx=m.pid_idx and a.uid_idx is NULL ".
		     "      and m.trust!='none'");

    return -1
	if (!$query_result);

    while (my ($uid_idx, $uid, $trust) = $query_result->fetchrow_array()) {
1294
	if ($uids_only) {
1295
	    push(@result, $uid);
1296 1297 1298 1299 1300
	    next;
	}
	
	my $user = User->Lookup($uid_idx);
	if (!defined($user)) {
1301
	    print "Group::NonMemberList: Could not map $uid_idx to object\n";
1302 1303 1304 1305 1306 1307 1308
	    return undef;
	}
	push(@result, $user);
    }
    @$prval = @result;
    return 0;
}
1309

1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
#
# Update the aggregate stats.
#
sub UpdateStats($$$$$)
{
    my ($self, $mode, $duration, $pnodes, $vnodes) = @_;
	
    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $gid_idx = $self->gid_idx();

    DBQueryWarn("update group_stats ".
		"set expt${mode}_count=expt${mode}_count+1, ".
		"    expt${mode}_last=now(), ".
		"    allexpt_duration=allexpt_duration+${duration}, ".
		"    allexpt_vnodes=allexpt_vnodes+${vnodes}, ".
		"    allexpt_pnodes=allexpt_pnodes+${pnodes}, ".
		"    allexpt_vnode_duration=".
		"        allexpt_vnode_duration+($vnodes * ${duration}), ".
		"    allexpt_pnode_duration=".
		"        allexpt_pnode_duration+($pnodes * ${duration}) ".
		"where gid_idx='$gid_idx'");

1335
    if ($mode eq TBDB_STATS_SWAPIN() || $mode eq TBDB_STATS_START()) {
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
	DBQueryWarn("update groups set ".
		    " expt_last=now(),expt_count=expt_count+1 ".
		    "where gid_idx='$gid_idx'");
    }
    $self->Refresh();

    return 0;
}

#
# Bump last activity
#
sub BumpActivity($)
{
    my ($self) = @_;
	
    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $gid_idx = $self->gid_idx();
    
    DBQueryWarn("update group_stats set last_activity=now() ".
		"where gid_idx='$gid_idx'");

    return 0;
}

1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
#
# Check to see if a gid is valid.
#
sub ValidGID($$)
{
    my ($class, $gid) = @_;

    return TBcheck_dbslot($gid, "groups", "gid",
			  TBDB_CHECKDBSLOT_WARN()|
			  TBDB_CHECKDBSLOT_ERROR());
}

1376 1377 1378 1379 1380
############################################################################

package Group::MemberShip;
use libdb;
use libtestbed;
1381
use EmulabConstants;
1382 1383
use English;
use overload ('""' => 'Stringify');
1384 1385 1386 1387
use vars qw($TRUSTSTRING_NONE $TRUSTSTRING_USER
	    $TRUSTSTRING_LOCALROOT $TRUSTSTRING_GROUPROOT
	    $TRUSTSTRING_PROJROOT
	    @EXPORT_OK);
1388 1389

# Constants for membership.
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
$TRUSTSTRING_NONE		= "none";
$TRUSTSTRING_USER		= "user";
$TRUSTSTRING_LOCALROOT		= "local_root";
$TRUSTSTRING_GROUPROOT		= "group_root";
$TRUSTSTRING_PROJROOT		= "project_root";

# Why, why, why?
@EXPORT_OK = qw($TRUSTSTRING_NONE $TRUSTSTRING_USER
		$TRUSTSTRING_LOCALROOT $TRUSTSTRING_GROUPROOT
		$TRUSTSTRING_PROJROOT);
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456

my @alltrustvals = ($TRUSTSTRING_NONE, $TRUSTSTRING_USER,
		    $TRUSTSTRING_LOCALROOT, $TRUSTSTRING_GROUPROOT,
		    $TRUSTSTRING_PROJROOT);

# Cache of instances to avoid regenerating them.
my %membership = ();

#
# Lookup user membership in a group. Group and User are references. Hmm ...
#
sub LookupUser($$$)
{
    my ($class, $group, $user) = @_;

    # Must be a real reference. 
    return -1
	if (! (ref($group) && ref($user)));

    my $pid_idx = $group->pid_idx();
    my $gid_idx = $group->gid_idx();
    my $uid_idx = $user->uid_idx();

    # Look in cache first
    return $membership{"$uid_idx:$gid_idx"}
        if (exists($membership{"$uid_idx:$gid_idx"}));
    
    my $query_result =
	DBQueryWarn("select * from group_membership ".
		    "where uid_idx=$uid_idx and gid_idx=$gid_idx");

    return undef
	if (!$query_result || !$query_result->numrows);

    my $self              = {};
    $self->{'MEMBERSHIP'} = $query_result->fetchrow_hashref();
    $self->{'GROUP'}      = $group;
    $self->{'USER'}       = $user;

    bless($self, $class);
    
    # Add to cache. 
    $membership{"$uid_idx:$gid_idx"} = $self;
    
    return $self;
}
# accessors
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'MEMBERSHIP'}->{$_[1]});}
sub uid($)	        { return field($_[0], "uid"); }
sub pid($)	        { return field($_[0], "pid"); }
sub gid($)	        { return field($_[0], "gid"); }
sub uid_idx($)          { return field($_[0], "uid_idx"); }
sub pid_idx($)          { return field($_[0], "pid_idx"); }
sub gid_idx($)          { return field($_[0], "gid_idx"); }
sub trust($)            { return field($_[0], "trust"); }
sub date_applied($)     { return field($_[0], "date_applied"); }
sub date_approved($)    { return field($_[0], "date_approved"); }
Leigh Stoller's avatar
Leigh Stoller committed
1457
sub group($)            { return $_[0]->{'GROUP'}; }
1458 1459 1460
sub user($)             { return $_[0]->{'USER'}; }
sub IsApproved($)       { return $_[0]->trust() eq $TRUSTSTRING_NONE ? 0 : 1; }
    
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
#
# Is user trust in the group at least equal to the supplied trust
#
sub MinTrust($$)
{
    my ($self, $trust) = @_;

    return TBMinTrust(TBTrustConvert($self->trust()), TBTrustConvert($trust));
}

1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
#
# Refresh a class instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

    return -1
	if (! ref($self));

    my $uid_idx = $self->uid_idx();
    my $gid_idx = $self->gid_idx();

    my $query_result =
	DBQueryWarn("select * from group_membership ".
		    "where uid_idx=$uid_idx and gid_idx=$gid_idx");

    return -1
	if (!$query_result || !$query_result->numrows);

    $self->{'MEMBERSHIP'} = $query_result->fetchrow_hashref();

    return 0;
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $uid     = $self->uid();
    my $pid     = $self->pid();
    my $gid     = $self->gid();
    my $uid_idx = $self->uid_idx();
    my $pid_idx = $self->pid_idx();
    my $gid_idx = $self->gid_idx();
    my $trust   = $self->trust();

    return "[MemberShip: $uid/$trust/$pid/$gid]";
}

#
# Perform some updates ...
#
sub Update($$)
{
    my ($self, $argref) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $uid_idx = $self->uid_idx();
    my $gid_idx = $self->gid_idx();

    my $query = "update group_membership set ".
	join(",", map("$_='" . $argref->{$_} . "'", keys(%{$argref})));

    $query .= " where gid_idx='$gid_idx' and uid_idx='$uid_idx'";

    return -1
	if (! DBQueryWarn($query));

    return Refresh($self);
}

#
# Create new membership in a group. This is a "class" method.
#
sub NewMemberShip($$$;$)
{
    my ($class, $group, $user, $trust) = @_;
    my $clause = "";
    
    # Must be a real reference. 
    return -1
	if (! (ref($group) && ref($user)));

    my $uid     = $user->uid();
    my $pid     = $group->pid();
    my $gid     = $group->gid();
    my $uid_idx = $user->uid_idx();
    my $pid_idx = $group->pid_idx();
    my $gid_idx = $group->gid_idx();

    $trust = $TRUSTSTRING_NONE
	if (!defined($trust));
    
    # Sanity check.
    if (! grep {$_ eq $trust} @alltrustvals) {
	print STDERR "*** NewMemberShip: Not a valid trust: $trust\n";
	return -1;
    }

    # If current trust is none, then requesting membership.
    $clause = ", date_approved=now() "
	if ($trust ne $TRUSTSTRING_NONE);

    DBQueryWarn("insert into group_membership set ".
		"     uid='$uid', uid_idx=$uid_idx, ".
		"     pid='$pid', pid_idx=$pid_idx, ".
		"     gid='$gid', gid_idx=$gid_idx, ".
		"     trust='$trust', ".
		"     date_applied=now() $clause ")
	or return -1;

Leigh Stoller's avatar
Leigh Stoller committed
1579 1580 1581
    # Mark as needing an update.
    $user->BumpModified();

1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
    return 0;
}

#
# Delete membership from a group. This is a "class" method.
#
sub DeleteMemberShip($$$)
{
    my ($class, $group, $user) = @_;
    my $clause = "";
    
    # Must be a real reference. 
    return -1
	if (! (ref($group) && ref($user)));

    my $uid     = $user->uid();
    my $pid     = $group->pid();
    my $gid     = $group->gid();
    my $uid_idx = $user->uid_idx();
    my $pid_idx = $group->pid_idx();
    my $gid_idx = $group->gid_idx();

    # Remove from cache.
    delete($membership{"$uid_idx:$gid_idx"})
	if (exists($membership{"$uid_idx:$gid_idx"}));

    DBQueryWarn("delete from group_membership ".
		"where gid_idx='$gid_idx' and uid_idx='$uid_idx'")
	or return -1;

Leigh Stoller's avatar
Leigh Stoller committed
1612 1613 1614
    # Mark as needing an update.
    $user->BumpModified();

1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
    return 0;
}

#
# Modify a membership trust value.
#
sub ModifyTrust($$)
{
    my ($self, $trust) = @_;
    my $clause = "";

    # Must be a real reference. 
    return -1
	if (! ref($self));

    # Sanity check.
    if (! grep {$_ eq $trust} @alltrustvals) {
	print STDERR "*** ModifyTrust: Not a valid trust: $trust\n";
	return -1;
    }

    my $uid_idx = $self->uid_idx();
    my $gid_idx = $self->gid_idx();

    # If current trust is none, then also update date_approved.
    $clause  = ", date_approved=now() "
	if ($self->trust() eq $TRUSTSTRING_NONE);

    DBQueryWarn("update group_membership set trust='$trust' $clause ".
		"where gid_idx='$gid_idx' and uid_idx='$uid_idx'")
	or return -1;

Leigh Stoller's avatar
Leigh Stoller committed
1647 1648 1649
    # Mark as needing an update.
    $self->user()->BumpModified();

1650 1651 1652
    return Refresh($self);
}

1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
#
# Trust consistency.
#
sub CheckTrustConsistency($$$$)
{
    my ($self, $user, $newtrust, $fail) = @_;
    my $uid	   = $user->uid();
    my $pid	   = $self->pid();
    my $gid	   = $self->gid();
    my $uid_idx	   = $user->uid_idx();
    my $pid_idx	   = $self->pid_idx();
    my $gid_idx	   = $self->gid_idx();
    my $trust_none = $TRUSTSTRING_NONE;
    my $project	   = $self->Group::GetProject();

    # 
    # set $newtrustisroot to 1 if attempting to set a rootful trust,
    # 0 otherwise.
    #
    my $newtrustisroot = TBTrustConvert($newtrust) > PROJMEMBERTRUST_USER() ? 1 : 0;

    #
    # If changing subgroup trust level, then compare levels.
    # A user may not have root privs in the project and user privs
    # in the subgroup; it makes no sense to do that and can violate trust.
    #
    my $projtrustisroot;
    if ($pid_idx != $gid_idx) {
	#
	# Setting non-default "sub"group.
	# Verify that if user has root in project,
	# we are setting a rootful trust for him in 
	# the subgroup as well.
	#
	$projtrustisroot =
	    ($project->Trust($user) > PROJMEMBERTRUST_USER() ? 1 : 0);

	if ($projtrustisroot > $newtrustisroot) {
	    print("*** User $uid may not have a root trust level in ".
		    "the default group of $pid, ".
		    "yet be non-root in subgroup $gid!\n");
	    return 0;
	}
    }
    else {
	#
	# Setting default group.
	# Do not verify anything (yet.)
	#
	my $projtrustisroot = $newtrustisroot;
    }

    #
    # Get all the subgroups not equal to the subgroup being changed.
    # 
    my $query_result =
	DBQueryFatal("select trust,gid from group_membership ".
		     "where uid_idx='$uid_idx' and ".
		     "      pid_idx='$pid_idx' and ".
		     "      gid_idx!=pid_idx and ".
		     "      gid_idx!='$gid_idx' and ".
		     "      trust!='$trust_none'");

    while (my ($grptrust, $ogid) = $query_result->fetchrow_array()) {

	# 
	# Get what the users trust level is in the 
	# current subgroup we are looking at.
	#
	my $grptrustisroot = 
	    TBTrustConvert($grptrust) > PROJMEMBERTRUST_USER() ? 1 : 0;

	#
	# If users trust level is higher in the default group than in the
	# subgroup we are looking at, this is wrong.
	#
	if ($projtrustisroot > $grptrustisroot) {
	    print("*** User $uid may not have a root trust level in ".
		    "the default group of $pid, ".
		    "yet be non-root in subgroup $ogid!/n");
	    return 0;

	}

	if ($pid_idx != $gid_idx) {
	    #
	    # Iff we are modifying a subgroup, 
	    # Make sure that the trust we are setting is as
	    # rootful as the trust we already have set in
	    # every other subgroup.
	    # 
	    if ($newtrustisroot != $grptrustisroot) { 
		print("*** User $uid may not mix root and ".
			"non-root trust levels in ".
			"different subgroups of $pid!/n");
		return 0;
	    }
	}
    }
    return 1;
}

Leigh Stoller's avatar
Leigh Stoller committed
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
#
# Return group_exports info, as a plain hash.
#
sub PeerExports($$)
{
    my ($self, $pref) = @_;
    my $pid_idx = $self->pid_idx();
    my $gid_idx = $self->gid_idx();
    my $result  = {};

    my $query_result =
	DBQueryWarn("select e.*,p.* from group_exports as e ".
		    "left join emulab_peers as p on p.name=e.peer ".
		    "where e.pid_idx='$pid_idx' and e.gid_idx='$gid_idx'");

    while (my $row = $query_result->fetchrow_hashref()) {
	my $peer = $row->{'name'};
	$result->{$peer} = $row;
    }
    $$pref = $result;
    return 0;
}

1778 1779
# _Always_ make sure that this 1 is at the end of the file...
1;
1780