xref: /openbsd-src/sbin/dump/main.c (revision a0747c9f67a4ae71ccb71e62a28d1ea19e06a63c)
1 /*	$OpenBSD: main.c,v 1.62 2021/01/21 00:16:36 mortimer Exp $	*/
2 /*	$NetBSD: main.c,v 1.14 1997/06/05 11:13:24 lukem Exp $	*/
3 
4 /*-
5  * Copyright (c) 1980, 1991, 1993, 1994
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/param.h>	/* MAXBSIZE DEV_BSIZE roundup */
34 #include <sys/mount.h>
35 #include <sys/stat.h>
36 #include <sys/time.h>
37 #include <sys/ioctl.h>
38 #include <sys/disklabel.h>
39 #include <sys/dkio.h>
40 #include <ufs/ffs/fs.h>
41 #include <ufs/ufs/dinode.h>
42 
43 #include <protocols/dumprestore.h>
44 
45 #include <ctype.h>
46 #include <err.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <fstab.h>
50 #include <paths.h>
51 #include <signal.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <time.h>
56 #include <unistd.h>
57 #include <limits.h>
58 #include <util.h>
59 
60 #include "dump.h"
61 #include "pathnames.h"
62 
63 int     mapsize;	/* size of the state maps */
64 char    *usedinomap;	/* map of allocated inodes */
65 char    *dumpdirmap;	/* map of directories to be dumped */
66 char    *dumpinomap;	/* map of files to be dumped */
67 char    *disk;		/* name of the disk file */
68 char    *tape;		/* name of the tape file */
69 char    level;		/* dump level of this dump */
70 int     uflag;		/* update flag */
71 int     diskfd;		/* disk file descriptor */
72 int     pipeout;	/* true => output to standard output */
73 int     density = 0;	/* density in bytes/0.1" */
74 int64_t tapesize;	/* estimated tape size, blocks */
75 int64_t tsize;		/* tape size in 0.1" units */
76 int     etapes;		/* estimated number of tapes */
77 int     nonodump;	/* if set, do not honor UF_NODUMP user flags */
78 int     unlimited;	/* if set, write to end of medium */
79 int     notify = 0;	/* notify operator flag */
80 int64_t blockswritten = 0; /* number of blocks written on current tape */
81 int     tapeno = 0;	/* current tape number */
82 int     ntrec = NTREC;	/* # tape blocks in each tape record */
83 int64_t blocksperfile;	/* output blocks per file */
84 int     cartridge = 0;	/* Assume non-cartridge tape */
85 char    *host = NULL;	/* remote host (if any) */
86 time_t  tstart_writing;	/* when started writing the first tape block */
87 long    xferrate;	/* averaged transfer rate of all volumes */
88 struct fs *sblock;	/* the file system super block */
89 char    sblock_buf[MAXBSIZE];
90 int     tp_bshift;	/* log2(TP_BSIZE) */
91 char    *duid;		/* duid of the disk being dumped */
92 int     maxbsize = 64*1024; /* XXX MAXBSIZE from sys/param.h */
93 
94 struct disklabel lab;
95 
96 /*
97  * Possible superblock locations ordered from most to least likely.
98  */
99 static int sblock_try[] = SBLOCKSEARCH;
100 
101 static long long numarg(char *, long long, long long);
102 static void obsolete(int *, char **[]);
103 static void usage(void);
104 
105 int
106 main(int argc, char *argv[])
107 {
108 	ino_t ino;
109 	int dirty;
110 	union dinode *dp;
111 	struct	fstab *dt;
112 	char *map;
113 	int ch, mode;
114 	struct tm then;
115 	struct statfs fsbuf;
116 	int i, anydirskipped, bflag = 0, Tflag = 0, honorlevel = 1;
117 	ino_t maxino;
118 	time_t t;
119 	int dirlist;
120 	char *toplevel, *str, *mount_point = NULL, *realpath;
121 	int just_estimate = 0;
122 	u_int64_t zero_uid = 0;
123 
124 	spcl.c_date = (int64_t)time(NULL);
125 
126 	tsize = 0;	/* Default later, based on 'c' option for cart tapes */
127 	if ((tape = getenv("TAPE")) == NULL)
128 		tape = _PATH_DEFTAPE;
129 	dumpdates = _PATH_DUMPDATES;
130 	if (TP_BSIZE / DEV_BSIZE == 0 || TP_BSIZE % DEV_BSIZE != 0)
131 		quit("TP_BSIZE must be a multiple of DEV_BSIZE\n");
132 	level = '0';
133 
134 	if (argc < 2)
135 		usage();
136 
137 	obsolete(&argc, &argv);
138 	while ((ch = getopt(argc, argv, "0123456789aB:b:cd:f:h:ns:ST:uWw")) != -1)
139 		switch (ch) {
140 		/* dump level */
141 		case '0': case '1': case '2': case '3': case '4':
142 		case '5': case '6': case '7': case '8': case '9':
143 			level = ch;
144 			break;
145 
146 		case 'B':		/* blocks per output file */
147 			blocksperfile = numarg("blocks per file", 1, 0);
148 			break;
149 
150 		case 'b':		/* blocks per tape write */
151 			ntrec = numarg("blocks per write", 1, 1000);
152 			if (ntrec > maxbsize/1024) {
153 				msg("Please choose a blocksize <= %dKB\n",
154 				    maxbsize/1024);
155 				exit(X_STARTUP);
156 			}
157 			bflag = 1;
158 			break;
159 
160 		case 'c':		/* Tape is cart. not 9-track */
161 			cartridge = 1;
162 			break;
163 
164 		case 'd':		/* density, in bits per inch */
165 			density = numarg("density", 10, 327670) / 10;
166 			if (density >= 625 && !bflag)
167 				ntrec = HIGHDENSITYTREC;
168 			break;
169 
170 		case 'f':		/* output file */
171 			tape = optarg;
172 			break;
173 
174 		case 'h':
175 			honorlevel = numarg("honor level", 0, 10);
176 			break;
177 
178 		case 'n':		/* notify operators */
179 			notify = 1;
180 			break;
181 
182 		case 's':		/* tape size, feet */
183 			tsize = numarg("tape size", 1, 0) * 12 * 10;
184 			break;
185 
186 		case 'S':		/* estimate blocks and # of tapes */
187 			just_estimate = 1;
188 			break;
189 
190 		case 'T':		/* time of last dump */
191 			str = strptime(optarg, "%a %b %e %H:%M:%S %Y", &then);
192 			then.tm_isdst = -1;
193 			if (str == NULL || (*str != '\n' && *str != '\0'))
194 				spcl.c_ddate = -1;
195 			else
196 				spcl.c_ddate = (int64_t)mktime(&then);
197 			if (spcl.c_ddate < 0) {
198 				(void)fprintf(stderr, "bad time \"%s\"\n",
199 				    optarg);
200 				exit(X_STARTUP);
201 			}
202 			Tflag = 1;
203 			lastlevel = '?';
204 			break;
205 
206 		case 'u':		/* update /etc/dumpdates */
207 			uflag = 1;
208 			break;
209 
210 		case 'W':		/* what to do */
211 		case 'w':
212 			lastdump(ch);
213 			exit(X_FINOK);	/* do nothing else */
214 			break;
215 
216 		case 'a':		/* `auto-size', Write to EOM. */
217 			unlimited = 1;
218 			break;
219 
220 		default:
221 			usage();
222 		}
223 	argc -= optind;
224 	argv += optind;
225 
226 	if (argc < 1) {
227 		(void)fprintf(stderr, "Must specify disk or filesystem\n");
228 		exit(X_STARTUP);
229 	}
230 
231 	/*
232 	 *	determine if disk is a subdirectory, and setup appropriately
233 	 */
234 	dirlist = 0;
235 	toplevel = NULL;
236 	for (i = 0; i < argc; i++) {
237 		struct stat sb;
238 
239 		/* Convert potential duid into a device name */
240 		if ((diskfd = opendev(argv[i], O_RDONLY | O_NOFOLLOW, 0,
241 		    &realpath)) >= 0) {
242 			argv[i] = strdup(realpath);
243 			if (argv[i] == NULL) {
244 				msg("Cannot malloc realpath\n");
245 				exit(X_STARTUP);
246 			}
247 			(void)close(diskfd);
248 		}
249 		if (lstat(argv[i], &sb) == -1) {
250 			msg("Cannot lstat %s: %s\n", argv[i], strerror(errno));
251 			exit(X_STARTUP);
252 		}
253 		if (!S_ISDIR(sb.st_mode) && !S_ISREG(sb.st_mode))
254 			break;
255 		if (statfs(argv[i], &fsbuf) == -1) {
256 			msg("Cannot statfs %s: %s\n", argv[i], strerror(errno));
257 			exit(X_STARTUP);
258 		}
259 		if (strcmp(argv[i], fsbuf.f_mntonname) == 0) {
260 			if (dirlist != 0) {
261 				msg("Can't dump a mountpoint and a filelist\n");
262 				exit(X_STARTUP);
263 			}
264 			break;		/* exit if sole mountpoint */
265 		}
266 		if (!disk) {
267 			if ((toplevel = strdup(fsbuf.f_mntonname)) == NULL) {
268 				msg("Cannot malloc diskname\n");
269 				exit(X_STARTUP);
270 			}
271 			disk = toplevel;
272 			if (uflag) {
273 				msg("Ignoring u flag for subdir dump\n");
274 				uflag = 0;
275 			}
276 			if (level > '0') {
277 				msg("Subdir dump is done at level 0\n");
278 				level = '0';
279 			}
280 			msg("Dumping sub files/directories from %s\n", disk);
281 		} else {
282 			if (strcmp(disk, fsbuf.f_mntonname) != 0) {
283 				msg("%s is not on %s\n", argv[i], disk);
284 				exit(X_STARTUP);
285 			}
286 		}
287 		msg("Dumping file/directory %s\n", argv[i]);
288 		dirlist++;
289 	}
290 	if (dirlist == 0) {
291 		disk = *argv++;
292 		if (argc != 1) {
293 			(void)fputs("Excess arguments to dump:", stderr);
294 			while (--argc) {
295 				(void)putc(' ', stderr);
296 				(void)fputs(*argv++, stderr);
297 			}
298 			(void)putc('\n', stderr);
299 			exit(X_STARTUP);
300 		}
301 	}
302 	if (Tflag && uflag) {
303 	        (void)fprintf(stderr,
304 		    "You cannot use the T and u flags together.\n");
305 		exit(X_STARTUP);
306 	}
307 	if (strcmp(tape, "-") == 0) {
308 		pipeout++;
309 		tape = "standard output";
310 	}
311 
312 	if (blocksperfile)
313 		blocksperfile = blocksperfile / ntrec * ntrec; /* round down */
314 	else if (!unlimited) {
315 		/*
316 		 * Determine how to default tape size and density
317 		 *
318 		 *         	density				tape size
319 		 * 9-track	1600 bpi (160 bytes/.1")	2300 ft.
320 		 * 9-track	6250 bpi (625 bytes/.1")	2300 ft.
321 		 * cartridge	8000 bpi (800 bytes/.1")	1700 ft.
322 		 *						(450*4 - slop)
323 		 */
324 		if (density == 0)
325 			density = cartridge ? 100 : 160;
326 		if (tsize == 0)
327 			tsize = cartridge ? 1700L*120L : 2300L*120L;
328 	}
329 
330 	if (strchr(tape, ':')) {
331 		host = tape;
332 		tape = strchr(host, ':');
333 		*tape++ = '\0';
334 #ifdef RDUMP
335 		if (rmthost(host) == 0)
336 			exit(X_STARTUP);
337 #else
338 		(void)fprintf(stderr, "remote dump not enabled\n");
339 		exit(X_STARTUP);
340 #endif
341 	}
342 
343 	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
344 		signal(SIGHUP, sig);
345 	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
346 		signal(SIGTERM, sig);
347 	if (signal(SIGINT, interrupt) == SIG_IGN)
348 		signal(SIGINT, SIG_IGN);
349 
350 	getfstab();		/* /etc/fstab snarfed */
351 
352 	/*
353 	 *	disk can be either the full special file name,
354 	 *	the suffix of the special file name,
355 	 *	the special name missing the leading '/',
356 	 *	the file system name with or without the leading '/'.
357 	 */
358 	if (!statfs(disk, &fsbuf) && !strcmp(fsbuf.f_mntonname, disk)) {
359 		/* mounted disk? */
360 		disk = rawname(fsbuf.f_mntfromname);
361 		if (!disk) {
362 			(void)fprintf(stderr, "cannot get raw name for %s\n",
363 			    fsbuf.f_mntfromname);
364 			exit(X_STARTUP);
365 		}
366 		mount_point = fsbuf.f_mntonname;
367 		(void)strlcpy(spcl.c_dev, fsbuf.f_mntfromname,
368 		    sizeof(spcl.c_dev));
369 		if (dirlist != 0) {
370 			(void)snprintf(spcl.c_filesys, sizeof(spcl.c_filesys),
371 			    "a subset of %s", mount_point);
372 		} else {
373 			(void)strlcpy(spcl.c_filesys, mount_point,
374 			    sizeof(spcl.c_filesys));
375 		}
376 	} else if ((dt = fstabsearch(disk)) != NULL) {
377 		/* in fstab? */
378 		if (strchr(dt->fs_spec, '/')) {
379 			/* fs_spec is a /dev/something */
380 			disk = rawname(dt->fs_spec);
381 		} else {
382 			/* fs_spec is a DUID */
383 			disk = rawname(disk);
384 		}
385 		mount_point = dt->fs_file;
386 		(void)strlcpy(spcl.c_dev, dt->fs_spec, sizeof(spcl.c_dev));
387 		if (dirlist != 0) {
388 			(void)snprintf(spcl.c_filesys, sizeof(spcl.c_filesys),
389 			    "a subset of %s", mount_point);
390 		} else {
391 			(void)strlcpy(spcl.c_filesys, mount_point,
392 			    sizeof(spcl.c_filesys));
393 		}
394 	} else {
395 		/* must be a device */
396 		(void)strlcpy(spcl.c_dev, disk, sizeof(spcl.c_dev));
397 		(void)strlcpy(spcl.c_filesys, "an unlisted file system",
398 		    sizeof(spcl.c_filesys));
399 	}
400 	(void)strlcpy(spcl.c_label, "none", sizeof(spcl.c_label));
401 	(void)gethostname(spcl.c_host, sizeof(spcl.c_host));
402 	spcl.c_level = level - '0';
403 	spcl.c_type = TS_TAPE;
404 
405 	if ((diskfd = open(disk, O_RDONLY)) == -1) {
406 		msg("Cannot open %s\n", disk);
407 		exit(X_STARTUP);
408 	}
409 	if (ioctl(diskfd, DIOCGDINFO, (char *)&lab) == -1)
410 		err(1, "ioctl (DIOCGDINFO)");
411 
412 	if (memcmp(lab.d_uid, &zero_uid, sizeof(lab.d_uid)) != 0) {
413 		if (asprintf(&duid,
414 		    "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx.%c",
415 		    lab.d_uid[0], lab.d_uid[1], lab.d_uid[2], lab.d_uid[3],
416 		    lab.d_uid[4], lab.d_uid[5], lab.d_uid[6], lab.d_uid[7],
417 		    disk[strlen(disk)-1]) == -1) {
418 			msg("Cannot malloc duid\n");
419 			exit(X_STARTUP);
420 		}
421 	}
422 	if (!Tflag)
423 	        getdumptime();		/* /etc/dumpdates snarfed */
424 
425 	t = (time_t)spcl.c_date;
426 	msg("Date of this level %c dump: %s", level,
427 		t == 0 ? "the epoch\n" : ctime(&t));
428 	t = (time_t)spcl.c_ddate;
429  	msg("Date of last level %c dump: %s", lastlevel,
430 		t == 0 ? "the epoch\n" : ctime(&t));
431 	msg("Dumping %s ", disk);
432 	if (mount_point != NULL)
433 		msgtail("(%s) ", mount_point);
434 	if (host)
435 		msgtail("to %s on host %s\n", tape, host);
436 	else
437 		msgtail("to %s\n", tape);
438 
439 	if (ioctl(diskfd, DIOCGPDINFO, (char *)&lab) == -1)
440 		err(1, "ioctl (DIOCGPDINFO)");
441 	sync();
442 	sblock = (struct fs *)sblock_buf;
443 	for (i = 0; sblock_try[i] != -1; i++) {
444 		ssize_t n = pread(diskfd, sblock, SBLOCKSIZE,
445 		    (off_t)sblock_try[i]);
446 		if (n == SBLOCKSIZE && (sblock->fs_magic == FS_UFS1_MAGIC ||
447 		     (sblock->fs_magic == FS_UFS2_MAGIC &&
448 		      sblock->fs_sblockloc == sblock_try[i])) &&
449 		    sblock->fs_bsize <= MAXBSIZE &&
450 		    sblock->fs_bsize >= sizeof(struct fs))
451 			break;
452 	}
453 	if (sblock_try[i] == -1)
454 		quit("Cannot find filesystem superblock\n");
455 	tp_bshift = ffs(TP_BSIZE) - 1;
456 	if (TP_BSIZE != (1 << tp_bshift))
457 		quit("TP_BSIZE (%d) is not a power of 2\n", TP_BSIZE);
458 #ifdef FS_44INODEFMT
459 	if (sblock->fs_magic == FS_UFS2_MAGIC ||
460 	    sblock->fs_inodefmt >= FS_44INODEFMT)
461 		spcl.c_flags |= DR_NEWINODEFMT;
462 #endif
463 	maxino = (ino_t)sblock->fs_ipg * sblock->fs_ncg;
464 	mapsize = roundup(howmany(maxino, NBBY), TP_BSIZE);
465 	usedinomap = calloc((unsigned) mapsize, sizeof(char));
466 	dumpdirmap = calloc((unsigned) mapsize, sizeof(char));
467 	dumpinomap = calloc((unsigned) mapsize, sizeof(char));
468 	tapesize = 3 * (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
469 
470 	nonodump = spcl.c_level < honorlevel;
471 
472 	(void)signal(SIGINFO, statussig);
473 
474 	msg("mapping (Pass I) [regular files]\n");
475 	anydirskipped = mapfiles(maxino, &tapesize, toplevel,
476 	    (dirlist ? argv : NULL));
477 
478 	msg("mapping (Pass II) [directories]\n");
479 	while (anydirskipped) {
480 		anydirskipped = mapdirs(maxino, &tapesize);
481 	}
482 
483 	if (pipeout || unlimited) {
484 		tapesize += 10;	/* 10 trailer blocks */
485 		msg("estimated %lld tape blocks.\n", tapesize);
486 	} else {
487 		double fetapes;
488 
489 		if (blocksperfile)
490 			fetapes = (double) tapesize / blocksperfile;
491 		else if (cartridge) {
492 			/* Estimate number of tapes, assuming streaming stops at
493 			   the end of each block written, and not in mid-block.
494 			   Assume no erroneous blocks; this can be compensated
495 			   for with an artificially low tape size. */
496 			fetapes =
497 			(	  tapesize	/* blocks */
498 				* TP_BSIZE	/* bytes/block */
499 				* (1.0/density)	/* 0.1" / byte */
500 			  +
501 				  tapesize	/* blocks */
502 				* (1.0/ntrec)	/* streaming-stops per block */
503 				* 15.48		/* 0.1" / streaming-stop */
504 			) * (1.0 / tsize );	/* tape / 0.1" */
505 		} else {
506 			/* Estimate number of tapes, for old fashioned 9-track
507 			   tape */
508 			int tenthsperirg = (density == 625) ? 3 : 7;
509 			fetapes =
510 			(	  tapesize	/* blocks */
511 				* TP_BSIZE	/* bytes / block */
512 				* (1.0/density)	/* 0.1" / byte */
513 			  +
514 				  tapesize	/* blocks */
515 				* (1.0/ntrec)	/* IRG's / block */
516 				* tenthsperirg	/* 0.1" / IRG */
517 			) * (1.0 / tsize );	/* tape / 0.1" */
518 		}
519 		etapes = fetapes;		/* truncating assignment */
520 		etapes++;
521 		/* count the dumped inodes map on each additional tape */
522 		tapesize += (etapes - 1) *
523 			(howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
524 		tapesize += etapes + 10;	/* headers + 10 trailer blks */
525 		msg("estimated %lld tape blocks on %3.2f tape(s).\n",
526 		    tapesize, fetapes);
527 	}
528 
529 	/*
530 	 * Exit if user wants an estimate of blocks and # of tapes only.
531 	 */
532 	if (just_estimate)
533 		exit(X_FINOK);
534 
535 	/*
536 	 * Allocate tape buffer.
537 	 */
538 	if (!alloctape())
539 		quit("can't allocate tape buffers - try a smaller blocking factor.\n");
540 
541 	startnewtape(1);
542 	(void)time(&tstart_writing);
543 	xferrate = 0;
544 	dumpmap(usedinomap, TS_CLRI, maxino - 1);
545 
546 	msg("dumping (Pass III) [directories]\n");
547 	dirty = 0;		/* XXX just to get gcc to shut up */
548 	for (map = dumpdirmap, ino = 1; ino < maxino; ino++) {
549 		if (((ino - 1) % NBBY) == 0)	/* map is offset by 1 */
550 			dirty = *map++;
551 		else
552 			dirty >>= 1;
553 		if ((dirty & 1) == 0)
554 			continue;
555 		/*
556 		 * Skip directory inodes deleted and maybe reallocated
557 		 */
558 		dp = getino(ino, &mode);
559 		if (mode != IFDIR)
560 			continue;
561 		(void)dumpino(dp, ino);
562 	}
563 
564 	msg("dumping (Pass IV) [regular files]\n");
565 	for (map = dumpinomap, ino = 1; ino < maxino; ino++) {
566 		if (((ino - 1) % NBBY) == 0)	/* map is offset by 1 */
567 			dirty = *map++;
568 		else
569 			dirty >>= 1;
570 		if ((dirty & 1) == 0)
571 			continue;
572 		/*
573 		 * Skip inodes deleted and reallocated as directories.
574 		 */
575 		dp = getino(ino, &mode);
576 		if (mode == IFDIR)
577 			continue;
578 		(void)dumpino(dp, ino);
579 	}
580 
581 	spcl.c_type = TS_END;
582 	for (i = 0; i < ntrec; i++)
583 		writeheader(maxino - 1);
584 	if (pipeout)
585 		msg("%lld tape blocks\n", spcl.c_tapea);
586 	else
587 		msg("%lld tape blocks on %d volume%s\n",
588 		    spcl.c_tapea, spcl.c_volume,
589 		    (spcl.c_volume == 1) ? "" : "s");
590 	t = (time_t)spcl.c_date;
591 	msg("Date of this level %c dump: %s", level,
592 	    t == 0 ? "the epoch\n" : ctime(&t));
593 	t = do_stats();
594 	msg("Date this dump completed:  %s", ctime(&t));
595 	msg("Average transfer rate: %ld KB/s\n", xferrate / tapeno);
596 	putdumptime();
597 	trewind();
598 	broadcast("DUMP IS DONE!\7\7\n");
599 	msg("DUMP IS DONE\n");
600 	Exit(X_FINOK);
601 	/* NOTREACHED */
602 }
603 
604 static void
605 usage(void)
606 {
607 	extern char *__progname;
608 
609 	(void)fprintf(stderr, "usage: %s [-0123456789acnSuWw] [-B records] "
610 		      "[-b blocksize] [-d density]\n"
611 		      "\t[-f file] [-h level] [-s feet] "
612 		      "[-T date] files-to-dump\n",
613 		      __progname);
614 	exit(X_STARTUP);
615 }
616 
617 /*
618  * Pick up a numeric argument.  It must be nonnegative and in the given
619  * range (except that a vmax of 0 means unlimited).
620  */
621 static long long
622 numarg(char *meaning, long long vmin, long long vmax)
623 {
624 	long long val;
625 	const char *errstr;
626 
627 	if (vmax == 0)
628 		vmax = LLONG_MAX;
629 	val = strtonum(optarg, vmin, vmax, &errstr);
630 	if (errstr)
631 		errx(X_STARTUP, "%s is %s [%lld - %lld]",
632 		    meaning, errstr, vmin, vmax);
633 
634 	return (val);
635 }
636 
637 void
638 sig(int signo)
639 {
640 	switch(signo) {
641 	case SIGALRM:
642 	case SIGHUP:
643 	case SIGTERM:
644 		/* XXX signal race */
645 		if (pipeout)
646 			quit("Signal on pipe: cannot recover\n");
647 		msg("Rewriting attempted as response to unknown signal.\n");
648 		(void)fflush(stderr);
649 		(void)fflush(stdout);
650 		close_rewind();
651 		exit(X_REWRITE);
652 		/* NOTREACHED */
653 	}
654 }
655 
656 char *
657 rawname(char *cp)
658 {
659 	static char rawbuf[PATH_MAX];
660 	char *dp = strrchr(cp, '/');
661 	char *prefix;
662 
663 	if (dp == NULL)
664 		return (NULL);
665 	prefix = dp[1] == 'r' ? "" : "r";
666 	*dp = '\0';
667 	(void)snprintf(rawbuf, sizeof(rawbuf), "%s/%s%s", cp, prefix, dp + 1);
668 	*dp = '/';
669 	return (rawbuf);
670 }
671 
672 char *
673 getduid(char *path)
674 {
675 	int fd;
676 	struct disklabel lab;
677 	u_int64_t zero_uid = 0;
678 	char *duid;
679 
680 	if ((fd = opendev(path, O_RDONLY | O_NOFOLLOW, 0, NULL)) >= 0) {
681 		if (ioctl(fd, DIOCGDINFO, (char *)&lab) == -1) {
682 			close(fd);
683 			warn("ioctl(DIOCGDINFO)");
684 			return (NULL);
685 		}
686 		close(fd);
687 
688 		if (memcmp(lab.d_uid, &zero_uid, sizeof(lab.d_uid)) != 0) {
689 			if (asprintf(&duid,
690 			    "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx.%c",
691 			    lab.d_uid[0], lab.d_uid[1], lab.d_uid[2],
692 			    lab.d_uid[3], lab.d_uid[4], lab.d_uid[5],
693 			    lab.d_uid[6], lab.d_uid[7],
694 			    path[strlen(path)-1]) == -1) {
695 				warn("Cannot malloc duid");
696 				return (NULL);
697 			}
698 			return (duid);
699 		}
700 	}
701 
702 	return (NULL);
703 }
704 
705 /*
706  * obsolete --
707  *	Change set of key letters and ordered arguments into something
708  *	getopt(3) will like.
709  */
710 static void
711 obsolete(int *argcp, char **argvp[])
712 {
713 	int argc, flags;
714 	char *ap, **argv, *flagsp, **nargv, *p;
715 	size_t len;
716 
717 	/* Setup. */
718 	argv = *argvp;
719 	argc = *argcp;
720 
721 	/* Return if no arguments or first argument has leading dash. */
722 	ap = argv[1];
723 	if (argc == 1 || *ap == '-')
724 		return;
725 
726 	/* Allocate space for new arguments. */
727 	if ((*argvp = nargv = calloc(argc + 1, sizeof(char *))) == NULL ||
728 	    (p = flagsp = malloc(strlen(ap) + 2)) == NULL)
729 		err(1, NULL);
730 
731 	*nargv++ = *argv;
732 	argv += 2;
733 
734 	for (flags = 0; *ap; ++ap) {
735 		switch (*ap) {
736 		case 'B':
737 		case 'b':
738 		case 'd':
739 		case 'f':
740 		case 'h':
741 		case 's':
742 		case 'T':
743 			if (*argv == NULL) {
744 				warnx("option requires an argument -- %c", *ap);
745 				usage();
746 			}
747 			len = 2 + strlen(*argv) + 1;
748 			if ((nargv[0] = malloc(len)) == NULL)
749 				err(1, NULL);
750 			nargv[0][0] = '-';
751 			nargv[0][1] = *ap;
752 			(void)strlcpy(&nargv[0][2], *argv, len - 2);
753 			++argv;
754 			++nargv;
755 			break;
756 		default:
757 			if (!flags) {
758 				*p++ = '-';
759 				flags = 1;
760 			}
761 			*p++ = *ap;
762 			break;
763 		}
764 	}
765 
766 	/* Terminate flags, or toss the buffer we did not use. */
767 	if (flags) {
768 		*p = '\0';
769 		*nargv++ = flagsp;
770 	} else
771 		free(flagsp);
772 
773 	/* Copy remaining arguments. */
774 	while ((*nargv++ = *argv++))
775 		continue;
776 
777 	/* Update argument count. */
778 	*argcp = nargv - *argvp - 1;
779 }
780