Group.pm.in 43.7 KB
Newer Older
1
2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2005-2015 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;
Leigh B Stoller's avatar
Leigh B Stoller committed
35
use emutil;
36
use User;
37
38
39
40
use English;
use Data::Dumper;
use File::Basename;
use overload ('""' => 'Stringify');
41
use vars qw($MEMBERLIST_FLAGS_UIDSONLY $MEMBERLIST_FLAGS_ALLUSERS
Russ Fish's avatar
Russ Fish committed
42
	    $MEMBERLIST_FLAGS_GETTRUST $MEMBERLIST_FLAGS_EXCLUDE_LEADER);
43
44

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

# Cache of instances to avoid regenerating them.
my %groups    = ();
my $debug      = 0;

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

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

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

#
# Lookup by idx.
#
78
sub Lookup($$;$)
79
{
80
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
    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();
    }
116
117
118
119
120
121

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

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

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

    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"); }
145
sub leader_idx($)       { return field($_[0], "leader_idx"); }
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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) = @_;

162
    return Group->Lookup($pid, $gid);
163
164
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
}

#
# 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);
}

227
228
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
#
# 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
276
277
278
279
	# 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!
280
281
282
283
284
	#
	$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 ".
285
			"where g.unix_gid>=$min_gid and ".
286
287
288
289
290
291
			"      g.unix_gid<50000 and ".
			"      r.unix_gid is null limit 1");

	return undef
	    if (! $query_result);

292
293
	my $unused;

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

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

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

322
323
324
325
326
327
328
    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', ".
329
		     " gid_uuid='$uuid', ".
330
331
332
333
334
335
		     " gid_idx=$gid_idx, ".
		     " pid_idx=$pid_idx, ".
		     " unix_gid=$unix_gid")) {
	return undef;
    }

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

    return $newgroup;
}

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

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

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

362
363
364
365
366
367
368
369
    # 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'"));
    }
    
370
371
372
    return 0;
}

373
374
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
#
# 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;
413
414
415
    if ($group->MemberList(\@curmembers, 
			   $MEMBERLIST_FLAGS_GETTRUST |
			   $MEMBERLIST_FLAGS_EXCLUDE_LEADER)) {
416
417
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
	$$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();
514
	    $foo        = "add_$target_idx";
515
516
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

	    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;
}

630
631
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
#
# 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;
}

685
686
687
688
689
690
691
692
693
694
#
# 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.
    #
695
    return PROJMEMBERTRUST_NONE()
696
697
698
699
700
701
702
703
704
705
	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?
    #
706
    return PROJMEMBERTRUST_NONE()
707
708
709
710
711
	if (!defined($membership));
    
    return TBTrustConvert($membership->trust());
}

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

724
725
726
727
    my $pid = $self->pid();
    my $gid = $self->gid();
    my $uid = $user->uid();

728
729
    if ($access_type < TB_PROJECT_MIN() ||
	$access_type > TB_PROJECT_MAX()) {
730
731
732
	print "*** Invalid access type: $access_type!\n";
	return 0;
    }
733
734
    # 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.
735
    return 1
736
	if ($user->IsAdmin() && $access_type != TB_PROJECT_LEADGROUP());
737

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

790
	if ($gid eq $pid)  {
791
792
793
794
795
796
797
798
799
800
801
802
	    #
	    # 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.
	    #
803
	    if (TBMinTrust($self->Trust($user), PROJMEMBERTRUST_GROUPROOT())) {
804
805
806
807
808
809
810
		return 1;
	    }

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

834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
#
# 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);
}

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

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

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

    if (defined($membership)) {
	print "*** AddMemberShip: $user is already a member of $self!\n";
	return -1;
    }
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
    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);
}

885
886
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
#
# 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();
912
913
    my $wanted_sslcert = (defined($user->initial_passphrase()) ?
			  "Yes" : "No");
914
915
916
917
918
919
920
921
922

    # 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();
923
924
925
926
927
928

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

Leigh B Stoller's avatar
Leigh B Stoller committed
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
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
    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";

    if ($project->isAPT() || $project->isCloud()) {
	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");
977
978
979
980

    return 0;
}

981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# 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);
1001
    my $project     = $self->GetProject();
1002
1003
1004
1005
1006

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

    my $trust = $membership->trust();
Leigh B Stoller's avatar
Leigh B Stoller committed
1007
1008
1009
    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'";
1010

Leigh B Stoller's avatar
Leigh B Stoller committed
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
    if ($project->isAPT() || $project->isCloud()) {
	$message .= "project $pid.";
	$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");
1026
1027
1028
1029
1030
1031
1032
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

    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;
}

1069
1070
1071
1072
1073
1074
1075
#
# Lookup user membership in this group
#
sub LookupUser($$)
{
    my ($self, $user) = @_;

1076
1077
1078
1079
    # Must be a real reference. 
    return undef
	if (! (ref($self) && ref($user)));

1080
1081
1082
    return Group::MemberShip->LookupUser($self, $user);
}

1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
#
# 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
1103
    require Project;
1104
1105
1106
1107
1108
1109
1110
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
1174
1175
1176
1177
1178

    # 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 ".
		     "      (trust='$projroot' or trust='$grouproot') ".
		     "order by trust DESC, usr_name");

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

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

1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
#
# 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);
1197
    my $gettrust   = ($flags & $MEMBERLIST_FLAGS_GETTRUST ? 1 : 0);
Russ Fish's avatar
Russ Fish committed
1198
    my $exclude_leader = ($flags & $MEMBERLIST_FLAGS_EXCLUDE_LEADER ? 1 : 0);
1199
1200
    my $trust_clause;

1201
1202
1203
1204
1205
1206
1207
    my $leader	    = $self->GetLeader();
    my $leader_idx;
    # There will be no leader during approveproject/Destroy.
    if (defined($leader)) {
	$leader_idx = $leader->uid_idx();
    }

1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
    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 =
1219
	DBQueryWarn("select distinct m.uid_idx,m.uid,m.trust ".
1220
1221
1222
1223
1224
1225
		    "   from group_membership as m ".
		    "where m.pid_idx='$pid_idx' and ".
		    "      m.gid_idx='$gid_idx' $trust_clause");

    return -1
	if (!$query_result);
1226

1227
1228
    while (my ($uid_idx, $uid, $trust) = $query_result->fetchrow_array()) {

1229
	if ($exclude_leader && defined($leader) && $leader_idx == $uid_idx) {
1230
1231
1232
1233
1234
1235
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
	    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()) {
1288
	if ($uids_only) {
1289
	    push(@result, $uid);
1290
1291
1292
1293
1294
	    next;
	}
	
	my $user = User->Lookup($uid_idx);
	if (!defined($user)) {
1295
	    print "Group::NonMemberList: Could not map $uid_idx to object\n";
1296
1297
1298
1299
1300
1301
1302
	    return undef;
	}
	push(@result, $user);
    }
    @$prval = @result;
    return 0;
}
1303

1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
#
# 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'");

1329
    if ($mode eq TBDB_STATS_SWAPIN() || $mode eq TBDB_STATS_START()) {
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
	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;
}

Leigh B Stoller's avatar
Leigh B Stoller committed
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
#
# 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());
}

1370
1371
1372
1373
1374
1375
1376
############################################################################

package Group::MemberShip;
use libdb;
use libtestbed;
use English;
use overload ('""' => 'Stringify');
1377
1378
1379
1380
use vars qw($TRUSTSTRING_NONE $TRUSTSTRING_USER
	    $TRUSTSTRING_LOCALROOT $TRUSTSTRING_GROUPROOT
	    $TRUSTSTRING_PROJROOT
	    @EXPORT_OK);
1381
1382

# Constants for membership.
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
$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);
1393
1394
1395
1396
1397
1398
1399
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

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 B Stoller's avatar
Leigh B Stoller committed
1450
1451
sub group($)            { return $_[0]->{'GROUP'}; }
sub user($ )            { return $_[0]->{'USER'}; }
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
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

#
# 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 B Stoller's avatar
Leigh B Stoller committed
1561
1562
1563
    # Mark as needing an update.
    $user->BumpModified();

1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
    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 B Stoller's avatar
Leigh B Stoller committed
1594
1595
1596
    # Mark as needing an update.
    $user->BumpModified();

1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
    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 B Stoller's avatar
Leigh B Stoller committed
1629
1630
1631
    # Mark as needing an update.
    $self->user()->BumpModified();

1632
1633
1634
    return Refresh($self);
}

1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
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
#
# 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 B Stoller's avatar
Leigh B Stoller committed
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
#
# 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;
}

1760
1761
# _Always_ make sure that this 1 is at the end of the file...
1;
1762