All new accounts created on Gitlab now require administrator approval. If you invite any collaborators, please let Flux staff know so they can approve the accounts.

imagezip.c 65.3 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1 2
/*
 * EMULAB-COPYRIGHT
3
 * Copyright (c) 2000-2012 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
4 5 6
 * All rights reserved.
 */

7 8
/*
 * An image zipper.
Mike Hibler's avatar
all:  
Mike Hibler committed
9 10
 *
 * TODO:
11 12 13
 *	Multithread so that we can be reading ahead on the input device
 *	and overlapping IO with compression.  Maybe a third thread for
 *	doing output.
14
 */
15 16 17
#ifdef WITH_CRYPTO
#include <openssl/evp.h>
#include <openssl/sha.h>
18
#include <openssl/rsa.h>
19
#include <openssl/rand.h>
20 21 22
#ifdef SIGN_CHECKSUM
#include <openssl/err.h>
#endif
23
#endif
24
#include <ctype.h>
25
#include <err.h>
Mac Newbold's avatar
Mac Newbold committed
26
#include <fcntl.h>
27
#if !defined(__UCLIBC__)
28
#include <fstab.h>
29
#endif
30 31
#include <stdio.h>
#include <stdlib.h>
Mac Newbold's avatar
Mac Newbold committed
32
#include <unistd.h>
Mike Hibler's avatar
all:  
Mike Hibler committed
33
#include <string.h>
34
#include <assert.h>
Mike Hibler's avatar
all:  
Mike Hibler committed
35
#include <errno.h>
36 37 38
#include <sys/param.h>
#include <sys/time.h>
#include <sys/stat.h>
Mac Newbold's avatar
Mac Newbold committed
39
#include <zlib.h>
40

41
#include "imagehdr.h"
Mike Hibler's avatar
Mike Hibler committed
42 43
#include "sliceinfo.h"
#include "global.h"
44
#include "checksum.h"
45

46 47
/* XXX this is a hack right now */
#define USE_HACKSORT 0
Mac Newbold's avatar
Mac Newbold committed
48

49
#define min(a,b) ((a) <= (b) ? (a) : (b))
50

51 52 53 54 55 56 57 58 59 60 61 62
char	*infilename;
int	infd, outfd, outcanseek;
int	secsize	  = 512;	/* XXX bytes. */
int	debug	  = 0;
int	dots	  = 0;
int	info	  = 0;
int	version	  = 0;
int	slicemode = 0;
int	maxmode	  = 0;
int	slice	  = 0;
int	level	  = 4;
long	dev_bsize = 1;
63
uint32_t compat   = 0;
64
int	frangesize= 64;	/* 32k */
65
int	zerofrange= 0;
66 67 68 69 70 71 72
int	forcereads= 0;
int	badsectors= 0;
int	retrywrites= 1;
int	dorelocs  = 1;
int	metaoptimize = 0;
int	filemode  = 0;
int	do_encrypt = 0;
73
int	cipher = ENC_NONE;
74
int	do_checksum = 0;
75
int	csumalg = CSUM_NONE;
76
off_t	datawritten;
77
partmap_t ignore, forceraw;
Mike Hibler's avatar
Mike Hibler committed
78
static	int got_imageid;
79
static unsigned char imageid[UUID_LENGTH];
80

81
#ifdef WITH_HASH
82 83 84 85
char	*hashfile;
#endif

#ifdef WITH_CRYPTO
86
#ifdef SIGN_CHECKSUM
87
RSA		*sig_key = NULL;	/* signing key */
88 89
static void output_public_key(char *, RSA *);
#endif
90
unsigned char	*enc_key = NULL;	/* encryption key */
91
static void output_encrypt_key(char *, unsigned char *, int);
92
#endif
93
static void output_uuid(char *, char *);
Mike Hibler's avatar
all:  
Mike Hibler committed
94

95 96 97 98
#define HDRUSED(reg, rel) \
    (sizeof(blockhdr_t) + \
    (reg) * sizeof(struct region) + (rel) * sizeof(struct blockreloc))

99 100 101
/*
 * We want to be able to compress slices by themselves, so we need
 * to know where the slice starts when reading the input file for
102
 * compression.
103 104 105
 *
 * These numbers are in sectors.
 */
106
extern unsigned long getdisksize(int fd);
107 108
unsigned long inputminsec	= 0;
unsigned long inputmaxsec	= 0;	/* 0 means the entire input image */
109 110

/*
111
 * A list of data ranges.
112
 */
113
struct range {
114 115 116 117
	uint32_t	start;		/* In sectors */
	uint32_t	size;		/* In sectors */
	void		*data;
	struct range	*next;
118
};
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
struct range	*ranges, *skips, *fixups;
int		numranges, numskips;
struct blockreloc	*relocs;
int			numregions, numrelocs;

void	dumpskips(int verbose);
static void	sortrange(struct range **head, int domerge,
		  int (*rangecmp)(struct range *, struct range *));
int	mergeskips(int verbose);
int	mergeranges(struct range *head);
void	makeranges(void);
void	freeranges(struct range *);
void	dumpranges(int verbose);
void	dumpfixups(int verbose);
void	addvalid(uint32_t start, uint32_t size);
void	addreloc(off_t offset, off_t size, int reloctype);
Mike Hibler's avatar
Mike Hibler committed
135
static int cmpfixups(struct range *r1, struct range *r2);
136
static int read_doslabel(int infd, int lsect, int pstart,
137
			 struct doslabel *label);
138 139

/* Forward decls */
140 141 142 143
int	read_image(u_int32_t start, int pstart, u_int32_t extstart);
int	read_raw(void);
int	compress_image(void);
void	usage(void);
144

145 146
#ifdef WITH_HASH
struct range *hashmap_compute_delta(struct range *, char *, int, u_int32_t);
147
void	report_hash_stats(int pnum);
148 149
#endif

Mike Hibler's avatar
Mike Hibler committed
150 151 152
static SLICEMAP_PROCESS_PROTO(read_slice);

struct slicemap fsmap[] = {
153
	{ DOSPTYP_UNUSED,	"UNUSED",	0 },
Mike Hibler's avatar
Mike Hibler committed
154
#ifdef WITH_FFS
155 156
	{ DOSPTYP_386BSD,	"FreeBSD FFS",	read_bsdslice },
	{ DOSPTYP_OPENBSD,	"OpenBSD FFS",	read_bsdslice },
Mike Hibler's avatar
Mike Hibler committed
157 158
#endif
#ifdef WITH_EXTFS
159 160
	{ DOSPTYP_LINUX,	"Linux EXT",	read_linuxslice },
	{ DOSPTYP_LINSWP,	"Linux SWP",	read_linuxswap },
Mike Hibler's avatar
Mike Hibler committed
161 162
#endif
#ifdef WITH_NTFS
163
	{ DOSPTYP_NTFS,		"NTFS",		read_ntfsslice },
Mike Hibler's avatar
Mike Hibler committed
164 165
#endif
#ifdef WITH_FAT
166 167 168 169 170 171
	{ DOSPTYP_FAT12,	"FAT12",	read_fatslice },
	{ DOSPTYP_FAT16,	"FAT16",	read_fatslice },
	{ DOSPTYP_FAT16L,	"FAT16L",	read_fatslice },
	{ DOSPTYP_FAT16L_LBA,	"FAT16 LBA",	read_fatslice },
	{ DOSPTYP_FAT32,	"FAT32",	read_fatslice },
	{ DOSPTYP_FAT32_LBA,	"FAT32 LBA",	read_fatslice },
Mike Hibler's avatar
Mike Hibler committed
172
#endif
173 174 175
	{ DOSPTYP_EXT,		"DOSEXT",	0 },
	{ DOSPTYP_EXT_LBA,	"DOSEXT LBA",	0 },
	{ -1,			"",		0 },
Mike Hibler's avatar
Mike Hibler committed
176 177
};

178
static __inline struct slicemap *
Mike Hibler's avatar
Mike Hibler committed
179 180
getslicemap(int stype)
{
181
	struct slicemap *smap;
Mike Hibler's avatar
Mike Hibler committed
182

183 184 185 186
	for (smap = fsmap; smap->type != -1; smap++)
		if (smap->type == stype)
			return smap;
	return 0;
Mike Hibler's avatar
Mike Hibler committed
187
}
188

189 190
#define READ_RETRIES	1
#define WRITE_RETRIES	10
191 192 193 194

ssize_t
slowread(int fd, void *buf, size_t nbytes, off_t startoffset)
{
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
	int cc, i, count;

	fprintf(stderr, "read failed: will retry by sector %d more times\n",
		READ_RETRIES);

	count = 0;
	for (i = 0; i < READ_RETRIES; i++) {
		if (lseek(fd, startoffset, SEEK_SET) < 0) {
			perror("devread: seeking to set file ptr");
			exit(1);
		}
		while (nbytes > 0) {
			cc = read(fd, buf, nbytes);
			if (cc == 0) {
				nbytes = 0;
				continue;
			}
			if (cc > 0) {
				nbytes -= cc;
				buf     = (void *)((char *)buf + cc);
				count  += cc;
				continue;
			}

			nbytes += count;
			buf     = (void *)((char *)buf - count);
			count   = 0;
			break;
		}
		if (nbytes == 0)
			break;
	}
	return count;
228
}
229

Mike Hibler's avatar
Mike Hibler committed
230 231 232 233 234
/*
 * Assert the hell out of it...
 */
off_t
devlseek(int fd, off_t off, int whence)
235
{
236 237 238 239 240 241 242
	off_t noff;
	assert((off & (DEV_BSIZE-1)) == 0);
	noff = lseek(fd, off, whence);
	if (!filemode) {
		assert(noff == (off_t)-1 || (noff & (DEV_BSIZE-1)) == 0);
	}
	return noff;
243 244
}

245 246 247 248 249 250
/*
 * Wrap up read in a retry mechanism to persist in the face of IO errors,
 * even faking data if requested.
 */
ssize_t
devread(int fd, void *buf, size_t nbytes)
251
{
252 253 254
	int		cc, count;
	off_t		startoffset;
	size_t		onbytes;
255 256

#ifndef linux
257
	assert((nbytes & (DEV_BSIZE-1)) == 0);
258
#endif
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
	cc = read(fd, buf, nbytes);
	if (!forcereads || cc >= 0)
		return cc;

	/*
	 * Got an error reading the range.
	 * Retry one sector at a time, replacing any bad sectors with
	 * zeroed data.
	 */
	if ((startoffset = lseek(fd, (off_t) 0, SEEK_CUR)) < 0) {
		perror("devread: seeking to get input file ptr");
		exit(1);
	}
	assert((startoffset & (DEV_BSIZE-1)) == 0);

	onbytes = nbytes;
	while (nbytes > 0) {
		if (nbytes > DEV_BSIZE)
			count = DEV_BSIZE;
		else
			count = nbytes;
		cc = slowread(fd, buf, count, startoffset);
		if (cc != count) {
			fprintf(stderr, "devread: read failed on sector %u, "
				"returning zeros\n",
				bytestosec(startoffset));
			if (cc < 0)
				cc = 0;
			memset(buf, 0, count-cc);
			badsectors++;
			cc = count;
		}
		nbytes -= cc;
		buf = (void *)((char *)buf + cc);
		startoffset += cc;
	}
	return onbytes;
296
}
297

298 299
/*
 * Wrap up write in a retry mechanism to protect against transient NFS
300
 * errors causing a fatal error.
301 302
 */
ssize_t
303
devwrite(int fd, const void *buf, size_t nbytes)
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
	int		cc, i, count = 0;
	off_t		startoffset = 0;

	if (retrywrites && outcanseek &&
	    ((startoffset = lseek(fd, (off_t) 0, SEEK_CUR)) < 0)) {
		perror("devwrite: seeking to get output file ptr");
		exit(1);
	}

	for (i = 0; i < WRITE_RETRIES; i++) {
		while (nbytes) {
			cc = write(fd, buf, nbytes);

			if (cc > 0) {
				nbytes -= cc;
				buf     = (void *)((char *)buf + cc);
				count  += cc;
				continue;
			}

			if (!retrywrites)
				return cc;

			if (i == 0)
				perror("write error: will retry");

			sleep(1);
			nbytes += count;
			buf     = (void *)((char *)buf - count);
			count   = 0;
			goto again;
		}
		if (retrywrites && fsync(fd) < 0) {
			perror("fsync error: will retry");
			sleep(1);
			nbytes += count;
			buf     = (void *)((char *)buf - count);
			count   = 0;
			goto again;
		}
		datawritten += count;
		return count;
	again:
		if (lseek(fd, startoffset, SEEK_SET) < 0) {
			perror("devwrite: seeking to set file ptr");
			exit(1);
		}
	}
	perror("write error: busted for too long");
	fflush(stderr);
	exit(1);
356 357
}

358 359 360
static int
setpartition(partmap_t map, char *str)
{
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
	int dospart;
	char bsdpart;

	if (isdigit(str[1])) {
		bsdpart = str[2];
		str[2] = '\0';
	} else {
		bsdpart = str[1];
		str[1] = '\0';
	}
	dospart = atoi(str);
	if (dospart < 1 || dospart > MAXSLICES)
		return EINVAL;

	/* common case: apply to complete DOS partition */
	if (bsdpart == '\0') {
		map[dospart-1] = ~0;
		return 0;
	}

	if (bsdpart < 'a' || bsdpart > 'p')
		return EINVAL;

	map[dospart-1] |= (1 << (bsdpart - 'a'));
	return 0;
386
}
Mac Newbold's avatar
Mac Newbold committed
387 388

int
389
main(int argc, char *argv[])
Mac Newbold's avatar
Mac Newbold committed
390
{
391 392 393 394 395 396 397 398 399 400
	int	ch, rval;
	char	*outfilename = 0;
	int	rawmode	  = 0;
	int	slicetype = 0;
	struct timeval sstamp;
	extern char build_info[];

	memset(imageid, UUID_LENGTH, '\0');

	gettimeofday(&sstamp, 0);
401
	while ((ch = getopt(argc, argv, "vlbnNdihrs:c:z:ofI:13F:DR:S:XH:Me:k:u:a:Z")) != -1)
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 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
		switch(ch) {
		case 'v':
			version++;
			break;
		case 'i':
			info++;
			debug++;
			break;
		case 'D':
			retrywrites = 0;
			break;
		case 'd':
			debug++;
			break;
		case 'l':
			slicetype = DOSPTYP_LINUX;
			break;
		case 'b':
			slicetype = DOSPTYP_386BSD;
			break;
		case 'N':
			dorelocs = 0;
			break;
		case 'n':
			slicetype = DOSPTYP_NTFS;
			break;
		case 'o':
			dots++;
			break;
		case 'r':
			rawmode++;
			break;
		case 'S':
			slicetype = atoi(optarg);
			break;
		case 's':
			slicemode = 1;
			slice = atoi(optarg);
			break;
		case 'z':
			level = atoi(optarg);
			if (level < 0 || level > 9)
				usage();
			break;
		case 'c':
			maxmode     = 1;
			inputmaxsec = atoi(optarg);
			break;
		case 'I':
			if (setpartition(ignore, optarg))
				usage();
			break;
		case 'R':
			if (setpartition(forceraw, optarg))
				usage();
			break;
		case '1':
459 460 461 462
			compat = COMPRESSED_V1;
			break;
		case '3':
			compat = COMPRESSED_V3;
463 464 465 466 467 468
			break;
		case 'F':
			frangesize = atoi(optarg);
			if (frangesize < 0)
				usage();
			break;
469 470 471
		case 'Z':
			zerofrange = 1;
			break;
472 473 474 475
		case 'X':
			forcereads++;
			break;
		case 'H':
476
#ifdef WITH_HASH
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
			hashfile = optarg;
#else
			fprintf(stderr, "'H' option not supported\n");
			usage();
#endif
			break;
		case 'M':
			metaoptimize++;
			break;
		case 'f':
			filemode++;
			rawmode++;
			break;
		case 'a':
#ifdef WITH_CRYPTO
492
			/* Authentication (checksum) hash algorithm */
493 494 495 496 497
			if (strcmp(optarg, "SHA1") == 0) {
				csumalg = CSUM_SHA1;
			}
			else {
				fprintf(stderr, "Only know \"SHA1\"\n");
498 499
				usage();
			}
500
			do_checksum++;
501 502 503
#ifdef SIGN_CHECKSUM
			csumalg |= CSUM_SIGNED;
#else
504 505
			fprintf(stderr, "WARNING: checksum is not signed\n");
#endif
506
#else
507 508
			fprintf(stderr, "'a' option not supported\n");
			usage();
509
#endif
510 511 512
			break;

		case 'e':
513
#ifdef WITH_CRYPTO
514
			/* Encryption cipher */
515 516 517 518
			if (strcmp(optarg, "bf_cbc") == 0) {
				cipher = ENC_BLOWFISH_CBC;
			}
			else {
519 520 521 522 523
				fprintf(stderr,
					"Only know \"bf_cbc\" (blowfish CBC)\n");
				usage();
			}
			do_encrypt++;
524
#else
525 526
			fprintf(stderr, "'e' option not supported\n");
			usage();
527
#endif
528 529 530 531 532 533 534 535
			break;
		case 'k':
#ifdef WITH_CRYPTO
			/* Encryption key file */
			enc_key = calloc(1, ENC_MAX_KEYLEN);
			if (enc_key == NULL ||
			    !encrypt_readkey(optarg, enc_key, ENC_MAX_KEYLEN))
				usage();
536 537 538
			/* XXX can you intuit the cipher from the key? */
			if (cipher == ENC_NONE)
				cipher = ENC_BLOWFISH_CBC;
539 540 541 542 543 544 545
#else
			fprintf(stderr, "'k' option not supported\n");
			usage();
#endif
			break;
		case 'u':
			/* UUID for image id. */
546
			if (!hexstr_to_mem(imageid, optarg, UUID_LENGTH))
547
				usage();
548
			got_imageid = 1;
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
			break;
		case 'h':
		case '?':
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (version || debug) {
		fprintf(stderr, "%s\n", build_info);
		if (version) {
			fprintf(stderr, "Supports");
			for (ch = 1; fsmap[ch].type != -1; ch++)
				if (fsmap[ch].process != 0)
					fprintf(stderr, "%c %s",
						ch > 1 ? ',' : ':',
						fsmap[ch].desc);
567
#ifdef WITH_HASH
568
			fprintf(stderr, ", hash-signature comparison");
569
#endif
570 571 572 573 574 575 576 577
			fprintf(stderr, "\n");
			exit(0);
		}
	}

	if (argc < 1 || argc > 2)
		usage();

578 579 580 581 582 583 584 585 586
	if (compat &&
	    (
#ifdef WITH_CRYPTO
	     do_encrypt || do_checksum ||
#endif
	     got_imageid)) {
		fprintf(stderr, "Cannot use uuid/encrypt/checksum with -3\n");
		usage();
	}
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
	if (slicemode && (slice < 1 || slice > MAXSLICES)) {
		fprintf(stderr, "Slice must be a DOS partition (1-4) "
			"or extended DOS partition (5-%d)\n\n", MAXSLICES);
		usage();
	}
	if (maxmode && slicemode) {
		fprintf(stderr, "Count option (-c) cannot be used with "
			"the slice (-s) option\n\n");
		usage();
	}
	if (!info && argc != 2) {
		fprintf(stderr, "Must specify an output filename!\n\n");
		usage();
	}
	else
		outfilename = argv[1];

	if (!slicemode && !filemode && dorelocs)
		dorelocs = 0;

	infilename = argv[0];
	if ((infd = open(infilename, O_RDONLY, 0)) < 0) {
		perror(infilename);
		exit(1);
	}
612

613
#ifdef WITH_CRYPTO
614 615 616
	/*
	 * Let's get random!
	 */
Mike Hibler's avatar
Mike Hibler committed
617 618
	if (!RAND_load_file("/dev/urandom", 1024))
		fprintf(stderr, "Error getting random seed\n");
619 620 621 622 623 624 625 626 627 628 629

#ifdef SIGN_CHECKSUM
	/*
	 * Generate a signing pubkey.
	 * The pubkey is written to <imagename>.skey.
	 */
	if (do_checksum) {
		sig_key = RSA_generate_key(CSUM_MAX_LEN*8, 17, NULL, NULL);
		if (!info)
			output_public_key(outfilename, sig_key);
	}
Mike Hibler's avatar
Mike Hibler committed
630 631
#endif

632 633 634 635 636 637 638 639
	/*
	 * Generate an encryption key if none was given on the command line.
	 * The key is written to <imagename>.ekey.
	 */
	if (do_encrypt && enc_key == NULL) {
		enc_key = calloc(1, ENC_MAX_KEYLEN);
		if (enc_key == NULL || !RAND_bytes(enc_key, ENC_MAX_KEYLEN)) {
			fprintf(stderr, "Unable to generate random key\n");
Mike Hibler's avatar
Mike Hibler committed
640 641
			exit(1);
		}
642
		if (!info)
643 644
			output_encrypt_key(outfilename, enc_key,
					   ENC_MAX_KEYLEN);
645
	}
646 647
#endif

648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
#ifdef WITH_V3COMPAT
	/*
	 * Deal with pre-crypto backward compatibility.
	 * We don't want to generate V4 images unless we really need it.
	 * Note that this means we do NOT generate a UUID if none was provided.
	 */
	if (!compat &&
#ifdef WITH_CRYPTO
	    !do_encrypt && !do_checksum &&
#endif
	    !got_imageid)
		compat = COMPRESSED_V3;
#endif

	/*
	 * Generate a random UUID if one was not provided and we are
	 * not operating in compatibility mode.
	 */
	if (!compat && !got_imageid) {
		int fd = open("/dev/urandom", O_RDONLY, 0);

		if (fd < 0 ||
		    read(fd, imageid, sizeof(imageid)) != sizeof(imageid)) {
			fprintf(stderr, "WARNING: no UUID generated\n");
			memset(imageid, UUID_LENGTH, '\0');
		} else {
			char uuidstr[UUID_LENGTH*2+1];

			mem_to_hexstr(uuidstr, imageid, UUID_LENGTH);
			output_uuid(outfilename, uuidstr);
			got_imageid = 1;
		}

		if (fd >= 0)
			close(fd);
	}

685
#if 0
686 687 688 689 690 691 692 693
	/*
	 * Use OS-specific techniques to discover the size of the disk.
	 * Note that this could produce an image that will not fit on a
	 * smaller disk, as imagezip will consider any space beyond the
	 * final partition as allocated and will record the ranges.
	 */
	if (!slicemode && !maxmode)
		inputmaxsec = getdisksize(infd);
694 695
#endif

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
	/*
	 * Create the skip list by scanning the filesystems on
	 * the disk or indicated partition.
	 */
	if (slicetype != 0) {
		rval = read_slice(-1, slicetype, 0, 0,
				  infilename, infd);
		if (rval == -1)
			fprintf(stderr, ", cannot process\n");
	} else if (rawmode)
		rval = read_raw();
	else
		rval = read_image(DOSBBSECTOR, 0, 0);
	if (rval) {
		fprintf(stderr, "* * * Aborting * * *\n");
		exit(1);
712
	}
713 714 715 716 717 718 719 720

	/*
	 * Create a valid range list from the skip list
	 */
	(void) mergeskips(debug > 1);
	if (debug)
		dumpskips(debug > 1);
	makeranges();
721 722 723 724 725 726
	if (debug)
		dumpranges(debug > 1);
	sortrange(&fixups, 0, cmpfixups);
	if (debug > 1)
		dumpfixups(debug > 2);
	fflush(stderr);
727

728
#ifdef WITH_HASH
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
	/*
	 * If we are creating a "delta" image from a hash signature,
	 * we read in the signature info and reconcile that with the
	 * known allocated range that we have just computed.  The result
	 * is a new list of ranges that are currently allocated and that
	 * have changed from the signature version.
	 */
	if (hashfile != NULL) {
		struct range *nranges;

		/*
		 * next compare allocated 'ranges' and 'hinfo' to find out the
		 * changed blocks -- computing the hashes for some 'ranges'
		 * in the process
		 */
		nranges = hashmap_compute_delta(ranges, hashfile, infd,
						inputminsec);
		if (nranges == NULL)
			fprintf(stderr, "NO differences !!!!\n");

		freeranges(ranges);
		ranges = nranges;

		if (debug) {
			fprintf(stderr, "\nAfter delta computation: ");
			dumpranges(debug > 1);
		}
		report_hash_stats(slice);
	}
758
#endif
759

760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
	/*
	 * Now we have all the allocated information, create the image
	 * (unless we just want an info report).
	 */
	if (!info) {
		if (strcmp(outfilename, "-")) {
			if ((outfd = open(outfilename, O_RDWR|O_CREAT|O_TRUNC,
					  0666)) < 0) {
				perror("opening output file");
				exit(1);
			}
			outcanseek = 1;
		}
		else {
			outfd = fileno(stdout);
			outcanseek = 0;
			retrywrites = 0;
		}
		compress_image();
		assert(fixups == NULL);

		if (outcanseek)
			close(outfd);
	}
	close(infd);

	{
		struct timeval stamp;
		unsigned int ms;

		gettimeofday(&stamp, 0);
		if (stamp.tv_usec < sstamp.tv_usec) {
			stamp.tv_usec += 1000000;
			stamp.tv_sec--;
		}
		ms = (stamp.tv_sec - sstamp.tv_sec) * 1000 +
			(stamp.tv_usec - sstamp.tv_usec) / 1000;
		fprintf(stderr,
			"Finished in %u.%03u seconds\n",
			ms / 1000, ms % 1000);
	}
	fflush(stderr);
802 803

#ifdef WITH_CRYPTO
804 805
#ifdef SIGN_CHECKSUM
	if (do_checksum)
806
		RSA_free(sig_key);
807
#endif
808 809
#endif

810
	exit(0);
811 812
}

Mike Hibler's avatar
Mike Hibler committed
813 814
static int
read_slice(int snum, int stype, u_int32_t start, u_int32_t size,
815
	   char *sname, int sfd)
Mike Hibler's avatar
Mike Hibler committed
816
{
817
	struct slicemap *smap = getslicemap(stype);
818

819 820
	if (smap && smap->process)
		return (*smap->process)(snum, stype, start, size, sname, sfd);
821

822 823 824
	fprintf(stderr, "Slice %d is an unknown type %#x (%s)",
		snum+1, stype, smap ? smap->desc : "??");
	return -1;
Mike Hibler's avatar
Mike Hibler committed
825 826
}

827
/*
828 829
 * Read a DOS partition table at the indicated offset.
 * If successful return 0 with *label filled in.  Otherwise return an error.
830
 */
831 832
static int
read_doslabel(int infd, int lsect, int pstart, struct doslabel *label)
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
	int cc;

	if (devlseek(infd, sectobytes(lsect), SEEK_SET) < 0) {
		warn("Could not seek to DOS label at sector %u", lsect);
		return 1;
	}
	if ((cc = devread(infd, label->pad2, DOSPARTSIZE)) < 0) {
		warn("Could not read DOS label at sector %u", lsect);
		return 1;
	}
	if (cc != DOSPARTSIZE) {
		warnx("Incomplete read of DOS label at sector %u", lsect);
		return 1;
	}
	if (label->magic != BOOT_MAGIC) {
		warnx("Wrong magic number in DOS partition table at sector %u",
		      lsect);
		return 1;
	}

	if (debug) {
		int i;

		if (lsect == DOSBBSECTOR)
			fprintf(stderr, "DOS Partitions:\n");
		else
			fprintf(stderr,
				"DOS Partitions in Extended table at %u\n",
				lsect);
		for (i = 0; i < NDOSPART; i++) {
			struct slicemap *smap;
			u_int32_t start;
			int bsdix = pstart + i;

			fprintf(stderr, "  P%d: ", bsdix + 1);
			smap = getslicemap(label->parts[i].dp_typ);
			if (smap == 0)
871
				fprintf(stderr, "%-12s", "UNKNOWN");
872
			else
873
				fprintf(stderr, "%-12s", smap->desc);
874 875

			start = label->parts[i].dp_start;
876
#if 0
877 878 879 880 881
			/* Make start sector absolute */
			if (ISEXT(label->parts[i].dp_typ))
				start += extstart;
			else
				start += bbstart;
882
#endif
883 884 885 886 887
			fprintf(stderr, "  start %9d, size %9d\n",
				start, label->parts[i].dp_size);
		}
		fprintf(stderr, "\n");
	}
888

889
	return 0;
890 891 892 893 894 895 896 897
}

/*
 * Parse the DOS partition table and dispatch to the individual readers.
 */
int
read_image(u_int32_t bbstart, int pstart, u_int32_t extstart)
{
898 899 900 901 902 903 904 905
	int		i, rval = 0;
	struct slicemap	*smap;
	struct doslabel doslabel;

	if (read_doslabel(infd, bbstart, pstart, &doslabel) != 0)
		return 1;

	/*
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
	 * Quick, brute-force check for overlap of partitions.
	 * XXX right now, any overlap is bad and we bail.  In the future,
	 * we could determine all areas of intersection and be conservative
	 * with those areas; i.e., always save unless overlap is strictly
	 * between unused/ignored partitions.
	 */
	for (i = 0; i < NDOSPART-1; i++) {
		u_int32_t start1, size1, start2, size2;
		int i2;

		if ((size1 = doslabel.parts[i].dp_size) == 0)
			continue;

		start1 = bbstart + doslabel.parts[i].dp_start;
		for (i2 = i+1; i2 < NDOSPART; i2++) {
			if ((size2 = doslabel.parts[i2].dp_size) == 0)
				continue;
			start2 = bbstart + doslabel.parts[i2].dp_start;
			if (start2+size2 > start1 &&
			    start1+size1 > start2) {
				warnx("P%d and P%d overlap!", i+1, i2+1);
				rval++;
			}
		}
	}
	if (rval)
		return 1;

934 935
	/*
	 * Now operate on individual slices. 
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 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
	 */
	for (i = 0; i < NDOSPART; i++) {
		unsigned char	type  = doslabel.parts[i].dp_typ;
		u_int32_t	start = bbstart + doslabel.parts[i].dp_start;
		u_int32_t	size  = doslabel.parts[i].dp_size;
		int		bsdix = pstart + i;

		if (slicemode && bsdix + 1 != slice && !ISEXT(type))
			continue;

		if (ignore[bsdix]) {
			if (!ISBSD(type) || ignore[bsdix] == ~0)
				type = DOSPTYP_UNUSED;
		} else if (forceraw[bsdix]) {
			if (!ISBSD(type) || forceraw[bsdix] == ~0) {
				fprintf(stderr,
					"  Slice %d, forcing raw compression\n",
					bsdix + 1);
				goto skipcheck;
			}
		}

		smap = getslicemap(type);
		switch (type) {
		case DOSPTYP_EXT:
		case DOSPTYP_EXT_LBA:
			/*
			 * XXX extended partition start sectors are
			 * relative to the first extended partition found
			 */
			rval = read_image(extstart + doslabel.parts[i].dp_start,
					  pstart + NDOSPART,
					  extstart ? extstart : start);
			/* XXX for inputmaxsec calculation below */
			start = extstart + doslabel.parts[i].dp_start;
			break;

		case DOSPTYP_UNUSED:
			fprintf(stderr,
				"  Slice %d %s, NOT SAVING.\n", bsdix + 1,
				ignore[bsdix] ? "ignored" : "is unused");
			if (size > 0)
				addskip(start, size);
			break;

		default:
			rval = read_slice(bsdix, type, start, size,
					  infilename, infd);
			if (rval == -1) {
				fprintf(stderr, ", forcing raw compression\n");
				rval = 0;
			}
			break;
		}
		if (rval) {
			if (!ISEXT(type))
				fprintf(stderr,
					"  Filesystem specific error "
					"in Slice %d, "
					"use -R%d to force raw compression.\n",
					bsdix + 1, bsdix + 1);
			break;
		}

	skipcheck:
		/*
		 * In slicemode, we need to set the bounds of compression.
		 * Slice is a DOS partition number (1-4). If not in slicemode,
		 * we cannot set the bounds according to the doslabel since its
		 * possible that someone will create a disk with empty space
		 * before the first partition (typical, to start partition 1
		 * at the second cylinder) or after the last partition (Mike!).
		 * However, do not set the inputminsec since we usually want the
		 * stuff before the first partition, which is the boot stuff.
		 */
		if (slicemode && slice == bsdix + 1) {
			inputminsec = start;
			inputmaxsec = start + size;
		} else if (!slicemode && !maxmode) {
			if (start + size > inputmaxsec)
				inputmaxsec = start + size;
		}
	}

	return rval;
1021 1022
}

1023

1024 1025
/*
 * For a raw image (something we know nothing about), we report the size
1026
 * and compress the entire thing (that is, there are no skip ranges).
1027 1028 1029 1030
 */
int
read_raw(void)
{
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
	off_t	size;

	if ((size = devlseek(infd, (off_t) 0, SEEK_END)) < 0) {
		warn("lseeking to end of raw image");
		return 1;
	}

	/*
	 * Round up the size to a sector boundary
	 */
	if (filemode)
		size = sectobytes(bytestosec(size + secsize-1));

	if (debug) {
		fprintf(stderr, "  Raw Image\n");
		fprintf(stderr, "        start %12d, size %12lld\n",
			0, (long long)size);
	}
	return 0;
1050 1051
}

1052
char *usagestr =
1053
 "usage: imagezip [-vihor] [-s #] <image | device> [outputfilename]\n"
Mike Hibler's avatar
all:  
Mike Hibler committed
1054
 " -v             Print version info and exit\n"
1055
 " -i             Info mode only.  Do not write an output file\n"
Mike Hibler's avatar
all:  
Mike Hibler committed
1056
 " -h             Print this help message\n"
1057 1058
 " -o             Print progress indicating dots\n"
 " -r             Generate a `raw' image.  No FS compression is attempted\n"
Weibin Sun's avatar
Weibin Sun committed
1059
 " -f             Generate an image from a regular file (implies -r)\n"
1060 1061 1062 1063
 " -s slice       Compress a particular slice (DOS numbering 1-4)\n"
 " image | device The input image or a device special file (ie: /dev/ad0)\n"
 " outputfilename The output file ('-' for stdout)\n"
 "\n"
1064
 " Authentication and integrity options\n"
1065 1066 1067
 " -a hashalg     Create per-chunk signatures using the hash algorithm given\n"
 " -u uuid        Assign the given value as the image UUID\n"
 "\n"
1068
 " Encryption options\n"
1069
 " -e cipher      Encrypt the image with the given cipher\n"
1070
 " -k keyfile     File containing a key to use for encrypting\n"
1071
 "\n"
1072 1073 1074
 " Advanced options\n"
 " -z level       Set the compression level.  Range 0-9 (0==none, default==4)\n"
 " -I slice       Ignore (skip) the indicated slice (not with slice mode)\n"
Mike Hibler's avatar
Mike Hibler committed
1075
 " -R slice       Force raw compression of the indicated slice (not with slice mode)\n"
1076
 " -c count       Compress <count> number of sectors (not with slice mode)\n"
Mike Hibler's avatar
Mike Hibler committed
1077
 " -D             Do `dangerous' writes (don't check for async errors)\n"
1078
 " -1             Output a version one image file\n"
1079
 " -H hashfile    Use the specified imagehash-generated signature to produce a delta image\n"
1080 1081
 "\n"
 " Debugging options (not to be used by mere mortals!)\n"
1082
 " -d             Turn on debugging.  Multiple -d options increase output\n"
1083 1084
 " -b             FreeBSD slice only.  Input must be a FreeBSD FFS slice\n"
 " -l             Linux slice only.  Input must be a Linux EXT2FS slice\n"
Mike Hibler's avatar
Mike Hibler committed
1085 1086
 " -n             NTFS slice only.  Input must be an NTFS slice\n"
 " -S DOS-ptype   Treat the input device as containing a slice of the given type\n";
1087 1088 1089 1090

void
usage()
{
1091 1092
	fprintf(stderr, "%s", usagestr);
	exit(1);
1093 1094
}

1095 1096 1097
/*
 * Add a range of free space to skip
 */
1098
void
Mike Hibler's avatar
all:  
Mike Hibler committed
1099
addskip(uint32_t start, uint32_t size)
1100
{
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
	struct range	   *skip;

	if ((skip = (struct range *) malloc(sizeof(*skip))) == NULL) {
		fprintf(stderr, "No memory for skip range, "
			"try again with '-F <numsect>'\n"
			"where <numsect> is greater than the current %d\n",
			frangesize);
		exit(1);
	}

	skip->start = start;
	skip->size  = size;
	skip->next  = skips;
	skips       = skip;
	numskips++;
1116 1117
}

1118 1119 1120 1121 1122 1123 1124 1125
/*
 * Add an explicit valid block range.
 * We always add entries to the end of the list since we are commonly
 * called with alredy sorted entries.
 */
void
addvalid(uint32_t start, uint32_t size)
{
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
	static struct range **lastvalid = &ranges;
	struct range *valid;

	if ((valid = (struct range *) malloc(sizeof(*valid))) == NULL) {
		fprintf(stderr, "No memory for valid range\n");
		exit(1);
	}

	valid->start = start;
	valid->size  = size;
	valid->next  = 0;
	*lastvalid   = valid;
	lastvalid    = &valid->next;
	numranges++;
1140 1141
}

Mike Hibler's avatar
all:  
Mike Hibler committed
1142
void
1143
dumpskips(int verbose)
Mike Hibler's avatar
all:  
Mike Hibler committed
1144
{
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
	struct range	*pskip;
	uint32_t	offset = 0, total = 0;
	int		nranges = 0;

	if (!skips)
		return;

	if (verbose) {
		fprintf(stderr, "\nMin sector %lu, Max sector %lu\n",
			inputminsec, inputmaxsec);
		fprintf(stderr, "Skip ranges (start/size) in sectors:\n");
	}

	pskip = skips;
	while (pskip) {
		if (verbose)
			fprintf(stderr,
				"  %12d    %9d\n", pskip->start, pskip->size);
		assert(pskip->start >= offset);
		offset = pskip->start + pskip->size;
		total += pskip->size;
		nranges++;
		pskip  = pskip->next;
	}

	fprintf(stderr,
		"Total Number of Free Sectors: %d (bytes %lld) in %d ranges\n",
		total, (long long)sectobytes(total), nranges);
1173 1174 1175 1176
}

#undef DOHISTO

1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
/*
 * Zero the data associated with a free range that is being included
 * in the image because its size is less than frangesize.
 */
static void
zerofixup(void *bstart, off_t bsize, void *fdata)
{
	if (debug > 1)
		fprintf(stderr, "zerofixup: zeroing %llu@%p\n",
			(unsigned long long)bsize, bstart);

	memset(bstart, 0, bsize);
}

1191 1192 1193 1194 1195 1196 1197 1198 1199
/*
 * Sort and merge the list of skip blocks.
 * This code also winnows out the free ranges smaller than frangesize.
 * Returns the number of entries freed, useful so that it can be called
 * on-the-fly if we run out of memory to see if we managed to free anything.
 */
int
mergeskips(int verbose)
{
1200 1201 1202
	struct range *prange, **prevp;
	int freed = 0, culled = 0;
	uint32_t total = 0;
1203
#ifdef DOHISTO
1204 1205
	uint32_t histo[64];
	memset(histo, 0, sizeof(histo));
1206 1207
#endif

1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
	sortrange(&skips, 0, 0);
	freed += mergeranges(skips);

	/*
	 * After merging, make another pass to cull out the too-small ranges.
	 */
	if (frangesize) {
		prevp = &skips;
		while (*prevp) {
			prange = *prevp;
			if (prange->size < (uint32_t)frangesize) {
				if (debug > 2)
					fprintf(stderr,
						"dropping range [%u-%u]\n",
						prange->start,
						prange->start+prange->size-1);
1224 1225 1226 1227 1228 1229
				if (zerofrange)
					addfixupfunc(zerofixup,
						     sectobytes(prange->start),
						     0,
						     sectobytes(prange->size),
						     NULL, 0, RELOC_NONE);
1230
				total += prange->size;
1231
#ifdef DOHISTO
1232 1233
				if (prange->size < 64)
					histo[prange->size]++;
1234
#endif
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
				*prevp = prange->next;
				free(prange);
				culled++;
			} else
				prevp = &prange->next;
		}
		if (verbose && culled) {
			fprintf(stderr,
				"\nFree Sectors Ignored: %d (%lld bytes) in %d ranges\n",
				total, (long long)sectobytes(total), culled);
1245
#ifdef DOHISTO
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
			{
				int i;
				double r, s;
				double cumr = 0.0, cums = 0.0;
				for (i = 0; i < 64; i++) {
					if (histo[i] == 0)
						continue;
					r = (double)histo[i]/culled*100.0;
					cumr += r;
					s = (double)(histo[i]*i)/total*100.0;
					cums += s;
					fprintf(stderr,
						"%d: %u, %4.1f%% (%4.1f%%) of ranges "
						"%4.1f%% (%4.1f%%) of sectors)\n",
						i, histo[i], r, cumr, s, cums);
				}
			}
1263
#endif
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
		}
	}

	return (freed + culled);
}

#if USE_HACKSORT > 0
/*
 * A "better" sort.  Put pointers to all the linked list elements in an
 * array so that we can use qsort and then rebuild the linked list afterward.
 * The best sort technology available with less than 5 minutes work!
 */
int
sfunc(void *rfunc, const void *e1, const void *e2)
{
	int ((*rangecmp)(struct range *, struct range *)) = rfunc;
	struct range *r1 = *(struct range **)e1;
	struct range *r2 = *(struct range **)e2;

	if (r1->start > r2->start ||
	    (rfunc && (*rangecmp)(r1, r2)))
		return 1;
	return -1;
}
1288

1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
struct range *
bettersort(struct range *head, int count,
	       int (*rangecmp)(struct range *, struct range *))
{
	struct range **tarray, *nlist, **listp, *prange;
	int i;

	tarray = calloc(count, sizeof(struct range *));
	if (tarray == NULL)
		return NULL;

	i = 0;
	for (prange = head; prange; prange = prange->next) {
		assert(i < count);
		tarray[i] = prange;
		i++;
	}
	assert(i == count);
	qsort_r(tarray, count, sizeof(struct range *), rangecmp, sfunc);
	listp = &nlist;
	for (i = 0; i < count; i++) {
		assert(tarray[i+1] == NULL ||
		       tarray[i]->start <= tarray[i+1]->start);
		prange = tarray[i];
		*listp = prange;
		listp = &prange->next;
	}
	*listp = NULL;
	free(tarray);
	return nlist;
Mike Hibler's avatar
all:  
Mike Hibler committed
1319
}
1320
#endif
Mike Hibler's avatar
all:  
Mike Hibler committed
1321

1322 1323 1324 1325
/*
 * A very dumb bubblesort!
 */
void
1326 1327
sortrange(struct range **headp, int domerge,
	  int (*rangecmp)(struct range *, struct range *))
1328
{
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354