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