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