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