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