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