imagevalidate.in 29.5 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2014-2016 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
#
use English;
use strict;
use Getopt::Std;
use Data::Dumper;
use File::stat;

#
# Validate information for an image in the DB.
# Currently we validate:
#
#  * that image file exists
#  * that file mtime matches DB update time
#  * file size is correct
#  * SHA1 hash is correct
#  * covered sector range is correct
39
#  * (optional) the signature file exists and is correct
40 41 42
#
# The update option will fix all but the first.
#
43 44 45 46
# Note that any of the existence checks requires that the caller be able
# to access the project's image directory. That may not always be true
# if validating a shared image!
#
47 48
sub usage()
{
49 50 51
    print("Usage: imagevalidate [-dfupqRS] [-H hash] [-V str] <imageid> ...\n".
	  "       imagevalidate [-dfupqRS] [-H hash] [-V str] -P pid\n".
	  "       imagevalidate [-dfupqRS] [-H hash] [-V str] -a\n".
52
	  "Validate image information in the DB.\n".
53 54 55 56 57 58 59
	  "Options:\n".
	  "       -d      Turn on debug mode\n".
	  "       -f      Only update if DB says an image is out of date\n".
	  "       -u      Update incorrect or missing info in the DB\n".
	  "       -p      Show current information from the DB\n".
	  "       -q      Update quietly, no messages about mismatches\n".
	  "       -R      Set the relocatable flag if image file has relocations\n".
60
	  "       -a      Validate/update all images\n".
61
	  "       -A      Validate/update all versions of an image\n".
62
	  "       -P pid  Validate/update all images for a specific pid\n".
63 64 65
	  "       -U      Do not modify updater_uid in DB\n".
	  "       -H hash Use the provided hash rather than recalculating\n".
	  "       -V str  Comma separated list of fields to validate/update\n".
66 67 68
	  "               fields: 'hash', 'range', 'size', 'all', 'sig'; default is 'all'\n".
	  "               NOTE: 'sig' is special as it is not a DB field and\n".
	  "               thus is not included in the 'all' option.\n".
69
	  "       -S      Validate/update the image signature\n".
70
	  "               This is the same as specifying \"-V sig\".\n");
71 72
    exit(-1);
}
73
my $optlist    = "dfnupqRaP:UH:V:FSA";
74 75 76 77 78 79 80 81
my $debug      = 0;
my $showinfo   = 0;
my $update     = 0;
my $fastupdate = 0;
my $setreloc   = 0;
my $quiet      = 0;
my $doall      = 0;
my $doallpid;
82
my $allvers    = 0;
83
my $dosig      = 0;
84 85 86
my $nouser     = 0;
my %validate   = ();
my @images     = ();
87
my $userperm;
88
my $newhash;
89
my $accessfs   = 1;
90 91 92 93 94 95 96 97

#
# Configure variables
#
my $TB		= "@prefix@";
my $SHA1	= "/sbin/sha1";
my $IMAGEINFO	= "$TB/sbin/imageinfo";

98 99 100 101
# XXX note: bin not sbin, /usr/testbed/sbin/imagehash is something 
# entirely different!
my $IMAGEHASH   = "$TB/bin/imagehash";

102 103
# Protos
sub doimage($);
104 105
sub makehashfile($$$$);
sub removehashfile($$);
106
sub checksigfile($$$);
107
sub makesigfile($$$);
108
sub removesigfile($$);
109 110
sub havefullimage($);
sub havedeltaimage($);
111 112 113 114 115 116 117 118 119 120 121 122 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
sub fatal($);

#
# Untaint the path
#
$ENV{'PATH'} = "$TB/bin:$TB/sbin:/bin:/usr/bin:/usr/bin:/usr/sbin";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Turn off line buffering on output
#
$| = 1;

#
# Load the Testbed support stuff.
#
use lib "@prefix@/lib";
use EmulabConstants;
use Image;
use OSinfo;
use User;
use Project;

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
if (defined($options{"f"})) {
    $fastupdate = 1;
}
if (defined($options{"u"})) {
    $update = 1;
    $userperm = TB_IMAGEID_MODIFYINFO();
}
152 153 154
else {
    $userperm = TB_IMAGEID_READINFO();
}
155 156 157 158 159 160 161 162 163 164 165 166 167
if (defined($options{"p"})) {
    $showinfo = 1;
}
if (defined($options{"q"})) {
    $quiet = 1;
}
if (defined($options{"R"})) {
    fatal("Do not use -R; image relocations are NOT a reliable indicator!");
    #$setreloc = 1;
}
if (defined($options{"a"})) {
    $doall = 1;
}
168 169 170
if (defined($options{"A"})) {
    $allvers = 1;
}
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
if (defined($options{"P"})) {
    if ($options{"P"} =~ /^([-\w]+)$/) {
	$doallpid = $1;
	$doall = 1;
    } else {
	fatal("Invalid project name for -P");
    }
}
if (defined($options{"U"})) {
    $nouser = 1;
}
if (defined($options{"H"})) {
    if ($options{"H"} =~ /^([\da-fA-F]+)$/) {
	$newhash = lc($1);
    } else {
	fatal("Invalid hash string");
    }
}
if (defined($options{"V"})) {
    foreach my $f (split(',', $options{"V"})) {
	$validate{$f} = 1;
    }
} else {
    $validate{"all"} = 1;
}
196
if (defined($options{"S"}) || $validate{"sig"}) {
197 198
    $dosig = 1;
}
199 200
@images = @ARGV;

201 202 203 204 205
my $fixit = 0;
if (defined($options{"F"})) {
    $fixit = 1;
}

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
my ($user,$user_uid);
if ($UID) {
    $user = User->ThisUser();
    if (!defined($user)) {
	fatal("You ($UID) do not exist!");
    }
    $user_uid = $user->uid();
}

if ($nouser && $UID && !$user->IsAdmin()) {
    fatal("Only admin can use -U");
}

if ($doall) {
    if ($UID && !$user->IsAdmin()) {
	fatal("Only admin can use -a");
    }
    if ($doallpid) {
	if (!Project->Lookup($doallpid)) {
	    fatal("No such project '$doallpid'");
	}
    }
228 229
    @images = Image->ListAllVersions("ndz", $doallpid);
    if (@images > 50 && ($validate{"hash"} || $dosig)) {
230 231 232 233 234 235 236 237 238 239 240
	print STDERR "WARNING: processing ", int(@images),
	" images, will take a LONG time!\n";
    }
}

if (!$doall && @images == 0) {
    usage();
}
if (defined($newhash) && @images > 1) {
    fatal("-H option can only be used with a single image");
}
241 242 243
if ($allvers && @images > 1) {
    fatal("-A option can only be used with a single image");
}
244 245

my $errs = 0;
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

#
# Check all versions of a single image.
#
# In addition to putting all the versions in our list to check
# individually, perform some aggregate checks:
#
# - make sure there is SOME version of the image
# - all versions from 0 to current must exist in DB
# - version 0 must be a full image
#
if ($allvers) {
    my $image = Image->Lookup($images[0]);
    if (!$image) {
	print STDERR "$images[0]: no such image\n";
	exit(1);
    }

    my @iversions;
    $image->AllVersions(\@iversions);

    # Get the canonical name, sans version, for reporting.
    my $iname = $image->pid() . "/" . $image->imagename();

    if (@iversions == 0) {
	print STDERR "$iname: no version exists!\n";
	exit(1);
    }
    my $vers = 0;
    my @nimages = ();
    @iversions = reverse @iversions;
    foreach my $imobj (@iversions) {
	my $fqname = "$iname:$vers";
	if ($imobj->version() != $vers) {
	    my $ivers = $imobj->version() - 1;
	    if ($vers == $ivers) {
		print STDERR "$iname: version $vers missing\n";
	    } else {
		print STDERR "$iname: versions $vers-$ivers missing\n";
	    }
	    $vers = $imobj->version();
	    $errs++;
	    next;
	}

291
	if ($vers == 0 && !havefullimage($imobj)) {
292 293 294 295 296 297 298 299 300 301
	    print STDERR "$iname: no full initial version!\n";
	    $errs++;
	}

	push @nimages, $fqname;
	$vers++;
    }
    @images = @nimages;
}

302 303 304 305 306 307 308 309 310
foreach my $pidimage (@images) {
    $errs += doimage($pidimage);
}
exit($errs);

sub doimage($)
{
    my ($pidimage) = @_;

311 312
    print STDERR "Checking image '$pidimage' ...\n"
	if ($debug);
313 314 315 316 317 318 319
    my $image = Image->Lookup($pidimage);
    if (!defined($image)) {
	print STDERR "$pidimage: no such image\n";
	return 1;
    }
    my $imageid = $image->imageid();

320
    #
321
    # If the user is not an admin, must have perm on the image.
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
    #
    # We also test to see if the user can access the directory in which
    # images, etc. reside. This will not always be the case, a user may
    # have DB access to an image without being able to directly access
    # the image file. This can affect the way we do tests below.
    #
    if ($UID) {
	if (!$user->IsAdmin() && !$image->AccessCheck($user, $userperm)) {
	    print STDERR "$pidimage: insufficient privilege\n";
	    return 1;
	}

	my $statme;
	if ($image->IsDirPath()) {
	    $statme = $image->path();
	} elsif ($image->path() =~ /^(.*\/)[^\/]*$/) {
	    $statme = $1;
	}
	if ($statme && -e "$statme") {
	    $accessfs = 1;
	} else {
	    print STDERR "$pidimage: WARNING: cannot access image directory '$statme', some validations disabled.\n";
	    $accessfs = 0;
	}
    } else {
	$accessfs = 1;
348 349
    }

350 351 352 353
    #
    # Determine whether the image has a delta or a full image file or both!
    #
    my ($path,$dpath,$hash,$dhash,$isdir);
354
    if ($image->IsDirPath()) {
355 356
	$isdir = 1;
	#
357 358 359 360 361 362
	# XXX We prefer to use image file existence as the type
	# differentiator rather than using the Have{Full,Delta}Image()
	# methods since they use the size/deltasize fields which may not
	# be initialized yet. However, we may not always be able to access
	# the image in the filesystem, so we may have to fall back on the
	# standard methods. This is all hidden in our haveXXXimage functions.
363
	#
364
	if (havefullimage($image)) {
365 366
	    $path = $image->FullImageFile();
	}
367
	if (havedeltaimage($image)) {
368 369 370 371 372 373
	    $dpath = $image->DeltaImageFile();
	}
	$hash = $image->hash();
	$dhash = $image->deltahash();
    } else {
	$isdir = 0;
374 375 376 377 378
	#
	# XXX backward compat I
	# Originally, isdelta signified that the path (always .ndz)
	# represented a delta image and not a full image.
	#
379 380 381
	if ($image->isdelta()) {
	    $dpath = $image->DeltaImageFile();
	    $dhash = $image->deltahash();
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
	}
	#
	# XXX backward compat II
	# Then we introduced separate size/hash fields to differentiate
	# deltas from fulls and to allow both to exist at once. However,
	# we never finished that (by making the path a prefix to which
        # we appended .ndz or .ddz) so the path is always .ndz and only
	# one of full or delta will exist. So we have to trust the size
	# (via HaveXXXImage()) to determine whether the path represents
	# a full or delta image.
	#
	else {
	    if ($image->HaveFullImage()) {
		$path = $image->FullImageFile();
		$hash = $image->hash();
	    } elsif ($image->HaveDeltaImage()) {
		$dpath = $image->DeltaImageFile();
		$dhash = $image->deltahash();
	    }
401 402 403 404 405 406 407 408 409 410 411
	    #
	    # XXX backward compat III
	    # We may be called from image_import with neither size set (size
	    # being the value used by HaveXImage to determine existence),
	    # so we have to fall back on stating the image if we can and
	    # assuming it is a full image!
	    #
	    elsif ($accessfs && -e $image->FullImagePath()) {
		$path = $image->FullImageFile();
		$hash = $image->hash();
	    }
412
	}
413
    }
414 415
    $path = ""
	if (!defined($path));
416 417
    $dpath = ""
	if (!defined($dpath));
418 419
    $hash = ""
	if (!defined($hash));
420 421
    $dhash = ""
	if (!defined($dhash));
422 423 424 425 426 427

    my $size = $image->size();
    my $lbalo = $image->lba_low();
    my $lbahi = $image->lba_high();
    my $lbasize = $image->lba_size();
    my $relocatable = $image->relocatable();
428
    my $isdelta = $image->isdelta();
429
    my $dsize = $image->deltasize();
430 431 432 433 434 435 436
    my $stamp;
    $image->GetUpdate(\$stamp);
    $stamp = 0
	if (!defined($stamp));

    if ($showinfo) {
	print "$pidimage: mtime: $stamp\n";
437 438 439 440
	print "$pidimage: path: $path\n"
	    if ($path);
	print "$pidimage: deltapath: $dpath\n"
	    if ($dpath);
441
	if ($validate{"all"} || $validate{"size"}) {
442
	    my $chunks;
443
	    if ($size) {
444 445 446
		$chunks = int(($size + (1024*1024-1)) / (1024*1024));
		print "$pidimage: size: $size ($chunks chunks)\n";
	    }
447 448 449 450
	    if ($dsize) {
		$chunks = int(($dsize + (1024*1024-1)) / (1024*1024));
		print "$pidimage: deltasize: $dsize ($chunks chunks)\n";
	    }
451 452
	}
	if ($validate{"all"} || $validate{"hash"}) {
453 454 455 456
	    print "$pidimage: hash: $hash\n"
		if ($hash);
	    print "$pidimage: deltahash: $dhash\n"
		if ($dhash);
457 458 459 460 461 462
	}
	# XXX do sector range
	if ($validate{"all"} || $validate{"range"}) {
	    print "$pidimage: range: [$lbalo-$lbahi] (ssize: $lbasize), ".
		  "relocatable=$relocatable\n";
	}
463 464
	# XXX report on ancillary files
	my @afiles = ();
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
	if ($accessfs) {
	    if ($path && -e $image->FullImageSHA1File()) {
		push(@afiles, "full-SHA1");
	    }
	    if ($dpath && -e $image->DeltaImageSHA1File()) {
		push(@afiles, "delta-SHA1");
	    }
	    if ($path && -e $image->FullImageSigFile()) {
		push(@afiles, "full-sig");
	    }
	    if ($dpath && -e $image->DeltaImageSigFile()) {
		push(@afiles, "delta-sig");
	    }
	} else {
	    push(@afiles, "<cannot access directory>");
480 481 482 483
	}
	if (@afiles > 0) {
	    print "$pidimage: files: ", join(", ", @afiles), "\n";
	}
484 485 486 487 488

	return 0;
    }

    #
489
    # The image files have to exist.
490
    #
491
    if (!$path && !$dpath) {
492
	print STDERR "$pidimage: no image file found or cannot access\n";
493 494
	return 1;
    }
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
    my ($ftime,$fsize,$fuid,$dftime,$dfsize,$dfuid);
    if ($path) {
	if (! -r "$path") {
	    print STDERR "$pidimage: path: image path '$path' cannot be read\n";
	    #
	    # If root and cannot read it, it doesn't exist so get rid of
	    # hash and signature files too
	    #
	    if ($UID == 0 && ($update || $fixit)) {
		removehashfile($pidimage, $path);
		removesigfile($pidimage, $path);
	    }
	    return 1;
	}
	$ftime = stat($path)->mtime;
	$fuid = stat($path)->uid;
	$fsize = stat($path)->size;

	# XXX image file size must be non-zero
	if ($fsize == 0) {
	    print STDERR "$pidimage: full image file is zero-length, no can do!\n";
	    return 1;
517
	}
518
    }
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
    if ($dpath) {
	if (! -r "$dpath") {
	    print STDERR "$pidimage: path: deltaimage path '$dpath' cannot be read\n";
	    #
	    # If root and cannot read it, it doesn't exist so get rid of
	    # hash and signature files too
	    #
	    if ($UID == 0 && ($update || $fixit)) {
		removehashfile($pidimage, $dpath);
		removesigfile($pidimage, $dpath);
	    }
	    return 1;
	}
	$dftime = stat($dpath)->mtime;
	$dfuid = stat($dpath)->uid;
	$dfsize = stat($dpath)->size;

	# XXX image file size must be non-zero
	if ($dfsize == 0) {
	    print STDERR "$pidimage: delta image file is zero-length, no can do!\n";
	    return 1;
	}
541 542
    }

543 544 545
    #
    # Take care of one-off fix to hash and sig files
    #
546
    if ($fixit) {
547 548 549 550
	if (!$accessfs) {
	    print STDERR "$pidimage: hash: cannot access hash/sig files\n";
	    return 1;
	}
551 552 553 554 555 556 557
	if ($path) {
	    print "$pidimage: fixing hash file\n";
	    if ($hash eq "") {
		$hash = `$SHA1 $path`;
		if ($?) {
		    print("$pidimage: hash: could not generate SHA1 hash of '$path'\n");
		    return 1;
558
		} else {
559 560 561 562 563 564 565 566 567
		    if ($hash =~ /^SHA1.*= ([\da-fA-F]+)$/) {
			$hash = lc($1);
		    } else {
			print("$pidimage: hash: could not parse sha1 hash: '$hash'\n");
			return 1;
		    }
		}
		if ($image->SetHash($hash) != 0) {
		    print("$pidimage: hash: could not store new hash: '$hash'\n");
568 569 570
		    return 1;
		}
	    }
571 572 573 574
	    makehashfile($pidimage, $path, $hash, $fuid);

	    if ($dosig && checksigfile($pidimage, $path, 0)) {
		makesigfile($pidimage, $path, $fuid);
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
	if ($dpath) {
	    print "$pidimage: fixing delta hash file\n";
	    if ($dhash eq "") {
		$dhash = `$SHA1 $dpath`;
		if ($?) {
		    print("$pidimage: hash: could not generate SHA1 hash of '$path'\n");
		    return 1;
		} else {
		    if ($dhash =~ /^SHA1.*= ([\da-fA-F]+)$/) {
			$dhash = lc($1);
		    } else {
			print("$pidimage: hash: could not parse sha1 hash: '$dhash'\n");
			return 1;
		    }
		}
		if ($image->SetDeltaHash($dhash) != 0) {
		    print("$pidimage: hash: could not store new delta hash: '$dhash'\n");
		    return 1;
		}
	    }
	    makehashfile($pidimage, $dpath, $dhash, $dfuid);

	    #
	    # XXX cannot check the signature of a delta image since the
	    # signature is for the full image. Here we just make sure that
	    # the delta signature is the same as that of the full image.
	    #
	    if ($dosig) {
		my $dsfile = $image->DeltaImageSigFile();
		if ($path) {
		    my $sfile = $image->FullImageSigFile();
		    if (system("ln -f $sfile $dsfile")) {
			print STDERR
			    "$pidimage: WARNING: could not link $sfile to $dsfile\n";
		    }
		} elsif (-e "$dsfile") {
		    print STDERR
			"$pidimage: WARNING: could not verify signature for '$dpath'\n";
		} else {
		    print STDERR
			"$pidimage: no signature file for '$dpath'!\n";
		    return 1;
		}
	    }
621
	}
622 623 624
	return 0;
    }

625 626 627 628 629 630
    my $rv = 0;
    my $changed = 0;

    #
    # Check/fix mtime.
    #
631
    if ((!$path || $stamp == $ftime) && (!$dpath || $stamp == $dftime)) {
632 633 634 635 636 637
	if ($fastupdate) {
	    print STDERR "$pidimage: skipping due to time stamp\n"
		if ($debug);
	    return 0;
	}
    } else {
638 639 640 641 642 643 644 645 646 647 648 649 650
	if ($path && $stamp != $ftime) {
	    print("$pidimage: mtime: DB timestamp ($stamp) != mtime ($ftime)\n")
		if (!$update || !$quiet);
	    if ($update) {
		$changed = 1;
	    }
	}
	if ($dpath && $stamp != $dftime) {
	    print("$pidimage: mtime: DB timestamp ($stamp) != delta mtime ($dftime)\n")
		if (!$update || !$quiet);
	    if ($update) {
		$changed = 1;
	    }
651 652 653 654 655 656 657
	}
    }

    #
    # Check/fix file size.
    #
    if ($validate{"all"} || $validate{"size"}) {
658 659 660
	if ($path) {
	    if ($fsize != $size) {
		print("$pidimage: size: DB size ($size) != file size ($fsize)\n")
661 662
		    if (!$update || !$quiet);
		if ($update) {
663
		    print("$pidimage: size: ")
664
			if (!$quiet);
665
		    if ($image->SetSize($fsize) == 0) {
666 667 668 669 670 671 672 673
			$changed = 1;
			print "[FIXED]\n"
			    if (!$quiet);
		    } else {
			print "[FAILED]\n"
			    if (!$quiet);
			$rv = 1;
		    }
674
		} else {
675 676 677 678
		    $rv = 1;
		}
	    }
	    # XXX backward compat, only one of size/deltasize should be set
679 680
	    if ($update && !$dpath) {
		$image->SetDeltaSize(0);
681
	    }
682 683 684 685
	}
	if ($dpath) {
	    if ($dfsize != $dsize) {
		print("$pidimage: size: DB deltasize ($dsize) != file size ($dfsize)\n")
686 687
		    if (!$update || !$quiet);
		if ($update) {
688
		    print("$pidimage: dsize: ")
689
			if (!$quiet);
690
		    if ($image->SetDeltaSize($dfsize) == 0) {
691 692 693 694 695 696 697 698 699
			$changed = 1;
			print "[FIXED]\n"
			    if (!$quiet);
		    } else {
			print "[FAILED]\n"
			    if (!$quiet);
			$rv = 1;
		    }
		} else {
700 701
		    $rv = 1;
		}
702 703
	    }
	    # XXX backward compat, only one of size/deltasize should be set
704 705
	    if ($update && !$path) {
		$image->SetSize(0);
706 707
	    }
	}
708 709 710 711 712 713 714 715 716 717

	#
	# XXX isdelta is history, clear it if set.
	#
	# We do this after updating the size fields since those are now used
	# to distinguish full/delta.
	#
	if ($update && $isdelta) {
	    $image->SetDelta(0);
	}
718 719 720 721 722 723 724
    }

    #
    # Check/fix hash.
    #
    if ($validate{"all"} || $validate{"hash"}) {
	my $filehash = $newhash;
725 726 727 728 729
	if ($path) {
	    if (!defined($filehash)) {
		$filehash = `$SHA1 $path`;
		if ($?) {
		    print("$pidimage: hash: could not generate SHA1 hash of '$path'\n");
730
		    $filehash = "";
731 732 733 734 735 736 737 738
		    $rv = 1;
		} else {
		    if ($filehash =~ /^SHA1.*= ([\da-fA-F]+)$/) {
			$filehash = lc($1);
		    } else {
			print("$pidimage: hash: could not parse sha1 hash: '$filehash'\n");
			$filehash = "";
		    }
739 740 741 742 743 744 745 746
		}
	    }
	    if ($filehash && ($hash ne $filehash)) {
		print("$pidimage: hash: DB hash ('$hash') != file hash ('$filehash')\n")
		    if (!$update || !$quiet);
		if ($update) {
		    print("$pidimage: hash: ")
			if (!$quiet);
747
		    if ($image->SetHash($filehash) == 0) {
748
			makehashfile($pidimage, $path, $filehash, $fuid);
749 750 751 752 753 754 755 756 757 758 759 760 761 762
			$changed = 1;
			print "[FIXED]\n"
			    if (!$quiet);
		    } else {
			print "[FAILED]\n"
			    if (!$quiet);
			$rv = 1;
		    }
		} else {
		    $rv = 1;
		}
	    } elsif ($filehash) {
		# even if the DB is correct, make sure .sha1 file is correct
		if ($update) {
763
		    makehashfile($pidimage, $path, $filehash, $fuid);
764 765
		}
	    }
766 767

	    if ($update && !$dpath) {
768
		$image->SetDeltaHash(undef);
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
	    }
	}

	if ($dpath) {
	    if (!defined($filehash)) {
		$filehash = `$SHA1 $dpath`;
		if ($?) {
		    print("$pidimage: hash: could not generate SHA1 hash of '$dpath'\n");
		    $filehash = "";
		    $rv = 1;
		} else {
		    if ($filehash =~ /^SHA1.*= ([\da-fA-F]+)$/) {
			$filehash = lc($1);
		    } else {
			print("$pidimage: hash: could not parse sha1 hash: '$filehash'\n");
			$filehash = "";
		    }
		}
	    }
	    if ($filehash && ($dhash ne $filehash)) {
		print("$pidimage: hash: DB deltahash ('$dhash') != delta file hash ('$filehash')\n")
		    if (!$update || !$quiet);
		if ($update) {
		    print("$pidimage: hash: ")
			if (!$quiet);
		    if ($image->SetDeltaHash($filehash) == 0) {
			makehashfile($pidimage, $dpath, $filehash, $dfuid);
			$changed = 1;
			print "[FIXED]\n"
			    if (!$quiet);
		    } else {
			print "[FAILED]\n"
			    if (!$quiet);
			$rv = 1;
		    }
		} else {
		    $rv = 1;
		}
	    } elsif ($filehash) {
		# even if the DB is correct, make sure .sha1 file is correct
		if ($update) {
		    makehashfile($pidimage, $dpath, $filehash, $dfuid);
		}
	    }

	    if ($update && !$path) {
815
		$image->SetHash(undef);
816
	    }
817 818 819 820 821
	}
    }

    #
    # Check/fix sector range.
822
    # We can only do this if we have a full image.
823
    #
824
    if ($path && ($validate{"all"} || $validate{"range"})) {
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 887 888 889 890 891
	my ($lo,$hi,$ssize) = (-1,0,0);
	my $isreloc = $relocatable;
	my $out = `imageinfo -r $pidimage 2>&1`;
	if ($?) {
	    print("$pidimage: range: could not get sector range:\n$out");
	} else {
	    if ($out =~ /minsect=(\d+).*maxsect=(\d+).*secsize=(\d+)/s) {
		$lo = $1;
		$hi = $2;
		$ssize = $3;
		#
		# The sector range is actually relative to the slice
		# (partition) number that imagezip was told to save.
		# Thus a zero offset is actually the start sector of the
		# partition and we compensate for that before recording
		# the values in the DB.
		#
		my $off = $image->GetDiskOffset();
		if ($off > 0) {
		    $lo += $off;
		    $hi += $off;
		}
		#
		# XXX this is unreliable since we also generate a relocation
		# for images that do not have a full final sector. Hence, we
		# have disabled this.
		#
		# XXX the relocatable value returned by imageinfo is only a
		# heuristic. It says only that relocations exist in the image.
		# It is possible for a relocatable image to not actually
		# have any imagezip relocations. Hence we only change the
		# DB relocatable value from 0 -> 1 if explicitly asked and
		# there are relocations in the image file.
		#
		#if ($setreloc && $relocatable == 0 &&
		#    $out =~ /relocatable=1/s) {
		#    $isreloc = 1;
		#}
	    } else {
		print("$pidimage: range: could not parse imageinfo output:\n$out");
	    }

	    if ($lo >= 0 &&
		($lo != $lbalo || $hi != $lbahi || $ssize != $lbasize ||
		 $isreloc != $relocatable)) {
		print("$pidimage: range: DB range ([$lbalo-$lbahi]/$lbasize) != file range ([$lo-$hi]/$ssize)\n")
		    if (!$update || !$quiet);
		if ($update) {
		    print("$pidimage: range: ")
			if (!$quiet);
		    if ($image->SetRange($lo, $hi, $ssize, $isreloc) == 0) {
			$changed = 1;
			print "[FIXED]\n"
			    if (!$quiet);
		    } else {
			print "[FAILED]\n"
			    if (!$quiet);
			$rv = 1;
		    }
		} else {
		    $rv = 1;
		}
	    }
	}
    }

    #
892 893
    # Set update time to match mtime of image.
    # If there is both a full and delta image, set DB to full image time.
894 895
    #
    if ($changed) {
896 897
	my $mtime = ($path ? $ftime : $dftime);

898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
	print("$pidimage: mtime: ")
	    if (!$quiet);

	my $uuser = ($nouser ? undef : $user);
	# XXX if running as root and no current user, set to image creator
	if ($UID == 0 && !defined($image->updater())) {
	    $uuser = User->LookupByUid($image->creator());
	}

	if ($image->MarkUpdate($uuser, $mtime) == 0) {
	    print "[FIXED]\n"
		if (!$quiet);
	} else {
	    print "[FAILED]\n"
		if (!$quiet);
	    $rv = 1;
	}
915 916 917 918 919 920 921 922 923 924

	#
	# If both full and delta images, make sure delta matches full.
	#
	if ($path && $dpath && $ftime != $dftime) {
	    if (system("touch -r $path $dpath >/dev/null 2>&1")) {
		print STDERR
		    "$pidimage: WARNING: could not set modtime of $dpath\n";
	    }
	}
925 926
    }

927 928 929 930
    #
    # Check/fix signature file.
    #
    if ($dosig) {
931 932 933 934
	if (!$accessfs) {
	    print STDERR "$pidimage: sig: cannot access signature file\n";
	    return 1;
	}
935 936 937 938 939 940
	if ($path) {
	    if (checksigfile($pidimage, $path, 0)) {
		print("$pidimage: sig: image does not match signature\n")
		    if (!$update || !$quiet);
		if ($update) {
		    print("$pidimage: sig: ")
941
			if (!$quiet);
942 943 944 945 946 947 948 949
		    if (makesigfile($pidimage, $path, $fuid) == 0) {
			print "[FIXED]\n"
			    if (!$quiet);
		    } else {
			print "[FAILED]\n"
			    if (!$quiet);
			$rv = 1;
		    }
950 951 952
		} else {
		    $rv = 1;
		}
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
	    }
	}
	#
	# XXX cannot check the signature of a delta image since the signature
	# is for the full image. Here we just make sure that the delta
	# signature is the same as that of the full image.
	#
	# There is also no old sigfile to worry about.
	#
	if ($dpath) {
	    my $dsfile = $image->DeltaImageSigFile();
	    if ($path) {
		my $sfile = $image->FullImageSigFile();
		if (! -e "$dsfile" || system("cmp -s $sfile $dsfile")) {
		    print("$pidimage: dsig: delta signature missing or not the same as full\n")
			if (!$update || !$quiet);
		    if ($update) {
			print("$pidimage: dsig: ")
			    if (!$quiet);
			if (system("ln -f $sfile $dsfile") == 0) {
			    print "[FIXED]\n"
				if (!$quiet);
			} else {
			    print "[FAILED]\n"
				if (!$quiet);
			    $rv = 1;
			}
		    } else {
			$rv = 1;
		    }
		}
	    } elsif (-e "$dsfile") {
		print STDERR
		    "$pidimage: dsig: WARNING: could not verify signature for '$dpath'\n";
987
	    } else {
988 989
		print STDERR
		    "$pidimage: dsig: no signature file for '$dpath'!\n";
990 991 992 993 994
		$rv = 1;
	    }
	}
    }

995 996 997 998 999 1000 1001 1002
    return $rv;
}

sub partoffset($$)
{
    my ($part,$mbroff) = @_;
}

1003
# Return 0 if action is successful
1004
sub checksigfile($$$)
1005
{
1006
    my ($pidimage,$imagepath,$isdelta) = @_;
1007 1008
    my $sigfile = "$imagepath.sig";

1009 1010
    print STDERR "$pidimage: sig: checking signature of '$imagepath' ...\n"
	if ($debug);
1011 1012 1013 1014 1015 1016

    if (!$accessfs) {
	print STDERR "$pidimage: sig: cannot access signature file\n";
	return 0;
    }

1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    if (! -e "$sigfile") {
	# XXX the old stateful swapout path puts sigs in a sigs/ subdir
	if ($imagepath =~ /^(.*)\/([^\/]+)$/) {
	    my ($idir,$iname) = ($1,$2);
	    my $osigfile = "$idir/sigs/$iname.sig";
	    if (-e "$osigfile") {
		print STDERR
		    "$pidimage: WARNING: found old signature file $osigfile, ".
		    "use -u to create new signature.\n";
	    }
	}
1028

1029 1030 1031 1032
	print STDERR
	    "$pidimage: WARNING: no signature file for $imagepath\n";
	return 1;
    }
1033 1034 1035 1036 1037 1038 1039 1040 1041

    # XXX delta images will have full-image signatures and won't match
    if ($isdelta) {
	print STDERR
	    "$pidimage: WARNING: cannot verify signature of delta image ".
	    "$imagepath\n";
	return 0;
    }

1042 1043 1044 1045 1046
    if (system("$IMAGEHASH -SX $imagepath")) {
	print STDERR
	    "$pidimage: WARNING: $imagepath does not match signature\n";
	return 1;
    }
1047 1048 1049

    print STDERR "$pidimage: sig: signature OK\n"
	if ($debug);
1050 1051 1052 1053
    return 0;
}

# Return 0 if action is successful
1054
sub makesigfile($$$)
1055
{
1056
    my ($pidimage,$imagepath,$fuid) = @_;
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
    my $sigfile = "$imagepath.sig";

    # XXX get rid of old sigfile
    if ($imagepath =~ /^(.*)\/([^\/]+)$/) {
	my ($idir,$iname) = ($1,$2);
	my $osigfile = "$idir/sigs/$iname.sig";
	if (-e "$osigfile") {
	    print STDERR
		"$pidimage: NOTE: removing old signature file $osigfile\n";
	    unlink($osigfile);
	}
    }

1070 1071 1072 1073 1074 1075 1076
    unlink($sigfile);
    if (system("$IMAGEHASH -cXq $imagepath")) {
	print STDERR
	    "$pidimage: WARNING: could not create signature for $imagepath\n";
	unlink($sigfile);
	return 1;
    }
1077 1078 1079 1080
    if (defined($fuid) && system("chown $fuid $sigfile >/dev/null 2>&1")) {
	print STDERR
	    "$pidimage: WARNING: could not chown $sigfile to $fuid\n";
    }
1081

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
    return 0;
}

# Return 0 if action is successful
sub removesigfile($$)
{
    my ($pidimage,$imagepath) = @_;
    my $sigfile = "$imagepath.sig";

    if (!unlink($sigfile)) {
	return 1;
1093 1094
    }

1095 1096 1097 1098 1099 1100
    return 0;
}

#
# XXX Over time, we have used two different conventions for sha1 files.
#
1101
# Old format is <image>.sha1. New format is <image>.ndz.sha1, possibly
1102 1103 1104 1105 1106 1107 1108 1109 1110
# with a version number. We take it upon ourselves to force everything
# into the new format.
#

sub makehashfile($$$$)
{
    my ($pidimage,$imagepath,$hash,$fuid) = @_;

    my $hashfile = "$imagepath.sha1";
1111 1112
    unlink($hashfile);
    if (open(HASH, ">$hashfile")) {
1113 1114
	# XXX recreate the sha1 output format for compatibility
	print HASH "SHA1 ($imagepath) = $hash\n";
1115
	close($hashfile);
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
	if (defined($fuid) &&
	    system("chown $fuid $hashfile >/dev/null 2>&1")) {
	    print STDERR
		"$pidimage: WARNING: could not chown $hashfile to $fuid\n";
	}
	if (system("touch -r $imagepath $hashfile >/dev/null 2>&1")) {
	    print STDERR
		"$pidimage: WARNING: could not set modtime of $hashfile\n";
	}
    } else {
	print STDERR
	    "$pidimage: WARNING: could not create $hashfile\n";
    }

    # Look for old format files so we can remove them
    # XXX there only appear in the pre-version number days.
    if ($imagepath =~ /(.*)\.ndz$/) {
	my $oldhashfile = "$1.sha1";
	if (-e "$oldhashfile") {
	    print STDERR
		"$pidimage: NOTE: removing old sha1 file $oldhashfile\n";
	    unlink("$oldhashfile");
1138
	}
1139 1140 1141
    }
}

1142
sub removehashfile($$)
1143
{
1144
    my ($pidimage,$imagepath) = @_;
1145

1146 1147 1148 1149
    my $hashfile = "$imagepath.sha1";
    unlink($hashfile);

    # Remove old format file too
1150
    if ($imagepath =~ /(.*)\.ndz$/) {
1151 1152
	my $oldhashfile = "$1.sha1";
	unlink($oldhashfile);
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
#
# XXX our versions of image existence checks.
# We don't want to have to rely on DB state if we don't have to since
# we are probably the ones initializing that state!
#
sub havefullimage($)
{
    my ($image) = @_;

    if ($accessfs) {
	if (-e $image->FullImagePath()) {
	    return 1;
	}
    } else {
	if ($image->HaveFullImage()) {
	    return 1;
	}
    }
    return 0;
}

sub havedeltaimage($)
{
    my ($image) = @_;

    if ($accessfs) {
	if (-e $image->DeltaImagePath()) {
	    return 1;
	}
    } else {
	if ($image->HaveDeltaImage()) {
	    return 1;
	}
    }
    return 0;
}

1193 1194 1195 1196 1197 1198 1199 1200
sub fatal($)
{
    my ($mesg) = @_;

    print STDERR "*** $0:\n".
	         "    $mesg\n";
    exit(-1);
}