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