imagevalidate.in 48.6 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
Mike Hibler's avatar
Mike Hibler committed
3
# Copyright (c) 2014-2017 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
	  "               fields: 'hash', 'range', 'size', 'perm', 'all', 'sig'; default is 'all'\n".
67 68
	  "               NOTE: 'sig' is special as it is not a DB field and\n".
	  "               thus is not included in the 'all' option.\n".
Mike Hibler's avatar
Mike Hibler committed
69 70 71
	  "       -D      Validate/update the deleted status of image versions.\n".
	  "               WARNING: if image is marked as deleted in the DB,\n".
	  "               update will remove image files from the disk!\n".
72
	  "       -S      Validate/update the image signature\n".
73
	  "               This is the same as specifying \"-V sig\".\n");
74 75
    exit(-1);
}
Mike Hibler's avatar
Mike Hibler committed
76
my $optlist    = "dfnupqRaP:UH:V:FSDA";
77 78 79 80 81 82 83 84
my $debug      = 0;
my $showinfo   = 0;
my $update     = 0;
my $fastupdate = 0;
my $setreloc   = 0;
my $quiet      = 0;
my $doall      = 0;
my $doallpid;
85
my $allvers    = 0;
86
my $dosig      = 0;
Mike Hibler's avatar
Mike Hibler committed
87
my $dodeleted  = 0;
88 89 90
my $nouser     = 0;
my %validate   = ();
my @images     = ();
91
my $userperm;
92
my $newhash;
Mike Hibler's avatar
Mike Hibler committed
93 94
my $accessfs   = $UID ? 0 : 1;
my %imagedir   = ();
95 96
my %piddirperms   = ();
my %imagedirperms = ();
Mike Hibler's avatar
Mike Hibler committed
97 98

my $warnonfixable = 0;
99 100 101 102 103 104 105

#
# Configure variables
#
my $TB		= "@prefix@";
my $SHA1	= "/sbin/sha1";
my $IMAGEINFO	= "$TB/sbin/imageinfo";
Mike Hibler's avatar
Mike Hibler committed
106
my $PROJROOT    = "@PROJROOT_DIR@";
107
my $FSNODE      = "@FSNODE@";
108

109 110 111 112
# XXX note: bin not sbin, /usr/testbed/sbin/imagehash is something 
# entirely different!
my $IMAGEHASH   = "$TB/bin/imagehash";

113 114 115
# for efficient computation of hashes, we ssh to the FS node
my $SSH		= "$TB/bin/sshtb -n -l root -host $FSNODE";

116
# Protos
Mike Hibler's avatar
Mike Hibler committed
117 118
sub checkdeadimages($);
sub getallversions($);
119
sub doimage($);
120 121
sub makehashfile($$$$);
sub removehashfile($$);
122
sub checksigfile($$$);
123
sub makesigfile($$$);
124
sub removesigfile($$);
125 126
sub havefullimage($);
sub havedeltaimage($);
127
sub fatal($);
128
sub hashit($);
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

#
# 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;
146
use OSImage;
147 148
use User;
use Project;
Mike Hibler's avatar
Mike Hibler committed
149
use libdb;
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168

#
# 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();
}
169 170 171
else {
    $userperm = TB_IMAGEID_READINFO();
}
172 173 174 175 176 177 178 179 180 181 182 183 184
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;
}
185 186 187
if (defined($options{"A"})) {
    $allvers = 1;
}
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
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;
}
213
if (defined($options{"S"}) || $validate{"sig"}) {
214 215
    $dosig = 1;
}
Mike Hibler's avatar
Mike Hibler committed
216 217 218 219
if (defined($options{"D"})) {
    $dodeleted = 1;
    $allvers = 1;
}
220 221
@images = @ARGV;

222 223 224 225 226
my $fixit = 0;
if (defined($options{"F"})) {
    $fixit = 1;
}

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
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'");
	}
    }
Mike Hibler's avatar
Mike Hibler committed
249 250 251 252
    if ($allvers) {
	@images = OSImage->ListAll("ndz", $doallpid);
    } else {
	@images = OSImage->ListAllVersions("ndz", $doallpid);
253 254 255 256 257 258
    }
}

if (!$doall && @images == 0) {
    usage();
}
Mike Hibler's avatar
Mike Hibler committed
259 260 261
if ($allvers && @images == 0) {
    fatal("-A option needs at least one image");
}
262 263 264 265 266
if (defined($newhash) && @images > 1) {
    fatal("-H option can only be used with a single image");
}

my $errs = 0;
267

Mike Hibler's avatar
Mike Hibler committed
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 296 297 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 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 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 421 422 423 424 425 426 427
if ($allvers) {
    # check all dead images
    if ($doall && $dodeleted && $accessfs) {
	checkdeadimages($doallpid);
    }

    my @nimages = ();
    foreach my $pidimage (@images) {
	# XXX OSImage->Lookup blows up on old multi-partition images
	my $image = Image->Lookup($pidimage);
	if ($image && $image->ezid()) {
	    $image = OSImage->Lookup($pidimage);
	}
	if (!$image) {
	    print STDERR "$pidimage: no such image, ignoring\n";
	    next;
	}
	push(@nimages, getallversions($image));
    }
    @images = @nimages;
}

if (@images > 50 && ($validate{"hash"} || $dosig)) {
    print STDERR "WARNING: processing ", int(@images),
    " images, will take a LONG time!\n";
}

print STDERR "Will process ", int(@images), " images\n";
foreach my $pidimage (@images) {
    $errs += doimage($pidimage);
}
exit($errs);

#
# Dead image versions exist only in the image_versions table and
# have no corresponding imageid entry in the images table.
# For dead images:
#
# - all versions should be deleted
# - image file path should point to deleted image directory
#
# XXX We really cannot delete the image files as the path might be wrong
# and point to the image files for the live "pid/imagename"
#
# XXX uses naked DB queries since Image lookup functions won't work.
#
sub checkdeadimages($)
{
    my ($pid) = @_;

    my $clause = "";
    if (defined($pid)) {
	$clause = "AND v.pid='$pid'";
    }
    my $subquery = "SELECT v.imageid FROM image_versions AS v ".
	"  LEFT JOIN images AS i ON v.imageid=i.imageid ".
	"  WHERE i.imageid IS NULL $clause ".
	"  GROUP BY v.imageid";

    my $query_result =
	DBQueryWarn("SELECT pid,imagename,version,imageid,deleted,path".
		    "  FROM image_versions ".
		    "  WHERE imageid IN ($subquery) ".
		    "  ORDER BY pid,imagename,imageid,version");

    my %fixdirs = ();
    while (my ($pid,$name,$vers,$id,$del,$path) =
	   $query_result->fetchrow_array()) {
	my $iname = "DEAD $pid/$name ($id)";
	print STDERR "Checking dead image $id ('$pid/$name:$vers') ...\n"
	    if ($debug);
	if (!$del) {
	    print "$iname: version $vers not deleted ";
	    if ($update) {
		if (!DBQueryWarn("UPDATE image_versions SET deleted=now() ".
				 "WHERE imageid='$id' AND version='$vers'")) {
		    print "[FAILED]";
		} else {
		    print "[FIXED]";
		}
	    }
	    print "\n";
	}
	#
	# Figure out if the path is already in the correct form.
	# There is a limited amount we can do here since the path may
	# incorrectly point to the current incarnation of the image.
	#
	# If the directory part of the path contains a ':', we convert
	# it to a ',' in keeping with the new convention. If such a path
	# references a valid file, we rename the file as well.
	#
	if (defined($path)) {
	    my $dpath;

	    # XXX duplicate FullImagePath() method
	    if ($path =~ /\/$/) {
		$dpath = "$path$name.ddz" . ($vers ? ":$vers" : "");
		$path = "$path$name.ndz" . ($vers ? ":$vers" : "");
	    }
	    # XXX deleted versions always have a full path
	    elsif ($path =~ /^(.*):(\d+)\/([^\/]*)$/) {
		my ($iname,$oid,$ofile) = ($1,$2,$3);
		my $npath = "$iname,$oid/$ofile";
		print "$iname: version $vers changing path to '$npath' ";
		if ($update) {
		    if (!DBQueryWarn("UPDATE image_versions SET path='$npath'".
				     " WHERE imageid='$id' AND version='$vers'")) {
			print "[FAILED]";
		    } else {
			print "[FIXED]";
		    }
		}
		print "\n";

		my $old = "$iname:$oid";
		if (!exists($fixdirs{$old})) {
		    $fixdirs{$old}{'iname'} = $iname;
		    $fixdirs{$old}{'ndir'} = "$iname,$oid";
		}
	    }

	    #
	    # If path exists AND it is in the top-level images directory AND
	    # no one else references the path, then we could rename/delete it.
	    # But not even I am that anal...
	    #
	    if (-e "$path") {
		print STDERR "$iname: WARNING: version $vers full image '$path' exists\n";
	    }
	    if (defined($dpath) && -e "$dpath") {
		print STDERR "$iname: WARNING: version $vers delta image '$dpath' exists\n";
	    }
	}
    }

    #
    # Check for directories that had old-style names and convert them
    # to the new style (':' -> ',').
    #
    foreach my $odir (keys %fixdirs) {
	my $iname = $fixdirs{$odir}{'iname'};
	my $ndir = $fixdirs{$odir}{'ndir'};

	print STDERR "Processing old image dir '$odir' ...\n"
	    if ($debug);
	if (-d "$odir") {
	    print "$iname: renaming image directory to '$ndir' ";
	    if ($update) {
		if (!rename($odir, $ndir)) {
		    print "[FAILED]";
		} else {
		    print "[FIXED]";
		}
	    }
	    print "\n";
	}
    }
}

428 429 430 431 432 433
#
# Check all versions of a single image.
#
# In addition to putting all the versions in our list to check
# individually, perform some aggregate checks:
#
Mike Hibler's avatar
Mike Hibler committed
434 435
# - current version of the image must exist (there must be an image file)
#   this also implies that some version of an image exists
436
# - all versions from 0 to current must exist in DB
Mike Hibler's avatar
Mike Hibler committed
437 438
# - delta images must be preceded by a full version with no intermediate
#   deleted versions
439
#
Mike Hibler's avatar
Mike Hibler committed
440 441 442
sub getallversions($)
{
    my ($image) = @_;
443

Mike Hibler's avatar
Mike Hibler committed
444
    my $headvers = $image->version();
445
    my @iversions;
446
    $image->AllVersions(\@iversions, 1);
447 448 449 450 451 452 453 454

    # 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);
    }
Mike Hibler's avatar
Mike Hibler committed
455 456 457 458 459 460 461 462 463 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

    #
    # XXX make sure the imagedir exists for this project.
    # If not, the project may be inactive and the directory not exported
    # to boss.
    #
    my $idir = "$PROJROOT/" . $image->pid();
    if (!exists($imagedir{$idir})) {
	if (! -d "$idir") {
	    print STDERR $image->pid() . ": WARNING: project image directory does not exist (project may be inactive)!\n";
	    $imagedir{$idir} = 0;
	} else {
	    $imagedir{$idir} = 1;
	}
    }
    if (!$imagedir{$idir}) {
	print STDERR "$iname: WARNING: image directory does not exist, ignoring\n";
	return ();
    }

    # Skip certain images that do not conform to our rules
    if (!$image->isdataset() && (!$image->ezid() || $image->mfs())) {
	my $msg;
	if (!$image->ezid()) {
	    $msg = "legacy image";
	} else {
	    $msg = "MFS";
	}
	print STDERR "$iname: $msg, ignoring\n";
	return ();
    }

    my $ready = $iversions[0]->ready();
    my $released = $iversions[0]->released();
    my $lastvers = $iversions[0]->version();
    if ($lastvers != $headvers) {
	if ($lastvers != $headvers + 1) {
	    printf STDERR "$iname: WARNING head version $headvers more than one rev away from latest version $lastvers\n";
	} elsif ($ready && $released) {	
	    print STDERR "$iname: WARNING: head version $headvers does not correspond to latest ready/released version $lastvers\n";
	}
    }
497
    my $vers = 0;
Mike Hibler's avatar
Mike Hibler committed
498 499
    my $gotfull = 0;
    my $gotundeleted = 0;
500
    my $gotdeleted = 0;
501 502 503 504 505 506 507
    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) {
Mike Hibler's avatar
Mike Hibler committed
508
		print STDERR "$iname: WARNING: version $vers missing in DB\n";
509
	    } else {
Mike Hibler's avatar
Mike Hibler committed
510
		print STDERR "$iname: WARNING: versions $vers-$ivers missing in DB\n";
511 512 513 514
	    }
	    $vers = $imobj->version();
	}

Mike Hibler's avatar
Mike Hibler committed
515 516 517 518
	$ready = $imobj->ready();
	$released = $imobj->released();
	my $deleted = ($imobj->deleted() ? 1 : 0);

519 520 521 522
	if ($deleted) {
	    $gotdeleted++;
	}

Mike Hibler's avatar
Mike Hibler committed
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
	#
	# Head version should be:
	# - not deleted
	# - image file should exist
	# - ready and released
	#
	if ($vers == $headvers) {
	    if ($deleted) {
		print STDERR "$iname: WARNING: head version $vers deleted\n";
		# if the head is deleted, all previous versions should be too
		if ($gotundeleted) {
		    print STDERR "$iname: WARNING: not all previous versions delted\n";
		}
	    } elsif (!havefullimage($imobj) && !havedeltaimage($imobj)) {
		print STDERR "$iname: WARNING: head version $vers has no image file\n"
		    if ($warnonfixable);
	    } elsif (!$ready || !$released) {
		print STDERR "$iname: WARNING: head version $vers is not ready ($ready) or released ($released)!\n";
	    }
	}

	#
	# For non-deleted images:
	#
	# Inform them if the latest version is not ready or released.
	# This is not an error, just something to be aware of.
	#
	# Released images should always be ready.
	#
	elsif (!$deleted) {
	    if ($released) {
		if (!$ready) {
		    print STDERR "$iname: WARNING: released version $vers is not ready\n";
		}
	    }
	    elsif (!$ready) {
		if ($released) {
		    print STDERR "$iname: WARNING: released version $vers is not ready\n";
		}
		if ($vers == $lastvers) {
		    print STDERR "$iname: WARNING: latest version ($lastvers) is not ready\n";
		} else {
		    print STDERR "$iname: WARNING: version $vers is not ready and not latest version ($lastvers)\n";
		}
	    }
	    elsif (!$released) {
		if ($vers == $lastvers) {
		    print STDERR "$iname: WARNING: latest version ($lastvers) is not released\n";
		}
	    }
	}

	if ($deleted) {
	    # deleted image breaks any delta chain
	    $gotfull = 0;
	} else {
	    # keep track of non-deleted image prior to head image
	    $gotundeleted++;
	}
	
	if (havefullimage($imobj)) {
	    $gotfull = 1;
	} elsif (havedeltaimage($imobj)) {
	    if (!$gotfull) {
		print STDERR "$iname: WARNING: no full image precedes delta version $vers\n";
	    }
	} elsif (!$deleted && $vers != $headvers) {
	    print STDERR "$iname: WARNING: no image file for version $vers\n";
591 592 593 594 595
	}

	push @nimages, $fqname;
	$vers++;
    }
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616

    #
    # If all versions are deleted we can delete the entire image.
    #
    if ($dodeleted && $gotdeleted == int(@iversions)) {
	if ($update) {
	    print "$iname: all versions deleted, image can be deleted"
		if (!$quiet);
	    if ($image->Delete(0) == 0) {
		@nimages = ();
		print " [FIXED]\n"
		    if (!$quiet);
	    } else {
		print " [FAILED]\n"
		    if (!$quiet);
	    }
	} else {
	    print STDERR "$iname: WARNING: all versions are deleted\n";
	}
    }
    
Mike Hibler's avatar
Mike Hibler committed
617
    return @nimages;
618 619
}

Mike Hibler's avatar
Mike Hibler committed
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
#
# XXX we have all kinds of existential issues here, i.e., what is a
# real image? We would like to think that if it has a row in the DB
# and the image file exists, it is a real image and we can validate
# based on the properties of the image file.
#
# But if we are not root, we may not be able to access the image file
# of a valid image directly even though we have permission to use the
# image. If so, then there is very little we can validate and nothing
# we can fix.
#
# A valid image may also have one or both of a delta and full version.
# If we don't have access to the image file(s), how do we know which
# "exists"?
#
# A valid image version may also be deleted. If so, it should have the
# deleted date set and one or both of the delta/full size/hash image
# attributes may be set so that we could verifiably restore the image
# at some point. But if the deleted flag is not set and no image file
# is present (or we cannot access it), is it deleted or not?
#
# And to top it all off, the DB path may represent either the image
# file itself, or a directory that the image is in (if it ends with '/').
#
# Here is the strategy.
#
# If we are root or otherwise have read/search access to the directory
# of the image, then we should be able to stat any image files and thus
# the files provide "ground truth."
#
# If we do not have access to the files ($accessfs == 0) then all we
# can do is check the internal consistency of some DB fields.
#
653 654 655 656
sub doimage($)
{
    my ($pidimage) = @_;

657 658
    print STDERR "Checking image '$pidimage' ...\n"
	if ($debug);
659 660 661 662 663 664

    # XXX OSImage->Lookup blows up on old multi-partition images
    my $image = Image->Lookup($pidimage);
    if ($image && $image->ezid()) {
	$image = OSImage->Lookup($pidimage);
    }
665 666 667 668 669 670
    if (!defined($image)) {
	print STDERR "$pidimage: no such image\n";
	return 1;
    }
    my $imageid = $image->imageid();

671
    #
672
    # If the user is not an admin, must have perm on the image.
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
    #
    # 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();
Mike Hibler's avatar
Mike Hibler committed
688
	} elsif ($image->path() =~ /^(.*\/)[^\/]+$/) {
689 690
	    $statme = $1;
	}
Mike Hibler's avatar
Mike Hibler committed
691 692 693
	# directory should be a directory, readable and searchable
	if ($statme &&
	    -d "$statme" && -r "$statme" && -x "$statme") {
694 695 696 697 698 699 700
	    $accessfs = 1;
	} else {
	    print STDERR "$pidimage: WARNING: cannot access image directory '$statme', some validations disabled.\n";
	    $accessfs = 0;
	}
    } else {
	$accessfs = 1;
701 702
    }

703 704 705 706
    #
    # Determine whether the image has a delta or a full image file or both!
    #
    my ($path,$dpath,$hash,$dhash,$isdir);
707
    if ($image->IsDirPath()) {
708 709
	$isdir = 1;
	#
710 711 712 713 714 715
	# 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.
716
	#
717
	if (havefullimage($image)) {
718 719
	    $path = $image->FullImageFile();
	}
720
	if (havedeltaimage($image)) {
721 722
	    $dpath = $image->DeltaImageFile();
	}
723
	# XXX $image->hash() returns a ref to the internal 'HASH' hash.
724
	$hash = $image->hash();
725 726 727
	$dhash = $image->deltahash();
    } else {
	$isdir = 0;
728 729 730 731 732
	#
	# XXX backward compat I
	# Originally, isdelta signified that the path (always .ndz)
	# represented a delta image and not a full image.
	#
733 734 735
	if ($image->isdelta()) {
	    $dpath = $image->DeltaImageFile();
	    $dhash = $image->deltahash();
736 737 738 739 740 741 742 743 744 745 746 747 748 749
	}
	#
	# 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();
750
		$hash = $image->hash();
751 752 753 754
	    } elsif ($image->HaveDeltaImage()) {
		$dpath = $image->DeltaImageFile();
		$dhash = $image->deltahash();
	    }
755 756 757 758 759 760 761 762 763
	    #
	    # 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();
764
		$hash = $image->hash();
765
	    }
766
	}
767
    }
768 769
    $path = ""
	if (!defined($path));
770 771
    $dpath = ""
	if (!defined($dpath));
772 773
    $hash = ""
	if (!defined($hash));
774 775
    $dhash = ""
	if (!defined($dhash));
776 777 778 779 780 781

    my $size = $image->size();
    my $lbalo = $image->lba_low();
    my $lbahi = $image->lba_high();
    my $lbasize = $image->lba_size();
    my $relocatable = $image->relocatable();
782
    my $isdelta = $image->isdelta();
783
    my $dsize = $image->deltasize();
784 785 786 787 788
    my $stamp;
    $image->GetUpdate(\$stamp);
    $stamp = 0
	if (!defined($stamp));

Mike Hibler's avatar
Mike Hibler committed
789 790 791 792 793
    my $deleted = defined($image->deleted()) ? 1 : 0;
    if ($deleted && !$dodeleted) {
	return 0;
    }

794
    if ($showinfo) {
Mike Hibler's avatar
Mike Hibler committed
795 796 797
	if ($deleted) {
	    print "$pidimage: DELETED on $deleted\n";
	}
798
	print "$pidimage: mtime: $stamp\n";
799 800 801 802
	print "$pidimage: path: $path\n"
	    if ($path);
	print "$pidimage: deltapath: $dpath\n"
	    if ($dpath);
803
	if ($validate{"all"} || $validate{"size"}) {
804
	    my $chunks;
805
	    if ($size) {
806 807 808
		$chunks = int(($size + (1024*1024-1)) / (1024*1024));
		print "$pidimage: size: $size ($chunks chunks)\n";
	    }
809 810 811 812
	    if ($dsize) {
		$chunks = int(($dsize + (1024*1024-1)) / (1024*1024));
		print "$pidimage: deltasize: $dsize ($chunks chunks)\n";
	    }
813 814
	}
	if ($validate{"all"} || $validate{"hash"}) {
815 816 817 818
	    print "$pidimage: hash: $hash\n"
		if ($hash);
	    print "$pidimage: deltahash: $dhash\n"
		if ($dhash);
819 820 821 822 823 824
	}
	# XXX do sector range
	if ($validate{"all"} || $validate{"range"}) {
	    print "$pidimage: range: [$lbalo-$lbahi] (ssize: $lbasize), ".
		  "relocatable=$relocatable\n";
	}
825 826
	# XXX report on ancillary files
	my @afiles = ();
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
	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>");
842 843 844 845
	}
	if (@afiles > 0) {
	    print "$pidimage: files: ", join(", ", @afiles), "\n";
	}
846 847 848 849

	return 0;
    }

Mike Hibler's avatar
Mike Hibler committed
850 851 852 853 854 855
    #
    # Make sure the deleted status is correct. We must have access to
    # the files in order to really do this.
    #
    # Here are the possibilities:
    #
856 857
    # 0. If a path target exists but is zero length, remove it
    # 1. Database image_versions.deleted is null:
Mike Hibler's avatar
Mike Hibler committed
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
    #    A. If one or both of the path targets exist, all is well
    #    B. Otherwise, version should be marked as deleted
    # 2. Database image_versions.deleted is not null:
    #    A. If neither path target exists, all is well
    #    B. If a path target exists but indicates a deleted version
    #       (i.e., we are renaming rather than deleting files), all is well
    #
    if ($dodeleted) {
	if (!$accessfs) {
	    print STDERR "$pidimage: no access to image, ".
		"cannot determine deleted status\n";
	    return 1;
	}

	#
	# XXX for deleted, we are interested in the existance of the
	# image file, not just whether path/dpath is set or not.
	#
	my $epath = ($path && -e $path) ? 1 : 0;
	my $edpath = ($dpath && -e $dpath) ? 1 : 0;

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
	if ($epath) {
	    my $fsize = stat($path)->size;
	    if ($fsize == 0) {
		print "$pidimage: zero-length full image file"
		    if (!$quiet);
		if ($update) {
		    if (unlink($path)) {
			$epath = 0;
			print " [FIXED]"
			    if (!$quiet);
		    } else {
			print " [ could not unlink $path ]"
			    if (!$quiet);
		    }
		}
		print "\n"
		    if (!$quiet);
	    }
	}
	if ($edpath) {
	    my $fsize = stat($dpath)->size;
	    if ($fsize == 0) {
		print "$pidimage: zero-length delta image file"
		    if (!$quiet);
		if ($update) {
		    if (unlink($dpath)) {
			$edpath = 0;
			print " [FIXED]"
			    if (!$quiet);
		    } else {
			print " [ could not unlink $dpath ]"
			    if (!$quiet);
		    }
		}
		print "\n"
		    if (!$quiet);
	    }
	}

Mike Hibler's avatar
Mike Hibler committed
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 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
	if ($deleted) {
	    if (!$epath && !$edpath) {
		return 0;
	    }
	    # Check for renamed images.
	    if (($epath && $path =~ /,/) || ($edpath && $dpath =~ /,/)) {
		print STDERR "$pidimage: found renamed image\n";
		return 0;
	    }
	    # Check for !ready images.
	    if (!$image->ready()) {
		print STDERR "$pidimage: not-ready deleted image has image files\n";
	    }
	}
	if (!$deleted && ($epath || $edpath)) {
	    # Check for !ready images.
	    if (!$image->ready()) {
		print STDERR "$pidimage: not-ready image has image files\n";
	    }
	    return 0;
	}

	my $ifs = "";
	if (!$deleted) {
	    $ifs = "no";
	} elsif ($epath) {
	    if ($edpath) {
		$ifs = "Full/delta";
	    } else {
		$ifs = "Full";
	    }
	} else {
	    $ifs = "Delta";
	}
	print("$pidimage: deleted: DB says " . ($deleted ? "" : "not ") .
	      "deleted but $ifs image file(s) exist")
	    if (!$quiet);
	if ($update) {
	    if ($deleted) {
		my $suf = ",$imageid";
		my $failed = 0;

		# XXX scary, so let's just move the image files aside
		if ($epath && !rename($path, "$path$suf")) {
		    print " [ could not rename $path ]"
			if (!$quiet);
		    $failed++;
		}
		if ($edpath && !rename($dpath, "$dpath$suf")) {
		    print " [ could not rename $dpath ]"
			if (!$quiet);
		    $failed++;
		}
		print " [FIXED]"
		    if (!$quiet && !$failed);
	    } else {
		$image->MarkDeleted();
		print " [FIXED]"
		    if (!$quiet);
	    }
	}
	print "\n"
	    if (!$quiet);

	return 0;
    }

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 1019 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
    #
    # Check image directory permissions.
    #
    # The 'images' directory for a project should be 0775, owned by the
    # image creator and in the group of the project.
    #
    # The 'images' directory for a subgroup in a project should be 0775,
    # owned by the image creator and in the group of the particular project
    # subgroup.
    #
    # In the IMAGEDIRECTORIES world, the individual image subdirectories
    # should be 0775, owned by the image creator and in the group of the
    # containing directory.
    #
    # XXX right now, I only check the directory permissions and not the
    # user/groups. Too lazy.
    #
    if (($validate{"all"} || $validate{"perm"}) &&
	$accessfs && ($path || $dpath)) {
	my $ipid = $image->pid();
	my $igid = $image->gid();

	my $idir;
	if ($ipid eq $igid) {
	    $idir = "/proj/$ipid/images/";
	} else {
	    $idir = "/groups/$ipid/$igid/images/";
	}

	# Just check the project/group main image dir once
	my $pidgid = "$ipid/$igid";
	if (!exists($piddirperms{$pidgid})) {
	    $piddirperms{$pidgid} = 1;

	    if (! -d $idir) {
		print STDERR "$pidimage: mode: image dir '$idir' does not exist?!\n";
	    } else {
		my $mode = (stat($idir)->mode & 0777);
		if ($mode != 0770) {
		    my $mstr = sprintf "0%o", $mode;
		    print("$pidimage: mode: '$idir' mode $mstr != 0770\n")
			if (!$update || !$quiet);
		    if ($update) {
			print("$pidimage: mode: ")
			    if (!$quiet);
			if (chmod(0770, $idir)) {
			    print "[FIXED]\n"
				if (!$quiet);
			} else {
			    print "[FAILED]\n"
				if (!$quiet);
			}
		    }
		}
	    }
	}

	# Check image sub directory
	if ($image->IsDirPath()) {
	    $idir = $image->path();
	    if (!exists($imagedirperms{$idir})) {
		$imagedirperms{$idir} = 1;
		if (! -d $idir) {
		    print STDERR "$pidimage: mode: image subdir '$idir' does not exist?!\n";
		} else {
		    my $mode = (stat($idir)->mode & 0777);
		    if ($mode != 0775) {
			my $mstr = sprintf "0%o", $mode;
			print("$pidimage: mode: '$idir' mode $mstr != 0775\n")
			    if (!$update || !$quiet);
			if ($update) {
			    print("$pidimage: mode: ")
				if (!$quiet);
			    if (chmod(0775, $idir)) {
				print "[FIXED]\n"
				    if (!$quiet);
			    } else {
				print "[FAILED]\n"
				    if (!$quiet);
			    }
			}
		    }
		}
	    }
	}
    }

1072
    #
1073
    # The image files have to exist.
1074
    #
1075
    if (!$path && !$dpath) {
1076
	print STDERR "$pidimage: no image file found or cannot access\n";
1077 1078
	return 1;
    }
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
    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;
1101
	}
1102
    }
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
    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;
	}
1125 1126
    }

1127 1128 1129
    #
    # Take care of one-off fix to hash and sig files
    #
1130
    if ($fixit) {
1131 1132 1133 1134
	if (!$accessfs) {
	    print STDERR "$pidimage: hash: cannot access hash/sig files\n";
	    return 1;
	}
1135 1136 1137
	if ($path) {
	    print "$pidimage: fixing hash file\n";
	    if ($hash eq "") {
1138
		$hash = hashit($path);
1139 1140 1141
		if ($?) {
		    print("$pidimage: hash: could not generate SHA1 hash of '$path'\n");
		    return 1;
1142
		} else {
1143 1144 1145 1146 1147 1148 1149 1150 1151
		    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");
1152 1153 1154
		    return 1;
		}
	    }
1155 1156 1157 1158
	    makehashfile($pidimage, $path, $hash, $fuid);

	    if ($dosig && checksigfile($pidimage, $path, 0)) {
		makesigfile($pidimage, $path, $fuid);
1159 1160
	    }
	}
1161 1162 1163
	if ($dpath) {
	    print "$pidimage: fixing delta hash file\n";
	    if ($dhash eq "") {
1164
		$dhash = hashit($dpath);
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
		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;
		}
	    }
1205
	}
1206 1207 1208
	return 0;
    }

1209 1210 1211 1212 1213 1214
    my $rv = 0;
    my $changed = 0;

    #
    # Check/fix mtime.
    #
Mike Hibler's avatar
Mike Hibler committed
1215 1216
    if ((!$path || abs($stamp - $ftime)) < 2 &&
	(!$dpath || abs($stamp - $dftime)) < 2) {
1217 1218 1219 1220 1221 1222
	if ($fastupdate) {
	    print STDERR "$pidimage: skipping due to time stamp\n"
		if ($debug);
	    return 0;
	}
    } else {
Mike Hibler's avatar
Mike Hibler committed
1223
	if ($path && abs($stamp - $ftime) > 1) {
1224 1225 1226 1227 1228 1229
	    print("$pidimage: mtime: DB timestamp ($stamp) != mtime ($ftime)\n")
		if (!$update || !$quiet);
	    if ($update) {
		$changed = 1;
	    }
	}
Mike Hibler's avatar
Mike Hibler committed
1230
	if ($dpath && abs($stamp - $dftime) > 1) {
1231 1232 1233 1234 1235
	    print("$pidimage: mtime: DB timestamp ($stamp) != delta mtime ($dftime)\n")
		if (!$update || !$quiet);
	    if ($update) {
		$changed = 1;
	    }
1236 1237 1238 1239 1240 1241 1242
	}
    }

    #
    # Check/fix file size.
    #
    if ($validate{"all"} || $validate{"size"}) {
1243 1244 1245
	if ($path) {
	    if ($fsize != $size) {
		print("$pidimage: size: DB size ($size) != file size ($fsize)\n")
1246 1247
		    if (!$update || !$quiet);
		if ($update) {
1248
		    print("$pidimage: size: ")
1249
			if (!$quiet);
1250
		    if ($image->SetSize($fsize) == 0) {
1251 1252 1253 1254 1255 1256 1257 1258
			$changed = 1;
			print "[FIXED]\n"
			    if (!$quiet);
		    } else {
			print "[FAILED]\n"
			    if (!$quiet);
			$rv = 1;
		    }
1259
		} else {
1260 1261 1262 1263
		    $rv = 1;
		}
	    }
	    # XXX backward compat, only one of size/deltasize should be set
1264
	    if ($update && !$dpath) {
1265 1266
		print("$pidimage: size: no delta image, clearing deltasize\n")
		    if (!$quiet && $dsize);
1267
		$image->SetDeltaSize(0);
1268
	    }
1269 1270 1271 1272
	}
	if ($dpath) {
	    if ($dfsize != $dsize) {
		print("$pidimage: size: DB deltasize ($dsize) != file size ($dfsize)\n")
1273 1274
		    if (!$update || !$quiet);
		if ($update) {
1275
		    print("$pidimage: dsize: ")
1276
			if (!$quiet);
1277
		    if ($image->SetDeltaSize($dfsize) == 0) {
1278 1279 1280 1281 1282 1283 1284 1285 1286
			$changed = 1;
			print "[FIXED]\n"
			    if (!$quiet);
		    } else {
			print "[FAILED]\n"
			    if (!$quiet);
			$rv = 1;
		    }
		} else {
1287 1288
		    $rv = 1;
		}
1289 1290
	    }
	    # XXX backward compat, only one of size/deltasize should be set
1291
	    if ($update && !$path) {
1292 1293
		print("$pidimage: size: no full image, clearing size\n")
		    if (!$quiet && $size);
1294
		$image->SetSize(0);
1295 1296
	    }
	}
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306

	#
	# 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);
	}
1307 1308 1309 1310 1311 1312 1313
    }

    #
    # Check/fix hash.
    #
    if ($validate{"all"} || $validate{"hash"}) {
	my $filehash = $newhash;
1314 1315
	if ($path) {
	    if (!defined($filehash)) {
1316
		$filehash = hashit($path);
1317 1318
		if ($?) {
		    print("$pidimage: hash: could not generate SHA1 hash of '$path'\n");
1319
		    $filehash = "";
1320 1321 1322 1323 1324 1325 1326 1327
		    $rv = 1;
		} else {
		    if ($filehash =~ /^SHA1.*= ([\da-fA-F]+)$/) {
			$filehash = lc($1);
		    } else {
			print("$pidimage: hash: could not parse sha1 hash: '$filehash'\n");
			$filehash = "";
		    }
1328 1329 1330 1331 1332 1333 1334 1335
		}
	    }
	    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);
1336
		    if ($image->SetHash($filehash) == 0) {
1337
			makehashfile($pidimage, $path, $filehash, $fuid);
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
			$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) {
1352
		    makehashfile($pidimage, $path, $filehash, $fuid);
1353 1354
		}
	    }
1355 1356

	    if ($update && !$dpath) {
1357 1358
		print("$pidimage: hash: no delta image, clearing deltahash\n")
		    if (!$quiet && $dhash);
1359
		$image->SetDeltaHash(undef);
1360
	    }
1361
	    $filehash = undef;
1362 1363 1364 1365
	}

	if ($dpath) {
	    if (!defined($filehash)) {
1366
		$filehash = hashit($dpath);
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
		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) {
1407 1408
		print("$pidimage: hash: no full image, clearing hash\n")
		    if (!$quiet && $hash);
1409
		$image->SetHash(undef);
1410
	    }
1411 1412 1413 1414 1415
	}
    }

    #
    # Check/fix sector range.
1416
    # We can only do this if we have a full image.
1417
    #
1418
    if ($path && ($validate{"all"} || $validate{"range"})) {
1419 1420
	my ($lo,$hi,$ssize) = (-1,0,0);
	my $isreloc = $relocatable;
1421
	my $out = `$IMAGEINFO -r $pidimage 2>&1`;
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
	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;
		}
	    }
	}
    }

    #
1486 1487
    # Set update time to match mtime of image.
    # If there is both a full and delta image, set DB to full image time.
1488 1489
    #
    if ($changed) {
1490 1491
	my $mtime = ($path ? $ftime : $dftime);

1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
	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;
	}
1509 1510 1511 1512 1513 1514 1515 1516

	#
	# 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";
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
	    } else {
		$dftime = $ftime;
	    }
	}
    }

    #
    # Make sure hash and signature file times match the image.
    #
    if ($path) {
	my $hfile = $image->FullImageSHA1File();
	if (-e $hfile) {
	    my $hftime = stat($hfile)->mtime;
	    if ($hftime != $ftime) {
		if ($update) {
		    print "$pidimage: SHA1 mtime: "
			if (!$quiet);
		    if (system("touch -r $path $hfile >/dev/null 2>&1")) {
			print "[FAILED]\n"
			    if (!$quiet);
		    } else {
			print "[FIXED]\n"
			    if (!$quiet);
		    }
		} else {
		    print "$pidimage: image mtime ($ftime) != SHA1 mtime ($hftime)\n"
			if (!$quiet);
		}
	    }
	}
	my $sfile = $image->FullImageSigFile();
	if (-e $sfile) {
	    my $sftime = stat($sfile)->mtime;
	    if ($sftime != $ftime) {
		if ($update) {
		    print "$pidimage: SIG mtime: "
			if (!$quiet);
		    if (system("touch -r $path $sfile >/dev/null 2>&1")) {
			print "[FAILED]\n"
			    if (!$quiet);
		    } else {
			print "[FIXED]\n"
			    if (!$quiet);
		    }
		} else {
		    print "$pidimage: image mtime ($ftime) != sig mtime ($sftime)\n"
			if (!$quiet);
		}
	    }
	}
    }
    if ($dpath) {
	my $hfile = $image->DeltaImageSHA1File();
	if (-e $hfile) {
	    my $hftime = stat($hfile)->mtime;
	    if ($hftime != $dftime) {
		if ($update) {
		    print "$pidimage: delta SHA1 mtime: "
			if (!$quiet);
		    if (system("touch -r $dpath $hfile >/dev/null 2>&1")) {
			print "[FAILED]\n"
			    if (!$quiet);
		    } else {
			print "[FIXED]\n"
			    if (!$quiet);
		    }
		} else {
		    print "$pidimage: delta image mtime ($dftime) != SHA1 mtime ($hftime)\n"
			if (!$quiet);
		}
	    }
	}
	my $sfile = $image->DeltaImageSigFile();
	if (-e $sfile) {
	    my $sftime = stat($sfile)->mtime;
	    if ($sftime != $dftime) {
		if ($update) {
		    print "$pidimage: delta SIG mtime: "
			if (!$quiet);
		    if (system("touch -r $dpath $sfile >/dev/null 2>&1")) {
			print "[FAILED]\n"
			    if (!$quiet);
		    } else {
			print "[FIXED]\n"
			    if (!$quiet);
		    }
		} else {
		    print "$pidimage: delta image mtime ($dftime) != sig mtime ($sftime)\n"
			if (!$quiet);
		}
1607 1608
	    }
	}
1609 1610
    }

1611 1612 1613 1614
    #
    # Check/fix signature file.
    #
    if ($dosig) {
1615 1616 1617 1618
	if (!$accessfs) {
	    print STDERR "$pidimage: sig: cannot access signature file\n";
	    return 1;
	}
1619 1620 1621 1622 1623 1624
	if ($path) {
	    if (checksigfile($pidimage, $path, 0)) {
		print("$pidimage: sig: image does not match signature\n")
		    if (!$update || !$quiet);
		if ($update) {
		    print("$pidimage: sig: ")
1625
			if (!$quiet);
1626 1627 1628 1629 1630 1631 1632 1633
		    if (makesigfile($pidimage, $path, $fuid) == 0) {
			print "[FIXED]\n"
			    if (!$quiet);
		    } else {
			print "[FAILED]\n"
			    if (!$quiet);
			$rv = 1;
		    }
1634 1635 1636
		} else {
		    $rv = 1;
		}
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
	    }
	}
	#
	# 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";
1671
	    } else {
1672 1673
		print STDERR
		    "$pidimage: dsig: no signature file for '$dpath'!\n";
1674 1675 1676 1677 1678
		$rv = 1;
	    }
	}
    }

1679 1680 1681 1682 1683 1684 1685 1686
    return $rv;
}

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

1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
#
# Compute the SHA1 of the indicated file.
# To optimize, if it is an NFS file, ssh over to the server and do
# the computation rather than blasting the control network.
#
sub hashit($)
{
    my ($file) = @_;
    my $hash;

1697
    if ($UID == 0 && $file =~ /^\/(proj|groups)/) {
1698 1699 1700 1701 1702 1703 1704
	$hash = `$SSH $SHA1 $file`;
    } else {
	$hash = `$SHA1 $file`;
    }
    return $? ? undef : $hash;
}

1705
# Return 0 if action is successful
1706
sub checksigfile($$$)
1707
{
1708
    my ($pidimage,$imagepath,$isdelta) = @_;
1709 1710
    my $sigfile = "$imagepath.sig";

1711 1712
    print STDERR "$pidimage: sig: checking signature of '$imagepath' ...\n"
	if ($debug);
1713 1714 1715 1716 1717 1718

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

1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
    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";
	    }
	}
1730

1731 1732 1733 1734
	print STDERR
	    "$pidimage: WARNING: no signature file for $imagepath\n";
	return 1;
    }
1735 1736 1737 1738 1739 1740 1741 1742 1743

    # 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;
    }

1744 1745 1746 1747 1748
    if (system("$IMAGEHASH -SX $imagepath")) {
	print STDERR
	    "$pidimage: WARNING: $imagepath does not match signature\n";
	return 1;
    }
1749 1750 1751

    print STDERR "$pidimage: sig: signature OK\n"
	if ($debug);
1752 1753 1754 1755
    return 0;
}

# Return 0 if action is successful
1756
sub makesigfile($$$)
1757
{
1758
    my ($pidimage,$imagepath,$fuid) = @_;
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
    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);
	}
    }

1772 1773 1774 1775 1776 1777 1778
    unlink($sigfile);
    if (system("$IMAGEHASH -cXq $imagepath")) {
	print STDERR
	    "$pidimage: WARNING: could not create signature for $imagepath\n";
	unlink($sigfile);
	return 1;
    }
1779 1780 1781 1782
    if (defined($fuid) && system("chown $fuid $sigfile >/dev/null 2>&1")) {
	print STDERR
	    "$pidimage: WARNING: could not chown $sigfile to $fuid\n";
    }
1783

1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
    return 0;
}

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

    if (!unlink($sigfile)) {
	return 1;
1795 1796
    }

1797 1798 1799 1800 1801 1802
    return 0;
}

#
# XXX Over time, we have used two different conventions for sha1 files.
#
1803
# Old format is <image>.sha1. New format is <image>.ndz.sha1, possibly
1804 1805 1806 1807 1808 1809 1810 1811 1812
# 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";
1813 1814
    unlink($hashfile);
    if (open(HASH, ">$hashfile")) {
1815 1816
	# XXX recreate the sha1 output format for compatibility
	print HASH "SHA1 ($imagepath) = $hash\n";
1817
	close($hashfile);
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
	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");
1840
	}
1841 1842 1843
    }
}

1844
sub removehashfile($$)
1845
{
1846
    my ($pidimage,$imagepath) = @_;
1847

1848 1849 1850 1851
    my $hashfile = "$imagepath.sha1";
    unlink($hashfile);

    # Remove old format file too
1852
    if ($imagepath =~ /(.*)\.ndz$/) {
1853 1854
	my $oldhashfile = "$1.sha1";
	unlink($oldhashfile);
1855 1856 1857
    }
}

1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
#
# 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;
}

1895 1896 1897 1898 1899 1900 1901 1902
sub fatal($)
{
    my ($mesg) = @_;

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