accountsetup.in 27.3 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2010-2016 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 23 24 25 26 27 28 29 30 31 32 33
# 
# {{{GENIPUBLIC-LICENSE
# 
# GENI Public License
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
# 
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
# 
# }}}
#
use strict;
use English;
use Getopt::Std;
use Data::Dumper;
34
use Fcntl;
35 36 37

#
# Setup accounts/projects/group stuff on ops/fs. This is installed on
38
# op/fs and invoked from boss by tbacct and the proj/group scripts.
39 40 41 42 43 44
#
sub usage()
{
    print "Usage: accountsetup adduser ...\n";
    print "       accountsetup deluser ...\n";
    print "       accountsetup moduser ...\n";
45
    print "       accountsetup setgroups ...\n";
46
    print "       accountsetup chpass ...\n";
47 48 49 50
    print "       accountsetup addproject ...\n";
    print "       accountsetup addgroup ...\n";
    print "       accountsetup delproject ...\n";
    print "       accountsetup delgroup ...\n";
51 52
    print "       accountsetup checkdotfiles ...\n";
    print "       accountsetup createsshkey ...\n";
53
    print "       accountsetup dropfile ...\n";
54 55
    print "       accountsetup deactivateuser ...\n";
    print "       accountsetup reactivateuser ...\n";
56 57
    exit(1);
}
58
my $optlist    = "dnf";
59 60 61
my $debug      = 0;
my $force      = 0;
my $impotent   = 0;
62 63 64

# XXX make this a sitevar
my $RENAMEDIRS = 1;
65 66 67 68 69

#
# Configure variables
#
my $TB		      = "@prefix@";
70
my $USERPATH          = "$TB/bin";
71
my $WITHZFS	      = @WITHZFS@;
72
my $ZFS_NOEXPORT      = @ZFS_NOEXPORT@;
73
my $OURDOMAIN         = "@OURDOMAIN@";
74 75 76 77
my $ZFS_ROOT          = "@ZFS_ROOT@";
my $ZFS_QUOTA_USER    = "@ZFS_QUOTA_USER@";
my $ZFS_QUOTA_PROJECT = "@ZFS_QUOTA_PROJECT@";
my $ZFS_QUOTA_GROUP   = "@ZFS_QUOTA_GROUP@";
78
my $PW		      = "/usr/sbin/pw";
79 80 81 82 83 84
my $USERADD	      = "/usr/sbin/pw useradd";
my $USERDEL	      = "/usr/sbin/pw userdel";
my $USERMOD	      = "/usr/sbin/pw usermod";
my $GROUPADD          = "/usr/sbin/pw groupadd";
my $GROUPDEL          = "/usr/sbin/pw groupdel";
my $CHPASS	      = "/usr/bin/chpass";
85
my $CHOWN	      = "/usr/sbin/chown";
86 87
my $CHMOD	      = "/bin/chmod";
my $MKDIR	      = "/bin/mkdir";
88
my $NOLOGIN	      = "/sbin/nologin";
89
my $MV		      = "/bin/mv";
90
my $ZFS		      = "/sbin/zfs";
91
my $KEYGEN	      = "/usr/bin/ssh-keygen";
92
my $SKEL	      = "/usr/share/skel";
93
my $PIDFILE           = "/var/run/mountd.pid";
94
my $TSFILE	      = "/var/run/mountd.ts";
95 96 97 98 99 100 101 102 103 104 105

# XXX
my $NOSUCHUSER  = 67;
my $USEREXISTS  = 65;

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libtestbed;

106
# Generic (mounted) names for filesystems
107
my $USERROOT    = USERROOT();
108 109
my $PROJROOT    = PROJROOT();
my $GROUPROOT   = GROUPROOT();
110 111
my $SCRATCHROOT = SCRATCHROOT();

112
# XXX we need the real fs mountpoints too
113 114 115 116
my $FSUSERROOT    = "@FSDIR_USERS@";
my $FSPROJROOT    = "@FSDIR_PROJ@";
my $FSGROUPROOT   = "@FSDIR_GROUPS@";
my $FSSCRATCHROOT = "@FSDIR_SCRATCH@";
117

118 119 120 121 122 123
# Project subdir list
my @DIRLIST  = ("exp", "images", "logs", "deltas", "tarfiles", "rpms",
		"groups", "tiplogs", "images/sigs", "templates");
# Groups subdir list
my @GDIRLIST = ("exp", "images", "logs", "tarfiles", "rpms", "tiplogs");

124 125 126 127 128
#
# Function prototypes
#
sub AddUser();
sub DeleteUser();
129
sub SetGroups();
130
sub ModifyUser();
131
sub ChangePassword();
132 133 134 135
sub AddProject();
sub AddGroup();
sub DelProject();
sub DelGroup();
136
sub DropFile();
137 138
sub CheckDotFiles();
sub CreateSSHKey();
139 140
sub ReactivateUser();
sub DeactivateUser();
141
sub fatal($);
142
sub SetDotGroup($$);
143
sub ZFSexists($);
144
sub MakeDir($$);
145
sub WhackDir($$);
146
sub mysystem($);
147
sub runBusyLoop($);
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 185

#
# Check args.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
if (defined($options{"f"})) {
    $force = 1;
}
if (defined($options{"n"})) {
    $impotent = 1;
}
usage()
    if (@ARGV < 1);

my $cmd = shift(@ARGV);

#
# Now dispatch operation.
#
SWITCH: for ($cmd) {
    /^adduser$/ && do {
	AddUser();
	last SWITCH;
    };
    /^deluser$/ && do {
	DeleteUser();
	last SWITCH;
    };
    /^moduser$/ && do {
	ModifyUser();
	last SWITCH;
    };
186 187 188 189
    /^setgroups$/ && do {
	SetGroups();
	last SWITCH;
    };
190 191 192 193
    /^chpass$/ && do {
	ChangePassword();
	last SWITCH;
    };
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
    /^addproject$/ && do {
	AddProject();
	last SWITCH;
    };
    /^addgroup$/ && do {
	AddGroup();
	last SWITCH;
    };
    /^delproject$/ && do {
	DelProject();
	last SWITCH;
    };
    /^delgroup$/ && do {
	DelGroup();
	last SWITCH;
    };
210 211 212 213
    /^dropfile$/ && do {
	DropFile();
	last SWITCH;
    };
214 215 216 217 218 219 220 221
    /^checkdotfiles$/ && do {
	CheckDotFiles();
	last SWITCH;
    };
    /^createsshkey$/ && do {
	CreateSSHKey();
	last SWITCH;
    };
222 223 224 225 226 227 228 229
    /^deactivateuser$/ && do {
	DeactivateUser();
	last SWITCH;
    };
    /^reactivateuser$/ && do {
	ReactivateUser();
	last SWITCH;
    };
230 231 232 233 234
    # Default
    usage();
}
exit(0);

235 236 237
#
# Usage: adduser username unix_uid full_name homedir unix_gid shell [ phash ]
#
238 239 240 241 242 243 244 245 246 247 248 249 250
sub AddUser()
{
    if (@ARGV < 6) {
	fatal("adduser: Wrong number of arguments");
    }
    
    my $user  = shift(@ARGV);
    my $uid   = shift(@ARGV);
    my $name  = shift(@ARGV);
    my $hdir  = shift(@ARGV);
    my $gid   = shift(@ARGV);
    my $shell = shift(@ARGV);

251 252 253 254
    if (! -d "$hdir") {
	# XXX we only handle homedirs of the form /users/$user here...
	if ($hdir ne "$USERROOT/$user" || MakeDir($USERROOT, $user)) {
	    fatal("Could not create $user homedir $hdir");
255 256 257
	}
    }

258
    if (mysystem("egrep -q -s '^${user}:' /etc/passwd") &&
259 260
	runBusyLoop("$USERADD $user -u $uid -c \"$name\" ".
		    "-k $SKEL -h - -d $hdir -g $gid -s $shell")) {
261 262 263 264
	if (($? >> 8) != $USEREXISTS) {
	    fatal("$USERADD: could not add account");
	}
    }
265 266 267 268 269 270 271 272 273 274

    #
    # Since we do not populate the new homedir with the useradd call,
    # we need to copy the skeleton files over.
    #
    if (! -e "$hdir/.cshrc") {
	opendir(DIR, "$SKEL") or
	    fatal("Unable to open skeleton directory");
	while (my $file = readdir(DIR)) {
	    if ($file =~ /^dot(.*)$/) {
275
		mysystem("/bin/cp -fp $SKEL/$file $hdir/$1") == 0
276
		    or fatal("Could not copy $SKEL/$file to $hdir/$1");
277 278
	    }
	}
279

Mike Hibler's avatar
Mike Hibler committed
280 281 282 283 284 285
	#
	# And set the owner and group right on everything
	#
	mysystem("/usr/sbin/chown -R $user:$gid $hdir") == 0
	    or fatal("Could not chown $hdir");
    }
286 287 288 289 290 291 292 293 294 295
    #
    # Some directories we need, with proper owner/group/mode
    #
    foreach my $dir (".ssl", ".ssh") {
	if (! -e "$hdir/$dir" &&
	    !mkdir("$hdir/$dir", 0700)) {
	    fatal("Could not make directory '$hdir/$dir': $!");
	}
	mysystem("$CHOWN -R $user:$gid $hdir/$dir") == 0
	    or fatal("Could not chown $hdir/$dir to $user:$gid");
296

297 298 299
	chmod(0700, "$hdir/$dir")
	    or fatal("Could not chmod '$hdir/$dir' to 0700: $!");
    }
300 301 302
    return 0;
}

303 304 305
#
# Usage: deluser username homedir
#
306 307 308 309 310 311 312 313
sub DeleteUser()
{
    if (@ARGV != 2) {
	fatal("deluser: Wrong number of arguments");
    }
    my $user  = shift(@ARGV);
    my $hdir  = shift(@ARGV);

314 315 316 317
    #
    # Note that this does NOT remove the user's homedir.
    # We remove/rename it below...
    #
318
    if (runBusyLoop("$USERDEL $user")) {
319 320 321 322
	if (($? >> 8) != $NOSUCHUSER) {
	    fatal("Could not remove user $user");
	}
    }
323 324

    # XXX we only handle homedirs of the form /users/$user here...
325 326
    if ($hdir ne "$USERROOT/$user" ||
	(-e $hdir && WhackDir($USERROOT, $user))) {
327
	fatal("Could not destroy $user homedir $hdir");
328
    }
329

330 331 332
    return 0;
}

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
#
# Usage: moduser username shell full_name
#
sub ModifyUser()
{
    if (@ARGV != 3) {
	fatal("moduser: Wrong number of arguments");
    }
    
    my $user  = shift(@ARGV);
    my $shell = shift(@ARGV);
    my $name  = shift(@ARGV);

    if (runBusyLoop("$USERMOD $user -c \"$name\" -s $shell")) {
	fatal("$USERMOD: could not modify account");
    }
    return 0;
}

352
#
353 354
# Usage: username group1 [ group2 ... groupN ]
# XXX this is specific to what is required by setgroups.
355
#
356
sub SetGroups()
357
{
358
    if (@ARGV < 2) {
359
	fatal("setgroups: Wrong number of arguments");
360 361 362
    }
    my $user  = shift(@ARGV);
    my $pgroup  = shift(@ARGV);
363
    my $grouplist = "''";
364
    if (@ARGV > 0) {
365
	$grouplist = "-G '" . join(',', @ARGV) . "'";
366
    }
367
    if (runBusyLoop("$USERMOD $user -g $pgroup $grouplist")) {
368
	fatal("Could not modify user $user to add groups!\n");
369
    }
370
    SetDotGroup($user, $pgroup);
371
    return 0;
372 373
}

374 375 376 377 378 379 380 381
sub ChangePassword()
{
    if (@ARGV != 2) {
	fatal("chpass: Wrong number of arguments");
    }
    my $user  = shift(@ARGV);
    my $hash  = shift(@ARGV);

382
    if (runBusyLoop("$CHPASS -p '$hash' $user")) {
383 384 385 386 387
	fatal("Could not change password");
    }
    return 0;
}

388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
#
# Usage: deactivate username
#
sub DeactivateUser()
{
    if (@ARGV != 1) {
	fatal("deactivateuser: Wrong number of arguments");
    }
    my $user = shift(@ARGV);

    if ($WITHZFS) {
	my $zfsdir = $ZFS_ROOT . USERROOT() . "/$user";
	if (ZFSexists($zfsdir) &&
	    mysystem("$ZFS set mountpoint=none $zfsdir")) {
	    fatal("Could not set ZFS dir $zfsdir to mountpoint=none");
	}
    }
405
    if (runBusyLoop("$USERMOD $user -d /var/empty -s $NOLOGIN")) {
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
	fatal("Could not set shell to $NOLOGIN");
    }
    return 0;
}

#
# Usage: reactivate username
#
# The shell is changed via ModifyUser (we do not know the correct
# shell here), this is just for ZFS.
#
sub ReactivateUser()
{
    if (@ARGV != 1) {
	fatal("reactivateuser: Wrong number of arguments");
    }
    my $user = shift(@ARGV);
423
    my $hdir = USERROOT() . "/$user";
424 425 426 427 428 429 430 431

    if ($WITHZFS) {
	my $zfsdir = $ZFS_ROOT . USERROOT() . "/$user";
	if (ZFSexists($zfsdir) &&
	    mysystem("$ZFS set mountpoint=$hdir $zfsdir")) {
	    fatal("Could not set ZFS dir $zfsdir to mountpoint=$hdir");
	}
    }
432
    if (runBusyLoop("$USERMOD $user -d $hdir")) {
433 434
	fatal("Could not set home directory back to $hdir");
    }
435 436 437 438 439 440 441 442 443 444
    #
    # Make dot files are in the right group, since while the user was
    # inactive, we skipped doing that cause the home dir was unmounted
    # (ZFS). Need the current default group for that.
    #
    my (undef,undef,undef,$gid) = getpwnam($user);
    if (!defined($gid)) {
	fatal("Could not get gid for $user");
    }
    SetDotGroup($user,$gid);
445 446 447
    return 0;
}

448 449 450
#
# Usage: addproject projname unix_gname unix_gid unix_uid
#
451 452
sub AddProject()
{
453
    if (@ARGV != 4) {
454 455 456 457
	fatal("addproject: Wrong number of arguments");
    }
    my $name      = shift(@ARGV);
    my $unix_name = shift(@ARGV);
458 459
    my $unix_gid  = shift(@ARGV);
    my $unix_uid  = shift(@ARGV);
460

461
    # Create the project unix group
462
    if (mysystem("egrep -q -s '^${unix_name}:' /etc/group")) {
463 464
	print "Adding group $unix_name ...\n";

465
	if (runBusyLoop("$GROUPADD $unix_name -g $unix_gid")) {
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
	    fatal("Could not add group $unix_name ($unix_gid)!\n");
	}
    }

    # Create the /proj directory
    my $path = "$PROJROOT/$name";
    if (! -d "$path" && MakeDir($PROJROOT, $name)) {
	fatal("Could not make directory '$path'");
    }
    if (! chmod(0770, "$path")) {
	fatal("Could not chmod '$path' to 0770: $!");
    }
    if (! chown($unix_uid, $unix_gid, "$path")) {
	fatal("Could not chown '$path' to $unix_uid/$unix_gid: $!");
    }

    # Create required /proj subdirs
    foreach my $dir (@DIRLIST) {
	$path = "$PROJROOT/$name/$dir";
	if (! -d "$path" && !mkdir("$path", 0770)) {
	    fatal("Could not make directory '$path': $!");
487
	}
488 489 490 491 492
	if (! chmod(0770, "$path")) {
	    fatal("Could not chmod '$path' to 0770: $!");
	}
	if (! chown($unix_uid, $unix_gid, "$path")) {
	    fatal("Could not chown '$path' to $unix_uid/$unix_gid: $!");
493 494 495
	}
    }

496 497 498 499 500 501 502 503 504 505 506
    # Create the /groups directory
    $path = "$GROUPROOT/$name";
    if (! -d "$path" && MakeDir($GROUPROOT, $name)) {
	fatal("Could not make directory '$path'");
    }
    if (! chmod(0770, "$path")) {
	fatal("Could not chmod '$path' to 0770: $!");
    }
    if (! chown($unix_uid, $unix_gid, "$path")) {
	fatal("Could not chown '$path'  to $unix_uid/$unix_gid: $!");
    }
507

508 509 510
    # Create a symlink for the default group
    $path = "$GROUPROOT/$name/$name";
    if (! -e "$path") {    
511
	if (mysystem("ln -s $PROJROOT/$name $path")) {
512
	    fatal("Could not symlink $PROJROOT/$name to $path");
513 514
	}
    }
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529

    # Finally, create /scratch dir if supported
    if ($SCRATCHROOT) {
	$path = "$SCRATCHROOT/$name";
	if (! -d "$path" && MakeDir($SCRATCHROOT, $name)) {
	    fatal("Could not make directory '$path'");
	}
	if (! chmod(0770, "$path")) {
	    fatal("Could not chmod '$path' to 0770: $!");
	}
	if (! chown($unix_uid, $unix_gid, "$path")) {
	    fatal("Could not chown '$path'  to $unix_uid/$unix_gid: $!");
	}
    }

530 531 532
    return 0;
}

533 534 535
#
# Usage: addgroup groupname unix_gname unix_gid unix_uid projname
#
536 537
sub AddGroup()
{
538
    if (@ARGV != 5) {
539 540 541 542
	fatal("addgroup: Wrong number of arguments");
    }
    my $name      = shift(@ARGV);
    my $unix_name = shift(@ARGV);
543 544 545
    my $unix_gid  = shift(@ARGV);
    my $unix_uid  = shift(@ARGV);
    my $projname  = shift(@ARGV);
546

547
    # Create the group unix group
548
    if (mysystem("egrep -q -s '^${unix_name}:' /etc/group")) {
549 550
	print "Adding group $unix_name ...\n";

551
	if (runBusyLoop("$GROUPADD $unix_name -g $unix_gid")) {
552 553 554 555 556
	    fatal("Could not add group $unix_name ($unix_gid)!\n");
	}
    }

    # Create the /groups/gid directory
557
    my $path = "$GROUPROOT/$projname/$name";
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
    # XXX note that this is always a regular directory, not a filesystem
    if (! -d "$path" && !mkdir("$path", 0770)) {
	fatal("Could not make directory '$path': $!");
    }
    if (! chmod(0770, "$path")) {
	fatal("Could not chmod '$path' to 0770: $!");
    }
    if (! chown($unix_uid, $unix_gid, "$path")) {
	fatal("Could not chown '$path' to $unix_uid/$unix_gid: $!");
    }

    # Create required /groups/gid subdirs
    foreach my $dir (@GDIRLIST) {
	$path = "$GROUPROOT/$projname/$name/$dir";
	if (! -d "$path" && !mkdir("$path", 0770)) {
	    fatal("Could not make directory '$path': $!");
	}
	if (! chmod(0770, "$path")) {
	    fatal("Could not chmod '$path' to 0770: $!");
	}
	if (! chown($unix_uid, $unix_gid, "$path")) {
	    fatal("Could not chown '$path' to $unix_uid/$unix_gid: $!");
580 581
	}
    }
582

583 584 585
    return 0;
}

586 587 588
#
# Usage: delproject projname unix_gname
#
589 590 591 592 593 594 595 596
sub DelProject()
{
    if (@ARGV != 2) {
	fatal("delproject: Wrong number of arguments");
    }
    my $name       = shift(@ARGV);
    my $unix_name  = shift(@ARGV);

597 598 599 600
    if ((-d "$PROJROOT/$name" && WhackDir($PROJROOT, $name)) ||
	(-d "$GROUPROOT/$name" && WhackDir($GROUPROOT, $name)) ||
	($SCRATCHROOT && -d "$SCRATCHROOT/$name" &&
	 WhackDir($SCRATCHROOT, $name))) {
601
	fatal("Could not destroy project '$name' related directories");
602
    }
603

604
    if (mysystem("egrep -q -s '^${unix_name}:' /etc/group") == 0) {
605 606
	print "Deleting project $unix_name ...\n";

607
	if (runBusyLoop("$GROUPDEL $unix_name")) {
608 609 610 611 612 613
	    fatal("Could not delete group $unix_name!\n");
	}
    }
    return 0;
}

614 615 616
#
# Usage: delgroup groupname unix_gname projname
#
617 618
sub DelGroup()
{
619
    if (@ARGV != 3) {
620 621 622 623
	fatal("delgroup: Wrong number of arguments");
    }
    my $name      = shift(@ARGV);
    my $unix_name = shift(@ARGV);
624
    my $projname   = shift(@ARGV);
625

626 627 628 629
    #
    # XXX groups are different because they are a subdirectory under
    # /groups/<pid>/.
    #
630 631
    if (-d "$GROUPROOT/$projname/$name" &&
	WhackDir($GROUPROOT, "$projname/$name")) {
632 633 634
	fatal("Could not destroy project group '$name' related directories");
    }

635
    if (mysystem("egrep -q -s '^${unix_name}:' /etc/group") == 0) {
636 637
	print "Deleting group $unix_name ...\n";

638
	if (runBusyLoop("$GROUPDEL $unix_name")) {
639 640 641 642 643 644
	    fatal("Could not delete group $unix_name!\n");
	}
    }
    return 0;
}

645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
#
# Drop a file into place. The file is piped into STDIN from boss.
#
sub DropFile()
{
    if (@ARGV != 5) {
	fatal("dropfile: Wrong number of arguments");
    }
    my $user  = shift(@ARGV);
    my $gid   = shift(@ARGV);
    my $mode  = shift(@ARGV);
    my $dir   = shift(@ARGV);
    my $fname = shift(@ARGV);
    my $file  = "$dir/$fname";

    # Default the directory creation to 770. Might need to specify this too.
    if (! -d "$dir" && mysystem("$MKDIR -m 770 -p $dir")) {
	fatal("Could not make directory '$dir'");
    }
    #
    # We want the file to have the proper mode before we try to write it,
    # to avoid a race that allows someone to see the contents.
    #
668
    if (-e $file && mysystem("$MV -f $file ${file}.save")) {
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
	fatal("Could not rename $file to ${file}.save");
    }
    sysopen(HANDLE, $file, O_WRONLY|O_CREAT|O_EXCL, 0600)
	or fatal("sysopen $file: $!");
    while (<STDIN>) {
	print HANDLE $_;
    }
    close(HANDLE);
    mysystem("$CHOWN $user:$gid $file") == 0
	or fatal("Could not chown $file to $user:$gid");
    mysystem("$CHMOD $mode $file") == 0
	or fatal("Could not chmod '$file' to $mode");
    return 0;
}

684 685 686 687 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
#
# Check the dot files.
#
sub CheckDotFiles()
{
    if (@ARGV != 3) {
	fatal("checkdotfiles: Wrong number of arguments");
    }
    my $user  = shift(@ARGV);
    my $gid   = shift(@ARGV);
    my $email = shift(@ARGV);

    my $forward = "$USERROOT/$user/.forward";
    my $cshrc   = "$USERROOT/$user/.cshrc";
    my $profile = "$USERROOT/$user/.profile";

    # Just in case we got called before account created.
    return 0
	if (! -d "$USERROOT/$user");

    #
    # Set up a .forward file so that any email to them gets forwarded off.
    #
    print "Setting up .forward file for $user.\n";

    sysopen(HANDLE, $forward, O_WRONLY|O_CREAT|O_TRUNC, 0600)
	or fatal("sysopen $forward: $!");
    print HANDLE "$email\n";
    close(HANDLE);
    mysystem("$CHOWN $user:$gid $forward") == 0
	or fatal("Could not chown $forward to $user:$gid");
    mysystem("$CHMOD 644 $forward") == 0
	or fatal("Could not chmod '$forward' to 644");

    #
    # Add testbed path to .cshrc and .profile.
    # Plus a conditional Cygwin section for the Windows system path.
    #
    my $cpathstr = "set path = ($USERPATH \$path)\n" .
    'if ( `uname -s` =~ CYGWIN* ) then' . "\n" .
    '    setenv PATH "${PATH}:/cygdrive/c/WINDOWS/system32:/cygdrive/c/WINDOWS"' . "\n" .
    'endif';
    if (-e $cshrc && system("egrep -q -s '$USERPATH' $cshrc")) {
	system("echo '$cpathstr' >> $cshrc");
    }

    my $spathstr = "PATH=$USERPATH:\$PATH\n" .
    'if [[ `uname -s` == CYGWIN* ]]; then' . "\n" .
    '    PATH="$PATH":/cygdrive/c/WINDOWS/system32:/cygdrive/c/WINDOWS' . "\n" .
    'fi';
    if (-e $profile && system("egrep -q -s '$USERPATH' $profile")) {
	system("echo '$spathstr' >> $profile");
    }
    return 0;
}

#
# Create ssh keys for user, sending back the pub part. This is a little
# incovenient since we generate two keys (V1 and V2) but can send back
# just one at a time via STDOUT (do not want to parse anything).
#
sub CreateSSHKey()
{
    if (@ARGV != 3) {
	fatal("createsshkey: Wrong number of arguments");
    }
    my $user   = shift(@ARGV);
    my $gid    = shift(@ARGV);
    my $type   = shift(@ARGV);
    my $sshdir = "$USERROOT/$user/.ssh";
    my $sshkey = "$sshdir/";

756
    if ($type eq "rsa1") {
757 758
	$sshkey .= "identity";
    }
759
    elsif ($type eq "rsa") {
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
	$sshkey .= "id_rsa";
    }
    else {
	fatal("Bad key type: $type");
    }
    unlink($sshkey)
	if (-e $sshkey);
    #
    # Since we send the key back via STDOUT, make sure all output
    # goes to STDERR.
    #
    mysystem("$KEYGEN -t $type -P '' -f $sshkey ".
	     "-C '${type}" . "\@" . ${OURDOMAIN} . "' 1>&2") == 0
	or fatal("Failure in ssh-keygen!");
    mysystem("$CHOWN $user:$gid $sshkey ${sshkey}.pub") == 0
	or fatal("Could not chown $sshkey to $user:$gid");
    
    # Return the key via STDOUT to boss.
    my $ident = `cat ${sshkey}.pub`;
    print STDOUT $ident;
    return 0;
}

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 812
#
# Make sure the users dot files and other critical files/dirs
# are in the correct group. I looked at the source code to
# chown, and it does not do anything to files that are already
# set correctly. Thank you chown.
#
sub SetDotGroup($$)
{
    my ($user, $gid) = @_;

    my @dots = (".login", ".profile", ".cshrc", ".ssl", ".ssh");
    my $homedir = USERROOT() . "/$user";

    if (! -e $homedir) {
	print STDERR "$homedir does not exist, skipping dots chown\n";
	return 0;
    }
    print "Changing dot files group for $user to $gid\n";
    
    mysystem("$CHOWN $user:$gid $homedir") == 0
	or fatal("Could not chown home dir to $user:$gid");

    foreach my $dot (@dots) {
	if (-e "$homedir/$dot") {
	    mysystem("$CHOWN -R $user:$gid $homedir/$dot") == 0
		or fatal("Could not chown $homedir/$dot to $user:$gid");
	}
    }
}

813 814 815 816 817 818 819
#
# Check for ZFS existence.
#
sub ZFSexists($)
{
    my ($path) = @_;

820
    mysystem("$ZFS list $path >/dev/null 2>&1");
821 822
    return ($? ? 0 : 1);
}
823

824
sub MakeDir($$)
825
{
826 827
    my ($fs,$dir) = @_;
    my ($cmd,$cmdarg,$path);
828

829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
    # XXX right now we assume that WITHZFS means per-user/proj FSes
    if ($WITHZFS) {
	$cmd = "$ZFS create";
	$path = "${ZFS_ROOT}${fs}/$dir";

	# XXX quotas
	if ($fs eq $USERROOT) {
	    $cmdarg = "-o quota=$ZFS_QUOTA_USER";
	} elsif ($fs eq $PROJROOT) {
	    $cmdarg = "-o quota=$ZFS_QUOTA_PROJECT";
	} elsif ($fs eq $GROUPROOT) {
	    $cmdarg = "-o quota=$ZFS_QUOTA_GROUP";
	} else {
	    $cmdarg = "";
	}
844
    } else {
845 846 847 848
	$cmd = "mkdir";
	$cmdarg = "";
	$path = "$fs/$dir";
    }
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
    #
    # If we are relying on ZFS to HUP mountd (!ZFS_NOEXPORT), then we have to
    # give mountd a chance to finish its work before we return. This is because
    # it is likely that our caller (on boss) will try to access the directory
    # via NFS after we return and if mountd is not done, that will fail.
    # If ZFS_NOEXPORT is set, then our caller will do the HUPing and waiting.
    #
    my $waitforit = 0;
    if (!$ZFS_NOEXPORT) {
	#
	# Note that "waiting for mountd" involves a Utah hack to mountd to
	# make it record a timestamp in a file when it is done. If there is
	# no timestamp file, assume we are not running the hacked mountd and
	# don't sleep. If the file exists, remove it and wait for it to
	# reappear as a sign mountd is done.
	#
	# XXX since we cannot guarantee that mountd gets HUP'ed when we
	# call zfs (i.e., the command fails or the nfsshare attribute is
	# not set correctly) we save the old timestamp and put it back
	# on failures. Otherwise, the next call to us or exports_setup will
	# not properly wait for mountd.
	#
	if (-e "$TSFILE" && rename("$TSFILE", "$TSFILE.bak") != 0) {
	    $waitforit = 1;
	}
    }

876
    if (mysystem("$cmd $cmdarg $path")) {
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
	my $stat = $?;
	if ($waitforit && !rename("$TSFILE.bak", "$TSFILE")) {
	    print STDERR "accountsetup: could not replace $TSFILE;".
		" You must HUP mountd\n";
	}
	return $stat;
    }

    if ($waitforit) {
	# With potentially thousands of mount points, this can take 15 seconds!
	my $wtime = 15;
	my $i;

	for ($i = 0; $i < $wtime; $i++) {
	    if (-e "$TSFILE") {
		print "accountsetup: mountd done.\n"
		    if ($i > 0);
		last;
	    }
	    print "accountsetup: waiting for mountd to finish ($i)...\n";
	    sleep(1);
	}
	if ($i == $wtime) {
	    print STDERR "accountsetup: mountd not finished after $i seconds;".
		"Perhaps ZFS sharenfs attribute not set on $path?\n";
	    if (!rename("$TSFILE.bak", "$TSFILE")) {
		print STDERR "accountsetup: could not replace $TSFILE;".
		    " You must HUP mountd\n";
	    }
	} else {
	    unlink("$TSFILE.bak");
	}
909 910
    }

911
    # should we be setting permissions or ownership here?
912

913 914 915 916 917 918 919
    return 0;
}

sub WhackDir($$)
{
    my ($fs,$dir) = @_;
    my $zfsfs = "";
920 921

    if ($WITHZFS) {
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
	my $path = "${ZFS_ROOT}${fs}/$dir";
	$zfsfs = $path
	    if (ZFSexists($path));
    }
    if ($RENAMEDIRS) {
	my ($cmd, $path, $npath);
	my $suffix = "-D" . time();

	if ($zfsfs) {
	    $cmd = "$ZFS rename";
	    $path = $zfsfs;
	    $npath = "${ZFS_ROOT}${fs}/$dir$suffix";
	} else {
	    $cmd = "mv";
	    $path = "$fs/$dir";
	    $npath = "$fs/$dir$suffix";
938
	}
939
	if (mysystem("$cmd $path $npath")) {
940 941
	    return $?;
	}
942 943

	# Since we reuse uid/gids let's make the dir root/0700
Mike Hibler's avatar
Mike Hibler committed
944 945
	$path = "$fs/$dir$suffix";
	if (!chown(0, 0, $path) || !chmod(0700, $path)) {
946 947 948 949 950 951 952 953 954
	    print STDERR "WARNING: could not chown/chmod '$path': $!\n";
	}
	#
	# And then unmount, we do not need it around. The empty subdir
	# will still be there, so we have some clue ... maybe we should
	# drop a file into the empty dir?
	#
	if ($zfsfs && mysystem("$ZFS set mountpoint=none $npath")) {
	    print STDERR "Could not set ZFS dir $npath to mountpoint=none\n";
955 956 957 958 959 960 961
	}
    }
    #
    # XXX maybe we should do this in the background since it could
    # take a really long time!
    #
    else {
962 963 964 965 966 967 968 969 970
	my ($cmd, $path);

	if ($zfsfs) {
	    $cmd = "$ZFS destroy -f";
	    $path = $zfsfs;
	} else {
	    $cmd = "rm -rf";
	    $path = "$fs/$dir";
	}
971
	if (mysystem("$cmd $path")) {
972
	    return $?;
973 974 975 976 977
	}
    }
    return 0;
}

978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
#
# HUP Mountd after changes to ZFS volumes. Not used, Mike says we
# can do "zfs share -a" instead, but I will leave this code here
# for now.
#
sub HUPMountd()
{
    if (! -e $PIDFILE) {
	fatal("$PIDFILE does not exist. Is mountd running?");
    }
    my $daemonpid = `cat $PIDFILE`;
    chomp($daemonpid);
    # untaint
    if ($daemonpid =~ /^([-\@\w.]+)$/) {
	$daemonpid = $1;
    }
    if (kill('HUP', $daemonpid) == 0) {
	fatal("Could not kill(HUP) process $daemonpid (mountd): $!");
    }
    # Give mountd time to react.
    sleep(1);
}
1000 1001 1002 1003 1004 1005 1006

# XXX temporary while debugging
sub mysystem($)
{
    my $cmd = shift;

    print STDERR "accountsetup: '$cmd'\n";
1007 1008 1009 1010 1011 1012

    if (open(FD, ">>/usr/testbed/log/accountsetup.log")) {
	my $tstamp = POSIX::strftime("%b %e %H:%M:%S", localtime());
	print FD "$tstamp: $cmd\n";
	close(FD);
    }
1013 1014
    return system($cmd);
}
1015

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
#
# Run pw/chpass, checking for a locked passwd/group file. The pw routines
# exit with non specific error code 1 for everything, so there is no way
# to tell that its a busy file except by looking at the error message. Then
# wait for a bit and try again. Silly.
#
sub runBusyLoop($)
{
    my $command   = shift;
    my $maxtries  = 10;
1026
    my $stime     = time();
1027 1028 1029 1030

    print STDERR "accountsetup: '$command'\n";

    if (open(FD, ">>/usr/testbed/log/accountsetup.log")) {
1031
	my $tstamp = POSIX::strftime("%b %e %H:%M:%S", localtime($stime));
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
	print FD "$tstamp: $command\n";
	close(FD);
    }

    while ($maxtries--) {
	my $output    = "";
    
	#
	# This open implicitly forks a child, which goes on to execute the
	# command. The parent is going to sit in this loop and capture the
	# output of the child. We do this so that we have better control
	# over the descriptors.
	#
	my $pid = open(PIPE, "-|");
	if (!defined($pid)) {
	    print STDERR "runBusyLoop; popen failed!\n";
	    return -1;
	}
	if ($pid) {
	    while (<PIPE>) {
		$output .= $_;
	    }
	    close(PIPE);
	    print $output;
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
	    if (!$?) {
		if ($command =~ /^$PW .*/) {
		    if (open(FD, ">>/usr/testbed/log/accountsetup.log")) {
			my $etime = time();
			my $tstamp = POSIX::strftime("%b %e %H:%M:%S",
						     localtime($etime));
			$etime -= $stime;
			print FD "$tstamp: $PW done in $etime seconds\n";
			close(FD);
		    }
		}
		return 0
	    }
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
	    if ($output =~ /(group|db) file is busy/m) {
		print "runBusyLoop; waiting a few seconds before trying again\n";
		sleep(3);
	    }
	}
	else {
	    open(STDERR, ">&STDOUT");
	    exec($command);
	}
    }
    return -1;
}

1082 1083 1084 1085 1086 1087
sub fatal($) {
    my ($msg) = @_;

    print STDERR "$msg\n";
    exit(-1);
}