User.pm.in 43.1 KB
Newer Older
1 2 3
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2005-2010 University of Utah and the Flux Group.
5 6 7 8 9 10
# All rights reserved.
#
package User;

use strict;
use Exporter;
11
use vars qw(@ISA);
12 13
@ISA    = "Exporter";

14
use emdb;
15
use emutil;
16
use EmulabConstants;
17 18 19 20 21
use libtestbed;
use English;
use Data::Dumper;
use File::Basename;
use overload ('""' => 'Stringify');
22 23
use vars qw($NEWUSER_FLAGS_PROJLEADER $NEWUSER_FLAGS_WIKIONLY
	    $NEWUSER_FLAGS_WEBONLY $NEWUSER_FLAGS_ARCHIVED
24
	    $NEWUSER_FLAGS_NOUUID
25 26 27 28
	    $USERSTATUS_ACTIVE $USERSTATUS_FROZEN
	    $USERSTATUS_UNAPPROVED $USERSTATUS_UNVERIFIED
	    $USERSTATUS_NEWUSER $USERSTATUS_ARCHIVED
	    @EXPORT_OK);
29 30

# Configure variables
31
my $TB		   = "@prefix@";
32 33 34 35 36 37
my $TBOPS          = "@TBOPSEMAIL@";
my $TBAPPROVAL     = "@TBAPPROVALEMAIL@";
my $TBAUDIT   	   = "@TBAUDITEMAIL@";
my $TBBASE         = "@TBBASE@";
my $TBWWW          = "@TBWWW@";
my $WIKISUPPORT    = @WIKISUPPORT@;
38 39 40 41 42
my $BOSSNODE       = "@BOSSNODE@";
my $CONTROL	   = "@USERNODE@";
my $OURDOMAIN      = "@OURDOMAIN@";
my $MIN_UNIX_UID   = @MIN_UNIX_UID@;
my $MIN_UNIX_GID   = @MIN_UNIX_GID@;
43
my $tbacct	   = "$TB/sbin/tbacct";
44 45 46 47 48 49

# Create() flags.
$NEWUSER_FLAGS_PROJLEADER	= 0x01;
$NEWUSER_FLAGS_WIKIONLY		= 0x02;
$NEWUSER_FLAGS_WEBONLY		= 0x04;
$NEWUSER_FLAGS_ARCHIVED		= 0x08;
50
$NEWUSER_FLAGS_NOUUID		= 0x80;
51 52 53 54 55 56 57 58 59 60 61 62

# Status values.
$USERSTATUS_ACTIVE		= "active";
$USERSTATUS_FROZEN		= "frozen";
$USERSTATUS_UNAPPROVED		= "unapproved";
$USERSTATUS_UNVERIFIED		= "unverified";
$USERSTATUS_NEWUSER	        = "newuser";
$USERSTATUS_ARCHIVED	        = "archived";

# Why, why, why?
@EXPORT_OK = qw($NEWUSER_FLAGS_PROJLEADER $NEWUSER_FLAGS_WIKIONLY
		$NEWUSER_FLAGS_WEBONLY $NEWUSER_FLAGS_ARCHIVED
63
		$NEWUSER_FLAGS_NOUUID
64 65 66
		$USERSTATUS_ACTIVE $USERSTATUS_FROZEN
		$USERSTATUS_UNAPPROVED $USERSTATUS_UNVERIFIED
		$USERSTATUS_NEWUSER $USERSTATUS_ARCHIVED);
67

68 69 70 71
# Protos
sub SetUserInterface($$);
sub escapeshellarg($);

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
# Cache of instances to avoid regenerating them.
my %users      = ();
my $debug      = 0;

# Little helper and debug function.
sub mysystem($)
{
    my ($command) = @_;

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

#
# Lookup by idx.
#
sub Lookup($$)
{
91
    my ($class, $token) = @_;
92
    my $status_archived = $USERSTATUS_ARCHIVED;
93
    my $query_result;
94 95

    # Look in cache first
96 97 98 99 100 101 102
    return $users{"$token"}
        if (exists($users{"$token"}));

    #
    # For backwards compatability, look to see if the token is numeric
    # or alphanumeric. If numeric, assumes its an idx, otherwise a name.
    #
103
    if ($token =~ /^\d+$/) {
104 105 106
	$query_result =
	    DBQueryWarn("select * from users where uid_idx='$token'");
    }
107 108 109 110 111
    elsif ($token =~ /^\w+$/) {
	# When looking up by uid, only look for non-archived users;
	# Must use an idx if you really want an archived user. This
	# will prevent problems with code that has not yet been
	# changed to use the idx field.
112
	$query_result =
113 114
	    DBQueryWarn("select * from users ".
			"where uid='$token' and status!='$status_archived'");
115 116 117 118
    }
    else {
	return undef;
    }
119 120 121 122 123 124 125 126 127 128
    
    return undef
	if (!$query_result || !$query_result->numrows);

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

    bless($self, $class);
    
    # Add to cache. 
129
    $users{$self->{'USER'}->{'uid_idx'}} = $self;
130 131 132 133 134 135
    
    return $self;
}
# accessors
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'USER'}->{$_[1]}); }
sub uid_idx($)		{ return field($_[0], "uid_idx"); }
136
sub dbid($)		{ return field($_[0], "uid_idx"); }
137
sub uid($)		{ return field($_[0], "uid"); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
138
sub uuid($)		{ return field($_[0], "uid_uuid"); }
139 140 141 142 143 144
sub created($)		{ return field($_[0], "usr_created"); }
sub expires($)		{ return field($_[0], "usr_expires"); }
sub modified($)		{ return field($_[0], "usr_modified"); }
sub name($)		{ return field($_[0], "usr_name"); }
sub title($)		{ return field($_[0], "usr_title"); }
sub affil($)		{ return field($_[0], "usr_affil"); }
145
sub affil_abbrev($)	{ return field($_[0], "usr_affil_abbrev"); }
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
sub email($)		{ return field($_[0], "usr_email"); }
sub URL($)		{ return field($_[0], "usr_URL"); }
sub addr($)		{ return field($_[0], "usr_addr"); }
sub addr2($)		{ return field($_[0], "usr_addr2"); }
sub city($)		{ return field($_[0], "usr_city"); }
sub state($)		{ return field($_[0], "usr_state"); }
sub zip($)		{ return field($_[0], "usr_zip"); }
sub country($)		{ return field($_[0], "usr_country"); }
sub phone($)		{ return field($_[0], "usr_phone"); }
sub shell($)		{ return field($_[0], "usr_shell"); }
sub pswd($)		{ return field($_[0], "usr_pswd"); }
sub w_pswd($)		{ return field($_[0], "usr_w_pswd"); }
sub unix_uid($)		{ return field($_[0], "unix_uid"); }
sub status($)		{ return field($_[0], "status"); }
sub admin($)		{ return field($_[0], "admin"); }
sub foreign_admin($)	{ return field($_[0], "foreign_admin"); }
sub dbedit($)		{ return field($_[0], "dbedit"); }
sub stud($)		{ return field($_[0], "stud"); }
sub webonly($)		{ return field($_[0], "webonly"); }
sub pswd_expires($)	{ return field($_[0], "pswd_expires"); }
sub cvsweb($)		{ return field($_[0], "cvsweb"); }
sub emulab_pubkey($)	{ return field($_[0], "emulab_pubkey"); }
sub home_pubkey($)	{ return field($_[0], "home_pubkey"); }
sub adminoff($)		{ return field($_[0], "adminoff"); }
sub verify_key($)	{ return field($_[0], "verify_key"); }
sub widearearoot($)	{ return field($_[0], "widearearoot"); }
sub wideareajailroot($) { return field($_[0], "wideareajailroot"); }
sub notes($)		{ return field($_[0], "notes"); }
sub weblogin_frozen($)  { return field($_[0], "weblogin_frozen"); }
sub weblogin_failcount($){return field($_[0], "weblogin_failcount");}
sub weblogin_failstamp($){return field($_[0], "weblogin_failstamp");}
sub plab_user($)	{ return field($_[0], "plab_user"); }
sub user_interface($)	{ return field($_[0], "user_interface"); }
sub chpasswd_key($)	{ return field($_[0], "chpasswd_key"); }
sub chpasswd_expires($) { return field($_[0], "chpasswd_expires"); }
sub wikiname($)		{ return field($_[0], "wikiname"); }
sub wikionly($)		{ return field($_[0], "wikionly"); }
sub mailman_password($) { return field($_[0], "mailman_password"); }

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
# Temporary data storage ... useful.
sub GetTempData($$) { return field($_[0], "tempdata"); } 
sub SetTempData($$) {

    my ($self, $value) = @_;

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

    $self->{'USER'}->{"tempdata"} = $value;

    return 0;
}

200 201 202 203 204 205 206
#
# Lookup user given a plain uid. For backwards compat.
#
sub LookupByUid($$)
{
    my ($class, $uid) = @_;

207
    return User->Lookup($uid);
208 209
}

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
# Include archived users, as for checking a newuser account.
sub LookupByUidAll($$)
{
    my ($class, $uid) = @_;

    my $query_result =
	DBQueryFatal("select uid_idx from users where uid='$uid'");

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

    my ($uid_idx) = $query_result->fetchrow_array();

    return User->Lookup($uid_idx);
}

226 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
#
# Lookup user given the unix uid ($UID typically).
#
sub LookupByUnixId($$)
{
    my ($class, $unix_uid) = @_;

    my $query_result =
	DBQueryFatal("select uid,uid_idx from users ".
		     "where unix_uid='$unix_uid'");

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

    my ($uid, $uid_idx) = $query_result->fetchrow_array();

    # Sanity check against password file before returning.
    my ($pwname) = getpwuid($unix_uid) or
	die("*** $unix_uid is not in the password file!");

    if ($uid ne $pwname) {
	warn("*** WARNING: LookupByUnixId: $pwname does not match $uid\n");
	return undef
    }

    return User->Lookup($uid_idx);
}

254 255 256 257 258 259 260
#
# Lookup user given a wikiname. This is just to make sure the wikiname
# the user picked is unique.
#
sub LookupByWikiName($$)
{
    my ($class, $wikiname) = @_;
261 262
    my $status_archived = $USERSTATUS_ARCHIVED;
    
263 264
    my $query_result =
	DBQueryFatal("select uid_idx from users ".
265 266
		     "where wikiname='$wikiname' and ".
		     "      status!='$status_archived'");
267 268 269 270 271 272 273 274 275 276

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

    my ($uid_idx) = $query_result->fetchrow_array();

    return User->Lookup($uid_idx);
}

#
277 278
# Lookup user given an e-mail address.  This is just to make sure the
# e-mail address the user picked is unique.
279 280 281 282
#
sub LookupByEmail($$)
{
    my ($class, $email) = @_;
283
    my $status_archived = $USERSTATUS_ARCHIVED;
284 285 286

    my $query_result =
	DBQueryFatal("select uid_idx from users ".
287 288
		     "where LCASE(usr_email)=LCASE('$email') and ".
		     "      status!='$status_archived'");
289 290 291 292 293 294 295 296 297

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

    my ($uid_idx) = $query_result->fetchrow_array();

    return User->Lookup($uid_idx);
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
#
# Lookup user given a UUID.  
#
sub LookupByUUID($$)
{
    my ($class, $uuid) = @_;
    my $status_archived = $USERSTATUS_ARCHIVED;
    my $safe_uuid = DBQuoteSpecial($uuid);

    my $query_result =
	DBQueryFatal("select uid_idx from users ".
		     "where uid_uuid=$safe_uuid and ".
		     "      status!='$status_archived'");

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

    my ($uid_idx) = $query_result->fetchrow_array();

    return User->Lookup($uid_idx);
}

320 321 322 323 324 325
#
# Class function to create new user and return object.
#
sub Create($$$$)
{
    my ($class, $uid, $flags, $argref) = @_;
326
    my $uuid;
327 328 329 330 331

    my $isleader = ($flags & $NEWUSER_FLAGS_PROJLEADER ? 1 : 0);
    my $wikionly = ($flags & $NEWUSER_FLAGS_WIKIONLY   ? 1 : 0);
    my $webonly  = ($flags & $NEWUSER_FLAGS_WEBONLY    ? 1 : 0);
    my $archived = ($flags & $NEWUSER_FLAGS_ARCHIVED   ? 1 : 0);
332
    my $nouuid   = ($flags & $NEWUSER_FLAGS_NOUUID     ? 1 : 0);
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 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

    #
    # If no uid, we need to generate a unique one for the user.
    #
    if (! $uid) {
	#
	# Take the first 5 letters of the email to form a root. That gives
	# us 3 digits to make it unique, since unix uids are limited to 8
	# chars, sheesh!
	#
	my $email = $argref->{'usr_email'};
	my $token;

	if ($email =~ /^([-\w\+\.]+)\@([-\w\.]+)$/) {
	    $token = $1;
	}
	else {
	    return undef;
	}
	# Squeeze out any dots or dashes.
	$token =~ s/\.//g;
	$token =~ s/\-//g;

	# Trim off any trailing numbers or +foo tokens.
	if ($token =~ /^([a-zA-Z]+)/) {
	    $token = $1;
	}
	else {
	    return undef;
	}

	# First 5 chars, at most.
	$token = substr($token, 0, 5);

	# Grab all root matches from the DB.
	my $query_result =
	    DBQueryWarn("select uid from users where uid like '${token}%'");

	return undef
	    if (!$query_result);

	# Easy; no matches at all!
	if (!$query_result->numrows) {
	    $uid = "$token" . "001";
	}
	else {
	    my $max = 0;
		
	    #
	    # Find unused slot. Must be a better way to do this!
	    #
	    while (my ($foo) = $query_result->fetchrow_array()) {
		my $name;
		my $number;
		
		# Split name from number
		if ($foo =~ /^([a-zA-Z]+)(\d*)$/) {
		    $name   = $1;
		    $number = $2;
		}
		else {
		    return undef;
		}
		# Must be exact root
		next
398
		    if ($name ne $token);
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418

		# Backwards compatability; might not have appended number.
		if (isset($number) && intval($number) > $max) {
		    $max = intval($number);
		}
	    }
	    $max++;
	    $uid = $token . sprintf("%03d", $max);
	}
    }
	
    #
    # The array of inserts is assumed to be safe already. Generate
    # a list of actual insert clauses to be joined below.
    #
    my @insert_data = (!defined($argref) ? () :
		       map("$_=" . DBQuoteSpecial($argref->{$_}),
			   keys(%{$argref})));

    # Every user gets a new unique index.
419
    my $uid_idx = User->NextIDX();
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441

    #
    # Get me an unused unix id. 
    #
    my $unix_uid;

    #
    # Start here, and keep going if the one picked from the DB just
    # happens to be in use (in the passwd file). Actually happens!
    #
    my $min_uid = $MIN_UNIX_UID;
    
    while (! defined($unix_uid)) {
	#
	# Nice query, eh? Basically, find unused numbers by looking at
	# existing numbers plus one, and check to see if that number
	# is taken.
	#
	my $query_result =
	    DBQueryWarn("select u.unix_uid + 1 as start from users as u ".
			"left outer join users as r on ".
			"  u.unix_uid + 1 = r.unix_uid ".
442
			"where u.unix_uid>=$min_uid and ".
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
			"      u.unix_uid<60000 and ".
			"      r.unix_uid is null limit 1");
	return undef
	    if (! $query_result);

	if (! $query_result->numrows) {
	    print "*** WARNING: Could not find an unused unix_uid!\n";
	    return undef;
	}

	my ($unused) = $query_result->fetchrow_array();

	if (getpwuid($unused)) {
	    # Keep going.
	    $min_uid++;
	}
	else {
	    # Break out of loop.
	    $unix_uid = $unused;
	}
    }

    # Initial mailman_password.
    my $mailman_password = substr(TBGenSecretKey(), 0, 10);

    # And a verification key.
    my $verify_key = TBGenSecretKey();

471 472 473 474 475 476 477 478
    if (! $nouuid) {
	# And a UUID (universally unique identifier).
	$uuid = NewUUID();
	if (!defined($uuid)) {
	    print "*** WARNING: Could not generate a UUID!\n";
	    return undef;
	}
	push(@insert_data, "uid_uuid='$uuid'");
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
    # Now tack on other stuff we need.
    push(@insert_data, "wikionly='1'")
	if ($wikionly);
    push(@insert_data, "webonly='1'")
	if ($webonly);

    push(@insert_data, "usr_created=now()");
    push(@insert_data, "usr_modified=now()");
    push(@insert_data, "unix_uid=$unix_uid");
    push(@insert_data, "mailman_password='$mailman_password'");
    push(@insert_data, "verify_key='$verify_key'");
    push(@insert_data, "uid_idx='$uid_idx'");
    push(@insert_data, "uid='$uid'");

    if ($archived) {
	#
	# Creating an archived user; this only happens when restoring a
        # deleted user (which is to say, not often).
	#
	push(@insert_data, "status='$USERSTATUS_ARCHIVED'");
	push(@insert_data, "usr_name='$uid'");
	push(@insert_data, "pswd_expires=now()");
	push(@insert_data, "usr_pswd='*'");
	push(@insert_data, "usr_email='bouncer\@${OURDOMAIN}'");
    }
    else {
	push(@insert_data, "status='$USERSTATUS_NEWUSER'");
	push(@insert_data, "pswd_expires=date_add(now(), interval 1 year)");
    }

    # Insert into DB.
    DBQueryWarn("insert into users set " . join(",", @insert_data))
	or return undef;

515 516 517 518 519 520 521 522
    # And the stats record.
    @insert_data = ();
    push(@insert_data, "uid_idx='$uid_idx'");
    push(@insert_data, "uid='$uid'");
    push(@insert_data, "uid_uuid='$uuid'")
	if (!$nouuid);

    if (! DBQueryWarn("insert into user_stats set ".join(",", @insert_data))) {
523 524 525 526 527 528
	DBQueryFatal("delete from users where uid_idx='$uid_idx'");
	return undef;
    }
    return User->Lookup($uid_idx);
}

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
#
# Delete the user from the users and user_stats tables.
#
sub Delete($)
{
    my ($self) = @_;

    return 0
	if (! ref($self));

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

    DBQueryWarn("delete from user_stats where uid_idx='$uid_idx'")
	or return -1;
    DBQueryWarn("delete from users where uid_idx='$uid_idx'")
	or return -1;
    
    return 0;
}

549 550 551 552 553 554 555 556 557 558 559
#
# Utility (class) function to get a new uid for a user.
#
sub NextIDX($)
{
    my ($class) = @_;

    my $idx = TBGetUniqueIndex('next_uid', 1);
    return $idx;
}

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
#
# Purge user from various tables, but not the user table.
#
sub Purge($)
{
    my ($self) = @_;

    return 0
	if (! ref($self));

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

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

    #
    # Then the pubkey tables.
    # 
    DBQueryWarn("delete from user_pubkeys  where uid_idx='$uid_idx'")
	or return -1;
    DBQueryWarn("delete from user_sfskeys  where uid_idx='$uid_idx'")
	or return -1;
583 584 585 586 587 588 589 590

    #
    # Do not delete certs; we need them around so we can generte the CRLS.
    # Just set the revoked flag for them. At some point we need to prune
    # the table.
    #
    DBQueryWarn("update user_sslcerts set revoked=now() ".
		"where uid_idx='$uid_idx' and revoked is null")
591 592 593 594 595 596 597 598 599 600 601 602 603
	or return -1;

    #
    # Must do widearea_accounts too.
    #
    DBQueryWarn("delete from widearea_accounts where uid_idx='$uid_idx'")
	or return -1;

    #
    # Then some other pidly tables.
    # 
    DBQueryWarn("delete from login where uid_idx='$uid_idx'")
	or return -1;
604
    DBQueryWarn("delete from nodeuidlastlogin where uid='$uid_idx'")
605
	or return -1;
606
    DBQueryWarn("delete from uidnodelastlogin where uid='$uid_idx'")
607
	or return -1;
608
    DBQueryWarn("delete from unixgroup_membership where uid='$uid_idx'")
609
	or return -1;
610
    DBQueryWarn("delete from userslastlogin where uid='$uid_idx'")
611
	or return -1;
612
    DBQueryWarn("delete from user_policies where uid='$uid_idx'")
613 614 615 616 617
	or return -1;

    return 0;
}

618 619 620 621 622 623 624 625
#
# Wrap above function so I do not forget to use it for the current user.
#
sub ThisUser($)
{
    return User->LookupByUnixId($UID);
}

626 627 628 629 630 631 632 633 634 635 636 637
#
# The "implied" user is the user the web interface says we are running as.
#
sub ImpliedUser($)
{
    return undef
	if (! exists($ENV{'HTTP_INVOKING_USER'}));
    
    # The lookup routine checks it argument, so no need to taint check.
    return User->Lookup($ENV{'HTTP_INVOKING_USER'});
}

638 639 640 641 642 643
#
# See if user is member of emulab-ops project. Must be the current user.
#
sub IsOpsGuy($)
{
    my ($self) = @_;
644
    require Group;
645 646 647 648 649 650 651 652

    return 0
	if (! ref($self));

    if (!$self->SameUser($self->ThisUser())) {
	print STDERR "*** IsOpsGuy: Must be invoked on current user!\n";
	return 0;
    }
653 654 655 656 657 658
    my $group = Group->Lookup(TBOPSPID(), TBOPSPID());
    if (!defined($group)) {
	print STDERR "*** IsOpsGuy: No emulab-ops project!\n";
	return 0;
    }
    return TBMinTrust($group->Trust($self), PROJMEMBERTRUST_USER());
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 687
}

#
# See if user is an admin. Must be the current user.
#
sub IsAdmin($)
{
    my ($self) = @_;

    return 0
	if (! ref($self));

    if (!$self->SameUser($self->ThisUser())) {
	print STDERR "*** IsAdmin: Must be invoked on current user!\n";
	return 0;
    }
    #
    # No one is considered an admin unless they have the magic environment
    # variable set (so that you have to be a bit more explict about wanting
    # admin privs.) Use the withadminprivs script to get this variable set.
    # Also check with HTTP_ at the front of the name, since this is required
    # to get it through suexec from the web scripts.
    #
    if (!($ENV{WITH_TB_ADMIN_PRIVS} || $ENV{HTTP_WITH_TB_ADMIN_PRIVS})) {
	return 0;
    }
    return $self->admin();
}

688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
#
# Worker class method to change the user profile.
# Assumes most argument checking was done elsewhere.
#
sub ModUserInfo($$$$)
{
    my ($class, $this_user, $target_user, $argref, $usrerr_ref) = @_;

    my $this_uid = $this_user->uid();
    my $isadmin = $this_user->IsAdmin();

    my $target_uid = $target_user->uid();
    my $target_uid_idx = $target_user->uid_idx();
    my $target_name = $target_user->name();
    my $target_email = $target_user->email();
    my $wikionly = $target_user->wikionly();

    my %mods;
    my $noreport;

    #
    # Only admin types can change the email address. If its different, the
    # user circumvented the form, and so its okay to blast it.
    #
    my $usr_email = $argref->{"usr_email"};
    if ($usr_email && $target_email ne $usr_email) {
	if (!$isadmin) {
	    $$usrerr_ref = "Email: ".
		"You are not allowed to change your email address";
	    return undef;
	}

	#
	# Invoke the backend to deal with this.
	#
	my $cmd = "$tbacct email $target_uid " .
		   escapeshellarg($usr_email);
	##print $cmd;
	my $cmd_out = `$cmd`;
	if ($?) {
	    chomp($cmd_out);
	    $$usrerr_ref = "Error: " . $cmd_out;
	    return undef;
	}
	$mods{"usr_email"} = $usr_email;
    }

    #
    # Now see if the user is requesting to change the password.
    #
    if (($argref->{"password1"} && $argref->{"password1"} ne "") &&
	($argref->{"password2"} && $argref->{"password2"} ne "")) {

	my $old_encoding = $target_user->pswd();
	my $new_encoding = crypt($argref->{"password1"}, $old_encoding);

	#
	# Compare. Must change it!
	# 
	if ($old_encoding eq $new_encoding) {
	    $$usrerr_ref = "Error: " .
		"New password same as old password";
	    return undef;
	}

	#
	# Do it again. This ensures we use the current algorithm, not whatever
	# it was encoded with last time.
	# XXX Perl crypt doesn't have this option!
	# XXX $new_encoding  = crypt($argref->{"password1"});

	my $safe_encoding = escapeshellarg($new_encoding);

	#
	# Invoke the backend to deal with this.
	#
	my $cmd = "tbacct passwd $target_uid $safe_encoding";
	##print $cmd;
	my $cmd_out = `$cmd`;
	if ($?) {
	    chomp($cmd_out);
	    $$usrerr_ref = "Error: " . $cmd_out;
	    return undef;
	}
	$noreport = 1;
    }

    #
    # See if the user is requesting to change the Windows password.
    #
    if (($argref->{"w_password1"} && $argref->{"w_password1"} ne "") &&
	($argref->{"w_password2"} && $argref->{"w_password2"} ne "")) {

	my $old_wpswd = $target_user->w_pswd();
	my $new_wpswd = $argref->{"w_password1"};

	#
	# Compare. Must change it!
	# 
	if ($old_wpswd eq $new_wpswd) {
	    $$usrerr_ref = "Error: " .
		"New Windows password same as old Windows password";
	    return undef;
	}

	#
	# Invoke the backend to deal with this.
	#
	my $cmd = "tbacct wpasswd $target_uid " . escapeshellarg($new_wpswd);
	##print $cmd;
	my $cmd_out = `$cmd`;
	if ($?) {
	    chomp($cmd_out);
	    $$usrerr_ref = "Error: " . $cmd_out;
	    return undef;
	}
	$noreport = 1;
    }

    #
    # Only admins can change the notes field. We do not bother to generate
    # any email or external updates for this.
    #
    my $notes = $argref->{"notes"};
812
    if (defined($notes) && $isadmin && $target_user->notes() ne $notes) {
813 814 815 816 817 818 819 820
	$target_user->SetNotes($notes);
	$noreport = 1;
    }

    #
    # Set the plab bit separately since no need to call out to the backend.
    #
    my $ui = $argref->{"user_interface"};
821
    if (defined($ui) && $target_user->user_interface() ne $ui) {
822 823 824 825 826 827 828 829 830
	$target_user->SetUserInterface($ui);
	$noreport = 1;
    }

    #
    # Now update the rest of the information in the DB.
    # (Others above already did their own updates.)
    #
    my %updates;
831 832
    foreach my $col ("usr_name", "usr_title", "usr_affil", "usr_affil_abbrev", 
		     "usr_URL",
833 834
		     "usr_addr", "usr_addr2", "usr_city", "usr_state",
		     "usr_zip", "usr_country", "usr_phone", "usr_shell") {
Russ Fish's avatar
Russ Fish committed
835 836 837
	# Copy args we want so that others can't get through.
	if (exists($argref->{$col})) {
	    $updates{$col} = $mods{$col} = $argref->{$col};
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
	}
    }
    if (keys %updates) {
	if ($target_user->Update(\%updates)) {
	    return undef;
	}
    }

    if (!keys %mods) {
	if (!$noreport) {
	    # Warn the user that the submit button was pressed with no effect.
	    $$usrerr_ref = "Submit: Nothing changed";
	    return undef;
	}
    }
    else {
	# Send an audit e-mail reporting what is being changed.
	my @report = ("Name:usr_name", "Email:usr_email",
856 857
		      "Job Title:usr_title", "Affiliation:usr_affil",
		      "Affiliation Abbreviation:usr_affil_abbrev",
858 859 860 861 862 863 864 865 866 867 868
		      "URL:usr_URL", "Address1:usr_addr",
		      "Address2:usr_addr2", "City:usr_city",
		      "State:usr_state", "ZIP/Postal Code:usr_zip",
		      "Country:usr_country", "Phone:usr_phone",
		      "Shell:usr_shell");
	my $msg = "\n".
	    "User information for '$target_uid' changed by '$this_uid'.\n".
	     "(IDX: $target_uid_idx, $target_name, $target_email".
		 ($wikionly ? ", *WikiOnly*" : "") . ")\n\n";
	foreach my $line (@report) {
	    my ($label, $field) = split /:/, $line;
Russ Fish's avatar
Russ Fish committed
869 870
	    if (exists($mods{$field})) {
		$msg .= sprintf "%-20s%s\n", $label .":", $mods{$field};
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
	    }
	}
	SENDMAIL("$target_name <$target_email>",
		 "User Information for '$target_uid' Modified",
		 $msg, TBMAIL_OPS(), sprintf("Bcc: %s\nErrors-To:%s", 
					     TBMAIL_AUDIT(), TBMAIL_WWW()));

	#
	# "tbacct mod" updates the user gecos field (usr_name) and shell.
	#
	if ($mods{"usr_name"} || $mods{"usr_shell"}) {
	    my $cmd = "$tbacct mod $target_uid";
	    ##print $cmd;
	    my $cmd_out = `$cmd`;
	    if ($?) {
		chomp($cmd_out);
		$$usrerr_ref = "Error: " . $cmd_out;
		return undef;
	    }
	}
    }
    return 1;
}

895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
#
# 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 $query_result =
	DBQueryWarn("select * from users where uid_idx=$uid_idx");

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

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

    return 0;
}

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

    return "[User: $uid, IDX: $uid_idx]";
}

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

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

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

944
    my $query = "update users set usr_modified=now(), ".
945
	join(",", map("$_=" . DBQuoteSpecial($argref->{$_}), keys(%{$argref})));
946 947 948 949 950 951 952 953 954

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

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

    return Refresh($self);
}

955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
#
# Equality test for two users. Not strictly necessary in perl, but good form.
#
sub SameUser($$)
{
    my ($self, $other) = @_;

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

    return $self->uid_idx() == $other->uid_idx();
}

#
# First approved project.
#
sub FirstApprovedProject($$)
{
    my ($self, $pptr) = @_;
975
    require Project;
976 977 978 979 980 981 982 983 984 985 986 987 988 989

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

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

    my $query_result =
	DBQueryWarn("select pid_idx from group_membership ".
		    "where uid_idx='$uid_idx' and pid_idx=gid_idx and ".
		    "      trust!='none' ".
		    "order by date_approved asc limit 1");

    if (! $query_result || !$query_result->numrows) {
990
	$$pptr = undef;
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
	return 0;
    }

    my ($pid_idx) = $query_result->fetchrow_array();
    my $project   = Project->Lookup($pid_idx);
    
    if (! defined($project)) {
	warn("*** User::FirstApprovedProject: ".
	     "Could not load project $pid_idx!");
	return -1;
    }
    $$pptr = $project;
    return 0;
}

1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
#
# Change the status of a user in the DB.
#
sub SetStatus($$)
{
    my ($self, $status) = @_;

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

    my %args = ("status" => $status);

    return $self->Update(\%args);
}

1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
#
# Get user ssl certificate (pubkey). 
#
sub SSLCert($$$)
{
    my ($self, $encrypted, $pref) = @_;
    $encrypted = ($encrypted ? 1 : 0);
    
    # Must be a real reference. 
    return -1
	if (! ref($self));

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

    my $query_result =
	DBQueryWarn("select cert from user_sslcerts ".
1038 1039 1040
		    "where uid_idx='$uid_idx' and encrypted=$encrypted and ".
		    "      revoked is null");
		    
1041 1042 1043 1044 1045 1046 1047 1048
    return -1
	if (!defined($query_result) || !$query_result->numrows);

    my ($cert) = $query_result->fetchrow_array();
    $$pref = $cert;
    return 0;
}

1049
#
1050 1051
# Get user ssh keys. This is bogus; I am making sure not to return the
# emulab key which is not encrypted. The keys table needs work.
1052
#
1053
sub GetSSHKeys($$)
1054 1055
{
    my ($self, $pref) = @_;
1056
    my @result = ();
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
    
    # Must be a real reference. 
    return -1
	if (! (ref($self) && ref($pref)));

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

    my $query_result =
	DBQueryWarn("select pubkey from user_pubkeys ".
		    "where uid_idx='$uid_idx' and ".
1067
		    "      comment not like '%${OURDOMAIN}'");
1068 1069 1070 1071

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

1072 1073 1074 1075
    while (my ($key) = $query_result->fetchrow_array()) { 
	push(@result, $key);
    }    
    @$pref = @result;
1076 1077 1078
    return 0;
}

1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
#
# Get the passphrase for the encrypted key.
#
sub SSLPassPhrase($$$)
{
    my ($self, $encrypted, $pref) = @_;
    $encrypted = ($encrypted ? 1 : 0);
    
    # Must be a real reference. 
    return -1
	if (! ref($self));

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

    my $query_result =
	DBQueryWarn("select password from user_sslcerts ".
		    "where uid_idx='$uid_idx' and encrypted=$encrypted and ".
		    "      revoked is null");
    return -1
	if (!defined($query_result) || !$query_result->numrows);

    my ($password) = $query_result->fetchrow_array();
    $$pref = $password;
    return 0;
}

1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
#
# Set password for user.
#
sub SetPassword($$$)
{
    my ($self, $encoding, $expires) = @_;

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

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

    # Clear the chpasswd stuff anytime passwd is set.
    return -1
	if (! DBQueryWarn("update users set ".
			  "  usr_pswd='$encoding', pswd_expires=$expires, ".
			  "  chpasswd_key=NULL,chpasswd_expires=0 ".
			  "where uid_idx='$uid_idx'"));

    return Refresh($self);
}

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 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
#
# Set Windows password for user.
#
sub SetWindowsPassword($$)
{
    my ($self, $wpswd) = @_;

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

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

    return -1
	if (! DBQueryWarn("update users set ".
			  "  usr_w_pswd='$wpswd' ".
			  "where uid_idx='$uid_idx'"));

    return Refresh($self);
}

#
# Set notes field for user.
#
sub SetNotes($$)
{
    my ($self, $notes) = @_;

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

    $notes = escapeshellarg($notes);
    my $uid_idx = $self->uid_idx();

    return -1
	if (! DBQueryWarn("update users set ".
			  "  notes='$notes' ".
			  "where uid_idx='$uid_idx'"));

    return Refresh($self);
}

#
# Set user interface mode for user.
#
sub SetUserInterface($$)
{
    my ($self, $interface) = @_;

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

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

    return -1
	if (! DBQueryWarn("update users set ".
			  "  user_interface='$interface' ".
			  "where uid_idx='$uid_idx'"));

    return Refresh($self);
}

1192
#
1193
# User verified; find users groups and send email.
1194
#
1195
sub SendVerifiedEmail($)
1196 1197
{
    my ($self) = @_;
1198
    require Group;
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253

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

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

    my $newuser     = $USERSTATUS_NEWUSER;
    my $unapproved  = $USERSTATUS_UNAPPROVED;
    my $none        = $Group::MemberShip::TRUSTSTRING_NONE;

    # Audit email.
    SENDMAIL($TBAUDIT,
	     "User '$uid' has been verified",
	     "\n".
	     "User '$uid' has been verified.\n".	
	     "Status has been changed from '$newuser' to '$unapproved'\n",
	     "$TBAPPROVAL");

    #
    # Get the list of all project/groups this users has tried to join
    # but whose membership messages where delayed until the user verified
    # himself.
    #
    my $query_result =
	DBQueryFatal("select gid_idx from group_membership ".
		     "where uid_idx='$uid_idx' and trust='$none'");

    while (my ($gid_idx) = $query_result->fetchrow_array()) {
	my $group = Group->Lookup($gid_idx);

	if (!defined($group)) {
	    print("*** User::SendApprovalEmail: ".
		  "Could not load group $gid_idx!");
	    return -1;
	}
	#
	# If a project leader is verifying himself, then we do the project
	# version of the email (sends to tbapproval).
	#
	if ($group->IsProjectGroup() && $group->IsLeader($self)) {
	    my $project = $group->GetProject();

	    $project->SendNewProjectEmail() == 0 or
		return -1;
	}
	else {
	    $group->SendJoinEmail($self) == 0 or
		return -1;
	}
    }
    return 0;
}

1254 1255 1256 1257 1258 1259
#
# Return group membership for a user.  
#
sub GroupMembershipList($$;$)
{
    my ($self, $prval, $desired_trust) = @_;
1260
    require Group;
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271

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

    my $uid_idx     = $self->uid_idx();
    my $none        = $Group::MemberShip::TRUSTSTRING_NONE;
    my @result      = ();
    my $trust_clause;

    if (!defined($desired_trust)) {
1272 1273 1274 1275
	$trust_clause = "and trust!='$none'"
    }
    elsif ($desired_trust eq "") {
	$trust_clause = "";
1276 1277
    }
    else {
1278
	$trust_clause = "and trust='$desired_trust'"
1279 1280 1281 1282
    }

    my $query_result =
	DBQueryWarn("select distinct gid_idx from group_membership ".
1283
		    "where uid_idx='$uid_idx' $trust_clause");
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299

    return -1
	if (!$query_result);

    while (my ($gid_idx) = $query_result->fetchrow_array()) {
	my $group = Group->Lookup($gid_idx);

	if (!defined($group)) {
	    print("*** User::GroupMembershipList: ".
		  "Could not load group $gid_idx!");
	    return -1;
	}
	push(@result, $group);
    }
    @$prval = @result;
    return 0;
1300 1301
}

1302 1303 1304 1305 1306 1307
#
# Return project membership for a user.  
#
sub ProjectMembershipList($$;$)
{
    my ($self, $prval, $desired_trust) = @_;
1308 1309
    require Project;
    require Group;
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 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357

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

    my $uid_idx     = $self->uid_idx();
    my $none        = $Group::MemberShip::TRUSTSTRING_NONE;
    my @result      = ();
    my $trust_clause;

    if (!defined($desired_trust)) {
	$trust_clause = "and trust!='$none'"
    }
    elsif ($desired_trust eq "") {
	$trust_clause = "";
    }
    else {
	$trust_clause = "and trust='$desired_trust'"
    }

    my $query_result =
	DBQueryWarn("select distinct pid_idx from group_membership ".
		    "where uid_idx='$uid_idx' and pid_idx=gid_idx ".
		    "      $trust_clause");

    return -1
	if (!$query_result);

    while (my ($pid_idx) = $query_result->fetchrow_array()) {
	my $project = Project->Lookup($pid_idx);

	if (!defined($project)) {
	    print("*** User::ProjectMembershipList: ".
		  "Could not load project $pid_idx!");
	    return -1;
	}
	push(@result, $project);
    }
    @$prval = @result;
    return 0;
}

#
# Return project leadership for a user.  
#
sub ProjectLeaderList($$;$)
{
    my ($self, $prval) = @_;
1358
    require Project;
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386

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

    my $uid_idx     = $self->uid_idx();
    my @result      = ();

    my $query_result =
	DBQueryFatal("select pid_idx from projects where head_idx='$uid_idx'");
    
    return -1
	if (!$query_result);

    while (my ($pid_idx) = $query_result->fetchrow_array()) {
	my $project = Project->Lookup($pid_idx);

	if (!defined($project)) {
	    print("*** User::ProjectLeaderList: ".
		  "Could not load project $pid_idx!");
	    return -1;
	}
	push(@result, $project);
    }
    @$prval = @result;
    return 0;
}

1387 1388 1389 1390 1391 1392 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
#
# Return a glist for setting user groups. The argument is the default
# group, since the list has to be reordered for perl to do the right thing. 
#
sub GList($$)
{
    my ($self, $default) = @_;

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

    my $user_uid = $self->uid();

    # Should we get this info from the DB instead of using "id?"
    my $glist = `id -G $user_uid`;
    if ($glist =~ /^([\d ]*)$/) {
	$glist = $1;
    }
    else {
	print STDERR "*** Unexpected results from 'id -G $user_uid': $glist\n";
	return undef;
    }

    #
    # Remove current group from glist, then add gid twice at the front
    # of the list Order matters here, or we won't pick up all the groups
    # we need.
    #
    $glist =~ s/ ?\b$default\b ?//;
    $glist = $default . " " . $default . " " . $glist;

    return $glist;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
#
# Return a list of the additional Unix groups a user is in. These are
# returned as plain integers.
#
sub UnixGroupList($$)
{
    my ($self, $prval) = @_;

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

1434
    my $uid_idx  = $self->uid_idx();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1435 1436 1437 1438 1439
    my @glist    = ();
    @$prval      = ();

    my $query_result =
	DBQueryWarn("select gid from unixgroup_membership ".
1440
		    "where uid_idx='$uid_idx'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
    return -1
	if (!defined($query_result));
    return 0
	if (!$query_result->numrows);

    while (my ($gid) = $query_result->fetchrow_array()) {
	push(@glist, $gid)
    }
    @$prval = @glist;
    return 0;
}

1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
#
# Flip to user, with the provided group as the default.
#
sub FlipTo($$)
{
    my ($self, $default_gid) = @_;

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

    my $glist = $self->GList($default_gid);
    return -1
	if (!defined($glist));

    $GID            = $default_gid;
    $EGID           = $glist;
    $EUID = $UID    = $self->unix_uid();
    $ENV{'USER'}    = $self->uid();
    $ENV{'LOGNAME'} = $self->uid();

    return 0;
}

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
#
# Update aggregate stats.
#
sub UpdateStats($$$$$)
{
    my ($self, $mode, $duration, $pnodes, $vnodes) = @_;
	
    # Must be a real reference. 
    return -1
	if (! ref($self));

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

    DBQueryWarn("update user_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 uid_idx='$uid_idx'");

    $self->Refresh();

    return 0;
}

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

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

    return 0;
}
1525

1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
#
# Check permissions.
#
sub AccessCheck($$$)
{
    my ($self, $user, $access_type) = @_;

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

    my $mintrust;

1539
    if ($access_type < TB_USERINFO_MIN() || $access_type > TB_USERINFO_MAX()) {
1540 1541 1542 1543 1544 1545 1546
	print "*** Invalid access type $access_type!\n";
	return 0;
    }
    # Admins do whatever they want!
    return 1
	if ($user->IsAdmin());

1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
    # User can muck with his own stuff.
    return 1
	if SameUser($self, $user);

    my $auth_idx = $user->uid_idx();
    my $this_idx = $self->uid_idx();

    #
    # Only project leader in same project as user.
    #
1557
    if ($access_type == TB_USERINFO_MODIFYINFO()) {
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
        #
        # This join will allow the operation if the current user is in the 
        # same project (any project) as the target user, but with root permissions.
        # 
	my $query_result =
	    DBQueryFatal("select g.trust from group_membership as g ".
			 "left join group_membership as authed on ".
			 "     g.pid_idx=authed.pid_idx and ".
			 "     g.gid_idx=authed.gid_idx and ".
			 "     g.uid_idx='$this_idx' ".
			 "where authed.uid_idx='$auth_idx' and ".
			 "      (authed.trust='project_root')");

	return $query_result->numrows;
    }
    return 0;
1574 1575
}

1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
#
# Home dir for user.
#
sub HomeDir($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return undef
	if (! ref($self));
    
    return USERROOT() . "/" . $self->uid();
}

1590 1591 1592 1593 1594
sub escapeshellarg($)
{
    my ($str) = @_;

    $str =~ s/[^[:alnum:]]/\\$&/g;
1595 1596
    $str =~ /^(.+)$/; # untaint the result
    return $1;
1597 1598
}

1599 1600 1601 1602
#############################################################################
# Non-local users, as for federation/geni.
#
package User::NonLocal;
1603
use emdb;
1604
use User;
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 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
use libtestbed;
use English;
use overload ('""' => 'Stringify');

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

#
# Lookup by idx.
#
sub Lookup($$)
{
    my ($class, $token) = @_;
    my $idx;
    my $query_result;

    if ($token =~ /^\d+$/) {
	$idx = $token;
    }
    elsif ($token =~ /^\w+\-\w+\-\w+\-\w+\-\w+$/) {
	$query_result =
	    DBQueryWarn("select uid_idx from nonlocal_users ".
			"where uid_uuid='$token'");
	    return undef
		if (! $query_result || !$query_result->numrows);

	    ($idx) = $query_result->fetchrow_array();
    }
    else {
	return undef;
    }
    
    # Look in cache first
    return $nonlocal_users{"$idx"}
        if (exists($nonlocal_users{"$idx"}));

    $query_result =
	DBQueryWarn("select * from nonlocal_users where uid_idx='$idx'");

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

1647 1648 1649 1650
    my $self          = {};
    $self->{'USER'}   = $query_result->fetchrow_hashref();
    # Want to know if this is a shadow of a local user.
    $self->{'SHADOW'} = User->Lookup($idx);
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667

    bless($self, $class);
    
    # Add to cache. 
    $nonlocal_users{$self->{'USER'}->{'uid_idx'}} = $self;
    
    return $self;
}
# accessors
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'USER'}->{$_[1]}); }
sub uid_idx($)		{ return field($_[0], "uid_idx"); }
sub idx($)		{ return field($_[0], "uid_idx"); }
sub uid($)		{ return field($_[0], "uid"); }
sub uid_uuid($)		{ return field($_[0], "uid_uuid"); }
sub created($)		{ return field($_[0], "created"); }
sub name($)		{ return field($_[0], "name"); }
sub email($)		{ return field($_[0], "email"); }
1668
sub shadow($)		{ return $_[0]->{'SHADOW'}; }
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $uid = $self->uid();
    my $idx = $self->idx();

    return "[NonLocalUser: $uid, IDX: $idx]";
}

#
1684
# Class function to create a new nonlocal user and return object.
1685
#
1686
sub Create($$$$$$;$)
1687
{
1688
    my ($class, $idx, $uid, $uuid, $name, $email, $sshkeys) = @_;
1689
    my @insert_data = ();
1690
    my $islocal = 0;
1691 1692

    # Every user gets a new unique index.
1693 1694 1695 1696 1697 1698 1699
    if (!defined($idx) || $idx == 0) {
	$idx = User->NextIDX();
    }
    else {
	# Sanity check.
	my $existing = User->Lookup($idx);
	if (defined($existing)) {
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
	    if ($uuid eq $existing->uuid()) {
		#
		# Shadow a local user, strictly for tmcd.
		#
		$islocal = 1;
	    }
	    else {
		print STDERR "NonLocal user with $idx exists: $existing\n";
		return undef;
	    }
1710 1711
	}
    }
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725

    # Now tack on other stuff we need.
    push(@insert_data, "created=now()");
    push(@insert_data, "uid_idx='$idx'");

    my $safe_uid   = DBQuoteSpecial($uid);
    my $safe_name  = DBQuoteSpecial($name);
    my $safe_email = DBQuoteSpecial($email);
    my $safe_uuid  = DBQuoteSpecial($uuid);
    push(@insert_data, "uid=$safe_uid");
    push(@insert_data, "name=$safe_name");
    push(@insert_data, "email=$safe_email");
    push(@insert_data, "uid_uuid=$safe_uuid");

1726
    if (defined($sshkeys)) {
1727 1728
	foreach my $sshkey (@{ $sshkeys }) {
	    my $safe_sshkey = DBQuoteSpecial($sshkey);
1729

1730
	    DBQueryWarn("insert into nonlocal_user_pubkeys set ".
1731 1732 1733 1734
			"  uid=$safe_uid, uid_idx='$idx', ".
			"  idx=NULL, stamp=now(), pubkey=$safe_sshkey")
		or return undef;
	}
1735
    }
1736

1737 1738 1739
    # Insert into DB.
    if (!DBQueryWarn("insert into nonlocal_users set " .
		     join(",", @insert_data))) {
1740
	DBQueryWarn("delete from nonlocal_user_pubkeys where uid_idx='$idx'")
1741
	    if (!$islocal);
1742 1743
	return undef;
    }
1744 1745 1746
    return User::NonLocal->Lookup($idx);
}

1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
#
# Modify the keys.
#
sub ModifyKeys($$)
{
    my ($self, $sshkeys) = @_;

    my $idx = $self->uid_idx();
    my $uid = $self->uid();
    
1757
    DBQueryWarn("delete from nonlocal_user_pubkeys where uid_idx='$idx'")
1758 1759 1760 1761 1762 1763
	or return -1;
    
    if (defined($sshkeys)) {
	foreach my $sshkey (@{ $sshkeys }) {
	    my $safe_sshkey = DBQuoteSpecial($sshkey);

1764
	    DBQueryWarn("insert into nonlocal_user_pubkeys set ".
1765 1766 1767 1768 1769 1770 1771 1772
			"  uid='$uid', uid_idx='$idx', ".
			"  idx=NULL, stamp=now(), pubkey=$safe_sshkey")
		or return -1;
	}
    }
    return 0;
}

1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
#
# Delete the user, as for registration errors.
#
sub Delete($)
{
    my ($self) = @_;

    return 0
	if (! ref($self));

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

1785 1786
    DBQueryWarn("delete from nonlocal_user_pubkeys where uid_idx='$idx'")
	or return -1;
1787 1788
    DBQueryWarn("delete from nonlocal_user_bindings where uid_idx='$idx'")
	or return -1;
1789 1790 1791 1792 1793 1794
    DBQueryWarn("delete from nonlocal_users where uid_idx='$idx'")
	or return -1;
    
    return 0;
}

1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
#
# Bind nonlocal user to experiment (slice, in Geni).
#
sub BindToExperiment($$)
{
    my ($self, $experiment) = @_;

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

    my $uid     = $self->uid();
    my $idx     = $self->idx();
    my $exptidx = $experiment->idx();
    
    # Insert into DB.
    DBQueryWarn("replace into nonlocal_user_bindings set " .
		"  uid='$uid', uid_idx='$idx', exptidx='$exptidx'")
	or return -1;

    return 0;
}

sub UnBindFromExperiment($$)
{
    my ($self, $experiment) = @_;

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

    my $uid     = $self->uid();
    my $idx     = $self->idx();
    my $exptidx = $experiment->idx();
    
    # Insert into DB.
    DBQueryWarn("delete from nonlocal_user_bindings " .
		"where uid_idx='$idx' and exptidx='$exptidx'")
	or return -1;

    return 0;
}

1836 1837
# _Always_ make sure that this 1 is at the end of the file...
1;
1838