accountsetup.in 27.7 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2010-2018 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 79 80
my $ZFS_QUOTA_USER_X  = "@ZFS_QUOTA_USER_X@";
my $ZFS_QUOTA_PROJECT_X = "@ZFS_QUOTA_PROJECT_X@";
my $ZFS_QUOTA_GROUP_X = "@ZFS_QUOTA_GROUP_X@";
81
my $PW		      = "/usr/sbin/pw";
82 83 84 85 86 87
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";
88
my $CHOWN	      = "/usr/sbin/chown";
89 90
my $CHMOD	      = "/bin/chmod";
my $MKDIR	      = "/bin/mkdir";
91
my $NOLOGIN	      = "/sbin/nologin";
92
my $MV		      = "/bin/mv";
93
my $ZFS		      = "/sbin/zfs";
94
my $KEYGEN	      = "/usr/bin/ssh-keygen";
95
my $SKEL	      = "/usr/share/skel";
96
my $PIDFILE           = "/var/run/mountd.pid";
97
my $TSFILE	      = "/var/run/mountd.ts";
98 99 100 101 102 103 104 105 106 107 108

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

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

109
# Generic (mounted) names for filesystems
110
my $USERROOT    = USERROOT();
111 112
my $PROJROOT    = PROJROOT();
my $GROUPROOT   = GROUPROOT();
113 114
my $SCRATCHROOT = SCRATCHROOT();

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

121 122 123 124 125 126
# 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");

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

#
# 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;
    };
189 190 191 192
    /^setgroups$/ && do {
	SetGroups();
	last SWITCH;
    };
193 194 195 196
    /^chpass$/ && do {
	ChangePassword();
	last SWITCH;
    };
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    /^addproject$/ && do {
	AddProject();
	last SWITCH;
    };
    /^addgroup$/ && do {
	AddGroup();
	last SWITCH;
    };
    /^delproject$/ && do {
	DelProject();
	last SWITCH;
    };
    /^delgroup$/ && do {
	DelGroup();
	last SWITCH;
    };
213 214 215 216
    /^dropfile$/ && do {
	DropFile();
	last SWITCH;
    };
217 218 219 220 221 222 223 224
    /^checkdotfiles$/ && do {
	CheckDotFiles();
	last SWITCH;
    };
    /^createsshkey$/ && do {
	CreateSSHKey();
	last SWITCH;
    };
225 226 227 228 229 230 231 232
    /^deactivateuser$/ && do {
	DeactivateUser();
	last SWITCH;
    };
    /^reactivateuser$/ && do {
	ReactivateUser();
	last SWITCH;
    };
233 234 235 236 237
    # Default
    usage();
}
exit(0);

238 239 240
#
# Usage: adduser username unix_uid full_name homedir unix_gid shell [ phash ]
#
241 242 243 244 245 246 247 248 249 250 251 252 253
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);

254 255 256 257
    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");
258 259 260
	}
    }

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

    #
    # 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(.*)$/) {
278
		mysystem("/bin/cp -fp $SKEL/$file $hdir/$1") == 0
279
		    or fatal("Could not copy $SKEL/$file to $hdir/$1");
280 281
	    }
	}
282

Mike Hibler's avatar
Mike Hibler committed
283 284 285 286 287 288
	#
	# And set the owner and group right on everything
	#
	mysystem("/usr/sbin/chown -R $user:$gid $hdir") == 0
	    or fatal("Could not chown $hdir");
    }
289 290 291 292 293 294 295 296 297 298
    #
    # 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");
299

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

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

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

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

333 334 335
    return 0;
}

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
#
# 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;
}

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

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

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

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
#
# 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");
	}
    }
408
    if (runBusyLoop("$USERMOD $user -d /var/empty -s $NOLOGIN")) {
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
	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);
426
    my $hdir = USERROOT() . "/$user";
427 428 429 430 431 432 433 434

    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");
	}
    }
435
    if (runBusyLoop("$USERMOD $user -d $hdir")) {
436 437
	fatal("Could not set home directory back to $hdir");
    }
438 439 440 441 442 443 444 445 446 447
    #
    # 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);
448 449 450
    return 0;
}

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

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

468
	if (runBusyLoop("$GROUPADD $unix_name -g $unix_gid")) {
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
	    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': $!");
490
	}
491 492 493 494 495
	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: $!");
496 497 498
	}
    }

499 500 501 502 503 504 505 506 507 508 509
    # 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: $!");
    }
510

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

    # 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: $!");
	}
    }

533 534 535
    return 0;
}

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

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

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

    # Create the /groups/gid directory
560
    my $path = "$GROUPROOT/$projname/$name";
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
    # 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: $!");
583 584
	}
    }
585

586 587 588
    return 0;
}

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

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

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

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

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

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

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

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

648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
#
# 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.
    #
671
    if (-e $file && mysystem("$MV -f $file ${file}.save")) {
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
	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;
}

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 756 757 758
#
# 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/";

759
    if ($type eq "rsa1") {
760 761
	$sshkey .= "identity";
    }
762
    elsif ($type eq "rsa") {
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
	$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;
}

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 813 814 815
#
# 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");
	}
    }
}

816 817 818 819 820 821 822
#
# Check for ZFS existence.
#
sub ZFSexists($)
{
    my ($path) = @_;

823
    mysystem("$ZFS list $path >/dev/null 2>&1");
824 825
    return ($? ? 0 : 1);
}
826

827
sub MakeDir($$)
828
{
829 830
    my ($fs,$dir) = @_;
    my ($cmd,$cmdarg,$path);
831

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

	# XXX quotas
838
	my ($refquota,$mult);
839
	if ($fs eq $USERROOT) {
840 841
	    $refquota = $ZFS_QUOTA_USER;
	    $mult = $ZFS_QUOTA_USER_X;
842
	} elsif ($fs eq $PROJROOT) {
843 844
	    $refquota = $ZFS_QUOTA_PROJECT;
	    $mult = $ZFS_QUOTA_PROJECT_X;
845
	} elsif ($fs eq $GROUPROOT) {
846 847 848 849 850 851 852 853
	    $refquota = $ZFS_QUOTA_GROUP;
	    $mult = $ZFS_QUOTA_GROUP_X;
	}
	if (defined($refquota) && $refquota =~ /^(\d+(?:\.\d+)?)([MGT]?)$/) {
	    my ($num,$unit) = ($1,$2);
	    $unit = "" if (!defined($unit));
	    $num = sprintf "%.1f", $num * $mult;
	    $cmdarg = "-o refquota=$refquota -o quota=$num$unit";
854 855 856
	} else {
	    $cmdarg = "";
	}
857
    } else {
858 859 860 861
	$cmd = "mkdir";
	$cmdarg = "";
	$path = "$fs/$dir";
    }
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
    #
    # 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;
	}
    }

889
    if (mysystem("$cmd $cmdarg $path")) {
890 891 892 893 894 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
	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");
	}
922 923
    }

924
    # should we be setting permissions or ownership here?
925

926 927 928 929 930 931 932
    return 0;
}

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

    if ($WITHZFS) {
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
	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";
951
	}
952
	if (mysystem("$cmd $path $npath")) {
953 954
	    return $?;
	}
955 956

	# Since we reuse uid/gids let's make the dir root/0700
Mike Hibler's avatar
Mike Hibler committed
957 958
	$path = "$fs/$dir$suffix";
	if (!chown(0, 0, $path) || !chmod(0700, $path)) {
959 960 961 962 963 964 965 966 967
	    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";
968 969 970 971 972 973 974
	}
    }
    #
    # XXX maybe we should do this in the background since it could
    # take a really long time!
    #
    else {
975 976 977 978 979 980 981 982 983
	my ($cmd, $path);

	if ($zfsfs) {
	    $cmd = "$ZFS destroy -f";
	    $path = $zfsfs;
	} else {
	    $cmd = "rm -rf";
	    $path = "$fs/$dir";
	}
984
	if (mysystem("$cmd $path")) {
985
	    return $?;
986 987 988 989 990
	}
    }
    return 0;
}

991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
#
# 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);
}
1013 1014 1015 1016 1017 1018 1019

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

    print STDERR "accountsetup: '$cmd'\n";
1020 1021 1022 1023 1024 1025

    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);
    }
1026 1027
    return system($cmd);
}
1028

1029 1030 1031 1032 1033 1034 1035 1036 1037
#
# 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;
1038
    my $maxtries  = 20;
1039
    my $stime     = time();
1040 1041 1042 1043

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

    if (open(FD, ">>/usr/testbed/log/accountsetup.log")) {
1044
	my $tstamp = POSIX::strftime("%b %e %H:%M:%S", localtime($stime));
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
	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;
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
	    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
	    }
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
	    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;
}

1095 1096 1097 1098 1099 1100
sub fatal($) {
    my ($msg) = @_;

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