xref: /freebsd/sbin/dump/main.c (revision 3e0f6b97b257a96f7275e4442204263e44b16686)
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 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 static char sccsid[] = "@(#)main.c	8.4 (Berkeley) 4/15/94";
42 #endif /* not lint */
43 
44 #include <sys/param.h>
45 #include <sys/time.h>
46 #ifdef sunos
47 #include <sys/vnode.h>
48 
49 #include <ufs/inode.h>
50 #include <ufs/fs.h>
51 #else
52 #include <ufs/ffs/fs.h>
53 #include <ufs/ufs/dinode.h>
54 #endif
55 
56 #include <protocols/dumprestore.h>
57 
58 #include <ctype.h>
59 #include <errno.h>
60 #include <fcntl.h>
61 #include <fstab.h>
62 #include <signal.h>
63 #include <stdio.h>
64 #ifdef __STDC__
65 #include <stdlib.h>
66 #include <string.h>
67 #include <unistd.h>
68 #endif
69 
70 #include "dump.h"
71 #include "pathnames.h"
72 
73 #ifndef SBOFF
74 #define SBOFF (SBLOCK * DEV_BSIZE)
75 #endif
76 
77 int	notify = 0;	/* notify operator flag */
78 int	blockswritten = 0;	/* number of blocks written on current tape */
79 int	tapeno = 0;	/* current tape number */
80 int	density = 0;	/* density in bytes/0.1" " <- this is for hilit19 */
81 int	ntrec = NTREC;	/* # tape blocks in each tape record */
82 int	cartridge = 0;	/* Assume non-cartridge tape */
83 long	dev_bsize = 1;	/* recalculated below */
84 long	blocksperfile;	/* output blocks per file */
85 char	*host = NULL;	/* remote host (if any) */
86 
87 static long numarg __P((int, char *, long, long, int *, char ***));
88 static void missingarg __P((int, char *)) __dead2;
89 
90 int
91 main(argc, argv)
92 	int argc;
93 	char **argv;
94 {
95 	register ino_t ino;
96 	register int dirty;
97 	register struct dinode *dp;
98 	register struct	fstab *dt;
99 	register char *map;
100 	register char *cp;
101 	int i, anydirskipped, bflag = 0, Tflag = 0, honorlevel = 1;
102 	ino_t maxino;
103 
104 	spcl.c_date = 0;
105 	(void)time((time_t *)&spcl.c_date);
106 
107 	tsize = 0;	/* Default later, based on 'c' option for cart tapes */
108 	if ((tape = getenv("TAPE")) == NULL)
109 		tape = _PATH_DEFTAPE;
110 	dumpdates = _PATH_DUMPDATES;
111 	temp = _PATH_DTMP;
112 	if (TP_BSIZE / DEV_BSIZE == 0 || TP_BSIZE % DEV_BSIZE != 0)
113 		quit("TP_BSIZE must be a multiple of DEV_BSIZE\n");
114 	level = '0';
115 	if (argc == 1) {
116 		(void) fprintf(stderr, "Must specify a key.\n");
117 		Exit(X_ABORT);
118 	}
119 	argv++;
120 	argc -= 2;
121 	for (cp = *argv++; cp != NULL && *cp != '\0'; cp++) {
122 		switch (*cp) {
123 		case '-':
124 			break;
125 
126 		case 'w':
127 			lastdump('w');	/* tell us only what has to be done */
128 			exit(0);
129 
130 		case 'W':		/* what to do */
131 			lastdump('W');	/* tell us state of what is done */
132 			exit(0);	/* do nothing else */
133 
134 		case 'f':		/* output file */
135 			if (argc < 1)
136 				missingarg('f', "output file");
137 			tape = *argv++;
138 			argc--;
139 			break;
140 
141 		case 'd':		/* density, in bits per inch */
142 			density = numarg('d', "density",
143 			    10L, 327670L, &argc, &argv) / 10;
144 			if (density >= 625 && !bflag)
145 				ntrec = HIGHDENSITYTREC;
146 			break;
147 
148 		case 's':		/* tape size, feet */
149 			tsize = numarg('s', "size",
150 			    1L, 0L, &argc, &argv) * 12 * 10;
151 			break;
152 
153 		case 'T':		/* time of last dump */
154 			if (argc < 1)
155 				missingarg('T', "time of last dump");
156 			spcl.c_ddate = unctime(*argv);
157 			if (spcl.c_ddate < 0) {
158 				(void)fprintf(stderr, "bad time \"%s\"\n",
159 				    *argv);
160 				exit(X_ABORT);
161 			}
162 			Tflag = 1;
163 			lastlevel = '?';
164 			argc--;
165 			argv++;
166 			break;
167 
168 		case 'b':		/* blocks per tape write */
169 			ntrec = numarg('b', "number of blocks per write",
170 			    1L, 1000L, &argc, &argv);
171 			/*
172 			 * XXX
173 			 * physio(9) currently slices all requests to
174 			 * 64 KB chunks.  So now, if somebody entered
175 			 * e.g. 96 KB block size here, he would effectively
176 			 * yield one 64 KB and one 32 KB block, which
177 			 * restore cannot handle.
178 			 * Thus we currently enforce pyhsio(9)'s limit
179 			 * here, too.
180 			 */
181 			if ( ntrec > 64 ) {
182 				msg("please choose a blocksize <= 64\n");
183 				exit(X_ABORT);
184 			}
185 			break;
186 
187 		case 'B':		/* blocks per output file */
188 			blocksperfile = numarg('B', "number of blocks per file",
189 			    1L, 0L, &argc, &argv);
190 			break;
191 
192 		case 'c':		/* Tape is cart. not 9-track */
193 			cartridge = 1;
194 			break;
195 
196 		case 'a':		/* `auto-size', Write to EOM. */
197 			unlimited = 1;
198 			break;
199 
200 		/* dump level */
201 		case '0': case '1': case '2': case '3': case '4':
202 		case '5': case '6': case '7': case '8': case '9':
203 			level = *cp;
204 			break;
205 
206 		case 'u':		/* update /etc/dumpdates */
207 			uflag = 1;
208 			break;
209 
210 		case 'n':		/* notify operators */
211 			notify = 1;
212 			break;
213 
214 		case 'h':
215 			honorlevel = numarg('h', "honor level",
216 			    0L, 10L, &argc, &argv);
217 			break;
218 
219 		default:
220 			(void)fprintf(stderr, "bad key '%c'\n", *cp);
221 			exit(X_ABORT);
222 		}
223 	}
224 	if (argc < 1) {
225 		(void)fprintf(stderr, "Must specify disk or filesystem\n");
226 		exit(X_ABORT);
227 	}
228 	disk = *argv++;
229 	argc--;
230 	if (argc >= 1) {
231 		(void)fprintf(stderr, "Unknown arguments to dump:");
232 		while (argc--)
233 			(void)fprintf(stderr, " %s", *argv++);
234 		(void)fprintf(stderr, "\n");
235 		exit(X_ABORT);
236 	}
237 	if (Tflag && uflag) {
238 	        (void)fprintf(stderr,
239 		    "You cannot use the T and u flags together.\n");
240 		exit(X_ABORT);
241 	}
242 	if (strcmp(tape, "-") == 0) {
243 		pipeout++;
244 		tape = "standard output";
245 	}
246 
247 	if (blocksperfile)
248 		blocksperfile = blocksperfile / ntrec * ntrec; /* round down */
249 	else if (!unlimited) {
250 		/*
251 		 * Determine how to default tape size and density
252 		 *
253 		 *         	density				tape size
254 		 * 9-track	1600 bpi (160 bytes/.1")	2300 ft.
255 		 * 9-track	6250 bpi (625 bytes/.1")	2300 ft.
256 		 * cartridge	8000 bpi (100 bytes/.1")	1700 ft.
257 		 *						(450*4 - slop)
258 		 * hilit19 hits again: "
259 		 */
260 		if (density == 0)
261 			density = cartridge ? 100 : 160;
262 		if (tsize == 0)
263 			tsize = cartridge ? 1700L*120L : 2300L*120L;
264 	}
265 
266 	if (index(tape, ':')) {
267 		host = tape;
268 		tape = index(host, ':');
269 		*tape++ = '\0';
270 #ifdef RDUMP
271 		if (index(tape, '\n')) {
272 		    (void)fprintf(stderr, "invalid characters in tape\n");
273 		    exit(X_ABORT);
274 		}
275 		if (rmthost(host) == 0)
276 			exit(X_ABORT);
277 #else
278 		(void)fprintf(stderr, "remote dump not enabled\n");
279 		exit(X_ABORT);
280 #endif
281 	}
282 	(void)setuid(getuid()); /* rmthost() is the only reason to be setuid */
283 
284 	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
285 		signal(SIGHUP, sig);
286 	if (signal(SIGTRAP, SIG_IGN) != SIG_IGN)
287 		signal(SIGTRAP, sig);
288 	if (signal(SIGFPE, SIG_IGN) != SIG_IGN)
289 		signal(SIGFPE, sig);
290 	if (signal(SIGBUS, SIG_IGN) != SIG_IGN)
291 		signal(SIGBUS, sig);
292 	if (signal(SIGSEGV, SIG_IGN) != SIG_IGN)
293 		signal(SIGSEGV, sig);
294 	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
295 		signal(SIGTERM, sig);
296 	if (signal(SIGINT, interrupt) == SIG_IGN)
297 		signal(SIGINT, SIG_IGN);
298 
299 	set_operators();	/* /etc/group snarfed */
300 	getfstab();		/* /etc/fstab snarfed */
301 	/*
302 	 *	disk can be either the full special file name,
303 	 *	the suffix of the special file name,
304 	 *	the special name missing the leading '/',
305 	 *	the file system name with or without the leading '/'.
306 	 */
307 	dt = fstabsearch(disk);
308 	if (dt != NULL) {
309 		disk = rawname(dt->fs_spec);
310 		(void)strncpy(spcl.c_dev, dt->fs_spec, NAMELEN);
311 		(void)strncpy(spcl.c_filesys, dt->fs_file, NAMELEN);
312 	} else {
313 		(void)strncpy(spcl.c_dev, disk, NAMELEN);
314 		(void)strncpy(spcl.c_filesys, "an unlisted file system",
315 		    NAMELEN);
316 	}
317 	spcl.c_dev[NAMELEN-1]='\0';
318 	spcl.c_filesys[NAMELEN-1]='\0';
319 	(void)strcpy(spcl.c_label, "none");
320 	(void)gethostname(spcl.c_host, NAMELEN);
321 	spcl.c_level = level - '0';
322 	spcl.c_type = TS_TAPE;
323 	if (!Tflag)
324 	        getdumptime();		/* /etc/dumpdates snarfed */
325 
326 	msg("Date of this level %c dump: %s", level,
327 		spcl.c_date == 0 ? "the epoch\n" : ctime(&spcl.c_date));
328  	msg("Date of last level %c dump: %s", lastlevel,
329 		spcl.c_ddate == 0 ? "the epoch\n" : ctime(&spcl.c_ddate));
330 	msg("Dumping %s ", disk);
331 	if (dt != NULL)
332 		msgtail("(%s) ", dt->fs_file);
333 	if (host)
334 		msgtail("to %s on host %s\n", tape, host);
335 	else
336 		msgtail("to %s\n", tape);
337 
338 	if ((diskfd = open(disk, O_RDONLY)) < 0) {
339 		msg("Cannot open %s\n", disk);
340 		exit(X_ABORT);
341 	}
342 	sync();
343 	sblock = (struct fs *)sblock_buf;
344 	bread(SBOFF, (char *) sblock, SBSIZE);
345 	if (sblock->fs_magic != FS_MAGIC)
346 		quit("bad sblock magic number\n");
347 	dev_bsize = sblock->fs_fsize / fsbtodb(sblock, 1);
348 	dev_bshift = ffs(dev_bsize) - 1;
349 	if (dev_bsize != (1 << dev_bshift))
350 		quit("dev_bsize (%d) is not a power of 2", dev_bsize);
351 	tp_bshift = ffs(TP_BSIZE) - 1;
352 	if (TP_BSIZE != (1 << tp_bshift))
353 		quit("TP_BSIZE (%d) is not a power of 2", TP_BSIZE);
354 #ifdef FS_44INODEFMT
355 	if (sblock->fs_inodefmt >= FS_44INODEFMT)
356 		spcl.c_flags |= DR_NEWINODEFMT;
357 #endif
358 	maxino = sblock->fs_ipg * sblock->fs_ncg;
359 	mapsize = roundup(howmany(maxino, NBBY), TP_BSIZE);
360 	usedinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
361 	dumpdirmap = (char *)calloc((unsigned) mapsize, sizeof(char));
362 	dumpinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
363 	tapesize = 3 * (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
364 
365 	nonodump = spcl.c_level < honorlevel;
366 
367 	msg("mapping (Pass I) [regular files]\n");
368 	anydirskipped = mapfiles(maxino, &tapesize);
369 
370 	msg("mapping (Pass II) [directories]\n");
371 	while (anydirskipped) {
372 		anydirskipped = mapdirs(maxino, &tapesize);
373 	}
374 
375 	if (pipeout || unlimited) {
376 		tapesize += 10;	/* 10 trailer blocks */
377 		msg("estimated %ld tape blocks.\n", tapesize);
378 	} else {
379 		double fetapes;
380 
381 		if (blocksperfile)
382 			fetapes = (double) tapesize / blocksperfile;
383 		else if (cartridge) {
384 			/* Estimate number of tapes, assuming streaming stops at
385 			   the end of each block written, and not in mid-block.
386 			   Assume no erroneous blocks; this can be compensated
387 			   for with an artificially low tape size. */
388 			fetapes =
389 			(	  (double) tapesize	/* blocks */
390 				* TP_BSIZE	/* bytes/block */
391 				* (1.0/density)	/* 0.1" / byte " */
392 			  +
393 				  (double) tapesize	/* blocks */
394 				* (1.0/ntrec)	/* streaming-stops per block */
395 				* 15.48		/* 0.1" / streaming-stop " */
396 			) * (1.0 / tsize );	/* tape / 0.1" " */
397 		} else {
398 			/* Estimate number of tapes, for old fashioned 9-track
399 			   tape */
400 			int tenthsperirg = (density == 625) ? 3 : 7;
401 			fetapes =
402 			(	  (double) tapesize	/* blocks */
403 				* TP_BSIZE	/* bytes / block */
404 				* (1.0/density)	/* 0.1" / byte " */
405 			  +
406 				  (double) tapesize	/* blocks */
407 				* (1.0/ntrec)	/* IRG's / block */
408 				* tenthsperirg	/* 0.1" / IRG " */
409 			) * (1.0 / tsize );	/* tape / 0.1" " */
410 		}
411 		etapes = fetapes;		/* truncating assignment */
412 		etapes++;
413 		/* count the dumped inodes map on each additional tape */
414 		tapesize += (etapes - 1) *
415 			(howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
416 		tapesize += etapes + 10;	/* headers + 10 trailer blks */
417 		msg("estimated %ld tape blocks on %3.2f tape(s).\n",
418 		    tapesize, fetapes);
419 	}
420 
421 	/*
422 	 * Allocate tape buffer.
423 	 */
424 	if (!alloctape())
425 		quit("can't allocate tape buffers - try a smaller blocking factor.\n");
426 
427 	startnewtape(1);
428 	(void)time((time_t *)&(tstart_writing));
429 	dumpmap(usedinomap, TS_CLRI, maxino - 1);
430 
431 	msg("dumping (Pass III) [directories]\n");
432 	dirty = 0;		/* XXX just to get gcc to shut up */
433 	for (map = dumpdirmap, ino = 1; ino < maxino; ino++) {
434 		if (((ino - 1) % NBBY) == 0)	/* map is offset by 1 */
435 			dirty = *map++;
436 		else
437 			dirty >>= 1;
438 		if ((dirty & 1) == 0)
439 			continue;
440 		/*
441 		 * Skip directory inodes deleted and maybe reallocated
442 		 */
443 		dp = getino(ino);
444 		if ((dp->di_mode & IFMT) != IFDIR)
445 			continue;
446 		(void)dumpino(dp, ino);
447 	}
448 
449 	msg("dumping (Pass IV) [regular files]\n");
450 	for (map = dumpinomap, ino = 1; ino < maxino; ino++) {
451 		int mode;
452 
453 		if (((ino - 1) % NBBY) == 0)	/* map is offset by 1 */
454 			dirty = *map++;
455 		else
456 			dirty >>= 1;
457 		if ((dirty & 1) == 0)
458 			continue;
459 		/*
460 		 * Skip inodes deleted and reallocated as directories.
461 		 */
462 		dp = getino(ino);
463 		mode = dp->di_mode & IFMT;
464 		if (mode == IFDIR)
465 			continue;
466 		(void)dumpino(dp, ino);
467 	}
468 
469 	(void)time((time_t *)&(tend_writing));
470 	spcl.c_type = TS_END;
471 	for (i = 0; i < ntrec; i++)
472 		writeheader(maxino - 1);
473 	if (pipeout)
474 		msg("DUMP: %ld tape blocks\n", spcl.c_tapea);
475 	else
476 		msg("DUMP: %ld tape blocks on %d volumes(s)\n",
477 		    spcl.c_tapea, spcl.c_volume);
478 
479 	/* report dump performance, avoid division through zero */
480 	if (tend_writing - tstart_writing == 0)
481 		msg("finished in less than a second\n");
482 	else
483 		msg("finished in %d seconds, throughput %d KBytes/sec\n",
484 		    tend_writing - tstart_writing,
485 		    spcl.c_tapea / (tend_writing - tstart_writing));
486 
487 	putdumptime();
488 	trewind();
489 	broadcast("DUMP IS DONE!\7\7\n");
490 	msg("DUMP IS DONE\n");
491 	Exit(X_FINOK);
492 	/* NOTREACHED */
493 }
494 
495 /*
496  * Pick up a numeric argument.  It must be nonnegative and in the given
497  * range (except that a vmax of 0 means unlimited).
498  */
499 static long
500 numarg(letter, meaning, vmin, vmax, pargc, pargv)
501 	int letter;
502 	char *meaning;
503 	long vmin, vmax;
504 	int *pargc;
505 	char ***pargv;
506 {
507 	register char *p;
508 	long val;
509 	char *str;
510 
511 	if (--*pargc < 0)
512 		missingarg(letter, meaning);
513 	str = *(*pargv)++;
514 	for (p = str; *p; p++)
515 		if (!isdigit(*p))
516 			goto bad;
517 	val = atol(str);
518 	if (val < vmin || (vmax && val > vmax))
519 		goto bad;
520 	return (val);
521 
522 bad:
523 	(void)fprintf(stderr, "bad '%c' (%s) value \"%s\"\n",
524 	    letter, meaning, str);
525 	exit(X_ABORT);
526 }
527 
528 static void
529 missingarg(letter, meaning)
530 	int letter;
531 	char *meaning;
532 {
533 
534 	(void)fprintf(stderr, "The '%c' flag (%s) requires an argument\n",
535 	    letter, meaning);
536 	exit(X_ABORT);
537 }
538 
539 void
540 sig(signo)
541 	int signo;
542 {
543 	switch(signo) {
544 	case SIGALRM:
545 	case SIGBUS:
546 	case SIGFPE:
547 	case SIGHUP:
548 	case SIGTERM:
549 	case SIGTRAP:
550 		if (pipeout)
551 			quit("Signal on pipe: cannot recover\n");
552 		msg("Rewriting attempted as response to unknown signal.\n");
553 		(void)fflush(stderr);
554 		(void)fflush(stdout);
555 		close_rewind();
556 		exit(X_REWRITE);
557 		/* NOTREACHED */
558 	case SIGSEGV:
559 		msg("SIGSEGV: ABORTING!\n");
560 		(void)signal(SIGSEGV, SIG_DFL);
561 		(void)kill(0, SIGSEGV);
562 		/* NOTREACHED */
563 	}
564 }
565 
566 char *
567 rawname(cp)
568 	char *cp;
569 {
570 	static char rawbuf[MAXPATHLEN];
571 	char *dp = rindex(cp, '/');
572 
573 	if (dp == NULL)
574 		return (NULL);
575 	*dp = '\0';
576 	(void)strncpy(rawbuf, cp, MAXPATHLEN - 1);
577 	rawbuf[MAXPATHLEN-1] = '\0';
578 	*dp = '/';
579 	(void)strncat(rawbuf, "/r", MAXPATHLEN - 1 - strlen(rawbuf));
580 	(void)strncat(rawbuf, dp + 1, MAXPATHLEN - 1 - strlen(rawbuf));
581 	return (rawbuf);
582 }
583 
584 #ifdef sunos
585 const char *
586 strerror(errnum)
587 	int errnum;
588 {
589 	extern int sys_nerr;
590 	extern const char *const sys_errlist[];
591 
592 	if (errnum < sys_nerr)
593 		return (sys_errlist[errnum]);
594 	else
595 		return ("bogus errno in strerror");
596 }
597 #endif
598