netbed-setup.pl 28.9 KB
Newer Older
1 2 3
#!/usr/bin/perl -w
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2003 University of Utah and the Flux Group.
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 34 35 36 37 38 39 40 41 42 43
# All rights reserved.
#
use English;
use Getopt::Std;
use Fcntl;
use IO::Handle;
use Socket;

#
# This file goes in boss:/z/testbed/distributions on boss so that is can
# be passed over via wget to the CDROM on widearea nodes.
#
sub usage()
{
    print("Usage: netbed-setup.pl <bootdisk> <ipaddr>\n");
    exit(-1);
}
my  $optlist = "";

#
# Turn off line buffering on output
#
STDOUT->autoflush(1);
STDERR->autoflush(1);

#
# Untaint the environment.
# 
$ENV{'PATH'} = "/tmp:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:".
    "/usr/local/bin:/usr/site/bin:/usr/site/sbin:/usr/local/etc/testbed";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Definitions
#
my $WWW         = "https://www.emulab.net";
#my $WWW        = "http://golden-gw.ballmoss.com:8080/~stoller/testbed";
#my $WWW        = "https://www.emulab.net/~stoller/www";
my $etcdir	= "/etc";
44
my $pubkey      = "$etcdir/emulab_pubkey.pem";
45 46 47 48 49 50 51 52 53 54 55 56 57 58
# Hardwired cdkey.
my $cdkeyfile	= "$etcdir/emulab.cdkey";
# Hardwired config.
my $setupconfig	= "$etcdir/emulab-setup.txt";
# Good for onetime install without being prompted! See note below.
my $installkey  = "$etcdir/emulab.ikey";
# Current private key.
my $privkeyfile = "$etcdir/emulab.pkey";
# File to place in toplevel of each slice; holds original MD5.
my $slicetag    = "slicetag";
# The current IP config, as determined by waipconfig.pl at boot.
my $softconfig	= "$etcdir/emulab-soft.txt";
my $tbboot	= "tbbootconfig";
my $wget	= "wget";
59
my $ifconfig    = "ifconfig";
60 61
my $logfile     = "/tmp/netbed-setup.log";

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
#
# Function prototypes
#
sub GetInstructions();
sub FinishedInstructions();
sub MakeFS($$);
sub LocalizeRoot();
sub WritePrivKey();
sub MountRoot();
sub UnMountMnt();
sub WriteConfigBlock();
sub GetRootTag();
sub fatal($);
sub mysystem($);
sub mypopen($);
sub Prompt($$;$);
sub VerifySig($$);

80 81 82 83 84 85 86 87 88 89 90 91 92 93
#
# Locals
#
my $tempdevice  = "s2c";
my $rootdevice  = "s1a";
my $slicexpart  = "e";
my $slicexdev;
my $needstore   = 0;
my $fromscratch = 0;
my $needumount  = 0;
my $showprogress= 1;
my $cdkey;
my $privkey;
my %slicesizes;
94
my $uses_dhcp   = 0;
95 96 97 98 99
	
my $PATIENCEMSG  = "This could take several minutes, please be patient!\n";

my %config = ( privkey        => undef,
	       fdisk          => undef,
100 101
	       fdisk_md5      => undef,
	       fdisk_sig      => undef,
102
	       slice1_image   => undef,
103
	       slice1_alt_image => undef,
104
	       slice1_md5     => undef,
105
	       slice1_sig     => undef,
106
	       slice3_image   => undef,
107
	       slice3_alt_image => undef,
108
	       slice3_md5     => undef,
109
	       slice3_sig     => undef,
110
	       slice4_image   => undef,
111
	       slice4_alt_image => undef,
112
	       slice4_md5     => undef,
113
	       slice4_sig     => undef,
114 115 116 117
	       slicex_slice   => undef,
	       slicex_mount   => undef,
	       slicex_tarball => undef,
	       slicex_md5     => undef,
118
	       slicex_sig     => undef,
119 120 121 122 123 124 125 126 127 128 129
	     );

# These errors must match what the web page returns.
my $CDROMSTATUS_OKAY	 =	0;
my $CDROMSTATUS_MISSINGARGS =	100;
my $CDROMSTATUS_INVALIDARGS =	101;
my $CDROMSTATUS_BADCDKEY =	102;
my $CDROMSTATUS_BADPRIVKEY =	103;
my $CDROMSTATUS_BADIPADDR =	104;
my $CDROMSTATUS_BADREMOTEIP =	105;
my $CDROMSTATUS_IPADDRINUSE =	106;
130
my $CDROMSTATUS_UPGRADEERROR =	107;
131 132 133 134 135 136 137 138 139 140
my $CDROMSTATUS_OTHER =		199;

my %weberrors =
    ( $CDROMSTATUS_MISSINGARGS  => "Missing Page Arguments",
      $CDROMSTATUS_INVALIDARGS  => "Invalid Page Arguments",
      $CDROMSTATUS_BADCDKEY     => "Invalid CD Key",
      $CDROMSTATUS_BADPRIVKEY   => "Invalid Private Key",
      $CDROMSTATUS_BADIPADDR    => "IP address does not match key",
      $CDROMSTATUS_BADREMOTEIP  => "IP address does not match remote IP",
      $CDROMSTATUS_IPADDRINUSE  => "IP address already registered at Netbed",
141
      $CDROMSTATUS_UPGRADEERROR => "Error getting upgrade instructions",
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
      $CDROMSTATUS_OTHER        => "Unknown Error",
    );

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (@ARGV != 2) {
    usage();
}
my $rawbootdisk = $ARGV[0];
my $IP = $ARGV[1];

#
160
# Untaint stuff.
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
#
if ($rawbootdisk =~ /^([\w\/]+)$/) {
    $rawbootdisk = $1;
}
else {
    fatal("Tainted argument $rawbootdisk!");
}

#
# Grab hostname for passing back to website so it can cons up a nickname.
#
my $hostname = `hostname`;
if ($hostname =~ /^([-\w\.\@]*)$/) {
    $hostname = $1;
}
else {
    fatal("Tainted hostname $hostname!");
}

180 181 182 183
#
# If our IP came via DHCP, we need to figure out what it is. 
#
if ($IP eq "DHCP") {
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    my $ip_found = 0;
    my $dhcp_if;
    $uses_dhcp = 1;

    open(SOFT, $softconfig);
    while (<SOFT>) {
	if (/^interface=(.*)$/) {
	    $dhcp_if = $1;
	    last;
	}
    }
    close(SOFT);
    if ($dhcp_if) {
	open(IFCONFIG, "$ifconfig $dhcp_if|");
	while (<IFCONFIG>) {
	    if (/inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) /) {
		$ip_found = 1;
		$IP = $1;
		last;
	    }
	}
205
    }
206 207 208 209 210 211
    if (!$ip_found && $hostname) {
	my @ipaddrs;
	(undef, undef, undef, undef, @ipaddrs) = gethostbyname($hostname);
	if (scalar @ipaddrs) {
	    $IP = inet_ntoa($ipaddrs[0]);
	}
212
    }
213 214 215 216
    if ($ip_found && !$hostname) {
	my $iptrans = $IP;
	$iptrans =~ s/\./\-/;
	$hostname = "dhcp-$iptrans.wa.emulab.net";
217 218 219
    }
}

220 221 222 223
if ($IP =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/) {
    $IP = $1;
}
else {
224
    fatal("Bad IP: $IP!");
225 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 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
#
# Get the plain device names (ad0, rad0).
# Note, there is no difference in block/raw devices anymore.
#
my $rawdevice   = substr($rawbootdisk, rindex($rawbootdisk, '/') + 1);
my $blockdevice = $rawdevice;

#
# See if this is the first time. Look for the magic boot header.
#
$fromscratch = mysystem("$tbboot -v $rawbootdisk");

GetInstructions();

#
# Do we even need a temp store? After the initial setup, we won't
# need it unless updating the disk. See Checkin() for the variable.
#
if ($needstore) {
    #
    # If the disk is raw, we need to get the fdisk params and lay it down.
    #
    if ($fromscratch) {
	my $fdisk  = $config{fdisk};
	my $adjust = 0;
	my $FDSK;

	fatal("Testbed Central did not tell us what fdisk table to use!")
	    if (!defined($fdisk));

	print "Creating a temporary filesystem on slice 2 to hold images.\n";
	print "    (ignore kernel generated \"no disk label\" messages.)\n";
	
	#
	# First time through we need to lay down a DOS partition table.
	#
	mysystem("dd if=/dev/zero of=${rawbootdisk} bs=1k count=1024");
	fatal("Failed to clear disk of old goop!")
	    if ($?);
	
	mysystem("fdisk -I $rawbootdisk");
	fatal("Failed to initialize DOS partition table!")
	    if ($?);

	#
	# Read the summary info to see if we are going to have a problem
	# with fdisk changing the sizes!
	#
	my $summary = `fdisk -s $rawbootdisk | head -1`;
	if ($summary =~ /^.*cyl (\d*) hd (\d*) sec/) {
	    if ($1 != 255) {
		$adjust = $1 * $2;
	    }
	}

	#
	# Get the fdisk table. 
	# 
	if ($fdisk =~ /^http:.*$/ || $fdisk =~ /^ftp:.*$/) {
	    mysystem("$wget -nv -O /tmp/fdisk.table $fdisk");
	    fatal("Failed to transfer fdisk table: $fdisk!")
		if ($?);
	    
	    $fdisk = "/tmp/fdisk.table";
	}
	else {
	    $fdisk = "/${fdisk}";
	}

296 297 298 299 300 301 302
	#
	# Always verify.
	#
	if (VerifySig($fdisk, "fdisk") < 0) {
	    fatal("Could not verify signature of $fdisk!");
	}

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 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
	#
	# We are going to feed the fdisk table one line at a time
	# so we can apply the adjustment. Yuck.
	# 
	if (! ($FDSK = mypopen("| fdisk -f - $rawbootdisk"))) {
	    fatal("Could not start fdisk on $rawbootdisk!");
	}
	foreach my $line (`cat $fdisk`) {
	    chomp($line);
	    my ($key, $part, $sysid, $start, $size) = split(' ', $line);

	    if (defined($start)) {
		$size += $adjust;
		if ($part != 1) {
		    $start += $adjust;
		}
		print $FDSK "$key $part $sysid $start $size\n";
	    }
	    else {
		print $FDSK "$key $part\n";
	    }
	}
	if (!close($FDSK)) {
	    fatal("Failed to lay down initial DOS partition table!");
	}

	#
	# Clear old disklabels to avoid errors.
	#

	#
	# Give the boot slice an auto label to prevent a bunch of warnings.
	# Its going to get overwritten anyway. 
	# 
	mysystem("disklabel -w -r ${blockdevice}s1 auto");
    }

    #
    # Turn slice2 into a filesystem we can stash the image on.
    # This slice is reserved forever! But its only 1gig.
    #
    # Make it active so that the machine will not boot without the cd.
    #
    mysystem("echo \"a 2\" | fdisk -f - $rawbootdisk");
    
    mysystem("disklabel -w -r ${blockdevice}s2 auto");
    fatal("Failed to put a disklabel on ${blockdevice}s2!")
	if ($?);
	
    mysystem("newfs /dev/${rawdevice}${tempdevice}");
    fatal("Failed to put a filesystem on /dev/${rawdevice}${tempdevice}!")
	if ($?);

    mysystem("mount /dev/${blockdevice}${tempdevice} /mnt");
    fatal("Failed to mount /dev/${blockdevice}${tempdevice}! on /mnt!")
	if ($?);
    $needumount = 1;

    #
    # Find out the actual slice sizes so that we can modify the C
    # partitions of images we lay down. Why? Cause if fdisk modified the
    # size, then the kernel is going to complain all the time that the
    # size of the slice does not match the size of the C partition.
    # 
    foreach my $line (`fdisk -s $rawbootdisk`) {
	chomp($line);
	if ($line =~ /\s*(\d):\s*\d*\s*(\d*)/) {
	    $slicesizes{$1} = $2;
	}
    }
}

#
# Now go through each possible slice except slice 2, since we use slice 2
# as temp storage when first creating the disk. The fdisk table we got from
# Emulab will have reserved that slice. 
#
for ($i = 1; $i <= 4; $i++) {
    my $ED;
    
    if ($i == 2) {
	next;
    }
    my $image = $config{"slice${i}_image"};
387 388
    my $alt_image = $config{"slice${i}_alt_image"};
    my $image_md5 = $config{"slice${i}_md5"};
389 390 391 392 393 394
    
    if (!defined($image) || $image eq "skipit") {
	next;
    }

    #
395 396 397
    # If told to load a local image from the CDROM, do so, but make
    # sure that we have the right thing on the CD.  If not, fall
    # back to grabbing it via the network (alt_image).
398
    # 
399 400 401

    my $bad_local_image = 0;

402
    if (! ($image =~ /^http:.*$/ || $image =~ /^ftp:.*$/)) {
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
	
	if (! -f "/$image") { 
	    print "No disk image on CDROM.  Trying alternate.\n";
	    goto tryalt;
	}
	
	if (-f "/${image}.md5") {
	    open(IN, "/${image}.md5");
	    my $md5line = <IN>;
	    close(IN);
	    chomp($md5line);
	    $md5line =~ s/[^=]+ = //;
	    if ($image_md5 && ($md5line ne $image_md5)) {
		print "CDROM image has wrong MD5.  Trying alternate.\n";
		goto tryalt;
	    }
	}

421
	#
422
	# Always check the signature.
423
	#
424

425
	if (VerifySig("/$image", "slice${i}") < 0) {
426 427
	    print "CDROM image has invalid signature!  Trying alternate.\n";
	    goto tryalt;
428 429 430 431 432 433 434 435 436 437
	}

	#
	# Then load up the disk straight from the CDROM.
	#
	print "Loading image for slice $i from $image.\n";
	print $PATIENCEMSG;

	if ($showprogress) {
	    print "(Output indicates uncompressed bytes written to disk.)\n";
438
	    system("imageunzip -n -o -s $i /$image $rawbootdisk");
439
	} else {
440
	    mysystem("imageunzip -n -s $i /$image $rawbootdisk");
441
	}
442 443 444 445 446 447
	if ($?) {
	    # It's possible that a bad read on the CD could cause this
	    # failure, though not likely that it would pass the signature
	    # verification.  Probably not worth forcing a net read.
	    fatal("Failed to lay down image /$image!");
	}
448
	goto finished;
449 450 451 452 453 454 455 456 457 458 459
    tryalt:
	$bad_local_image = 1;
    }

    if ($bad_local_image) {
	if ($alt_image && $alt_image ne "skipit") {
	    print "Setting image to $alt_image\n";
	    $image = $alt_image;
	} else {
	    fatal("Could not locate a valid image!");
	}
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    }

    #
    # Transfer the image to the temp store and then unzip to the slice.
    #
    if ($image =~ /^http:.*$/ || $image =~ /^ftp:.*$/) {
      again:
	print "Transferring image to temp storage for slice $i from:\n".
	      "    $image \n";
	print $PATIENCEMSG;
	
	if ($showprogress) {
	    system("$wget -O /mnt/image.ndz $image");
	} else {
	    mysystem("$wget -nv -O /mnt/image.ndz $image");
	}
	fatal("Failed to transfer image!")
	    if ($?);

	#
480
	# Always check the signature.
481
	#
482 483 484 485
	if (VerifySig("/mnt/image.ndz", "slice${i}") < 0) {
	    print "*** Invalid signature! Getting the image again.\n";
	    sleep(60);
	    goto again;
486 487 488 489 490 491 492
	}

	print "Writing image from temp storage to slice $i.\n";
	print $PATIENCEMSG;

	if ($showprogress) {
	    print "(Output indicates uncompressed bytes written to disk.)\n";
493
	    system("imageunzip -n -o -s $i /mnt/image.ndz $rawbootdisk");
494
	} else {
495
	    mysystem("imageunzip -n -s $i /mnt/image.ndz $rawbootdisk");
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
	}
	fatal("Failed to lay down image!")
	    if ($?);

	unlink("/mnt/image.ndz") or
	    fatal("Failed to unlink /mnt/image.ndz!");
    }
  finished:
    #
    # Update the the label, changing the C partition to match the actual
    # slice size.
    #
    $ENV{'EDITOR'} = "ed";
    if (! ($ED = mypopen("| disklabel -e -r ${rawdevice}s${i}"))) {
	fatal("Could not edit label on ${rawdevice}s${i}!");
    }
    print $ED "/^  c: /\n";
    print $ED "t\n";
    print $ED "s/c: [0-9]*/c: $slicesizes{$i}/\n";
    print $ED "w\n";
    print $ED "q\n";
    if (!close($ED)) {
	fatal("Error editing disklabel on ${rawdevice}s${i}!");
    }
}

#
# Unmount the temp store.
#
UnMountMnt();

#
# Create extra FS.
# 
if (defined($config{"slicex_mount"}) &&
    defined($config{"slicex_slice"})) {
    my $slicex_mount = $config{"slicex_mount"};
    my $slicex_slice = $config{"slicex_slice"};
    
    if ($fromscratch) {
	#
	# Easy. Just make it and remember the device for fstab.
	#
	if (MakeFS($slicex_mount, $slicex_slice) < 0) {
	    fatal("Error creating extra filesystem");
	}
    }
    else {
	#
	# Harder. We have to trust that we are being told the truth!
	#
	$slicexdev = "s${slicex_slice}${slicexpart}";
    }
}

#
# Localize the root filesystem (might not be needed of course).
# 
LocalizeRoot();
WritePrivKey();

#
# Wow, made it. Now write the current configuration back to the magic
# header and set things up to reboot from the disk instead of the CDROM.
#
WriteConfigBlock();

#
# Let Emulab know we made it through
#
FinishedInstructions();

#
# Wrapper does the rest.
# 
exit 0;

#
# Check in with emulab for instructions.
#
sub GetInstructions()
{
    my $path  = $setupconfig;

    #
    # Talk to emulab and see what to do. We use wget to invoke a secure
    # script on the webserver, passing it the cdkey.
    # We give it our IP as an argument plus our private key.
    #
    if (! -s $path) {
	my $roottag = 0;

	if (! $fromscratch) {
	    $roottag = GetRootTag();
	}
      again:
	$path = "/tmp/emulab-config.$$";
	undef($privkey);
	
	#
	# The cdkey describes the cd.
	# 
	if (! -s $cdkeyfile) {
	    fatal("No CD key on the CD!");
	}
	$cdkey = `cat $cdkeyfile`;
	chomp($cdkey);
	
	#
	# If not from scratch, then get the current privkey.
	# If from scratch, then prompt user for the privkey, which had to
	# come from emulab beforehand.
	#
	if (! $fromscratch) {
	    $privkey = `$tbboot -e - $rawbootdisk`;
	    chomp($privkey);
	}
	else {
	    #
	    # We allow for the initial install key to be on the CDROM.
	    # Its only good for one install though! It will be rejected
	    # if its tried again. Thats not so bad though; it just means
	    # that if the disk gets totally scrogged we need to edit the
	    # DB state slightly to allow the key to be used. That would
	    # be on demand!
	    #
	    if (-s $installkey) {
		$privkey = `cat $installkey`;
		chomp($privkey);
	    }
	    else {
		while (!defined($privkey)) {
		    $privkey =
			Prompt("Please enter your 16 character CD password".
			       " (no spaces)", undef);
		}
	    }
	}

	while (1) {
	    print "Checking in at Netbed Central for configuration ...\n";
	    
	    mysystem("$wget -q -O $path ".
		     "'${WWW}/cdromcheckin.php3".
		     "?cdkey=$cdkey&IP=$IP&privkey=$privkey".
		     "&wahostname=$hostname&roottag=$roottag'");
	    if (!$?) {
		last;
	    }
	    print "Error checking in. Will try again in one minute ...\n";
	    sleep(60);
	}
	
	if (! -s $path) {
	    fatal("Could not get a valid setup configuration from $WWW!");
	}
    }

    #
    # Read the output file. It will tell us what to do.
    #
    if (! open(INSTR, $path)) {
	fatal("$path could not be opened for reading: $!");
    }
    while (<INSTR>) {
	chomp();
        SWITCH1: {
	    /^emulab_status=(.*)$/ && do {
		$config{emulab_status} = $1;
		last SWITCH1;
	    };
	    /^privkey=(.*)$/ && do {
668
		$config{"privkey"} = $1;
669 670 671
		last SWITCH1;
	    };
	    /^fdisk=(.*)$/ && do {
672 673 674 675 676 677 678 679 680
		$config{"fdisk"} = $1;
		last SWITCH1;
	    };
	    /^fdisk_md5=(.*)$/ && do {
		$config{"fdisk_md5"} = $1;
		last SWITCH1;
	    };
	    /^fdisk_sig=(.*)$/ && do {
		$config{"fdisk_sig"} = $1;
681 682 683 684 685 686 687
		last SWITCH1;
	    };
	    /^slice(\d)_image=(.*)$/ && do {
		$config{"slice${1}_image"} = $2;
		$needstore++;
		last SWITCH1;
	    };
688 689 690 691
	    /^slice(\d)_alt_image=(.*)$/ && do {
		$config{"slice${1}_alt_image"} = $2;
		last SWITCH1;
	    };
692 693 694 695
	    /^slice(\d)_md5=(.*)$/ && do {
		$config{"slice${1}_md5"} = $2;
		last SWITCH1;
	    };
696 697 698 699
	    /^slice(\d)_sig=(.*)$/ && do {
		$config{"slice${1}_sig"} = $2;
		last SWITCH1;
	    };
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
	    /^slicex_mount=(.*)$/ && do {
		$config{"slicex_mount"} = $1;
		last SWITCH1;
	    };
	    /^slicex_slice=(.*)$/ && do {
		$config{"slicex_slice"} = $1;
		last SWITCH1;
	    };
	    /^slicex_tarball=(.*)$/ && do {
		$config{"slicex_tarball"} = $1;
		last SWITCH1;
	    };
	    /^slicex_md5=(.*)$/ && do {
		$config{"slicex_md5"} = $1;
		last SWITCH1;
	    };
716 717 718 719
	    /^slicex_sig=(.*)$/ && do {
		$config{"slicex_sig"} = $1;
		last SWITCH1;
	    };
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
	    print STDERR "Invalid instruction: $_\n";
	}
    }
    close(INSTR);

    if (defined($config{"emulab_status"}) &&
	$config{"emulab_status"} != $CDROMSTATUS_OKAY) {

	my $err = $config{"emulab_status"};
	my $msg = $weberrors{$err};

	if ($err == $CDROMSTATUS_BADPRIVKEY &&
	    Prompt("Invalid CD password. Try again?", "Yes") =~ /yes/i) {
	    delete($config{"emulab_status"});
	    goto again;
	}
	fatal("Netbed Checkin Error: '$msg'");
    }
    return 0;
}

#
# Tell Emulab we finished its instruction.
#
sub FinishedInstructions()
{
    $path = "/tmp/emulab-finished.$$";
    
    #
    # No need to do this when operating off local instructions.
    # 
    if (-s $setupconfig) {
	return 0;
    }

755 756
    my $roottag = GetRootTag();
    
757 758 759 760 761 762
  again:
    while (1) {
	print "Letting Netbed Central know we finished ...\n";
	    
	mysystem("$wget -q -O $path ".
		 "'${WWW}/cdromcheckin.php3".
763
		 "?cdkey=$cdkey&IP=$IP&privkey=$privkey&roottag=$roottag".
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 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 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 876 877 878 879 880 881 882 883 884 885 886
		 "&wahostname=$hostname&updated=1'");
	if (!$?) {
	    last;
	}
	print "Error checking in. Will try again in one minute ...\n";
	sleep(60);
    }
    if (! -s $path) {
	fatal("Could not update Netbed Central with status!");
    }

    #
    # Read the output file to see if there was an error.
    #
    if (! open(INSTR, $path)) {
	fatal("$path could not be opened for reading: $!");
    }
    while (<INSTR>) {
	chomp();
        SWITCH1: {
	    /^emulab_status=(.*)$/ && do {
		$config{emulab_status} = $1;
		last SWITCH1;
	    };
	    fatal("Invalid Response: $_");
	}
    }
    close(INSTR);

    if ($config{"emulab_status"} != $CDROMSTATUS_OKAY) {
	my $status = $config{"emulab_status"};
	my $msg    = $weberrors{$status};

	fatal("Netbed Update Error: '$msg'");
    }
    return 0;
}

#
# Create a filesystem on the last unused slice. 
#
sub MakeFS($$)
{
    my ($mntpoint, $slice) = @_;
    my $ED;
    my $foo;

    print "Looking for a DOS partition that can be resized ...\n";

    my $pline = `growdisk -f $rawbootdisk`;
    if ($?) {
	print STDERR "*** Oops, no extra DOS slices to use!\n";
	return 1;
    }
    chomp($pline);
    my (undef, $growslice, $type, $start, $size) = split(/\s/, $pline);

    if ($growslice != $slice) {
	print STDERR
	    "*** Oops, extra DOS slice mismatch ($slice,$growslice)!\n";
	return 1;
    }

    mysystem("echo \"$pline\" | fdisk -f - $rawbootdisk");
    if ($?) {
	print STDERR "*** Oops, could not setup extra DOS slice $slice!\n";
	return -1;
    }

    mysystem("disklabel -w -r ${rawdevice}s${slice} auto");
    if ($?) {
	print STDERR "*** Oops, could not disklabel ${rawdevice}s${slice}!\n";
	return -1;
    }

    # Make sure the kernel really has the new label!
    mysystem("disklabel -r ${rawdevice}s${slice} > /tmp/disklabel");
    mysystem("disklabel -R -r ${rawdevice}s${slice} /tmp/disklabel");

    $ENV{'EDITOR'} = "ed";
    if (! ($ED = mypopen("| disklabel -e -r ${rawdevice}s${slice}"))) {
	print STDERR
	    "*** Oops, could not edit label on ${rawdevice}s${slice}!\n";
	return -1;
    }
    print $ED "/^  c: /\n";
    print $ED "t\n";
    print $ED "s/c: /${slicexpart}: /\n";
    print $ED "w\n";
    print $ED "q\n";
    if (!close($ED)) {
	print STDERR
	    "*** Oops, error editing label on ${rawdevice}s${slice}!\n";
	return -1;
    }

    print "Creating filesystem on $mntpoint (${rawdevice}s${slice}e).\n";
    print "    (ignore kernel generated \"no disk label\" messages.)\n";
    mysystem("newfs -U ${rawdevice}s${slice}e");
    if ($?) {
	print STDERR "*** Oops, could not newfs ${rawdevice}s${slice}e!\n";
	return -1;
    }
    $foo = "s${slice}${slicexpart}";
	
    #
    # If there was a tarball then mount up the filesystem and unpack it.
    # We have to drag it across, and I assume that the FS is big enough
    # to hold the tarball and the unpacked contents.
    #
    if ($config{"slicex_tarball"}) {
	my $tarball = $config{"slicex_tarball"};
	    
	mysystem("mount /dev/${blockdevice}${foo} /mnt");
	fatal("Failed to mount /dev/${blockdevice}${foo} on /mnt!")
	    if ($?);
	$needumount = 1;

	#
	# If told to use a local image from the CDROM, its really easy!
	# 
	if (! ($tarball =~ /^http:.*$/ || $tarball =~ /^ftp:.*$/)) {
	    #
887 888 889 890
	    # Always check signature.
	    # 
	    if (VerifySig("/$tarball", "slicex") < 0) {
		fatal("Tarball has an invalid signature!");
891 892 893 894 895
	    }

	    print "Unpacking $tarball to $mntpoint.\n";
	    print $PATIENCEMSG;
	
896
	    mysystem("tar -zxf /$tarball -C /mnt");
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
	    fatal("Failed to untar /$tarball!")
		if ($?);
	}
	else {
	  again:
	    #
	    # Transfer the image to the temp store and then unzip to the slice.
	    #
	    print "Transferring tarball for $mntpoint from:\n".
		  "    $tarball\n";
	    print $PATIENCEMSG;
	
	    mysystem("$wget -nv -O /mnt/slicex.tar.gz $tarball");
	    fatal("Failed to transfer tarball!")
		if ($?);

	    #
914
	    # Always check the signature.
915
	    #
916 917 918 919
	    if (VerifySig("/mnt/slicex.tar.gz", "slicex") < 0) {
		print "*** Invalid signature! Getting the tarball again.\n";
		sleep(60);
		goto again;
920 921 922 923 924
	    }

	    print "Unpacking tarball.\n";
	    print $PATIENCEMSG;

925
	    mysystem("tar -zxf /mnt/slicex.tar.gz -C /mnt");
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
	    fatal("Failed to untar /mnt/slicex.tar.gz!")
		if ($?);
	}
	
	mysystem("umount /mnt");
	fatal("Failed to unmount /mnt!")
	    if ($?);
	$needumount = 0;
    }
    
    $slicexdev = $foo;
    return 0;
}

#
# Localize the root filesystem by putting out a proper rc.conf.local,
# resolv.conf, fstab, etc.
#
sub LocalizeRoot()
{
    my $root = "${blockdevice}${rootdevice}";
    my $ED;
	
    print "Localizing root filesystem on $root ...\n";
    MountRoot();

    #
    # Copy over the easy ones.
    #
    mysystem("cp -p /etc/rc.conf.local /mnt/etc");
    fatal("Failed to copy /etc/rc.conf.local to /mnt/etc!")
	if ($?);
    mysystem("cp -p /etc/resolv.conf /mnt/etc");
    fatal("Failed to copy /etc/resolv.conf to /mnt/etc!")
	if ($?);
    mysystem("cp -p /etc/namedb/localhost.rev /mnt/etc/namedb");
    fatal("Failed to copy /etc/namedb/localhost.rev to /mnt/etc!")
	if ($?);

965 966 967 968 969 970 971 972
    #
    # The rest happens only if a newly installed slice.
    # 
    if (! defined($config{"slice1_image"})) {
	UnMountMnt();
	return 0;
    }

973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    #
    # Write MD5 to toplevel. Serves as poor version info.
    #
    my $hash = $config{"slice1_md5"};
    mysystem("echo '$hash' > /mnt/$slicetag");
    fatal("Failed to create /mnt/$slicetag!")
	if ($?);

    #
    # Edit fstab, replacing the s1 entries with the current device.
    #
    chmod(0644, "/mnt/etc/fstab");
    
    if (! ($ED = mypopen("| ed /mnt/etc/fstab "))) {
	fatal("Could not edit /mnt/etc/fstab!");
    }
#   print $ED "1,\$s;/dev/.*\\(s1[a-z]*\\);/dev/${blockdevice}\\1;p\n";
    print $ED "1,\$s;/dev/[a-z]*[0-9]\\(.*[a-z]\\);/dev/${blockdevice}\\1;p\n";

    #
    # Append a mountpoint for the extra fs.
    #
    if (defined($config{"slicex_mount"}) && defined($slicexdev)) {
	my $slicex_mount = $config{"slicex_mount"};

	print $ED "\$\n";
	print $ED "a\n";
	print $ED "/dev/${blockdevice}${slicexdev}\t\t$slicex_mount\t\t".
	    "ufs\trw,nosuid\t0\t2\n";
	print $ED ".\n";
    }
    
    print $ED "w\n";
    print $ED "q\n";
    if (!close($ED)) {
	fatal("Error editing /mnt/etc/fstab!");
    }

    chdir("/mnt/dev") or
	fatal("Could not chdir to /mnt/dev!");
    mysystem("./MAKEDEV ${blockdevice}");
    mysystem("./MAKEDEV ${blockdevice}s1c ${blockdevice}s2c");
    mysystem("./MAKEDEV ${blockdevice}s3c ${blockdevice}s4c");
    chdir("/") or
	fatal("Could not chdir to /!");
    
1019
    UnMountMnt();
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 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 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
    return 0;
}

#
# Write out the privkey
#
sub WritePrivKey()
{
    if (! $needumount) {
	MountRoot();
    }
    
    if (defined($config{"privkey"})) {
	my $key = $config{"privkey"};
	
	mysystem("echo \"$key\" > /mnt/${privkeyfile}");
	fatal("Could not create /mnt/${privkeyfile}")
	    if ($?);
	chmod(0640, "/mnt/${privkeyfile}") or
	    fatal("Could not chmod 0640 /mnt/${privkeyfile}");
    }
    UnMountMnt();
    
    return 0;
}

#
# Mount up the root partition.
#
sub MountRoot()
{
    my $root  = "${blockdevice}${rootdevice}";
    my $rroot = "${rawdevice}${rootdevice}";

    #
    # Need to fsck it. If its dirty, the mount will fail and we will
    # be hosed. If it fails fsck, well we are hosed anyway!
    #
    mysystem("fsck -y /dev/${rroot}");
    fatal("Could not fsck root filesystem (/dev/${rroot}!")
	if ($?);

    mysystem("mount /dev/${root} /mnt");
    fatal("Failed to mount /dev/${root}! on /mnt!")
	if ($?);
    $needumount = 1;

    return 0;
}

#
# Unmount the mounted filesystem.
#
sub UnMountMnt()
{
    if ($needumount) {
	mysystem("umount /mnt");
	$needumount = 0;
	
	fatal("Failed to umount /mnt!")
	    if ($?);
    }
    return 0;
}

#
# When running from the CDROM write the config info to the magic spot.
# 
sub WriteConfigBlock()
{
    my $cmd;

    $cmd = "$tbboot -f -d -w $softconfig -k 1 -c 0 ";

    if (defined($config{privkey})) {
	$cmd .= "-e $config{privkey} ";
    }
    $cmd .= "  $rawbootdisk";

    mysystem("$cmd");
    fatal("Failed to write header block info!")
	if ($?);

    return 0;
}

#
# Get the tag for the root slice. 
# 
sub GetRootTag()
{
    MountRoot();

    if (! -e "/mnt/$slicetag") {
	UnMountMnt();
	return 0;
    }

    my $tag = `cat /mnt/$slicetag`;
    chomp($tag);

    UnMountMnt();
    return $tag;
}

#
# Print error and exit.
#
sub fatal($)
{
    my ($msg) = @_;

    if ($needumount) {
	chdir("/");
	mysystem("umount /mnt");
    }
    
    die("*** $0:\n".
	"    $msg\n");
}

#
# Run a command string, redirecting output to a logfile.
#
sub mysystem($)
{
    my ($command) = @_;

    if (defined($logfile)) {
	system("echo \"$command\" >> $logfile");
	system("($command) >> $logfile 2>&1");
    }
    else {
	print "Command: '$command\'\n";
	system($command);
    }
    return $?;
}

sub mypopen($)
{
    my ($command) = @_;
    local *FD;

    if (defined($logfile)) {
	system("echo \"$command\" >> $logfile");
	open(FD, "$command >> $logfile 2>&1")
	    or return undef;
    }
    else {
	print "Command: '$command\'\n";
	open(FD, "$command")
	    or return undef;
    }
    return *FD;
}

#
# Spit out a prompt and a default answer. If optional timeout supplied,
# then wait that long before returning the default. Otherwise, wait forever.
#
sub Prompt($$;$)
{
    my ($prompt, $default, $timeout) = @_;

    if (!defined($timeout)) {
	$timeout = 10000000;
    }

    print "$prompt";
    if (defined($default)) {
	print " [$default]";
    }
    print ": ";

    eval {
	local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
	
	alarm $timeout;
	$_ = <STDIN>;
	alarm 0;
    };
    if ($@) {
	if ($@ ne "alarm\n") {
	    die("Unexpected interrupt in prompt\n");
	}
	#
	# Timed out.
	#
	print "\n";
	return $default;
    }
    return undef
	if (!defined($_));
	
    chomp();
    if ($_ eq "") {
	return $default;
    }

    return $_;
}

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 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
#
# Verify a file using the provided digital signature. 
# 
sub VerifySig($$)
{
    my ($file, $which) = @_;

    if (!defined($config{"${which}_sig"})) {
	print("No $which signature specification for $file\n");
	    return -1;
    }
    my $sig     = $config{"${which}_sig"};

    #
    # Sig is either local or remote
    # 
    if ($sig =~ /^https:.*$/ || $sig =~ /^ftp:.*$/ || $sig =~ /^http:.*$/) {
	while (1) {
	    print "Downloading signature from Netbed Central ...\n";

	    unlink("/tmp/sig");
	    mysystem("$wget -nv -O /tmp/sig $sig");
	    if (!$?) {
		last;
	    }

	    print "Error getting signature: $sig\n";
	    print "Will try again in 15 seconds!\n";
	    sleep(15);
	}
	$sig = "/tmp/sig";
    }

    #
    # Check the digital signature. 
    #
    print "Checking digital signature of $file\n";
    print $PATIENCEMSG;

    my $cmd  = "openssl dgst -sha1 -verify $pubkey -signature $sig $file";
    my $hval = `$cmd`;
    chomp($hval);

    #
    # Yep, its amazing. Instead of exiting with status, this stupid
    # program always exits with 0, so have to check the output. 
    #
    if ($hval ne "Verified OK") {
	return -1;
    }
    return 0;
}