e2image.c revision f38cf3cb34addaa53d1f855d7607b151082a4229
1/*
2 * e2image.c --- Program which writes an image file backing up
3 * critical metadata for the filesystem.
4 *
5 * Copyright 2000, 2001 by Theodore Ts'o.
6 *
7 * %Begin-Header%
8 * This file may be redistributed under the terms of the GNU Public
9 * License.
10 * %End-Header%
11 */
12
13#define _LARGEFILE_SOURCE
14#define _LARGEFILE64_SOURCE
15
16#include <fcntl.h>
17#include <grp.h>
18#ifdef HAVE_GETOPT_H
19#include <getopt.h>
20#else
21extern char *optarg;
22extern int optind;
23#endif
24#include <pwd.h>
25#include <stdio.h>
26#ifdef HAVE_STDLIB_H
27#include <stdlib.h>
28#endif
29#include <string.h>
30#include <time.h>
31#include <unistd.h>
32#include <fcntl.h>
33#include <errno.h>
34#include <sys/stat.h>
35#include <sys/types.h>
36
37#include "ext2fs/ext2_fs.h"
38#include "ext2fs/ext2fs.h"
39#include "et/com_err.h"
40#include "uuid/uuid.h"
41#include "e2p/e2p.h"
42#include "ext2fs/e2image.h"
43
44#include "../version.h"
45#include "nls-enable.h"
46
47const char * program_name = "e2image";
48char * device_name = NULL;
49
50static void usage(void)
51{
52	fprintf(stderr, _("Usage: %s [-rsI] device image_file\n"),
53		program_name);
54	exit (1);
55}
56
57static void write_header(int fd, struct ext2_image_hdr *hdr, int blocksize)
58{
59	char *header_buf;
60	int actual;
61
62	header_buf = malloc(blocksize);
63	if (!header_buf) {
64		fputs(_("Couldn't allocate header buffer\n"), stderr);
65		exit(1);
66	}
67
68	if (lseek(fd, 0, SEEK_SET) < 0) {
69		perror("lseek while writing header");
70		exit(1);
71	}
72	memset(header_buf, 0, blocksize);
73
74	if (hdr)
75		memcpy(header_buf, hdr, sizeof(struct ext2_image_hdr));
76
77	actual = write(fd, header_buf, blocksize);
78	if (actual < 0) {
79		perror("write header");
80		exit(1);
81	}
82	if (actual != blocksize) {
83		fprintf(stderr, _("short write (only %d bytes) for "
84				  "writing image header"), actual);
85		exit(1);
86	}
87	free(header_buf);
88}
89
90static void write_image_file(ext2_filsys fs, int fd)
91{
92	struct ext2_image_hdr	hdr;
93	struct stat		st;
94	errcode_t		retval;
95
96	write_header(fd, NULL, fs->blocksize);
97	memset(&hdr, 0, sizeof(struct ext2_image_hdr));
98
99	hdr.offset_super = lseek(fd, 0, SEEK_CUR);
100	retval = ext2fs_image_super_write(fs, fd, 0);
101	if (retval) {
102		com_err(program_name, retval, _("while writing superblock"));
103		exit(1);
104	}
105
106	hdr.offset_inode = lseek(fd, 0, SEEK_CUR);
107	retval = ext2fs_image_inode_write(fs, fd,
108				  (fd != 1) ? IMAGER_FLAG_SPARSEWRITE : 0);
109	if (retval) {
110		com_err(program_name, retval, _("while writing inode table"));
111		exit(1);
112	}
113
114	hdr.offset_blockmap = lseek(fd, 0, SEEK_CUR);
115	retval = ext2fs_image_bitmap_write(fs, fd, 0);
116	if (retval) {
117		com_err(program_name, retval, _("while writing block bitmap"));
118		exit(1);
119	}
120
121	hdr.offset_inodemap = lseek(fd, 0, SEEK_CUR);
122	retval = ext2fs_image_bitmap_write(fs, fd, IMAGER_FLAG_INODEMAP);
123	if (retval) {
124		com_err(program_name, retval, _("while writing inode bitmap"));
125		exit(1);
126	}
127
128	hdr.magic_number = EXT2_ET_MAGIC_E2IMAGE;
129	strcpy(hdr.magic_descriptor, "Ext2 Image 1.0");
130	gethostname(hdr.fs_hostname, sizeof(hdr.fs_hostname));
131	strncpy(hdr.fs_device_name, device_name, sizeof(hdr.fs_device_name)-1);
132	hdr.fs_device_name[sizeof(hdr.fs_device_name) - 1] = 0;
133	hdr.fs_blocksize = fs->blocksize;
134
135	if (stat(device_name, &st) == 0)
136		hdr.fs_device = st.st_rdev;
137
138	if (fstat(fd, &st) == 0) {
139		hdr.image_device = st.st_dev;
140		hdr.image_inode = st.st_ino;
141	}
142	memcpy(hdr.fs_uuid, fs->super->s_uuid, sizeof(hdr.fs_uuid));
143
144	hdr.image_time = time(0);
145	write_header(fd, &hdr, fs->blocksize);
146}
147
148/*
149 * These set of functions are used to write a RAW image file.
150 */
151ext2fs_block_bitmap meta_block_map;
152ext2fs_block_bitmap scramble_block_map;	/* Directory blocks to be scrambled */
153
154struct process_block_struct {
155	ext2_ino_t	ino;
156	int		is_dir;
157};
158
159/*
160 * These subroutines short circuits ext2fs_get_blocks and
161 * ext2fs_check_directory; we use them since we already have the inode
162 * structure, so there's no point in letting the ext2fs library read
163 * the inode again.
164 */
165static ino_t stashed_ino = 0;
166static struct ext2_inode *stashed_inode;
167
168static errcode_t meta_get_blocks(ext2_filsys fs EXT2FS_ATTR((unused)),
169				 ext2_ino_t ino,
170				 blk_t *blocks)
171{
172	int	i;
173
174	if ((ino != stashed_ino) || !stashed_inode)
175		return EXT2_ET_CALLBACK_NOTHANDLED;
176
177	for (i=0; i < EXT2_N_BLOCKS; i++)
178		blocks[i] = stashed_inode->i_block[i];
179	return 0;
180}
181
182static errcode_t meta_check_directory(ext2_filsys fs EXT2FS_ATTR((unused)),
183				      ext2_ino_t ino)
184{
185	if ((ino != stashed_ino) || !stashed_inode)
186		return EXT2_ET_CALLBACK_NOTHANDLED;
187
188	if (!LINUX_S_ISDIR(stashed_inode->i_mode))
189		return EXT2_ET_NO_DIRECTORY;
190	return 0;
191}
192
193static errcode_t meta_read_inode(ext2_filsys fs EXT2FS_ATTR((unused)),
194				 ext2_ino_t ino,
195				 struct ext2_inode *inode)
196{
197	if ((ino != stashed_ino) || !stashed_inode)
198		return EXT2_ET_CALLBACK_NOTHANDLED;
199	*inode = *stashed_inode;
200	return 0;
201}
202
203static void use_inode_shortcuts(ext2_filsys fs, int bool)
204{
205	if (bool) {
206		fs->get_blocks = meta_get_blocks;
207		fs->check_directory = meta_check_directory;
208		fs->read_inode = meta_read_inode;
209		stashed_ino = 0;
210	} else {
211		fs->get_blocks = 0;
212		fs->check_directory = 0;
213		fs->read_inode = 0;
214	}
215}
216
217static int process_dir_block(ext2_filsys fs EXT2FS_ATTR((unused)),
218			     blk_t *block_nr,
219			     e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
220			     blk_t ref_block EXT2FS_ATTR((unused)),
221			     int ref_offset EXT2FS_ATTR((unused)),
222			     void *priv_data EXT2FS_ATTR((unused)))
223{
224	struct process_block_struct *p;
225
226	p = (struct process_block_struct *) priv_data;
227
228	ext2fs_mark_block_bitmap(meta_block_map, *block_nr);
229	if (scramble_block_map && p->is_dir && blockcnt >= 0)
230		ext2fs_mark_block_bitmap(scramble_block_map, *block_nr);
231	return 0;
232}
233
234static int process_file_block(ext2_filsys fs EXT2FS_ATTR((unused)),
235			      blk_t *block_nr,
236			      e2_blkcnt_t blockcnt,
237			      blk_t ref_block EXT2FS_ATTR((unused)),
238			      int ref_offset EXT2FS_ATTR((unused)),
239			      void *priv_data EXT2FS_ATTR((unused)))
240{
241	if (blockcnt < 0) {
242		ext2fs_mark_block_bitmap(meta_block_map, *block_nr);
243	}
244	return 0;
245}
246
247static void mark_table_blocks(ext2_filsys fs)
248{
249	blk_t	first_block, b;
250	unsigned int	i,j;
251
252	first_block = fs->super->s_first_data_block;
253	/*
254	 * Mark primary superblock
255	 */
256	ext2fs_mark_block_bitmap(meta_block_map, first_block);
257
258	/*
259	 * Mark the primary superblock descriptors
260	 */
261	for (j = 0; j < fs->desc_blocks; j++) {
262		ext2fs_mark_block_bitmap(meta_block_map,
263			 ext2fs_descriptor_block_loc(fs, first_block, j));
264	}
265
266	for (i = 0; i < fs->group_desc_count; i++) {
267		/*
268		 * Mark the blocks used for the inode table
269		 */
270		if (fs->group_desc[i].bg_inode_table) {
271			for (j = 0, b = fs->group_desc[i].bg_inode_table;
272			     j < (unsigned) fs->inode_blocks_per_group;
273			     j++, b++)
274				ext2fs_mark_block_bitmap(meta_block_map, b);
275		}
276
277		/*
278		 * Mark block used for the block bitmap
279		 */
280		if (fs->group_desc[i].bg_block_bitmap) {
281			ext2fs_mark_block_bitmap(meta_block_map,
282				     fs->group_desc[i].bg_block_bitmap);
283		}
284
285		/*
286		 * Mark block used for the inode bitmap
287		 */
288		if (fs->group_desc[i].bg_inode_bitmap) {
289			ext2fs_mark_block_bitmap(meta_block_map,
290				 fs->group_desc[i].bg_inode_bitmap);
291		}
292	}
293}
294
295/*
296 * This function returns 1 if the specified block is all zeros
297 */
298static int check_zero_block(char *buf, int blocksize)
299{
300	char	*cp = buf;
301	int	left = blocksize;
302
303	while (left > 0) {
304		if (*cp++)
305			return 0;
306		left--;
307	}
308	return 1;
309}
310
311static void write_block(int fd, char *buf, int sparse_offset,
312			int blocksize, blk_t block)
313{
314	int		count;
315	errcode_t	err;
316
317	if (sparse_offset) {
318#ifdef HAVE_LSEEK64
319		if (lseek64(fd, sparse_offset, SEEK_CUR) < 0)
320			perror("lseek");
321#else
322		if (lseek(fd, sparse_offset, SEEK_CUR) < 0)
323			perror("lseek");
324#endif
325	}
326	if (blocksize) {
327		count = write(fd, buf, blocksize);
328		if (count != blocksize) {
329			if (count == -1)
330				err = errno;
331			else
332				err = 0;
333			com_err(program_name, err, "error writing block %u",
334				block);
335			exit(1);
336		}
337	}
338}
339
340int name_id[256];
341
342static void scramble_dir_block(ext2_filsys fs, blk_t blk, char *buf)
343{
344	char *p, *end, *cp;
345	struct ext2_dir_entry_2 *dirent;
346	int rec_len, id, len;
347
348	end = buf + fs->blocksize;
349	for (p = buf; p < end-8; p += rec_len) {
350		dirent = (struct ext2_dir_entry_2 *) p;
351		rec_len = dirent->rec_len;
352#ifdef WORDS_BIGENDIAN
353		rec_len = ext2fs_swab16(rec_len);
354#endif
355		rec_len = (rec_len || fs->blocksize < 65536) ?
356			rec_len : 65536;
357#if 0
358		printf("rec_len = %d, name_len = %d\n", rec_len, dirent->name_len);
359#endif
360		if (rec_len < 8 || (rec_len % 4) ||
361		    (p+rec_len > end)) {
362			printf("Corrupt directory block %lu: "
363			       "bad rec_len (%d)\n", (unsigned long) blk,
364			       rec_len);
365			rec_len = end - p;
366#ifdef WORDS_BIGENDIAN
367				dirent->rec_len = ext2fs_swab16(rec_len);
368#endif
369			continue;
370		}
371		if (dirent->name_len + 8 > rec_len) {
372			printf("Corrupt directory block %lu: "
373			       "bad name_len (%d)\n", (unsigned long) blk,
374			       dirent->name_len);
375			dirent->name_len = rec_len - 8;
376			continue;
377		}
378		cp = p+8;
379		len = rec_len - dirent->name_len - 8;
380		if (len > 0)
381			memset(cp+dirent->name_len, 0, len);
382		if (dirent->name_len==1 && cp[0] == '.')
383			continue;
384		if (dirent->name_len==2 && cp[0] == '.' && cp[1] == '.')
385			continue;
386
387		memset(cp, 'A', dirent->name_len);
388		len = dirent->name_len;
389		id = name_id[len]++;
390		while ((len > 0) && (id > 0)) {
391			*cp += id % 26;
392			id = id / 26;
393			cp++;
394			len--;
395		}
396	}
397}
398
399static void output_meta_data_blocks(ext2_filsys fs, int fd)
400{
401	errcode_t	retval;
402	blk_t		blk;
403	char		*buf, *zero_buf;
404	int		sparse = 0;
405
406	buf = malloc(fs->blocksize);
407	if (!buf) {
408		com_err(program_name, ENOMEM, "while allocating buffer");
409		exit(1);
410	}
411	zero_buf = malloc(fs->blocksize);
412	if (!zero_buf) {
413		com_err(program_name, ENOMEM, "while allocating buffer");
414		exit(1);
415	}
416	memset(zero_buf, 0, fs->blocksize);
417	for (blk = 0; blk < fs->super->s_blocks_count; blk++) {
418		if ((blk >= fs->super->s_first_data_block) &&
419		    ext2fs_test_block_bitmap(meta_block_map, blk)) {
420			retval = io_channel_read_blk(fs->io, blk, 1, buf);
421			if (retval) {
422				com_err(program_name, retval,
423					"error reading block %u", blk);
424			}
425			if (scramble_block_map &&
426			    ext2fs_test_block_bitmap(scramble_block_map, blk))
427				scramble_dir_block(fs, blk, buf);
428			if ((fd != 1) && check_zero_block(buf, fs->blocksize))
429				goto sparse_write;
430			write_block(fd, buf, sparse, fs->blocksize, blk);
431			sparse = 0;
432		} else {
433		sparse_write:
434			if (fd == 1) {
435				write_block(fd, zero_buf, 0,
436					    fs->blocksize, blk);
437				continue;
438			}
439			sparse += fs->blocksize;
440			if (sparse >= 1024*1024) {
441				write_block(fd, 0, sparse, 0, 0);
442				sparse = 0;
443			}
444		}
445	}
446	if (sparse)
447		write_block(fd, zero_buf, sparse-1, 1, -1);
448	free(zero_buf);
449	free(buf);
450}
451
452static void write_raw_image_file(ext2_filsys fs, int fd, int scramble_flag)
453{
454	struct process_block_struct	pb;
455	struct ext2_inode		inode;
456	ext2_inode_scan			scan;
457	ext2_ino_t			ino;
458	errcode_t			retval;
459	char *				block_buf;
460
461	retval = ext2fs_allocate_block_bitmap(fs, "in-use block map",
462					      &meta_block_map);
463	if (retval) {
464		com_err(program_name, retval, "while allocating block bitmap");
465		exit(1);
466	}
467
468	if (scramble_flag) {
469		retval = ext2fs_allocate_block_bitmap(fs, "scramble block map",
470						      &scramble_block_map);
471		if (retval) {
472			com_err(program_name, retval,
473				"while allocating scramble block bitmap");
474			exit(1);
475		}
476	}
477
478	mark_table_blocks(fs);
479
480	retval = ext2fs_open_inode_scan(fs, 0, &scan);
481	if (retval) {
482		com_err(program_name, retval, _("while opening inode scan"));
483		exit(1);
484	}
485
486	block_buf = malloc(fs->blocksize * 3);
487	if (!block_buf) {
488		com_err(program_name, 0, "Can't allocate block buffer");
489		exit(1);
490	}
491
492	use_inode_shortcuts(fs, 1);
493	stashed_inode = &inode;
494	while (1) {
495		retval = ext2fs_get_next_inode(scan, &ino, &inode);
496		if (retval == EXT2_ET_BAD_BLOCK_IN_INODE_TABLE)
497			continue;
498		if (retval) {
499			com_err(program_name, retval,
500				_("while getting next inode"));
501			exit(1);
502		}
503		if (ino == 0)
504			break;
505		if (!inode.i_links_count)
506			continue;
507		if (inode.i_file_acl) {
508			ext2fs_mark_block_bitmap(meta_block_map,
509						 inode.i_file_acl);
510		}
511		if (!ext2fs_inode_has_valid_blocks(&inode))
512			continue;
513
514		stashed_ino = ino;
515		pb.ino = ino;
516		pb.is_dir = LINUX_S_ISDIR(inode.i_mode);
517		if (LINUX_S_ISDIR(inode.i_mode) ||
518		    (LINUX_S_ISLNK(inode.i_mode) &&
519		     ext2fs_inode_has_valid_blocks(&inode)) ||
520		    ino == fs->super->s_journal_inum) {
521			retval = ext2fs_block_iterate2(fs, ino,
522					BLOCK_FLAG_READ_ONLY, block_buf,
523					process_dir_block, &pb);
524			if (retval) {
525				com_err(program_name, retval,
526					"while iterating over inode %u",
527					ino);
528				exit(1);
529			}
530		} else {
531			if ((inode.i_flags & EXT4_EXTENTS_FL) ||
532			    inode.i_block[EXT2_IND_BLOCK] ||
533			    inode.i_block[EXT2_DIND_BLOCK] ||
534			    inode.i_block[EXT2_TIND_BLOCK]) {
535				retval = ext2fs_block_iterate2(fs,
536				       ino, BLOCK_FLAG_READ_ONLY, block_buf,
537				       process_file_block, &pb);
538				if (retval) {
539					com_err(program_name, retval,
540					"while iterating over inode %u", ino);
541					exit(1);
542				}
543			}
544		}
545	}
546	use_inode_shortcuts(fs, 0);
547	output_meta_data_blocks(fs, fd);
548	free(block_buf);
549}
550
551static void install_image(char *device, char *image_fn, int raw_flag)
552{
553	errcode_t retval;
554	ext2_filsys fs;
555	int open_flag = EXT2_FLAG_IMAGE_FILE;
556	int fd = 0;
557	io_manager	io_ptr;
558	io_channel	io, image_io;
559
560	if (raw_flag) {
561		com_err(program_name, 0, "Raw images cannot be installed");
562		exit(1);
563	}
564
565#ifdef CONFIG_TESTIO_DEBUG
566	if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
567		io_ptr = test_io_manager;
568		test_io_backing_manager = unix_io_manager;
569	} else
570#endif
571		io_ptr = unix_io_manager;
572
573	retval = ext2fs_open (image_fn, open_flag, 0, 0,
574			      io_ptr, &fs);
575        if (retval) {
576		com_err (program_name, retval, _("while trying to open %s"),
577			 image_fn);
578		exit(1);
579	}
580
581	retval = ext2fs_read_bitmaps (fs);
582	if (retval) {
583		com_err(program_name, retval, "error reading bitmaps");
584		exit(1);
585	}
586
587#ifdef HAVE_OPEN64
588	fd = open64(image_fn, O_RDONLY);
589#else
590	fd = open(image_fn, O_RDONLY);
591#endif
592	if (fd < 0) {
593		perror(image_fn);
594		exit(1);
595	}
596
597	retval = io_ptr->open(device, IO_FLAG_RW, &io);
598	if (retval) {
599		com_err(device, 0, "while opening device file");
600		exit(1);
601	}
602
603	image_io = fs->io;
604
605	ext2fs_rewrite_to_io(fs, io);
606
607	if (lseek(fd, fs->image_header->offset_inode, SEEK_SET) < 0) {
608		perror("lseek");
609		exit(1);
610	}
611
612	retval = ext2fs_image_inode_read(fs, fd, 0);
613	if (retval) {
614		com_err(image_fn, 0, "while restoring the image table");
615		exit(1);
616	}
617
618	ext2fs_close (fs);
619	exit (0);
620}
621
622int main (int argc, char ** argv)
623{
624	int c;
625	errcode_t retval;
626	ext2_filsys fs;
627	char *image_fn;
628	int open_flag = 0;
629	int raw_flag = 0;
630	int install_flag = 0;
631	int scramble_flag = 0;
632	int fd = 0;
633
634#ifdef ENABLE_NLS
635	setlocale(LC_MESSAGES, "");
636	setlocale(LC_CTYPE, "");
637	bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
638	textdomain(NLS_CAT_NAME);
639#endif
640	fprintf (stderr, "e2image %s (%s)\n", E2FSPROGS_VERSION,
641		 E2FSPROGS_DATE);
642	if (argc && *argv)
643		program_name = *argv;
644	add_error_table(&et_ext2_error_table);
645	while ((c = getopt (argc, argv, "rsI")) != EOF)
646		switch (c) {
647		case 'r':
648			raw_flag++;
649			break;
650		case 's':
651			scramble_flag++;
652			break;
653		case 'I':
654			install_flag++;
655			break;
656		default:
657			usage();
658		}
659	if (optind != argc - 2 )
660		usage();
661	device_name = argv[optind];
662	image_fn = argv[optind+1];
663
664	if (install_flag) {
665		install_image(device_name, image_fn, raw_flag);
666		exit (0);
667	}
668
669	retval = ext2fs_open (device_name, open_flag, 0, 0,
670			      unix_io_manager, &fs);
671        if (retval) {
672		com_err (program_name, retval, _("while trying to open %s"),
673			 device_name);
674		fputs(_("Couldn't find valid filesystem superblock.\n"), stdout);
675		exit(1);
676	}
677
678	if (strcmp(image_fn, "-") == 0)
679		fd = 1;
680	else {
681#ifdef HAVE_OPEN64
682		fd = open64(image_fn, O_CREAT|O_TRUNC|O_WRONLY, 0600);
683#else
684		fd = open(image_fn, O_CREAT|O_TRUNC|O_WRONLY, 0600);
685#endif
686		if (fd < 0) {
687			com_err(program_name, errno,
688				_("while trying to open %s"), argv[optind+1]);
689			exit(1);
690		}
691	}
692
693	if (raw_flag)
694		write_raw_image_file(fs, fd, scramble_flag);
695	else
696		write_image_file(fs, fd);
697
698	ext2fs_close (fs);
699	remove_error_table(&et_ext2_error_table);
700	exit (0);
701}
702