]> git.wh0rd.org Git - dump.git/blob - restore/tape.c
Eliminate unexistent prototype gcc warning.
[dump.git] / restore / tape.c
1 /*
2  *      Ported to Linux's Second Extended File System as part of the
3  *      dump and restore backup suit
4  *      Remy Card <card@Linux.EU.Org>, 1994-1997
5  *      Stelian Pop <stelian@popies.net>, 1999-2000
6  *      Stelian Pop <stelian@popies.net> - AlcĂ´ve <www.alcove.com>, 2000-2002
7  */
8
9 /*
10  * Copyright (c) 1983, 1993
11  *      The Regents of the University of California.  All rights reserved.
12  * (c) UNIX System Laboratories, Inc.
13  * All or some portions of this file are derived from material licensed
14  * to the University of California by American Telephone and Telegraph
15  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
16  * the permission of UNIX System Laboratories, Inc.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  * 3. All advertising materials mentioning features or use of this software
27  *    must display the following acknowledgement:
28  *      This product includes software developed by the University of
29  *      California, Berkeley and its contributors.
30  * 4. Neither the name of the University nor the names of its contributors
31  *    may be used to endorse or promote products derived from this software
32  *    without specific prior written permission.
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
35  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
36  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
37  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
38  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
39  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
40  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
41  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
42  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
43  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
44  * SUCH DAMAGE.
45  */
46
47 #ifndef lint
48 static const char rcsid[] =
49         "$Id: tape.c,v 1.65 2002/11/15 09:25:42 stelian Exp $";
50 #endif /* not lint */
51
52 #include <config.h>
53 #include <compatlfs.h>
54 #include <errno.h>
55 #include <compaterr.h>
56 #include <system.h>
57 #include <setjmp.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62
63 #include <sys/param.h>
64 #include <sys/file.h>
65 #include <sys/mtio.h>
66 #include <sys/stat.h>
67
68 #ifdef  __linux__
69 #include <sys/time.h>
70 #include <time.h>
71 #ifdef HAVE_EXT2FS_EXT2_FS_H
72 #include <ext2fs/ext2_fs.h>
73 #else
74 #include <linux/ext2_fs.h>
75 #endif
76 #include <ext2fs/ext2fs.h>
77 #include <bsdcompat.h>
78 #else   /* __linux__ */
79 #include <ufs/ufs/dinode.h>
80 #endif  /* __linux__ */
81 #include <protocols/dumprestore.h>
82
83 #ifdef HAVE_ZLIB
84 #include <zlib.h>
85 #endif /* HAVE_ZLIB */
86
87 #ifdef HAVE_BZLIB
88 #include <bzlib.h>
89 #endif /* HAVE_BZLIB */
90
91 #include "restore.h"
92 #include "extern.h"
93 #include "pathnames.h"
94
95 #ifdef USE_QFA
96 int             noresyncmesg = 0;
97 #endif /* USE_QFA */
98 static long     fssize = MAXBSIZE;
99 static int      mt = -1;
100 int             pipein = 0;
101 static int      magtapein = 0;          /* input is from magtape */
102 static char     magtape[MAXPATHLEN];
103 static char     magtapeprefix[MAXPATHLEN];
104 static int      blkcnt;
105 static int      numtrec;
106 static char     *tapebuf;               /* input buffer for read */
107 static int      bufsize;                /* buffer size without prefix */
108 static char     *tbufptr = NULL;        /* active tape buffer */
109 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB)
110 static char     *comprbuf;              /* uncompress work buf */
111 static size_t   comprlen;               /* size including prefix */
112 #endif
113 static union    u_spcl endoftapemark;
114 static long     blksread;               /* blocks read since last header */
115 static long     tpblksread = 0;         /* TP_BSIZE blocks read */
116 static long     tapesread;
117 static sigjmp_buf       restart;
118 static int      gettingfile = 0;        /* restart has a valid frame */
119 char            *host = NULL;
120
121 static int      ofile;
122 static char     *map;
123 static char     lnkbuf[MAXPATHLEN + 1];
124 static int      pathlen;
125
126 int             oldinofmt;      /* old inode format conversion required */
127 int             Bcvt;           /* Swap Bytes (for CCI or sun) */
128 static int      Qcvt;           /* Swap quads (for sun) */
129
130 #define FLUSHTAPEBUF()  blkcnt = ntrec + 1
131
132 static void      accthdr __P((struct s_spcl *));
133 static int       checksum __P((int *));
134 static void      findinode __P((struct s_spcl *));
135 static void      findtapeblksize __P((void));
136 static int       gethead __P((struct s_spcl *));
137 static void      readtape __P((char *));
138 static void      setdumpnum __P((void));
139 static u_int     swabi __P((u_int));
140 #if 0
141 static u_long    swabl __P((u_long));
142 #endif
143 static u_char   *swab64 __P((u_char *, int));
144 static u_char   *swab32 __P((u_char *, int));
145 static u_char   *swab16 __P((u_char *, int));
146 static void      terminateinput __P((void));
147 static void      xtrfile __P((char *, size_t));
148 static void      xtrlnkfile __P((char *, size_t));
149 static void      xtrlnkskip __P((char *, size_t));
150 static void      xtrmap __P((char *, size_t));
151 static void      xtrmapskip __P((char *, size_t));
152 static void      xtrskip __P((char *, size_t));
153 static void      setmagtapein __P((void));
154
155 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB)
156 static void     newcomprbuf __P((int));
157 static void     (*readtape_func) __P((char *));
158 static void     readtape_set __P((char *));
159 static void     readtape_uncompr __P((char *));
160 static void     readtape_comprfile __P((char *));
161 static void     readtape_comprtape __P((char *));
162 static char     *decompress_tapebuf __P((struct tapebuf *, int));
163 static void     msg_read_error __P((char *));
164 #endif
165 static int      read_a_block __P((int, char *, size_t, long *));
166 #define PREFIXSIZE      sizeof(struct tapebuf)
167
168 #define COMPARE_ONTHEFLY 1
169
170 #if COMPARE_ONTHEFLY
171 static int      ifile;          /* input file for compare */
172 static int      cmperror;       /* compare error */
173 static void     xtrcmpfile __P((char *, size_t));
174 static void     xtrcmpskip __P((char *, size_t));
175 #endif
176
177 static int readmapflag;
178 static int readingmaps;         /* set to 1 while reading the maps */
179
180 /*
181  * Set up an input source. This is called from main.c before setup() is.
182  */
183 void
184 setinput(char *source)
185 {
186         FLUSHTAPEBUF();
187         if (bflag)
188                 newtapebuf(ntrec);
189         else
190                 newtapebuf(NTREC > HIGHDENSITYTREC ? NTREC : HIGHDENSITYTREC);
191         terminal = stdin;
192
193 #ifdef RRESTORE
194         if (strchr(source, ':')) {
195                 host = source;
196                 source = strchr(host, ':');
197                 *source++ = '\0';
198                 if (rmthost(host) == 0)
199                         exit(1);
200         } else
201 #endif
202         if (strcmp(source, "-") == 0) {
203                 /*
204                  * Since input is coming from a pipe we must establish
205                  * our own connection to the terminal.
206                  */
207                 terminal = fopen(_PATH_TTY, "r");
208                 if (terminal == NULL) {
209                         warn("cannot open %s", _PATH_TTY);
210                         terminal = fopen(_PATH_DEVNULL, "r");
211                         if (terminal == NULL)
212                                 err(1, "cannot open %s", _PATH_DEVNULL);
213                 }
214                 pipein++;
215         }
216         setuid(getuid());       /* no longer need or want root privileges */
217         if (Mflag) {
218                 strncpy(magtapeprefix, source, MAXPATHLEN);
219                 magtapeprefix[MAXPATHLEN-1] = '\0';
220                 snprintf(magtape, MAXPATHLEN, "%s%03d", source, 1);
221         }
222         else
223                 strncpy(magtape, source, MAXPATHLEN);
224         magtape[MAXPATHLEN - 1] = '\0';
225 }
226
227 void
228 newtapebuf(long size)
229 {
230         static int tapebufsize = -1;
231
232         ntrec = size;
233         bufsize = ntrec * TP_BSIZE;
234         if (size <= tapebufsize)
235                 return;
236         if (tapebuf != NULL)
237                 free(tapebuf);
238         tapebuf = malloc(size * TP_BSIZE + sizeof(struct tapebuf));
239         if (tapebuf == NULL)
240                 errx(1, "Cannot allocate space for tape buffer");
241         tapebufsize = size;
242 }
243
244 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB)
245 static void
246 newcomprbuf(int size)
247 {
248         size_t buf_size = (size+1) * TP_BSIZE + sizeof(struct tapebuf);
249         if (buf_size <= comprlen)
250                 return;
251         comprlen = buf_size;
252         if (comprbuf != NULL)
253                 free(comprbuf);
254         comprbuf = malloc(comprlen);
255         if (comprbuf == NULL)
256                 errx(1, "Cannot allocate space for decompress buffer");
257 }
258 #endif /* HAVE_ZLIB || HAVE_BZLIB */
259
260 /*
261  * Verify that the tape drive can be accessed and
262  * that it actually is a dump tape.
263  */
264 void
265 setup(void)
266 {
267         int i, j, *ip, bot_code;
268         struct STAT stbuf;
269         char *temptape;
270
271         Vprintf(stdout, "Verify tape and initialize maps\n");
272         if (Afile == NULL && bot_script) {
273                 msg("Launching %s\n", bot_script);
274                 bot_code = system_command(bot_script, magtape, 1);
275                 if (bot_code != 0 && bot_code != 1) {
276                         msg("Restore aborted by the beginning of tape script\n");
277                         exit(1);
278                 }
279         }
280
281         if (Afile)
282                 temptape = Afile;
283         else
284                 temptape = magtape;
285
286 #ifdef RRESTORE
287         if (host)
288                 mt = rmtopen(temptape, O_RDONLY);
289         else
290 #endif
291         if (pipein)
292                 mt = 0;
293         else
294                 mt = OPEN(temptape, O_RDONLY, 0);
295         if (mt < 0)
296                 err(1, "%s", magtape);
297         if (!Afile) {
298                 volno = 1;
299                 setmagtapein();
300                 setdumpnum();
301         }
302 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB)
303         readtape_func = readtape_set;
304 #endif
305         FLUSHTAPEBUF();
306         findtapeblksize();
307         if (gethead(&spcl) == FAIL) {
308                 blkcnt--; /* push back this block */
309                 blksread--;
310                 tpblksread--;
311                 cvtflag++;
312                 if (gethead(&spcl) == FAIL)
313                         errx(1, "Tape is not a dump tape");
314                 fprintf(stderr, "Converting to new file system format.\n");
315         }
316
317         if (zflag) {
318                 fprintf(stderr, "Dump tape is compressed.\n");
319 #if !defined(HAVE_ZLIB) && !defined(HAVE_BZLIB)
320                 errx(1,"This restore version doesn't support decompression");
321 #endif /* !HAVE_ZLIB && !HAVE_BZLIB */
322         }
323         if (pipein) {
324                 endoftapemark.s_spcl.c_magic = cvtflag ? OFS_MAGIC : NFS_MAGIC;
325                 endoftapemark.s_spcl.c_type = TS_END;
326                 ip = (int *)&endoftapemark;
327                 j = sizeof(union u_spcl) / sizeof(int);
328                 i = 0;
329                 do
330                         i += *ip++;
331                 while (--j);
332                 endoftapemark.s_spcl.c_checksum = CHECKSUM - i;
333         }
334         if (vflag || command == 't' || command == 'C')
335                 printdumpinfo();
336 #ifdef USE_QFA
337         if (tapeposflag && (unsigned long)spcl.c_date != qfadumpdate)
338                 errx(1, "different QFA/dumpdates detected\n");
339 #endif
340         if (filesys[0] == '\0') {
341                 char *dirptr;
342                 strncpy(filesys, spcl.c_filesys, NAMELEN);
343                 filesys[NAMELEN - 1] = '\0';
344                 dirptr = strstr(filesys, " (dir");
345                 if (dirptr != NULL)
346                         *dirptr = '\0';
347         }
348         dumptime = spcl.c_ddate;
349         dumpdate = spcl.c_date;
350         if (STAT(".", &stbuf) < 0)
351                 err(1, "cannot stat .");
352         if (stbuf.st_blksize > 0 && stbuf.st_blksize < TP_BSIZE )
353                 fssize = TP_BSIZE;
354         if (stbuf.st_blksize >= TP_BSIZE && stbuf.st_blksize <= MAXBSIZE)
355                 fssize = stbuf.st_blksize;
356         if (((fssize - 1) & fssize) != 0)
357                 errx(1, "bad block size %ld", fssize);
358         if (spcl.c_volume != 1)
359                 errx(1, "Tape is not volume 1 of the dump");
360         if (gethead(&spcl) == FAIL) {
361                 Dprintf(stdout, "header read failed at %ld blocks\n", (long)blksread);
362                 panic("no header after volume mark!\n");
363         }
364         readingmaps = 1;
365         findinode(&spcl);
366         if (spcl.c_type != TS_CLRI)
367                 errx(1, "Cannot find file removal list");
368         maxino = (spcl.c_count * TP_BSIZE * NBBY) + 1;
369         map = calloc((unsigned)1, (unsigned)howmany(maxino, NBBY));
370         if (map == NULL)
371                 errx(1, "no memory for active inode map");
372         usedinomap = map;
373         curfile.action = USING;
374         getfile(xtrmap, xtrmapskip);
375         while (spcl.c_type == TS_ADDR) {
376                 /* Recompute maxino and the map */
377                 dump_ino_t oldmaxino = maxino;
378                 maxino += (spcl.c_count * TP_BSIZE * NBBY) + 1;
379                 resizemaps(oldmaxino, maxino);
380
381                 spcl.c_dinode.di_size = spcl.c_count * TP_BSIZE;
382                 getfile(xtrmap, xtrmapskip);
383         }
384         Dprintf(stdout, "maxino = %lu\n", (unsigned long)maxino);
385         if (spcl.c_type != TS_BITS)
386                 errx(1, "Cannot find file dump list");
387         map = calloc((unsigned)1, (unsigned)howmany(maxino, NBBY));
388         if (map == (char *)NULL)
389                 errx(1, "no memory for file dump list");
390         dumpmap = map;
391         curfile.action = USING;
392         getfile(xtrmap, xtrmapskip);
393         while (spcl.c_type == TS_ADDR) {
394                 spcl.c_dinode.di_size = spcl.c_count * TP_BSIZE;
395                 getfile(xtrmap, xtrmapskip);
396         }
397         /*
398          * If there may be whiteout entries on the tape, pretend that the
399          * whiteout inode exists, so that the whiteout entries can be
400          * extracted.
401          */
402         if (oldinofmt == 0)
403                 SETINO(WINO, dumpmap);
404         readingmaps = 0;
405         findinode(&spcl);
406 }
407
408 /*
409  * Prompt user to load a new dump volume.
410  * "Nextvol" is the next suggested volume to use.
411  * This suggested volume is enforced when doing full
412  * or incremental restores, but can be overridden by
413  * the user when only extracting a subset of the files.
414  */
415 void
416 getvol(long nextvol)
417 {
418         long newvol = 0, wantnext = 0, i;
419         long saved_blksread = 0, saved_tpblksread = 0;
420         union u_spcl tmpspcl;
421 #       define tmpbuf tmpspcl.s_spcl
422         char buf[TP_BSIZE];
423         int haderror = 0, bot_code = 1;
424
425         if (nextvol == 1) {
426                 tapesread = 0;
427                 gettingfile = 0;
428                 tpblksread = 0;
429                 blksread = 0;
430         }
431         if (pipein) {
432                 if (nextvol != 1)
433                         panic("Changing volumes on pipe input?\n");
434                 if (volno == 1)
435                         return;
436                 goto gethdr;
437         }
438         saved_blksread = blksread;
439         saved_tpblksread = tpblksread;
440 #if defined(USE_QFA) && defined(sunos)
441         if (createtapeposflag || tapeposflag) 
442                 close(fdsmtc);
443 #endif
444 again:
445         if (pipein)
446                 exit(1); /* pipes do not get a second chance */
447         if (aflag || curfile.action != SKIP) {
448                 newvol = nextvol;
449                 wantnext = 1;
450         } else {
451                 newvol = 0;
452                 wantnext = 0;
453         }
454         while (newvol <= 0) {
455                 if (tapesread == 0) {
456                         fprintf(stderr, "%s%s%s%s%s",
457                             "You have not read any volumes yet.\n",
458                             "Unless you know which volume your",
459                             " file(s) are on you should start\n",
460                             "with the last volume and work",
461                             " towards the first.\n");
462                 } else {
463                         fprintf(stderr, "You have read volumes");
464                         strcpy(buf, ": ");
465                         for (i = 1; i < 32; i++)
466                                 if (tapesread & (1 << i)) {
467                                         fprintf(stderr, "%s%ld", buf, (long)i);
468                                         strcpy(buf, ", ");
469                                 }
470                         fprintf(stderr, "\n");
471                 }
472                 do      {
473                         fprintf(stderr, "Specify next volume # (none if no more volumes): ");
474                         (void) fflush(stderr);
475                         (void) fgets(buf, TP_BSIZE, terminal);
476                 } while (!feof(terminal) && buf[0] == '\n');
477                 if (feof(terminal))
478                         exit(1);
479                 if (!strcmp(buf, "none\n")) {
480                         terminateinput();
481                         return;
482                 }
483                 newvol = atoi(buf);
484                 if (newvol <= 0) {
485                         fprintf(stderr,
486                             "Volume numbers are positive numerics\n");
487                 }
488         }
489         if (newvol == volno) {
490                 tapesread |= 1 << volno;
491 #if defined(USE_QFA) && defined(sunos)
492                 if (createtapeposflag || tapeposflag) {
493                         if (OpenSMTCmt(magtape) < 0) {
494                                 volno = -1;
495                                 haderror = 1;
496                                 goto again;
497                         }
498                 }
499 #endif
500                 return;
501         }
502         closemt();
503         if (Mflag) {
504                 snprintf(magtape, MAXPATHLEN, "%s%03ld", magtapeprefix, newvol);
505                 magtape[MAXPATHLEN - 1] = '\0';
506         }
507         if (bot_script && !haderror) {
508                 msg("Launching %s\n", bot_script);
509                 bot_code = system_command(bot_script, magtape, newvol);
510                 if (bot_code != 0 && bot_code != 1) {
511                         msg("Restore aborted by the beginning of tape script\n");
512                         exit(1);
513                 }
514         }
515         if (haderror || (bot_code && !Mflag)) {
516                 haderror = 0;
517                 fprintf(stderr, "Mount volume %ld\n", (long)newvol);
518                 fprintf(stderr, "Enter ``none'' if there are no more volumes\n");
519                 fprintf(stderr, "otherwise enter volume name (default: %s) ", magtape);
520                 (void) fflush(stderr);
521                 (void) fgets(buf, TP_BSIZE, terminal);
522                 if (feof(terminal))
523                         exit(1);
524                 if (!strcmp(buf, "none\n")) {
525                         terminateinput();
526                         return;
527                 }
528                 if (buf[0] != '\n') {
529                         char *pos;
530                         (void) strncpy(magtape, buf, sizeof(magtape));
531                         magtape[sizeof(magtape) - 1] = '\0';
532                         if ((pos = strchr(magtape, '\n'))) 
533                                 magtape[pos - magtape] = '\0';
534                 }
535         }
536 #ifdef RRESTORE
537         if (host)
538                 mt = rmtopen(magtape, O_RDONLY);
539         else
540 #endif
541                 mt = OPEN(magtape, O_RDONLY, 0);
542
543         if (mt == -1) {
544                 fprintf(stderr, "Cannot open %s\n", magtape);
545                 volno = -1;
546                 haderror = 1;
547                 goto again;
548         }
549 gethdr:
550         setmagtapein();
551 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB)
552         readtape_func = readtape_set;
553 #endif
554         volno = newvol;
555         setdumpnum();
556         FLUSHTAPEBUF();
557         findtapeblksize();
558         if (gethead(&tmpbuf) == FAIL) {
559                 Dprintf(stdout, "header read failed at %ld blocks\n", (long)blksread);
560                 fprintf(stderr, "tape is not dump tape\n");
561                 volno = 0;
562                 haderror = 1;
563                 blksread = saved_blksread;
564                 tpblksread = saved_tpblksread;
565                 goto again;
566         }
567         if (tmpbuf.c_volume != volno) {
568                 fprintf(stderr, "Wrong volume (%d)\n", tmpbuf.c_volume);
569                 volno = 0;
570                 haderror = 1;
571                 blksread = saved_blksread;
572                 tpblksread = saved_tpblksread;
573                 goto again;
574         }
575         if (tmpbuf.c_date != dumpdate || tmpbuf.c_ddate != dumptime) {
576                 fprintf(stderr, "Wrong dump date\n\tgot: %s",
577                         ctime4(&tmpbuf.c_date));
578                 fprintf(stderr, "\twanted: %s", ctime(&dumpdate));
579                 volno = 0;
580                 haderror = 1;
581                 blksread = saved_blksread;
582                 tpblksread = saved_tpblksread;
583                 goto again;
584         }
585         tapesread |= 1 << volno;
586         /*
587          * If continuing from the previous volume, skip over any
588          * blocks read already at the end of the previous volume.
589          *
590          * If coming to this volume at random, skip to the beginning
591          * of the next record.
592          */
593         if (zflag) {
594                 fprintf(stderr, "Dump tape is compressed.\n");
595 #if !defined(HAVE_ZLIB) && !defined(HAVE_BZLIB)
596                 errx(1,"This restore version doesn't support decompression");
597 #endif /* !HAVE_ZLIB && !HAVE_BZLIB */
598         }
599         Dprintf(stdout, "read %ld recs, tape starts with %ld\n",
600                 tpblksread - 1, (long)tmpbuf.c_firstrec);
601         if (tmpbuf.c_type == TS_TAPE && (tmpbuf.c_flags & DR_NEWHEADER)) {
602                 if (!wantnext) {
603                         tpblksread = tmpbuf.c_firstrec + 1;
604                         for (i = tmpbuf.c_count; i > 0; i--)
605                                 readtape(buf);
606                 } else if (tmpbuf.c_firstrec > 0 &&
607                            tmpbuf.c_firstrec < tpblksread - 1) {
608                         /*
609                          * -1 since we've read the volume header
610                          */
611                         i = tpblksread - tmpbuf.c_firstrec - 1;
612                         Dprintf(stderr, "Skipping %ld duplicate record%s.\n",
613                                 (long)i, i > 1 ? "s" : "");
614                         while (--i >= 0)
615                                 readtape(buf);
616                 }
617         }
618         if (curfile.action == USING) {
619                 if (volno == 1)
620                         panic("active file into volume 1\n");
621                 return;
622         }
623         /*
624          * Skip up to the beginning of the next record
625          */
626         if (tmpbuf.c_type == TS_TAPE && (tmpbuf.c_flags & DR_NEWHEADER))
627                 for (i = tmpbuf.c_count; i > 0; i--)
628                         readtape(buf);
629         (void) gethead(&spcl);
630         findinode(&spcl);
631         if (gettingfile) {
632                 gettingfile = 0;
633                 siglongjmp(restart, 1);
634         }
635 }
636
637 /*
638  * Handle unexpected EOF.
639  */
640 static void
641 terminateinput(void)
642 {
643
644         if (gettingfile && curfile.action == USING) {
645                 printf("Warning: %s %s\n",
646                     "End-of-input encountered while extracting", curfile.name);
647         }
648         curfile.name = "<name unknown>";
649         curfile.action = UNKNOWN;
650         curfile.dip = NULL;
651         curfile.ino = maxino;
652         if (gettingfile) {
653                 gettingfile = 0;
654                 siglongjmp(restart, 1);
655         }
656 }
657
658 /*
659  * handle multiple dumps per tape by skipping forward to the
660  * appropriate one.
661  */
662 static void
663 setdumpnum(void)
664 {
665         struct mtop tcom;
666
667         if (dumpnum == 1 || volno != 1)
668                 return;
669         if (pipein)
670                 errx(1, "Cannot have multiple dumps on pipe input");
671         tcom.mt_op = MTFSF;
672         tcom.mt_count = dumpnum - 1;
673 #ifdef RRESTORE
674         if (host)
675                 rmtioctl(MTFSF, dumpnum - 1);
676         else
677 #endif
678                 if (ioctl(mt, (int)MTIOCTOP, (char *)&tcom) < 0)
679                         warn("ioctl MTFSF");
680 }
681
682 void
683 printdumpinfo(void)
684 {
685         fprintf(stdout, "Dump   date: %s", ctime4(&spcl.c_date));
686         fprintf(stdout, "Dumped from: %s",
687             (spcl.c_ddate == 0) ? "the epoch\n" : ctime4(&spcl.c_ddate));
688         if (spcl.c_host[0] == '\0')
689                 return;
690         fprintf(stdout, "Level %d dump of %s on %s:%s\n",
691                 spcl.c_level, spcl.c_filesys, spcl.c_host, spcl.c_dev);
692         fprintf(stdout, "Label: %s\n", spcl.c_label);
693 }
694
695 void 
696 printvolinfo(void)
697 {
698         int i;
699
700         if (volinfo[1] == ROOTINO) {
701                 printf("Starting inode numbers by volume:\n");
702                 for (i = 1; i < (int)TP_NINOS && volinfo[i] != 0; ++i)
703                         printf("\tVolume %d: %lu\n", i, (unsigned long)volinfo[i]);
704         }
705 }
706
707 #ifdef sunos
708 struct timeval
709         time_t          tv_sec;         /* seconds */
710         suseconds_t     tv_usec;        /* and microseconds */
711 };
712 #endif
713
714 int
715 extractfile(struct entry *ep, int doremove)
716 {
717         unsigned int flags;
718         mode_t mode;
719         struct timeval timep[2];
720         char *name = myname(ep);
721
722         /* If removal is requested (-r mode) do remove it unless
723          * we are extracting a metadata only inode */
724         if (spcl.c_flags & DR_METAONLY) {
725                 Vprintf(stdout, "file %s is metadata only\n", name);
726         }
727         else {
728                 if (doremove) {
729                         removeleaf(ep);
730                         ep->e_flags &= ~REMOVED;
731                 }
732         }
733
734         curfile.name = name;
735         curfile.action = USING;
736 #if defined(__linux__) || defined(sunos)
737         timep[0].tv_sec = curfile.dip->di_atime.tv_sec;
738         timep[0].tv_usec = curfile.dip->di_atime.tv_usec;
739         timep[1].tv_sec = curfile.dip->di_mtime.tv_sec;
740         timep[1].tv_usec = curfile.dip->di_mtime.tv_usec;
741 #else   /* __linux__ || sunos */
742         timep[0].tv_sec = curfile.dip->di_atime;
743         timep[0].tv_usec = curfile.dip->di_atimensec / 1000;
744         timep[1].tv_sec = curfile.dip->di_mtime;
745         timep[1].tv_usec = curfile.dip->di_mtimensec / 1000;
746 #endif  /* __linux__ */
747         mode = curfile.dip->di_mode;
748         flags = curfile.dip->di_flags;
749         switch (mode & IFMT) {
750
751         default:
752                 fprintf(stderr, "%s: unknown file mode 0%o\n", name, mode);
753                 skipfile();
754                 return (FAIL);
755
756         case IFSOCK:
757                 Vprintf(stdout, "skipped socket %s\n", name);
758                 skipfile();
759                 return (GOOD);
760
761         case IFDIR:
762                 if (mflag) {
763                         if (ep == NULL || ep->e_flags & EXTRACT)
764                                 panic("unextracted directory %s\n", name);
765                         skipfile();
766                         return (GOOD);
767                 }
768                 Vprintf(stdout, "extract file %s\n", name);
769                 return (genliteraldir(name, curfile.ino));
770
771         case IFLNK:
772         {
773 #ifdef HAVE_LCHOWN
774                 uid_t luid = curfile.dip->di_uid;
775                 gid_t lgid = curfile.dip->di_gid;
776 #endif
777                 if (! (spcl.c_flags & DR_METAONLY)) {
778                         lnkbuf[0] = '\0';
779                         pathlen = 0;
780                         getfile(xtrlnkfile, xtrlnkskip);
781                         if (pathlen == 0) {
782                                 Vprintf(stdout,
783                                     "%s: zero length symbolic link (ignored)\n", name);
784                                 return (GOOD);
785                         }
786                         if (linkit(lnkbuf, name, SYMLINK) == FAIL)
787                                 return (FAIL);
788                 }
789                 else
790                         skipfile();
791
792 #ifdef HAVE_LCHOWN
793                 (void) lchown(name, luid, lgid);
794 #endif
795                 return (GOOD);
796         }
797
798         case IFIFO:
799                 Vprintf(stdout, "extract fifo %s\n", name);
800                 if (Nflag) {
801                         skipfile();
802                         return (GOOD);
803                 }
804                 if (! (spcl.c_flags & DR_METAONLY)) {
805                         if (uflag && !Nflag)
806                                 (void)unlink(name);
807                         if (mkfifo(name, mode) < 0) {
808                                 warn("%s: cannot create fifo", name);
809                                 skipfile();
810                                 return (FAIL);
811                         }
812                 }
813                 (void) chown(name, curfile.dip->di_uid, curfile.dip->di_gid);
814                 (void) chmod(name, mode);
815                 if (flags)
816 #ifdef  __linux__
817                         (void) fsetflags(name, flags);
818 #else
819                         (void) chflags(name, flags);
820 #endif
821                 skipfile();
822                 utimes(name, timep);
823                 return (GOOD);
824
825         case IFCHR:
826         case IFBLK:
827                 Vprintf(stdout, "extract special file %s\n", name);
828                 if (Nflag) {
829                         skipfile();
830                         return (GOOD);
831                 }
832                 if (! (spcl.c_flags & DR_METAONLY)) {
833                         if (uflag)
834                                 (void)unlink(name);
835                         if (mknod(name, mode, (int)curfile.dip->di_rdev) < 0) {
836                                 warn("%s: cannot create special file", name);
837                                 skipfile();
838                                 return (FAIL);
839                         }
840                 }
841                 (void) chown(name, curfile.dip->di_uid, curfile.dip->di_gid);
842                 (void) chmod(name, mode);
843                 if (flags)
844 #ifdef  __linux__
845                         {
846                         warn("%s: fsetflags called on a special file", name);
847                         (void) fsetflags(name, flags);
848                         }
849 #else
850                         (void) chflags(name, flags);
851 #endif
852                 skipfile();
853                 utimes(name, timep);
854                 return (GOOD);
855
856         case IFREG:
857         {
858                 uid_t luid = curfile.dip->di_uid;
859                 gid_t lgid = curfile.dip->di_gid;
860
861                 Vprintf(stdout, "extract file %s\n", name);
862                 if (Nflag) {
863                         skipfile();
864                         return (GOOD);
865                 }
866                 if (! (spcl.c_flags & DR_METAONLY)) {
867                         if (uflag)
868                                 (void)unlink(name);
869                         if ((ofile = OPEN(name, O_WRONLY | O_CREAT | O_TRUNC,
870                             0666)) < 0) {
871                                 warn("%s: cannot create file", name);
872                                 skipfile();
873                                 return (FAIL);
874                         }
875                         getfile(xtrfile, xtrskip);
876                         (void) close(ofile);
877                 }
878                 else
879                         skipfile();
880                 (void) chown(name, luid, lgid);
881                 (void) chmod(name, mode);
882                 if (flags)
883 #ifdef  __linux__
884                         (void) fsetflags(name, flags);
885 #else
886                         (void) chflags(name, flags);
887 #endif
888                 utimes(name, timep);
889                 return (GOOD);
890         }
891         }
892         /* NOTREACHED */
893 }
894
895 /*
896  * skip over bit maps on the tape
897  */
898 void
899 skipmaps(void)
900 {
901
902         while (spcl.c_type == TS_BITS || spcl.c_type == TS_CLRI)
903                 skipfile();
904 }
905
906 /*
907  * skip over a file on the tape
908  */
909 void
910 skipfile(void)
911 {
912
913         curfile.action = SKIP;
914         getfile(xtrnull, xtrnull);
915 }
916
917 /*
918  * Extract a file from the tape.
919  * When an allocated block is found it is passed to the fill function;
920  * when an unallocated block (hole) is found, a zeroed buffer is passed
921  * to the skip function.
922  */
923 void
924 getfile(void (*fill) __P((char *, size_t)), void (*skip) __P((char *, size_t)))
925 {
926         int i;
927         volatile int curblk = 0;
928         volatile quad_t size = spcl.c_dinode.di_size;
929         volatile int last_write_was_hole = 0;
930         quad_t origsize = size;
931         static char clearedbuf[MAXBSIZE];
932         char buf[MAXBSIZE / TP_BSIZE][TP_BSIZE];
933         char junk[TP_BSIZE];
934
935         if (spcl.c_type == TS_END)
936                 panic("ran off end of tape\n");
937         if (spcl.c_magic != NFS_MAGIC)
938                 panic("not at beginning of a file\n");
939         if (!gettingfile && setjmp(restart) != 0)
940                 return;
941         gettingfile++;
942 loop:
943         for (i = 0; i < spcl.c_count; i++) {
944                 if (readmapflag || spcl.c_addr[i]) {
945                         readtape(&buf[curblk++][0]);
946                         if (curblk == fssize / TP_BSIZE) {
947                                 (*fill)((char *)buf, (size_t)(size > TP_BSIZE ?
948                                      fssize : (curblk - 1) * TP_BSIZE + size));
949                                 curblk = 0;
950                                 last_write_was_hole = 0;
951                         }
952                 } else {
953                         if (curblk > 0) {
954                                 (*fill)((char *)buf, (size_t)(size > TP_BSIZE ?
955                                      curblk * TP_BSIZE :
956                                      (curblk - 1) * TP_BSIZE + size));
957                                 curblk = 0;
958                         }
959                         (*skip)(clearedbuf, (long)(size > TP_BSIZE ?
960                                 TP_BSIZE : size));
961                         last_write_was_hole = 1;
962                 }
963                 if ((size -= TP_BSIZE) <= 0) {
964                         for (i++; i < spcl.c_count; i++)
965                                 if (readmapflag || spcl.c_addr[i])
966                                         readtape(junk);
967                         break;
968                 }
969         }
970         if (gethead(&spcl) == GOOD && size > 0) {
971                 if (spcl.c_type == TS_ADDR)
972                         goto loop;
973                 Dprintf(stdout,
974                         "Missing address (header) block for %s at %ld blocks\n",
975                         curfile.name, (long)blksread);
976         }
977         if (curblk > 0) {
978                 (*fill)((char *)buf, (size_t)((curblk * TP_BSIZE) + size));
979                 last_write_was_hole = 0;
980         }
981         if (size > 0) {
982                 fprintf(stderr, "Missing blocks at the end of %s, assuming hole\n", curfile.name);
983                 while (size > 0) {
984                         size_t skp = size > TP_BSIZE ? TP_BSIZE : size;
985                         (*skip)(clearedbuf, skp);
986                         size -= skp;
987                 }
988                 last_write_was_hole = 1;
989         }
990         if (last_write_was_hole) {
991                 FTRUNCATE(ofile, origsize);
992         }
993         if (!readingmaps) 
994                 findinode(&spcl);
995         gettingfile = 0;
996 }
997
998 /*
999  * Write out the next block of a file.
1000  */
1001 static void
1002 xtrfile(char *buf, size_t size)
1003 {
1004
1005         if (Nflag)
1006                 return;
1007         if (write(ofile, buf, (int) size) == -1)
1008                 err(1, "write error extracting inode %lu, name %s\nwrite",
1009                         (unsigned long)curfile.ino, curfile.name);
1010 }
1011
1012 /*
1013  * Skip over a hole in a file.
1014  */
1015 /* ARGSUSED */
1016 static void
1017 xtrskip(UNUSED(char *buf), size_t size)
1018 {
1019
1020         if (LSEEK(ofile, (off_t)size, SEEK_CUR) == -1)
1021                 err(1, "seek error extracting inode %lu, name %s\nlseek",
1022                         (unsigned long)curfile.ino, curfile.name);
1023 }
1024
1025 /*
1026  * Collect the next block of a symbolic link.
1027  */
1028 static void
1029 xtrlnkfile(char *buf, size_t size)
1030 {
1031
1032         pathlen += size;
1033         if (pathlen > MAXPATHLEN)
1034                 errx(1, "symbolic link name: %s->%s%s; too long %d",
1035                     curfile.name, lnkbuf, buf, pathlen);
1036         (void) strcat(lnkbuf, buf);
1037 }
1038
1039 /*
1040  * Skip over a hole in a symbolic link (should never happen).
1041  */
1042 /* ARGSUSED */
1043 static void
1044 xtrlnkskip(UNUSED(char *buf), UNUSED(size_t size))
1045 {
1046
1047         errx(1, "unallocated block in symbolic link %s", curfile.name);
1048 }
1049
1050 /*
1051  * Collect the next block of a bit map.
1052  */
1053 static void
1054 xtrmap(char *buf, size_t size)
1055 {
1056
1057         memmove(map, buf, size);
1058         map += size;
1059 }
1060
1061 /*
1062  * Skip over a hole in a bit map (should never happen).
1063  */
1064 /* ARGSUSED */
1065 static void
1066 xtrmapskip(UNUSED(char *buf), size_t size)
1067 {
1068
1069         panic("hole in map\n");
1070         map += size;
1071 }
1072
1073 /*
1074  * Noop, when an extraction function is not needed.
1075  */
1076 /* ARGSUSED */
1077 void
1078 xtrnull(UNUSED(char *buf), UNUSED(size_t size))
1079 {
1080
1081         return;
1082 }
1083
1084 #if COMPARE_ONTHEFLY
1085 /*
1086  * Compare the next block of a file.
1087  */
1088 static void
1089 xtrcmpfile(char *buf, size_t size)
1090 {
1091         static char cmpbuf[MAXBSIZE];
1092
1093         if (cmperror)
1094                 return;
1095         
1096         if (read(ifile, cmpbuf, size) != (ssize_t)size) {
1097                 fprintf(stderr, "%s: size has changed.\n", 
1098                         curfile.name);
1099                 cmperror = 1;
1100                 return;
1101         }
1102         
1103         if (memcmp(buf, cmpbuf, size) != 0) {
1104                 fprintf(stderr, "%s: tape and disk copies are different\n",
1105                         curfile.name);
1106                 cmperror = 1;
1107                 return;
1108         }
1109 }
1110
1111 /*
1112  * Skip over a hole in a file.
1113  */
1114 static void
1115 xtrcmpskip(UNUSED(char *buf), size_t size)
1116 {
1117         static char cmpbuf[MAXBSIZE];
1118         int i;
1119
1120         if (cmperror)
1121                 return;
1122         
1123         if (read(ifile, cmpbuf, size) != (ssize_t)size) {
1124                 fprintf(stderr, "%s: size has changed.\n", 
1125                         curfile.name);
1126                 cmperror = 1;
1127                 return;
1128         }
1129
1130         for (i = 0; i < (int)size; ++i)
1131                 if (cmpbuf[i] != '\0') {
1132                         fprintf(stderr, "%s: tape and disk copies are different\n",
1133                                 curfile.name);
1134                         cmperror = 1;
1135                         return;
1136                 }
1137 }
1138 #endif /* COMPARE_ONTHEFLY */
1139
1140 #if !COMPARE_ONTHEFLY
1141 static int
1142 do_cmpfiles(int fd_tape, int fd_disk, long size)
1143 {
1144         static char buf_tape[BUFSIZ];
1145         static char buf_disk[BUFSIZ];
1146         ssize_t n_tape;
1147         ssize_t n_disk;
1148
1149         while (size > 0) {
1150                 if ((n_tape = read(fd_tape, buf_tape, sizeof(buf_tape))) < 1) {
1151                         close(fd_tape), close(fd_disk);
1152                         panic("do_cmpfiles: unexpected EOF[1]");
1153                 }
1154                 if ((n_disk = read(fd_disk, buf_disk, sizeof(buf_tape))) < 1) {
1155                         close(fd_tape), close(fd_disk);
1156                         panic("do_cmpfiles: unexpected EOF[2]");
1157                 }
1158                 if (n_tape != n_disk) {
1159                         close(fd_tape), close(fd_disk);
1160                         panic("do_cmpfiles: sizes different!");
1161                 }
1162                 if (memcmp(buf_tape, buf_disk, (size_t)n_tape) != 0) return (1);
1163                 size -= n_tape;
1164         }
1165         return (0);
1166 }
1167
1168 /* for debugging compare problems */
1169 #undef COMPARE_FAIL_KEEP_FILE
1170
1171 static
1172 #ifdef COMPARE_FAIL_KEEP_FILE
1173 /* return true if tapefile should be unlinked after compare */
1174 int
1175 #else
1176 void
1177 #endif
1178 cmpfiles(char *tapefile, char *diskfile, struct STAT *sbuf_disk)
1179 {
1180         struct STAT sbuf_tape;
1181         int fd_tape, fd_disk;
1182
1183         if (STAT(tapefile, &sbuf_tape) != 0) {
1184                 panic("Can't lstat tmp file %s: %s\n", tapefile,
1185                       strerror(errno));
1186                 do_compare_error;
1187         }
1188
1189         if (sbuf_disk->st_size != sbuf_tape.st_size) {
1190                 fprintf(stderr,
1191                         "%s: size changed from %ld to %ld.\n",
1192                         diskfile, (long)sbuf_tape.st_size, (long)sbuf_disk->st_size);
1193                 do_compare_error;
1194 #ifdef COMPARE_FAIL_KEEP_FILE
1195                 return (0);
1196 #else
1197                 return;
1198 #endif
1199         }
1200
1201         if ((fd_tape = OPEN(tapefile, O_RDONLY)) < 0) {
1202                 panic("Can't open %s: %s\n", tapefile, strerror(errno));
1203                 do_compare_error;
1204         }
1205         if ((fd_disk = OPEN(diskfile, O_RDONLY)) < 0) {
1206                 close(fd_tape);
1207                 panic("Can't open %s: %s\n", diskfile, strerror(errno));
1208                 do_compare_error;
1209         }
1210
1211         if (do_cmpfiles(fd_tape, fd_disk, sbuf_tape.st_size)) {
1212                 fprintf(stderr, "%s: tape and disk copies are different\n",
1213                         diskfile);
1214                 close(fd_tape);
1215                 close(fd_disk);
1216                 do_compare_error;
1217 #ifdef COMPARE_FAIL_KEEP_FILE
1218                 /* rename the file to live in /tmp */
1219                 /* rename `tapefile' to /tmp/<basename of diskfile> */
1220                 {
1221                         char *p = strrchr(diskfile, '/');
1222                         char newname[MAXPATHLEN];
1223                         if (!p) {
1224                                 panic("can't find / in %s\n", diskfile);
1225                         }
1226                         snprintf(newname, sizeof(newname), "%s/debug/%s", tmpdir, p + 1);
1227                         if (rename(tapefile, newname)) {
1228                                 panic("rename from %s to %s failed: %s\n",
1229                                       tapefile, newname,
1230                                       strerror(errno));
1231                         } else {
1232                                 fprintf(stderr, "*** %s saved to %s\n",
1233                                         tapefile, newname);
1234                         }
1235                 }
1236                 
1237                 /* don't unlink the file (it's not there anymore */
1238                 /* anyway) */
1239                 return (0);
1240 #else
1241                 return;
1242 #endif
1243         }
1244         close(fd_tape);
1245         close(fd_disk);
1246 #ifdef COMPARE_FAIL_KEEP_FILE
1247         return (1);
1248 #endif
1249 }
1250 #endif /* !COMPARE_ONTHEFLY */
1251
1252 #if !COMPARE_ONTHEFLY
1253 static char tmpfilename[MAXPATHLEN];
1254 #endif
1255
1256 void
1257 comparefile(char *name)
1258 {
1259         unsigned int mode;
1260         struct STAT sb;
1261         int r;
1262 #if !COMPARE_ONTHEFLY
1263         static char *tmpfile = NULL;
1264         struct STAT stemp;
1265 #endif
1266
1267         if ((r = LSTAT(name, &sb)) != 0) {
1268                 warn("%s: does not exist (%d)", name, r);
1269                 do_compare_error;
1270                 skipfile();
1271                 return;
1272         }
1273
1274         curfile.name = name;
1275         curfile.action = USING;
1276         mode = curfile.dip->di_mode;
1277
1278         Vprintf(stdout, "comparing %s (size: %ld, mode: 0%o)\n", name,
1279                 (long)sb.st_size, mode);
1280
1281         if (sb.st_mode != mode) {
1282                 fprintf(stderr, "%s: mode changed from 0%o to 0%o.\n",
1283                         name, mode & 07777, sb.st_mode & 07777);
1284                 do_compare_error;
1285         }
1286         if (spcl.c_flags & DR_METAONLY) {
1287                 skipfile();
1288                 return;
1289         }
1290         switch (mode & IFMT) {
1291         default:
1292                 skipfile();
1293                 return;
1294
1295         case IFSOCK:
1296                 skipfile();
1297                 return;
1298
1299         case IFDIR:
1300                 skipfile();
1301                 return;
1302
1303         case IFLNK: {
1304                 char lbuf[MAXPATHLEN + 1];
1305                 int lsize;
1306
1307                 if (!(sb.st_mode & S_IFLNK)) {
1308                         fprintf(stderr, "%s: is no longer a symbolic link\n",
1309                                 name);
1310                         do_compare_error;
1311                         return;
1312                 }
1313                 lnkbuf[0] = '\0';
1314                 pathlen = 0;
1315                 getfile(xtrlnkfile, xtrlnkskip);
1316                 if (pathlen == 0) {
1317                         fprintf(stderr,
1318                                 "%s: zero length symbolic link (ignored)\n",
1319                                 name);
1320                         do_compare_error;
1321                         return;
1322                 }
1323                 if ((lsize = readlink(name, lbuf, MAXPATHLEN)) < 0) {
1324                         panic("readlink of %s failed: %s", name,
1325                               strerror(errno));
1326                         do_compare_error;
1327                 }
1328                 lbuf[lsize] = 0;
1329                 if (strcmp(lbuf, lnkbuf) != 0) {
1330                         fprintf(stderr,
1331                                 "%s: symbolic link changed from %s to %s.\n",
1332                                 name, lnkbuf, lbuf);
1333                         do_compare_error;
1334                         return;
1335                 }
1336                 return;
1337         }
1338
1339         case IFCHR:
1340         case IFBLK:
1341                 if (!(sb.st_mode & (S_IFCHR|S_IFBLK))) {
1342                         fprintf(stderr, "%s: no longer a special file\n",
1343                                 name);
1344                         do_compare_error;
1345                         skipfile();
1346                         return;
1347                 }
1348
1349                 if (sb.st_rdev != (dev_t)curfile.dip->di_rdev) {
1350                         fprintf(stderr,
1351                                 "%s: device changed from %d,%d to %d,%d.\n",
1352                                 name,
1353                                 ((int)curfile.dip->di_rdev >> 8) & 0xff,
1354                                 (int)curfile.dip->di_rdev & 0xff,
1355                                 ((int)sb.st_rdev >> 8) & 0xff,
1356                                 (int)sb.st_rdev & 0xff);
1357                         do_compare_error;
1358                 }
1359                 skipfile();
1360                 return;
1361
1362         case IFREG:
1363 #if COMPARE_ONTHEFLY
1364                 if ((ifile = OPEN(name, O_RDONLY)) < 0) {
1365                         panic("Can't open %s: %s\n", name, strerror(errno));
1366                         skipfile();
1367                         do_compare_error;
1368                 }
1369                 else {
1370                         cmperror = 0;
1371                         getfile(xtrcmpfile, xtrcmpskip);
1372                         if (!cmperror) {
1373                                 char c;
1374                                 if (read(ifile, &c, 1) != 0) {
1375                                         fprintf(stderr, "%s: size has changed.\n", 
1376                                                 name);
1377                                         cmperror = 1;
1378                                 }
1379                         }
1380                         if (cmperror)
1381                                 do_compare_error;
1382                         close(ifile);
1383                 }
1384 #else
1385                 if (tmpfile == NULL) {
1386                         /* argument to mktemp() must not be in RO space: */
1387                         snprintf(tmpfilename, sizeof(tmpfilename), "%s/restoreCXXXXXX", tmpdir);
1388                         tmpfile = mktemp(&tmpfilename[0]);
1389                 }
1390                 if ((STAT(tmpfile, &stemp) == 0) && (unlink(tmpfile) != 0)) {
1391                         panic("cannot delete tmp file %s: %s\n",
1392                               tmpfile, strerror(errno));
1393                 }
1394                 if ((ofile = OPEN(tmpfile, O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0) {
1395                         panic("cannot create file temp file %s: %s\n",
1396                               name, strerror(errno));
1397                 }
1398                 getfile(xtrfile, xtrskip);
1399                 (void) close(ofile);
1400 #ifdef COMPARE_FAIL_KEEP_FILE
1401                 if (cmpfiles(tmpfile, name, &sb))
1402                         unlink(tmpfile);
1403 #else
1404                 cmpfiles(tmpfile, name, &sb);
1405                 unlink(tmpfile);
1406 #endif
1407 #endif /* COMPARE_ONTHEFLY */
1408                 return;
1409         }
1410         /* NOTREACHED */
1411 }
1412
1413 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB)
1414 static void (*readtape_func)(char *) = readtape_set;
1415
1416 /*
1417  * Read TP_BSIZE blocks from the input.
1418  * Handle read errors, and end of media.
1419  * Decompress compressed blocks.
1420  */
1421 static void
1422 readtape(char *buf)
1423 {
1424         (*readtape_func)(buf);  /* call the actual processing routine */
1425 }
1426
1427 /*
1428  * Set function pointer for readtape() routine. zflag and magtapein must
1429  * be correctly set before the first call to readtape().
1430  */
1431 static void
1432 readtape_set(char *buf)
1433 {
1434         if (!zflag) 
1435                 readtape_func = readtape_uncompr;
1436         else {
1437                 newcomprbuf(ntrec);
1438                 if (magtapein)
1439                         readtape_func = readtape_comprtape;
1440                 else
1441                         readtape_func = readtape_comprfile;
1442         }
1443         readtape(buf);
1444 }
1445
1446 #endif /* HAVE_ZLIB || HAVE_BZLIB */
1447
1448 /*
1449  * This is the original readtape(), it's used for reading uncompressed input.
1450  * Read TP_BSIZE blocks from the input.
1451  * Handle read errors, and end of media.
1452  */
1453 static void
1454 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB)
1455 readtape_uncompr(char *buf)
1456 #else
1457 readtape(char *buf)
1458 #endif
1459 {
1460         ssize_t rd, newvol, i;
1461         int cnt, seek_failed;
1462
1463         if (blkcnt < numtrec) {
1464                 memmove(buf, &tbufptr[(blkcnt++ * TP_BSIZE)], TP_BSIZE);
1465                 blksread++;
1466                 tpblksread++;
1467                 return;
1468         }
1469         tbufptr = tapebuf;
1470         for (i = 0; i < ntrec; i++)
1471                 ((struct s_spcl *)&tapebuf[i * TP_BSIZE])->c_magic = 0;
1472         if (numtrec == 0)
1473                 numtrec = ntrec;
1474         cnt = ntrec * TP_BSIZE;
1475         rd = 0;
1476 #ifdef USE_QFA
1477         if (createtapeposflag)
1478                 (void)GetTapePos(&curtapepos);
1479 #endif
1480 getmore:
1481 #ifdef RRESTORE
1482         if (host)
1483                 i = rmtread(&tapebuf[rd], cnt);
1484         else
1485 #endif
1486                 i = read(mt, &tapebuf[rd], cnt);
1487
1488         /*
1489          * Check for mid-tape short read error.
1490          * If found, skip rest of buffer and start with the next.
1491          */
1492         if (!pipein && numtrec < ntrec && i > 0) {
1493                 Dprintf(stdout, "mid-media short read error.\n");
1494                 numtrec = ntrec;
1495         }
1496         /*
1497          * Handle partial block read.
1498          */
1499         if (pipein && i == 0 && rd > 0)
1500                 i = rd;
1501         else if (i > 0 && i != ntrec * TP_BSIZE) {
1502                 if (pipein) {
1503                         rd += i;
1504                         cnt -= i;
1505                         if (cnt > 0)
1506                                 goto getmore;
1507                         i = rd;
1508                 } else {
1509                         /*
1510                          * Short read. Process the blocks read.
1511                          */
1512                         if (i % TP_BSIZE != 0)
1513                                 Vprintf(stdout,
1514                                     "partial block read: %ld should be %ld\n",
1515                                     (long)i, ntrec * TP_BSIZE);
1516                         numtrec = i / TP_BSIZE;
1517                 }
1518         }
1519         /*
1520          * Handle read error.
1521          */
1522         if (i < 0) {
1523                 fprintf(stderr, "Tape read error while ");
1524                 switch (curfile.action) {
1525                 default:
1526                         fprintf(stderr, "trying to set up tape\n");
1527                         break;
1528                 case UNKNOWN:
1529                         fprintf(stderr, "trying to resynchronize\n");
1530                         break;
1531                 case USING:
1532                         fprintf(stderr, "restoring %s\n", curfile.name);
1533                         break;
1534                 case SKIP:
1535                         fprintf(stderr, "skipping over inode %lu\n",
1536                                 (unsigned long)curfile.ino);
1537                         break;
1538                 }
1539                 if (!yflag && !reply("continue"))
1540                         exit(1);
1541                 i = ntrec * TP_BSIZE;
1542                 memset(tapebuf, 0, (size_t)i);
1543 #ifdef RRESTORE
1544                 if (host)
1545                         seek_failed = (rmtseek(i, 1) < 0);
1546                 else
1547 #endif
1548                         seek_failed = (LSEEK(mt, i, SEEK_CUR) == (off_t)-1);
1549
1550                 if (seek_failed) {
1551                         warn("continuation failed");
1552                         if (!yflag && !reply("assume end-of-tape and continue"))
1553                                 exit(1);
1554                         i = 0;
1555                 }
1556         }
1557         /*
1558          * Handle end of tape.
1559          */
1560         if (i == 0) {
1561                 Vprintf(stdout, "End-of-tape encountered\n");
1562                 if (!pipein) {
1563                         newvol = volno + 1;
1564                         volno = 0;
1565                         numtrec = 0;
1566                         getvol(newvol);
1567                         readtape(buf);
1568                         return;
1569                 }
1570                 if (rd % TP_BSIZE != 0)
1571                         panic("partial block read: %d should be %d\n",
1572                                 rd, ntrec * TP_BSIZE);
1573                 terminateinput();
1574                 memmove(&tapebuf[rd], &endoftapemark, TP_BSIZE);
1575         }
1576         blkcnt = 0;
1577         memmove(buf, &tbufptr[(blkcnt++ * TP_BSIZE)], TP_BSIZE);
1578         blksread++;
1579         tpblksread++;
1580 }
1581
1582 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB)
1583
1584 /*
1585  * Read a compressed format block from a file or pipe and uncompress it.
1586  * Attempt to handle read errors, and end of file. 
1587  */
1588 static void
1589 readtape_comprfile(char *buf)
1590 {
1591         long rl, size, i, ret;
1592         int newvol; 
1593         struct tapebuf *tpb;
1594
1595         if (blkcnt < numtrec) {
1596                 memmove(buf, &tbufptr[(blkcnt++ * TP_BSIZE)], TP_BSIZE);
1597                 blksread++;
1598                 tpblksread++;
1599                 return;
1600         }
1601         /* need to read the next block */
1602         tbufptr = tapebuf;
1603         for (i = 0; i < ntrec; i++)
1604                 ((struct s_spcl *)&tapebuf[i * TP_BSIZE])->c_magic = 0;
1605         numtrec = ntrec;
1606         tpb = (struct tapebuf *) tapebuf;
1607
1608         /* read the block prefix */
1609         ret = read_a_block(mt, tapebuf, PREFIXSIZE, &rl);
1610
1611         if (Vflag && (ret == 0 || rl < (int)PREFIXSIZE  ||  tpb->length == 0))
1612                 ret = 0;
1613         if (ret <= 0)
1614                 goto readerr;
1615
1616         /* read the data */
1617         size = tpb->length;
1618         if (size > bufsize)  {
1619                 /* something's wrong */
1620                 Vprintf(stdout, "Prefix size error, max size %d, got %ld\n",
1621                         bufsize, size);
1622                 size = bufsize;
1623                 tpb->length = bufsize;
1624         }
1625         ret = read_a_block(mt, tpb->buf, size, &rl);
1626         if (ret <= 0)
1627                 goto readerr;
1628
1629         tbufptr = decompress_tapebuf(tpb, rl + PREFIXSIZE);
1630         if (tbufptr == NULL) {
1631                 msg_read_error("File decompression error while");
1632                 if (!yflag && !reply("continue"))
1633                         exit(1);
1634                 memset(tapebuf, 0, bufsize);
1635                 tbufptr = tapebuf;
1636         }
1637
1638         blkcnt = 0;
1639         memmove(buf, &tbufptr[(blkcnt++ * TP_BSIZE)], TP_BSIZE);
1640         blksread++;
1641         tpblksread++;
1642         return;
1643
1644 readerr:
1645         /* Errors while reading from a file or pipe are catastrophic. Since
1646          * there are no block boundaries, it's impossible to bypass the
1647          * block in error and find the start of the next block.
1648          */
1649         if (ret == 0) {
1650                 /* It's possible to have multiple input files using -M
1651                  * and -f file1,file2...
1652                  */
1653                 Vprintf(stdout, "End-of-File encountered\n");
1654                 if (!pipein) {
1655                         newvol = volno + 1;
1656                         volno = 0;
1657                         numtrec = 0;
1658                         getvol(newvol);
1659                         readtape(buf);
1660                         return;
1661                 }
1662         }
1663         msg_read_error("Read error while");
1664         /* if (!yflag && !reply("continue")) */
1665                 exit(1);
1666 }
1667
1668 /*
1669  * Read compressed data from a tape and uncompress it.
1670  * Handle read errors, and end of media.
1671  * Since a tape consists of separate physical blocks, we try
1672  * to recover from errors by repositioning the tape to the next
1673  * block.
1674  */
1675 static void
1676 readtape_comprtape(char *buf)
1677 {
1678         long rl, size, i;
1679         int ret, newvol;
1680         struct tapebuf *tpb;
1681         struct mtop tcom;
1682
1683         if (blkcnt < numtrec) {
1684                 memmove(buf, &tbufptr[(blkcnt++ * TP_BSIZE)], TP_BSIZE);
1685                 blksread++;
1686                 tpblksread++;
1687                 return;
1688         }
1689         /* need to read the next block */
1690         tbufptr = tapebuf;
1691         for (i = 0; i < ntrec; i++)
1692                 ((struct s_spcl *)&tapebuf[i * TP_BSIZE])->c_magic = 0;
1693         numtrec = ntrec;
1694         tpb = (struct tapebuf *) tapebuf;
1695
1696         /* read the block */
1697         size = bufsize + PREFIXSIZE;
1698         ret = read_a_block(mt, tapebuf, size, &rl);
1699         if (ret <= 0)
1700                 goto readerr;
1701
1702         tbufptr = decompress_tapebuf(tpb, rl);
1703         if (tbufptr == NULL) {
1704                 msg_read_error("Tape decompression error while");
1705                 if (!yflag && !reply("continue"))
1706                         exit(1);
1707                 memset(tapebuf, 0, PREFIXSIZE + bufsize);
1708                 tbufptr = tapebuf;
1709         }
1710         goto moverecord;
1711
1712 readerr:
1713         /* Handle errors: EOT switches to the next volume, other errors
1714          * attempt to position the tape to the next block.
1715          */
1716         if (ret == 0) {
1717                 Vprintf(stdout, "End-of-tape encountered\n");
1718                 newvol = volno + 1;
1719                 volno = 0;
1720                 numtrec = 0;
1721                 getvol(newvol);
1722                 readtape(buf);
1723                 return;
1724         }
1725
1726         msg_read_error("Tape read error while");
1727         if (!yflag && !reply("continue"))
1728                 exit(1);
1729         memset(tapebuf, 0, PREFIXSIZE + bufsize);
1730         tbufptr = tapebuf;
1731
1732 #ifdef RRESTORE
1733         if (host)
1734                 rl = rmtioctl(MTFSR, 1);
1735         else
1736 #endif
1737         {
1738                 tcom.mt_op = MTFSR;
1739                 tcom.mt_count = 1;
1740                 rl = ioctl(mt, MTIOCTOP, &tcom);
1741         }
1742
1743         if (rl < 0) {
1744                 warn("continuation failed");
1745                 if (!yflag && !reply("assume end-of-tape and continue"))
1746                         exit(1);
1747                 ret = 0;         /* end of tape */
1748                 goto readerr;
1749         }
1750
1751 moverecord:
1752         blkcnt = 0;
1753         memmove(buf, &tbufptr[(blkcnt++ * TP_BSIZE)], TP_BSIZE);
1754         blksread++;
1755         tpblksread++;
1756 }
1757
1758 /*
1759  *  Decompress a struct tapebuf into a buffer. readsize is the size read
1760  *  from the tape/file and is used for error messages. Returns a pointer
1761  *  to the location of the uncompressed buffer or NULL on errors.
1762  *  Adjust numtrec and complain for a short block.
1763  */
1764 static char *
1765 decompress_tapebuf(struct tapebuf *tpbin, int readsize)
1766 {
1767         /* If zflag is on, all blocks have a struct tapebuf prefix */
1768         /* zflag gets set in setup() from the dump header          */
1769         int cresult, blocklen;        
1770         unsigned long worklen;
1771 #ifdef HAVE_BZLIB
1772         unsigned int worklen2;
1773 #endif
1774         char *output = NULL,*reason = NULL, *lengtherr = NULL;              
1775        
1776         /* build a length error message */
1777         blocklen = tpbin->length;
1778         if (readsize < blocklen + (int)PREFIXSIZE)
1779                 lengtherr = "short";
1780         else
1781                 if (readsize > blocklen + (int)PREFIXSIZE)
1782                         lengtherr = "long";
1783
1784         worklen = comprlen;
1785         cresult = 1;
1786         if (tpbin->compressed) {
1787                 /* uncompress whatever we read, if it fails, complain later */
1788                 if (tpbin->flags == COMPRESS_ZLIB) {
1789 #ifndef HAVE_ZLIB
1790                         errx(1,"This restore version doesn't support zlib decompression");
1791 #else
1792                         cresult = uncompress(comprbuf, &worklen, 
1793                                              tpbin->buf, blocklen);
1794                         output = comprbuf;
1795                         switch (cresult) {
1796                                 case Z_OK:
1797                                         break;
1798                                 case Z_MEM_ERROR:
1799                                         reason = "not enough memory";
1800                                         break;
1801                                 case Z_BUF_ERROR:
1802                                         reason = "buffer too small";
1803                                         break;
1804                                 case Z_DATA_ERROR:
1805                                         reason = "data error";
1806                                         break;
1807                                 default:
1808                                         reason = "unknown";
1809                         }
1810                         if (cresult == Z_OK)
1811                                 cresult = 1;
1812                         else
1813                                 cresult = 0;
1814 #endif /* HAVE_ZLIB */
1815                 }
1816                 if (tpbin->flags == COMPRESS_BZLIB) {
1817 #ifndef HAVE_BZLIB
1818                         errx(1,"This restore version doesn't support bzlib decompression");
1819 #else
1820                         worklen2 = worklen;
1821                         cresult = BZ2_bzBuffToBuffDecompress(
1822                                         comprbuf, &worklen2, 
1823                                         tpbin->buf, blocklen, 0, 0);
1824                         worklen = worklen2;
1825                         output = comprbuf;
1826                         switch (cresult) {
1827                                 case BZ_OK:
1828                                         break;
1829                                 case BZ_MEM_ERROR:
1830                                         reason = "not enough memory";
1831                                         break;
1832                                 case BZ_OUTBUFF_FULL:
1833                                         reason = "buffer too small";
1834                                         break;
1835                                 case BZ_DATA_ERROR:
1836                                 case BZ_DATA_ERROR_MAGIC:
1837                                 case BZ_UNEXPECTED_EOF:
1838                                         reason = "data error";
1839                                         break;
1840                                 default:
1841                                         reason = "unknown";
1842                         }
1843                         if (cresult == BZ_OK)
1844                                 cresult = 1;
1845                         else
1846                                 cresult = 0;
1847 #endif /* HAVE_BZLIB */
1848                 }
1849         }
1850         else {
1851                 output = tpbin->buf;
1852                 worklen = blocklen;
1853         }
1854         if (cresult) {
1855                 numtrec = worklen / TP_BSIZE;
1856                 if (worklen % TP_BSIZE != 0)
1857                         reason = "length mismatch";
1858         }
1859         if (reason) {
1860                 if (lengtherr)
1861                         fprintf(stderr, "%s compressed block: %d expected: %d\n",
1862                                 lengtherr, readsize, tpbin->length + PREFIXSIZE);
1863                 fprintf(stderr, "decompression error, block %ld: %s\n",
1864                         tpblksread+1, reason);
1865                 if (!cresult)
1866                         output = NULL;
1867         }
1868         return output;
1869 }
1870
1871 /*
1872  * Print an error message for a read error.
1873  * This was exteracted from the original readtape().
1874  */
1875 static void
1876 msg_read_error(char *m)
1877 {
1878         switch (curfile.action) {
1879                 default:
1880                         fprintf(stderr, "%s trying to set up tape\n", m);
1881                         break;
1882                 case UNKNOWN:
1883                         fprintf(stderr, "%s trying to resynchronize\n", m);
1884                         break;
1885                 case USING:
1886                         fprintf(stderr, "%s restoring %s\n", m, curfile.name);
1887                         break;
1888                 case SKIP:
1889                         fprintf(stderr, "%s skipping over inode %lu\n", m,
1890                                 (unsigned long)curfile.ino);
1891                         break;
1892         }
1893 }
1894 #endif /* HAVE_ZLIB || HAVE_BZLIB */
1895
1896 /*
1897  * Read the first block and get the blocksize from it. Test
1898  * for a compressed dump tape/file. setup() will make the final
1899  * determination by checking the compressed flag if gethead()
1900  * finds a valid header. The test here is necessary to offset the buffer
1901  * by the size of the compressed prefix. zflag is set here so that
1902  * readtape_set can set the correct function pointer for readtape().
1903  * Note that the first block of each tape/file is not compressed
1904  * and does not have a prefix.
1905  */ 
1906 static void
1907 findtapeblksize(void)
1908 {
1909         long i;
1910         size_t len;
1911         struct tapebuf *tpb = (struct tapebuf *) tapebuf;
1912         struct s_spcl *spclpt = (struct s_spcl *) tapebuf;
1913
1914         for (i = 0; i < ntrec; i++)
1915                 ((struct s_spcl *)&tapebuf[i * TP_BSIZE])->c_magic = 0;
1916         blkcnt = 0;
1917         tbufptr = tapebuf;
1918         /*
1919          * For a pipe or file, read in the first record. For a tape, read
1920          * the first block.
1921          */
1922         len = magtapein ? ntrec * TP_BSIZE : TP_BSIZE;
1923
1924         if (read_a_block(mt, tapebuf, len, &i) <= 0)
1925                 errx(1, "Tape read error on first record");
1926
1927         /*
1928          * If the input is from a file or a pipe, we read TP_BSIZE
1929          * bytes looking for a dump header. If the dump is compressed
1930          * we need to read in the rest of the block, as determined
1931          * by c_ntrec in the dump header. The first block of the
1932          * dump is not compressed and does not have a prefix.
1933          */
1934         if (!magtapein) {
1935                 if (spclpt->c_type == TS_TAPE
1936                     && spclpt->c_flags & DR_COMPRESSED) {
1937                         /* It's a compressed dump file, read in the */
1938                         /* rest of the block based on spclpt->c_ntrec. */
1939                         if (spclpt->c_ntrec > ntrec)
1940                                 errx(1, "Tape blocksize is too large, use "
1941                                      "\'-b %d\' ", spclpt->c_ntrec);
1942                         ntrec = spclpt->c_ntrec;
1943                         len = (ntrec - 1) * TP_BSIZE;
1944                         zflag = 1;   
1945                 }
1946                 else {
1947                         /* read in the rest of the block based on bufsize */
1948                         len = bufsize - TP_BSIZE;
1949                 }
1950                 if (read_a_block(mt, tapebuf+TP_BSIZE, len, &i) < 0
1951                     || (i != (long)len && i % TP_BSIZE != 0))
1952                         errx(1,"Error reading dump file header");
1953                 tbufptr = tapebuf;
1954                 numtrec = ntrec;
1955                 Vprintf(stdout, "Input block size is %ld\n", ntrec);
1956                 return;
1957         } /* if (!magtapein) */
1958
1959         /*
1960          * If the input is a tape, we tried to read ntrec * TP_BSIZE bytes.
1961          * If the value of ntrec is too large, we read less than
1962          * what we asked for; adjust the value of ntrec and test for 
1963          * a compressed dump tape.
1964          */
1965
1966         if (i % TP_BSIZE != 0) {
1967                 /* may be old format compressed dump tape with a prefix */
1968                 spclpt = (struct s_spcl *) tpb->buf;
1969                 if (i % TP_BSIZE == PREFIXSIZE
1970                     && tpb->compressed == 0
1971                     && spclpt->c_type == TS_TAPE
1972                     && spclpt->c_flags & DR_COMPRESSED) {
1973                         zflag = 1;
1974                         tbufptr = tpb->buf;
1975                         if (tpb->length > bufsize)
1976                                 errx(1, "Tape blocksize is too large, use "
1977                                         "\'-b %d\' ", tpb->length / TP_BSIZE);
1978                 }
1979                 else
1980                         errx(1, "Tape block size (%ld) is not a multiple of dump block size (%d)",
1981                                 i, TP_BSIZE);
1982         }
1983         ntrec = i / TP_BSIZE;
1984         if (spclpt->c_type == TS_TAPE) {
1985                 if (spclpt->c_flags & DR_COMPRESSED)
1986                         zflag = 1;
1987                 if (spclpt->c_ntrec > ntrec)
1988                         errx(1, "Tape blocksize is too large, use "
1989                                 "\'-b %d\' ", spclpt->c_ntrec);
1990         }
1991         numtrec = ntrec;
1992         Vprintf(stdout, "Tape block size is %ld\n", ntrec);
1993 }
1994
1995 /*
1996  * Read a block of data handling all of the messy details.
1997  */
1998 static int read_a_block(int fd, char *buf, size_t len, long *lengthread)
1999 {
2000         long i = 1, size;
2001
2002         size = len;
2003         while (size > 0) {
2004 #ifdef RRESTORE
2005                 if (host)
2006                         i = rmtread(buf, size);
2007                 else
2008 #endif
2009                         i = read(fd, buf, size);                 
2010
2011                 if (i <= 0)
2012                         break; /* EOD or error */
2013                 size -= i;
2014                 if (magtapein)
2015                         break; /* block at a time for mt */
2016                 buf += i;
2017         }
2018         *lengthread = len - size;
2019         return i;
2020 }
2021
2022 void
2023 closemt(void)
2024 {
2025
2026         if (mt < 0)
2027                 return;
2028 #ifdef RRESTORE
2029         if (host)
2030                 rmtclose();
2031         else
2032 #endif
2033                 (void) close(mt);
2034 }
2035
2036 static void
2037 setmagtapein(void) {
2038         struct mtget mt_stat;
2039         static int done = 0;
2040         if (done)
2041                 return;
2042         done = 1;
2043         if (!pipein) {
2044                 /* need to know if input is really from a tape */
2045 #ifdef RRESTORE
2046                 if (host)
2047                         magtapein = !lflag;
2048                 else
2049 #endif
2050                         magtapein = ioctl(mt, MTIOCGET, (char *)&mt_stat) == 0;
2051         }
2052
2053         Vprintf(stdout,"Input is from %s\n", 
2054                         magtapein ? "tape" :
2055                         Vflag ? "multi-volume (no tape)" : "file/pipe");
2056 }
2057
2058 /*
2059  * Read the next block from the tape.
2060  * Check to see if it is one of several vintage headers.
2061  * If it is an old style header, convert it to a new style header.
2062  * If it is not any valid header, return an error.
2063  */
2064 static int
2065 gethead(struct s_spcl *buf)
2066 {
2067         int32_t i;
2068         union {
2069                 quad_t  qval;
2070                 int32_t val[2];
2071         } qcvt;
2072         union u_ospcl {
2073                 char dummy[TP_BSIZE];
2074                 struct  s_ospcl {
2075                         int32_t c_type;
2076                         int32_t c_date;
2077                         int32_t c_ddate;
2078                         int32_t c_volume;
2079                         int32_t c_tapea;
2080                         u_int16_t c_inumber;
2081                         int32_t c_magic;
2082                         int32_t c_checksum;
2083                         struct odinode {
2084                                 u_int16_t odi_mode;
2085                                 u_int16_t odi_nlink;
2086                                 u_int16_t odi_uid;
2087                                 u_int16_t odi_gid;
2088                                 int32_t odi_size;
2089                                 int32_t odi_rdev;
2090                                 char    odi_addr[36];
2091                                 int32_t odi_atime;
2092                                 int32_t odi_mtime;
2093                                 int32_t odi_ctime;
2094                         } c_dinode;
2095                         int32_t c_count;
2096                         char    c_fill[256];
2097                 } s_ospcl;
2098         } u_ospcl;
2099
2100         if (!cvtflag) {
2101                 readtape((char *)buf);
2102                 if (buf->c_magic != NFS_MAGIC) {
2103                         if (swabi(buf->c_magic) != NFS_MAGIC)
2104                                 return (FAIL);
2105                         if (!Bcvt) {
2106                                 Vprintf(stdout, "Note: Doing Byte swapping\n");
2107                                 Bcvt = 1;
2108                         }
2109                 }
2110                 if (checksum((int *)buf) == FAIL)
2111                         return (FAIL);
2112                 if (Bcvt)
2113                         swabst((u_char *)"8i4s31i528bi192b2i", (u_char *)buf);
2114                 goto good;
2115         }
2116         readtape((char *)(&u_ospcl.s_ospcl));
2117         memset((char *)buf, 0, (long)TP_BSIZE);
2118         buf->c_type = u_ospcl.s_ospcl.c_type;
2119         buf->c_date = u_ospcl.s_ospcl.c_date;
2120         buf->c_ddate = u_ospcl.s_ospcl.c_ddate;
2121         buf->c_volume = u_ospcl.s_ospcl.c_volume;
2122         buf->c_tapea = u_ospcl.s_ospcl.c_tapea;
2123         buf->c_inumber = u_ospcl.s_ospcl.c_inumber;
2124         buf->c_checksum = u_ospcl.s_ospcl.c_checksum;
2125         buf->c_magic = u_ospcl.s_ospcl.c_magic;
2126         buf->c_dinode.di_mode = u_ospcl.s_ospcl.c_dinode.odi_mode;
2127         buf->c_dinode.di_nlink = u_ospcl.s_ospcl.c_dinode.odi_nlink;
2128         buf->c_dinode.di_uid = u_ospcl.s_ospcl.c_dinode.odi_uid;
2129         buf->c_dinode.di_gid = u_ospcl.s_ospcl.c_dinode.odi_gid;
2130         buf->c_dinode.di_size = u_ospcl.s_ospcl.c_dinode.odi_size;
2131         buf->c_dinode.di_rdev = u_ospcl.s_ospcl.c_dinode.odi_rdev;
2132 #if defined(__linux__) || defined(sunos)
2133         buf->c_dinode.di_atime.tv_sec = u_ospcl.s_ospcl.c_dinode.odi_atime;
2134         buf->c_dinode.di_mtime.tv_sec = u_ospcl.s_ospcl.c_dinode.odi_mtime;
2135         buf->c_dinode.di_ctime.tv_sec = u_ospcl.s_ospcl.c_dinode.odi_ctime;
2136 #else   /* __linux__ || sunos */
2137         buf->c_dinode.di_atime = u_ospcl.s_ospcl.c_dinode.odi_atime;
2138         buf->c_dinode.di_mtime = u_ospcl.s_ospcl.c_dinode.odi_mtime;
2139         buf->c_dinode.di_ctime = u_ospcl.s_ospcl.c_dinode.odi_ctime;
2140 #endif  /* __linux__ || sunos */
2141         buf->c_count = u_ospcl.s_ospcl.c_count;
2142         memmove(buf->c_addr, u_ospcl.s_ospcl.c_fill, (long)256);
2143         if (u_ospcl.s_ospcl.c_magic != OFS_MAGIC ||
2144             checksum((int *)(&u_ospcl.s_ospcl)) == FAIL)
2145                 return(FAIL);
2146         buf->c_magic = NFS_MAGIC;
2147
2148 good:
2149         if ((buf->c_dinode.di_size == 0 || buf->c_dinode.di_size > 0xfffffff) &&
2150             (buf->c_dinode.di_mode & IFMT) == IFDIR && Qcvt == 0) {
2151                 qcvt.qval = buf->c_dinode.di_size;
2152                 if (qcvt.val[0] || qcvt.val[1]) {
2153                         Vprintf(stdout, "Note: Doing Quad swapping\n");
2154                         Qcvt = 1;
2155                 }
2156         }
2157         if (Qcvt) {
2158                 qcvt.qval = buf->c_dinode.di_size;
2159                 i = qcvt.val[1];
2160                 qcvt.val[1] = qcvt.val[0];
2161                 qcvt.val[0] = i;
2162                 buf->c_dinode.di_size = qcvt.qval;
2163         }
2164         readmapflag = 0;
2165
2166         switch (buf->c_type) {
2167
2168         case TS_CLRI:
2169         case TS_BITS:
2170                 /*
2171                  * Have to patch up missing information in bit map headers
2172                  */
2173                 buf->c_inumber = 0;
2174                 buf->c_dinode.di_size = buf->c_count * TP_BSIZE;
2175                 if (buf->c_count > TP_NINDIR)
2176                         readmapflag = 1;
2177                 else 
2178                         for (i = 0; i < buf->c_count; i++)
2179                                 buf->c_addr[i]++;
2180                 break;
2181
2182         case TS_TAPE:
2183                 if ((buf->c_flags & DR_NEWINODEFMT) == 0)
2184                         oldinofmt = 1;
2185                 /* fall through */
2186         case TS_END:
2187                 buf->c_inumber = 0;
2188                 if (buf->c_flags & DR_INODEINFO) {
2189                         memcpy(volinfo, buf->c_inos, TP_NINOS * sizeof(dump_ino_t));
2190                         if (Bcvt)
2191                                 swabst((u_char *)"128i", (u_char *)volinfo);
2192                 }
2193                 break;
2194
2195         case TS_INODE:
2196         case TS_ADDR:
2197                 break;
2198
2199         default:
2200                 panic("gethead: unknown inode type %d\n", buf->c_type);
2201                 break;
2202         }
2203         /*
2204          * If we are restoring a filesystem with old format inodes,
2205          * copy the uid/gid to the new location.
2206          */
2207         if (oldinofmt) {
2208                 buf->c_dinode.di_uid = buf->c_dinode.di_ouid;
2209                 buf->c_dinode.di_gid = buf->c_dinode.di_ogid;
2210         }
2211         if (dflag)
2212                 accthdr(buf);
2213         return(GOOD);
2214 }
2215
2216 /*
2217  * Check that a header is where it belongs and predict the next header
2218  */
2219 static void
2220 accthdr(struct s_spcl *header)
2221 {
2222         static dump_ino_t previno = 0x7fffffff;
2223         static int prevtype;
2224         static long predict;
2225         long blks, i;
2226
2227         if (header->c_type == TS_TAPE) {
2228                 fprintf(stderr, "Volume header (%s inode format) ",
2229                     oldinofmt ? "old" : "new");
2230                 if (header->c_firstrec)
2231                         fprintf(stderr, "begins with record %d",
2232                                 header->c_firstrec);
2233                 fprintf(stderr, "\n");
2234                 previno = 0x7fffffff;
2235                 return;
2236         }
2237         if (previno == 0x7fffffff)
2238                 goto newcalc;
2239         switch (prevtype) {
2240         case TS_BITS:
2241                 fprintf(stderr, "Dumped inodes map header");
2242                 break;
2243         case TS_CLRI:
2244                 fprintf(stderr, "Used inodes map header");
2245                 break;
2246         case TS_INODE:
2247                 fprintf(stderr, "File header, ino %lu", (unsigned long)previno);
2248                 break;
2249         case TS_ADDR:
2250                 fprintf(stderr, "File continuation header, ino %ld", (long)previno);
2251                 break;
2252         case TS_END:
2253                 fprintf(stderr, "End of tape header");
2254                 break;
2255         }
2256         if (predict != blksread - 1)
2257                 fprintf(stderr, "; predicted %ld blocks, got %ld blocks",
2258                         predict, blksread - 1);
2259         fprintf(stderr, "\n");
2260 newcalc:
2261         blks = 0;
2262         if (header->c_type != TS_END)
2263                 for (i = 0; i < header->c_count; i++)
2264                         if (readmapflag || header->c_addr[i] != 0)
2265                                 blks++;
2266         predict = blks;
2267         blksread = 0;
2268         prevtype = header->c_type;
2269         previno = header->c_inumber;
2270 }
2271
2272 /*
2273  * Find an inode header.
2274  * Complain if had to skip, and complain is set.
2275  */
2276 static void
2277 findinode(struct s_spcl *header)
2278 {
2279         static long skipcnt = 0;
2280         long i;
2281         char buf[TP_BSIZE];
2282
2283         curfile.name = "<name unknown>";
2284         curfile.action = UNKNOWN;
2285         curfile.dip = NULL;
2286         curfile.ino = 0;
2287         do {
2288                 if (header->c_magic != NFS_MAGIC) {
2289                         skipcnt++;
2290                         while (gethead(header) == FAIL ||
2291                             header->c_date != dumpdate)
2292                                 skipcnt++;
2293                 }
2294                 switch (header->c_type) {
2295
2296                 case TS_ADDR:
2297                         /*
2298                          * Skip up to the beginning of the next record
2299                          */
2300                         for (i = 0; i < header->c_count; i++)
2301                                 if (header->c_addr[i])
2302                                         readtape(buf);
2303                         while (gethead(header) == FAIL ||
2304                             header->c_date != dumpdate)
2305                                 skipcnt++;
2306                         break;
2307
2308                 case TS_INODE:
2309                         curfile.dip = &header->c_dinode;
2310                         curfile.ino = header->c_inumber;
2311                         break;
2312
2313                 case TS_END:
2314                         curfile.ino = maxino;
2315                         break;
2316
2317                 case TS_CLRI:
2318                         curfile.name = "<file removal list>";
2319                         break;
2320
2321                 case TS_BITS:
2322                         curfile.name = "<file dump list>";
2323                         break;
2324
2325                 case TS_TAPE:
2326                         panic("unexpected tape header\n");
2327                         /* NOTREACHED */
2328
2329                 default:
2330                         panic("unknown tape header type %d\n", spcl.c_type);
2331                         /* NOTREACHED */
2332
2333                 }
2334         } while (header->c_type == TS_ADDR);
2335         if (skipcnt > 0)
2336 #ifdef USE_QFA
2337                 if (!noresyncmesg)
2338 #endif
2339                         fprintf(stderr, "resync restore, skipped %ld blocks\n",
2340                                 skipcnt);
2341         skipcnt = 0;
2342 }
2343
2344 static int
2345 checksum(int *buf)
2346 {
2347         int i, j;
2348
2349         j = sizeof(union u_spcl) / sizeof(int);
2350         i = 0;
2351         if(!Bcvt) {
2352                 do
2353                         i += *buf++;
2354                 while (--j);
2355         } else {
2356                 /* What happens if we want to read restore tapes
2357                         for a 16bit int machine??? */
2358                 do
2359                         i += swabi(*buf++);
2360                 while (--j);
2361         }
2362
2363         if (i != CHECKSUM) {
2364                 fprintf(stderr, "Checksum error %o, inode %lu file %s\n", i,
2365                         (unsigned long)curfile.ino, curfile.name);
2366                 return(FAIL);
2367         }
2368         return(GOOD);
2369 }
2370
2371 #ifdef RRESTORE
2372 #ifdef __STDC__
2373 #include <stdarg.h>
2374 #else
2375 #include <varargs.h>
2376 #endif
2377
2378 void
2379 #ifdef __STDC__
2380 msg(const char *fmt, ...)
2381 #else
2382 msg(fmt, va_alist)
2383         char *fmt;
2384         va_dcl
2385 #endif
2386 {
2387         va_list ap;
2388 #ifdef __STDC__
2389         va_start(ap, fmt);
2390 #else
2391         va_start(ap);
2392 #endif
2393         (void)vfprintf(stderr, fmt, ap);
2394         va_end(ap);
2395 }
2396 #endif /* RRESTORE */
2397
2398 static u_char *
2399 swab16(u_char *sp, int n)
2400 {
2401         char c;
2402
2403         while (--n >= 0) {
2404                 c = sp[0]; sp[0] = sp[1]; sp[1] = c;
2405                 sp += 2;
2406         }
2407         return (sp);
2408 }
2409
2410 static u_char *
2411 swab32(u_char *sp, int n)
2412 {
2413         char c;
2414
2415         while (--n >= 0) {
2416                 c = sp[0]; sp[0] = sp[3]; sp[3] = c;
2417                 c = sp[1]; sp[1] = sp[2]; sp[2] = c;
2418                 sp += 4;
2419         }
2420         return (sp);
2421 }
2422
2423 static u_char *
2424 swab64(u_char *sp, int n)
2425 {
2426         char c;
2427
2428         while (--n >= 0) {
2429                 c = sp[0]; sp[0] = sp[7]; sp[7] = c;
2430                 c = sp[1]; sp[1] = sp[6]; sp[6] = c;
2431                 c = sp[2]; sp[2] = sp[5]; sp[5] = c;
2432                 c = sp[3]; sp[3] = sp[4]; sp[4] = c;
2433                 sp += 8;
2434         }
2435         return (sp);
2436 }
2437
2438 void
2439 swabst(u_char *cp, u_char *sp)
2440 {
2441         int n = 0;
2442
2443         while (*cp) {
2444                 switch (*cp) {
2445                 case '0': case '1': case '2': case '3': case '4':
2446                 case '5': case '6': case '7': case '8': case '9':
2447                         n = (n * 10) + (*cp++ - '0');
2448                         continue;
2449
2450                 case 's': case 'w': case 'h':
2451                         if (n == 0)
2452                                 n = 1;
2453                         sp = swab16(sp, n);
2454                         break;
2455
2456                 case 'i':
2457                         if (n == 0)
2458                                 n = 1;
2459                         sp = swab32(sp, n);
2460                         break;
2461
2462                 case 'l':
2463                         if (n == 0)
2464                                 n = 1;
2465                         sp = swab64(sp, n);
2466                         break;
2467
2468                 default: /* Any other character, like 'b' counts as byte. */
2469                         if (n == 0)
2470                                 n = 1;
2471                         sp += n;
2472                         break;
2473                 }
2474                 cp++;
2475                 n = 0;
2476         }
2477 }
2478
2479 static u_int
2480 swabi(u_int x)
2481 {
2482         swabst((u_char *)"i", (u_char *)&x);
2483         return (x);
2484 }
2485
2486 #if 0
2487 static u_long
2488 swabl(u_long x)
2489 {
2490         swabst((u_char *)"l", (u_char *)&x);
2491         return (x);
2492 }
2493 #endif
2494
2495 #ifdef USE_QFA
2496 /*
2497  * get the current position of the tape
2498  */
2499 int
2500 GetTapePos(long long *pos)
2501 {
2502         int err = 0;
2503
2504 #ifdef RDUMP
2505         if (host) {
2506                 *pos = (long long) rmtseek(0, SEEK_CUR);
2507                 err = *pos < 0;
2508         }
2509         else
2510 #endif
2511         {
2512         if (magtapein) {
2513                 long mtpos;
2514                 *pos = 0;
2515                 err = (ioctl(mt, MTIOCPOS, &mtpos) < 0);
2516                 *pos = (long long)mtpos;
2517         }
2518         else {
2519                 *pos = LSEEK(mt, 0, SEEK_CUR);
2520                 err = (*pos < 0);
2521         }
2522         }
2523         if (err) {
2524                 err = errno;
2525                 fprintf(stdout, "[%ld] error: %d (getting tapepos: %lld)\n", 
2526                         (unsigned long)getpid(), err, *pos);
2527                 return err;
2528         }
2529         return err;
2530 }
2531
2532 typedef struct mt_pos {
2533         short    mt_op;
2534         int      mt_count;
2535 } MTPosRec, *MTPosPtr;
2536
2537 /*
2538  * go to specified position on tape
2539  */
2540 int
2541 GotoTapePos(long long pos)
2542 {
2543         int err = 0;
2544
2545 #ifdef RDUMP
2546         if (host)
2547                 err = (rmtseek((long)pos, SEEK_SET) < 0);
2548         else
2549 #endif
2550         {
2551         if (magtapein) {
2552                 struct mt_pos buf;
2553                 buf.mt_op = MTSEEK;
2554                 buf.mt_count = (int) pos;
2555                 err = (ioctl(mt, MTIOCTOP, &buf) < 0);
2556         }
2557         else {
2558                 pos = LSEEK(mt, pos, SEEK_SET);
2559                 err = (pos < 0);
2560         }
2561         }
2562         if (err) {
2563                 err = errno;
2564                 fprintf(stdout, "[%ld] error: %d (setting tapepos: %lld)\n", 
2565                         (unsigned long)getpid(), err, pos);
2566                 return err;
2567         }
2568         return err;
2569 }
2570
2571 /*
2572  * read next data from tape to re-sync
2573  */
2574 void
2575 ReReadFromTape(void)
2576 {
2577         FLUSHTAPEBUF();
2578         noresyncmesg = 1;
2579         if (gethead(&spcl) == FAIL) {
2580 #ifdef DEBUG_QFA
2581                 fprintf(stdout, "DEBUG 1 gethead failed\n");
2582 #endif
2583         }
2584         findinode(&spcl);
2585         noresyncmesg = 0;
2586 }
2587
2588 void
2589 ReReadInodeFromTape(dump_ino_t theino)
2590 {
2591         long cntloop = 0;
2592
2593         FLUSHTAPEBUF();
2594         noresyncmesg = 1;
2595         do {
2596                 cntloop++;
2597                 gethead(&spcl);
2598         } while (!(spcl.c_inumber == theino && spcl.c_type == TS_INODE && spcl.c_date == dumpdate) && (cntloop < 32));
2599 #ifdef DEBUG_QFA
2600         fprintf(stderr, "%ld reads\n", cntloop);
2601         if (cntloop == 32) {
2602                 fprintf(stderr, "DEBUG: bufsize %d\n", bufsize);
2603                 fprintf(stderr, "DEBUG: ntrec %ld\n", ntrec);
2604                 fprintf(stderr, "DEBUG: %ld reads\n", cntloop);
2605         }
2606 #endif
2607         findinode(&spcl);
2608         noresyncmesg = 0;
2609 }
2610 #endif /* USE_QFA */
2611
2612 void
2613 RequestVol(long tnum)
2614 {
2615         FLUSHTAPEBUF();
2616         getvol(tnum);
2617 }