tape.c revision 241013
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 241013 2012-09-27 23:31:06Z mdf $");
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 && !pipecmdin && !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 = %ju\n", (uintmax_t)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		goto gethdr;
337	}
338again:
339	if (pipein)
340		done(1); /* pipes do not get a second chance */
341	if (command == 'R' || command == 'r' || curfile.action != SKIP)
342		newvol = nextvol;
343	else
344		newvol = 0;
345	while (newvol <= 0) {
346		if (tapesread == 0) {
347			fprintf(stderr, "%s%s%s%s%s%s%s",
348			    "You have not read any tapes yet.\n",
349			    "If you are extracting just a few files,",
350			    " start with the last volume\n",
351			    "and work towards the first; restore",
352			    " can quickly skip tapes that\n",
353			    "have no further files to extract.",
354			    " Otherwise, begin with volume 1.\n");
355		} else {
356			fprintf(stderr, "You have read volumes");
357			strcpy(buf, ": ");
358			for (i = 0; i < 32; i++)
359				if (tapesread & (1 << i)) {
360					fprintf(stderr, "%s%ld", buf, i + 1);
361					strcpy(buf, ", ");
362				}
363			fprintf(stderr, "\n");
364		}
365		do	{
366			fprintf(stderr, "Specify next volume #: ");
367			(void) fflush(stderr);
368			if (fgets(buf, BUFSIZ, terminal) == NULL)
369				done(1);
370		} while (buf[0] == '\n');
371		newvol = atoi(buf);
372		if (newvol <= 0) {
373			fprintf(stderr,
374			    "Volume numbers are positive numerics\n");
375		}
376	}
377	if (newvol == volno) {
378		tapesread |= 1 << (volno - 1);
379		return;
380	}
381	closemt();
382	fprintf(stderr, "Mount tape volume %ld\n", newvol);
383	fprintf(stderr, "Enter ``none'' if there are no more tapes\n");
384	fprintf(stderr, "otherwise enter tape name (default: %s) ", magtape);
385	(void) fflush(stderr);
386	if (fgets(buf, BUFSIZ, terminal) == NULL)
387		done(1);
388	if (!strcmp(buf, "none\n")) {
389		terminateinput();
390		return;
391	}
392	if (buf[0] != '\n') {
393		(void) strcpy(magtape, buf);
394		magtape[strlen(magtape) - 1] = '\0';
395	}
396	if (pipecmdin) {
397		char volno[sizeof("2147483647")];
398
399		(void)sprintf(volno, "%ld", newvol);
400		if (setenv("RESTORE_VOLUME", volno, 1) == -1) {
401			fprintf(stderr, "Cannot set $RESTORE_VOLUME: %s\n",
402			    strerror(errno));
403			done(1);
404		}
405		popenfp = popen(magtape, "r");
406		mt = popenfp ? fileno(popenfp) : -1;
407	} else
408#ifdef RRESTORE
409	if (host)
410		mt = rmtopen(magtape, 0);
411	else
412#endif
413		mt = open(magtape, O_RDONLY, 0);
414
415	if (mt == -1) {
416		fprintf(stderr, "Cannot open %s\n", magtape);
417		volno = -1;
418		goto again;
419	}
420gethdr:
421	volno = newvol;
422	setdumpnum();
423	FLUSHTAPEBUF();
424	if (gethead(&tmpbuf) == FAIL) {
425		dprintf(stdout, "header read failed at %ld blocks\n", blksread);
426		fprintf(stderr, "tape is not dump tape\n");
427		volno = 0;
428		goto again;
429	}
430	if (tmpbuf.c_volume != volno) {
431		fprintf(stderr, "Wrong volume (%jd)\n",
432		    (intmax_t)tmpbuf.c_volume);
433		volno = 0;
434		goto again;
435	}
436	if (_time64_to_time(tmpbuf.c_date) != dumpdate ||
437	    _time64_to_time(tmpbuf.c_ddate) != dumptime) {
438		time_t t = _time64_to_time(tmpbuf.c_date);
439		fprintf(stderr, "Wrong dump date\n\tgot: %s", ctime(&t));
440		fprintf(stderr, "\twanted: %s", ctime(&dumpdate));
441		volno = 0;
442		goto again;
443	}
444	tapesread |= 1 << (volno - 1);
445	blksread = savecnt;
446 	/*
447 	 * If continuing from the previous volume, skip over any
448 	 * blocks read already at the end of the previous volume.
449 	 *
450 	 * If coming to this volume at random, skip to the beginning
451 	 * of the next record.
452 	 */
453	dprintf(stdout, "last rec %jd, tape starts with %jd\n",
454	    (intmax_t)prevtapea, (intmax_t)tmpbuf.c_tapea);
455 	if (tmpbuf.c_type == TS_TAPE) {
456 		if (curfile.action != USING) {
457			/*
458			 * XXX Dump incorrectly sets c_count to 1 in the
459			 * volume header of the first tape, so ignore
460			 * c_count when volno == 1.
461			 */
462			if (volno != 1)
463				for (i = tmpbuf.c_count; i > 0; i--)
464					readtape(buf);
465 		} else if (tmpbuf.c_tapea <= prevtapea) {
466			/*
467			 * Normally the value of c_tapea in the volume
468			 * header is the record number of the header itself.
469			 * However in the volume header following an EOT-
470			 * terminated tape, it is the record number of the
471			 * first continuation data block (dump bug?).
472			 *
473			 * The next record we want is `prevtapea + 1'.
474			 */
475 			i = prevtapea + 1 - tmpbuf.c_tapea;
476			dprintf(stderr, "Skipping %ld duplicate record%s.\n",
477				i, i > 1 ? "s" : "");
478 			while (--i >= 0)
479 				readtape(buf);
480 		}
481 	}
482	if (curfile.action == USING) {
483		if (volno == 1)
484			panic("active file into volume 1\n");
485		return;
486	}
487	(void) gethead(&spcl);
488	findinode(&spcl);
489	if (gettingfile) {
490		gettingfile = 0;
491		longjmp(restart, 1);
492	}
493}
494
495/*
496 * Handle unexpected EOF.
497 */
498static void
499terminateinput(void)
500{
501
502	if (gettingfile && curfile.action == USING) {
503		printf("Warning: %s %s\n",
504		    "End-of-input encountered while extracting", curfile.name);
505	}
506	curfile.name = "<name unknown>";
507	curfile.action = UNKNOWN;
508	curfile.mode = 0;
509	curfile.ino = maxino;
510	if (gettingfile) {
511		gettingfile = 0;
512		longjmp(restart, 1);
513	}
514}
515
516/*
517 * handle multiple dumps per tape by skipping forward to the
518 * appropriate one.
519 */
520static void
521setdumpnum(void)
522{
523	struct mtop tcom;
524
525	if (dumpnum == 1 || volno != 1)
526		return;
527	if (pipein) {
528		fprintf(stderr, "Cannot have multiple dumps on pipe input\n");
529		done(1);
530	}
531	tcom.mt_op = MTFSF;
532	tcom.mt_count = dumpnum - 1;
533#ifdef RRESTORE
534	if (host)
535		rmtioctl(MTFSF, dumpnum - 1);
536	else
537#endif
538		if (!pipecmdin && ioctl(mt, MTIOCTOP, (char *)&tcom) < 0)
539			fprintf(stderr, "ioctl MTFSF: %s\n", strerror(errno));
540}
541
542void
543printdumpinfo(void)
544{
545	time_t t;
546	t = _time64_to_time(spcl.c_date);
547	fprintf(stdout, "Dump   date: %s", ctime(&t));
548	t = _time64_to_time(spcl.c_ddate);
549	fprintf(stdout, "Dumped from: %s",
550	    (spcl.c_ddate == 0) ? "the epoch\n" : ctime(&t));
551	if (spcl.c_host[0] == '\0')
552		return;
553	fprintf(stderr, "Level %jd dump of %s on %s:%s\n",
554	    (intmax_t)spcl.c_level, spcl.c_filesys, spcl.c_host, spcl.c_dev);
555	fprintf(stderr, "Label: %s\n", spcl.c_label);
556}
557
558int
559extractfile(char *name)
560{
561	int flags;
562	uid_t uid;
563	gid_t gid;
564	mode_t mode;
565	int extsize;
566	struct timeval mtimep[2], ctimep[2];
567	struct entry *ep;
568	char *buf;
569
570	curfile.name = name;
571	curfile.action = USING;
572	mtimep[0].tv_sec = curfile.atime_sec;
573	mtimep[0].tv_usec = curfile.atime_nsec / 1000;
574	mtimep[1].tv_sec = curfile.mtime_sec;
575	mtimep[1].tv_usec = curfile.mtime_nsec / 1000;
576	ctimep[0].tv_sec = curfile.atime_sec;
577	ctimep[0].tv_usec = curfile.atime_nsec / 1000;
578	ctimep[1].tv_sec = curfile.birthtime_sec;
579	ctimep[1].tv_usec = curfile.birthtime_nsec / 1000;
580	extsize = curfile.extsize;
581	uid = getuid();
582	if (uid == 0)
583		uid = curfile.uid;
584	gid = curfile.gid;
585	mode = curfile.mode;
586	flags = curfile.file_flags;
587	switch (mode & IFMT) {
588
589	default:
590		fprintf(stderr, "%s: unknown file mode 0%o\n", name, mode);
591		skipfile();
592		return (FAIL);
593
594	case IFSOCK:
595		vprintf(stdout, "skipped socket %s\n", name);
596		skipfile();
597		return (GOOD);
598
599	case IFDIR:
600		if (mflag) {
601			ep = lookupname(name);
602			if (ep == NULL || ep->e_flags & EXTRACT)
603				panic("unextracted directory %s\n", name);
604			skipfile();
605			return (GOOD);
606		}
607		vprintf(stdout, "extract file %s\n", name);
608		return (genliteraldir(name, curfile.ino));
609
610	case IFLNK:
611		lnkbuf[0] = '\0';
612		pathlen = 0;
613		buf = setupextattr(extsize);
614		getfile(xtrlnkfile, xtrattr, xtrlnkskip);
615		if (pathlen == 0) {
616			vprintf(stdout,
617			    "%s: zero length symbolic link (ignored)\n", name);
618			return (GOOD);
619		}
620		if (linkit(lnkbuf, name, SYMLINK) == GOOD) {
621			if (extsize > 0)
622				set_extattr_link(name, buf, extsize);
623			(void) lchown(name, uid, gid);
624			(void) lchmod(name, mode);
625			(void) lutimes(name, ctimep);
626			(void) lutimes(name, mtimep);
627			(void) lchflags(name, flags);
628			return (GOOD);
629		}
630		return (FAIL);
631
632	case IFIFO:
633		vprintf(stdout, "extract fifo %s\n", name);
634		if (Nflag) {
635			skipfile();
636			return (GOOD);
637		}
638		if (uflag)
639			(void) unlink(name);
640		if (mkfifo(name, 0600) < 0) {
641			fprintf(stderr, "%s: cannot create fifo: %s\n",
642			    name, strerror(errno));
643			skipfile();
644			return (FAIL);
645		}
646		if (extsize == 0) {
647			skipfile();
648		} else {
649			buf = setupextattr(extsize);
650			getfile(xtrnull, xtrattr, xtrnull);
651			set_extattr_file(name, buf, extsize);
652		}
653		(void) chown(name, uid, gid);
654		(void) chmod(name, mode);
655		(void) utimes(name, ctimep);
656		(void) utimes(name, mtimep);
657		(void) chflags(name, flags);
658		return (GOOD);
659
660	case IFCHR:
661	case IFBLK:
662		vprintf(stdout, "extract special file %s\n", name);
663		if (Nflag) {
664			skipfile();
665			return (GOOD);
666		}
667		if (uflag)
668			(void) unlink(name);
669		if (mknod(name, (mode & (IFCHR | IFBLK)) | 0600,
670		    (int)curfile.rdev) < 0) {
671			fprintf(stderr, "%s: cannot create special file: %s\n",
672			    name, strerror(errno));
673			skipfile();
674			return (FAIL);
675		}
676		if (extsize == 0) {
677			skipfile();
678		} else {
679			buf = setupextattr(extsize);
680			getfile(xtrnull, xtrattr, xtrnull);
681			set_extattr_file(name, buf, extsize);
682		}
683		(void) chown(name, uid, gid);
684		(void) chmod(name, mode);
685		(void) utimes(name, ctimep);
686		(void) utimes(name, mtimep);
687		(void) chflags(name, flags);
688		return (GOOD);
689
690	case IFREG:
691		vprintf(stdout, "extract file %s\n", name);
692		if (Nflag) {
693			skipfile();
694			return (GOOD);
695		}
696		if (uflag)
697			(void) unlink(name);
698		if ((ofile = open(name, O_WRONLY | O_CREAT | O_TRUNC,
699		    0600)) < 0) {
700			fprintf(stderr, "%s: cannot create file: %s\n",
701			    name, strerror(errno));
702			skipfile();
703			return (FAIL);
704		}
705		buf = setupextattr(extsize);
706		getfile(xtrfile, xtrattr, xtrskip);
707		if (extsize > 0)
708			set_extattr_fd(ofile, name, buf, extsize);
709		(void) fchown(ofile, uid, gid);
710		(void) fchmod(ofile, mode);
711		(void) futimes(ofile, ctimep);
712		(void) futimes(ofile, mtimep);
713		(void) fchflags(ofile, flags);
714		(void) close(ofile);
715		return (GOOD);
716	}
717	/* NOTREACHED */
718}
719
720/*
721 * Set attributes for a file.
722 */
723void
724set_extattr_file(char *name, void *buf, int size)
725{
726	struct extattr *eap, *eaend;
727
728	vprintf(stdout, "Set attributes for %s:", name);
729	eaend = buf + size;
730	for (eap = buf; eap < eaend; eap = EXTATTR_NEXT(eap)) {
731		/*
732		 * Make sure this entry is complete.
733		 */
734		if (EXTATTR_NEXT(eap) > eaend || eap->ea_length <= 0) {
735			dprintf(stdout, "\n\t%scorrupted",
736				eap == buf ? "" : "remainder ");
737			break;
738		}
739		if (eap->ea_namespace == EXTATTR_NAMESPACE_EMPTY)
740			continue;
741		vprintf(stdout, "\n\t%s, (%d bytes), %*s",
742			namespace_names[eap->ea_namespace], eap->ea_length,
743			eap->ea_namelength, eap->ea_name);
744		/*
745		 * First we try the general attribute setting interface.
746		 * However, some attributes can only be set by root or
747		 * by using special interfaces (for example, ACLs).
748		 */
749		if (extattr_set_file(name, eap->ea_namespace, eap->ea_name,
750		    EXTATTR_CONTENT(eap), EXTATTR_CONTENT_SIZE(eap)) != -1) {
751			dprintf(stdout, " (set using extattr_set_file)");
752			continue;
753		}
754		/*
755		 * If the general interface refuses to set the attribute,
756		 * then we try all the specialized interfaces that we
757		 * know about.
758		 */
759		if (eap->ea_namespace == EXTATTR_NAMESPACE_SYSTEM &&
760		    !strcmp(eap->ea_name, POSIX1E_ACL_ACCESS_EXTATTR_NAME)) {
761			if (acl_set_file(name, ACL_TYPE_ACCESS,
762			    EXTATTR_CONTENT(eap)) != -1) {
763				dprintf(stdout, " (set using acl_set_file)");
764				continue;
765			}
766		}
767		if (eap->ea_namespace == EXTATTR_NAMESPACE_SYSTEM &&
768		    !strcmp(eap->ea_name, POSIX1E_ACL_DEFAULT_EXTATTR_NAME)) {
769			if (acl_set_file(name, ACL_TYPE_DEFAULT,
770			    EXTATTR_CONTENT(eap)) != -1) {
771				dprintf(stdout, " (set using acl_set_file)");
772				continue;
773			}
774		}
775		vprintf(stdout, " (unable to set)");
776	}
777	vprintf(stdout, "\n");
778}
779
780/*
781 * Set attributes for a symbolic link.
782 */
783static void
784set_extattr_link(char *name, void *buf, int size)
785{
786	struct extattr *eap, *eaend;
787
788	vprintf(stdout, "Set attributes for %s:", name);
789	eaend = buf + size;
790	for (eap = buf; eap < eaend; eap = EXTATTR_NEXT(eap)) {
791		/*
792		 * Make sure this entry is complete.
793		 */
794		if (EXTATTR_NEXT(eap) > eaend || eap->ea_length <= 0) {
795			dprintf(stdout, "\n\t%scorrupted",
796				eap == buf ? "" : "remainder ");
797			break;
798		}
799		if (eap->ea_namespace == EXTATTR_NAMESPACE_EMPTY)
800			continue;
801		vprintf(stdout, "\n\t%s, (%d bytes), %*s",
802			namespace_names[eap->ea_namespace], eap->ea_length,
803			eap->ea_namelength, eap->ea_name);
804		/*
805		 * First we try the general attribute setting interface.
806		 * However, some attributes can only be set by root or
807		 * by using special interfaces (for example, ACLs).
808		 */
809		if (extattr_set_link(name, eap->ea_namespace, eap->ea_name,
810		    EXTATTR_CONTENT(eap), EXTATTR_CONTENT_SIZE(eap)) != -1) {
811			dprintf(stdout, " (set using extattr_set_link)");
812			continue;
813		}
814		/*
815		 * If the general interface refuses to set the attribute,
816		 * then we try all the specialized interfaces that we
817		 * know about.
818		 */
819		if (eap->ea_namespace == EXTATTR_NAMESPACE_SYSTEM &&
820		    !strcmp(eap->ea_name, POSIX1E_ACL_ACCESS_EXTATTR_NAME)) {
821			if (acl_set_link_np(name, ACL_TYPE_ACCESS,
822			    EXTATTR_CONTENT(eap)) != -1) {
823				dprintf(stdout, " (set using acl_set_link_np)");
824				continue;
825			}
826		}
827		if (eap->ea_namespace == EXTATTR_NAMESPACE_SYSTEM &&
828		    !strcmp(eap->ea_name, POSIX1E_ACL_DEFAULT_EXTATTR_NAME)) {
829			if (acl_set_link_np(name, ACL_TYPE_DEFAULT,
830			    EXTATTR_CONTENT(eap)) != -1) {
831				dprintf(stdout, " (set using acl_set_link_np)");
832				continue;
833			}
834		}
835		vprintf(stdout, " (unable to set)");
836	}
837	vprintf(stdout, "\n");
838}
839
840/*
841 * Set attributes on a file descriptor.
842 */
843static void
844set_extattr_fd(int fd, char *name, void *buf, int size)
845{
846	struct extattr *eap, *eaend;
847
848	vprintf(stdout, "Set attributes for %s:", name);
849	eaend = buf + size;
850	for (eap = buf; eap < eaend; eap = EXTATTR_NEXT(eap)) {
851		/*
852		 * Make sure this entry is complete.
853		 */
854		if (EXTATTR_NEXT(eap) > eaend || eap->ea_length <= 0) {
855			dprintf(stdout, "\n\t%scorrupted",
856				eap == buf ? "" : "remainder ");
857			break;
858		}
859		if (eap->ea_namespace == EXTATTR_NAMESPACE_EMPTY)
860			continue;
861		vprintf(stdout, "\n\t%s, (%d bytes), %*s",
862			namespace_names[eap->ea_namespace], eap->ea_length,
863			eap->ea_namelength, eap->ea_name);
864		/*
865		 * First we try the general attribute setting interface.
866		 * However, some attributes can only be set by root or
867		 * by using special interfaces (for example, ACLs).
868		 */
869		if (extattr_set_fd(fd, eap->ea_namespace, eap->ea_name,
870		    EXTATTR_CONTENT(eap), EXTATTR_CONTENT_SIZE(eap)) != -1) {
871			dprintf(stdout, " (set using extattr_set_fd)");
872			continue;
873		}
874		/*
875		 * If the general interface refuses to set the attribute,
876		 * then we try all the specialized interfaces that we
877		 * know about.
878		 */
879		if (eap->ea_namespace == EXTATTR_NAMESPACE_SYSTEM &&
880		    !strcmp(eap->ea_name, POSIX1E_ACL_ACCESS_EXTATTR_NAME)) {
881			if (acl_set_fd(fd, EXTATTR_CONTENT(eap)) != -1) {
882				dprintf(stdout, " (set using acl_set_fd)");
883				continue;
884			}
885		}
886		if (eap->ea_namespace == EXTATTR_NAMESPACE_SYSTEM &&
887		    !strcmp(eap->ea_name, POSIX1E_ACL_DEFAULT_EXTATTR_NAME)) {
888			if (acl_set_file(name, ACL_TYPE_DEFAULT,
889			    EXTATTR_CONTENT(eap)) != -1) {
890				dprintf(stdout, " (set using acl_set_file)");
891				continue;
892			}
893		}
894		vprintf(stdout, " (unable to set)");
895	}
896	vprintf(stdout, "\n");
897}
898
899/*
900 * skip over bit maps on the tape
901 */
902void
903skipmaps(void)
904{
905
906	while (spcl.c_type == TS_BITS || spcl.c_type == TS_CLRI)
907		skipfile();
908}
909
910/*
911 * skip over a file on the tape
912 */
913void
914skipfile(void)
915{
916
917	curfile.action = SKIP;
918	getfile(xtrnull, xtrnull, xtrnull);
919}
920
921/*
922 * Extract a file from the tape.
923 * When an allocated block is found it is passed to the fill function;
924 * when an unallocated block (hole) is found, a zeroed buffer is passed
925 * to the skip function.
926 */
927void
928getfile(void (*datafill)(char *, long), void (*attrfill)(char *, long),
929	void (*skip)(char *, long))
930{
931	int i;
932	off_t size;
933	int curblk, attrsize;
934	void (*fillit)(char *, long);
935	static char clearedbuf[MAXBSIZE];
936	char buf[MAXBSIZE / TP_BSIZE][TP_BSIZE];
937	char junk[TP_BSIZE];
938
939	curblk = 0;
940	size = spcl.c_size;
941	attrsize = spcl.c_extsize;
942	if (spcl.c_type == TS_END)
943		panic("ran off end of tape\n");
944	if (spcl.c_magic != FS_UFS2_MAGIC)
945		panic("not at beginning of a file\n");
946	if (!gettingfile && setjmp(restart) != 0)
947		return;
948	gettingfile++;
949	fillit = datafill;
950	if (size == 0 && attrsize > 0) {
951		fillit = attrfill;
952		size = attrsize;
953		attrsize = 0;
954	}
955loop:
956	for (i = 0; i < spcl.c_count; i++) {
957		if (!readmapflag && i > TP_NINDIR) {
958			if (Dflag) {
959				fprintf(stderr, "spcl.c_count = %jd\n",
960				    (intmax_t)spcl.c_count);
961				break;
962			} else
963				panic("spcl.c_count = %jd\n",
964				    (intmax_t)spcl.c_count);
965		}
966		if (readmapflag || spcl.c_addr[i]) {
967			readtape(&buf[curblk++][0]);
968			if (curblk == fssize / TP_BSIZE) {
969				(*fillit)((char *)buf, (long)(size > TP_BSIZE ?
970				     fssize : (curblk - 1) * TP_BSIZE + size));
971				curblk = 0;
972			}
973		} else {
974			if (curblk > 0) {
975				(*fillit)((char *)buf, (long)(size > TP_BSIZE ?
976				     curblk * TP_BSIZE :
977				     (curblk - 1) * TP_BSIZE + size));
978				curblk = 0;
979			}
980			(*skip)(clearedbuf, (long)(size > TP_BSIZE ?
981				TP_BSIZE : size));
982		}
983		if ((size -= TP_BSIZE) <= 0) {
984			if (size > -TP_BSIZE && curblk > 0) {
985				(*fillit)((char *)buf,
986					(long)((curblk * TP_BSIZE) + size));
987				curblk = 0;
988			}
989			if (attrsize > 0) {
990				fillit = attrfill;
991				size = attrsize;
992				attrsize = 0;
993				continue;
994			}
995			if (spcl.c_count - i > 1)
996				dprintf(stdout, "skipping %d junk block(s)\n",
997					spcl.c_count - i - 1);
998			for (i++; i < spcl.c_count; i++) {
999				if (!readmapflag && i > TP_NINDIR) {
1000					if (Dflag) {
1001						fprintf(stderr,
1002						    "spcl.c_count = %jd\n",
1003						    (intmax_t)spcl.c_count);
1004						break;
1005					} else
1006						panic("spcl.c_count = %jd\n",
1007						    (intmax_t)spcl.c_count);
1008				}
1009				if (readmapflag || spcl.c_addr[i])
1010					readtape(junk);
1011			}
1012			break;
1013		}
1014	}
1015	if (gethead(&spcl) == GOOD && size > 0) {
1016		if (spcl.c_type == TS_ADDR)
1017			goto loop;
1018		dprintf(stdout,
1019			"Missing address (header) block for %s at %ld blocks\n",
1020			curfile.name, blksread);
1021	}
1022	if (curblk > 0)
1023		panic("getfile: lost data\n");
1024	findinode(&spcl);
1025	gettingfile = 0;
1026}
1027
1028/*
1029 * These variables are shared between the next two functions.
1030 */
1031static int extbufsize = 0;
1032static char *extbuf;
1033static int extloc;
1034
1035/*
1036 * Allocate a buffer into which to extract extended attributes.
1037 */
1038static char *
1039setupextattr(int extsize)
1040{
1041
1042	extloc = 0;
1043	if (extsize <= extbufsize)
1044		return (extbuf);
1045	if (extbufsize > 0)
1046		free(extbuf);
1047	if ((extbuf = malloc(extsize)) != NULL) {
1048		extbufsize = extsize;
1049		return (extbuf);
1050	}
1051	extbufsize = 0;
1052	extbuf = NULL;
1053	fprintf(stderr, "Cannot extract %d bytes %s for inode %ju, name %s\n",
1054	    extsize, "of extended attributes", (uintmax_t)curfile.ino,
1055	    curfile.name);
1056	return (NULL);
1057}
1058
1059/*
1060 * Extract the next block of extended attributes.
1061 */
1062static void
1063xtrattr(char *buf, long size)
1064{
1065
1066	if (extloc + size > extbufsize)
1067		panic("overrun attribute buffer\n");
1068	memmove(&extbuf[extloc], buf, size);
1069	extloc += size;
1070}
1071
1072/*
1073 * Write out the next block of a file.
1074 */
1075static void
1076xtrfile(char *buf, long	size)
1077{
1078
1079	if (Nflag)
1080		return;
1081	if (write(ofile, buf, (int) size) == -1) {
1082		fprintf(stderr,
1083		    "write error extracting inode %ju, name %s\nwrite: %s\n",
1084		    (uintmax_t)curfile.ino, curfile.name, strerror(errno));
1085	}
1086}
1087
1088/*
1089 * Skip over a hole in a file.
1090 */
1091/* ARGSUSED */
1092static void
1093xtrskip(char *buf, long size)
1094{
1095
1096	if (lseek(ofile, size, SEEK_CUR) == -1) {
1097		fprintf(stderr,
1098		    "seek error extracting inode %ju, name %s\nlseek: %s\n",
1099		    (uintmax_t)curfile.ino, curfile.name, strerror(errno));
1100		done(1);
1101	}
1102}
1103
1104/*
1105 * Collect the next block of a symbolic link.
1106 */
1107static void
1108xtrlnkfile(char *buf, long size)
1109{
1110
1111	pathlen += size;
1112	if (pathlen > MAXPATHLEN) {
1113		fprintf(stderr, "symbolic link name: %s->%s%s; too long %d\n",
1114		    curfile.name, lnkbuf, buf, pathlen);
1115		done(1);
1116	}
1117	(void) strcat(lnkbuf, buf);
1118}
1119
1120/*
1121 * Skip over a hole in a symbolic link (should never happen).
1122 */
1123/* ARGSUSED */
1124static void
1125xtrlnkskip(char *buf, long size)
1126{
1127
1128	fprintf(stderr, "unallocated block in symbolic link %s\n",
1129		curfile.name);
1130	done(1);
1131}
1132
1133/*
1134 * Collect the next block of a bit map.
1135 */
1136static void
1137xtrmap(char *buf, long size)
1138{
1139
1140	memmove(map, buf, size);
1141	map += size;
1142}
1143
1144/*
1145 * Skip over a hole in a bit map (should never happen).
1146 */
1147/* ARGSUSED */
1148static void
1149xtrmapskip(char *buf, long size)
1150{
1151
1152	panic("hole in map\n");
1153	map += size;
1154}
1155
1156/*
1157 * Noop, when an extraction function is not needed.
1158 */
1159/* ARGSUSED */
1160void
1161xtrnull(char *buf, long size)
1162{
1163
1164	return;
1165}
1166
1167/*
1168 * Read TP_BSIZE blocks from the input.
1169 * Handle read errors, and end of media.
1170 */
1171static void
1172readtape(char *buf)
1173{
1174	long rd, newvol, i, oldnumtrec;
1175	int cnt, seek_failed;
1176
1177	if (blkcnt + (byteslide > 0) < numtrec) {
1178		memmove(buf, &tapebuf[(blkcnt++ * TP_BSIZE) + byteslide], (long)TP_BSIZE);
1179		blksread++;
1180		tapeaddr++;
1181		return;
1182	}
1183	if (numtrec > 0)
1184		memmove(&tapebuf[-TP_BSIZE],
1185		    &tapebuf[(numtrec-1) * TP_BSIZE], (long)TP_BSIZE);
1186	oldnumtrec = numtrec;
1187	for (i = 0; i < ntrec; i++)
1188		((struct s_spcl *)&tapebuf[i * TP_BSIZE])->c_magic = 0;
1189	if (numtrec == 0)
1190		numtrec = ntrec;
1191	cnt = ntrec * TP_BSIZE;
1192	rd = 0;
1193getmore:
1194#ifdef RRESTORE
1195	if (host)
1196		i = rmtread(&tapebuf[rd], cnt);
1197	else
1198#endif
1199		i = read(mt, &tapebuf[rd], cnt);
1200	/*
1201	 * Check for mid-tape short read error.
1202	 * If found, skip rest of buffer and start with the next.
1203	 */
1204	if (!pipein && !pipecmdin && numtrec < ntrec && i > 0) {
1205		dprintf(stdout, "mid-media short read error.\n");
1206		numtrec = ntrec;
1207	}
1208	/*
1209	 * Handle partial block read.
1210	 */
1211	if ((pipein || pipecmdin) && i == 0 && rd > 0)
1212		i = rd;
1213	else if (i > 0 && i != ntrec * TP_BSIZE) {
1214		if (pipein || pipecmdin) {
1215			rd += i;
1216			cnt -= i;
1217			if (cnt > 0)
1218				goto getmore;
1219			i = rd;
1220		} else {
1221			/*
1222			 * Short read. Process the blocks read.
1223			 */
1224			if (i % TP_BSIZE != 0)
1225				vprintf(stdout,
1226				    "partial block read: %ld should be %ld\n",
1227				    i, ntrec * TP_BSIZE);
1228			numtrec = i / TP_BSIZE;
1229		}
1230	}
1231	/*
1232	 * Handle read error.
1233	 */
1234	if (i < 0) {
1235		fprintf(stderr, "Tape read error while ");
1236		switch (curfile.action) {
1237		default:
1238			fprintf(stderr, "trying to set up tape\n");
1239			break;
1240		case UNKNOWN:
1241			fprintf(stderr, "trying to resynchronize\n");
1242			break;
1243		case USING:
1244			fprintf(stderr, "restoring %s\n", curfile.name);
1245			break;
1246		case SKIP:
1247			fprintf(stderr, "skipping over inode %ju\n",
1248			    (uintmax_t)curfile.ino);
1249			break;
1250		}
1251		if (!yflag && !reply("continue"))
1252			done(1);
1253		i = ntrec * TP_BSIZE;
1254		memset(tapebuf, 0, i);
1255#ifdef RRESTORE
1256		if (host)
1257			seek_failed = (rmtseek(i, 1) < 0);
1258		else
1259#endif
1260			seek_failed = (lseek(mt, i, SEEK_CUR) == (off_t)-1);
1261
1262		if (seek_failed) {
1263			fprintf(stderr,
1264			    "continuation failed: %s\n", strerror(errno));
1265			done(1);
1266		}
1267	}
1268	/*
1269	 * Handle end of tape.
1270	 */
1271	if (i == 0) {
1272		vprintf(stdout, "End-of-tape encountered\n");
1273		if (!pipein) {
1274			newvol = volno + 1;
1275			volno = 0;
1276			numtrec = 0;
1277			getvol(newvol);
1278			readtape(buf);
1279			return;
1280		}
1281		if (rd % TP_BSIZE != 0)
1282			panic("partial block read: %ld should be %ld\n",
1283				rd, ntrec * TP_BSIZE);
1284		terminateinput();
1285		memmove(&tapebuf[rd], &endoftapemark, (long)TP_BSIZE);
1286	}
1287	if (oldnumtrec == 0)
1288		blkcnt = 0;
1289	else
1290		blkcnt -= oldnumtrec;
1291	memmove(buf,
1292	    &tapebuf[(blkcnt++ * TP_BSIZE) + byteslide], (long)TP_BSIZE);
1293	blksread++;
1294	tapeaddr++;
1295}
1296
1297static void
1298findtapeblksize(void)
1299{
1300	long i;
1301
1302	for (i = 0; i < ntrec; i++)
1303		((struct s_spcl *)&tapebuf[i * TP_BSIZE])->c_magic = 0;
1304	blkcnt = 0;
1305#ifdef RRESTORE
1306	if (host)
1307		i = rmtread(tapebuf, ntrec * TP_BSIZE);
1308	else
1309#endif
1310		i = read(mt, tapebuf, ntrec * TP_BSIZE);
1311
1312	if (i <= 0) {
1313		fprintf(stderr, "tape read error: %s\n", strerror(errno));
1314		done(1);
1315	}
1316	if (i % TP_BSIZE != 0) {
1317		fprintf(stderr, "Tape block size (%ld) %s (%d)\n",
1318			i, "is not a multiple of dump block size", TP_BSIZE);
1319		done(1);
1320	}
1321	ntrec = i / TP_BSIZE;
1322	numtrec = ntrec;
1323	vprintf(stdout, "Tape block size is %ld\n", ntrec);
1324}
1325
1326void
1327closemt(void)
1328{
1329
1330	if (mt < 0)
1331		return;
1332	if (pipecmdin) {
1333		pclose(popenfp);
1334		popenfp = NULL;
1335	} else
1336#ifdef RRESTORE
1337	if (host)
1338		rmtclose();
1339	else
1340#endif
1341		(void) close(mt);
1342}
1343
1344/*
1345 * Read the next block from the tape.
1346 * If it is not any valid header, return an error.
1347 */
1348static int
1349gethead(struct s_spcl *buf)
1350{
1351	long i;
1352
1353	readtape((char *)buf);
1354	if (buf->c_magic != FS_UFS2_MAGIC && buf->c_magic != NFS_MAGIC) {
1355		if (buf->c_magic == OFS_MAGIC) {
1356			fprintf(stderr,
1357			    "Format of dump tape is too old. Must use\n");
1358			fprintf(stderr,
1359			    "a version of restore from before 2002.\n");
1360			return (FAIL);
1361		}
1362		if (swabl(buf->c_magic) != FS_UFS2_MAGIC &&
1363		    buf->c_magic != NFS_MAGIC) {
1364			if (buf->c_magic == OFS_MAGIC) {
1365				fprintf(stderr,
1366				  "Format of dump tape is too old. Must use\n");
1367				fprintf(stderr,
1368				  "a version of restore from before 2002.\n");
1369			}
1370			return (FAIL);
1371		}
1372		if (!Bcvt) {
1373			vprintf(stdout, "Note: Doing Byte swapping\n");
1374			Bcvt = 1;
1375		}
1376	}
1377	if (checksum((int *)buf) == FAIL)
1378		return (FAIL);
1379	if (Bcvt) {
1380		swabst((u_char *)"8l4s1q8l2q17l", (u_char *)buf);
1381		swabst((u_char *)"l",(u_char *) &buf->c_level);
1382		swabst((u_char *)"2l4q",(u_char *) &buf->c_flags);
1383	}
1384	readmapflag = 0;
1385
1386	switch (buf->c_type) {
1387
1388	case TS_CLRI:
1389	case TS_BITS:
1390		/*
1391		 * Have to patch up missing information in bit map headers
1392		 */
1393		buf->c_size = buf->c_count * TP_BSIZE;
1394		if (buf->c_count > TP_NINDIR)
1395			readmapflag = 1;
1396		else
1397			for (i = 0; i < buf->c_count; i++)
1398				buf->c_addr[i]++;
1399		/* FALL THROUGH */
1400
1401	case TS_TAPE:
1402		if (buf->c_magic == NFS_MAGIC &&
1403		    (buf->c_flags & NFS_DR_NEWINODEFMT) == 0)
1404			oldinofmt = 1;
1405		/* FALL THROUGH */
1406
1407	case TS_END:
1408		buf->c_inumber = 0;
1409		/* FALL THROUGH */
1410
1411	case TS_ADDR:
1412	case TS_INODE:
1413		/*
1414		 * For old dump tapes, have to copy up old fields to
1415		 * new locations.
1416		 */
1417		if (buf->c_magic == NFS_MAGIC) {
1418			buf->c_tapea = buf->c_old_tapea;
1419			buf->c_firstrec = buf->c_old_firstrec;
1420			buf->c_date = _time32_to_time(buf->c_old_date);
1421			buf->c_ddate = _time32_to_time(buf->c_old_ddate);
1422			buf->c_atime = _time32_to_time(buf->c_old_atime);
1423			buf->c_mtime = _time32_to_time(buf->c_old_mtime);
1424			buf->c_birthtime = 0;
1425			buf->c_birthtimensec = 0;
1426			buf->c_extsize = 0;
1427		}
1428		break;
1429
1430	default:
1431		panic("gethead: unknown inode type %d\n", buf->c_type);
1432		break;
1433	}
1434	if (dumpdate != 0 && _time64_to_time(buf->c_date) != dumpdate)
1435		fprintf(stderr, "Header with wrong dumpdate.\n");
1436	/*
1437	 * If we're restoring a filesystem with the old (FreeBSD 1)
1438	 * format inodes, copy the uid/gid to the new location
1439	 */
1440	if (oldinofmt) {
1441		buf->c_uid = buf->c_spare1[1];
1442		buf->c_gid = buf->c_spare1[2];
1443	}
1444	buf->c_magic = FS_UFS2_MAGIC;
1445	tapeaddr = buf->c_tapea;
1446	if (dflag)
1447		accthdr(buf);
1448	return(GOOD);
1449}
1450
1451/*
1452 * Check that a header is where it belongs and predict the next header
1453 */
1454static void
1455accthdr(struct s_spcl *header)
1456{
1457	static ino_t previno = 0x7fffffff;
1458	static int prevtype;
1459	static long predict;
1460	long blks, i;
1461
1462	if (header->c_type == TS_TAPE) {
1463		fprintf(stderr, "Volume header ");
1464 		if (header->c_firstrec)
1465 			fprintf(stderr, "begins with record %jd",
1466			    (intmax_t)header->c_firstrec);
1467 		fprintf(stderr, "\n");
1468		previno = 0x7fffffff;
1469		return;
1470	}
1471	if (previno == 0x7fffffff)
1472		goto newcalc;
1473	switch (prevtype) {
1474	case TS_BITS:
1475		fprintf(stderr, "Dumped inodes map header");
1476		break;
1477	case TS_CLRI:
1478		fprintf(stderr, "Used inodes map header");
1479		break;
1480	case TS_INODE:
1481		fprintf(stderr, "File header, ino %ju", (uintmax_t)previno);
1482		break;
1483	case TS_ADDR:
1484		fprintf(stderr, "File continuation header, ino %ju",
1485		    (uintmax_t)previno);
1486		break;
1487	case TS_END:
1488		fprintf(stderr, "End of tape header");
1489		break;
1490	}
1491	if (predict != blksread - 1)
1492		fprintf(stderr, "; predicted %ld blocks, got %ld blocks",
1493			predict, blksread - 1);
1494	fprintf(stderr, "\n");
1495newcalc:
1496	blks = 0;
1497	if (header->c_type != TS_END)
1498		for (i = 0; i < header->c_count; i++)
1499			if (readmapflag || header->c_addr[i] != 0)
1500				blks++;
1501	predict = blks;
1502	blksread = 0;
1503	prevtype = header->c_type;
1504	previno = header->c_inumber;
1505}
1506
1507/*
1508 * Find an inode header.
1509 * Complain if had to skip.
1510 */
1511static void
1512findinode(struct s_spcl *header)
1513{
1514	static long skipcnt = 0;
1515	long i;
1516	char buf[TP_BSIZE];
1517	int htype;
1518
1519	curfile.name = "<name unknown>";
1520	curfile.action = UNKNOWN;
1521	curfile.mode = 0;
1522	curfile.ino = 0;
1523	do {
1524		htype = header->c_type;
1525		switch (htype) {
1526
1527		case TS_ADDR:
1528			/*
1529			 * Skip up to the beginning of the next record
1530			 */
1531			for (i = 0; i < header->c_count; i++)
1532				if (header->c_addr[i])
1533					readtape(buf);
1534			while (gethead(header) == FAIL ||
1535			    _time64_to_time(header->c_date) != dumpdate) {
1536				skipcnt++;
1537				if (Dflag) {
1538					byteslide++;
1539					if (byteslide < TP_BSIZE) {
1540						blkcnt--;
1541						blksread--;
1542					} else
1543						byteslide = 0;
1544				}
1545			}
1546			break;
1547
1548		case TS_INODE:
1549			curfile.mode = header->c_mode;
1550			curfile.uid = header->c_uid;
1551			curfile.gid = header->c_gid;
1552			curfile.file_flags = header->c_file_flags;
1553			curfile.rdev = header->c_rdev;
1554			curfile.atime_sec = header->c_atime;
1555			curfile.atime_nsec = header->c_atimensec;
1556			curfile.mtime_sec = header->c_mtime;
1557			curfile.mtime_nsec = header->c_mtimensec;
1558			curfile.birthtime_sec = header->c_birthtime;
1559			curfile.birthtime_nsec = header->c_birthtimensec;
1560			curfile.extsize = header->c_extsize;
1561			curfile.size = header->c_size;
1562			curfile.ino = header->c_inumber;
1563			break;
1564
1565		case TS_END:
1566			/* If we missed some tapes, get another volume. */
1567			if (tapesread & (tapesread + 1)) {
1568				getvol(0);
1569				continue;
1570			}
1571			curfile.ino = maxino;
1572			break;
1573
1574		case TS_CLRI:
1575			curfile.name = "<file removal list>";
1576			break;
1577
1578		case TS_BITS:
1579			curfile.name = "<file dump list>";
1580			break;
1581
1582		case TS_TAPE:
1583			if (Dflag)
1584				fprintf(stderr, "unexpected tape header\n");
1585			else
1586				panic("unexpected tape header\n");
1587
1588		default:
1589			if (Dflag)
1590				fprintf(stderr, "unknown tape header type %d\n",
1591				    spcl.c_type);
1592			else
1593				panic("unknown tape header type %d\n",
1594				    spcl.c_type);
1595			while (gethead(header) == FAIL ||
1596			    _time64_to_time(header->c_date) != dumpdate) {
1597				skipcnt++;
1598				if (Dflag) {
1599					byteslide++;
1600					if (byteslide < TP_BSIZE) {
1601						blkcnt--;
1602						blksread--;
1603					} else
1604						byteslide = 0;
1605				}
1606			}
1607
1608		}
1609	} while (htype == TS_ADDR);
1610	if (skipcnt > 0)
1611		fprintf(stderr, "resync restore, skipped %ld %s\n",
1612		    skipcnt, Dflag ? "bytes" : "blocks");
1613	skipcnt = 0;
1614}
1615
1616static int
1617checksum(int *buf)
1618{
1619	int i, j;
1620
1621	j = sizeof(union u_spcl) / sizeof(int);
1622	i = 0;
1623	if (!Bcvt) {
1624		do
1625			i += *buf++;
1626		while (--j);
1627	} else {
1628		/* What happens if we want to read restore tapes
1629			for a 16bit int machine??? */
1630		do
1631			i += swabl(*buf++);
1632		while (--j);
1633	}
1634
1635	if (i != CHECKSUM) {
1636		fprintf(stderr, "Checksum error %o, inode %ju file %s\n", i,
1637		    (uintmax_t)curfile.ino, curfile.name);
1638		return(FAIL);
1639	}
1640	return(GOOD);
1641}
1642
1643#ifdef RRESTORE
1644#include <stdarg.h>
1645
1646void
1647msg(const char *fmt, ...)
1648{
1649	va_list ap;
1650	va_start(ap, fmt);
1651	(void)vfprintf(stderr, fmt, ap);
1652	va_end(ap);
1653}
1654#endif /* RRESTORE */
1655
1656static u_char *
1657swabshort(u_char *sp, int n)
1658{
1659	char c;
1660
1661	while (--n >= 0) {
1662		c = sp[0]; sp[0] = sp[1]; sp[1] = c;
1663		sp += 2;
1664	}
1665	return (sp);
1666}
1667
1668static u_char *
1669swablong(u_char *sp, int n)
1670{
1671	char c;
1672
1673	while (--n >= 0) {
1674		c = sp[0]; sp[0] = sp[3]; sp[3] = c;
1675		c = sp[2]; sp[2] = sp[1]; sp[1] = c;
1676		sp += 4;
1677	}
1678	return (sp);
1679}
1680
1681static u_char *
1682swabquad(u_char *sp, int n)
1683{
1684	char c;
1685
1686	while (--n >= 0) {
1687		c = sp[0]; sp[0] = sp[7]; sp[7] = c;
1688		c = sp[1]; sp[1] = sp[6]; sp[6] = c;
1689		c = sp[2]; sp[2] = sp[5]; sp[5] = c;
1690		c = sp[3]; sp[3] = sp[4]; sp[4] = c;
1691		sp += 8;
1692	}
1693	return (sp);
1694}
1695
1696void
1697swabst(u_char *cp, u_char *sp)
1698{
1699	int n = 0;
1700
1701	while (*cp) {
1702		switch (*cp) {
1703		case '0': case '1': case '2': case '3': case '4':
1704		case '5': case '6': case '7': case '8': case '9':
1705			n = (n * 10) + (*cp++ - '0');
1706			continue;
1707
1708		case 's': case 'w': case 'h':
1709			if (n == 0)
1710				n = 1;
1711			sp = swabshort(sp, n);
1712			break;
1713
1714		case 'l':
1715			if (n == 0)
1716				n = 1;
1717			sp = swablong(sp, n);
1718			break;
1719
1720		case 'q':
1721			if (n == 0)
1722				n = 1;
1723			sp = swabquad(sp, n);
1724			break;
1725
1726		case 'b':
1727			if (n == 0)
1728				n = 1;
1729			sp += n;
1730			break;
1731
1732		default:
1733			fprintf(stderr, "Unknown conversion character: %c\n",
1734			    *cp);
1735			done(0);
1736			break;
1737		}
1738		cp++;
1739		n = 0;
1740	}
1741}
1742
1743static u_long
1744swabl(u_long x)
1745{
1746	swabst((u_char *)"l", (u_char *)&x);
1747	return (x);
1748}
1749