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