xref: /freebsd/sbin/restore/tape.c (revision b00ab754)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1983, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #ifndef lint
38 #if 0
39 static char sccsid[] = "@(#)tape.c	8.9 (Berkeley) 5/1/95";
40 #endif
41 #endif /* not lint */
42 
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45 
46 #include <sys/param.h>
47 #include <sys/file.h>
48 #include <sys/mtio.h>
49 #include <sys/stat.h>
50 #include <sys/time.h>
51 #include <sys/extattr.h>
52 #include <sys/acl.h>
53 
54 #include <ufs/ufs/extattr.h>
55 #include <ufs/ufs/dinode.h>
56 #include <protocols/dumprestore.h>
57 
58 #include <errno.h>
59 #include <limits.h>
60 #include <paths.h>
61 #include <setjmp.h>
62 #include <stdint.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <time.h>
67 #include <timeconv.h>
68 #include <unistd.h>
69 
70 #include "restore.h"
71 #include "extern.h"
72 
73 static long	fssize = MAXBSIZE;
74 static int	mt = -1;
75 static int	pipein = 0;
76 static int	pipecmdin = 0;
77 static FILE	*popenfp = NULL;
78 static char	*magtape;
79 static int	blkcnt;
80 static int	numtrec;
81 static char	*tapebuf;
82 static union	u_spcl endoftapemark;
83 static long	byteslide = 0;
84 static long	blksread;		/* blocks read since last header */
85 static int64_t	tapeaddr = 0;		/* current TP_BSIZE tape record */
86 static long	tapesread;
87 static jmp_buf	restart;
88 static int	gettingfile = 0;	/* restart has a valid frame */
89 static char	*host = NULL;
90 static int	readmapflag;
91 
92 static int	ofile;
93 static char	*map;
94 static char	lnkbuf[MAXPATHLEN + 1];
95 static int	pathlen;
96 
97 int		Bcvt;		/* Swap Bytes */
98 int		oldinofmt;	/* FreeBSD 1 inode format needs cvt */
99 
100 #define	FLUSHTAPEBUF()	blkcnt = ntrec + 1
101 
102 char *namespace_names[] = EXTATTR_NAMESPACE_NAMES;
103 
104 static void	 accthdr(struct s_spcl *);
105 static int	 checksum(int *);
106 static void	 findinode(struct s_spcl *);
107 static void	 findtapeblksize(void);
108 static char	*setupextattr(int);
109 static void	 xtrattr(char *, size_t);
110 static void	 skiphole(void (*)(char *, size_t), size_t *);
111 static int	 gethead(struct s_spcl *);
112 static void	 readtape(char *);
113 static void	 setdumpnum(void);
114 static u_long	 swabl(u_long);
115 static u_char	*swablong(u_char *, int);
116 static u_char	*swabshort(u_char *, int);
117 static void	 terminateinput(void);
118 static void	 xtrfile(char *, size_t);
119 static void	 xtrlnkfile(char *, size_t);
120 static void	 xtrlnkskip(char *, size_t);
121 static void	 xtrmap(char *, size_t);
122 static void	 xtrmapskip(char *, size_t);
123 static void	 xtrskip(char *, size_t);
124 
125 /*
126  * Set up an input source
127  */
128 void
129 setinput(char *source, int ispipecommand)
130 {
131 	FLUSHTAPEBUF();
132 	if (bflag)
133 		newtapebuf(ntrec);
134 	else
135 		newtapebuf(MAX(NTREC, HIGHDENSITYTREC));
136 	terminal = stdin;
137 
138 	if (ispipecommand)
139 		pipecmdin++;
140 	else
141 #ifdef RRESTORE
142 	if (strchr(source, ':')) {
143 		host = source;
144 		source = strchr(host, ':');
145 		*source++ = '\0';
146 		if (rmthost(host) == 0)
147 			done(1);
148 	} else
149 #endif
150 	if (strcmp(source, "-") == 0) {
151 		/*
152 		 * Since input is coming from a pipe we must establish
153 		 * our own connection to the terminal.
154 		 */
155 		terminal = fopen(_PATH_TTY, "r");
156 		if (terminal == NULL) {
157 			(void)fprintf(stderr, "cannot open %s: %s\n",
158 			    _PATH_TTY, strerror(errno));
159 			terminal = fopen(_PATH_DEVNULL, "r");
160 			if (terminal == NULL) {
161 				(void)fprintf(stderr, "cannot open %s: %s\n",
162 				    _PATH_DEVNULL, strerror(errno));
163 				done(1);
164 			}
165 		}
166 		pipein++;
167 	}
168 	/* no longer need or want root privileges */
169 	if (setuid(getuid()) != 0) {
170 		fprintf(stderr, "setuid failed\n");
171 		done(1);
172 	}
173 	magtape = strdup(source);
174 	if (magtape == NULL) {
175 		fprintf(stderr, "Cannot allocate space for magtape buffer\n");
176 		done(1);
177 	}
178 }
179 
180 void
181 newtapebuf(long size)
182 {
183 	static int tapebufsize = -1;
184 
185 	ntrec = size;
186 	if (size <= tapebufsize)
187 		return;
188 	if (tapebuf != NULL)
189 		free(tapebuf - TP_BSIZE);
190 	tapebuf = malloc((size+1) * TP_BSIZE);
191 	if (tapebuf == NULL) {
192 		fprintf(stderr, "Cannot allocate space for tape buffer\n");
193 		done(1);
194 	}
195 	tapebuf += TP_BSIZE;
196 	tapebufsize = size;
197 }
198 
199 /*
200  * Verify that the tape drive can be accessed and
201  * that it actually is a dump tape.
202  */
203 void
204 setup(void)
205 {
206 	int i, j, *ip;
207 	struct stat stbuf;
208 
209 	vprintf(stdout, "Verify tape and initialize maps\n");
210 	if (pipecmdin) {
211 		if (setenv("RESTORE_VOLUME", "1", 1) == -1) {
212 			fprintf(stderr, "Cannot set $RESTORE_VOLUME: %s\n",
213 			    strerror(errno));
214 			done(1);
215 		}
216 		popenfp = popen(magtape, "r");
217 		mt = popenfp ? fileno(popenfp) : -1;
218 	} else
219 #ifdef RRESTORE
220 	if (host)
221 		mt = rmtopen(magtape, 0);
222 	else
223 #endif
224 	if (pipein)
225 		mt = 0;
226 	else
227 		mt = open(magtape, O_RDONLY, 0);
228 	if (mt < 0) {
229 		fprintf(stderr, "%s: %s\n", magtape, strerror(errno));
230 		done(1);
231 	}
232 	volno = 1;
233 	setdumpnum();
234 	FLUSHTAPEBUF();
235 	if (!pipein && !pipecmdin && !bflag)
236 		findtapeblksize();
237 	if (gethead(&spcl) == FAIL) {
238 		fprintf(stderr, "Tape is not a dump tape\n");
239 		done(1);
240 	}
241 	if (pipein) {
242 		endoftapemark.s_spcl.c_magic = FS_UFS2_MAGIC;
243 		endoftapemark.s_spcl.c_type = TS_END;
244 		ip = (int *)&endoftapemark;
245 		j = sizeof(union u_spcl) / sizeof(int);
246 		i = 0;
247 		do
248 			i += *ip++;
249 		while (--j);
250 		endoftapemark.s_spcl.c_checksum = CHECKSUM - i;
251 	}
252 	if (vflag || command == 't')
253 		printdumpinfo();
254 	dumptime = _time64_to_time(spcl.c_ddate);
255 	dumpdate = _time64_to_time(spcl.c_date);
256 	if (stat(".", &stbuf) < 0) {
257 		fprintf(stderr, "cannot stat .: %s\n", strerror(errno));
258 		done(1);
259 	}
260 	if (stbuf.st_blksize > 0 && stbuf.st_blksize < TP_BSIZE )
261 		fssize = TP_BSIZE;
262 	if (stbuf.st_blksize >= TP_BSIZE && stbuf.st_blksize <= MAXBSIZE)
263 		fssize = stbuf.st_blksize;
264 	if (((TP_BSIZE - 1) & stbuf.st_blksize) != 0) {
265 		fprintf(stderr, "Warning: filesystem with non-multiple-of-%d "
266 		    "blocksize (%d);\n", TP_BSIZE, stbuf.st_blksize);
267 		fssize = roundup(fssize, TP_BSIZE);
268 		fprintf(stderr, "\twriting using blocksize %ld\n", fssize);
269 	}
270 	if (spcl.c_volume != 1) {
271 		fprintf(stderr, "Tape is not volume 1 of the dump\n");
272 		done(1);
273 	}
274 	if (gethead(&spcl) == FAIL) {
275 		dprintf(stdout, "header read failed at %ld blocks\n", blksread);
276 		panic("no header after volume mark!\n");
277 	}
278 	findinode(&spcl);
279 	if (spcl.c_type != TS_CLRI) {
280 		fprintf(stderr, "Cannot find file removal list\n");
281 		done(1);
282 	}
283 	maxino = (spcl.c_count * TP_BSIZE * NBBY) + 1;
284 	dprintf(stdout, "maxino = %ju\n", (uintmax_t)maxino);
285 	map = calloc((unsigned)1, (unsigned)howmany(maxino, NBBY));
286 	if (map == NULL)
287 		panic("no memory for active inode map\n");
288 	usedinomap = map;
289 	curfile.action = USING;
290 	getfile(xtrmap, xtrmapskip, xtrmapskip);
291 	if (spcl.c_type != TS_BITS) {
292 		fprintf(stderr, "Cannot find file dump list\n");
293 		done(1);
294 	}
295 	map = calloc((unsigned)1, (unsigned)howmany(maxino, NBBY));
296 	if (map == (char *)NULL)
297 		panic("no memory for file dump list\n");
298 	dumpmap = map;
299 	curfile.action = USING;
300 	getfile(xtrmap, xtrmapskip, xtrmapskip);
301 	/*
302 	 * If there may be whiteout entries on the tape, pretend that the
303 	 * whiteout inode exists, so that the whiteout entries can be
304 	 * extracted.
305 	 */
306 	SETINO(UFS_WINO, dumpmap);
307 	/* 'r' restores don't call getvol() for tape 1, so mark it as read. */
308 	if (command == 'r')
309 		tapesread = 1;
310 }
311 
312 /*
313  * Prompt user to load a new dump volume.
314  * "Nextvol" is the next suggested volume to use.
315  * This suggested volume is enforced when doing full
316  * or incremental restores, but can be overridden by
317  * the user when only extracting a subset of the files.
318  */
319 void
320 getvol(long nextvol)
321 {
322 	int64_t prevtapea;
323 	long i, newvol, savecnt;
324 	union u_spcl tmpspcl;
325 #	define tmpbuf tmpspcl.s_spcl
326 	char buf[TP_BSIZE];
327 
328 	if (nextvol == 1) {
329 		tapesread = 0;
330 		gettingfile = 0;
331 	}
332 	prevtapea = tapeaddr;
333 	savecnt = blksread;
334 	if (pipein) {
335 		if (nextvol != 1) {
336 			panic("Changing volumes on pipe input?\n");
337 			/* Avoid looping if we couldn't ask the user. */
338 			if (yflag || ferror(terminal) || feof(terminal))
339 				done(1);
340 		}
341 		if (volno == 1)
342 			return;
343 		newvol = 0;
344 		goto gethdr;
345 	}
346 again:
347 	if (pipein)
348 		done(1); /* pipes do not get a second chance */
349 	if (command == 'R' || command == 'r' || curfile.action != SKIP)
350 		newvol = nextvol;
351 	else
352 		newvol = 0;
353 	while (newvol <= 0) {
354 		if (tapesread == 0) {
355 			fprintf(stderr, "%s%s%s%s%s%s%s",
356 			    "You have not read any tapes yet.\n",
357 			    "If you are extracting just a few files,",
358 			    " start with the last volume\n",
359 			    "and work towards the first; restore",
360 			    " can quickly skip tapes that\n",
361 			    "have no further files to extract.",
362 			    " Otherwise, begin with volume 1.\n");
363 		} else {
364 			fprintf(stderr, "You have read volumes");
365 			strcpy(buf, ": ");
366 			for (i = 0; i < 32; i++)
367 				if (tapesread & (1 << i)) {
368 					fprintf(stderr, "%s%ld", buf, i + 1);
369 					strcpy(buf, ", ");
370 				}
371 			fprintf(stderr, "\n");
372 		}
373 		do	{
374 			fprintf(stderr, "Specify next volume #: ");
375 			(void) fflush(stderr);
376 			if (fgets(buf, BUFSIZ, terminal) == NULL)
377 				done(1);
378 		} while (buf[0] == '\n');
379 		newvol = atoi(buf);
380 		if (newvol <= 0) {
381 			fprintf(stderr,
382 			    "Volume numbers are positive numerics\n");
383 		}
384 	}
385 	if (newvol == volno) {
386 		tapesread |= 1 << (volno - 1);
387 		return;
388 	}
389 	closemt();
390 	fprintf(stderr, "Mount tape volume %ld\n", newvol);
391 	fprintf(stderr, "Enter ``none'' if there are no more tapes\n");
392 	fprintf(stderr, "otherwise enter tape name (default: %s) ", magtape);
393 	(void) fflush(stderr);
394 	if (fgets(buf, BUFSIZ, terminal) == NULL)
395 		done(1);
396 	if (!strcmp(buf, "none\n")) {
397 		terminateinput();
398 		return;
399 	}
400 	if (buf[0] != '\n') {
401 		(void) strcpy(magtape, buf);
402 		magtape[strlen(magtape) - 1] = '\0';
403 	}
404 	if (pipecmdin) {
405 		char volno[sizeof("2147483647")];
406 
407 		(void)sprintf(volno, "%ld", newvol);
408 		if (setenv("RESTORE_VOLUME", volno, 1) == -1) {
409 			fprintf(stderr, "Cannot set $RESTORE_VOLUME: %s\n",
410 			    strerror(errno));
411 			done(1);
412 		}
413 		popenfp = popen(magtape, "r");
414 		mt = popenfp ? fileno(popenfp) : -1;
415 	} else
416 #ifdef RRESTORE
417 	if (host)
418 		mt = rmtopen(magtape, 0);
419 	else
420 #endif
421 		mt = open(magtape, O_RDONLY, 0);
422 
423 	if (mt == -1) {
424 		fprintf(stderr, "Cannot open %s\n", magtape);
425 		volno = -1;
426 		goto again;
427 	}
428 gethdr:
429 	volno = newvol;
430 	setdumpnum();
431 	FLUSHTAPEBUF();
432 	if (gethead(&tmpbuf) == FAIL) {
433 		dprintf(stdout, "header read failed at %ld blocks\n", blksread);
434 		fprintf(stderr, "tape is not dump tape\n");
435 		volno = 0;
436 		goto again;
437 	}
438 	if (tmpbuf.c_volume != volno) {
439 		fprintf(stderr, "Wrong volume (%jd)\n",
440 		    (intmax_t)tmpbuf.c_volume);
441 		volno = 0;
442 		goto again;
443 	}
444 	if (_time64_to_time(tmpbuf.c_date) != dumpdate ||
445 	    _time64_to_time(tmpbuf.c_ddate) != dumptime) {
446 		time_t t = _time64_to_time(tmpbuf.c_date);
447 		fprintf(stderr, "Wrong dump date\n\tgot: %s", ctime(&t));
448 		fprintf(stderr, "\twanted: %s", ctime(&dumpdate));
449 		volno = 0;
450 		goto again;
451 	}
452 	tapesread |= 1 << (volno - 1);
453 	blksread = savecnt;
454  	/*
455  	 * If continuing from the previous volume, skip over any
456  	 * blocks read already at the end of the previous volume.
457  	 *
458  	 * If coming to this volume at random, skip to the beginning
459  	 * of the next record.
460  	 */
461 	dprintf(stdout, "last rec %jd, tape starts with %jd\n",
462 	    (intmax_t)prevtapea, (intmax_t)tmpbuf.c_tapea);
463  	if (tmpbuf.c_type == TS_TAPE) {
464  		if (curfile.action != USING) {
465 			/*
466 			 * XXX Dump incorrectly sets c_count to 1 in the
467 			 * volume header of the first tape, so ignore
468 			 * c_count when volno == 1.
469 			 */
470 			if (volno != 1)
471 				for (i = tmpbuf.c_count; i > 0; i--)
472 					readtape(buf);
473  		} else if (tmpbuf.c_tapea <= prevtapea) {
474 			/*
475 			 * Normally the value of c_tapea in the volume
476 			 * header is the record number of the header itself.
477 			 * However in the volume header following an EOT-
478 			 * terminated tape, it is the record number of the
479 			 * first continuation data block (dump bug?).
480 			 *
481 			 * The next record we want is `prevtapea + 1'.
482 			 */
483  			i = prevtapea + 1 - tmpbuf.c_tapea;
484 			dprintf(stderr, "Skipping %ld duplicate record%s.\n",
485 				i, i > 1 ? "s" : "");
486  			while (--i >= 0)
487  				readtape(buf);
488  		}
489  	}
490 	if (curfile.action == USING) {
491 		if (volno == 1)
492 			panic("active file into volume 1\n");
493 		return;
494 	}
495 	(void) gethead(&spcl);
496 	findinode(&spcl);
497 	if (gettingfile) {
498 		gettingfile = 0;
499 		longjmp(restart, 1);
500 	}
501 }
502 
503 /*
504  * Handle unexpected EOF.
505  */
506 static void
507 terminateinput(void)
508 {
509 
510 	if (gettingfile && curfile.action == USING) {
511 		printf("Warning: %s %s\n",
512 		    "End-of-input encountered while extracting", curfile.name);
513 	}
514 	curfile.name = "<name unknown>";
515 	curfile.action = UNKNOWN;
516 	curfile.mode = 0;
517 	curfile.ino = maxino;
518 	if (gettingfile) {
519 		gettingfile = 0;
520 		longjmp(restart, 1);
521 	}
522 }
523 
524 /*
525  * handle multiple dumps per tape by skipping forward to the
526  * appropriate one.
527  */
528 static void
529 setdumpnum(void)
530 {
531 	struct mtop tcom;
532 
533 	if (dumpnum == 1 || volno != 1)
534 		return;
535 	if (pipein) {
536 		fprintf(stderr, "Cannot have multiple dumps on pipe input\n");
537 		done(1);
538 	}
539 	tcom.mt_op = MTFSF;
540 	tcom.mt_count = dumpnum - 1;
541 #ifdef RRESTORE
542 	if (host)
543 		rmtioctl(MTFSF, dumpnum - 1);
544 	else
545 #endif
546 		if (!pipecmdin && ioctl(mt, MTIOCTOP, (char *)&tcom) < 0)
547 			fprintf(stderr, "ioctl MTFSF: %s\n", strerror(errno));
548 }
549 
550 void
551 printdumpinfo(void)
552 {
553 	time_t t;
554 	t = _time64_to_time(spcl.c_date);
555 	fprintf(stdout, "Dump   date: %s", ctime(&t));
556 	t = _time64_to_time(spcl.c_ddate);
557 	fprintf(stdout, "Dumped from: %s",
558 	    (spcl.c_ddate == 0) ? "the epoch\n" : ctime(&t));
559 	if (spcl.c_host[0] == '\0')
560 		return;
561 	fprintf(stderr, "Level %jd dump of %s on %s:%s\n",
562 	    (intmax_t)spcl.c_level, spcl.c_filesys, spcl.c_host, spcl.c_dev);
563 	fprintf(stderr, "Label: %s\n", spcl.c_label);
564 }
565 
566 int
567 extractfile(char *name)
568 {
569 	u_int flags;
570 	uid_t uid;
571 	gid_t gid;
572 	mode_t mode;
573 	int extsize;
574 	struct timespec mtimep[2], ctimep[2];
575 	struct entry *ep;
576 	char *buf;
577 
578 	curfile.name = name;
579 	curfile.action = USING;
580 	mtimep[0].tv_sec = curfile.atime_sec;
581 	mtimep[0].tv_nsec = curfile.atime_nsec;
582 	mtimep[1].tv_sec = curfile.mtime_sec;
583 	mtimep[1].tv_nsec = curfile.mtime_nsec;
584 	ctimep[0].tv_sec = curfile.atime_sec;
585 	ctimep[0].tv_nsec = curfile.atime_nsec;
586 	ctimep[1].tv_sec = curfile.birthtime_sec;
587 	ctimep[1].tv_nsec = curfile.birthtime_nsec;
588 	extsize = curfile.extsize;
589 	uid = getuid();
590 	if (uid == 0)
591 		uid = curfile.uid;
592 	gid = curfile.gid;
593 	mode = curfile.mode;
594 	flags = curfile.file_flags;
595 	switch (mode & IFMT) {
596 
597 	default:
598 		fprintf(stderr, "%s: unknown file mode 0%o\n", name, mode);
599 		skipfile();
600 		return (FAIL);
601 
602 	case IFSOCK:
603 		vprintf(stdout, "skipped socket %s\n", name);
604 		skipfile();
605 		return (GOOD);
606 
607 	case IFDIR:
608 		if (mflag) {
609 			ep = lookupname(name);
610 			if (ep == NULL || ep->e_flags & EXTRACT)
611 				panic("unextracted directory %s\n", name);
612 			skipfile();
613 			return (GOOD);
614 		}
615 		vprintf(stdout, "extract file %s\n", name);
616 		return (genliteraldir(name, curfile.ino));
617 
618 	case IFLNK:
619 		lnkbuf[0] = '\0';
620 		pathlen = 0;
621 		buf = setupextattr(extsize);
622 		getfile(xtrlnkfile, xtrattr, xtrlnkskip);
623 		if (pathlen == 0) {
624 			vprintf(stdout,
625 			    "%s: zero length symbolic link (ignored)\n", name);
626 			return (GOOD);
627 		}
628 		if (linkit(lnkbuf, name, SYMLINK) == GOOD) {
629 			if (extsize > 0)
630 				set_extattr(-1, name, buf, extsize, SXA_LINK);
631 			(void) lchown(name, uid, gid);
632 			(void) lchmod(name, mode);
633 			(void) utimensat(AT_FDCWD, name, ctimep,
634 			    AT_SYMLINK_NOFOLLOW);
635 			(void) utimensat(AT_FDCWD, name, mtimep,
636 			    AT_SYMLINK_NOFOLLOW);
637 			(void) lchflags(name, flags);
638 			return (GOOD);
639 		}
640 		return (FAIL);
641 
642 	case IFIFO:
643 		vprintf(stdout, "extract fifo %s\n", name);
644 		if (Nflag) {
645 			skipfile();
646 			return (GOOD);
647 		}
648 		if (uflag)
649 			(void) unlink(name);
650 		if (mkfifo(name, 0600) < 0) {
651 			fprintf(stderr, "%s: cannot create fifo: %s\n",
652 			    name, strerror(errno));
653 			skipfile();
654 			return (FAIL);
655 		}
656 		if (extsize == 0) {
657 			skipfile();
658 		} else {
659 			buf = setupextattr(extsize);
660 			getfile(xtrnull, xtrattr, xtrnull);
661 			set_extattr(-1, name, buf, extsize, SXA_FILE);
662 		}
663 		(void) chown(name, uid, gid);
664 		(void) chmod(name, mode);
665 		(void) utimensat(AT_FDCWD, name, ctimep, 0);
666 		(void) utimensat(AT_FDCWD, name, mtimep, 0);
667 		(void) chflags(name, flags);
668 		return (GOOD);
669 
670 	case IFCHR:
671 	case IFBLK:
672 		vprintf(stdout, "extract special file %s\n", name);
673 		if (Nflag) {
674 			skipfile();
675 			return (GOOD);
676 		}
677 		if (uflag)
678 			(void) unlink(name);
679 		if (mknod(name, (mode & (IFCHR | IFBLK)) | 0600,
680 		    (int)curfile.rdev) < 0) {
681 			fprintf(stderr, "%s: cannot create special file: %s\n",
682 			    name, strerror(errno));
683 			skipfile();
684 			return (FAIL);
685 		}
686 		if (extsize == 0) {
687 			skipfile();
688 		} else {
689 			buf = setupextattr(extsize);
690 			getfile(xtrnull, xtrattr, xtrnull);
691 			set_extattr(-1, name, buf, extsize, SXA_FILE);
692 		}
693 		(void) chown(name, uid, gid);
694 		(void) chmod(name, mode);
695 		(void) utimensat(AT_FDCWD, name, ctimep, 0);
696 		(void) utimensat(AT_FDCWD, name, mtimep, 0);
697 		(void) chflags(name, flags);
698 		return (GOOD);
699 
700 	case IFREG:
701 		vprintf(stdout, "extract file %s\n", name);
702 		if (Nflag) {
703 			skipfile();
704 			return (GOOD);
705 		}
706 		if (uflag)
707 			(void) unlink(name);
708 		if ((ofile = open(name, O_WRONLY | O_CREAT | O_TRUNC,
709 		    0600)) < 0) {
710 			fprintf(stderr, "%s: cannot create file: %s\n",
711 			    name, strerror(errno));
712 			skipfile();
713 			return (FAIL);
714 		}
715 		buf = setupextattr(extsize);
716 		getfile(xtrfile, xtrattr, xtrskip);
717 		if (extsize > 0)
718 			set_extattr(ofile, name, buf, extsize, SXA_FD);
719 		(void) fchown(ofile, uid, gid);
720 		(void) fchmod(ofile, mode);
721 		(void) futimens(ofile, ctimep);
722 		(void) futimens(ofile, mtimep);
723 		(void) fchflags(ofile, flags);
724 		(void) close(ofile);
725 		return (GOOD);
726 	}
727 	/* NOTREACHED */
728 }
729 
730 /*
731  * Set attributes on a file descriptor, link, or file.
732  */
733 void
734 set_extattr(int fd, char *name, void *buf, int size, enum set_extattr_mode mode)
735 {
736 	struct extattr *eap, *eaend;
737 	const char *method;
738 	ssize_t res;
739 	int error;
740 	char eaname[EXTATTR_MAXNAMELEN + 1];
741 
742 	vprintf(stdout, "Set attributes for %s:", name);
743 	eaend = buf + size;
744 	for (eap = buf; eap < eaend; eap = EXTATTR_NEXT(eap)) {
745 		/*
746 		 * Make sure this entry is complete.
747 		 */
748 		if (EXTATTR_NEXT(eap) > eaend || eap->ea_length <= 0) {
749 			dprintf(stdout, "\n\t%scorrupted",
750 				eap == buf ? "" : "remainder ");
751 			break;
752 		}
753 		if (eap->ea_namespace == EXTATTR_NAMESPACE_EMPTY)
754 			continue;
755 		snprintf(eaname, sizeof(eaname), "%.*s",
756 		    (int)eap->ea_namelength, eap->ea_name);
757 		vprintf(stdout, "\n\t%s, (%d bytes), %s",
758 			namespace_names[eap->ea_namespace], eap->ea_length,
759 			eaname);
760 		/*
761 		 * First we try the general attribute setting interface.
762 		 * However, some attributes can only be set by root or
763 		 * by using special interfaces (for example, ACLs).
764 		 */
765 		if (mode == SXA_FD) {
766 			res = extattr_set_fd(fd, eap->ea_namespace,
767 			    eaname, EXTATTR_CONTENT(eap),
768 			    EXTATTR_CONTENT_SIZE(eap));
769 			method = "extattr_set_fd";
770 		} else if (mode == SXA_LINK) {
771 			res = extattr_set_link(name, eap->ea_namespace,
772 			    eaname, EXTATTR_CONTENT(eap),
773 			    EXTATTR_CONTENT_SIZE(eap));
774 			method = "extattr_set_link";
775 		} else if (mode == SXA_FILE) {
776 			res = extattr_set_file(name, eap->ea_namespace,
777 			    eaname, EXTATTR_CONTENT(eap),
778 			    EXTATTR_CONTENT_SIZE(eap));
779 			method = "extattr_set_file";
780 		}
781 		if (res != -1) {
782 			dprintf(stdout, " (set using %s)", method);
783 			continue;
784 		}
785 		/*
786 		 * If the general interface refuses to set the attribute,
787 		 * then we try all the specialized interfaces that we
788 		 * know about.
789 		 */
790 		if (eap->ea_namespace == EXTATTR_NAMESPACE_SYSTEM &&
791 		    strcmp(eaname, POSIX1E_ACL_ACCESS_EXTATTR_NAME) == 0) {
792 			if (mode == SXA_FD) {
793 				error = acl_set_fd(fd, EXTATTR_CONTENT(eap));
794 				method = "acl_set_fd";
795 			} else if (mode == SXA_LINK) {
796 				error = acl_set_link_np(name, ACL_TYPE_ACCESS,
797 				    EXTATTR_CONTENT(eap));
798 				method = "acl_set_link_np";
799 			} else if (mode == SXA_FILE) {
800 				error = acl_set_file(name, ACL_TYPE_ACCESS,
801 				    EXTATTR_CONTENT(eap));
802 				method = "acl_set_file";
803 			}
804 			if (error != -1) {
805 				dprintf(stdout, " (set using %s)", method);
806 				continue;
807 			}
808 		}
809 		if (eap->ea_namespace == EXTATTR_NAMESPACE_SYSTEM &&
810 		    strcmp(eaname, POSIX1E_ACL_DEFAULT_EXTATTR_NAME) == 0) {
811 			if (mode == SXA_LINK) {
812 				error = acl_set_link_np(name, ACL_TYPE_DEFAULT,
813 				    EXTATTR_CONTENT(eap));
814 				method = "acl_set_link_np";
815 			} else {
816 				error = acl_set_file(name, ACL_TYPE_DEFAULT,
817 				    EXTATTR_CONTENT(eap));
818 				method = "acl_set_file";
819 			}
820 			if (error != -1) {
821 				dprintf(stdout, " (set using %s)", method);
822 				continue;
823 			}
824 		}
825 		vprintf(stdout, " (unable to set)");
826 	}
827 	vprintf(stdout, "\n");
828 }
829 
830 /*
831  * skip over bit maps on the tape
832  */
833 void
834 skipmaps(void)
835 {
836 
837 	while (spcl.c_type == TS_BITS || spcl.c_type == TS_CLRI)
838 		skipfile();
839 }
840 
841 /*
842  * skip over a file on the tape
843  */
844 void
845 skipfile(void)
846 {
847 
848 	curfile.action = SKIP;
849 	getfile(xtrnull, xtrnull, xtrnull);
850 }
851 
852 /*
853  * Skip a hole in an output file
854  */
855 static void
856 skiphole(void (*skip)(char *, size_t), size_t *seekpos)
857 {
858 	char buf[MAXBSIZE];
859 
860 	if (*seekpos > 0) {
861 		(*skip)(buf, *seekpos);
862 		*seekpos = 0;
863 	}
864 }
865 
866 /*
867  * Extract a file from the tape.
868  * When an allocated block is found it is passed to the fill function;
869  * when an unallocated block (hole) is found, a zeroed buffer is passed
870  * to the skip function.
871  */
872 void
873 getfile(void (*datafill)(char *, size_t), void (*attrfill)(char *, size_t),
874 	void (*skip)(char *, size_t))
875 {
876 	int i;
877 	volatile off_t size;
878 	size_t seekpos;
879 	int curblk, attrsize;
880 	void (*fillit)(char *, size_t);
881 	char buf[MAXBSIZE / TP_BSIZE][TP_BSIZE];
882 	char junk[TP_BSIZE];
883 
884 	curblk = 0;
885 	size = spcl.c_size;
886 	seekpos = 0;
887 	attrsize = spcl.c_extsize;
888 	if (spcl.c_type == TS_END)
889 		panic("ran off end of tape\n");
890 	if (spcl.c_magic != FS_UFS2_MAGIC)
891 		panic("not at beginning of a file\n");
892 	if (!gettingfile && setjmp(restart) != 0)
893 		return;
894 	gettingfile++;
895 	fillit = datafill;
896 	if (size == 0 && attrsize > 0) {
897 		fillit = attrfill;
898 		size = attrsize;
899 		attrsize = 0;
900 	}
901 loop:
902 	for (i = 0; i < spcl.c_count; i++) {
903 		if (!readmapflag && i > TP_NINDIR) {
904 			if (Dflag) {
905 				fprintf(stderr, "spcl.c_count = %jd\n",
906 				    (intmax_t)spcl.c_count);
907 				break;
908 			} else
909 				panic("spcl.c_count = %jd\n",
910 				    (intmax_t)spcl.c_count);
911 		}
912 		if (readmapflag || spcl.c_addr[i]) {
913 			readtape(&buf[curblk++][0]);
914 			if (curblk == fssize / TP_BSIZE) {
915 				skiphole(skip, &seekpos);
916 				(*fillit)((char *)buf, (long)(size > TP_BSIZE ?
917 				     fssize : (curblk - 1) * TP_BSIZE + size));
918 				curblk = 0;
919 			}
920 		} else {
921 			if (curblk > 0) {
922 				skiphole(skip, &seekpos);
923 				(*fillit)((char *)buf, (long)(size > TP_BSIZE ?
924 				     curblk * TP_BSIZE :
925 				     (curblk - 1) * TP_BSIZE + size));
926 				curblk = 0;
927 			}
928 			/*
929 			 * We have a block of a hole. Don't skip it
930 			 * now, because there may be next adjacent
931 			 * block of the hole in the file. Postpone the
932 			 * seek until next file write.
933 			 */
934 			seekpos += (long)MIN(TP_BSIZE, size);
935 		}
936 		if ((size -= TP_BSIZE) <= 0) {
937 			if (size > -TP_BSIZE && curblk > 0) {
938 				skiphole(skip, &seekpos);
939 				(*fillit)((char *)buf,
940 					(long)((curblk * TP_BSIZE) + size));
941 				curblk = 0;
942 			}
943 			if (attrsize > 0) {
944 				fillit = attrfill;
945 				size = attrsize;
946 				attrsize = 0;
947 				continue;
948 			}
949 			if (spcl.c_count - i > 1)
950 				dprintf(stdout, "skipping %d junk block(s)\n",
951 					spcl.c_count - i - 1);
952 			for (i++; i < spcl.c_count; i++) {
953 				if (!readmapflag && i > TP_NINDIR) {
954 					if (Dflag) {
955 						fprintf(stderr,
956 						    "spcl.c_count = %jd\n",
957 						    (intmax_t)spcl.c_count);
958 						break;
959 					} else
960 						panic("spcl.c_count = %jd\n",
961 						    (intmax_t)spcl.c_count);
962 				}
963 				if (readmapflag || spcl.c_addr[i])
964 					readtape(junk);
965 			}
966 			break;
967 		}
968 	}
969 	if (gethead(&spcl) == GOOD && size > 0) {
970 		if (spcl.c_type == TS_ADDR)
971 			goto loop;
972 		dprintf(stdout,
973 			"Missing address (header) block for %s at %ld blocks\n",
974 			curfile.name, blksread);
975 	}
976 	if (curblk > 0)
977 		panic("getfile: lost data\n");
978 	findinode(&spcl);
979 	gettingfile = 0;
980 }
981 
982 /*
983  * These variables are shared between the next two functions.
984  */
985 static int extbufsize = 0;
986 static char *extbuf;
987 static int extloc;
988 
989 /*
990  * Allocate a buffer into which to extract extended attributes.
991  */
992 static char *
993 setupextattr(int extsize)
994 {
995 
996 	extloc = 0;
997 	if (extsize <= extbufsize)
998 		return (extbuf);
999 	if (extbufsize > 0)
1000 		free(extbuf);
1001 	if ((extbuf = malloc(extsize)) != NULL) {
1002 		extbufsize = extsize;
1003 		return (extbuf);
1004 	}
1005 	extbufsize = 0;
1006 	extbuf = NULL;
1007 	fprintf(stderr, "Cannot extract %d bytes %s for inode %ju, name %s\n",
1008 	    extsize, "of extended attributes", (uintmax_t)curfile.ino,
1009 	    curfile.name);
1010 	return (NULL);
1011 }
1012 
1013 /*
1014  * Extract the next block of extended attributes.
1015  */
1016 static void
1017 xtrattr(char *buf, size_t size)
1018 {
1019 
1020 	if (extloc + size > extbufsize)
1021 		panic("overrun attribute buffer\n");
1022 	memmove(&extbuf[extloc], buf, size);
1023 	extloc += size;
1024 }
1025 
1026 /*
1027  * Write out the next block of a file.
1028  */
1029 static void
1030 xtrfile(char *buf, size_t size)
1031 {
1032 
1033 	if (Nflag)
1034 		return;
1035 	if (write(ofile, buf, (int) size) == -1) {
1036 		fprintf(stderr,
1037 		    "write error extracting inode %ju, name %s\nwrite: %s\n",
1038 		    (uintmax_t)curfile.ino, curfile.name, strerror(errno));
1039 	}
1040 }
1041 
1042 /*
1043  * Skip over a hole in a file.
1044  */
1045 /* ARGSUSED */
1046 static void
1047 xtrskip(char *buf, size_t size)
1048 {
1049 
1050 	if (lseek(ofile, size, SEEK_CUR) == -1) {
1051 		fprintf(stderr,
1052 		    "seek error extracting inode %ju, name %s\nlseek: %s\n",
1053 		    (uintmax_t)curfile.ino, curfile.name, strerror(errno));
1054 		done(1);
1055 	}
1056 }
1057 
1058 /*
1059  * Collect the next block of a symbolic link.
1060  */
1061 static void
1062 xtrlnkfile(char *buf, size_t size)
1063 {
1064 
1065 	pathlen += size;
1066 	if (pathlen > MAXPATHLEN) {
1067 		fprintf(stderr, "symbolic link name: %s->%s%s; too long %d\n",
1068 		    curfile.name, lnkbuf, buf, pathlen);
1069 		done(1);
1070 	}
1071 	(void) strcat(lnkbuf, buf);
1072 }
1073 
1074 /*
1075  * Skip over a hole in a symbolic link (should never happen).
1076  */
1077 /* ARGSUSED */
1078 static void
1079 xtrlnkskip(char *buf, size_t size)
1080 {
1081 
1082 	fprintf(stderr, "unallocated block in symbolic link %s\n",
1083 		curfile.name);
1084 	done(1);
1085 }
1086 
1087 /*
1088  * Collect the next block of a bit map.
1089  */
1090 static void
1091 xtrmap(char *buf, size_t size)
1092 {
1093 
1094 	memmove(map, buf, size);
1095 	map += size;
1096 }
1097 
1098 /*
1099  * Skip over a hole in a bit map (should never happen).
1100  */
1101 /* ARGSUSED */
1102 static void
1103 xtrmapskip(char *buf, size_t size)
1104 {
1105 
1106 	panic("hole in map\n");
1107 	map += size;
1108 }
1109 
1110 /*
1111  * Noop, when an extraction function is not needed.
1112  */
1113 /* ARGSUSED */
1114 void
1115 xtrnull(char *buf, size_t size)
1116 {
1117 
1118 	return;
1119 }
1120 
1121 /*
1122  * Read TP_BSIZE blocks from the input.
1123  * Handle read errors, and end of media.
1124  */
1125 static void
1126 readtape(char *buf)
1127 {
1128 	long rd, newvol, i, oldnumtrec;
1129 	int cnt, seek_failed;
1130 
1131 	if (blkcnt + (byteslide > 0) < numtrec) {
1132 		memmove(buf, &tapebuf[(blkcnt++ * TP_BSIZE) + byteslide], (long)TP_BSIZE);
1133 		blksread++;
1134 		tapeaddr++;
1135 		return;
1136 	}
1137 	if (numtrec > 0)
1138 		memmove(&tapebuf[-TP_BSIZE],
1139 		    &tapebuf[(numtrec-1) * TP_BSIZE], (long)TP_BSIZE);
1140 	oldnumtrec = numtrec;
1141 	for (i = 0; i < ntrec; i++)
1142 		((struct s_spcl *)&tapebuf[i * TP_BSIZE])->c_magic = 0;
1143 	if (numtrec == 0)
1144 		numtrec = ntrec;
1145 	cnt = ntrec * TP_BSIZE;
1146 	rd = 0;
1147 getmore:
1148 #ifdef RRESTORE
1149 	if (host)
1150 		i = rmtread(&tapebuf[rd], cnt);
1151 	else
1152 #endif
1153 		i = read(mt, &tapebuf[rd], cnt);
1154 	/*
1155 	 * Check for mid-tape short read error.
1156 	 * If found, skip rest of buffer and start with the next.
1157 	 */
1158 	if (!pipein && !pipecmdin && numtrec < ntrec && i > 0) {
1159 		dprintf(stdout, "mid-media short read error.\n");
1160 		numtrec = ntrec;
1161 	}
1162 	/*
1163 	 * Handle partial block read.
1164 	 */
1165 	if ((pipein || pipecmdin) && i == 0 && rd > 0)
1166 		i = rd;
1167 	else if (i > 0 && i != ntrec * TP_BSIZE) {
1168 		if (pipein || pipecmdin) {
1169 			rd += i;
1170 			cnt -= i;
1171 			if (cnt > 0)
1172 				goto getmore;
1173 			i = rd;
1174 		} else {
1175 			/*
1176 			 * Short read. Process the blocks read.
1177 			 */
1178 			if (i % TP_BSIZE != 0)
1179 				vprintf(stdout,
1180 				    "partial block read: %ld should be %ld\n",
1181 				    i, ntrec * TP_BSIZE);
1182 			numtrec = i / TP_BSIZE;
1183 		}
1184 	}
1185 	/*
1186 	 * Handle read error.
1187 	 */
1188 	if (i < 0) {
1189 		fprintf(stderr, "Tape read error while ");
1190 		switch (curfile.action) {
1191 		default:
1192 			fprintf(stderr, "trying to set up tape\n");
1193 			break;
1194 		case UNKNOWN:
1195 			fprintf(stderr, "trying to resynchronize\n");
1196 			break;
1197 		case USING:
1198 			fprintf(stderr, "restoring %s\n", curfile.name);
1199 			break;
1200 		case SKIP:
1201 			fprintf(stderr, "skipping over inode %ju\n",
1202 			    (uintmax_t)curfile.ino);
1203 			break;
1204 		}
1205 		if (!yflag && !reply("continue"))
1206 			done(1);
1207 		i = ntrec * TP_BSIZE;
1208 		memset(tapebuf, 0, i);
1209 #ifdef RRESTORE
1210 		if (host)
1211 			seek_failed = (rmtseek(i, 1) < 0);
1212 		else
1213 #endif
1214 			seek_failed = (lseek(mt, i, SEEK_CUR) == (off_t)-1);
1215 
1216 		if (seek_failed) {
1217 			fprintf(stderr,
1218 			    "continuation failed: %s\n", strerror(errno));
1219 			done(1);
1220 		}
1221 	}
1222 	/*
1223 	 * Handle end of tape.
1224 	 */
1225 	if (i == 0) {
1226 		vprintf(stdout, "End-of-tape encountered\n");
1227 		if (!pipein) {
1228 			newvol = volno + 1;
1229 			volno = 0;
1230 			numtrec = 0;
1231 			getvol(newvol);
1232 			readtape(buf);
1233 			return;
1234 		}
1235 		if (rd % TP_BSIZE != 0)
1236 			panic("partial block read: %ld should be %ld\n",
1237 				rd, ntrec * TP_BSIZE);
1238 		terminateinput();
1239 		memmove(&tapebuf[rd], &endoftapemark, (long)TP_BSIZE);
1240 	}
1241 	if (oldnumtrec == 0)
1242 		blkcnt = 0;
1243 	else
1244 		blkcnt -= oldnumtrec;
1245 	memmove(buf,
1246 	    &tapebuf[(blkcnt++ * TP_BSIZE) + byteslide], (long)TP_BSIZE);
1247 	blksread++;
1248 	tapeaddr++;
1249 }
1250 
1251 static void
1252 findtapeblksize(void)
1253 {
1254 	long i;
1255 
1256 	for (i = 0; i < ntrec; i++)
1257 		((struct s_spcl *)&tapebuf[i * TP_BSIZE])->c_magic = 0;
1258 	blkcnt = 0;
1259 #ifdef RRESTORE
1260 	if (host)
1261 		i = rmtread(tapebuf, ntrec * TP_BSIZE);
1262 	else
1263 #endif
1264 		i = read(mt, tapebuf, ntrec * TP_BSIZE);
1265 
1266 	if (i <= 0) {
1267 		fprintf(stderr, "tape read error: %s\n", strerror(errno));
1268 		done(1);
1269 	}
1270 	if (i % TP_BSIZE != 0) {
1271 		fprintf(stderr, "Tape block size (%ld) %s (%d)\n",
1272 			i, "is not a multiple of dump block size", TP_BSIZE);
1273 		done(1);
1274 	}
1275 	ntrec = i / TP_BSIZE;
1276 	numtrec = ntrec;
1277 	vprintf(stdout, "Tape block size is %ld\n", ntrec);
1278 }
1279 
1280 void
1281 closemt(void)
1282 {
1283 
1284 	if (mt < 0)
1285 		return;
1286 	if (pipecmdin) {
1287 		pclose(popenfp);
1288 		popenfp = NULL;
1289 	} else
1290 #ifdef RRESTORE
1291 	if (host)
1292 		rmtclose();
1293 	else
1294 #endif
1295 		(void) close(mt);
1296 }
1297 
1298 /*
1299  * Read the next block from the tape.
1300  * If it is not any valid header, return an error.
1301  */
1302 static int
1303 gethead(struct s_spcl *buf)
1304 {
1305 	long i;
1306 
1307 	readtape((char *)buf);
1308 	if (buf->c_magic != FS_UFS2_MAGIC && buf->c_magic != NFS_MAGIC) {
1309 		if (buf->c_magic == OFS_MAGIC) {
1310 			fprintf(stderr,
1311 			    "Format of dump tape is too old. Must use\n");
1312 			fprintf(stderr,
1313 			    "a version of restore from before 2002.\n");
1314 			return (FAIL);
1315 		}
1316 		if (swabl(buf->c_magic) != FS_UFS2_MAGIC &&
1317 		    buf->c_magic != NFS_MAGIC) {
1318 			if (buf->c_magic == OFS_MAGIC) {
1319 				fprintf(stderr,
1320 				  "Format of dump tape is too old. Must use\n");
1321 				fprintf(stderr,
1322 				  "a version of restore from before 2002.\n");
1323 			}
1324 			return (FAIL);
1325 		}
1326 		if (!Bcvt) {
1327 			vprintf(stdout, "Note: Doing Byte swapping\n");
1328 			Bcvt = 1;
1329 		}
1330 	}
1331 	if (checksum((int *)buf) == FAIL)
1332 		return (FAIL);
1333 	if (Bcvt) {
1334 		swabst((u_char *)"8l4s1q8l2q17l", (u_char *)buf);
1335 		swabst((u_char *)"l",(u_char *) &buf->c_level);
1336 		swabst((u_char *)"2l4q",(u_char *) &buf->c_flags);
1337 	}
1338 	readmapflag = 0;
1339 
1340 	switch (buf->c_type) {
1341 
1342 	case TS_CLRI:
1343 	case TS_BITS:
1344 		/*
1345 		 * Have to patch up missing information in bit map headers
1346 		 */
1347 		buf->c_size = buf->c_count * TP_BSIZE;
1348 		if (buf->c_count > TP_NINDIR)
1349 			readmapflag = 1;
1350 		else
1351 			for (i = 0; i < buf->c_count; i++)
1352 				buf->c_addr[i]++;
1353 		/* FALL THROUGH */
1354 
1355 	case TS_TAPE:
1356 		if (buf->c_magic == NFS_MAGIC &&
1357 		    (buf->c_flags & NFS_DR_NEWINODEFMT) == 0)
1358 			oldinofmt = 1;
1359 		/* FALL THROUGH */
1360 
1361 	case TS_END:
1362 		buf->c_inumber = 0;
1363 		/* FALL THROUGH */
1364 
1365 	case TS_ADDR:
1366 	case TS_INODE:
1367 		/*
1368 		 * For old dump tapes, have to copy up old fields to
1369 		 * new locations.
1370 		 */
1371 		if (buf->c_magic == NFS_MAGIC) {
1372 			buf->c_tapea = buf->c_old_tapea;
1373 			buf->c_firstrec = buf->c_old_firstrec;
1374 			buf->c_date = _time32_to_time(buf->c_old_date);
1375 			buf->c_ddate = _time32_to_time(buf->c_old_ddate);
1376 			buf->c_atime = _time32_to_time(buf->c_old_atime);
1377 			buf->c_mtime = _time32_to_time(buf->c_old_mtime);
1378 			buf->c_birthtime = 0;
1379 			buf->c_birthtimensec = 0;
1380 			buf->c_extsize = 0;
1381 		}
1382 		break;
1383 
1384 	default:
1385 		panic("gethead: unknown inode type %d\n", buf->c_type);
1386 		break;
1387 	}
1388 	if (dumpdate != 0 && _time64_to_time(buf->c_date) != dumpdate)
1389 		fprintf(stderr, "Header with wrong dumpdate.\n");
1390 	/*
1391 	 * If we're restoring a filesystem with the old (FreeBSD 1)
1392 	 * format inodes, copy the uid/gid to the new location
1393 	 */
1394 	if (oldinofmt) {
1395 		buf->c_uid = buf->c_spare1[1];
1396 		buf->c_gid = buf->c_spare1[2];
1397 	}
1398 	buf->c_magic = FS_UFS2_MAGIC;
1399 	tapeaddr = buf->c_tapea;
1400 	if (dflag)
1401 		accthdr(buf);
1402 	return(GOOD);
1403 }
1404 
1405 /*
1406  * Check that a header is where it belongs and predict the next header
1407  */
1408 static void
1409 accthdr(struct s_spcl *header)
1410 {
1411 	static ino_t previno = 0x7fffffff;
1412 	static int prevtype;
1413 	static long predict;
1414 	long blks, i;
1415 
1416 	if (header->c_type == TS_TAPE) {
1417 		fprintf(stderr, "Volume header ");
1418  		if (header->c_firstrec)
1419  			fprintf(stderr, "begins with record %jd",
1420 			    (intmax_t)header->c_firstrec);
1421  		fprintf(stderr, "\n");
1422 		previno = 0x7fffffff;
1423 		return;
1424 	}
1425 	if (previno == 0x7fffffff)
1426 		goto newcalc;
1427 	switch (prevtype) {
1428 	case TS_BITS:
1429 		fprintf(stderr, "Dumped inodes map header");
1430 		break;
1431 	case TS_CLRI:
1432 		fprintf(stderr, "Used inodes map header");
1433 		break;
1434 	case TS_INODE:
1435 		fprintf(stderr, "File header, ino %ju", (uintmax_t)previno);
1436 		break;
1437 	case TS_ADDR:
1438 		fprintf(stderr, "File continuation header, ino %ju",
1439 		    (uintmax_t)previno);
1440 		break;
1441 	case TS_END:
1442 		fprintf(stderr, "End of tape header");
1443 		break;
1444 	}
1445 	if (predict != blksread - 1)
1446 		fprintf(stderr, "; predicted %ld blocks, got %ld blocks",
1447 			predict, blksread - 1);
1448 	fprintf(stderr, "\n");
1449 newcalc:
1450 	blks = 0;
1451 	if (header->c_type != TS_END)
1452 		for (i = 0; i < header->c_count; i++)
1453 			if (readmapflag || header->c_addr[i] != 0)
1454 				blks++;
1455 	predict = blks;
1456 	blksread = 0;
1457 	prevtype = header->c_type;
1458 	previno = header->c_inumber;
1459 }
1460 
1461 /*
1462  * Find an inode header.
1463  * Complain if had to skip.
1464  */
1465 static void
1466 findinode(struct s_spcl *header)
1467 {
1468 	static long skipcnt = 0;
1469 	long i;
1470 	char buf[TP_BSIZE];
1471 	int htype;
1472 
1473 	curfile.name = "<name unknown>";
1474 	curfile.action = UNKNOWN;
1475 	curfile.mode = 0;
1476 	curfile.ino = 0;
1477 	do {
1478 		htype = header->c_type;
1479 		switch (htype) {
1480 
1481 		case TS_ADDR:
1482 			/*
1483 			 * Skip up to the beginning of the next record
1484 			 */
1485 			for (i = 0; i < header->c_count; i++)
1486 				if (header->c_addr[i])
1487 					readtape(buf);
1488 			while (gethead(header) == FAIL ||
1489 			    _time64_to_time(header->c_date) != dumpdate) {
1490 				skipcnt++;
1491 				if (Dflag) {
1492 					byteslide++;
1493 					if (byteslide < TP_BSIZE) {
1494 						blkcnt--;
1495 						blksread--;
1496 					} else
1497 						byteslide = 0;
1498 				}
1499 			}
1500 			break;
1501 
1502 		case TS_INODE:
1503 			curfile.mode = header->c_mode;
1504 			curfile.uid = header->c_uid;
1505 			curfile.gid = header->c_gid;
1506 			curfile.file_flags = header->c_file_flags;
1507 			curfile.rdev = header->c_rdev;
1508 			curfile.atime_sec = header->c_atime;
1509 			curfile.atime_nsec = header->c_atimensec;
1510 			curfile.mtime_sec = header->c_mtime;
1511 			curfile.mtime_nsec = header->c_mtimensec;
1512 			curfile.birthtime_sec = header->c_birthtime;
1513 			curfile.birthtime_nsec = header->c_birthtimensec;
1514 			curfile.extsize = header->c_extsize;
1515 			curfile.size = header->c_size;
1516 			curfile.ino = header->c_inumber;
1517 			break;
1518 
1519 		case TS_END:
1520 			/* If we missed some tapes, get another volume. */
1521 			if (tapesread & (tapesread + 1)) {
1522 				getvol(0);
1523 				continue;
1524 			}
1525 			curfile.ino = maxino;
1526 			break;
1527 
1528 		case TS_CLRI:
1529 			curfile.name = "<file removal list>";
1530 			break;
1531 
1532 		case TS_BITS:
1533 			curfile.name = "<file dump list>";
1534 			break;
1535 
1536 		case TS_TAPE:
1537 			if (Dflag)
1538 				fprintf(stderr, "unexpected tape header\n");
1539 			else
1540 				panic("unexpected tape header\n");
1541 
1542 		default:
1543 			if (Dflag)
1544 				fprintf(stderr, "unknown tape header type %d\n",
1545 				    spcl.c_type);
1546 			else
1547 				panic("unknown tape header type %d\n",
1548 				    spcl.c_type);
1549 			while (gethead(header) == FAIL ||
1550 			    _time64_to_time(header->c_date) != dumpdate) {
1551 				skipcnt++;
1552 				if (Dflag) {
1553 					byteslide++;
1554 					if (byteslide < TP_BSIZE) {
1555 						blkcnt--;
1556 						blksread--;
1557 					} else
1558 						byteslide = 0;
1559 				}
1560 			}
1561 
1562 		}
1563 	} while (htype == TS_ADDR);
1564 	if (skipcnt > 0)
1565 		fprintf(stderr, "resync restore, skipped %ld %s\n",
1566 		    skipcnt, Dflag ? "bytes" : "blocks");
1567 	skipcnt = 0;
1568 }
1569 
1570 static int
1571 checksum(int *buf)
1572 {
1573 	int i, j;
1574 
1575 	j = sizeof(union u_spcl) / sizeof(int);
1576 	i = 0;
1577 	if (!Bcvt) {
1578 		do
1579 			i += *buf++;
1580 		while (--j);
1581 	} else {
1582 		/* What happens if we want to read restore tapes
1583 			for a 16bit int machine??? */
1584 		do
1585 			i += swabl(*buf++);
1586 		while (--j);
1587 	}
1588 
1589 	if (i != CHECKSUM) {
1590 		fprintf(stderr, "Checksum error %o, inode %ju file %s\n", i,
1591 		    (uintmax_t)curfile.ino, curfile.name);
1592 		return(FAIL);
1593 	}
1594 	return(GOOD);
1595 }
1596 
1597 #ifdef RRESTORE
1598 #include <stdarg.h>
1599 
1600 void
1601 msg(const char *fmt, ...)
1602 {
1603 	va_list ap;
1604 	va_start(ap, fmt);
1605 	(void)vfprintf(stderr, fmt, ap);
1606 	va_end(ap);
1607 }
1608 #endif /* RRESTORE */
1609 
1610 static u_char *
1611 swabshort(u_char *sp, int n)
1612 {
1613 	char c;
1614 
1615 	while (--n >= 0) {
1616 		c = sp[0]; sp[0] = sp[1]; sp[1] = c;
1617 		sp += 2;
1618 	}
1619 	return (sp);
1620 }
1621 
1622 static u_char *
1623 swablong(u_char *sp, int n)
1624 {
1625 	char c;
1626 
1627 	while (--n >= 0) {
1628 		c = sp[0]; sp[0] = sp[3]; sp[3] = c;
1629 		c = sp[2]; sp[2] = sp[1]; sp[1] = c;
1630 		sp += 4;
1631 	}
1632 	return (sp);
1633 }
1634 
1635 static u_char *
1636 swabquad(u_char *sp, int n)
1637 {
1638 	char c;
1639 
1640 	while (--n >= 0) {
1641 		c = sp[0]; sp[0] = sp[7]; sp[7] = c;
1642 		c = sp[1]; sp[1] = sp[6]; sp[6] = c;
1643 		c = sp[2]; sp[2] = sp[5]; sp[5] = c;
1644 		c = sp[3]; sp[3] = sp[4]; sp[4] = c;
1645 		sp += 8;
1646 	}
1647 	return (sp);
1648 }
1649 
1650 void
1651 swabst(u_char *cp, u_char *sp)
1652 {
1653 	int n = 0;
1654 
1655 	while (*cp) {
1656 		switch (*cp) {
1657 		case '0': case '1': case '2': case '3': case '4':
1658 		case '5': case '6': case '7': case '8': case '9':
1659 			n = (n * 10) + (*cp++ - '0');
1660 			continue;
1661 
1662 		case 's': case 'w': case 'h':
1663 			if (n == 0)
1664 				n = 1;
1665 			sp = swabshort(sp, n);
1666 			break;
1667 
1668 		case 'l':
1669 			if (n == 0)
1670 				n = 1;
1671 			sp = swablong(sp, n);
1672 			break;
1673 
1674 		case 'q':
1675 			if (n == 0)
1676 				n = 1;
1677 			sp = swabquad(sp, n);
1678 			break;
1679 
1680 		case 'b':
1681 			if (n == 0)
1682 				n = 1;
1683 			sp += n;
1684 			break;
1685 
1686 		default:
1687 			fprintf(stderr, "Unknown conversion character: %c\n",
1688 			    *cp);
1689 			done(0);
1690 			break;
1691 		}
1692 		cp++;
1693 		n = 0;
1694 	}
1695 }
1696 
1697 static u_long
1698 swabl(u_long x)
1699 {
1700 	swabst((u_char *)"l", (u_char *)&x);
1701 	return (x);
1702 }
1703