• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Copyright (C) 2021 LG Electronics.
4  *
5  *   Author(s): Hyunchul Lee <hyc.lee@gmail.com>
6  */
7 
8 #include <unistd.h>
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <fcntl.h>
12 #include <stdlib.h>
13 #include <stdio.h>
14 #include <getopt.h>
15 #include <inttypes.h>
16 #include <string.h>
17 #include <errno.h>
18 
19 #include "exfat_ondisk.h"
20 #include "libexfat.h"
21 #include "exfat_fs.h"
22 #include "exfat_dir.h"
23 
24 #define EXFAT_MAX_UPCASE_CHARS	0x10000
25 
26 struct exfat2img_hdr {
27 	__le32	magic;
28 	__le32	major_version;
29 	__le32	minor_version;
30 	__le32	data_offset;
31 	__le32	heap_clus_offset;
32 	__le32	cluster_size;
33 	__le32	cluster_count;
34 	__le32	reserved[20];
35 } __packed;
36 
37 #define EI_MAGIC		0xB67598DB
38 #define EI_CC_PAYLOAD_LEN	4
39 
40 enum {
41 	EI_CC_INVALID,
42 	EI_CC_COPY_1,
43 	EI_CC_COPY_2,	/* followed by cluster count(4-byte) */
44 	EI_CC_SKIP_1,
45 	EI_CC_SKIP_2,	/* followed by cluster count(4-byte) */
46 };
47 
48 struct exfat2img {
49 	int			out_fd;
50 	bool			is_stdout;
51 	off_t			stdout_offset;
52 	bool			save_cc;
53 	struct exfat_blk_dev	bdev;
54 	struct exfat		*exfat;
55 	void			*dump_cluster;
56 	struct buffer_desc	*scan_bdesc;
57 	struct exfat_de_iter	de_iter;
58 };
59 
60 struct exfat_stat {
61 	long		dir_count;
62 	long		file_count;
63 	long		error_count;
64 	uint64_t	written_bytes;
65 };
66 
67 static struct exfat2img_hdr ei_hdr;
68 static struct exfat2img ei;
69 static struct exfat_stat exfat_stat;
70 static struct path_resolve_ctx path_resolve_ctx;
71 
72 static struct option opts[] = {
73 	{"output",	required_argument,	NULL,	'o' },
74 	{"version",	no_argument,		NULL,	'V' },
75 	{"help",	no_argument,		NULL,	'h' },
76 	{NULL,		0,			NULL,	 0  }
77 };
78 
usage(const char * name)79 static void usage(const char *name)
80 {
81 	fprintf(stderr, "Usage: %s <device> [image-file]\n", name);
82 	fprintf(stderr, "\t-o | --output <image-file> Specify destination file\n");
83 	fprintf(stderr, "\t-V | --version             Show version\n");
84 	fprintf(stderr, "\t-h | --help                Show help\n");
85 	exit(EXIT_FAILURE);
86 }
87 
88 #define ei_err(parent, inode, fmt, ...)			\
89 ({							\
90 		exfat_resolve_path_parent(&path_resolve_ctx,	\
91 			parent, inode);			\
92 		exfat_err("ERROR: %s: " fmt,		\
93 			path_resolve_ctx.local_path,	\
94 			##__VA_ARGS__);			\
95 })
96 
free_exfat2img(struct exfat2img * ei)97 static void free_exfat2img(struct exfat2img *ei)
98 {
99 	if (ei->scan_bdesc)
100 		exfat_free_buffer(ei->exfat, ei->scan_bdesc);
101 	if (ei->exfat)
102 		exfat_free_exfat(ei->exfat);
103 	if (ei->dump_cluster)
104 		free(ei->dump_cluster);
105 	if (ei->out_fd)
106 		close(ei->out_fd);
107 	if (ei->bdev.dev_fd)
108 		close(ei->bdev.dev_fd);
109 }
110 
create_exfat2img(struct exfat2img * ei,struct pbr * bs,const char * out_path)111 static int create_exfat2img(struct exfat2img *ei,
112 			    struct pbr *bs,
113 			    const char *out_path)
114 {
115 	int err;
116 
117 	ei->exfat = exfat_alloc_exfat(&ei->bdev, bs);
118 	if (!ei->exfat)
119 		return -ENOMEM;
120 
121 	ei->dump_cluster = malloc(ei->exfat->clus_size);
122 	if (!ei->dump_cluster) {
123 		err = -ENOMEM;
124 		goto err;
125 	}
126 
127 	ei->scan_bdesc = exfat_alloc_buffer(ei->exfat);
128 	if (!ei->scan_bdesc) {
129 		err = -ENOMEM;
130 		goto err;
131 	}
132 
133 	if (strcmp(out_path, "-")) {
134 		ei->out_fd = open(out_path, O_CREAT | O_TRUNC | O_RDWR, 0664);
135 	} else {
136 		ei->is_stdout = true;
137 		ei->out_fd = fileno(stdout);
138 		ei->save_cc = true;
139 	}
140 	if (ei->out_fd < 0) {
141 		exfat_err("failed to open %s: %s\n", out_path,
142 			  strerror(errno));
143 		err = -errno;
144 		goto err;
145 	}
146 
147 	return 0;
148 err:
149 	free_exfat2img(ei);
150 	return err;
151 }
152 
153 /**
154  * @end: excluded.
155  */
dump_range(struct exfat2img * ei,off_t start,off_t end)156 static ssize_t dump_range(struct exfat2img *ei, off_t start, off_t end)
157 {
158 	struct exfat *exfat = ei->exfat;
159 	size_t len, total_len = 0;
160 	ssize_t ret;
161 
162 	if (ei->is_stdout) {
163 		unsigned int sc, sc_offset;
164 		unsigned int ec, ec_offset;
165 
166 		if (exfat_o2c(ei->exfat, start, &sc, &sc_offset) < 0)
167 			return -ERANGE;
168 		if (exfat_o2c(ei->exfat, end - 1, &ec, &ec_offset) < 0)
169 			return -ERANGE;
170 		exfat_bitmap_set_range(ei->exfat, exfat->alloc_bitmap,
171 				       sc, ec - sc + 1);
172 		return end - start;
173 	}
174 
175 	while (start < end) {
176 		len = (size_t)MIN(end - start, exfat->clus_size);
177 
178 		ret = exfat_read(exfat->blk_dev->dev_fd,
179 				 ei->dump_cluster, len, start);
180 		if (ret != (ssize_t)len) {
181 			exfat_err("failed to read %llu bytes at %llu\n",
182 				  (unsigned long long)len,
183 				  (unsigned long long)start);
184 			return -EIO;
185 		}
186 
187 		ret = pwrite(ei->out_fd, ei->dump_cluster, len, start);
188 		if (ret != (ssize_t)len) {
189 			exfat_err("failed to write %llu bytes at %llu\n",
190 				  (unsigned long long)len,
191 				  (unsigned long long)start);
192 			return -EIO;
193 		}
194 
195 		start += len;
196 		total_len += len;
197 		exfat_stat.written_bytes += len;
198 	}
199 	return total_len;
200 }
201 
dump_sectors(struct exfat2img * ei,off_t start_sect,off_t end_sect_excl)202 static int dump_sectors(struct exfat2img *ei,
203 			off_t start_sect,
204 			off_t end_sect_excl)
205 {
206 	struct exfat *exfat = ei->exfat;
207 	off_t s, e;
208 
209 	s = exfat_s2o(exfat, start_sect);
210 	e = exfat_s2o(exfat, end_sect_excl);
211 	return dump_range(ei, s, e) <= 0 ? -EIO : 0;
212 }
213 
dump_clusters(struct exfat2img * ei,clus_t start_clus,clus_t end_clus_excl)214 static int dump_clusters(struct exfat2img *ei,
215 			 clus_t start_clus,
216 			 clus_t end_clus_excl)
217 {
218 	struct exfat *exfat = ei->exfat;
219 	off_t s, e;
220 
221 	s = exfat_c2o(exfat, start_clus);
222 	e = exfat_c2o(exfat, end_clus_excl);
223 	return dump_range(ei, s, e) <= 0 ? -EIO : 0;
224 }
225 
dump_directory(struct exfat2img * ei,struct exfat_inode * inode,size_t size,clus_t * out_clus_count)226 static int dump_directory(struct exfat2img *ei,
227 			  struct exfat_inode *inode, size_t size,
228 			  clus_t *out_clus_count)
229 {
230 	struct exfat *exfat = ei->exfat;
231 	clus_t clus, possible_count;
232 	uint64_t max_count;
233 	size_t dump_size;
234 	off_t start_off, end_off;
235 
236 	if (size == 0)
237 		return -EINVAL;
238 
239 	if (!(inode->attr & ATTR_SUBDIR))
240 		return -EINVAL;
241 
242 	clus = inode->first_clus;
243 	*out_clus_count = 0;
244 	max_count = DIV_ROUND_UP(inode->size, exfat->clus_size);
245 
246 	possible_count = (256 * MB) >> (exfat->bs->bsx.sect_per_clus_bits +
247 					exfat->bs->bsx.sect_size_bits);
248 	possible_count = MIN(possible_count, exfat->clus_count);
249 
250 	while (exfat_heap_clus(exfat, clus) && *out_clus_count < possible_count) {
251 		dump_size = MIN(size, exfat->clus_size);
252 		start_off = exfat_c2o(exfat, clus);
253 		end_off = start_off + DIV_ROUND_UP(dump_size, 512) * 512;
254 
255 		if (dump_range(ei, start_off, end_off) < 0)
256 			return -EIO;
257 
258 		*out_clus_count += 1;
259 		size -= dump_size;
260 		if (size == 0)
261 			break;
262 
263 		if (inode->is_contiguous) {
264 			if (*out_clus_count >= max_count)
265 				break;
266 		}
267 		if (exfat_get_inode_next_clus(exfat, inode, clus, &clus))
268 			return -EINVAL;
269 	}
270 	return 0;
271 }
272 
dump_root(struct exfat2img * ei)273 static int dump_root(struct exfat2img *ei)
274 {
275 	struct exfat *exfat = ei->exfat;
276 	struct exfat_inode *root;
277 	clus_t clus_count = 0;
278 
279 	root = exfat_alloc_inode(ATTR_SUBDIR);
280 	if (!root)
281 		return -ENOMEM;
282 
283 	root->first_clus = le32_to_cpu(exfat->bs->bsx.root_cluster);
284 	dump_directory(ei, root, (size_t)-1, &clus_count);
285 	root->size = clus_count * exfat->clus_size;
286 
287 	ei->exfat->root = root;
288 	return 0;
289 }
290 
read_file_dentry_set(struct exfat_de_iter * iter,struct exfat_inode ** new_node,int * skip_dentries)291 static int read_file_dentry_set(struct exfat_de_iter *iter,
292 				struct exfat_inode **new_node, int *skip_dentries)
293 {
294 	struct exfat_dentry *file_de, *stream_de, *dentry;
295 	struct exfat_inode *node = NULL;
296 	int i, ret;
297 
298 	ret = exfat_de_iter_get(iter, 0, &file_de);
299 	if (ret || file_de->type != EXFAT_FILE) {
300 		exfat_debug("failed to get file dentry\n");
301 		return -EINVAL;
302 	}
303 
304 	ret = exfat_de_iter_get(iter, 1, &stream_de);
305 	if (ret || stream_de->type != EXFAT_STREAM) {
306 		exfat_debug("failed to get stream dentry\n");
307 		*skip_dentries = 2;
308 		goto skip_dset;
309 	}
310 
311 	*new_node = NULL;
312 	node = exfat_alloc_inode(le16_to_cpu(file_de->file_attr));
313 	if (!node)
314 		return -ENOMEM;
315 
316 	for (i = 2; i <= MIN(file_de->file_num_ext, 1 + MAX_NAME_DENTRIES); i++) {
317 		ret = exfat_de_iter_get(iter, i, &dentry);
318 		if (ret || dentry->type != EXFAT_NAME)
319 			break;
320 		memcpy(node->name +
321 		       (i - 2) * ENTRY_NAME_MAX, dentry->name_unicode,
322 		       sizeof(dentry->name_unicode));
323 	}
324 
325 	node->first_clus = le32_to_cpu(stream_de->stream_start_clu);
326 	node->is_contiguous =
327 		((stream_de->stream_flags & EXFAT_SF_CONTIGUOUS) != 0);
328 	node->size = le64_to_cpu(stream_de->stream_size);
329 
330 	*skip_dentries = i;
331 	*new_node = node;
332 	return 0;
333 skip_dset:
334 	*new_node = NULL;
335 	exfat_free_inode(node);
336 	return -EINVAL;
337 }
338 
read_file(struct exfat_de_iter * de_iter,struct exfat_inode ** new_node,int * dentry_count)339 static int read_file(struct exfat_de_iter *de_iter,
340 		     struct exfat_inode **new_node, int *dentry_count)
341 {
342 	struct exfat_inode *node;
343 	int ret;
344 
345 	*new_node = NULL;
346 
347 	ret = read_file_dentry_set(de_iter, &node, dentry_count);
348 	if (ret)
349 		return ret;
350 
351 	if (node->attr & ATTR_SUBDIR)
352 		exfat_stat.dir_count++;
353 	else
354 		exfat_stat.file_count++;
355 	*new_node = node;
356 	return ret;
357 }
358 
read_bitmap(struct exfat2img * ei,struct exfat_de_iter * iter)359 static int read_bitmap(struct exfat2img *ei, struct exfat_de_iter *iter)
360 {
361 	struct exfat *exfat = ei->exfat;
362 	struct exfat_dentry *dentry;
363 	int ret;
364 
365 	ret = exfat_de_iter_get(iter, 0, &dentry);
366 	if (ret || dentry->type != EXFAT_BITMAP) {
367 		exfat_debug("failed to get bimtap dentry\n");
368 		return -EINVAL;
369 	}
370 
371 	exfat_debug("start cluster %#x, size %#" PRIx64 "\n",
372 		    le32_to_cpu(dentry->bitmap_start_clu),
373 		    le64_to_cpu(dentry->bitmap_size));
374 
375 	if (!exfat_heap_clus(exfat, le32_to_cpu(dentry->bitmap_start_clu))) {
376 		exfat_err("invalid start cluster of allocate bitmap. 0x%x\n",
377 			  le32_to_cpu(dentry->bitmap_start_clu));
378 		return -EINVAL;
379 	}
380 
381 	exfat->disk_bitmap_clus = le32_to_cpu(dentry->bitmap_start_clu);
382 	exfat->disk_bitmap_size = DIV_ROUND_UP(exfat->clus_count, 8);
383 
384 	return dump_clusters(ei,
385 			     exfat->disk_bitmap_clus,
386 			     exfat->disk_bitmap_clus +
387 			     DIV_ROUND_UP(exfat->disk_bitmap_size,
388 					  exfat->clus_size));
389 }
390 
read_upcase_table(struct exfat2img * ei,struct exfat_de_iter * iter)391 static int read_upcase_table(struct exfat2img *ei,
392 			     struct exfat_de_iter *iter)
393 {
394 	struct exfat *exfat = ei->exfat;
395 	struct exfat_dentry *dentry = NULL;
396 	int retval;
397 	ssize_t size;
398 
399 	retval = exfat_de_iter_get(iter, 0, &dentry);
400 	if (retval || dentry->type != EXFAT_UPCASE) {
401 		exfat_debug("failed to get upcase dentry\n");
402 		return -EINVAL;
403 	}
404 
405 	if (!exfat_heap_clus(exfat, le32_to_cpu(dentry->upcase_start_clu))) {
406 		exfat_err("invalid start cluster of upcase table. 0x%x\n",
407 			  le32_to_cpu(dentry->upcase_start_clu));
408 		return -EINVAL;
409 	}
410 
411 	size = EXFAT_MAX_UPCASE_CHARS * sizeof(__le16);
412 	return dump_clusters(ei, le32_to_cpu(dentry->upcase_start_clu),
413 			     le32_to_cpu(dentry->upcase_start_clu) +
414 			     DIV_ROUND_UP(size, exfat->clus_size));
415 }
416 
read_children(struct exfat2img * ei,struct exfat_inode * dir,off_t * end_file_offset)417 static int read_children(struct exfat2img *ei, struct exfat_inode *dir,
418 			 off_t *end_file_offset)
419 {
420 	struct exfat *exfat = ei->exfat;
421 	struct exfat_inode *node = NULL;
422 	struct exfat_dentry *dentry;
423 	struct exfat_de_iter *de_iter;
424 	int dentry_count;
425 	int ret;
426 
427 	*end_file_offset = 0;
428 	de_iter = &ei->de_iter;
429 	ret = exfat_de_iter_init(de_iter, exfat, dir, ei->scan_bdesc);
430 	if (ret == EOF)
431 		return 0;
432 	else if (ret)
433 		return ret;
434 
435 	while (1) {
436 		ret = exfat_de_iter_get(de_iter, 0, &dentry);
437 		if (ret == EOF) {
438 			break;
439 		} else if (ret) {
440 			ei_err(dir->parent, dir,
441 			       "failed to get a dentry. %d\n", ret);
442 			goto err;
443 		}
444 		dentry_count = 1;
445 
446 		switch (dentry->type) {
447 		case EXFAT_FILE:
448 			ret = read_file(de_iter, &node, &dentry_count);
449 			if (ret < 0) {
450 				exfat_stat.error_count++;
451 				break;
452 			}
453 
454 			if (node) {
455 				if ((node->attr & ATTR_SUBDIR) && node->size) {
456 					node->parent = dir;
457 					list_add_tail(&node->sibling,
458 						      &dir->children);
459 					list_add_tail(&node->list,
460 						      &exfat->dir_list);
461 				} else {
462 					exfat_free_inode(node);
463 				}
464 			}
465 			break;
466 		case EXFAT_LAST:
467 			goto out;
468 		case EXFAT_BITMAP:
469 			if (dir == exfat->root) {
470 				ret = read_bitmap(ei, de_iter);
471 				if (ret)
472 					exfat_debug("failed to read bitmap\n");
473 			}
474 			break;
475 		case EXFAT_UPCASE:
476 			if (dir == exfat->root) {
477 				ret = read_upcase_table(ei, de_iter);
478 				if (ret)
479 					exfat_debug("failed to upcase table\n");
480 			}
481 			break;
482 		case EXFAT_VOLUME:
483 		default:
484 			break;
485 		}
486 
487 		ret = exfat_de_iter_advance(de_iter, dentry_count);
488 	}
489 out:
490 	*end_file_offset = exfat_de_iter_file_offset(de_iter);
491 	exfat_de_iter_flush(de_iter);
492 	return 0;
493 err:
494 	exfat_free_children(dir, false);
495 	INIT_LIST_HEAD(&dir->children);
496 	exfat_de_iter_flush(de_iter);
497 	return ret;
498 }
499 
dump_filesystem(struct exfat2img * ei)500 static int dump_filesystem(struct exfat2img *ei)
501 {
502 	struct exfat *exfat = ei->exfat;
503 	struct exfat_inode *dir;
504 	int ret = 0, dir_errors;
505 	clus_t clus_count;
506 	off_t end_file_offset;
507 
508 	if (!exfat->root) {
509 		exfat_err("root is NULL\n");
510 		return -ENOENT;
511 	}
512 
513 	list_add(&exfat->root->list, &exfat->dir_list);
514 
515 	while (!list_empty(&exfat->dir_list)) {
516 		dir = list_entry(exfat->dir_list.next,
517 				 struct exfat_inode, list);
518 		clus_count = 0;
519 
520 		if (!(dir->attr & ATTR_SUBDIR)) {
521 			ei_err(dir->parent, dir,
522 			       "failed to travel directories. the node is not directory\n");
523 			ret = -EINVAL;
524 			goto out;
525 		}
526 
527 		dir_errors = read_children(ei, dir, &end_file_offset);
528 		if (!dir_errors) {
529 			dump_directory(ei, dir, (size_t)end_file_offset,
530 				       &clus_count);
531 		} else if (dir_errors) {
532 			dump_directory(ei, dir, (size_t)-1,
533 				       &clus_count);
534 			exfat_resolve_path(&path_resolve_ctx, dir);
535 			exfat_debug("failed to check dentries: %s\n",
536 				    path_resolve_ctx.local_path);
537 			ret = dir_errors;
538 		}
539 
540 		list_del(&dir->list);
541 		exfat_free_ancestors(dir);
542 	}
543 out:
544 	exfat_free_dir_list(exfat);
545 	return ret;
546 }
547 
dump_bytes_to_stdout(struct exfat2img * ei,off_t start,off_t end_excl)548 static int dump_bytes_to_stdout(struct exfat2img *ei,
549 				off_t start, off_t end_excl)
550 {
551 	struct exfat *exfat = ei->exfat;
552 	size_t len;
553 	ssize_t ret;
554 
555 	if (start != ei->stdout_offset) {
556 		exfat_err("try to skip for stdout at %llu, expected: %llu\n",
557 			  (unsigned long long)start,
558 			  (unsigned long long)ei->stdout_offset);
559 		return -EINVAL;
560 	}
561 
562 	while (start < end_excl) {
563 		len = (size_t)MIN(end_excl - start, exfat->clus_size);
564 		ret = exfat_read(exfat->blk_dev->dev_fd, ei->dump_cluster,
565 				 len, start);
566 		if (ret != (ssize_t)len) {
567 			exfat_err("failed to read %llu bytes at %llu\n",
568 				  (unsigned long long)len,
569 				  (unsigned long long)start);
570 			return -EIO;
571 		}
572 
573 		ret = write(ei->out_fd, ei->dump_cluster, len);
574 		if (ret != (ssize_t)len) {
575 			exfat_err("failed to write %llu bytes at %llu\n",
576 				  (unsigned long long)len,
577 				  (unsigned long long)start);
578 			return -EIO;
579 		}
580 
581 		start += len;
582 		ei->stdout_offset += len;
583 		exfat_stat.written_bytes += len;
584 	}
585 	return 0;
586 }
587 
dump_clusters_to_stdout(struct exfat2img * ei,unsigned int start_clu,unsigned int end_clu,bool fill_zero)588 static int dump_clusters_to_stdout(struct exfat2img *ei,
589 				   unsigned int start_clu, unsigned int end_clu,
590 				   bool fill_zero)
591 {
592 	unsigned int clu, clu_count;
593 	unsigned char cc;
594 	unsigned int cc_clu_count, cc_len;
595 	off_t start_off, end_off_excl;
596 	char buf[1 + EI_CC_PAYLOAD_LEN];
597 
598 	clu = start_clu;
599 	clu_count = end_clu - start_clu + 1;
600 
601 	if (ei->save_cc) {
602 		/* if the count of clusters is less than 5, use SKIP_1 or COPY_2 */
603 		cc_clu_count = clu_count < 5 ? 1 : clu_count;
604 		cc_len = cc_clu_count == 1 ? 1 : 1 + EI_CC_PAYLOAD_LEN;
605 		if (fill_zero)
606 			cc = cc_clu_count == 1 ? EI_CC_SKIP_1 : EI_CC_SKIP_2;
607 		else
608 			cc = cc_clu_count == 1 ? EI_CC_COPY_1 : EI_CC_COPY_2;
609 	} else {
610 		cc = EI_CC_INVALID;
611 		cc_clu_count = clu_count;
612 	}
613 
614 	while (clu <= end_clu) {
615 		if (cc != EI_CC_INVALID) {
616 			buf[0] = cc;
617 			*((__le32 *)&buf[1]) =
618 				cpu_to_le32(cc_clu_count);
619 			if (write(ei->out_fd, buf, cc_len) != (ssize_t)cc_len) {
620 				exfat_err("failed to write cc %d : %u\n for %u ~ %u clusters\n",
621 					  cc, cc_clu_count,
622 					  start_clu, start_clu + cc_clu_count - 1);
623 			}
624 		}
625 
626 		if (cc == EI_CC_COPY_1 || cc == EI_CC_COPY_2) {
627 			start_off = exfat_c2o(ei->exfat, clu);
628 			end_off_excl = exfat_c2o(ei->exfat, clu + cc_clu_count);
629 
630 			if (dump_bytes_to_stdout(ei, start_off, end_off_excl) < 0)
631 				return -EIO;
632 		} else {
633 			ei->stdout_offset += (off_t)cc_clu_count * ei->exfat->clus_size;
634 		}
635 		clu += cc_clu_count;
636 	}
637 
638 	return 0;
639 }
640 
dump_to_stdout(struct exfat2img * ei)641 static int dump_to_stdout(struct exfat2img *ei)
642 {
643 	struct exfat *exfat = ei->exfat;
644 	off_t start_off, end_off;
645 	unsigned int clu, last_clu, next_clu;
646 	unsigned int start_clu, end_clu;
647 
648 	start_off = 0;
649 	end_off = exfat_s2o(exfat, le32_to_cpu(exfat->bs->bsx.clu_offset));
650 	if (dump_bytes_to_stdout(ei, start_off, end_off) < 0) {
651 		exfat_err("failed to dump boot sectors and FAT tables\n");
652 		return -EIO;
653 	}
654 
655 	clu = EXFAT_FIRST_CLUSTER;
656 	last_clu = clu + exfat->clus_count;
657 	while (clu < last_clu) {
658 		/* read and write clusters for allocated ones */
659 		start_clu = 0;
660 		while (clu < last_clu &&
661 		       exfat_bitmap_get(exfat->alloc_bitmap, clu)) {
662 			if (!start_clu)
663 				start_clu = clu;
664 			end_clu = clu;
665 			clu++;
666 		}
667 
668 		if (start_clu) {
669 			if (dump_clusters_to_stdout(ei, start_clu, end_clu, false) < 0) {
670 				start_off = exfat_c2o(exfat, start_clu);
671 				end_off = exfat_c2o(exfat, end_clu);
672 				exfat_err("failed to dump range from %llx to %llx\n",
673 					  (unsigned long long)start_off,
674 					  (unsigned long long)end_off);
675 				return -EIO;
676 			}
677 		}
678 
679 		/* exit if all of the remaining clusters are free */
680 		if (clu >= last_clu)
681 			break;
682 		if (exfat_bitmap_find_one(exfat, exfat->alloc_bitmap,
683 					  clu, &next_clu))
684 			next_clu = EXFAT_FIRST_CLUSTER + exfat->clus_count;
685 
686 		/* write zeroes for free clusters */
687 		start_clu = clu;
688 		end_clu = next_clu - 1;
689 		if (dump_clusters_to_stdout(ei, start_clu, end_clu, true) < 0) {
690 			start_off = exfat_c2o(exfat, start_clu);
691 			end_off = exfat_c2o(exfat, end_clu);
692 			exfat_err("failed to dump zero range from %llx to %llx\n",
693 				  (unsigned long long)start_off,
694 				  (unsigned long long)end_off);
695 			return -EIO;
696 		}
697 
698 		clu = next_clu;
699 	}
700 
701 	return 0;
702 }
703 
dump_header(struct exfat2img * ei)704 static int dump_header(struct exfat2img *ei)
705 {
706 	struct exfat *exfat = ei->exfat;
707 
708 	ei_hdr.magic = cpu_to_le32(EI_MAGIC);
709 	ei_hdr.major_version = cpu_to_le32(1);
710 	ei_hdr.minor_version = cpu_to_le32(0);
711 	ei_hdr.data_offset = cpu_to_le32(sizeof(struct exfat2img_hdr));
712 	ei_hdr.heap_clus_offset =
713 		cpu_to_le32(le32_to_cpu(exfat->bs->bsx.clu_offset) *
714 			    exfat->sect_size);
715 	ei_hdr.cluster_size = cpu_to_le32(exfat->clus_size);
716 	ei_hdr.cluster_count = cpu_to_le32(exfat->clus_count);
717 
718 	if (write(ei->out_fd, &ei_hdr, sizeof(ei_hdr)) != (ssize_t)sizeof(ei_hdr)) {
719 		exfat_err("failed to write exfat2img header\n");
720 		return -EIO;
721 	}
722 	return 0;
723 }
724 
read_stream(int fd,void * buf,size_t len)725 static ssize_t read_stream(int fd, void *buf, size_t len)
726 {
727 	size_t read_len = 0;
728 	ssize_t ret;
729 
730 	while (read_len < len) {
731 		ret = read(fd, buf, len - read_len);
732 		if (ret < 0) {
733 			if (errno != -EAGAIN && errno != -EINTR)
734 				return -1;
735 			ret = 0;
736 		} else if (ret == 0) {
737 			return 0;
738 		}
739 		buf = (char *)buf + (size_t)ret;
740 		read_len += (size_t)ret;
741 	}
742 	return read_len;
743 }
744 
restore_from_stdin(struct exfat2img * ei)745 static int restore_from_stdin(struct exfat2img *ei)
746 {
747 	int in_fd, ret = 0;
748 	unsigned char cc;
749 	unsigned int clu, end_clu;
750 	unsigned int cc_clu_count;
751 	unsigned int clus_size;
752 	__le32 t_cc_clu_count;
753 	off_t out_start_off, out_end_off_excl;
754 	off_t in_start_off;
755 	size_t len;
756 
757 	in_fd = fileno(stdin);
758 	if (in_fd < 0) {
759 		exfat_err("failed to get fd from stdin\n");
760 		return in_fd;
761 	}
762 
763 	if (read_stream(in_fd, &ei_hdr, sizeof(ei_hdr)) != (ssize_t)sizeof(ei_hdr)) {
764 		exfat_err("failed to read a header\n");
765 		return -EIO;
766 	}
767 
768 	if (le32_to_cpu(ei_hdr.magic) != EI_MAGIC) {
769 		exfat_err("header has invalid magic %#x, expected %#x\n",
770 			  le32_to_cpu(ei_hdr.magic), EI_MAGIC);
771 		return -EINVAL;
772 	}
773 
774 	clus_size = le32_to_cpu(ei_hdr.cluster_size);
775 
776 	ei->out_fd = ei->bdev.dev_fd;
777 	ei->dump_cluster = malloc(clus_size);
778 	if (!ei->dump_cluster)
779 		return -ENOMEM;
780 
781 	/* restore boot regions, and FAT tables */
782 	in_start_off = le32_to_cpu(ei_hdr.data_offset);
783 	out_start_off = 0;
784 	out_end_off_excl = le32_to_cpu(ei_hdr.heap_clus_offset);
785 	while (out_start_off < out_end_off_excl) {
786 		len = MIN(out_end_off_excl - out_start_off, clus_size);
787 		if (read_stream(in_fd, ei->dump_cluster, len) != (ssize_t)len) {
788 			exfat_err("failed to read first meta region. %llu ~ %llu\n",
789 				  (unsigned long long)in_start_off,
790 				  (unsigned long long)in_start_off + len);
791 			ret = -EIO;
792 			goto out;
793 		}
794 
795 		if (pwrite(ei->out_fd, ei->dump_cluster, len, out_start_off)
796 		    != (ssize_t)len) {
797 			exfat_err("failed to write first meta region. %llu ~ %llu\n",
798 				  (unsigned long long)out_start_off,
799 				  (unsigned long long)out_start_off + len);
800 			ret = -EIO;
801 			goto out;
802 		}
803 
804 		out_start_off += len;
805 		in_start_off += len;
806 	}
807 
808 	/* restore heap clusters */
809 	clu = 0;
810 	while (clu < le32_to_cpu(ei_hdr.cluster_count)) {
811 		if (read_stream(in_fd, &cc, sizeof(cc)) != (ssize_t)sizeof(cc)) {
812 			exfat_err("failed to read cc at %llu\n",
813 				  (unsigned long long)in_start_off);
814 			ret = -EIO;
815 			goto out;
816 		}
817 		in_start_off += 1;
818 
819 		if (cc == EI_CC_COPY_2 || cc == EI_CC_SKIP_2) {
820 			if (read_stream(in_fd, &t_cc_clu_count, EI_CC_PAYLOAD_LEN) !=
821 			    (ssize_t)EI_CC_PAYLOAD_LEN) {
822 				exfat_err("failed to read cc cluster count at %llu\n",
823 					  (unsigned long long)in_start_off);
824 				ret = -EIO;
825 				goto out;
826 			}
827 			cc_clu_count = le32_to_cpu(t_cc_clu_count);
828 			in_start_off += EI_CC_PAYLOAD_LEN;
829 		} else if (cc == EI_CC_COPY_1 || cc == EI_CC_SKIP_1) {
830 			cc_clu_count = 1;
831 		} else {
832 			exfat_err("unexpected cc %d at %llu\n",
833 				  cc, (unsigned long long)in_start_off);
834 			ret = -EINVAL;
835 			goto out;
836 		}
837 
838 		if (cc == EI_CC_COPY_1 || cc == EI_CC_COPY_2) {
839 			end_clu = clu + cc_clu_count;
840 			while (clu < end_clu) {
841 				if (read_stream(in_fd, ei->dump_cluster,
842 						clus_size) != (ssize_t)clus_size) {
843 					exfat_err("failed to read range %llu ~ %llu\n",
844 						  (unsigned long long)in_start_off,
845 						  (unsigned long long)in_start_off + clus_size);
846 					ret = -EIO;
847 					goto out;
848 				}
849 				if (pwrite(ei->out_fd, ei->dump_cluster,
850 					   clus_size, out_start_off) != (ssize_t)clus_size) {
851 					exfat_err("failed to write range %llu ~ %llu\n",
852 						  (unsigned long long)out_start_off,
853 						  (unsigned long long)out_start_off + clus_size);
854 					ret = -EIO;
855 					goto out;
856 				}
857 
858 				out_start_off += clus_size;
859 				in_start_off += clus_size;
860 				clu++;
861 			}
862 		} else {
863 			out_start_off += (off_t)cc_clu_count * clus_size;
864 			in_start_off +=  (off_t)cc_clu_count * clus_size;
865 			if (lseek(ei->out_fd, out_start_off, SEEK_SET) == (off_t)-1) {
866 				exfat_err("failed to seek to %llu\n",
867 					  (unsigned long long)out_start_off);
868 				ret = -EIO;
869 				goto out;
870 			}
871 			clu += cc_clu_count;
872 		}
873 	}
874 out:
875 	if (fsync(ei->out_fd)) {
876 		exfat_err("failed to fsync: %d\n", errno);
877 		ret = -EIO;
878 	}
879 	free(ei->dump_cluster);
880 	return ret;
881 }
882 
main(int argc,char * const argv[])883 int main(int argc, char * const argv[])
884 {
885 	int err = 0, c;
886 	const char *in_path, *out_path = NULL, *blkdev_path;
887 	struct pbr *bs;
888 	struct exfat_user_input ui;
889 	off_t last_sect;
890 	bool restore;
891 
892 	print_level = EXFAT_ERROR;
893 
894 	opterr = 0;
895 	while ((c = getopt_long(argc, argv, "o:Vh", opts, NULL)) != EOF) {
896 		switch (c) {
897 		case 'o':
898 			out_path = optarg;
899 			break;
900 		case 'V':
901 			show_version();
902 			return 0;
903 		case 'h':
904 			/* Fall through */
905 		default:
906 			usage(argv[0]);
907 			break;
908 		}
909 	}
910 
911 	show_version();
912 	if (!(optind == argc - 1 && out_path) &&
913 	    !(optind == argc - 2 && !out_path))
914 		usage(argv[0]);
915 
916 	in_path = argv[optind++];
917 	if (!out_path)
918 		out_path = argv[optind++];
919 
920 	if (!strcmp(in_path, "-")) {
921 		restore = true;
922 		blkdev_path = out_path;
923 	} else {
924 		restore = false;
925 		blkdev_path = in_path;
926 	}
927 
928 	memset(&ui, 0, sizeof(ui));
929 	ui.dev_name = blkdev_path;
930 	if (restore)
931 		ui.writeable = true;
932 	else
933 		ui.writeable = false;
934 
935 	if (exfat_get_blk_dev_info(&ui, &ei.bdev)) {
936 		exfat_err("failed to open %s\n", ui.dev_name);
937 		return EXIT_FAILURE;
938 	}
939 
940 	if (restore)
941 		return restore_from_stdin(&ei);
942 
943 	err = read_boot_sect(&ei.bdev, &bs);
944 	if (err) {
945 		close(ei.bdev.dev_fd);
946 		return EXIT_FAILURE;
947 	}
948 
949 	err = create_exfat2img(&ei, bs, out_path);
950 	if (err)
951 		return EXIT_FAILURE;
952 
953 	if (!ei.is_stdout) {
954 		err = dump_sectors(&ei, 0, le32_to_cpu(ei.exfat->bs->bsx.clu_offset));
955 		if (err) {
956 			exfat_err("failed to dump boot sectors, fat\n");
957 			goto out;
958 		}
959 
960 		last_sect = (off_t)le32_to_cpu(ei.exfat->bs->bsx.clu_offset) +
961 			(le32_to_cpu(ei.exfat->bs->bsx.clu_count) <<
962 			 ei.exfat->bs->bsx.sect_per_clus_bits) - 1;
963 		err = dump_sectors(&ei, last_sect, last_sect + 1);
964 		if (err) {
965 			exfat_err("failed to dump last sector\n");
966 			goto out;
967 		}
968 	}
969 
970 	err = dump_root(&ei);
971 	if (err) {
972 		exfat_err("failed to dump root\n");
973 		goto out;
974 	}
975 
976 	dump_filesystem(&ei);
977 
978 	if (ei.is_stdout) {
979 		err = dump_header(&ei);
980 		if (err)
981 			goto out;
982 		err = dump_to_stdout(&ei);
983 		if (err)
984 			goto out;
985 	} else {
986 		err = fsync(ei.out_fd);
987 		if (err) {
988 			exfat_err("failed to fsync %s. %d\n", out_path, errno);
989 			goto out;
990 		}
991 		close(ei.out_fd);
992 	}
993 
994 	printf("%ld files found, %ld directories dumped, %llu kbytes written\n",
995 	       exfat_stat.file_count,
996 	       exfat_stat.dir_count,
997 	       (unsigned long long)DIV_ROUND_UP(exfat_stat.written_bytes, 1024));
998 
999 out:
1000 	free_exfat2img(&ei);
1001 	return err == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
1002 }
1003