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