linux_slicefix.pl 24.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
#! /usr/bin/perl

my $VOL_ID = '/lib/udev/vol_id';
my $BLKID = '/sbin/blkid';
my $FDISK = '/sbin/fdisk';
my $MOUNT = '/bin/mount';
my $UMOUNT = '/bin/umount';
my $RM = '/bin/rm';
my $CP = '/bin/cp';
my $CPIO = 'cpio';
my $GZIP = 'gzip';
Ryan Jackson's avatar
Ryan Jackson committed
12 13 14 15
my $MKSWAP = '/sbin/mkswap';
my $UUIDGEN = 'uuidgen';
my $LOSETUP = 'losetup';
my $TUNE2FS = 'tune2fs';
16 17
my $LOCALIZED1 = '/.localized';
my $LOCALIZED2 = '/root/.localized';
18 19 20

use constant GZHDR1 => 0x1f8b0800;
use constant GZHDR2 => 0x1f8b0808;
Ryan Jackson's avatar
Ryan Jackson committed
21 22
use constant LARGEST_PAGE_SIZE => 0x4000;
use constant UUID_OFFSET => 1036;
23

Mike Hibler's avatar
Mike Hibler committed
24 25 26 27 28
#
# Turn off line buffering on output
#
$| = 1;

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
# Load up the paths. Done like this in case init code is needed.
BEGIN
{
    if (! -e "/etc/emulab/paths.pm") {
	die("Yikes! Could not require /etc/emulab/paths.pm!\n");
    }
    require "/etc/emulab/paths.pm";
    import emulabpaths;
}

use strict;

sub get_uuid
{
	my ($device) = @_;
	my $uuid;

	if (-x $VOL_ID) {
		open CMD, $VOL_ID . " --uuid $device |" || die
		     "Couldn't run vol_id: $!\n";

		$uuid = <CMD>;
		chomp $uuid;

		close CMD;
	}
	elsif (-x $BLKID) {
Ryan Jackson's avatar
Ryan Jackson committed
56
		open CMD, "$BLKID|" || die
57 58 59 60 61
			"Couldn't run blkid: $!\n";

		while (<CMD>) {
			next unless m#^$device:\s+#;
			chomp;
Ryan Jackson's avatar
Ryan Jackson committed
62
			next unless s/.*\s+UUID="([a-f0-9-]+)".*/\1/;
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
			$uuid = $_;
		}

		close CMD;
	}
	else {
		print STDERR "Can't find program to get FS UUID\n";
	}

	return $uuid;
}

sub get_label
{
	my ($device) = @_;
	my $label;

	if (-x $VOL_ID) {
		open CMD, $VOL_ID . " --label-raw $device|" || die
		     "Couldn't run vol_id: $!\n";

		$label = <CMD>;
		chomp $label;

		close CMD;
	}
	elsif (-x $BLKID) {
Ryan Jackson's avatar
Ryan Jackson committed
90
		open CMD, "$BLKID|" || die
91 92 93 94 95
			"Couldn't run blkid: $!\n";

		while (<CMD>) {
			next unless m#^$device:\s+#;
			chomp;
Ryan Jackson's avatar
Ryan Jackson committed
96
			next unless s/.*\s+LABEL="([^"]*)".*/\1/;
97 98 99 100 101 102 103 104 105 106 107 108
			$label = $_;
		}

		close CMD;
	}
	else {
		print STDERR "Can't find program to get FS label\n";
	}

	return $label;
}

Ryan Jackson's avatar
Ryan Jackson committed
109 110 111 112 113 114 115
sub set_random_rootfs_uuid
{
	my ($root) = @_;
	
	system("$TUNE2FS -U random $root");
}

116 117 118 119 120 121 122
sub disable_time_dependent_fsck
{
	my ($root) = @_;
	
	system("$TUNE2FS -i 0 $root >/dev/null 2>&1");
}

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
sub kernel_version_compare
{
	my ($v1, $v2) = @_;

	my $v1_code = sprintf "%x%02x%02x", (split /\./, $v1)[0 .. 2];
	my $v2_code = sprintf "%x%02x%02x", (split /\./, $v2)[0 .. 2];

	if ($v1_code < $v2_code) {
		return -1;
	}
	elsif ($v1_code == $v2_code) {
		return 0;
	}
	else {
		return 1;
	}
}

sub find_swap_partitions
{
	my ($device) = @_;
	my @swap_devices;

	open CMD, $FDISK . " -l $device|" ||
	     die "Couldn't run fdisk: $!\n";

	while (<CMD>) {
		next unless m#^$device#;
		split /\s+/;
		if ($_[4] eq '82') {
			push @swap_devices, $_[0];
		}
	}

	close CMD;

	return @swap_devices;
}

Ryan Jackson's avatar
Ryan Jackson committed
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 189 190 191 192 193 194
sub set_swap_uuid
{
	my ($device, $uuid) = @_;
	my $swap_header;
	
	if (!open DEVICE, "+<$device") {
		print STDERR "Couldn't open $device: $!\n";      
		return 1;
	}
	
	my $id;
	for (my $i = 0x1000; $i <= LARGEST_PAGE_SIZE; $i <<= 1) {
		seek DEVICE, 0, 0;
		read DEVICE, $swap_header, $i;
		$id = unpack('Z10', substr($swap_header, $i - 10));
		last if ($id eq 'SWAPSPACE2');
	}
	                              
	if ($id ne 'SWAPSPACE2') {
		print STDERR "Device $device does not contain a new-style swap header\n";
		close DEVICE;
		return 1;
	}
	
	my $new_uuid = pack('H8H4H4H4H12', split(/-/, $uuid));
	substr $swap_header, UUID_OFFSET, 16, $new_uuid;
	
	seek DEVICE, 0, 0;
	print DEVICE $swap_header;
	
	close DEVICE;
}

Mike Hibler's avatar
Mike Hibler committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
sub fix_grub_dom0mem
{
	my ($imageroot, $file) = @_;
	my $dom0mem = $ENV{"SLICEFIX_DOM0MEM"};

	if (!$dom0mem ||
	    system("grep -q 'dom0_mem=' $imageroot/$file 2>/dev/null")) {
		return;
	}

	print STDERR "Setting dom0 memory to $dom0mem\n";
	open FILE, "+<$imageroot/$file" ||
	     die "Couldn't open $imageroot/$file: $!\n";

	my @buffer = ();
	while (<FILE>) {
		s#dom0_mem=\w+#dom0_mem=$dom0mem#g;
		push @buffer, $_;
	}

	seek FILE, 0, 0;

	print FILE @buffer;

	close FILE;

	return;
}

Ryan Jackson's avatar
Ryan Jackson committed
224 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
sub fix_swap_partitions
{
	my ($imageroot, $root, $old_root) = @_;
	my @swapdevs;

	return undef unless (-x $MKSWAP);

	my ($root_disk) = ($root =~ m#^(/dev/[a-z]+)#);
	my ($old_root_disk) = ($old_root =~ m#^(/dev/[a-z]+)#);
	my @swap_partitions = find_swap_partitions($root_disk);
	my ($l, $u) = binary_supports_blkid("$imageroot/sbin/swapon");

	for my $part (@swap_partitions) {
		my $swapdev = $part;
		next if system("$MKSWAP $part");
		my $uuid = get_uuid($part);
		if ($u) {
			if ($uuid) {
				$swapdev = "UUID=$uuid";
			}
			else {
				# BusyBox's mkswap doesn't support UUIDs, so
				# we'll need to generate it and write it out.
				$uuid = `$UUIDGEN`;
				chomp $uuid;
				set_swap_uuid($swapdev, $uuid);
				$swapdev="UUID=$uuid";
			}
		}
		elsif ($old_root) {
			$swapdev =~ s#^$root_disk#$old_root_disk#;
		}

		push @swapdevs, $swapdev;
	}

	return undef unless (@swapdevs);

	my @buffer;
	if (!open FSTAB, "+<$imageroot/etc/fstab") {
		print STDERR "Failed to open fstab: $!\n";
		return undef;
	}

	@buffer = grep {!/^[^#].*\bswap\b.*$/} <FSTAB>;
	for (@swapdevs) {
		push @buffer, "$_\tnone\tswap\tsw\t0 0\n";
	}
	seek FSTAB, 0, 0;
	print FSTAB @buffer;
	close FSTAB;
}

277
sub file_replace_string
278 279 280 281
{
	my ($imageroot, $file, $old_root, $new_root) = @_;
	my @buffer;

282 283 284 285 286
	if (!$old_root) {
		print STDERR "old_root is empty\n";
		return 1;
	}

287 288 289 290 291 292 293 294 295 296
	open FILE, "+<$imageroot/$file" ||
	     die "Couldn't open $imageroot/$file: $!\n";

	while (<FILE>) {
		s#$old_root#$new_root#g;
		push @buffer, $_;
	}

	seek FILE, 0, 0;

Ryan Jackson's avatar
Ryan Jackson committed
297
	print FILE @buffer;
298 299 300 301 302 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

	close FILE;

	return 1;
}

sub rewrite_lilo_config
{
	my ($imageroot, $old_root, $new_root) = @_;
	my @buffer;

	open FILE, "+<$imageroot/etc/lilo.conf" ||
	     die "Couldn't open $imageroot/etc/lilo.conf: $!\n";

	while (<FILE>) {
		chomp;
		next if /^\s*root\s*=\s*/;
		s/^\s*boot\s*=\s*.*$/boot = $new_root/g;
		if (/append\s*=\s*/i) {
			s/\s*root=[^"'\s]*//g;
			s/(["'])\s*$/ root=$new_root$1/;
		}
		push @buffer, $_;
	}

	seek FILE, 0, 0;

	print FILE "$_\n" for (@buffer);

	close FILE;

	return 1;
}

sub set_runlilo_flag
{
	my ($imageroot, $default_entry, $new_root) = @_;
Ryan Jackson's avatar
Ryan Jackson committed
335
	my $cmdline;
336 337 338

	open FILE, ">$imageroot/var/emulab/boot/runlilo" ||
	     die "Couldn't write to runlilo file: $!\n";
Ryan Jackson's avatar
Ryan Jackson committed
339 340
	
	$cmdline = "$default_entry root=$new_root";
341

Ryan Jackson's avatar
Ryan Jackson committed
342
	print FILE "$cmdline\n";
343 344 345

	close FILE;

Ryan Jackson's avatar
Ryan Jackson committed
346
	return $cmdline;
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
}

sub find_default_grub_entry
{
	my ($imageroot, $conf) = @_;
	my @buffer;
	my $default = 0;
	my $current_entry = -1;
	my ($kernel, $cmdline, $initrd);

	open FILE, "$imageroot/$conf" || die "Couldn't read grub config: $!\n";
	while (<FILE>) {
		if (/^default\s+(\d+)$/) {
			$default = $1;
			next;
		}
		elsif (/^\s*(\S+)\s+(.*)$/) {
			if ($1 eq 'title') {
				$current_entry++;
			}

			next if ($current_entry < $default);
			last if ($current_entry > $default);

			if ($1 eq 'kernel') {
				$_ = $2;
				($kernel, $cmdline) = /^(\S+)\s+(.*)$/;
			}
			elsif ($1 eq 'initrd') {
				$initrd = $2;
			}
		}
	}
	close FILE;

	return ($kernel, $cmdline, $initrd);
}

Ryan Jackson's avatar
Ryan Jackson committed
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
sub find_default_grub2_entry
{
	my ($imageroot, $conf) = @_;
	my @buffer;
	my $default = 0;
	my $current_entry = -1;
	my ($kernel, $cmdline, $initrd);

	open FILE, "$imageroot/$conf" || die "Couldn't read grub config: $!\n";
	while (<FILE>) {
		if (/^set\s+default\s*=\s*["']?(\d+)["']?$/) {
			$default = $1;
			next;
		}
		elsif (/^\s*(\S+)\s+(.*)$/) {
			if ($1 eq 'menuentry') {
				$current_entry++;
			}

			next if ($current_entry < $default);
			last if ($current_entry > $default);

			if ($1 eq 'linux') {
				$_ = $2;
				($kernel, $cmdline) = /^(\S+)\s+(.*)$/;
			}
			elsif ($1 eq 'initrd') {
				$initrd = $2;
			}
		}
	}
	close FILE;

	return ($kernel, $cmdline, $initrd);
}

421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
sub set_grub_root_device
{
	my ($imageroot, $grub_config, $root) = @_;
	my ($root_disk, $root_part) =
	   ($root =~ m#/dev/(.+)(\d+)#);
	my $grub_disk;

	if (-f $BOOTDIR . "/edd_map") {
		open FILE, $BOOTDIR . "/edd_map";
		while (<FILE>) {
			chomp;
			split /=/;
			if ($_[0] eq $root_disk) {
				$grub_disk = hex($_[1]) - 0x80;
				print "Found GRUB root device using EDD\n";
				last;
			}
		}
		close FILE;
	}

	if (not defined $grub_disk) {
		$grub_disk = $root;
Ryan Jackson's avatar
Ryan Jackson committed
444
		$grub_disk =~ s/^\/dev\/[hs]d(.).*$/$1/;
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
		$grub_disk =~ y/[a-h]/[0-7]/;
		print "Found GRUB root device by guessing\n";
	}

	printf "GRUB root device is (hd%d,%d)\n", $grub_disk, $root_part - 1;
	$root_part--;

	open FILE, "+<$imageroot/$grub_config" or
	     die "Couldn't open GRUB config: $!\n";
	my @buffer;
	while (<FILE>) {
		s/^(\s*)root \([^)]*\)/$1root (hd$grub_disk,$root_part)/;
		push @buffer, $_;
	}
	seek FILE, 0, 0;
Ryan Jackson's avatar
Ryan Jackson committed
460
	print FILE @buffer;
461 462 463
	close FILE;
}

Ryan Jackson's avatar
Ryan Jackson committed
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
sub set_grub2_root_device
{
	my ($imageroot, $grub_config, $root) = @_;
	my ($root_disk, $root_part) =
	   ($root =~ m#/dev/(.+)(\d+)#);
	my $grub_disk;

	if (-f $BOOTDIR . "/edd_map") {
		open FILE, $BOOTDIR . "/edd_map";
		while (<FILE>) {
			chomp;
			split /=/;
			if ($_[0] eq $root_disk) {
				$grub_disk = hex($_[1]) - 0x80;
				print "Found GRUB root device using EDD\n";
				last;
			}
		}
		close FILE;
	}

	if (not defined $grub_disk) {
		$grub_disk = $root;
		$grub_disk =~ s/^\/dev\/[hs]d(.).*$/$1/;
		$grub_disk =~ y/[a-h]/[0-7]/;
		print "Found GRUB root device by guessing\n";
	}

	printf "GRUB root device is (hd%d,%d)\n", $grub_disk, $root_part;

	open FILE, "+<$imageroot/$grub_config" or
	     die "Couldn't open GRUB config: $!\n";
	my @buffer;
	while (<FILE>) {
498 499 500 501
		# XXX eat the newline so the RE does not!
		chomp;
		s/^(\s*set\s+root\s*=\s*["']?\(?)[^)'"]*(\)?["']?)/$1hd$grub_disk,$root_part$2/;
		push @buffer, "$_\n";
Ryan Jackson's avatar
Ryan Jackson committed
502 503 504 505 506 507
	}
	seek FILE, 0, 0;
	print FILE @buffer;
	close FILE;
}

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
sub find_default_lilo_entry
{
	my ($imageroot, $conf) = @_;
	my %images;
	my %globals;
	my @image_list;
	my ($kernel, $cmdline, $initrd);
	my $default;

	open FILE, "$imageroot/$conf" || die "Couldn't read lilo config: $!\n";
	while (<FILE>) {
		chomp;

		my $command;
		my $args;
		s/\s*#.*$//; # Remove comments
		s/\s+$//; # Remove trailing whitespace
		next if (/^$/); # Skip blank lines
		if (/^\s*image\s*=\s*(.*)\s*$/i) {
			push @image_list, $1;
			$images{$1} = {'image' => $1};
		}
		elsif (/^\s*(?:label|alias)\s*=\s*(.*)\s*$/i) {
			$images{$1} = $images{$image_list[-1]};
		}
		elsif (/^\s*(\S+)\s*=\s*(.*)\s*$/) {
			($command, $args) = (lc $1, $2);
		}
		elsif (/^\s*(?:read-only|ro)$/) {
			($command, $args) = ('read-only', 'ro');
		}
		elsif (/^\s*(?:read-write|rw)$/) {
			($command, $args) = ('read-only', 'rw');
		}
		else {
			($command, $args) = ($_, 1);
		}

		if (@image_list) {
			${$images{$image_list[-1]}}{$command} = $args;
		}
		else {
			$globals{$command} = $args;
		}
	}
	close FILE;

	if (exists $globals{'default'}) {
		$default = $globals{'default'};
	}
	else {
		$default = $image_list[0];
	}

	my $root = $images{$default}{'root'};
	$initrd = $images{$default}{'initrd'};
	$cmdline = $images{$default}{'append'};
	$kernel = $images{$default}{'image'};
	my $ro = $images{$default}{'read-only'};
	if (not defined $root) {
		$root = $globals{'root'};
	}
	if (not defined $initrd) {
		$initrd = $globals{'initrd'};
	}
	if (not defined $cmdline) {
		$cmdline = $globals{'append'};
	}
	if (not defined $ro) {
		$ro = $globals{'read-only'};
	}

	$cmdline =~ s/^"(.*)"$/$1/;
	if ($root && $cmdline !~ /\broot=\S+\b/) {
		$cmdline .= " root=$root";
	}
	if ($ro && $cmdline !~ /\br[ow]\b/) {
		$cmdline .= " $ro";
	}

	return ($default, $kernel, $cmdline, $initrd);
}

sub guess_bootloader
{
	my ($device) = @_;
	my $buffer;
	my $bootloader;

	open DEVICE, $device || die "Couldn't open $device: $!\n";
	read DEVICE, $buffer, 512;
	close DEVICE;

	if ($buffer =~ /GRUB/) {
		$bootloader = 'grub';
	}
	elsif ($buffer =~ /LILO/) {
		$bootloader = 'lilo';
	}

	return $bootloader;
}

sub udev_supports_label
{
	my ($imageroot) = @_;
	my ($handles_label, $handles_uuid) = (0, 0);

	if (! -d "$imageroot/etc/udev/rules.d") {
		return (0, 0);
	}

	my @files = glob "$imageroot/etc/udev/rules.d/*";
Ryan Jackson's avatar
Ryan Jackson committed
621 622 623
	if (@files) {
		@files = glob "$imageroot/lib/udev/rules.d/*";
	}
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 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
	for my $file (@files) {
		open FILE, $file or next;
		my @buffer = <FILE>;
		close FILE;
		if (grep(/[^#]*ID_FS_UUID/, @buffer)) {
			$handles_uuid = 1;
		}

		if (grep(/[^#]*ID_FS_LABEL/, @buffer)) {
			$handles_label = 1;
		}
	}

	return ($handles_label, $handles_uuid);
}

sub binary_supports_blkid
{
	my ($file) = @_;
	my $handles_label = 0;
	my $handles_uuid = 0;

	if (-x $file) {
		local $/;
		my $buffer;
		open FILE, $file or
		     die "Couldn't grep $file: $!\n";
		$buffer = <FILE>;
		close FILE;

		if ($buffer =~ /libblkid\.so/) {
			$handles_label = 1;
			$handles_uuid = 1;
		}
		else{ 
			if ($buffer =~ /LABEL/) {
				$handles_label = 1;
			}
			if ($buffer =~ /UUID/) {
				$handles_uuid = 1;
			}
		}
	}

	return ($handles_label, $handles_uuid);
}

sub get_fstab_root
{
	my ($imageroot) = @_;
	my $root;

	open FSTAB, "$imageroot/etc/fstab" ||
	     die "Couldn't open fstab: $!\n";

	while (<FSTAB>) {
		split /\s+/;
		if ($_[1] eq '/') {
			$root = $_[0];
		}
	}

	close FSTAB;

	return $root;
}

sub check_kernel
{
	my ($kernel) = @_;
	my $offset = 0;;
	my $buffer;
	my $rc;
	my $kernel_file = "/tmp/kernel.$$";
	my $kernel_has_ide = 0;
	my $version_string;

Mike Hibler's avatar
Mike Hibler committed
701
	open KERNEL, $kernel or die "Couldn't open $kernel: $!\n";
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
	read KERNEL, $buffer, 4;
	while ($rc = read KERNEL, $buffer, 1, length($buffer)) {
		my ($value) = unpack 'N', $buffer;
		if ($value == GZHDR1 || $value == GZHDR2) {
			last;
		}
		$buffer = substr $buffer, 1;
	}
	if ($rc == 0) {
		return undef;
	}

	open GZIP, "|$GZIP -dc > $kernel_file 2> /dev/null";
	print GZIP $buffer;
	while (read KERNEL, $buffer, 4096) {
		print GZIP $buffer;
	}
	close KERNEL;
	close GZIP;


	open KERNEL, $kernel_file or die "Couldn't open raw kernel: $!\n";
	while (<KERNEL>) {
		if (/ide[-_]disk/) {
			$kernel_has_ide = 1;
		}
		if (/Linux version (\S+)/) {
			$version_string = $1;
		}
	}
	close KERNEL;

	unlink "$kernel_file";

	return ($version_string, $kernel_has_ide);
}

sub check_initrd
{
	my ($initrd) = @_;
	my $decompressed_initrd = "/tmp/initrd.$$";
	my $initrd_dir = "/tmp/initrd.dir.$$";
	my $handles_label = 0;
	my $handles_uuid = 0;

	return undef if (! -f $initrd);

	mkdir $initrd_dir;
	`$GZIP -dc < "$initrd" > "$decompressed_initrd" 2> /dev/null`;
	if ($? >> 8) {
		`$CP "$initrd" "$decompressed_initrd"`;
		if ($? & 0xff) {
			return undef;
		}
	}

	`$MOUNT -o ro,loop -t ext3 "$decompressed_initrd" "$initrd_dir" 2> /dev/null`;
	if ($? >> 8) {
		`$MOUNT -o ro,loop -t ext2 "$decompressed_initrd" "$initrd_dir" 2> /dev/null`;
		if ($? >> 8) {
			`cd "$initrd_dir" && $CPIO -idu < "$decompressed_initrd" > /dev/null 2>/dev/null`;
			if ($? >> 8) {
				return undef;
			}
		}
	}

	for ('/bin/busybox', '/bin/nash', '/bin/mount') {
		next unless (-f "$initrd_dir/$_");
		($handles_label, $handles_uuid) =
		    binary_supports_blkid("$initrd_dir/$_");
		last;
	}

	if (!$handles_label && !$handles_uuid) {
		($handles_label, $handles_uuid) =
		    udev_supports_label($initrd_dir);
	}

	`$UMOUNT "$initrd_dir" > /dev/null 2> /dev/null`;
	`$RM -rf "$initrd_dir" "$decompressed_initrd"`;
Ryan Jackson's avatar
Ryan Jackson committed
783 784 785 786 787 788 789 790 791 792 793 794 795
	
	my @loopdevs;
	open LOSETUP, "$LOSETUP|";
	while (<LOSETUP>) {
		chomp;
		split /:/;
		push @loopdevs, $_[0];
	}
	
	for my $dev (@loopdevs) {
		`$LOSETUP -d $dev`;
	}
		
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

	return ($handles_label, $handles_uuid);
}

sub mount_image
{
	my ($root, $imageroot) = @_;
	my $fstype;

	for my $type (qw/ext3 ext2/) {
		`mount -t $type $root $imageroot`;
		if (!($? >> 8)) {
			$fstype = $type;
			last;
		}
	}

	return $fstype;
}

sub update_random_seed
{
	my ($imageroot) = @_;
	my $seed;
	my $size;
	my $rc = 1;

	if (! -f "$imageroot/var/lib/random-seed") {
		return undef;
	}

	print "Updating /var/lib/random-seed\n";
	open URANDOM, '/dev/urandom';
	$size = 512;
	while ($rc && $size > 0) {
		my $rc = read URANDOM, $seed, $size, length($seed);
		$size -= $rc;
	}
	close URANDOM;

	open SEED, ">$imageroot/var/lib/random-seed";
	print SEED $seed;
	close SEED;
}

841 842 843 844 845 846 847 848
#
# Localize the image. We only do this if the MFS we are running in
# has the necessary files.
#
sub localize
{
    my ($imageroot) = @_;

849
    if (! -e "$LOCALIZED1" && ! -e "$LOCALIZED2") {
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 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
	return;
    }

    # Check the certs.
    if (! -d "$imageroot/etc/emulab") {
	if (!mkdir("$imageroot/etc/emulab", 0755)) {
	    print STDERR "Failed to mkdir $imageroot/etc/emulab\n";
	    return;
	}
    }
    if (-e "$ETCDIR/emulab.pem") {
	system("cmp -s $ETCDIR/emulab.pem $imageroot/etc/emulab/emulab.pem >/dev/null 2>&1");
	if ($?) {
	    print "Updating $imageroot/etc/emulab/emulab.pem\n";
	    system("cp -p $ETCDIR/emulab.pem $imageroot/etc/emulab/");
	    if ($?) {
		print STDERR "Failed to create $ETCDIR/emulab.pem\n";
		return;
	    }
	}
    }
    if (-e "$ETCDIR/client.pem") {
	system("cmp -s $ETCDIR/client.pem $imageroot/etc/emulab/client.pem >/dev/null 2>&1");
	if ($?) {
	    print "Updating $imageroot/etc/emulab/client.pem\n";
	    system("cp -p $ETCDIR/client.pem $imageroot/etc/emulab/");
	    if ($?) {
		print STDERR "Failed to create $ETCDIR/client.pem\n";
		return;
	    }
	}
    }

    # Check the root keys
    if (-e "/root/.ssh/authorized_keys2") {
	system("cmp -s /root/.ssh/authorized_keys2 $imageroot/root/.ssh/authorized_keys >/dev/null 2>&1");
	if ($?) {
	    print "Updating /root/.ssh/authorized_keys\n";
	    if (! -d "$imageroot/root/.ssh") {
		if (!mkdir("$imageroot/root/.ssh", 0700)) {
		    print STDERR "Failed to mkdir /root/.ssh\n";
		    return;
		}
	    }
	    # copy to both authorized_keys and _keys2
	    system("cp -p /root/.ssh/authorized_keys2 $imageroot/root/.ssh/authorized_keys");
	    if ($?) {
		print STDERR "Failed to create /root/.ssh/authorized_keys\n";
		return;
	    }
	    system("cp -p /root/.ssh/authorized_keys2 $imageroot/root/.ssh/");
	    if ($?) {
		print STDERR "Failed to create /root/.ssh/authorized_keys2\n";
		return;
	    }
	}
    }

    # Check the host keys.
    my $changehostkeys = 0;
    if (-e "/etc/ssh/ssh_host_key") {
	system("cmp -s /etc/ssh/ssh_host_key $imageroot/etc/ssh/ssh_host_key >/dev/null 2>&1");
	if ($?) {
	    $changehostkeys = 1;
	}
    }
    if (-e "/etc/ssh/ssh_host_rsa_key") {
	system("cmp -s /etc/ssh/ssh_host_rsa_key $imageroot/etc/ssh/ssh_host_rsa_key >/dev/null 2>&1");
	if ($?) {
	    $changehostkeys = 1;
	}
    }
    if (-e "/etc/ssh/ssh_host_dsa_key") {
	system("cmp -s /etc/ssh/ssh_host_dsa_key $imageroot/etc/ssh/ssh_host_dsa_key >/dev/null 2>&1");
	if ($?) {
	    $changehostkeys = 1;
	}
    }
    if ($changehostkeys) {
	print "Updating /etc/ssh/hostkeys\n";

	if (! -d "$imageroot/etc/ssh") {
	    if (!mkdir("$imageroot/etc/ssh", 0755)) {
		print STDERR "Failed to mkdir $imageroot/etc/ssh\n";
		return;
	    }
	}
	system("cp -p /etc/ssh/ssh_host_* $imageroot/etc/ssh/");
	if ($?) {
	    print STDERR "Failed to create /etc/ssh/hostkeys\n";
	    return;
	}
    }

    # Check the time zone.
    if (-e "/etc/localtime") {
	system("cmp -s /etc/localtime $imageroot/etc/localtime >/dev/null 2>&1");
	if ($?) {
	    print "Updating /etc/localtime\n";

	    system("cp -p /etc/localtime $imageroot/etc/localtime");
	    if ($?) {
		print STDERR "Failed to create /etc/localtime\n";
		return;
	    }
	}
    }
957 958 959 960 961 962 963 964 965 966 967 968 969 970

    # Check the NTP configuration.
    if (-e "/etc/ntp.conf") {
	system("cmp -s /etc/ntp.conf $imageroot/etc/ntp.conf >/dev/null 2>&1");
	if ($?) {
	    print "Updating /etc/ntp.conf\n";

	    system("cp -p /etc/ntp.conf $imageroot/etc/ntp.conf");
	    if ($?) {
		print STDERR "Failed to create /etc/ntp.conf\n";
		return;
	    }
	}
    }
971 972
}

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
sub hardwire_boss_node
{
	my ($imageroot) = @_;
	my $bossnode;

	if (-r $ETCDIR . "/bossnode") {
		local $/;
		open BOSSNODE, $ETCDIR . "/bossnode";
		$bossnode = <BOSSNODE>;
		close BOSSNODE;

		chomp $bossnode;
	}
	else {
		return undef;
	}

	if (!-d "$imageroot/etc/emulab") {
		return undef;
	}

	print "Hardwiring boss to $bossnode\n";
	if (!open BOSSNODE, "$imageroot/etc/emulab/bossnode") {
		print STDERR "Failed to create /etc/emulab/bossnode\n";
		return undef;
	}

	print BOSSNODE "$bossnode\n";
	close BOSSNODE;

	return 1;
}

sub main
{
	my ($root, $old_root) = @_;
	my $imageroot = '/mnt';
	my $new_fstab_root;
	my $new_bootloader_root;
	my $old_bootloader_root;
	my $grub_config;
	my ($kernel, $cmdline, $initrd);
	my $lilo_default;
	my $lilo_commandline = 0;

1018
	my $old_uuid = get_uuid($root);
Ryan Jackson's avatar
Ryan Jackson committed
1019
	set_random_rootfs_uuid($root);
1020
	disable_time_dependent_fsck($root);
1021 1022 1023 1024 1025
	my $fstype = mount_image($root, $imageroot);
	my $uuid = get_uuid($root);
	my $label = get_label($root);
	my $bootloader = guess_bootloader($root);
	my $old_fstab_root = get_fstab_root($imageroot);
Ryan Jackson's avatar
Ryan Jackson committed
1026 1027 1028 1029 1030 1031 1032

	# HACK: there's no simple way to distinguish grub2 from grub
	# by the boot sector.
	if ($bootloader eq 'grub' && -f "$imageroot/boot/grub/grub.cfg") {
		$bootloader = 'grub2';
	}

1033 1034 1035 1036 1037
	if ($bootloader eq 'lilo') {
		($lilo_default, $kernel, $cmdline, $initrd) =
		    find_default_lilo_entry($imageroot, "/etc/lilo.conf");
	}
	elsif ($bootloader eq 'grub') {
1038
		for (qw#/boot/grub/menu.lst#) {
Ryan Jackson's avatar
Ryan Jackson committed
1039
			if (-f "$imageroot/$_") {
1040 1041 1042 1043 1044 1045 1046 1047
				$grub_config = $_;
				last;
			}
		}

		($kernel, $cmdline, $initrd) =
		    find_default_grub_entry($imageroot, $grub_config);

Ryan Jackson's avatar
Ryan Jackson committed
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
	}
	elsif ($bootloader eq 'grub2') {
		for (qw#/boot/grub/grub.cfg#) {
			if (-f "$imageroot/$_") {
				$grub_config = $_;
				last;
			}
		}

		($kernel, $cmdline, $initrd) =
		    find_default_grub2_entry($imageroot, $grub_config);

1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
	}
	else {
		print STDERR "Couldn't guess bootloader\n";
		return 1;
	}

	for my $token (split /\s+/, $cmdline) {
		next unless ($token =~ /^root=/);
		$token =~ s/^root=//;
		$old_bootloader_root = $token;
		last;
	}

	my ($initrd_does_label, $initrd_does_uuid) = 
	    check_initrd("$imageroot/$initrd");
	my ($mount_does_label, $mount_does_uuid) = 
	    binary_supports_blkid("$imageroot/bin/mount");

	my ($kernel_version, $kernel_has_ide) = 
	    check_kernel("$imageroot/$kernel");

1081
	print "Old root FS uuid: $old_uuid\n";
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
	print "Root FS UUID: $uuid\n";
	print "Root FS LABEL: $label\n";
	print "Installed bootloader: $bootloader\n";
	print "fstab root: $old_fstab_root\n";
	print "kernel: $kernel\n";
	print "kernel version: $kernel_version\n";
	print "kernel has IDE support: $kernel_has_ide\n";
	print "cmdline: $cmdline\n";
	print "initrd: $initrd\n";
	print "initrd blkid: $initrd_does_label $initrd_does_uuid\n";
	print "mount blkid: $mount_does_label $mount_does_uuid\n";
1093
	print "old bootloader root: $old_bootloader_root\n";
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

	if ($uuid && $mount_does_uuid) {
		$new_fstab_root = "UUID=$uuid";
	}
	elsif ($label && $mount_does_label) {
		$new_fstab_root = "LABEL=$label";
	}
	elsif (kernel_version_compare($kernel_version, '2.6.21') < 0 ||
	       $kernel_has_ide) {
		$new_fstab_root = $old_root;
	}
	else {
		$new_fstab_root = $root;
	}

	if ($uuid && $initrd_does_uuid) {
		$new_bootloader_root = "UUID=$uuid";
	}
	elsif ($label && $initrd_does_label) {
		$new_bootloader_root = "LABEL=$label";
	}
	elsif (kernel_version_compare($kernel_version, '2.6.21') < 0 ||
	       $kernel_has_ide) {
		$new_bootloader_root = $old_root;
	}
	else {
		$new_bootloader_root = $root;
	}

	print "Rewriting /etc/fstab to use '$new_fstab_root' as root device\n";
1124
 	file_replace_string($imageroot, '/etc/fstab', $old_fstab_root,
1125
	                         $new_fstab_root);
1126 1127
	file_replace_string($imageroot, '/etc/fstab', $old_uuid,
	                         $uuid);
1128 1129 1130 1131 1132 1133 1134

	print "Rewriting $bootloader config to use '$new_bootloader_root' as root device\n";
	if ($bootloader eq 'lilo') {
		rewrite_lilo_config($imageroot, $old_bootloader_root, $new_bootloader_root);
		$lilo_commandline = set_runlilo_flag($imageroot, $lilo_default, $new_bootloader_root);
	}
	elsif ($bootloader eq 'grub') {
1135 1136 1137 1138
		print "grub config is $grub_config\n";
		#file_replace_string($imageroot, $grub_config, $old_bootloader_root,
		 #                        $new_bootloader_root);
		file_replace_string($imageroot, $grub_config, $old_uuid, $uuid);
1139 1140
		set_grub_root_device($imageroot, $grub_config, $root);
	}
Ryan Jackson's avatar
Ryan Jackson committed
1141
	elsif ($bootloader eq 'grub2') {
1142
		file_replace_string($imageroot, $grub_config, $old_bootloader_root,
Ryan Jackson's avatar
Ryan Jackson committed
1143
		                         $new_bootloader_root);
1144
		file_replace_string($imageroot, $grub_config, $old_uuid, $uuid);
1145
		file_replace_string($imageroot, $grub_config, $old_uuid, $uuid);
Ryan Jackson's avatar
Ryan Jackson committed
1146 1147
		set_grub2_root_device($imageroot, $grub_config, $root);
	}
Mike Hibler's avatar
Mike Hibler committed
1148
	fix_grub_dom0mem($imageroot, $grub_config);
1149

Ryan Jackson's avatar
Ryan Jackson committed
1150 1151 1152
	fix_swap_partitions($imageroot, $root,
		$kernel_has_ide ? $old_root : undef );

1153
	update_random_seed($imageroot);
1154
	localize($imageroot);
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
	hardwire_boss_node($imageroot);

	# Run any postconfig scripts
	if (-x $BINDIR . '/osconfig') {
		print "Checking for dynamic client-side updates to slice...\n";
		system($BINDIR . "/osconfig -m $imageroot -M \"-t $fstype\" -f $fstype " .
		       "-D $root -s Linux postload");
	}

	`umount $imageroot`;

	if ($lilo_commandline) {
		$root =~ m/^(.*)(\d+)$/;
		my $disk = $1;
		my $part = $2;

		system("$BINDIR/groklilo -c \"$lilo_commandline\" $part $disk");
		if ($?) {
			print STDERR "Failed to set LILO command line\n";
			return 1;
		}
	}

	return 0;
}

main(@ARGV);